@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,1979 @@
1
+ // `open-take film listen`: a film's sound as information the author can read —
2
+ // a picture on the film's time (spectrum, loudness, onsets and beat grid,
3
+ // texture sections, each stem's activity, the page's events and cuts and
4
+ // curves), marked with the same times as `film sheet`, and a text report
5
+ // where every line says whether it was measured, is an estimate, or was not
6
+ // found. Nothing is graded: no target, no pass line, no "should".
7
+ //
8
+ // ffmpeg reads what it measures to a standard (ebur128 loudness, true peak,
9
+ // silencedetect, the spectrum picture); the rest is plain arithmetic on the
10
+ // decoded sound here: a short-time spectrum, onsets from where its bands rise,
11
+ // a tempo from how the onset strength repeats, sections from where the
12
+ // texture stops resembling what came before, bars that repeat verbatim.
13
+
14
+ import { existsSync } from "node:fs";
15
+ import { mkdir, mkdtemp, readdir, readFile, rm, writeFile } from "node:fs/promises";
16
+ import { tmpdir } from "node:os";
17
+ import { basename, extname, join, resolve } from "node:path";
18
+ import { pathToFileURL } from "node:url";
19
+ import { resolveFfmpeg, resolveFfprobe, runTool } from "../ffmpeg";
20
+ import { launchHtmlBrowser } from "../html/cdp";
21
+ import {
22
+ BANDS,
23
+ chanceWithin,
24
+ decodeMono,
25
+ estimateTempo,
26
+ FLOOR_DB,
27
+ findSections,
28
+ LISTEN_RATE,
29
+ nearestOffset,
30
+ onsetStrength,
31
+ pickOnsets,
32
+ type Section,
33
+ type Spectrum,
34
+ spectrum,
35
+ type Tempo,
36
+ WIN,
37
+ } from "./beats";
38
+ import { formatSoundChanges, type SoundChange, soundChanges } from "./changes";
39
+ import { fileEnergy } from "./probe";
40
+ import { PICTURE_ENERGY } from "./render";
41
+ import { formatTuning, type Tuning, tuning } from "./tuning";
42
+
43
+ // the analysis lives in ./beats (shared with `film beats` and `film probe`);
44
+ // what this module has always exported is still exported from here
45
+ export {
46
+ chanceWithin,
47
+ estimateTempo,
48
+ findSections,
49
+ LISTEN_RATE,
50
+ nearestOffset,
51
+ onsetStrength,
52
+ pickOnsets,
53
+ type Section,
54
+ type Spectrum,
55
+ spectrum,
56
+ type Tempo,
57
+ } from "./beats";
58
+
59
+ // --- the page's events (the file `film render` writes beside the film) ------------
60
+
61
+ export type FilmEvent = {
62
+ /** seconds on the film's time */
63
+ t: number;
64
+ /** "click", "key", "land", "cut", "mark", … — whatever the page names */
65
+ kind: string;
66
+ /** stage px */
67
+ x?: number;
68
+ y?: number;
69
+ /** 0..1 */
70
+ force?: number;
71
+ label?: string;
72
+ };
73
+
74
+ export type FilmEvents = {
75
+ version: 1;
76
+ duration: number;
77
+ fps: number;
78
+ /** sorted by t */
79
+ events: FilmEvent[];
80
+ /** hard-cut times the clock detected or the page declared */
81
+ cuts: number[];
82
+ /** rows[i][j] = curve names[j] at time t0 + i·dt */
83
+ curves: { names: string[]; t0: number; dt: number; rows: number[][] };
84
+ };
85
+
86
+ const finite = (v: unknown): v is number => typeof v === "number" && Number.isFinite(v);
87
+
88
+ /** `<film>.events.json` read leniently: what is malformed is left out, never
89
+ * fatal — on the film's own clock: a render of part of the page (`range`
90
+ * [a, b]) starts at a, so its times move back by a and what falls outside
91
+ * [0, b − a] is left out */
92
+ export function parseFilmEvents(raw: unknown): FilmEvents {
93
+ const r = (raw && typeof raw === "object" ? raw : {}) as Record<string, unknown>;
94
+ const range =
95
+ Array.isArray(r.range) && finite(r.range[0]) && finite(r.range[1]) && r.range[1] > r.range[0]
96
+ ? ([r.range[0], r.range[1]] as [number, number])
97
+ : null;
98
+ const from = range ? range[0] : 0;
99
+ const inside = (t: number) => !range || (t >= -1e-6 && t <= range[1] - range[0] + 1e-6);
100
+ const events = (Array.isArray(r.events) ? r.events : [])
101
+ .filter((e): e is Record<string, unknown> => !!e && typeof e === "object" && finite(e.t))
102
+ .map((e) => {
103
+ const ev: FilmEvent = {
104
+ t: (e.t as number) - from,
105
+ kind: typeof e.kind === "string" ? e.kind : "event",
106
+ };
107
+ if (finite(e.x)) ev.x = e.x;
108
+ if (finite(e.y)) ev.y = e.y;
109
+ if (finite(e.force)) ev.force = e.force;
110
+ if (typeof e.label === "string") ev.label = e.label;
111
+ return ev;
112
+ })
113
+ .filter((e) => inside(e.t))
114
+ .sort((a, b) => a.t - b.t);
115
+ const cuts = (Array.isArray(r.cuts) ? r.cuts : [])
116
+ .filter(finite)
117
+ .map((t) => t - from)
118
+ .filter(inside)
119
+ .sort((a, b) => a - b);
120
+ const c = (r.curves && typeof r.curves === "object" ? r.curves : {}) as Record<string, unknown>;
121
+ const names = (Array.isArray(c.names) ? c.names : []).map(String);
122
+ const rows = (Array.isArray(c.rows) ? c.rows : [])
123
+ .filter((row): row is unknown[] => Array.isArray(row))
124
+ .map((row) => names.map((_, j) => (finite(row[j]) ? (row[j] as number) : Number.NaN)));
125
+ const fps = finite(r.fps) && r.fps > 0 ? r.fps : 60;
126
+ return {
127
+ version: 1,
128
+ duration: range ? range[1] - range[0] : finite(r.duration) ? r.duration : 0,
129
+ fps,
130
+ events,
131
+ cuts,
132
+ curves: {
133
+ names,
134
+ t0: (finite(c.t0) ? c.t0 : 0) - from,
135
+ dt: finite(c.dt) && c.dt > 0 ? c.dt : 1 / fps,
136
+ rows,
137
+ },
138
+ };
139
+ }
140
+
141
+ // --- repeats --------------------------------------------------------------------------
142
+
143
+ export type BarRepeats = {
144
+ beatsPerBar: number;
145
+ bars: number;
146
+ /** bars (1-based) that sound like an earlier bar, each with the first bar it repeats */
147
+ repeats: { bar: number; of: number }[];
148
+ /** the longest stretch of consecutive bars repeating a stretch before it */
149
+ longestRun: { from: number; to: number; of: number } | null;
150
+ };
151
+
152
+ /** bars (4 beats on the estimated grid) that repeat an earlier bar verbatim:
153
+ * the same band energies, step by step, within 1.5 dB on average and shaped
154
+ * alike (correlation ≥ 0.95). Silent bars are left out. */
155
+ export function repeatedBars(s: Spectrum, beats: readonly number[], beatsPerBar = 4): BarRepeats {
156
+ const STEPS = 16;
157
+ const COARSE = BANDS / 2;
158
+ const bars: (Float64Array | null)[] = [];
159
+ for (let i = 0; i + beatsPerBar < beats.length; i += beatsPerBar) {
160
+ const a = beats[i]!;
161
+ const b = beats[i + beatsPerBar]!;
162
+ const v = new Float64Array(STEPS * COARSE);
163
+ let loud = false;
164
+ for (let st = 0; st < STEPS; st++) {
165
+ const f0 = Math.floor((a + ((b - a) * st) / STEPS) / s.hopS);
166
+ const f1 = Math.max(f0 + 1, Math.floor((a + ((b - a) * (st + 1)) / STEPS) / s.hopS));
167
+ for (let f = f0; f < Math.min(f1, s.bands.length); f++) {
168
+ if (s.level[f]! > FLOOR_DB + 10) loud = true;
169
+ for (let k = 0; k < COARSE; k++)
170
+ v[st * COARSE + k] =
171
+ v[st * COARSE + k]! +
172
+ (Math.max(s.bands[f]![2 * k]!, s.bands[f]![2 * k + 1]!) - FLOOR_DB) / (f1 - f0);
173
+ }
174
+ }
175
+ bars.push(loud ? v : null);
176
+ }
177
+ const same = (p: Float64Array, q: Float64Array) => {
178
+ let diff = 0;
179
+ let mp = 0;
180
+ let mq = 0;
181
+ for (let i = 0; i < p.length; i++) {
182
+ diff += Math.abs(p[i]! - q[i]!);
183
+ mp += p[i]!;
184
+ mq += q[i]!;
185
+ }
186
+ if (diff / p.length > 1.5) return false;
187
+ mp /= p.length;
188
+ mq /= q.length;
189
+ let num = 0;
190
+ let dp = 0;
191
+ let dq = 0;
192
+ for (let i = 0; i < p.length; i++) {
193
+ num += (p[i]! - mp) * (q[i]! - mq);
194
+ dp += (p[i]! - mp) ** 2;
195
+ dq += (q[i]! - mq) ** 2;
196
+ }
197
+ return dp > 0 && dq > 0 && num / Math.sqrt(dp * dq) >= 0.95;
198
+ };
199
+ const repeats: { bar: number; of: number }[] = [];
200
+ const of: (number | null)[] = bars.map(() => null);
201
+ for (let i = 1; i < bars.length; i++) {
202
+ const p = bars[i];
203
+ if (!p) continue;
204
+ for (let j = 0; j < i; j++) {
205
+ const q = bars[j];
206
+ if (q && same(p, q)) {
207
+ of[i] = j;
208
+ repeats.push({ bar: i + 1, of: (of[j] ?? j) + 1 });
209
+ break;
210
+ }
211
+ }
212
+ }
213
+ // the longest run of bars i..i+k each repeating bar j..j+k
214
+ let longestRun: BarRepeats["longestRun"] = null;
215
+ for (let i = 1; i < bars.length; i++)
216
+ for (let j = 0; j < i; j++) {
217
+ let k = 0;
218
+ while (
219
+ i + k < bars.length &&
220
+ j + k < i &&
221
+ bars[i + k] &&
222
+ bars[j + k] &&
223
+ same(bars[i + k]!, bars[j + k]!)
224
+ )
225
+ k++;
226
+ if (k >= 2 && (!longestRun || k > longestRun.to - longestRun.from + 1))
227
+ longestRun = { from: i + 1, to: i + k, of: j + 1 };
228
+ }
229
+ return { beatsPerBar, bars: bars.length, repeats, longestRun };
230
+ }
231
+
232
+ // --- the whole listen ------------------------------------------------------------------
233
+
234
+ type How = "measured" | "estimated" | "not detected" | "not measured";
235
+
236
+ // --- the picture's change beside the sound ------------------------------------------
237
+
238
+ /** how much the picture changes into each frame (mean grey difference from
239
+ * the frame before, 0..1): values[i] at t0 + i·dt; NaN where unknown */
240
+ export type PictureEnergy = { t0: number; dt: number; values: number[] };
241
+
242
+ /** the events file's picture.energy curve (`film render` writes it); null when it has none */
243
+ export function pictureEnergyOf(ev: FilmEvents | null): PictureEnergy | null {
244
+ const j = ev?.curves.names.indexOf(PICTURE_ENERGY) ?? -1;
245
+ if (!ev || j < 0) return null;
246
+ const values = ev.curves.rows.map((r) => r[j] ?? Number.NaN);
247
+ if (!values.some(Number.isFinite)) return null;
248
+ return { t0: ev.curves.t0, dt: ev.curves.dt, values };
249
+ }
250
+
251
+ export type HalfSecond = {
252
+ /** start (s) */
253
+ t: number;
254
+ /** loudness (LUFS) of the momentary readings centred in it, power mean; −120 for silence */
255
+ lufs: number;
256
+ /** mean picture change of the frames in it; NaN when none is known */
257
+ energy: number;
258
+ };
259
+
260
+ /** the film cut into `binS` pieces, each with its loudness and picture change.
261
+ * A momentary reading (400 ms, stamped at its end) counts where its middle is. */
262
+ export function halfSeconds(
263
+ momentary: readonly { t: number; lufs: number }[],
264
+ picture: PictureEnergy,
265
+ duration: number,
266
+ binS = 0.5,
267
+ ): HalfSecond[] {
268
+ const n = Math.max(1, Math.ceil(duration / binS - 1e-6));
269
+ const pow = new Float64Array(n);
270
+ const cnt = new Uint32Array(n);
271
+ for (const m of momentary) {
272
+ const k = Math.floor((m.t - 0.2) / binS);
273
+ if (k < 0 || k >= n) continue;
274
+ pow[k]! += 10 ** (Math.max(-120, m.lufs) / 10);
275
+ cnt[k]!++;
276
+ }
277
+ const es = new Float64Array(n);
278
+ const ec = new Uint32Array(n);
279
+ picture.values.forEach((v, i) => {
280
+ const k = Math.floor((picture.t0 + i * picture.dt + 1e-9) / binS);
281
+ if (!Number.isFinite(v) || k < 0 || k >= n) return;
282
+ es[k]! += v;
283
+ ec[k]!++;
284
+ });
285
+ return Array.from({ length: n }, (_, k) => ({
286
+ t: round2(k * binS),
287
+ lufs: cnt[k] ? round1(Math.max(-120, 10 * Math.log10(pow[k]! / cnt[k]!))) : -120,
288
+ energy: ec[k] ? Math.round((es[k]! / ec[k]!) * 1e5) / 1e5 : Number.NaN,
289
+ }));
290
+ }
291
+
292
+ export type PictureAgainstSound = {
293
+ binS: number;
294
+ /** how many of the loudest and of the busiest pieces each list holds */
295
+ top: number;
296
+ /** start times of the loudest pieces, loudest first */
297
+ loudest: number[];
298
+ /** start times of the pieces where the picture changes most, busiest first */
299
+ busiest: number[];
300
+ /** how many pieces are in both */
301
+ shared: number;
302
+ /** stretches where one is over this film's median while the other is under
303
+ * it, holding at least one piece where one is in the film's top third while
304
+ * the other is in its bottom third: "busy-quiet" the picture busy, the sound
305
+ * quiet; "still-loud" the other way. Mean picture change and loudness over it */
306
+ opposite: {
307
+ from: number;
308
+ to: number;
309
+ kind: "busy-quiet" | "still-loud";
310
+ energy: number;
311
+ lufs: number;
312
+ }[];
313
+ };
314
+
315
+ /** each piece's place in the film from 0 (the lowest) to 1 (the highest); ties share the mean place */
316
+ function places(v: readonly number[]): number[] {
317
+ const order = v.map((x, i) => [x, i] as const).sort((a, b) => a[0] - b[0]);
318
+ const out = new Array<number>(v.length).fill(0.5);
319
+ for (let i = 0; i < order.length; ) {
320
+ let j = i;
321
+ while (j + 1 < order.length && order[j + 1]![0] === order[i]![0]) j++;
322
+ const p = order.length > 1 ? (i + j) / 2 / (order.length - 1) : 0.5;
323
+ for (let k = i; k <= j; k++) out[order[k]![1]] = p;
324
+ i = j + 1;
325
+ }
326
+ return out;
327
+ }
328
+
329
+ /** the picture's change against the loudness, piece by piece: where the
330
+ * loudest and the busiest pieces are, and where they run opposite. Pieces
331
+ * without a picture reading are left out. Information, not a grade */
332
+ export function pictureAgainstSound(halves: readonly HalfSecond[], top = 5): PictureAgainstSound {
333
+ const known = halves.filter((h) => Number.isFinite(h.energy));
334
+ const binS = halves.length > 1 ? round2(halves[1]!.t - halves[0]!.t) : 0.5;
335
+ const k = Math.min(top, known.length);
336
+ const by = (f: (h: HalfSecond) => number) =>
337
+ [...known]
338
+ .sort((a, b) => f(b) - f(a) || a.t - b.t)
339
+ .slice(0, k)
340
+ .map((h) => h.t);
341
+ const loudest = by((h) => h.lufs);
342
+ const busiest = by((h) => h.energy);
343
+ const pe = places(known.map((h) => h.energy));
344
+ const pl = places(known.map((h) => h.lufs));
345
+ const opposite: PictureAgainstSound["opposite"] = [];
346
+ // a stretch runs while one is over the film's middle and the other under it,
347
+ // and is kept when one of its pieces is in a top third against a bottom one
348
+ const side = (i: number) =>
349
+ pe[i]! > 0.5 && pl[i]! < 0.5
350
+ ? "busy-quiet"
351
+ : pe[i]! < 0.5 && pl[i]! > 0.5
352
+ ? "still-loud"
353
+ : null;
354
+ const strong = (i: number) =>
355
+ (pe[i]! >= 2 / 3 && pl[i]! <= 1 / 3) || (pe[i]! <= 1 / 3 && pl[i]! >= 2 / 3);
356
+ for (let i = 0; i < known.length; ) {
357
+ const kind = side(i);
358
+ if (!kind) {
359
+ i++;
360
+ continue;
361
+ }
362
+ let j = i;
363
+ while (
364
+ j + 1 < known.length &&
365
+ side(j + 1) === kind &&
366
+ Math.abs(known[j + 1]!.t - known[j]!.t - binS) < 1e-6
367
+ )
368
+ j++;
369
+ const idx = Array.from({ length: j - i + 1 }, (_, k) => i + k);
370
+ if (idx.some(strong)) {
371
+ const hs = idx.map((k) => known[k]!);
372
+ const pw = hs.reduce((s, h) => s + 10 ** (h.lufs / 10), 0) / hs.length;
373
+ opposite.push({
374
+ from: hs[0]!.t,
375
+ to: round2(hs.at(-1)!.t + binS),
376
+ kind,
377
+ energy: Math.round((hs.reduce((s, h) => s + h.energy, 0) / hs.length) * 1e5) / 1e5,
378
+ lufs: round1(Math.max(-120, 10 * Math.log10(pw))),
379
+ });
380
+ }
381
+ i = j + 1;
382
+ }
383
+ return {
384
+ binS,
385
+ top: k,
386
+ loudest,
387
+ busiest,
388
+ shared: loudest.filter((t) => busiest.includes(t)).length,
389
+ opposite,
390
+ };
391
+ }
392
+
393
+ export type FilmListen = {
394
+ input: string;
395
+ duration: number;
396
+ sampleRate: number;
397
+ channels: number;
398
+ loudness: {
399
+ how: How;
400
+ integratedLufs: number | null;
401
+ lra: number | null;
402
+ truePeakDb: number | null;
403
+ /** momentary loudness (LUFS, 400 ms) every 100 ms */
404
+ momentary: { t: number; lufs: number }[];
405
+ };
406
+ onsets: { how: How; times: number[]; perS: number };
407
+ tempo: { how: How; value: Tempo | null };
408
+ sections: { how: How; list: Section[] };
409
+ /** where several things in the sound change at once, and whether anything led into it */
410
+ changes: { how: How; list: SoundChange[] };
411
+ /** how in tune the pitched sound is, by register */
412
+ tuning: Tuning;
413
+ bars: { how: How; value: BarRepeats | null; note?: string };
414
+ silences: { how: How; list: { start: number; end: number }[] };
415
+ dips: { how: How; list: { start: number; end: number; belowLu: number }[] };
416
+ events: {
417
+ how: How;
418
+ file: string | null;
419
+ list: (FilmEvent & { nearestOnset: number | null })[];
420
+ unvoiced: (FilmEvent & { nearestOnset: number | null })[];
421
+ chance40: number;
422
+ };
423
+ cuts: {
424
+ how: How;
425
+ source: "events" | "picture" | "none";
426
+ list: { t: number; nearestOnset: number | null }[];
427
+ };
428
+ stems: {
429
+ how: How;
430
+ dir: string | null;
431
+ list: { name: string; file: string; activeS: number; peakDb: number; lane: boolean[] }[];
432
+ /** seconds per lane cell */
433
+ laneS: number;
434
+ /** per event: the stem that rises at it, and how many dB it sits over the rest */
435
+ eventWindows: { t: number; kind: string; stem: string; overRestDb: number }[];
436
+ };
437
+ curves: FilmEvents["curves"];
438
+ /** how much the picture changes, beside the sound */
439
+ picture: {
440
+ how: How;
441
+ /** the events file's "picture.energy" curve, or measured from the film's picture */
442
+ source: "events" | "picture" | "none";
443
+ /** per frame (see PictureEnergy); null without a picture */
444
+ energy: PictureEnergy | null;
445
+ /** the film in half-seconds: mean picture change and loudness in each */
446
+ halves: HalfSecond[];
447
+ against: PictureAgainstSound | null;
448
+ };
449
+ clips: string[];
450
+ /** what the sound is like — instruments, synthesized or recorded — is not measured */
451
+ timbre: { how: "not measured" };
452
+ /** the events file's "credits", as written there (absent: no such field) */
453
+ credits?: string[];
454
+ /** this sound beside a previous version of it (`--vs`) */
455
+ vs?: ListenVs;
456
+ };
457
+
458
+ export type FilmListenOptions = {
459
+ /** the film (an mp4) or the score alone (a wav, or any sound) */
460
+ input: string;
461
+ /** the folder to write listen.png / listen.md / listen.json into;
462
+ * default: `<input without extension>.listen/` */
463
+ out?: string;
464
+ /** default: `<input without extension>.events.json` when it exists */
465
+ events?: string;
466
+ /** a folder of stems (one sound file each, the score's parts) */
467
+ stems?: string;
468
+ /** solo/<stem>.m4a and mute/<stem>.m4a beside the report */
469
+ clips?: boolean;
470
+ /** draws listen.png; without it only the text and data are written */
471
+ chromePath?: string;
472
+ /** the seconds between `film sheet`'s frames, to mark the same times
473
+ * (default: the sheet's own default for this length) */
474
+ every?: number;
475
+ /** a previous version of the film or its sound (any file ffmpeg reads):
476
+ * what changed, on the same film time, and A/B clips of where it changed most */
477
+ vs?: string;
478
+ };
479
+
480
+ const SOUND_EXT = new Set([
481
+ ".wav",
482
+ ".mp3",
483
+ ".flac",
484
+ ".ogg",
485
+ ".m4a",
486
+ ".aac",
487
+ ".aif",
488
+ ".aiff",
489
+ ".opus",
490
+ ]);
491
+
492
+ export async function filmListen(opts: FilmListenOptions): Promise<{
493
+ png: string | null;
494
+ md: string;
495
+ json: string;
496
+ listen: FilmListen;
497
+ }> {
498
+ const input = resolve(opts.input);
499
+ if (!existsSync(input)) throw new Error(`film listen: no file at ${input}`);
500
+ const stem = input.replace(/\.[^./]+$/, "");
501
+ const outDir = resolve(opts.out ?? `${stem}.listen`);
502
+ const [ffmpeg, ffprobe] = await Promise.all([resolveFfmpeg(), resolveFfprobe()]);
503
+ const info = JSON.parse(
504
+ await runTool(ffprobe, [
505
+ "-v",
506
+ "error",
507
+ "-show_entries",
508
+ "stream=codec_type,width,height,r_frame_rate,sample_rate,channels:format=duration",
509
+ "-of",
510
+ "json",
511
+ input,
512
+ ]),
513
+ ) as {
514
+ streams?: {
515
+ codec_type?: string;
516
+ width?: number;
517
+ height?: number;
518
+ r_frame_rate?: string;
519
+ sample_rate?: string;
520
+ channels?: number;
521
+ }[];
522
+ format?: { duration?: string };
523
+ };
524
+ const audio = info.streams?.find((s) => s.codec_type === "audio");
525
+ const video = info.streams?.find((s) => s.codec_type === "video");
526
+ if (!audio) throw new Error(`film listen: ${input} has no sound to listen to`);
527
+ const duration = Number(info.format?.duration ?? 0);
528
+ if (!(duration > 0)) throw new Error(`film listen: ${input} has no duration`);
529
+
530
+ const eventsPath = opts.events
531
+ ? resolve(opts.events)
532
+ : existsSync(`${stem}.events.json`)
533
+ ? `${stem}.events.json`
534
+ : null;
535
+ if (opts.events && !existsSync(eventsPath!))
536
+ throw new Error(`film listen: no events file at ${eventsPath}`);
537
+ const evRaw: unknown = eventsPath ? JSON.parse(await readFile(eventsPath, "utf8")) : null;
538
+ const ev = eventsPath ? parseFilmEvents(evRaw) : null;
539
+ const vsPath = opts.vs ? resolve(opts.vs) : null;
540
+ if (vsPath && !existsSync(vsPath)) throw new Error(`film listen: no file at ${vsPath} (--vs)`);
541
+
542
+ const stemFiles = opts.stems
543
+ ? (await readdir(resolve(opts.stems)))
544
+ .filter((f) => SOUND_EXT.has(extname(f).toLowerCase()))
545
+ .sort()
546
+ .map((f) => join(resolve(opts.stems!), f))
547
+ : [];
548
+ if (opts.stems && !stemFiles.length)
549
+ throw new Error(`film listen: no sound files in ${resolve(opts.stems)}`);
550
+
551
+ // the passes that only read run side by side
552
+ const width = sheetWidth(video?.width, video?.height);
553
+ const plotW = width - GUTTER - PAD;
554
+ // a sound that ends before the picture does is read as silence to the film's
555
+ // end, so every row (the spectrum picture included) spans the same time
556
+ const pad = `apad=whole_dur=${duration}`;
557
+ const tmp = await mkdtemp(join(tmpdir(), "open-take-listen-"));
558
+ try {
559
+ const wantCuts = !ev?.cuts.length && !!video;
560
+ // the picture's change: the events file's curve, else read from the picture
561
+ const evEnergy = pictureEnergyOf(ev);
562
+ const pictureFps = frameRate(video?.r_frame_rate);
563
+ const measuredEnergy =
564
+ !evEnergy && video?.width && video.height
565
+ ? fileEnergy(ffmpeg, input, video.width, video.height, pictureFps).catch(() => null)
566
+ : Promise.resolve(null);
567
+ const [loudLog, pcm, stemPcm, pictureCuts] = await Promise.all([
568
+ runTool(
569
+ ffmpeg,
570
+ [
571
+ "-nostats",
572
+ "-v",
573
+ "info",
574
+ "-i",
575
+ input,
576
+ "-vn",
577
+ "-af",
578
+ `${pad},ebur128=peak=true,silencedetect=n=-50dB:d=0.3`,
579
+ "-f",
580
+ "null",
581
+ "-",
582
+ ],
583
+ { stderr: true },
584
+ ),
585
+ decodeMono(ffmpeg, input).then((x) => padTo(x, duration)),
586
+ Promise.all(stemFiles.map((f) => decodeMono(ffmpeg, f))),
587
+ wantCuts ? detectCuts(ffmpeg, input) : Promise.resolve([] as number[]),
588
+ opts.chromePath
589
+ ? runTool(ffmpeg, [
590
+ "-v",
591
+ "error",
592
+ "-i",
593
+ input,
594
+ "-vn",
595
+ "-ac",
596
+ "1",
597
+ "-lavfi",
598
+ `${pad},showspectrumpic=s=${plotW}x${SPEC_H}:legend=0:fscale=log:scale=log:start=30:stop=11000:color=intensity`,
599
+ "-y",
600
+ join(tmp, "spectrum.png"),
601
+ ])
602
+ : Promise.resolve(""),
603
+ ]);
604
+
605
+ // loudness, silences
606
+ const summary = loudLog.slice(loudLog.lastIndexOf("Summary:"));
607
+ const num = (re: RegExp) => {
608
+ const m = re.exec(summary);
609
+ return m ? Number(m[1]) : null;
610
+ };
611
+ const momentary = momentaryOf(loudLog);
612
+ const silences: { start: number; end: number }[] = [];
613
+ let open: number | null = null;
614
+ for (const m of loudLog.matchAll(/silence_(start|end): (-?[\d.]+)/g)) {
615
+ if (m[1] === "start") open = Math.max(0, Number(m[2]));
616
+ else if (open != null) {
617
+ silences.push({ start: round2(open), end: round2(Math.min(duration, Number(m[2]))) });
618
+ open = null;
619
+ }
620
+ }
621
+ if (open != null) silences.push({ start: round2(open), end: round2(duration) });
622
+ const dips = quietDips(momentary);
623
+
624
+ // the analysis
625
+ const s = spectrum(pcm);
626
+ const env = onsetStrength(s);
627
+ const onsets = pickOnsets(s, env, pcm).map(round3);
628
+ const tempo = estimateTempo(s, env, onsets, duration);
629
+ const sections = findSections(s, onsets, duration);
630
+ const changes = soundChanges(pcm);
631
+ const pitch = tuning(pcm);
632
+ const bars = tempo && tempo.beats.length >= 8 ? repeatedBars(s, tempo.beats) : null;
633
+
634
+ const events = (ev?.events ?? []).map((e) => ({
635
+ ...e,
636
+ nearestOnset: nearestOffset(onsets, e.t),
637
+ }));
638
+ const cutTimes = ev?.cuts.length ? ev.cuts : pictureCuts;
639
+ const cuts = cutTimes.map((t) => ({ t, nearestOnset: nearestOffset(onsets, t) }));
640
+
641
+ // stems
642
+ const laneS = 0.05;
643
+ const stems = stemFiles.map((file, i) => stemActivity(file, stemPcm[i]!, laneS, duration));
644
+ const eventWindows =
645
+ stems.length >= 2
646
+ ? (ev?.events ?? []).flatMap((e) => {
647
+ const w = eventWindow(stemPcm, e.t);
648
+ return w
649
+ ? [{ t: e.t, kind: e.kind, stem: stems[w.stem]!.name, overRestDb: w.overRestDb }]
650
+ : [];
651
+ })
652
+ : [];
653
+
654
+ const measured = await measuredEnergy;
655
+ const energy: PictureEnergy | null =
656
+ evEnergy ??
657
+ (measured ? { t0: 0, dt: 1 / pictureFps, values: Array.from(measured, round5) } : null);
658
+ const halves = energy ? halfSeconds(momentary, energy, duration) : [];
659
+
660
+ const listen: FilmListen = {
661
+ input,
662
+ duration: round3(duration),
663
+ sampleRate: Number(audio.sample_rate ?? 0),
664
+ channels: Number(audio.channels ?? 0),
665
+ loudness: {
666
+ // ebur128 reports −70 when nothing sounds above its gate
667
+ how: (num(/I:\s+(-?[\d.]+) LUFS/) ?? -70) > -70 ? "measured" : "not detected",
668
+ integratedLufs: num(/I:\s+(-?[\d.]+) LUFS/),
669
+ lra: num(/LRA:\s+(-?[\d.]+) LU/),
670
+ truePeakDb: num(/Peak:\s+(-?[\d.]+) dBFS/),
671
+ momentary,
672
+ },
673
+ onsets: {
674
+ how: onsets.length ? "measured" : "not detected",
675
+ times: onsets,
676
+ perS: round1(onsets.length / duration),
677
+ },
678
+ tempo: { how: tempo ? "estimated" : "not detected", value: tempo },
679
+ sections: { how: "estimated", list: sections },
680
+ changes: {
681
+ how: !changes ? "not measured" : changes.length ? "estimated" : "not detected",
682
+ list: changes ?? [],
683
+ },
684
+ tuning: pitch,
685
+ bars: bars
686
+ ? { how: "estimated", value: bars }
687
+ : { how: "not measured", value: null, note: "no beat grid to count bars on" },
688
+ silences: { how: "measured", list: silences },
689
+ dips: { how: "measured", list: dips },
690
+ events: {
691
+ how: !ev ? "not measured" : events.length ? "measured" : "not detected",
692
+ file: eventsPath,
693
+ list: events,
694
+ unvoiced: events.filter((e) => e.nearestOnset == null || Math.abs(e.nearestOnset) > 0.04),
695
+ chance40: chanceWithin(onsets, duration),
696
+ },
697
+ cuts: {
698
+ how: cuts.length ? "measured" : ev || video ? "not detected" : "not measured",
699
+ source: ev?.cuts.length ? "events" : pictureCuts.length ? "picture" : "none",
700
+ list: cuts,
701
+ },
702
+ stems: {
703
+ how: stems.length ? "measured" : "not measured",
704
+ dir: opts.stems ? resolve(opts.stems) : null,
705
+ list: stems,
706
+ laneS,
707
+ eventWindows,
708
+ },
709
+ curves: ev?.curves ?? { names: [], t0: 0, dt: 1 / 60, rows: [] },
710
+ picture: {
711
+ how: energy ? "measured" : "not measured",
712
+ source: evEnergy ? "events" : energy ? "picture" : "none",
713
+ energy,
714
+ halves,
715
+ against: halves.length ? pictureAgainstSound(halves) : null,
716
+ },
717
+ clips: [],
718
+ timbre: { how: "not measured" },
719
+ };
720
+
721
+ const credits = creditLines(evRaw);
722
+ if (credits) listen.credits = credits;
723
+
724
+ await mkdir(outDir, { recursive: true });
725
+ if (opts.clips && stemFiles.length) listen.clips = await writeClips(ffmpeg, stemFiles, outDir);
726
+ if (vsPath)
727
+ listen.vs = await listenVs({
728
+ ffmpeg,
729
+ ffprobe,
730
+ input,
731
+ previous: vsPath,
732
+ outDir,
733
+ listen,
734
+ pcm,
735
+ s,
736
+ env,
737
+ });
738
+ const md = join(outDir, "listen.md");
739
+ const json = join(outDir, "listen.json");
740
+ await writeFile(md, `${formatFilmListen(listen)}\n`);
741
+ await writeFile(json, `${JSON.stringify(listen)}\n`);
742
+ let png: string | null = null;
743
+ if (opts.chromePath) {
744
+ png = join(outDir, "listen.png");
745
+ await drawListen(listen, {
746
+ chromePath: opts.chromePath,
747
+ tmp,
748
+ out: png,
749
+ width,
750
+ plotW,
751
+ env,
752
+ hopS: s.hopS,
753
+ every: opts.every ?? defaultSheetEvery(duration),
754
+ fps: frameRate(video?.r_frame_rate),
755
+ });
756
+ }
757
+ return { png, md, json, listen };
758
+ } finally {
759
+ await rm(tmp, { recursive: true, force: true });
760
+ }
761
+ }
762
+
763
+ /** silence after the sound's end, up to the film's length */
764
+ function padTo(pcm: Float32Array, duration: number): Float32Array {
765
+ const n = Math.round(duration * LISTEN_RATE);
766
+ if (pcm.length >= n) return pcm;
767
+ const out = new Float32Array(n);
768
+ out.set(pcm);
769
+ return out;
770
+ }
771
+
772
+ /** hard cuts read from the picture (scene change ≥ 0.3 on a small grey copy),
773
+ * for a film with no events file saying where they are */
774
+ async function detectCuts(ffmpeg: string, file: string): Promise<number[]> {
775
+ const log = await runTool(
776
+ ffmpeg,
777
+ [
778
+ "-v",
779
+ "info",
780
+ "-nostats",
781
+ "-i",
782
+ file,
783
+ "-an",
784
+ "-vf",
785
+ "scale=160:-2,format=gray,select='gt(scene,0.3)',showinfo",
786
+ "-f",
787
+ "null",
788
+ "-",
789
+ ],
790
+ { stderr: true },
791
+ ).catch(() => "");
792
+ return [...log.matchAll(/pts_time:\s*([\d.]+)/g)].map((m) => round3(Number(m[1])));
793
+ }
794
+
795
+ /** stretches of at least 0.3 s whose momentary loudness sits 15 LU or more
796
+ * under the film's median (a breath in the sound, not silence) */
797
+ function quietDips(
798
+ m: { t: number; lufs: number }[],
799
+ ): { start: number; end: number; belowLu: number }[] {
800
+ const sounding = m.filter((p) => p.lufs > -70).map((p) => p.lufs);
801
+ if (!sounding.length) return [];
802
+ const mid = median(sounding);
803
+ const out: { start: number; end: number; belowLu: number }[] = [];
804
+ let start: number | null = null;
805
+ let low = 0;
806
+ for (const p of [...m, { t: Number.POSITIVE_INFINITY, lufs: mid }]) {
807
+ // silence is reported as silence, not as a dip
808
+ const quiet = p.lufs <= mid - 15 && p.lufs > -70;
809
+ if (quiet && start == null) {
810
+ start = p.t;
811
+ low = p.lufs;
812
+ } else if (quiet) low = Math.min(low, p.lufs);
813
+ else if (start != null) {
814
+ const end = Number.isFinite(p.t) ? p.t : m[m.length - 1]!.t;
815
+ // ebur128 stamps the end of each 400 ms window
816
+ if (end - start >= 0.3)
817
+ out.push({
818
+ start: round2(Math.max(0, start - 0.4)),
819
+ end: round2(end - 0.4),
820
+ belowLu: round1(mid - low),
821
+ });
822
+ start = null;
823
+ }
824
+ }
825
+ return out;
826
+ }
827
+
828
+ function stemActivity(file: string, pcm: Float32Array, laneS: number, duration: number) {
829
+ const step = Math.round(LISTEN_RATE * laneS);
830
+ const cells = Math.ceil(duration / laneS);
831
+ const db = new Float32Array(cells).fill(-120);
832
+ let peak = -120;
833
+ for (let c = 0; c < cells; c++) {
834
+ let sq = 0;
835
+ const a = c * step;
836
+ const b = Math.min(pcm.length, a + step);
837
+ for (let i = a; i < b; i++) sq += pcm[i]! * pcm[i]!;
838
+ if (b > a) db[c] = 10 * Math.log10(sq / (b - a) + 1e-12);
839
+ peak = Math.max(peak, db[c]!);
840
+ }
841
+ const gate = Math.max(-60, peak - 40);
842
+ const lane = Array.from(db, (v) => v > gate);
843
+ return {
844
+ name: basename(file).replace(/\.[^.]+$/, ""),
845
+ file,
846
+ activeS: round1(lane.filter(Boolean).length * laneS),
847
+ peakDb: round1(peak),
848
+ lane,
849
+ };
850
+ }
851
+
852
+ /** around an event (20 ms before to 150 ms after), the stem whose level rises
853
+ * most over the 150 ms before, and how many dB it sits over all the others */
854
+ function eventWindow(
855
+ stems: Float32Array[],
856
+ t: number,
857
+ ): { stem: number; overRestDb: number } | null {
858
+ const rms = (x: Float32Array, a: number, b: number) => {
859
+ const i0 = Math.max(0, Math.round(a * LISTEN_RATE));
860
+ const i1 = Math.min(x.length, Math.round(b * LISTEN_RATE));
861
+ let sq = 0;
862
+ for (let i = i0; i < i1; i++) sq += x[i]! * x[i]!;
863
+ return i1 > i0 ? sq / (i1 - i0) : 0;
864
+ };
865
+ const at = stems.map((x) => rms(x, t - 0.02, t + 0.15));
866
+ const before = stems.map((x) => rms(x, t - 0.17, t - 0.02));
867
+ let best = -1;
868
+ let rise = 3; // dB: less is no sound for this event
869
+ stems.forEach((_, i) => {
870
+ const r = 10 * Math.log10((at[i]! + 1e-12) / (before[i]! + 1e-12));
871
+ if (at[i]! > 1e-9 && r > rise) {
872
+ rise = r;
873
+ best = i;
874
+ }
875
+ });
876
+ if (best < 0) return null;
877
+ const rest = at.reduce((sum, p, i) => (i === best ? sum : sum + p), 0);
878
+ return { stem: best, overRestDb: round1(10 * Math.log10((at[best]! + 1e-12) / (rest + 1e-12))) };
879
+ }
880
+
881
+ async function writeClips(ffmpeg: string, stems: string[], outDir: string): Promise<string[]> {
882
+ await mkdir(join(outDir, "solo"), { recursive: true });
883
+ const written: string[] = [];
884
+ const name = (f: string) => basename(f).replace(/\.[^.]+$/, "");
885
+ await Promise.all(
886
+ stems.map(async (f) => {
887
+ const out = join(outDir, "solo", `${name(f)}.m4a`);
888
+ await runTool(ffmpeg, ["-v", "error", "-i", f, "-c:a", "aac", "-b:a", "160k", "-y", out]);
889
+ written.push(out);
890
+ }),
891
+ );
892
+ if (stems.length >= 2) {
893
+ await mkdir(join(outDir, "mute"), { recursive: true });
894
+ await Promise.all(
895
+ stems.map(async (f) => {
896
+ const others = stems.filter((g) => g !== f);
897
+ const out = join(outDir, "mute", `${name(f)}.m4a`);
898
+ await runTool(ffmpeg, [
899
+ "-v",
900
+ "error",
901
+ ...others.flatMap((g) => ["-i", g]),
902
+ "-filter_complex",
903
+ `amix=inputs=${others.length}:normalize=0:duration=longest`,
904
+ "-c:a",
905
+ "aac",
906
+ "-b:a",
907
+ "160k",
908
+ "-y",
909
+ out,
910
+ ]);
911
+ written.push(out);
912
+ }),
913
+ );
914
+ }
915
+ return written.sort();
916
+ }
917
+
918
+ // --- beside a previous version (--vs) ------------------------------------------------
919
+
920
+ type Loud = { integratedLufs: number | null; lra: number | null; truePeakDb: number | null };
921
+
922
+ export type ListenVsMoment = {
923
+ start: number;
924
+ end: number;
925
+ /** spectrumDiff's frame differences, averaged over the stretch (dB) */
926
+ diffDb: number;
927
+ /** dBFS RMS over the stretch */
928
+ levelDb: { this: number; previous: number };
929
+ /** onsets in the stretch with none within 40 ms in the other */
930
+ onlyThis: number;
931
+ onlyPrevious: number;
932
+ };
933
+
934
+ export type ListenVs = {
935
+ previous: string;
936
+ durations: { this: number; previous: number };
937
+ /** the time compared: the longer of the two, the shorter silent after its end */
938
+ duration: number;
939
+ /** where the previous one's onset strength lines up best with this one's, ±2 s
940
+ * (both are still compared on the same film time) */
941
+ offset: { how: How; seconds: number | null };
942
+ loudness: { how: How; this: Loud; previous: Loud };
943
+ tempo: { how: How; this: number | null; previous: number | null };
944
+ onsets: {
945
+ how: How;
946
+ this: number;
947
+ previous: number;
948
+ /** onset times with none within 40 ms in the other */
949
+ onlyThis: number[];
950
+ onlyPrevious: number[];
951
+ };
952
+ sections: {
953
+ how: How;
954
+ this: number[];
955
+ previous: number[];
956
+ /** boundaries with none within 0.5 s in the other */
957
+ onlyThis: number[];
958
+ onlyPrevious: number[];
959
+ };
960
+ /** the events file's events: an onset within 40 ms in this one and not the previous (gained), or the reverse */
961
+ events: {
962
+ how: How;
963
+ gained: { t: number; kind: string; label?: string }[];
964
+ lost: { t: number; kind: string; label?: string }[];
965
+ };
966
+ /** the 1 s stretches whose spectra differ most (1 dB or more), most first;
967
+ * typicalDb: the median 1 s stretch's difference, to read them against */
968
+ moments: { how: How; list: ListenVsMoment[]; typicalDb: number };
969
+ /** <out>/vs/: moment-N.this.m4a and moment-N.previous.m4a (the same film time,
970
+ * 1 s either side), aba.m4a (this, previous, this at the first moment) */
971
+ clips: string[];
972
+ };
973
+
974
+ /** a film's momentary loudness (400 ms windows, stamped at their end), as
975
+ * `film listen` reads it; [] when it has no sound */
976
+ export async function momentaryLoudness(
977
+ ffmpeg: string,
978
+ file: string,
979
+ duration?: number,
980
+ ): Promise<{ t: number; lufs: number }[]> {
981
+ // padded to the film's end as `film listen` pads it, so the two read the same bins
982
+ const af = duration ? `apad=whole_dur=${duration},ebur128` : "ebur128";
983
+ const log = await runTool(
984
+ ffmpeg,
985
+ ["-nostats", "-v", "info", "-i", file, "-vn", "-af", af, "-f", "null", "-"],
986
+ { stderr: true },
987
+ );
988
+ return momentaryOf(log);
989
+ }
990
+
991
+ /** ebur128's momentary readings (400 ms, stamped at their end) from its log; −120 for silence */
992
+ function momentaryOf(log: string): { t: number; lufs: number }[] {
993
+ const out: { t: number; lufs: number }[] = [];
994
+ for (const m of log.matchAll(/t:\s*([\d.]+)\s+TARGET:\S+ LUFS\s+M:\s*(-?[\d.]+|-?inf)/g))
995
+ out.push({ t: Number(m[1]), lufs: Number.isFinite(Number(m[2])) ? Number(m[2]) : -120 });
996
+ return out;
997
+ }
998
+
999
+ async function loudnessOf(ffmpeg: string, file: string): Promise<Loud> {
1000
+ const log = await runTool(
1001
+ ffmpeg,
1002
+ ["-nostats", "-v", "info", "-i", file, "-vn", "-af", "ebur128=peak=true", "-f", "null", "-"],
1003
+ { stderr: true },
1004
+ );
1005
+ const summary = log.slice(log.lastIndexOf("Summary:"));
1006
+ const num = (re: RegExp) => {
1007
+ const m = re.exec(summary);
1008
+ return m ? Number(m[1]) : null;
1009
+ };
1010
+ return {
1011
+ integratedLufs: num(/I:\s+(-?[\d.]+) LUFS/),
1012
+ lra: num(/LRA:\s+(-?[\d.]+) LU/),
1013
+ truePeakDb: num(/Peak:\s+(-?[\d.]+) dBFS/),
1014
+ };
1015
+ }
1016
+
1017
+ /** the lag (s, positive = the previous one comes later) at which two onset
1018
+ * strengths correlate best within ±maxS, or null when either is flat */
1019
+ export function bestLag(a: Float32Array, b: Float32Array, hopS: number, maxS = 2): number | null {
1020
+ const n = Math.min(a.length, b.length);
1021
+ const norm = (x: Float32Array) => {
1022
+ let m = 0;
1023
+ for (let i = 0; i < n; i++) m += x[i]!;
1024
+ m /= n || 1;
1025
+ const y = new Float32Array(n);
1026
+ let e = 0;
1027
+ for (let i = 0; i < n; i++) {
1028
+ y[i] = x[i]! - m;
1029
+ e += y[i]! * y[i]!;
1030
+ }
1031
+ return e > 1e-12 ? y : null;
1032
+ };
1033
+ const p = norm(a);
1034
+ const q = norm(b);
1035
+ if (!p || !q) return null;
1036
+ const maxLag = Math.round(maxS / hopS);
1037
+ let best = 0;
1038
+ let bestV = Number.NEGATIVE_INFINITY;
1039
+ for (let lag = -maxLag; lag <= maxLag; lag++) {
1040
+ let v = 0;
1041
+ for (let i = Math.max(0, -lag); i < Math.min(n, n - lag); i++) v += p[i]! * q[i + lag]!;
1042
+ if (v > bestV || (v === bestV && Math.abs(lag) < Math.abs(best))) {
1043
+ bestV = v;
1044
+ best = lag;
1045
+ }
1046
+ }
1047
+ return round3(best * hopS);
1048
+ }
1049
+
1050
+ /** per frame, how far two spectra's band energies differ (dB, each floored at
1051
+ * FLOOR_DB): the mean of the largest quarter of the band differences, so a
1052
+ * sound in a few bands counts as much as a broad one; frames past either
1053
+ * one's end count as silence */
1054
+ export function spectrumDiff(a: Spectrum, b: Spectrum): Float32Array {
1055
+ const n = Math.max(a.bands.length, b.bands.length);
1056
+ const out = new Float32Array(n);
1057
+ const top = Math.max(1, Math.round(BANDS / 4));
1058
+ const d = new Float64Array(BANDS);
1059
+ for (let f = 0; f < n; f++) {
1060
+ for (let k = 0; k < BANDS; k++)
1061
+ d[k] = Math.abs(
1062
+ Math.max(FLOOR_DB, a.bands[f]?.[k] ?? FLOOR_DB) -
1063
+ Math.max(FLOOR_DB, b.bands[f]?.[k] ?? FLOOR_DB),
1064
+ );
1065
+ d.sort();
1066
+ let sum = 0;
1067
+ for (let k = BANDS - top; k < BANDS; k++) sum += d[k]!;
1068
+ out[f] = sum / top;
1069
+ }
1070
+ return out;
1071
+ }
1072
+
1073
+ /** every `windowS` stretch, `stepS` apart, with its mean frame difference (dB) */
1074
+ function stretchDiffs(
1075
+ diff: Float32Array,
1076
+ hopS: number,
1077
+ duration: number,
1078
+ windowS: number,
1079
+ stepS: number,
1080
+ ): { start: number; end: number; diffDb: number }[] {
1081
+ const out: { start: number; end: number; diffDb: number }[] = [];
1082
+ const last = Math.max(0, duration - windowS);
1083
+ for (let a = 0; a <= last + 1e-9; a += stepS) {
1084
+ const b = Math.min(duration, a + windowS);
1085
+ const f0 = Math.floor(a / hopS);
1086
+ const f1 = Math.min(diff.length, Math.max(f0 + 1, Math.floor(b / hopS)));
1087
+ let sum = 0;
1088
+ for (let f = f0; f < f1; f++) sum += diff[f]!;
1089
+ out.push({ start: round2(a), end: round2(b), diffDb: round1(f1 > f0 ? sum / (f1 - f0) : 0) });
1090
+ }
1091
+ return out;
1092
+ }
1093
+
1094
+ /** the median of every 1 s stretch's difference: what the two differ by
1095
+ * anywhere, e.g. from encoding twice, to read the moments against */
1096
+ export function typicalDiff(diff: Float32Array, hopS: number, duration: number): number {
1097
+ const xs = stretchDiffs(diff, hopS, duration, 1, 0.25)
1098
+ .map((x) => x.diffDb)
1099
+ .sort((a, b) => a - b);
1100
+ if (!xs.length) return 0;
1101
+ const m = xs.length >> 1;
1102
+ return round1(xs.length % 2 ? xs[m]! : (xs[m - 1]! + xs[m]!) / 2);
1103
+ }
1104
+
1105
+ /** the stretches of `windowS` whose mean frame difference is largest, at least
1106
+ * `minDb`, none overlapping, most first */
1107
+ export function changedMoments(
1108
+ diff: Float32Array,
1109
+ hopS: number,
1110
+ duration: number,
1111
+ { windowS = 1, stepS = 0.25, minDb = 1, max = 3 } = {},
1112
+ ): { start: number; end: number; diffDb: number }[] {
1113
+ const cands = stretchDiffs(diff, hopS, duration, windowS, stepS).filter((c) => c.diffDb >= minDb);
1114
+ cands.sort((x, y) => y.diffDb - x.diffDb || x.start - y.start);
1115
+ const out: typeof cands = [];
1116
+ for (const c of cands) {
1117
+ if (out.length >= max) break;
1118
+ if (out.every((o) => c.end <= o.start || c.start >= o.end)) out.push(c);
1119
+ }
1120
+ return out;
1121
+ }
1122
+
1123
+ const rmsDb = (pcm: Float32Array, a: number, b: number) => {
1124
+ const i0 = Math.max(0, Math.round(a * LISTEN_RATE));
1125
+ const i1 = Math.min(pcm.length, Math.round(b * LISTEN_RATE));
1126
+ let sq = 0;
1127
+ for (let i = i0; i < i1; i++) sq += pcm[i]! * pcm[i]!;
1128
+ return round1(i1 > i0 ? Math.max(-120, 10 * Math.log10(sq / (i1 - i0) + 1e-12)) : -120);
1129
+ };
1130
+
1131
+ const onlyIn = (xs: readonly number[], other: readonly number[], w: number) =>
1132
+ xs.filter((t) => {
1133
+ const d = nearestOffset(other, t);
1134
+ return d == null || Math.abs(d) > w;
1135
+ });
1136
+
1137
+ async function listenVs(o: {
1138
+ ffmpeg: string;
1139
+ ffprobe: string;
1140
+ input: string;
1141
+ previous: string;
1142
+ outDir: string;
1143
+ listen: FilmListen;
1144
+ pcm: Float32Array;
1145
+ s: Spectrum;
1146
+ env: Float32Array;
1147
+ }): Promise<ListenVs> {
1148
+ const { ffmpeg, listen: l } = o;
1149
+ const probed = JSON.parse(
1150
+ await runTool(o.ffprobe, [
1151
+ "-v",
1152
+ "error",
1153
+ "-show_entries",
1154
+ "stream=codec_type:format=duration",
1155
+ "-of",
1156
+ "json",
1157
+ o.previous,
1158
+ ]),
1159
+ ) as { streams?: { codec_type?: string }[]; format?: { duration?: string } };
1160
+ if (!probed.streams?.some((x) => x.codec_type === "audio"))
1161
+ throw new Error(`film listen: ${o.previous} (--vs) has no sound to compare with`);
1162
+ const [pcmPrevRaw, loudPrev] = await Promise.all([
1163
+ decodeMono(ffmpeg, o.previous),
1164
+ loudnessOf(ffmpeg, o.previous),
1165
+ ]);
1166
+ const durPrev = Number(probed.format?.duration) || pcmPrevRaw.length / LISTEN_RATE;
1167
+ const D = Math.max(l.duration, durPrev);
1168
+ const pcmThis = padTo(o.pcm, D);
1169
+ const pcmPrev = padTo(pcmPrevRaw, D);
1170
+ const sThis = pcmThis === o.pcm ? o.s : spectrum(pcmThis);
1171
+ const envThis = sThis === o.s ? o.env : onsetStrength(sThis);
1172
+ const sPrev = spectrum(pcmPrev);
1173
+ const envPrev = onsetStrength(sPrev);
1174
+ const onsPrev = pickOnsets(sPrev, envPrev, pcmPrev).map(round3);
1175
+ const tempoPrev = estimateTempo(sPrev, envPrev, onsPrev, D);
1176
+ const secPrev = findSections(sPrev, onsPrev, D);
1177
+ const onsThis = l.onsets.times;
1178
+ const W = 0.04;
1179
+ const onlyThis = onlyIn(onsThis, onsPrev, W);
1180
+ const onlyPrevious = onlyIn(onsPrev, onsThis, W);
1181
+ const bThis = l.sections.list.slice(1).map((x) => x.start);
1182
+ const bPrev = secPrev.slice(1).map((x) => x.start);
1183
+ // a lag read off a handful of onsets is noise, not an offset
1184
+ const lag =
1185
+ onsThis.length >= 4 && onsPrev.length >= 4 ? bestLag(envThis, envPrev, sThis.hopS) : null;
1186
+ const diff = spectrumDiff(sThis, sPrev);
1187
+ const typicalDb = typicalDiff(diff, sThis.hopS, D);
1188
+ const moments = changedMoments(diff, sThis.hopS, D).map((m) => ({
1189
+ ...m,
1190
+ levelDb: { this: rmsDb(pcmThis, m.start, m.end), previous: rmsDb(pcmPrev, m.start, m.end) },
1191
+ onlyThis: onlyThis.filter((t) => t >= m.start && t < m.end).length,
1192
+ onlyPrevious: onlyPrevious.filter((t) => t >= m.start && t < m.end).length,
1193
+ }));
1194
+ const ev = (e: FilmEvent) =>
1195
+ e.label ? { t: e.t, kind: e.kind, label: e.label } : { t: e.t, kind: e.kind };
1196
+ const sounded = (d: number | null) => d != null && Math.abs(d) <= W;
1197
+ const gained = l.events.list.filter(
1198
+ (e) => sounded(e.nearestOnset) && !sounded(nearestOffset(onsPrev, e.t)),
1199
+ );
1200
+ const lost = l.events.list.filter(
1201
+ (e) => !sounded(e.nearestOnset) && sounded(nearestOffset(onsPrev, e.t)),
1202
+ );
1203
+ const prevSounds = loudPrev.integratedLufs != null && loudPrev.integratedLufs > -70;
1204
+
1205
+ // the clips: the same film time from each, 1 s either side of the stretch
1206
+ const clips: string[] = [];
1207
+ if (moments.length) {
1208
+ const dir = join(o.outDir, "vs");
1209
+ await mkdir(dir, { recursive: true });
1210
+ const span = (m: { start: number; end: number }) => {
1211
+ const a = round2(Math.max(0, m.start - 1));
1212
+ return { a, b: round2(Math.min(D, m.end + 1)) };
1213
+ };
1214
+ const cut = (a: number, b: number) =>
1215
+ `apad=whole_dur=${b},atrim=start=${a}:end=${b},asetpts=PTS-STARTPTS`;
1216
+ const jobs = moments.flatMap((m, i) => {
1217
+ const { a, b } = span(m);
1218
+ return [
1219
+ [o.input, join(dir, `moment-${i + 1}.this.m4a`), a, b] as const,
1220
+ [o.previous, join(dir, `moment-${i + 1}.previous.m4a`), a, b] as const,
1221
+ ];
1222
+ });
1223
+ await Promise.all(
1224
+ jobs.map(([src, out, a, b]) =>
1225
+ runTool(ffmpeg, [
1226
+ "-v",
1227
+ "error",
1228
+ "-i",
1229
+ src,
1230
+ "-vn",
1231
+ "-af",
1232
+ cut(a, b),
1233
+ "-c:a",
1234
+ "aac",
1235
+ "-b:a",
1236
+ "192k",
1237
+ "-y",
1238
+ out,
1239
+ ]),
1240
+ ),
1241
+ );
1242
+ clips.push(...jobs.map((j) => j[1]));
1243
+ const { a, b } = span(moments[0]!);
1244
+ const fmt = "aformat=sample_rates=48000:channel_layouts=stereo";
1245
+ const aba = join(dir, "aba.m4a");
1246
+ await runTool(ffmpeg, [
1247
+ "-v",
1248
+ "error",
1249
+ "-i",
1250
+ o.input,
1251
+ "-i",
1252
+ o.previous,
1253
+ "-filter_complex",
1254
+ `[0:a]${cut(a, b)},${fmt},asplit=2[a1][a2];[1:a]${cut(a, b)},${fmt}[b];` +
1255
+ `anullsrc=r=48000:cl=stereo,atrim=duration=0.4,asplit=2[g1][g2];` +
1256
+ `[a1][g1][b][g2][a2]concat=n=5:v=0:a=1[o]`,
1257
+ "-map",
1258
+ "[o]",
1259
+ "-c:a",
1260
+ "aac",
1261
+ "-b:a",
1262
+ "192k",
1263
+ "-y",
1264
+ aba,
1265
+ ]);
1266
+ clips.push(aba);
1267
+ }
1268
+
1269
+ return {
1270
+ previous: o.previous,
1271
+ durations: { this: l.duration, previous: round3(durPrev) },
1272
+ duration: round3(D),
1273
+ offset: { how: lag == null ? "not detected" : "estimated", seconds: lag },
1274
+ loudness: {
1275
+ how: l.loudness.how === "measured" || prevSounds ? "measured" : "not detected",
1276
+ this: {
1277
+ integratedLufs: l.loudness.integratedLufs,
1278
+ lra: l.loudness.lra,
1279
+ truePeakDb: l.loudness.truePeakDb,
1280
+ },
1281
+ previous: loudPrev,
1282
+ },
1283
+ tempo: {
1284
+ how: l.tempo.value || tempoPrev ? "estimated" : "not detected",
1285
+ this: l.tempo.value?.bpm ?? null,
1286
+ previous: tempoPrev?.bpm ?? null,
1287
+ },
1288
+ onsets: {
1289
+ how: onsThis.length || onsPrev.length ? "measured" : "not detected",
1290
+ this: onsThis.length,
1291
+ previous: onsPrev.length,
1292
+ onlyThis,
1293
+ onlyPrevious,
1294
+ },
1295
+ sections: {
1296
+ how: "estimated",
1297
+ this: bThis,
1298
+ previous: bPrev,
1299
+ onlyThis: onlyIn(bThis, bPrev, 0.5),
1300
+ onlyPrevious: onlyIn(bPrev, bThis, 0.5),
1301
+ },
1302
+ events: {
1303
+ how: !l.events.file ? "not measured" : l.events.list.length ? "measured" : "not detected",
1304
+ gained: gained.map(ev),
1305
+ lost: lost.map(ev),
1306
+ },
1307
+ moments: { how: moments.length ? "measured" : "not detected", list: moments, typicalDb },
1308
+ clips,
1309
+ };
1310
+ }
1311
+
1312
+ function formatListenVs(v: ListenVs): string[] {
1313
+ const L: string[] = [];
1314
+ const tag = (h: How) => `(${h})`;
1315
+ const fmtS = (t: number) => `${t.toFixed(2)}s`;
1316
+ const list = (xs: number[], max = 12) =>
1317
+ xs.length > max
1318
+ ? `${xs.slice(0, max).map(fmtS).join(", ")}, … (${xs.length})`
1319
+ : xs.map(fmtS).join(", ");
1320
+ const lu = (a: number | null, b: number | null, unit: string) =>
1321
+ a == null || b == null
1322
+ ? `this ${a ?? "?"}, previous ${b ?? "?"} ${unit}`
1323
+ : `this ${a}, previous ${b} ${unit} (${a - b >= 0 ? "+" : ""}${round1(a - b)})`;
1324
+ const lvl = (db: number) => (db <= -120 ? "silent" : `${db} dBFS`);
1325
+ L.push(`## Beside the previous version — ${basename(v.previous)}`, "");
1326
+ L.push(
1327
+ `- lengths: this ${fmtS(v.durations.this)}, previous ${fmtS(v.durations.previous)}; compared on the same film time over ${fmtS(v.duration)}, the shorter one silent after its end ${tag("measured")}`,
1328
+ );
1329
+ L.push(
1330
+ v.offset.seconds == null
1331
+ ? `- alignment: too few onsets (under 4 in one of the two) to line them up ${tag(v.offset.how)}`
1332
+ : v.offset.seconds === 0
1333
+ ? `- alignment: the onsets line up best with no shift (searched ±2 s) ${tag(v.offset.how)}`
1334
+ : `- alignment: the onsets line up best with the previous one's sound ${Math.round(Math.abs(v.offset.seconds) * 1000)} ms ${v.offset.seconds > 0 ? "later" : "earlier"} than this one's (searched ±2 s); everything below still compares the same film time ${tag(v.offset.how)}`,
1335
+ );
1336
+ const a = v.loudness.this;
1337
+ const b = v.loudness.previous;
1338
+ L.push(
1339
+ `- loudness: integrated ${lu(a.integratedLufs, b.integratedLufs, "LUFS")}; range ${lu(a.lra, b.lra, "LU")}; true peak ${lu(a.truePeakDb, b.truePeakDb, "dBFS")} ${tag(v.loudness.how)}`,
1340
+ );
1341
+ L.push(
1342
+ v.tempo.this == null && v.tempo.previous == null
1343
+ ? `- tempo: neither has a repeating period between 60 and 200 BPM ${tag(v.tempo.how)}`
1344
+ : `- tempo: this ${v.tempo.this != null ? `≈ ${v.tempo.this} BPM` : "no grid"}, previous ${v.tempo.previous != null ? `≈ ${v.tempo.previous} BPM` : "no grid"} ${tag(v.tempo.how)}`,
1345
+ );
1346
+ L.push(
1347
+ `- onsets: this ${v.onsets.this}, previous ${v.onsets.previous}; ${v.onsets.onlyThis.length} only in this, ${v.onsets.onlyPrevious.length} only in the previous (none in the other within 40 ms) ${tag(v.onsets.how)}`,
1348
+ );
1349
+ if (v.onsets.onlyThis.length)
1350
+ L.push(` - only in this: ${list(v.onsets.onlyThis)} ${tag(v.onsets.how)}`);
1351
+ if (v.onsets.onlyPrevious.length)
1352
+ L.push(` - only in the previous: ${list(v.onsets.onlyPrevious)} ${tag(v.onsets.how)}`);
1353
+ L.push(
1354
+ `- section boundaries: this ${v.sections.this.length ? list(v.sections.this) : "none"}; previous ${v.sections.previous.length ? list(v.sections.previous) : "none"}; new (none in the previous within 0.5 s): ${v.sections.onlyThis.length ? list(v.sections.onlyThis) : "none"}; gone: ${v.sections.onlyPrevious.length ? list(v.sections.onlyPrevious) : "none"} ${tag(v.sections.how)}`,
1355
+ );
1356
+ const evs = (xs: ListenVs["events"]["gained"]) =>
1357
+ xs.map((x) => `${fmtS(x.t)} ${x.kind}${x.label ? ` "${x.label}"` : ""}`).join(", ");
1358
+ if (v.events.how === "not measured")
1359
+ L.push(`- events that gained or lost a sound: no events file ${tag(v.events.how)}`);
1360
+ else if (v.events.how === "not detected")
1361
+ L.push(`- events: the events file lists none ${tag(v.events.how)}`);
1362
+ else {
1363
+ L.push(
1364
+ `- events that gained a sound (an onset within 40 ms in this, none in the previous): ${v.events.gained.length ? evs(v.events.gained) : "none"} ${tag(v.events.how)}`,
1365
+ );
1366
+ L.push(
1367
+ `- events that lost one (an onset within 40 ms in the previous, none in this): ${v.events.lost.length ? evs(v.events.lost) : "none"} ${tag(v.events.how)}`,
1368
+ );
1369
+ }
1370
+ if (!v.moments.list.length)
1371
+ L.push(
1372
+ `- where they differ most: no 1 s stretch whose spectra differ by 1 dB or more (per frame the mean of the largest quarter of the 48 band-energy differences) ${tag(v.moments.how)}`,
1373
+ );
1374
+ else {
1375
+ L.push(
1376
+ `- where they differ most (1 s stretches; per frame the mean of the largest quarter of the 48 band-energy differences, averaged over the stretch; the median stretch differs by ${v.moments.typicalDb} dB, so a moment near that differs about as much as the two do everywhere, e.g. from encoding):`,
1377
+ );
1378
+ for (const [i, m] of v.moments.list.entries())
1379
+ L.push(
1380
+ ` ${i + 1}. ${fmtS(m.start)}–${fmtS(m.end)}: ${m.diffDb} dB; level this ${lvl(m.levelDb.this)}, previous ${lvl(m.levelDb.previous)}; ${m.onlyThis} onset${m.onlyThis === 1 ? "" : "s"} only in this, ${m.onlyPrevious} only in the previous ${tag(v.moments.how)}`,
1381
+ );
1382
+ }
1383
+ if (v.clips.length)
1384
+ L.push(
1385
+ "",
1386
+ "Clips (each moment from both, the same film time, 1 s either side; aba.m4a plays this, the previous, this at the first one; levels as they are, not matched):",
1387
+ "",
1388
+ ...v.clips.map((f) => `- ${f}`),
1389
+ );
1390
+ return L;
1391
+ }
1392
+
1393
+ /** the events file's "credits" field as lines. `film render` writes a list of
1394
+ * { what?, by?, licence?, url?, text? } (render.ts FilmCredit); read leniently
1395
+ * besides: a string, a list of strings, other names for the same fields
1396
+ * (title/name/file, author/artist, license, source), or an object of
1397
+ * name → credit; null when there is no such field */
1398
+ export function creditLines(raw: unknown): string[] | null {
1399
+ if (!raw || typeof raw !== "object" || !("credits" in raw)) return null;
1400
+ const c = (raw as { credits: unknown }).credits;
1401
+ const str = (x: unknown) =>
1402
+ typeof x === "string" || typeof x === "number" ? String(x).trim() : "";
1403
+ const one = (x: unknown): string => {
1404
+ if (typeof x !== "object" || !x) return str(x);
1405
+ const o = x as Record<string, unknown>;
1406
+ const by = str(o.by) || str(o.author) || str(o.artist);
1407
+ const parts = [
1408
+ str(o.what) || str(o.title) || str(o.name) || str(o.file),
1409
+ by ? `by ${by}` : "",
1410
+ str(o.licence) || str(o.license),
1411
+ str(o.url) || str(o.source),
1412
+ ].filter(Boolean);
1413
+ const text = str(o.text);
1414
+ // the attribution line as the page wants it shown, after what it credits
1415
+ if (text) return parts.length ? `${parts.join(", ")} — "${text}"` : text;
1416
+ return parts.length ? parts.join(", ") : JSON.stringify(x);
1417
+ };
1418
+ const lines = Array.isArray(c)
1419
+ ? c.map(one)
1420
+ : c && typeof c === "object"
1421
+ ? Object.entries(c as Record<string, unknown>).map(([k, x]) => `${k}: ${one(x)}`)
1422
+ : [one(c)];
1423
+ return lines.filter(Boolean);
1424
+ }
1425
+
1426
+ // --- the text --------------------------------------------------------------------------
1427
+
1428
+ /** this grid as the page can have it: kit/cut.js `grid({ bpm, offset })`
1429
+ * (offset: the time of beat 0), with the period as fitted. A tempo that is
1430
+ * not steady has beats that follow the onsets, which an even pulse does not.
1431
+ * Information. */
1432
+ export function gridOnPage(
1433
+ t: Pick<Tempo, "periodS" | "bpm" | "beats"> & { steady?: boolean },
1434
+ ): string {
1435
+ const bpm = t.periodS > 0 ? Math.round((60 / t.periodS) * 1000) / 1000 : t.bpm;
1436
+ const offset = Math.round((t.beats[0] ?? 0) * 1000) / 1000;
1437
+ const what =
1438
+ t.steady === false
1439
+ ? "gives an even pulse at this tempo from the first beat (these beats follow the onsets where the tempo moves; a beats file keeps them)"
1440
+ : "gives this grid (bar, snap, between; its beat 0 is the first beat found, which need not be a bar's first)";
1441
+ return `on the page: \`grid({ bpm: ${bpm}, offset: ${offset} })\` in kit/cut.js ${what}; \`film beats\` writes a music file's grid, downbeats included, as a beats file grid() also takes — information, not a limit`;
1442
+ }
1443
+
1444
+ export function formatFilmListen(l: FilmListen): string {
1445
+ const L: string[] = [];
1446
+ const tag = (h: How) => `(${h})`;
1447
+ const fmtS = (t: number) => `${t.toFixed(2)}s`;
1448
+ const ms = (d: number | null) =>
1449
+ d == null ? "no onset" : `${d >= 0 ? "+" : ""}${Math.round(d * 1000)} ms`;
1450
+ L.push(`# film listen — ${basename(l.input)}`, "");
1451
+ L.push(
1452
+ `duration ${fmtS(l.duration)}, ${l.sampleRate} Hz, ${l.channels} channel${l.channels === 1 ? "" : "s"}`,
1453
+ "",
1454
+ "Information only: what was measured, what is estimated, what was not found. Nothing here is a target.",
1455
+ "",
1456
+ );
1457
+ L.push("## Loudness", "");
1458
+ const lo = l.loudness;
1459
+ if (lo.how === "not detected")
1460
+ L.push(`- loudness: nothing sounds above ebur128's −70 LUFS gate ${tag(lo.how)}`);
1461
+ else
1462
+ L.push(
1463
+ `- integrated ${lo.integratedLufs ?? "?"} LUFS, loudness range ${lo.lra ?? "?"} LU, true peak ${lo.truePeakDb ?? "?"} dBFS ${tag(lo.how)}`,
1464
+ );
1465
+ const sounding = lo.momentary.filter((p) => p.lufs > -70);
1466
+ if (sounding.length) {
1467
+ const vals = sounding.map((p) => p.lufs).sort((a, b) => a - b);
1468
+ L.push(
1469
+ `- momentary (400 ms): 10th percentile ${round1(vals[Math.floor(vals.length * 0.1)]!)} LUFS, median ${round1(median(vals))}, 90th ${round1(vals[Math.floor(vals.length * 0.9)]!)} ${tag("measured")}`,
1470
+ );
1471
+ }
1472
+ L.push("", "## Rhythm", "");
1473
+ L.push(`- onsets: ${l.onsets.times.length} (${l.onsets.perS}/s) ${tag(l.onsets.how)}`);
1474
+ const t = l.tempo.value;
1475
+ if (t) {
1476
+ L.push(
1477
+ `- tempo ≈ ${t.bpm} BPM, periodicity strength ${t.strength} (autocorrelation of onset strength at that period over zero lag) ${tag("estimated")}`,
1478
+ );
1479
+ if (t.alternatives.length)
1480
+ L.push(
1481
+ `- also repeating at: ${t.alternatives.map((a) => `${a.bpm} BPM (${a.strength})`).join(", ")} ${tag("estimated")}`,
1482
+ );
1483
+ L.push(
1484
+ `- beat grid: ${t.beats.length} beats from ${fmtS(t.beats[0] ?? 0)}; ${Math.round(t.gridFit * 100)}% of beats have an onset within 40 ms ${tag("estimated")}`,
1485
+ );
1486
+ L.push(`- ${gridOnPage(t)}`);
1487
+ } else L.push(`- tempo: no repeating period between 60 and 200 BPM ${tag("not detected")}`);
1488
+ const b = l.bars.value;
1489
+ if (b) {
1490
+ L.push(
1491
+ `- bars of ${b.beatsPerBar} beats on that grid: ${b.bars}; ${b.repeats.length} repeat an earlier bar verbatim (same band energies within 1.5 dB, correlation ≥ 0.95) ${tag("estimated")}`,
1492
+ );
1493
+ if (b.longestRun)
1494
+ L.push(
1495
+ `- longest repeated stretch: bars ${b.longestRun.from}–${b.longestRun.to} repeat bars ${b.longestRun.of}–${b.longestRun.of + b.longestRun.to - b.longestRun.from} ${tag("estimated")}`,
1496
+ );
1497
+ if (b.repeats.length) {
1498
+ const groups = new Map<number, number[]>();
1499
+ for (const r of b.repeats) groups.set(r.of, [...(groups.get(r.of) ?? []), r.bar]);
1500
+ L.push(
1501
+ `- which: ${[...groups].map(([of, bars]) => `bar ${of} again at ${bars.join(", ")}`).join("; ")} ${tag("estimated")}`,
1502
+ );
1503
+ }
1504
+ } else L.push(`- repeated bars: ${l.bars.note ?? ""} ${tag(l.bars.how)}`);
1505
+ L.push("", "## Sections (where the texture changes)", "");
1506
+ for (const [i, s] of l.sections.list.entries())
1507
+ L.push(
1508
+ `- ${i + 1}. ${fmtS(s.start)}–${fmtS(s.end)}: ${s.levelDb > -120 ? `level ${s.levelDb} dBFS, ${s.onsetsPerS} onsets/s, centroid ${s.centroidHz} Hz` : "silent"}${i ? `, change at start ${s.change} (1 = the sharpest in this film)` : ""} ${tag(l.sections.how)}`,
1509
+ );
1510
+ // a listen read back from before these were measured has neither
1511
+ if (l.changes) {
1512
+ L.push("", "## Changes in the sound (what changed at once, against the 3 s before)", "");
1513
+ const nearCut = (t: number) => l.cuts.list.find((c) => Math.abs(c.t - t) <= 0.25);
1514
+ for (const [i, x] of formatSoundChanges(
1515
+ l.changes.how === "not measured" ? null : l.changes.list,
1516
+ ).entries()) {
1517
+ const c = l.changes.list[i];
1518
+ const cut = c && nearCut(c.t);
1519
+ L.push(cut ? x.replace(/ \(estimated\)$/, ` — a cut at ${fmtS(cut.t)} (estimated)`) : x);
1520
+ }
1521
+ }
1522
+ if (l.tuning) L.push("", "## Pitch", "", ...formatTuning(l.tuning));
1523
+ L.push("", "## Pauses", "");
1524
+ if (l.silences.list.length)
1525
+ L.push(
1526
+ `- silences (under −50 dBFS for 0.3 s or more): ${l.silences.list.map((s) => `${fmtS(s.start)}–${fmtS(s.end)}`).join(", ")} ${tag("measured")}`,
1527
+ );
1528
+ else L.push(`- silences (under −50 dBFS for 0.3 s or more): none ${tag("not detected")}`);
1529
+ if (l.dips.list.length)
1530
+ L.push(
1531
+ `- quiet dips (15 LU or more under the median momentary loudness): ${l.dips.list.map((d) => `${fmtS(d.start)}–${fmtS(d.end)} (−${d.belowLu} LU)`).join(", ")} ${tag("measured")}`,
1532
+ );
1533
+ else
1534
+ L.push(
1535
+ `- quiet dips (15 LU or more under the median momentary loudness): none ${tag("not detected")}`,
1536
+ );
1537
+
1538
+ L.push("", "## The picture's change against the sound", "");
1539
+ L.push(...formatPictureAgainst(l));
1540
+
1541
+ L.push("", "## Picture events against the sound", "");
1542
+ const e = l.events;
1543
+ if (!e.file)
1544
+ L.push(`- no events file — the page's events were not compared ${tag("not measured")}`);
1545
+ else if (!e.list.length) L.push(`- ${basename(e.file)} lists no events ${tag("not detected")}`);
1546
+ else {
1547
+ const near = e.list.length - e.unvoiced.length;
1548
+ L.push(
1549
+ `- ${near} of ${e.list.length} events have a sound onset within 40 ms; by chance ${Math.round(e.chance40 * 100)}% would (the share of the film within 40 ms of an onset) ${tag("measured")}`,
1550
+ );
1551
+ const kinds = [...new Set(e.list.map((x) => x.kind))];
1552
+ if (kinds.length > 1)
1553
+ for (const k of kinds) {
1554
+ const all = e.list.filter((x) => x.kind === k);
1555
+ const un = e.unvoiced.filter((x) => x.kind === k).length;
1556
+ L.push(` - ${k}: ${all.length - un} of ${all.length} ${tag("measured")}`);
1557
+ }
1558
+ if (e.unvoiced.length)
1559
+ L.push(
1560
+ `- no onset within 40 ms: ${e.unvoiced
1561
+ .map(
1562
+ (x) =>
1563
+ `${fmtS(x.t)} ${x.kind}${x.label ? ` "${x.label}"` : ""} (nearest ${ms(x.nearestOnset)})`,
1564
+ )
1565
+ .join(", ")} ${tag("measured")}`,
1566
+ );
1567
+ }
1568
+ const st = l.stems;
1569
+ if (!st.list.length)
1570
+ L.push(
1571
+ `- how loud each event's sound sits against the music: needs --stems ${tag("not measured")}`,
1572
+ );
1573
+ else if (st.list.length < 2)
1574
+ L.push(
1575
+ `- how loud each event's sound sits against the music: needs two or more stems ${tag("not measured")}`,
1576
+ );
1577
+ else if (!e.list.length)
1578
+ L.push(`- event windows: no events to measure at ${tag("not measured")}`);
1579
+ else {
1580
+ const missing = e.list.length - st.eventWindows.length;
1581
+ const byStem = new Map<string, number[]>();
1582
+ for (const w of st.eventWindows)
1583
+ byStem.set(w.stem, [...(byStem.get(w.stem) ?? []), w.overRestDb]);
1584
+ for (const [name, v] of byStem)
1585
+ L.push(
1586
+ `- events whose sound is in "${name}": ${v.length}; it sits ${fmtDb(median(v))} over the other stems (median; range ${fmtDb(Math.min(...v))} to ${fmtDb(Math.max(...v))}) in the 20 ms before to 150 ms after ${tag("measured")}`,
1587
+ );
1588
+ if (missing)
1589
+ L.push(
1590
+ `- ${missing} event${missing === 1 ? "" : "s"} where no stem rises by 3 dB or more ${tag("measured")}`,
1591
+ );
1592
+ L.push(
1593
+ `- per event: ${st.eventWindows.map((w) => `${fmtS(w.t)} ${w.kind} ${w.stem} ${fmtDb(w.overRestDb)}`).join(", ")} ${tag("measured")}`,
1594
+ );
1595
+ }
1596
+
1597
+ L.push("", "## Cuts against the sound", "");
1598
+ const c = l.cuts;
1599
+ if (!c.list.length)
1600
+ L.push(
1601
+ `- no cuts ${c.how === "not measured" ? "known (no picture, no events file)" : "found"} ${tag(c.how)}`,
1602
+ );
1603
+ else {
1604
+ const offs = c.list.map((x) => x.nearestOnset).filter((d): d is number => d != null);
1605
+ const within = offs.filter((d) => Math.abs(d) <= 0.04).length;
1606
+ L.push(
1607
+ `- ${c.list.length} cuts (${c.source === "events" ? "from the events file" : "read from the picture: scene change ≥ 0.3"}); ${within} within 40 ms of an onset, chance ${Math.round(e.chance40 * 100)}% ${tag("measured")}`,
1608
+ );
1609
+ if (offs.length)
1610
+ L.push(
1611
+ `- offset to the nearest onset (negative = the sound comes first): median ${ms(median(offs))}, median distance ${Math.round(median(offs.map(Math.abs)) * 1000)} ms ${tag("measured")}`,
1612
+ );
1613
+ L.push(
1614
+ `- each: ${c.list.map((x) => `${fmtS(x.t)} ${ms(x.nearestOnset)}`).join(", ")} ${tag("measured")}`,
1615
+ );
1616
+ }
1617
+ if (st.list.length) {
1618
+ L.push("", "## Stems", "");
1619
+ for (const s of st.list)
1620
+ L.push(
1621
+ `- ${s.name}: sounding ${s.activeS}s of ${l.duration.toFixed(1)}s, peak ${s.peakDb} dBFS RMS (50 ms) ${tag("measured")}`,
1622
+ );
1623
+ }
1624
+ const pageCurves = l.curves.names.filter((n) => n !== PICTURE_ENERGY);
1625
+ if (pageCurves.length)
1626
+ L.push("", "## Curves from the page", "", `- ${pageCurves.join(", ")} — drawn in listen.png`);
1627
+ L.push(
1628
+ "",
1629
+ "## What it sounds like",
1630
+ "",
1631
+ `- its instruments, whether it sounds synthesized or recorded, whether the action sounds resemble the product's own: nothing here hears timbre ${tag(l.timbre.how)}`,
1632
+ );
1633
+ if (l.clips.length) L.push("", "## Clips", "", ...l.clips.map((f) => `- ${f}`));
1634
+ if (l.vs) L.push("", ...formatListenVs(l.vs));
1635
+ if (l.credits) {
1636
+ L.push("", "## Credits (as the events file lists them)", "");
1637
+ if (l.credits.length) L.push(...l.credits.map((c) => `- ${c}`));
1638
+ else L.push(`- the "credits" field is empty ${tag("not detected")}`);
1639
+ }
1640
+ return L.join("\n");
1641
+ }
1642
+
1643
+ const fmtDb = (v: number) => `${v >= 0 ? "+" : ""}${v.toFixed(1)} dB`;
1644
+
1645
+ /** the lines of "The picture's change against the sound" */
1646
+ export function formatPictureAgainst(l: Pick<FilmListen, "picture">): string[] {
1647
+ const p = l.picture;
1648
+ const a = p.against;
1649
+ const tag = (h: How) => `(${h})`;
1650
+ const fmtS = (t: number) => `${t.toFixed(1)}s`;
1651
+ if (!p.energy || !a?.top)
1652
+ return [
1653
+ `- the picture's change: no picture and no "${PICTURE_ENERGY}" curve ${tag("not measured")}`,
1654
+ ];
1655
+ const known = p.halves.filter((h) => Number.isFinite(h.energy));
1656
+ const peak = known.reduce((m, h) => (h.energy > m.energy ? h : m), known[0]!);
1657
+ const half = a.binS === 0.5 ? "half-second" : `${a.binS} s piece`;
1658
+ const L = [
1659
+ `- how much the picture changes (mean grey difference from the frame before, 0..1, as \`film probe\` reads it; ${p.source === "events" ? `the events file's "${PICTURE_ENERGY}"` : "read from the picture"}): per ${half}, median ${fmtE(median(known.map((h) => h.energy)))}, most ${fmtE(peak.energy)} at ${fmtS(peak.t)}–${fmtS(peak.t + a.binS)} — drawn under the loudness in listen.png ${tag("measured")}`,
1660
+ `- the ${a.top} loudest ${half}s vs the ${a.top} busiest ${half}s of picture: ${a.shared} shared; loudest at ${a.loudest.map(fmtS).join(", ")}; busiest at ${a.busiest.map(fmtS).join(", ")} ${tag("measured")}`,
1661
+ ];
1662
+ const what = (o: PictureAgainstSound["opposite"][number]) =>
1663
+ o.kind === "busy-quiet"
1664
+ ? `the picture busy (${fmtE(o.energy)}) while the sound is quiet (${o.lufs} LUFS)`
1665
+ : `the picture changing little frame to frame (${fmtE(o.energy)}) while the sound is loud (${o.lufs} LUFS)`;
1666
+ L.push(
1667
+ a.opposite.length
1668
+ ? `- where they run opposite (one above this film's median, the other below, reaching its top and bottom thirds): ${a.opposite.map((o) => `${fmtS(o.from)}–${fmtS(o.to)} ${what(o)}`).join("; ")} ${tag("measured")}`
1669
+ : `- where they run opposite (one above this film's median, the other below, reaching its top and bottom thirds): nowhere ${tag("not detected")}`,
1670
+ );
1671
+ return L;
1672
+ }
1673
+
1674
+ const fmtE = (v: number) => (v >= 0.01 ? v.toFixed(3) : v.toFixed(4));
1675
+
1676
+ // --- the picture -------------------------------------------------------------------------
1677
+
1678
+ const GUTTER = 120;
1679
+ const PAD = 6;
1680
+ const SPEC_H = 280;
1681
+
1682
+ /** `film sheet`'s width for a film of this shape, so the two lie one above the other */
1683
+ function sheetWidth(w?: number, h?: number): number {
1684
+ const landscape = !(w && h) || w >= h;
1685
+ const columns = landscape ? 6 : 10;
1686
+ const tileW = landscape ? 480 : 216;
1687
+ return columns * tileW + (columns + 1) * 6;
1688
+ }
1689
+
1690
+ /** the times `film sheet` shows frames at: every `every` s, and the last frame
1691
+ * when it falls more than half a step after the last of them */
1692
+ function sheetFrameTimes(duration: number, every: number, fps: number): number[] {
1693
+ const last = Math.max(0, duration - 1.5 / fps);
1694
+ const times = Array.from(
1695
+ { length: Math.floor(last / every) + 1 },
1696
+ (_, i) => Math.round(i * every * 1000) / 1000,
1697
+ );
1698
+ if (last - times[times.length - 1]! > every / 2) times.push(Math.round(last * 1000) / 1000);
1699
+ return times;
1700
+ }
1701
+
1702
+ const frameRate = (r?: string) => {
1703
+ const [n, d] = String(r ?? "60/1")
1704
+ .split("/")
1705
+ .map(Number);
1706
+ return n && d ? n / d : 60;
1707
+ };
1708
+
1709
+ /** `film sheet`'s default seconds between frames */
1710
+ const defaultSheetEvery = (duration: number) => Math.max(0.25, Math.round((duration / 48) * 4) / 4);
1711
+
1712
+ const KIND_COLORS = [
1713
+ "#d9480f",
1714
+ "#1971c2",
1715
+ "#2f9e44",
1716
+ "#ae3ec9",
1717
+ "#f08c00",
1718
+ "#0c8599",
1719
+ "#e03131",
1720
+ "#5c7cfa",
1721
+ ];
1722
+
1723
+ async function drawListen(
1724
+ l: FilmListen,
1725
+ o: {
1726
+ chromePath: string;
1727
+ tmp: string;
1728
+ out: string;
1729
+ width: number;
1730
+ plotW: number;
1731
+ env: Float32Array;
1732
+ hopS: number;
1733
+ every: number;
1734
+ fps: number;
1735
+ },
1736
+ ): Promise<void> {
1737
+ const D = l.duration;
1738
+ const W = o.plotW;
1739
+ const x = (t: number) => round1((Math.max(0, Math.min(D, t)) / D) * W);
1740
+ const rows: { label: string; h: number; svg: string }[] = [];
1741
+ const esc = (s: string) => s.replace(/[&<>"]/g, (c) => `&#${c.charCodeAt(0)};`);
1742
+
1743
+ // the sheet's frame times
1744
+ const sheetTimes = sheetFrameTimes(D, o.every, o.fps);
1745
+ const labelEvery = Math.max(1, Math.ceil((sheetTimes.length * 46) / W));
1746
+ rows.push({
1747
+ label: "sheet times",
1748
+ h: 26,
1749
+ svg: sheetTimes
1750
+ .map(
1751
+ (t, i) =>
1752
+ `<line x1="${x(t)}" x2="${x(t)}" y1="${i % labelEvery ? 18 : 12}" y2="26" stroke="#555"/>` +
1753
+ (i % labelEvery
1754
+ ? ""
1755
+ : `<text x="${x(t) + 2}" y="10" class="s">${t < 60 ? `${t.toFixed(t % 1 ? 2 : 0)}s` : `${Math.floor(t / 60)}:${(t % 60).toFixed(1).padStart(4, "0")}`}</text>`),
1756
+ )
1757
+ .join(""),
1758
+ });
1759
+ rows.push({
1760
+ label: "spectrum<br><small>30 Hz–11 kHz, log</small>",
1761
+ h: SPEC_H,
1762
+ svg: `<image href="spectrum.png" x="0" y="0" width="${W}" height="${SPEC_H}" preserveAspectRatio="none"/>`,
1763
+ });
1764
+ // momentary loudness, −60..0 LUFS
1765
+ {
1766
+ const H = 130;
1767
+ const y = (v: number) => round1(H - ((Math.max(-60, Math.min(0, v)) + 60) / 60) * H);
1768
+ const grid = [-10, -20, -30, -40, -50]
1769
+ .map(
1770
+ (v) =>
1771
+ `<line x1="0" x2="${W}" y1="${y(v)}" y2="${y(v)}" stroke="#e5e5e5"/><text x="2" y="${y(v) - 2}" class="s">${v}</text>`,
1772
+ )
1773
+ .join("");
1774
+ const pts = l.loudness.momentary
1775
+ .map((p) => `${x(Math.max(0, p.t - 0.2))},${y(p.lufs)}`)
1776
+ .join(" ");
1777
+ const I = l.loudness.integratedLufs;
1778
+ rows.push({
1779
+ label: `loudness<br><small>momentary LUFS${I != null ? `<br>I ${I}` : ""}</small>`,
1780
+ h: H,
1781
+ svg:
1782
+ grid +
1783
+ (I != null
1784
+ ? `<line x1="0" x2="${W}" y1="${y(I)}" y2="${y(I)}" stroke="#d9480f" stroke-dasharray="6 4"/>`
1785
+ : "") +
1786
+ `<polyline points="${pts}" fill="none" stroke="#222" stroke-width="1.5"/>`,
1787
+ });
1788
+ }
1789
+ // the picture's change: the max of each column, on a square-root scale so
1790
+ // small motion shows (as film probe draws it); behind it, where it runs
1791
+ // opposite to the loudness
1792
+ if (l.picture.energy) {
1793
+ const H = 60;
1794
+ const pe = l.picture.energy;
1795
+ const peak = Math.max(1e-6, ...pe.values.filter(Number.isFinite));
1796
+ const cols = Math.max(1, Math.round(W / 2));
1797
+ let pts = "";
1798
+ for (let c = 0; c < cols; c++) {
1799
+ const a = ((c / cols) * D - pe.t0) / pe.dt;
1800
+ const b = (((c + 1) / cols) * D - pe.t0) / pe.dt;
1801
+ let v = 0;
1802
+ for (let i = Math.max(0, Math.floor(a)); i < Math.min(pe.values.length, Math.ceil(b)); i++)
1803
+ if (Number.isFinite(pe.values[i]!)) v = Math.max(v, pe.values[i]!);
1804
+ pts += `${x(((c + 0.5) / cols) * D)},${round1(H - 2 - Math.sqrt(v / peak) * (H - 6))} `;
1805
+ }
1806
+ const opp = (l.picture.against?.opposite ?? [])
1807
+ .map(
1808
+ (o) =>
1809
+ `<rect x="${x(o.from)}" y="0" width="${Math.max(1, x(o.to) - x(o.from))}" height="${H}" fill="${o.kind === "busy-quiet" ? "#ffd8a8" : "#a5d8ff"}"/>`,
1810
+ )
1811
+ .join("");
1812
+ rows.push({
1813
+ label: `picture<br><small>change/frame, √<br>${l.picture.source === "events" ? "events file" : "read from picture"}</small>`,
1814
+ h: H,
1815
+ svg: `${opp}<polyline points="${pts}" fill="none" stroke="#2b8a3e" stroke-width="1.2"/>`,
1816
+ });
1817
+ }
1818
+ // onset strength, onsets, beat grid
1819
+ {
1820
+ const H = 70;
1821
+ const max = Math.max(1e-6, ...o.env);
1822
+ const step = Math.max(1, Math.floor(o.env.length / (W * 2)));
1823
+ let path = "";
1824
+ for (let f = 0; f < o.env.length; f += step) {
1825
+ let v = 0;
1826
+ for (let k = f; k < Math.min(o.env.length, f + step); k++) v = Math.max(v, o.env[k]!);
1827
+ path += `${x(f * o.hopS + WIN / 2 / LISTEN_RATE)},${round1(H - (v / max) * (H - 14))} `;
1828
+ }
1829
+ const beats = (l.tempo.value?.beats ?? [])
1830
+ .map(
1831
+ (b, i) =>
1832
+ `<line x1="${x(b)}" x2="${x(b)}" y1="0" y2="${i % 4 ? 6 : 12}" stroke="#1971c2"/>`,
1833
+ )
1834
+ .join("");
1835
+ const ticks = l.onsets.times
1836
+ .map((t) => `<line x1="${x(t)}" x2="${x(t)}" y1="${H - 5}" y2="${H}" stroke="#d9480f"/>`)
1837
+ .join("");
1838
+ rows.push({
1839
+ label: `onsets<br><small>${l.tempo.value ? `grid ${l.tempo.value.bpm} BPM` : "no grid"}</small>`,
1840
+ h: H,
1841
+ svg: `<polyline points="${path}" fill="none" stroke="#888"/>${beats}${ticks}`,
1842
+ });
1843
+ }
1844
+ // sections
1845
+ rows.push({
1846
+ label: "sections",
1847
+ h: 26,
1848
+ svg: l.sections.list
1849
+ .map(
1850
+ (s, i) =>
1851
+ `<rect x="${x(s.start)}" y="2" width="${Math.max(1, x(s.end) - x(s.start) - 1)}" height="22" fill="${i % 2 ? "#dbe4ff" : "#fff3bf"}"/><text x="${x(s.start) + 4}" y="17" class="m">${i + 1}</text>`,
1852
+ )
1853
+ .join(""),
1854
+ });
1855
+ // stems
1856
+ for (const s of l.stems.list) {
1857
+ let svg = "";
1858
+ let run: number | null = null;
1859
+ s.lane.forEach((on, i) => {
1860
+ if (on && run == null) run = i;
1861
+ if ((!on || i === s.lane.length - 1) && run != null) {
1862
+ const end = on ? i + 1 : i;
1863
+ svg += `<rect x="${x(run * l.stems.laneS)}" y="3" width="${Math.max(1, x(end * l.stems.laneS) - x(run * l.stems.laneS))}" height="14" fill="#495057"/>`;
1864
+ run = null;
1865
+ }
1866
+ });
1867
+ rows.push({ label: `<small>${esc(s.name)}</small>`, h: 20, svg });
1868
+ }
1869
+ // events by kind, cuts
1870
+ const kinds = [...new Set(l.events.list.map((e) => e.kind))];
1871
+ const color = (k: string) => KIND_COLORS[kinds.indexOf(k) % KIND_COLORS.length]!;
1872
+ if (l.events.list.length) {
1873
+ const H = 18 * Math.max(1, kinds.length);
1874
+ rows.push({
1875
+ label: `events<br><small>${kinds.map((k) => `<span style="color:${color(k)}">${esc(k)}</span>`).join(" ")}</small>`,
1876
+ h: H,
1877
+ svg: l.events.list
1878
+ .map((e) => {
1879
+ const r = kinds.indexOf(e.kind);
1880
+ const miss = e.nearestOnset == null || Math.abs(e.nearestOnset) > 0.04;
1881
+ return `<line x1="${x(e.t)}" x2="${x(e.t)}" y1="${r * 18 + 2}" y2="${r * 18 + 16}" stroke="${color(e.kind)}" stroke-width="${miss ? 1 : 2.5}"${miss ? ' stroke-dasharray="2 2"' : ""}/>`;
1882
+ })
1883
+ .join(""),
1884
+ });
1885
+ }
1886
+ // curves, each scaled to its own range
1887
+ const cv = l.curves;
1888
+ for (const [j, name] of cv.names.entries()) {
1889
+ if (name === PICTURE_ENERGY) continue; // drawn under the loudness
1890
+ const vals = cv.rows.map((r) => r[j]!).filter(Number.isFinite);
1891
+ if (!vals.length) continue;
1892
+ const lo = Math.min(...vals);
1893
+ const hi = Math.max(...vals);
1894
+ const H = 44;
1895
+ const step = Math.max(1, Math.floor(cv.rows.length / (W * 2)));
1896
+ let pts = "";
1897
+ for (let i = 0; i < cv.rows.length; i += step) {
1898
+ const v = cv.rows[i]![j]!;
1899
+ if (!Number.isFinite(v)) continue;
1900
+ pts += `${x(cv.t0 + i * cv.dt)},${round1(H - 3 - ((v - lo) / (hi - lo || 1)) * (H - 6))} `;
1901
+ }
1902
+ rows.push({
1903
+ label: `<small>${esc(name)}<br>${fmtNum(lo)}–${fmtNum(hi)}</small>`,
1904
+ h: H,
1905
+ svg: `<polyline points="${pts}" fill="none" stroke="#7048e8" stroke-width="1.5"/>`,
1906
+ });
1907
+ }
1908
+
1909
+ const gap = 4;
1910
+ let top = PAD;
1911
+ const body = rows
1912
+ .map((r) => {
1913
+ const html = `<div class="row" style="top:${top}px;height:${r.h}px"><div class="lab">${r.label}</div><svg width="${W}" height="${r.h}" style="left:${GUTTER}px">${r.svg}</svg></div>`;
1914
+ top += r.h + gap;
1915
+ return html;
1916
+ })
1917
+ .join("");
1918
+ const height = top + PAD + 18;
1919
+ // cuts and silences across every row
1920
+ const over = `<svg class="over" width="${W}" height="${height - PAD * 2 - 18}" style="left:${GUTTER}px;top:${PAD}px">${l.silences.list
1921
+ .map(
1922
+ (s) =>
1923
+ `<rect x="${x(s.start)}" y="0" width="${Math.max(1, x(s.end) - x(s.start))}" height="100%" fill="#868e96" opacity="0.18"/>`,
1924
+ )
1925
+ .join("")}${l.cuts.list
1926
+ .map(
1927
+ (c) =>
1928
+ `<line x1="${x(c.t)}" x2="${x(c.t)}" y1="0" y2="100%" stroke="#e03131" stroke-width="1" opacity="0.55"/>`,
1929
+ )
1930
+ .join("")}</svg>`;
1931
+ const legend = `<div class="legend" style="top:${top}px">red lines: cuts (${l.cuts.source === "events" ? "events file" : l.cuts.source === "picture" ? "read from the picture" : "none"}) · grey: silence · onsets: orange ticks, beat grid blue (tall = every 4th) · events: solid = an onset within 40 ms, dashed = none${l.picture.against?.opposite.length ? " · picture lane: orange = picture busy while the sound is quiet, light blue = picture changing little frame to frame while the sound is loud" : ""} · ${esc(basename(l.input))} ${l.duration.toFixed(2)}s</div>`;
1932
+ await writeFile(
1933
+ join(o.tmp, "listen.html"),
1934
+ `<!doctype html><meta charset="utf-8"><style>
1935
+ html,body{margin:0;background:#fff}
1936
+ body{position:relative;width:${o.width}px;height:${height}px;font:12px/1.25 ui-monospace,Menlo,monospace;color:#111}
1937
+ .row{position:absolute;left:0;width:${o.width}px}
1938
+ .row svg,.over{position:absolute;top:0}
1939
+ .row svg{background:#fafafa}
1940
+ .over{pointer-events:none}
1941
+ .lab{position:absolute;left:${PAD}px;width:${GUTTER - PAD * 2}px;top:2px;font-weight:600}
1942
+ small{font-weight:400;color:#555}
1943
+ .s{font-size:10px;fill:#333}.m{font-size:12px;font-weight:600;fill:#333}
1944
+ .legend{position:absolute;left:${GUTTER}px;font-size:11px;color:#444}
1945
+ </style>${body}${over}${legend}`,
1946
+ );
1947
+ const browser = await launchHtmlBrowser({
1948
+ chromePath: o.chromePath,
1949
+ url: pathToFileURL(join(o.tmp, "listen.html")).href,
1950
+ width: o.width,
1951
+ height,
1952
+ profilePrefix: "open-take-listen-",
1953
+ });
1954
+ try {
1955
+ // the spectrum decoded, then two frames painted: a screenshot taken sooner
1956
+ // came out with the lower rows still showing tiles of the top ones
1957
+ await browser.evaluate(
1958
+ "new Promise((ok) => { const i = new Image(); i.onload = i.onerror = () => i.decode().catch(() => {}).then(() => requestAnimationFrame(() => requestAnimationFrame(() => ok(0)))); i.src = 'spectrum.png'; })",
1959
+ );
1960
+ await writeFile(o.out, await browser.screenshot({ format: "png" }));
1961
+ } finally {
1962
+ await browser.close();
1963
+ }
1964
+ }
1965
+
1966
+ const fmtNum = (v: number) => (Math.abs(v) >= 100 ? String(Math.round(v)) : String(round2(v)));
1967
+
1968
+ // --- small arithmetic -----------------------------------------------------------------
1969
+
1970
+ function median(xs: readonly number[]): number {
1971
+ if (!xs.length) return 0;
1972
+ const s = [...xs].sort((a, b) => a - b);
1973
+ const m = s.length >> 1;
1974
+ return s.length % 2 ? s[m]! : (s[m - 1]! + s[m]!) / 2;
1975
+ }
1976
+ const round1 = (v: number) => Math.round(v * 10) / 10;
1977
+ const round2 = (v: number) => Math.round(v * 100) / 100;
1978
+ const round3 = (v: number) => Math.round(v * 1000) / 1000;
1979
+ const round5 = (v: number) => Math.round(v * 1e5) / 1e5;