@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,3456 @@
1
+ // `open-take film probe`: a finished film's picture as information the author
2
+ // can read — how much the picture changes each frame, where it holds still,
3
+ // where it cuts and how long each shot runs, how the cut density moves over
4
+ // the film, what each big change of picture carries across (a region that
5
+ // stays or moves on, only the background, nothing), how far each cut sits
6
+ // from the nearest sound onset next to what chance would give, and, when the
7
+ // page declared where its subjects are, when one leaves the frame. Laid out
8
+ // on the same ruler as `film sheet` and `film listen`. Every line says
9
+ // whether it was measured, is an estimate, or was not found. Nothing is
10
+ // graded: no score, no target, no pass line.
11
+ //
12
+ // The picture is read once, as a small grey copy (192 px wide, every frame),
13
+ // and everything is plain arithmetic on it here; the sound's onsets are
14
+ // `film listen`'s.
15
+
16
+ import { spawn } from "node:child_process";
17
+ import { existsSync } from "node:fs";
18
+ import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
19
+ import { tmpdir } from "node:os";
20
+ import { basename, join, resolve } from "node:path";
21
+ import { pathToFileURL } from "node:url";
22
+ import { resolveFfmpeg, resolveFfprobe, runTool } from "../ffmpeg";
23
+ import { launchHtmlBrowser } from "../html/cdp";
24
+ import {
25
+ chanceWithin,
26
+ LISTEN_RATE,
27
+ nearestOffset,
28
+ onsetStrength,
29
+ parseFilmEvents,
30
+ pickOnsets,
31
+ spectrum,
32
+ } from "./listen";
33
+ import { formatMovingMaterial, type MovingMaterial, readMovingMaterial } from "./moving";
34
+ import {
35
+ type Box,
36
+ type FrameText,
37
+ gridCover,
38
+ type PageTextSample,
39
+ PHONE_W,
40
+ readFrameText,
41
+ readPageText,
42
+ } from "./probe-text";
43
+ import {
44
+ componentValueIndex,
45
+ type FilmProvenance,
46
+ findComponentFiles,
47
+ formatProvenance,
48
+ PROVENANCE_PAGE_JS,
49
+ type ProvenanceSample,
50
+ pageDirOf,
51
+ pageSourcesOf,
52
+ readProvenance,
53
+ } from "./provenance";
54
+ import {
55
+ checkSources,
56
+ FILM_TAG,
57
+ type FilmSegment,
58
+ handoffIs,
59
+ hiddenCutTimes,
60
+ liftSpans,
61
+ resolveFilmPage,
62
+ } from "./render";
63
+
64
+ // --- the picture as grey frames --------------------------------------------------------
65
+
66
+ /** every frame of a film as 8-bit grey, `w`×`h`, one after another */
67
+ export type GreyFrames = {
68
+ w: number;
69
+ h: number;
70
+ fps: number;
71
+ count: number;
72
+ data: Uint8Array;
73
+ /** the film time (s) of frame 0 — a stream can start after the sound does */
74
+ t0?: number;
75
+ };
76
+
77
+ /** the film time (s) of frame i */
78
+ export const frameTime = (g: Pick<GreyFrames, "fps" | "t0">, i: number) => (g.t0 ?? 0) + i / g.fps;
79
+
80
+ export const PROBE_W = 192;
81
+ const BLOCK = 8;
82
+ /** a block whose grey varies less than this (std, 0..255) is flat: background */
83
+ const FLAT_STD = 5;
84
+ /** a block whose mean difference is under this (0..255) has not changed */
85
+ const SAME_BLOCK = 8;
86
+
87
+ const frameAt = (g: GreyFrames, i: number) => g.data.subarray(i * g.w * g.h, (i + 1) * g.w * g.h);
88
+
89
+ /** how much the picture changes into each frame: the mean absolute grey
90
+ * difference from the frame before, 0..1 (frame 0 is 0) */
91
+ export function frameEnergy(g: GreyFrames): Float32Array {
92
+ const n = g.w * g.h;
93
+ const e = new Float32Array(g.count);
94
+ for (let i = 1; i < g.count; i++) {
95
+ const a = frameAt(g, i - 1);
96
+ const b = frameAt(g, i);
97
+ let s = 0;
98
+ for (let k = 0; k < n; k++) s += Math.abs(a[k]! - b[k]!);
99
+ e[i] = s / n / 255;
100
+ }
101
+ return e;
102
+ }
103
+
104
+ /** frameEnergy of a film file, read as `film probe` reads it (a PROBE_W-wide
105
+ * grey copy): one value per frame, frame 0's is 0 */
106
+ export async function fileEnergy(
107
+ ffmpeg: string,
108
+ file: string,
109
+ width: number,
110
+ height: number,
111
+ fps: number,
112
+ ): Promise<Float32Array> {
113
+ return frameEnergy(await fileGrey(ffmpeg, file, width, height, fps));
114
+ }
115
+
116
+ /** the film as the probe's small grey copy (PROBE_W wide) */
117
+ export function fileGrey(
118
+ ffmpeg: string,
119
+ file: string,
120
+ width: number,
121
+ height: number,
122
+ fps: number,
123
+ ): Promise<GreyFrames> {
124
+ const gh = Math.max(BLOCK, Math.round((PROBE_W * height) / width / 2) * 2);
125
+ return decodeGrey(ffmpeg, file, PROBE_W, gh, fps);
126
+ }
127
+
128
+ type Blocks = { bx: number; by: number };
129
+ const blocksOf = (g: GreyFrames): Blocks => ({
130
+ bx: Math.floor(g.w / BLOCK),
131
+ by: Math.floor(g.h / BLOCK),
132
+ });
133
+
134
+ /** per block: mean and standard deviation of the grey */
135
+ function blockStats(g: GreyFrames, f: Uint8Array): { mean: Float32Array; std: Float32Array } {
136
+ const { bx, by } = blocksOf(g);
137
+ const mean = new Float32Array(bx * by);
138
+ const std = new Float32Array(bx * by);
139
+ for (let y = 0; y < by; y++)
140
+ for (let x = 0; x < bx; x++) {
141
+ let s = 0;
142
+ let sq = 0;
143
+ for (let r = 0; r < BLOCK; r++) {
144
+ const row = (y * BLOCK + r) * g.w + x * BLOCK;
145
+ for (let c = 0; c < BLOCK; c++) {
146
+ const v = f[row + c]!;
147
+ s += v;
148
+ sq += v * v;
149
+ }
150
+ }
151
+ const m = s / (BLOCK * BLOCK);
152
+ mean[y * bx + x] = m;
153
+ std[y * bx + x] = Math.sqrt(Math.max(0, sq / (BLOCK * BLOCK) - m * m));
154
+ }
155
+ return { mean, std };
156
+ }
157
+
158
+ /** per block: the mean absolute grey difference between two frames (0..255) */
159
+ function blockDiff(g: GreyFrames, a: Uint8Array, b: Uint8Array): Float32Array {
160
+ const { bx, by } = blocksOf(g);
161
+ const d = new Float32Array(bx * by);
162
+ for (let y = 0; y < by; y++)
163
+ for (let x = 0; x < bx; x++) {
164
+ let s = 0;
165
+ for (let r = 0; r < BLOCK; r++) {
166
+ const row = (y * BLOCK + r) * g.w + x * BLOCK;
167
+ for (let c = 0; c < BLOCK; c++) s += Math.abs(a[row + c]! - b[row + c]!);
168
+ }
169
+ d[y * bx + x] = s / (BLOCK * BLOCK);
170
+ }
171
+ return d;
172
+ }
173
+
174
+ /** the share of blocks that changed between two frames */
175
+ function changedShare(g: GreyFrames, a: Uint8Array, b: Uint8Array, over = 12): number {
176
+ const d = blockDiff(g, a, b);
177
+ let n = 0;
178
+ for (const v of d) if (v > over) n++;
179
+ return n / d.length;
180
+ }
181
+
182
+ // --- cuts, stills -----------------------------------------------------------------------
183
+
184
+ /** frame indices where the picture jumps in one frame: a frame whose change
185
+ * stands far over the change around it (2.5× the second-largest of the four
186
+ * frames on each side, so a one-frame flash still shows as its two cuts) and
187
+ * that changes a fair share of the picture (≥ 12 % of its blocks) */
188
+ export function findCuts(g: GreyFrames, energy: Float32Array): number[] {
189
+ const out: number[] = [];
190
+ for (let i = 1; i < g.count; i++) {
191
+ const e = energy[i]!;
192
+ if (e < 0.01) continue;
193
+ const near: number[] = [];
194
+ for (let k = i - 4; k <= i + 4; k++)
195
+ if (k !== i && k >= 1 && k < g.count) near.push(energy[k]!);
196
+ near.sort((a, b) => b - a);
197
+ const ref = near[1] ?? 0;
198
+ if (e < 2.5 * ref) continue;
199
+ if (changedShare(g, frameAt(g, i - 1), frameAt(g, i)) < 0.12) continue;
200
+ out.push(i);
201
+ }
202
+ return out;
203
+ }
204
+
205
+ /** one-frame jumps too small for a cut: a frame whose change stands as far
206
+ * over the change around it as a cut's does, but that changes only 2–12 % of
207
+ * the frame's blocks — a word, a number or a panel swapped inside a picture
208
+ * that holds. `cuts` are left out. */
209
+ export function findSmallSwaps(
210
+ g: GreyFrames,
211
+ energy: Float32Array,
212
+ cuts: readonly number[],
213
+ ): { frame: number; changed: number }[] {
214
+ const out: { frame: number; changed: number }[] = [];
215
+ const isCut = new Set(cuts);
216
+ for (let i = 1; i < g.count; i++) {
217
+ if (isCut.has(i)) continue;
218
+ const e = energy[i]!;
219
+ if (e < 0.002) continue;
220
+ const near: number[] = [];
221
+ for (let k = i - 4; k <= i + 4; k++)
222
+ if (k !== i && k >= 1 && k < g.count) near.push(energy[k]!);
223
+ near.sort((a, b) => b - a);
224
+ if (e < 2.5 * (near[1] ?? 0)) continue;
225
+ const share = changedShare(g, frameAt(g, i - 1), frameAt(g, i));
226
+ if (share < 0.02 || share >= 0.12) continue;
227
+ out.push({ frame: i, changed: share });
228
+ }
229
+ return out;
230
+ }
231
+
232
+ export type JumpMove = {
233
+ /** share of the frame's blocks the jump changes */
234
+ changed: number;
235
+ /** the changed blocks with texture, and of them those found again nearby
236
+ * in the next frame, moved the same way together */
237
+ textured: number;
238
+ moved: number;
239
+ /** where the moved blocks went (median, grey px, to a fraction of one);
240
+ * null: nothing that changed was found moved — swapped where it stood */
241
+ shift: { x: number; y: number } | null;
242
+ };
243
+
244
+ /** what a one-frame jump into frame `i` did to the content: each textured
245
+ * block of the frame before that the jump changed, looked for within
246
+ * `radius` grey px in frame `i` (a close match for its own contrast), its
247
+ * offset refined to a fraction of a pixel. A card that jumps is found moved
248
+ * by how far it went; a word or a picture swapped in place is not found.
249
+ * Estimated on the grey copy: one grey px is the film's width / `g.w`. */
250
+ export function jumpMove(g: GreyFrames, i: number, radius = 16): JumpMove {
251
+ const a = frameAt(g, i - 1);
252
+ const b = frameAt(g, i);
253
+ const { bx, by } = blocksOf(g);
254
+ const d = blockDiff(g, a, b);
255
+ const st = blockStats(g, a);
256
+ const N = BLOCK * BLOCK;
257
+ const sad = (x: number, y: number, nx: number, ny: number) => {
258
+ if (nx < 0 || ny < 0 || nx + BLOCK > g.w || ny + BLOCK > g.h) return Number.NaN;
259
+ let s = 0;
260
+ for (let r = 0; r < BLOCK; r++)
261
+ for (let c = 0; c < BLOCK; c++)
262
+ s += Math.abs(a[(y + r) * g.w + x + c]! - b[(ny + r) * g.w + nx + c]!);
263
+ return s;
264
+ };
265
+ // the minimum of a parabola through three costs, as an offset from the middle
266
+ const vertex = (l: number, m: number, r: number) => {
267
+ const den = l - 2 * m + r;
268
+ return Number.isFinite(den) && den > 0 ? Math.max(-0.5, Math.min(0.5, (l - r) / (2 * den))) : 0;
269
+ };
270
+ let changed = 0;
271
+ let textured = 0;
272
+ const xs: number[] = [];
273
+ const ys: number[] = [];
274
+ for (let k = 0; k < bx * by; k++) {
275
+ if (d[k]! <= 12) continue;
276
+ changed++;
277
+ if (st.std[k]! < FLAT_STD) continue;
278
+ textured++;
279
+ const x = (k % bx) * BLOCK;
280
+ const y = Math.floor(k / bx) * BLOCK;
281
+ const m = searchBlock(g, a, b, x, y, [[0, 0]], radius);
282
+ if (m.x === x && m.y === y) continue;
283
+ if (m.best / N > Math.min(14, 0.35 * st.std[k]!)) continue;
284
+ if (patchStd(g, b, m.x, m.y) < FLAT_STD) continue;
285
+ xs.push(m.x - x + vertex(sad(x, y, m.x - 1, m.y), m.best, sad(x, y, m.x + 1, m.y)));
286
+ ys.push(m.y - y + vertex(sad(x, y, m.x, m.y - 1), m.best, sad(x, y, m.x, m.y + 1)));
287
+ }
288
+ const n = bx * by;
289
+ // a move is the changed blocks going one way together: those within 1.5 px
290
+ // of where most went, a sixth of what changed at least (stray matches
291
+ // in a swap scatter; a line of text can also match a glyph or two along)
292
+ const mx = median(xs);
293
+ const my = median(ys);
294
+ const together = xs.filter((x, k) => Math.hypot(x - mx, ys[k]! - my) <= 1.5).length;
295
+ const isMove = together >= 3 && together >= 0.15 * textured;
296
+ return {
297
+ changed: changed / n,
298
+ textured: textured / n,
299
+ moved: (isMove ? together : 0) / n,
300
+ shift: isMove ? { x: mx, y: my } : null,
301
+ };
302
+ }
303
+
304
+ /** stretches where the picture does not change (every frame's change under
305
+ * `under`, 0..1) for at least `minS` seconds, as frame ranges [a, b). With
306
+ * the frames themselves (`g`), a frame is still only when it is also within
307
+ * 2·`under` of the frame a quarter second before it: a push or a drift too
308
+ * slow to change one frame over the line adds up over a quarter second,
309
+ * where a held picture's encoder noise does not. */
310
+ export function findStills(
311
+ energy: Float32Array,
312
+ fps: number,
313
+ minS = 0.5,
314
+ under = 0.0015,
315
+ g?: GreyFrames,
316
+ ): { a: number; b: number }[] {
317
+ const out: { a: number; b: number }[] = [];
318
+ const lag = Math.max(1, Math.round(fps / 4));
319
+ const n = g ? g.w * g.h : 0;
320
+ const lagged = (i: number) => {
321
+ if (!g || i >= g.count) return true;
322
+ const x = frameAt(g, Math.max(0, i - lag));
323
+ const y = frameAt(g, i);
324
+ let s = 0;
325
+ for (let k = 0; k < n; k++) s += Math.abs(x[k]! - y[k]!);
326
+ return s / n / 255 < 2 * under;
327
+ };
328
+ let a: number | null = null;
329
+ for (let i = 1; i <= energy.length; i++) {
330
+ const still = i < energy.length && energy[i]! < under && lagged(i);
331
+ if (still && a == null) a = i - 1;
332
+ else if (!still && a != null) {
333
+ if ((i - a) / fps >= minS) out.push({ a, b: i });
334
+ a = null;
335
+ }
336
+ }
337
+ return out;
338
+ }
339
+
340
+ /** a handoff that names one of kit/seams.js's kinds, or a name it goes by
341
+ * (its KINDS and ALIASES; a test holds the two lists together) */
342
+ export const SEAM_KINDS =
343
+ /^(curve|whip|depth|inverse|push|dip|cut|pushcut|dipcut|cut on the curve|whip[ -]pan|into the lens|hard cut)$/i;
344
+
345
+ /** at each hard cut, whether each side moves in the `around` s next to it
346
+ * (the mean change a frame over the shot's own frames, against `under`)
347
+ * and what crosses it — so a cut where nothing moves and nothing is
348
+ * carried can be named. `declared` gives each cut the label the page
349
+ * declared it with (kit/seams.js labels its own "seam: <kind>"), when one
350
+ * was declared within `tol` s. */
351
+ export function seamsAtCuts(
352
+ cuts: readonly { frame: number; t: number; across: CarryKind }[],
353
+ energy: Float32Array,
354
+ fps: number,
355
+ declared: readonly { t: number; label: string }[] = [],
356
+ { around = 0.15, under = 0.0015, tol = 1.5 / fps } = {},
357
+ ): SeamSeen[] {
358
+ const k = Math.max(1, Math.round(around * fps));
359
+ const mean = (a: number, b: number) => {
360
+ let s = 0;
361
+ let n = 0;
362
+ for (let i = Math.max(1, a); i <= Math.min(energy.length - 1, b); i++) {
363
+ s += energy[i]!;
364
+ n++;
365
+ }
366
+ return n ? s / n : 0;
367
+ };
368
+ return cuts.map((c) => {
369
+ // energy[i] is the change from frame i − 1 to i: the outgoing shot's own
370
+ // frames are c − k … c − 1, the incoming's c … c + k
371
+ const before = mean(c.frame - k + 1, c.frame - 1) >= under ? "moving" : "still";
372
+ const after = mean(c.frame + 1, c.frame + k) >= under ? "moving" : "still";
373
+ const d = declared
374
+ .filter((x) => Math.abs(x.t - c.t) <= tol)
375
+ .sort((p, q) => Math.abs(p.t - c.t) - Math.abs(q.t - c.t))[0];
376
+ return {
377
+ t: round3(c.t),
378
+ before,
379
+ after,
380
+ across: c.across,
381
+ declared: d ? d.label : null,
382
+ nothing: before === "still" && after === "still" && c.across === "nothing carried",
383
+ };
384
+ });
385
+ }
386
+
387
+ export type SeamSeen = {
388
+ t: number;
389
+ /** the outgoing shot in its last 0.15 s, the incoming in its first */
390
+ before: "moving" | "still";
391
+ after: "moving" | "still";
392
+ across: CarryKind;
393
+ /** the label of the cut the page declared there, if it declared one */
394
+ declared: string | null;
395
+ /** neither side moves and nothing crosses */
396
+ nothing: boolean;
397
+ };
398
+
399
+ /** cuts per bin of `binS` seconds over the film */
400
+ export function cutDensity(cuts: readonly number[], duration: number, binS = 5): number[] {
401
+ const bins = new Array<number>(Math.max(1, Math.ceil(duration / binS - 1e-9))).fill(0);
402
+ for (const t of cuts) bins[Math.min(bins.length - 1, Math.floor(t / binS))]!++;
403
+ return bins;
404
+ }
405
+
406
+ // --- big changes of picture and what they carry across ----------------------------------
407
+
408
+ export type CarryKind = "carried" | "background only" | "nothing carried";
409
+ export type ChangeKind = "hard cut" | CarryKind;
410
+
411
+ export type PictureChange = {
412
+ /** the frame the new picture is complete at (a cut: its first frame) */
413
+ frame: number;
414
+ t: number;
415
+ kind: ChangeKind;
416
+ /** what crosses the change, cut or not */
417
+ across: CarryKind;
418
+ /** the frames compared: the last before the change, the first after it */
419
+ before: number;
420
+ after: number;
421
+ /** share of the frame's blocks that changed between before and after */
422
+ changed: number;
423
+ /** share of the frame (blocks) with texture that stays in place */
424
+ stays: number;
425
+ /** share of the frame with texture that is followed from before to after,
426
+ * in place or moving (each step a small search; a cut: one wider search) */
427
+ carried: number;
428
+ /** share of the frame that is flat in both and keeps its grey: background */
429
+ background: number;
430
+ /** where the carried blocks went on average, in % of the frame's width/height */
431
+ shift: { x: number; y: number } | null;
432
+ };
433
+
434
+ /** what this tool calls a cut to a new picture: half the frame changes */
435
+ const NEW_PICTURE = 0.5;
436
+ /** what this tool calls a large carried region: a tenth of the frame */
437
+ const CARRIED_SHARE = 0.1;
438
+ /** what it calls a kept background: a quarter of the frame */
439
+ const BACKGROUND_SHARE = 0.25;
440
+
441
+ /** the grey's standard deviation in the block at (x, y) */
442
+ function patchStd(g: GreyFrames, f: Uint8Array, x: number, y: number): number {
443
+ let s = 0;
444
+ let sq = 0;
445
+ for (let r = 0; r < BLOCK; r++)
446
+ for (let c = 0; c < BLOCK; c++) {
447
+ const v = f[(y + r) * g.w + x + c]!;
448
+ s += v;
449
+ sq += v * v;
450
+ }
451
+ const m = s / (BLOCK * BLOCK);
452
+ return Math.sqrt(Math.max(0, sq / (BLOCK * BLOCK) - m * m));
453
+ }
454
+
455
+ /** the frame shrunk by `f` in each direction (box average) */
456
+ function shrink(
457
+ g: GreyFrames,
458
+ fr: Uint8Array,
459
+ f: number,
460
+ ): { w: number; h: number; px: Float32Array } {
461
+ const w = Math.floor(g.w / f);
462
+ const h = Math.floor(g.h / f);
463
+ const px = new Float32Array(w * h);
464
+ for (let y = 0; y < h; y++)
465
+ for (let x = 0; x < w; x++) {
466
+ let s = 0;
467
+ for (let r = 0; r < f; r++)
468
+ for (let c = 0; c < f; c++) s += fr[(y * f + r) * g.w + x * f + c]!;
469
+ px[y * w + x] = s / (f * f);
470
+ }
471
+ return { w, h, px };
472
+ }
473
+
474
+ /** how the whole picture moved from frame `a` to frame `b`: a scale about the
475
+ * frame's centre and a shift (px of the grey copy), p' = c + s·(p − c) + t,
476
+ * searched on a quarter-size copy (scales 0.88–1.13, shifts up to a quarter
477
+ * of the width, around `around` when given); a still picture, or two that
478
+ * no motion lays together (fitting under 70 % of the difference left with
479
+ * none), is { s: 1, x: 0, y: 0 } */
480
+ export function globalMotion(
481
+ g: GreyFrames,
482
+ a: Uint8Array,
483
+ b: Uint8Array,
484
+ around: { x: number; y: number } = { x: 0, y: 0 },
485
+ ): { s: number; x: number; y: number } {
486
+ const F = 4;
487
+ const A = shrink(g, a, F);
488
+ const B = shrink(g, b, F);
489
+ const R = Math.max(2, Math.round(A.w / 4));
490
+ const cx = A.w / 2;
491
+ const cy = A.h / 2;
492
+ let best = Number.POSITIVE_INFINITY;
493
+ let out = { s: 1, x: 0, y: 0 };
494
+ const minN = A.w * A.h * 0.35;
495
+ let still = 0;
496
+ for (let k = 0; k < A.px.length; k++) still += Math.abs(A.px[k]! - B.px[k]!);
497
+ still /= A.px.length;
498
+ const ox = Math.round(around.x / F);
499
+ const oy = Math.round(around.y / F);
500
+ for (const sc of [1, 0.96, 1.04, 0.92, 1.08, 0.88, 1.13]) {
501
+ for (let dy = oy - R; dy <= oy + R; dy++)
502
+ for (let dx = ox - R; dx <= ox + R; dx++) {
503
+ let sum = 0;
504
+ let n = 0;
505
+ for (let y = 0; y < A.h; y++) {
506
+ const yb = Math.round(cy + sc * (y + 0.5 - cy) + dy - 0.5);
507
+ if (yb < 0 || yb >= B.h) continue;
508
+ for (let x = 0; x < A.w; x++) {
509
+ const xb = Math.round(cx + sc * (x + 0.5 - cx) + dx - 0.5);
510
+ if (xb < 0 || xb >= B.w) continue;
511
+ sum += Math.abs(A.px[y * A.w + x]! - B.px[yb * B.w + xb]!);
512
+ n++;
513
+ }
514
+ }
515
+ if (n < minN) continue;
516
+ // a small preference for no motion, so a still picture reads still
517
+ const v = sum / n + 0.02 * (Math.abs(dx) + Math.abs(dy)) + 2 * Math.abs(sc - 1);
518
+ if (v < best) {
519
+ best = v;
520
+ out = { s: sc, x: dx * F, y: dy * F };
521
+ }
522
+ }
523
+ }
524
+ // a motion that lays the frames together no better than none is no motion:
525
+ // two unrelated pictures always have some best fit
526
+ return best <= 0.7 * still ? out : { s: 1, x: 0, y: 0 };
527
+ }
528
+
529
+ /** the best place in `next` for the block at (x, y) of `prev`: searched
530
+ * `r` around each of `centres` (offsets from (x, y)); the summed absolute
531
+ * difference there */
532
+ function searchBlock(
533
+ g: GreyFrames,
534
+ prev: Uint8Array,
535
+ next: Uint8Array,
536
+ x: number,
537
+ y: number,
538
+ centres: readonly (readonly [number, number])[],
539
+ r: number,
540
+ ): { best: number; x: number; y: number } {
541
+ let best = Number.POSITIVE_INFINITY;
542
+ let bxp = x;
543
+ let byp = y;
544
+ for (const [cx, cy] of centres)
545
+ for (let dy = cy - r; dy <= cy + r; dy++) {
546
+ const ny = y + dy;
547
+ if (ny < 0 || ny + BLOCK > g.h) continue;
548
+ for (let dx = cx - r; dx <= cx + r; dx++) {
549
+ const nx = x + dx;
550
+ if (nx < 0 || nx + BLOCK > g.w) continue;
551
+ let s = 0;
552
+ for (let rr = 0; rr < BLOCK && s < best; rr++) {
553
+ const pa = (y + rr) * g.w + x;
554
+ const pb = (ny + rr) * g.w + nx;
555
+ for (let c = 0; c < BLOCK; c++) s += Math.abs(prev[pa + c]! - next[pb + c]!);
556
+ }
557
+ if (s < best) {
558
+ best = s;
559
+ bxp = nx;
560
+ byp = ny;
561
+ }
562
+ }
563
+ }
564
+ return { best, x: bxp, y: byp };
565
+ }
566
+
567
+ /** where a motion p' = c + s·(p − c) + t takes the block at (x, y), as an
568
+ * offset from (x, y) */
569
+ function motionOffset(
570
+ g: GreyFrames,
571
+ m: { s: number; x: number; y: number },
572
+ x: number,
573
+ y: number,
574
+ ): [number, number] {
575
+ const gcx = g.w / 2;
576
+ const gcy = g.h / 2;
577
+ const px = gcx + m.s * (x + BLOCK / 2 - gcx) + m.x - BLOCK / 2;
578
+ const py = gcy + m.s * (y + BLOCK / 2 - gcy) + m.y - BLOCK / 2;
579
+ return [Math.round(px - x), Math.round(py - y)];
580
+ }
581
+
582
+ /** follow the textured blocks of frame `a` to `b` two ways, and count a block
583
+ * followed by either: frame by frame (each step a small search around where
584
+ * the block was and around where the whole picture moved, so a fast pan is
585
+ * followed; the template renewed each step, so a zoom or turn is followed),
586
+ * and in one search from `a` straight to `b` around where the picture's
587
+ * summed motion takes it (so a pan whose middle frames are blurred past
588
+ * matching is still followed between its sharp ends). Returns the share of
589
+ * the frame followed to `b` with texture, and the mean shift. With a == b-1
590
+ * (a cut) it is one search of `radius` around the block's place and the
591
+ * picture's shift. */
592
+ export function follow(
593
+ g: GreyFrames,
594
+ a: number,
595
+ b: number,
596
+ radius: number,
597
+ ): { share: number; shift: { x: number; y: number } | null } {
598
+ const { bx, by } = blocksOf(g);
599
+ const st = blockStats(g, frameAt(g, a));
600
+ const step = Math.max(1, Math.round(g.fps / 30));
601
+ const frames: number[] = [];
602
+ for (let j = a + step; j < b; j += step) frames.push(j);
603
+ frames.push(b);
604
+ const N = BLOCK * BLOCK;
605
+ // the picture's motion at each step, and summed over all of them
606
+ const shifts: { s: number; x: number; y: number }[] = [];
607
+ let total = { s: 1, x: 0, y: 0 };
608
+ {
609
+ let prev = a;
610
+ for (const j of frames) {
611
+ const m = globalMotion(g, frameAt(g, prev), frameAt(g, j));
612
+ shifts.push(m);
613
+ total = { s: m.s * total.s, x: m.s * total.x + m.x, y: m.s * total.y + m.y };
614
+ prev = j;
615
+ }
616
+ }
617
+ const r = frames.length === 1 ? radius : 4;
618
+ // the steps miss what they could not read (a blurred or ghosted frame
619
+ // reads as no motion): the motion from a straight to b, searched around
620
+ // their sum, or the sum itself when nothing lays the two ends together
621
+ if (frames.length > 1) {
622
+ const direct = globalMotion(g, frameAt(g, a), frameAt(g, b), total);
623
+ if (direct.s !== 1 || direct.x || direct.y) total = direct;
624
+ }
625
+ const rDirect = Math.min(12, Math.max(4, Math.round(0.1 * Math.hypot(total.x, total.y))));
626
+ const close = (best: number, sd: number) => sd >= FLAT_STD && best / N <= Math.min(14, 0.35 * sd);
627
+ const fa = frameAt(g, a);
628
+ const fb = frameAt(g, b);
629
+ let kept = 0;
630
+ let sx = 0;
631
+ let sy = 0;
632
+ for (let k = 0; k < bx * by; k++) {
633
+ if (st.std[k]! < FLAT_STD) continue;
634
+ const x0 = (k % bx) * BLOCK;
635
+ const y0 = Math.floor(k / bx) * BLOCK;
636
+ let x = x0;
637
+ let y = y0;
638
+ let prev = fa;
639
+ let alive = true;
640
+ for (const [si, j] of frames.entries()) {
641
+ const next = frameAt(g, j);
642
+ const [mx, my] = motionOffset(g, shifts[si]!, x, y);
643
+ const centres: [number, number][] =
644
+ mx || my
645
+ ? [
646
+ [0, 0],
647
+ [mx, my],
648
+ ]
649
+ : [[0, 0]];
650
+ const m = searchBlock(g, prev, next, x, y, centres, r);
651
+ // a match is a close one for this patch's own contrast, so smooth
652
+ // ground does not pass for the same thing
653
+ if (!close(m.best, patchStd(g, prev, x, y))) {
654
+ alive = false;
655
+ break;
656
+ }
657
+ x = m.x;
658
+ y = m.y;
659
+ prev = next;
660
+ }
661
+ // still texture where it ended, not a match on flat ground
662
+ if (!alive || patchStd(g, fb, x, y) < FLAT_STD) {
663
+ alive = false;
664
+ if (frames.length > 1) {
665
+ const [mx, my] = motionOffset(g, total, x0, y0);
666
+ const m = searchBlock(g, fa, fb, x0, y0, [[mx, my]], rDirect);
667
+ if (close(m.best, st.std[k]!) && patchStd(g, fb, m.x, m.y) >= FLAT_STD) {
668
+ alive = true;
669
+ x = m.x;
670
+ y = m.y;
671
+ }
672
+ }
673
+ }
674
+ if (!alive) continue;
675
+ kept++;
676
+ sx += x - x0;
677
+ sy += y - y0;
678
+ }
679
+ return {
680
+ share: kept / (bx * by),
681
+ shift: kept ? { x: (sx / kept / g.w) * 100, y: (sy / kept / g.h) * 100 } : null,
682
+ };
683
+ }
684
+
685
+ function compare(g: GreyFrames, a: number, b: number, cut: boolean) {
686
+ const fa = frameAt(g, a);
687
+ const fb = frameAt(g, b);
688
+ const sa = blockStats(g, fa);
689
+ const sb = blockStats(g, fb);
690
+ const d = blockDiff(g, fa, fb);
691
+ let changed = 0;
692
+ let stays = 0;
693
+ let background = 0;
694
+ for (let k = 0; k < d.length; k++) {
695
+ if (d[k]! > 12) changed++;
696
+ if (sa.std[k]! >= FLAT_STD && d[k]! < SAME_BLOCK) stays++;
697
+ if (
698
+ sa.std[k]! < FLAT_STD &&
699
+ sb.std[k]! < FLAT_STD &&
700
+ Math.abs(sa.mean[k]! - sb.mean[k]!) < SAME_BLOCK
701
+ )
702
+ background++;
703
+ }
704
+ const n = d.length;
705
+ // across a cut there is no motion to follow: one search a little wider
706
+ const f = follow(g, a, b, cut ? 6 : 4);
707
+ const carried = Math.max(f.share, stays / n);
708
+ const across: CarryKind =
709
+ carried >= CARRIED_SHARE
710
+ ? "carried"
711
+ : background / n >= BACKGROUND_SHARE
712
+ ? "background only"
713
+ : "nothing carried";
714
+ return {
715
+ changed: changed / n,
716
+ stays: stays / n,
717
+ carried,
718
+ background: background / n,
719
+ shift: f.shift,
720
+ across,
721
+ };
722
+ }
723
+
724
+ /** the big changes of picture: every cut, and every moment where at least
725
+ * 40 % of the frame's blocks differ between a quarter second before and a
726
+ * quarter second after (the local peak, at least half a second from the next
727
+ * one); each compared before/after for what it carries across */
728
+ export function findChanges(
729
+ g: GreyFrames,
730
+ energy: Float32Array,
731
+ cuts: readonly number[],
732
+ ): PictureChange[] {
733
+ const k = Math.max(1, Math.round(g.fps * 0.25));
734
+ const C = new Float32Array(g.count);
735
+ for (let i = k; i + k < g.count; i++)
736
+ C[i] = changedShare(g, frameAt(g, i - k), frameAt(g, i + k));
737
+ const sep = Math.round(g.fps * 0.5);
738
+ const peaks: number[] = [];
739
+ for (let i = k; i + k < g.count; i++) {
740
+ if (C[i]! < 0.4) continue;
741
+ let top = true;
742
+ for (let j = Math.max(0, i - sep); j <= Math.min(g.count - 1, i + sep) && top; j++)
743
+ if (C[j]! > C[i]! || (C[j] === C[i] && j < i)) top = false;
744
+ if (top) peaks.push(i);
745
+ }
746
+ const out: PictureChange[] = [];
747
+ for (const c of cuts) {
748
+ const r = compare(g, c - 1, c, true);
749
+ out.push({
750
+ frame: c,
751
+ t: frameTime(g, c),
752
+ kind: "hard cut",
753
+ before: c - 1,
754
+ after: c,
755
+ ...r,
756
+ });
757
+ }
758
+ const moving = 0.003;
759
+ const maxSpan = Math.round(g.fps * 0.75);
760
+ for (const p of peaks) {
761
+ // a cut inside this window is this change
762
+ if (cuts.some((c) => Math.abs(c - p) <= k + 1)) continue;
763
+ let a = p - k;
764
+ while (a > 1 && p - a < maxSpan && energy[a]! >= moving) a--;
765
+ let b = p + k;
766
+ while (b < g.count - 1 && b - p < maxSpan && energy[b + 1]! >= moving) b++;
767
+ a = Math.max(0, a);
768
+ // the window can start before the motion and end after it: the change
769
+ // runs from the last frame before the picture moves to the first after
770
+ while (b - 1 > a && energy[b]! < moving) b--;
771
+ while (a + 1 < b && energy[a + 1]! < moving) a++;
772
+ const r = compare(g, a, b, false);
773
+ out.push({ frame: b, t: frameTime(g, b), kind: r.across, before: a, after: b, ...r });
774
+ }
775
+ return out.sort((x, y) => x.frame - y.frame);
776
+ }
777
+
778
+ // --- the whole picture's scale and shift over time ----------------------------------------
779
+
780
+ /** the picture's motion from one read frame to the next: a scale about the
781
+ * frame's centre and a shift, fitted by gradient steps (sub-pixel) on the
782
+ * grey copy, coarse to fine; pixels that move otherwise (a caption fading,
783
+ * a cursor) are left out of the fit after its first step */
784
+ function fitSimilarity(
785
+ A: Float32Array,
786
+ B: Float32Array,
787
+ w: number,
788
+ h: number,
789
+ init: { s: number; x: number; y: number },
790
+ ): { s: number; x: number; y: number; res: number } {
791
+ const cx = w / 2;
792
+ const cy = h / 2;
793
+ const gx = new Float32Array(w * h);
794
+ const gy = new Float32Array(w * h);
795
+ for (let y = 1; y < h - 1; y++)
796
+ for (let x = 1; x < w - 1; x++) {
797
+ const k = y * w + x;
798
+ gx[k] = (A[k + 1]! - A[k - 1]!) / 2;
799
+ gy[k] = (A[k + w]! - A[k - w]!) / 2;
800
+ }
801
+ let { s, x: tx, y: ty } = init;
802
+ let res = Number.POSITIVE_INFINITY;
803
+ let thr = Number.POSITIVE_INFINITY;
804
+ for (let it = 0; it < 12; it++) {
805
+ let h00 = 0;
806
+ let h01 = 0;
807
+ let h02 = 0;
808
+ let h11 = 0;
809
+ let h12 = 0;
810
+ let h22 = 0;
811
+ let b0 = 0;
812
+ let b1 = 0;
813
+ let b2 = 0;
814
+ let sumAbs = 0;
815
+ let n = 0;
816
+ const absR: number[] = [];
817
+ for (let y = 1; y < h - 1; y++)
818
+ for (let x = 1; x < w - 1; x++) {
819
+ const qx = cx + s * (x - cx) + tx;
820
+ const qy = cy + s * (y - cy) + ty;
821
+ if (qx < 0 || qy < 0 || qx >= w - 1 || qy >= h - 1) continue;
822
+ const x0 = Math.floor(qx);
823
+ const y0 = Math.floor(qy);
824
+ const fx = qx - x0;
825
+ const fy = qy - y0;
826
+ const k0 = y0 * w + x0;
827
+ const bv =
828
+ B[k0]! * (1 - fx) * (1 - fy) +
829
+ B[k0 + 1]! * fx * (1 - fy) +
830
+ B[k0 + w]! * (1 - fx) * fy +
831
+ B[k0 + w + 1]! * fx * fy;
832
+ const k = y * w + x;
833
+ const r = bv - A[k]!;
834
+ const ar = Math.abs(r);
835
+ if ((it & 3) === 0) absR.push(ar);
836
+ if (ar > thr) continue;
837
+ sumAbs += ar;
838
+ n++;
839
+ const j0 = gx[k]! * (x - cx) + gy[k]! * (y - cy);
840
+ const j1 = gx[k]!;
841
+ const j2 = gy[k]!;
842
+ h00 += j0 * j0;
843
+ h01 += j0 * j1;
844
+ h02 += j0 * j2;
845
+ h11 += j1 * j1;
846
+ h12 += j1 * j2;
847
+ h22 += j2 * j2;
848
+ b0 += j0 * r;
849
+ b1 += j1 * r;
850
+ b2 += j2 * r;
851
+ }
852
+ if (n < 0.2 * w * h) return { s, x: tx, y: ty, res: Number.POSITIVE_INFINITY };
853
+ res = sumAbs / n;
854
+ if (absR.length) {
855
+ absR.sort((a, b) => a - b);
856
+ thr = Math.max(6, 3 * absR[absR.length >> 1]!);
857
+ }
858
+ // solve the 3×3 normal equations
859
+ const det =
860
+ h00 * (h11 * h22 - h12 * h12) - h01 * (h01 * h22 - h12 * h02) + h02 * (h01 * h12 - h11 * h02);
861
+ if (!(Math.abs(det) > 1e-9)) break;
862
+ const i00 = (h11 * h22 - h12 * h12) / det;
863
+ const i01 = (h02 * h12 - h01 * h22) / det;
864
+ const i02 = (h01 * h12 - h02 * h11) / det;
865
+ const i11 = (h00 * h22 - h02 * h02) / det;
866
+ const i12 = (h01 * h02 - h00 * h12) / det;
867
+ const i22 = (h00 * h11 - h01 * h01) / det;
868
+ const ds = i00 * b0 + i01 * b1 + i02 * b2;
869
+ const dx = i01 * b0 + i11 * b1 + i12 * b2;
870
+ const dy = i02 * b0 + i12 * b1 + i22 * b2;
871
+ // the step is taken on A's side: compose with its inverse
872
+ const sd = 1 + ds;
873
+ if (!(sd > 0.5)) break;
874
+ s /= sd;
875
+ tx -= s * dx;
876
+ ty -= s * dy;
877
+ if (Math.abs(ds) < 1e-5 && Math.abs(dx) < 0.003 && Math.abs(dy) < 0.003) break;
878
+ }
879
+ return { s, x: tx, y: ty, res };
880
+ }
881
+
882
+ const halve = (A: Float32Array, w: number, h: number) => {
883
+ const W2 = Math.floor(w / 2);
884
+ const H2 = Math.floor(h / 2);
885
+ const o = new Float32Array(W2 * H2);
886
+ for (let y = 0; y < H2; y++)
887
+ for (let x = 0; x < W2; x++) {
888
+ const k = 2 * y * w + 2 * x;
889
+ o[y * W2 + x] = (A[k]! + A[k + 1]! + A[k + w]! + A[k + w + 1]!) / 4;
890
+ }
891
+ return { px: o, w: W2, h: H2 };
892
+ };
893
+
894
+ /** the whole picture's motion between frames a and b of the grey copy: scale
895
+ * and shift (px of the copy, about its centre); null where no single motion
896
+ * lays the two together (new content, a flat frame) */
897
+ export function pictureMotion(
898
+ g: GreyFrames,
899
+ a: number,
900
+ b: number,
901
+ ): { s: number; x: number; y: number } | null {
902
+ const fa = frameAt(g, a);
903
+ const fb = frameAt(g, b);
904
+ const A = Float32Array.from(fa);
905
+ const B = Float32Array.from(fb);
906
+ let r0 = 0;
907
+ let textured = 0;
908
+ for (let y = 1; y < g.h - 1; y++)
909
+ for (let x = 1; x < g.w - 1; x++) {
910
+ const k = y * g.w + x;
911
+ r0 += Math.abs(A[k]! - B[k]!);
912
+ if (Math.abs(A[k + 1]! - A[k - 1]!) + Math.abs(A[k + g.w]! - A[k - g.w]!) > 8) textured++;
913
+ }
914
+ const inner = (g.w - 2) * (g.h - 2);
915
+ r0 /= inner;
916
+ if (r0 < 0.35) return { s: 1, x: 0, y: 0 };
917
+ if (textured < 0.02 * inner) return null;
918
+ const try1 = (init: { s: number; x: number; y: number }) => {
919
+ const ha = halve(A, g.w, g.h);
920
+ const hb = halve(B, g.w, g.h);
921
+ const c = fitSimilarity(ha.px, hb.px, ha.w, ha.h, { s: init.s, x: init.x / 2, y: init.y / 2 });
922
+ const start =
923
+ Number.isFinite(c.res) && Math.abs(c.s - 1) < 0.3 ? { s: c.s, x: c.x * 2, y: c.y * 2 } : init;
924
+ return fitSimilarity(A, B, g.w, g.h, start);
925
+ };
926
+ let f = try1({ s: 1, x: 0, y: 0 });
927
+ if (!(f.res <= 0.6 * r0)) {
928
+ const coarse = globalMotion(g, fa, fb);
929
+ if (coarse.s !== 1 || coarse.x || coarse.y) {
930
+ const f2 = try1(coarse);
931
+ if (f2.res < f.res) f = f2;
932
+ }
933
+ }
934
+ // a motion no better than none is none: something else changed
935
+ if (!(f.res <= 0.6 * r0) || Math.abs(f.s - 1) > 0.25) return null;
936
+ return { s: f.s, x: f.x, y: f.y };
937
+ }
938
+
939
+ export type CameraPath = {
940
+ /** the frames compared: every `step`-th, so the curve is read at about 30 Hz */
941
+ step: number;
942
+ /** per step: its end time (s); the picture's scale change as a log (ln s),
943
+ * and its shift as a share of the frame's width / height; null where no
944
+ * single motion lays the frames together or a cut lies between them */
945
+ t: number[];
946
+ logScale: (number | null)[];
947
+ dx: (number | null)[];
948
+ dy: (number | null)[];
949
+ };
950
+
951
+ /** the whole picture's scale and shift, step by step over the film; a cut
952
+ * (or a small swap) between two read frames leaves that step out */
953
+ export function cameraPath(g: GreyFrames, breaks: readonly number[]): CameraPath {
954
+ const step = Math.max(1, Math.round(g.fps / 30));
955
+ const br = [...breaks].sort((a, b) => a - b);
956
+ const out: CameraPath = { step, t: [], logScale: [], dx: [], dy: [] };
957
+ for (let b = step; b < g.count; b += step) {
958
+ const a = b - step;
959
+ out.t.push(frameTime(g, b));
960
+ if (br.some((c) => c > a && c <= b)) {
961
+ out.logScale.push(null);
962
+ out.dx.push(null);
963
+ out.dy.push(null);
964
+ continue;
965
+ }
966
+ const m = pictureMotion(g, a, b);
967
+ out.logScale.push(m ? Math.log(m.s) : null);
968
+ // the shift of the frame's centre, as a share of the frame
969
+ out.dx.push(m ? m.x / g.w : null);
970
+ out.dy.push(m ? m.y / g.h : null);
971
+ }
972
+ return out;
973
+ }
974
+
975
+ export type CameraRun = {
976
+ what: "zoom" | "pan x" | "pan y";
977
+ /** zoom: "in" (the picture grows) / "out"; pan: the way the picture moves */
978
+ dir: "in" | "out" | "left" | "right" | "up" | "down";
979
+ start: number;
980
+ end: number;
981
+ /** zoom: the scale over the run (×); pan: the shift, share of the frame */
982
+ amount: number;
983
+ };
984
+
985
+ /** stretches where the picture keeps zooming or moving one way: the motion
986
+ * smoothed over about a sixth of a second, at least `minRate` a second
987
+ * (zoom: in ln units; pan: share of the frame), adding up to at least
988
+ * `minTotal`; a cut or an unread step ends one */
989
+ export function cameraRuns(
990
+ path: CameraPath,
991
+ fps: number,
992
+ o: { zoomRate?: number; zoomTotal?: number; panRate?: number; panTotal?: number } = {},
993
+ ): CameraRun[] {
994
+ const dt = path.step / fps;
995
+ const out: CameraRun[] = [];
996
+ const series: [
997
+ CameraRun["what"],
998
+ (number | null)[],
999
+ number,
1000
+ number,
1001
+ [CameraRun["dir"], CameraRun["dir"]],
1002
+ ][] = [
1003
+ ["zoom", path.logScale, o.zoomRate ?? 0.01, o.zoomTotal ?? Math.log(1.012), ["in", "out"]],
1004
+ ["pan x", path.dx, o.panRate ?? 0.02, o.panTotal ?? 0.03, ["right", "left"]],
1005
+ ["pan y", path.dy, o.panRate ?? 0.02, o.panTotal ?? 0.03, ["down", "up"]],
1006
+ ];
1007
+ for (const [what, v, minRate, minTotal, [pos, neg]] of series) {
1008
+ const n = v.length;
1009
+ // smoothed rate per second; an unread step breaks the smoothing
1010
+ const rate = new Array<number | null>(n).fill(null);
1011
+ for (let i = 0; i < n; i++) {
1012
+ if (v[i] == null) continue;
1013
+ let s = 0;
1014
+ let k = 0;
1015
+ for (let j = i - 2; j <= i + 2; j++) {
1016
+ if (j < 0 || j >= n) continue;
1017
+ if (v[j] == null) {
1018
+ if (Math.abs(j - i) <= 1) {
1019
+ k = 0;
1020
+ break;
1021
+ }
1022
+ continue;
1023
+ }
1024
+ s += v[j]!;
1025
+ k++;
1026
+ }
1027
+ rate[i] = k ? s / k / dt : v[i]! / dt;
1028
+ }
1029
+ let i = 0;
1030
+ while (i < n) {
1031
+ const r = rate[i];
1032
+ if (r == null || Math.abs(r) < minRate) {
1033
+ i++;
1034
+ continue;
1035
+ }
1036
+ const sign = Math.sign(r);
1037
+ let j = i;
1038
+ let total = 0;
1039
+ let quiet = 0;
1040
+ let last = i;
1041
+ while (j < n && rate[j] != null) {
1042
+ const rj = rate[j]!;
1043
+ if (Math.sign(rj) === sign && Math.abs(rj) >= minRate) {
1044
+ quiet = 0;
1045
+ last = j;
1046
+ } else if (Math.sign(rj) !== sign && Math.abs(rj) >= minRate) break;
1047
+ else if (++quiet > 2) break;
1048
+ j++;
1049
+ }
1050
+ for (let k = i; k <= last; k++) total += v[k] ?? 0;
1051
+ if (Math.abs(total) >= minTotal)
1052
+ out.push({
1053
+ what,
1054
+ dir: sign > 0 ? pos : neg,
1055
+ start: round3(path.t[i]! - dt),
1056
+ end: round3(path.t[last]!),
1057
+ amount: what === "zoom" ? round3(Math.exp(total)) : round3(total),
1058
+ });
1059
+ i = last + 1;
1060
+ }
1061
+ }
1062
+ return out.sort((a, b) => a.start - b.start);
1063
+ }
1064
+
1065
+ export type CameraBackForth = {
1066
+ what: CameraRun["what"];
1067
+ start: number;
1068
+ end: number;
1069
+ /** the runs, each the other way to the one before */
1070
+ runs: number;
1071
+ };
1072
+
1073
+ /** runs of the same kind that turn back within `gap` s of each other, at
1074
+ * least `min` in a row — a zoom in, out, in…, a pan back and forth */
1075
+ export function backAndForth(runs: readonly CameraRun[], gap = 1, min = 3): CameraBackForth[] {
1076
+ const out: CameraBackForth[] = [];
1077
+ for (const what of ["zoom", "pan x", "pan y"] as const) {
1078
+ const rs = runs.filter((r) => r.what === what);
1079
+ let a = 0;
1080
+ for (let i = 1; i <= rs.length; i++) {
1081
+ const turns =
1082
+ i < rs.length && rs[i]!.dir !== rs[i - 1]!.dir && rs[i]!.start - rs[i - 1]!.end <= gap;
1083
+ if (turns) continue;
1084
+ if (i - a >= min) out.push({ what, start: rs[a]!.start, end: rs[i - 1]!.end, runs: i - a });
1085
+ a = i;
1086
+ }
1087
+ }
1088
+ return out.sort((x, y) => x.start - y.start);
1089
+ }
1090
+
1091
+ export type CameraRepeat = {
1092
+ what: CameraRun["what"];
1093
+ dir: CameraRun["dir"];
1094
+ start: number;
1095
+ end: number;
1096
+ runs: number;
1097
+ /** the median time from one run's start to the next */
1098
+ every: number;
1099
+ };
1100
+
1101
+ /** the same short move made again and again: runs of one kind and way, each
1102
+ * after a pause (at least 0.1 s with no such run), starting within `gap` s
1103
+ * of the one before, of about the same size (within 2×), at least `min` in a
1104
+ * row — a pulse on every beat, a push that resets each time */
1105
+ export function repeatedRuns(runs: readonly CameraRun[], gap = 1.5, min = 3): CameraRepeat[] {
1106
+ const out: CameraRepeat[] = [];
1107
+ for (const what of ["zoom", "pan x", "pan y"] as const) {
1108
+ const rs = runs.filter((r) => r.what === what);
1109
+ const size = (r: CameraRun) =>
1110
+ what === "zoom" ? Math.abs(Math.log(r.amount)) : Math.abs(r.amount);
1111
+ let a = 0;
1112
+ for (let i = 1; i <= rs.length; i++) {
1113
+ const p = rs[i - 1]!;
1114
+ const q = rs[i];
1115
+ const goesOn =
1116
+ !!q &&
1117
+ q.dir === p.dir &&
1118
+ q.start - p.end >= 0.1 &&
1119
+ q.start - p.start <= gap &&
1120
+ Math.max(size(p), size(q)) <= 2 * Math.min(size(p), size(q));
1121
+ if (goesOn) continue;
1122
+ if (i - a >= min) {
1123
+ const starts = rs.slice(a, i).map((r) => r.start);
1124
+ out.push({
1125
+ what,
1126
+ dir: p.dir,
1127
+ start: rs[a]!.start,
1128
+ end: p.end,
1129
+ runs: i - a,
1130
+ every: round3(median(starts.slice(1).map((t, k) => t - starts[k]!))),
1131
+ });
1132
+ }
1133
+ a = i;
1134
+ }
1135
+ }
1136
+ return out.sort((x, y) => x.start - y.start);
1137
+ }
1138
+
1139
+ /** every turn back: a run the other way to the run of its kind before it,
1140
+ * starting within `gap` s of its end */
1141
+ export function reversals(
1142
+ runs: readonly CameraRun[],
1143
+ gap = 1,
1144
+ ): { t: number; what: CameraRun["what"] }[] {
1145
+ const out: { t: number; what: CameraRun["what"] }[] = [];
1146
+ for (const what of ["zoom", "pan x", "pan y"] as const) {
1147
+ const rs = runs.filter((r) => r.what === what);
1148
+ for (let i = 1; i < rs.length; i++)
1149
+ if (rs[i]!.dir !== rs[i - 1]!.dir && rs[i]!.start - rs[i - 1]!.end <= gap)
1150
+ out.push({ t: rs[i]!.start, what });
1151
+ }
1152
+ return out.sort((a, b) => a.t - b.t);
1153
+ }
1154
+
1155
+ // --- subjects the page declared ---------------------------------------------------------
1156
+
1157
+ export type SubjectTrack = {
1158
+ name: string;
1159
+ /** where the positions came from */
1160
+ source: "curves" | "events";
1161
+ samples: { t: number; x: number; y: number; w?: number; h?: number }[];
1162
+ };
1163
+
1164
+ export type SubjectExit = {
1165
+ name: string;
1166
+ start: number;
1167
+ end: number;
1168
+ /** out entirely, or only partly (a box crossing the frame's edge) */
1169
+ how: "out" | "partly out";
1170
+ edge: "left" | "right" | "top" | "bottom";
1171
+ };
1172
+
1173
+ /** subjects' positions from an events file: curve pairs `<name>.x`/`<name>.y`
1174
+ * (with `<name>.w`/`<name>.h` for a box), and events of kind "subject" with
1175
+ * x, y and a label naming the subject */
1176
+ export function subjectTracks(raw: unknown): SubjectTrack[] {
1177
+ const r = (raw && typeof raw === "object" ? raw : {}) as Record<string, unknown>;
1178
+ const out: SubjectTrack[] = [];
1179
+ const c = (r.curves && typeof r.curves === "object" ? r.curves : {}) as Record<string, unknown>;
1180
+ const names = (Array.isArray(c.names) ? c.names : []).map(String);
1181
+ const rows = (Array.isArray(c.rows) ? c.rows : []).filter(Array.isArray) as unknown[][];
1182
+ const t0 = typeof c.t0 === "number" ? c.t0 : 0;
1183
+ const dt = typeof c.dt === "number" && c.dt > 0 ? c.dt : 1 / 60;
1184
+ const num = (v: unknown) => (typeof v === "number" && Number.isFinite(v) ? v : null);
1185
+ for (const [j, name] of names.entries()) {
1186
+ if (!name.endsWith(".x")) continue;
1187
+ const base = name.slice(0, -2);
1188
+ const jy = names.indexOf(`${base}.y`);
1189
+ if (jy < 0) continue;
1190
+ const jw = names.indexOf(`${base}.w`);
1191
+ const jh = names.indexOf(`${base}.h`);
1192
+ const samples: SubjectTrack["samples"] = [];
1193
+ rows.forEach((row, i) => {
1194
+ const x = num(row[j]);
1195
+ const y = num(row[jy]);
1196
+ if (x == null || y == null) return;
1197
+ const s: SubjectTrack["samples"][number] = { t: t0 + i * dt, x, y };
1198
+ const w = jw >= 0 ? num(row[jw]) : null;
1199
+ const h = jh >= 0 ? num(row[jh]) : null;
1200
+ if (w != null && h != null) {
1201
+ s.w = w;
1202
+ s.h = h;
1203
+ }
1204
+ samples.push(s);
1205
+ });
1206
+ if (samples.length) out.push({ name: base, source: "curves", samples });
1207
+ }
1208
+ const evs = (Array.isArray(r.events) ? r.events : []) as Record<string, unknown>[];
1209
+ const byName = new Map<string, SubjectTrack["samples"]>();
1210
+ for (const e of evs) {
1211
+ if (e?.kind !== "subject") continue;
1212
+ const t = num(e.t);
1213
+ const x = num(e.x);
1214
+ const y = num(e.y);
1215
+ if (t == null || x == null || y == null) continue;
1216
+ const name = typeof e.label === "string" && e.label ? e.label : "subject";
1217
+ const s: SubjectTrack["samples"][number] = { t, x, y };
1218
+ const w = num(e.w);
1219
+ const h = num(e.h);
1220
+ if (w != null && h != null) {
1221
+ s.w = w;
1222
+ s.h = h;
1223
+ }
1224
+ byName.set(name, [...(byName.get(name) ?? []), s]);
1225
+ }
1226
+ for (const [name, samples] of byName)
1227
+ out.push({ name, source: "events", samples: samples.sort((a, b) => a.t - b.t) });
1228
+ return out;
1229
+ }
1230
+
1231
+ /** when each subject is outside a w×h frame: a point (x, y) is its centre; a
1232
+ * box (w, h) centred there is "partly out" when it crosses the edge and "out"
1233
+ * when nothing of it is inside. Between samples it holds the last state. */
1234
+ export function subjectExits(
1235
+ tracks: readonly SubjectTrack[],
1236
+ w: number,
1237
+ h: number,
1238
+ duration: number,
1239
+ ): SubjectExit[] {
1240
+ const out: SubjectExit[] = [];
1241
+ for (const tr of tracks) {
1242
+ let open: { start: number; how: SubjectExit["how"]; edge: SubjectExit["edge"] } | null = null;
1243
+ const state = (s: SubjectTrack["samples"][number]) => {
1244
+ const hw = (s.w ?? 0) / 2;
1245
+ const hh = (s.h ?? 0) / 2;
1246
+ const edges: [SubjectExit["edge"], number][] = [
1247
+ ["left", -(s.x + hw)],
1248
+ ["right", s.x - hw - w],
1249
+ ["top", -(s.y + hh)],
1250
+ ["bottom", s.y - hh - h],
1251
+ ];
1252
+ // fully out past an edge
1253
+ const out = edges.filter(([, v]) => v > 0).sort((a, b) => b[1] - a[1])[0];
1254
+ if (out) return { how: "out" as const, edge: out[0] };
1255
+ if (hw || hh) {
1256
+ const part: [SubjectExit["edge"], number][] = [
1257
+ ["left", hw - s.x],
1258
+ ["right", s.x + hw - w],
1259
+ ["top", hh - s.y],
1260
+ ["bottom", s.y + hh - h],
1261
+ ];
1262
+ const p = part.filter(([, v]) => v > 0).sort((a, b) => b[1] - a[1])[0];
1263
+ if (p) return { how: "partly out" as const, edge: p[0] };
1264
+ }
1265
+ return null;
1266
+ };
1267
+ for (const s of tr.samples) {
1268
+ const st = state(s);
1269
+ if (open && (!st || st.how !== open.how || st.edge !== open.edge)) {
1270
+ out.push({
1271
+ name: tr.name,
1272
+ start: round3(open.start),
1273
+ end: round3(s.t),
1274
+ how: open.how,
1275
+ edge: open.edge,
1276
+ });
1277
+ open = null;
1278
+ }
1279
+ if (st && !open) open = { start: s.t, ...st };
1280
+ }
1281
+ if (open)
1282
+ out.push({
1283
+ name: tr.name,
1284
+ start: round3(open.start),
1285
+ end: round3(Math.max(open.start, duration)),
1286
+ how: open.how,
1287
+ edge: open.edge,
1288
+ });
1289
+ }
1290
+ return out.sort((a, b) => a.start - b.start);
1291
+ }
1292
+
1293
+ // --- the beat sheet against what happened -------------------------------------------------
1294
+
1295
+ /** a segment of the page's beat sheet (kit/time.js `segment`), in film time */
1296
+ export type SheetSegment = {
1297
+ from: number;
1298
+ to: number;
1299
+ label?: string;
1300
+ hold?: boolean;
1301
+ handoff?: string;
1302
+ /** what the page named to follow across the boundary at `to` */
1303
+ carry?: string;
1304
+ subject?: string;
1305
+ sound?: string;
1306
+ };
1307
+
1308
+ /** a beat sheet as an events file or a page gives it: kept where it has two
1309
+ * times in order, by `from` */
1310
+ export function sheetSegments(raw: unknown): SheetSegment[] {
1311
+ if (!Array.isArray(raw)) return [];
1312
+ const out: SheetSegment[] = [];
1313
+ for (const e of raw as Record<string, unknown>[]) {
1314
+ if (!e || typeof e.from !== "number" || typeof e.to !== "number") continue;
1315
+ if (!Number.isFinite(e.from) || !Number.isFinite(e.to) || !(e.to > e.from)) continue;
1316
+ const s: SheetSegment = { from: e.from, to: e.to };
1317
+ for (const k of ["label", "handoff", "carry", "subject", "sound"] as const)
1318
+ if (typeof e[k] === "string" && e[k]) s[k] = e[k] as string;
1319
+ if (typeof e.hold === "boolean") s.hold = e.hold;
1320
+ out.push(s);
1321
+ }
1322
+ return out.sort((a, b) => a.from - b.from);
1323
+ }
1324
+
1325
+ export type SegmentReading = SheetSegment & {
1326
+ /** share of the segment's frames whose picture changes (≥ the still line) */
1327
+ moving: number;
1328
+ /** where it moves, stretches of at least 0.1 s */
1329
+ movingSpans: { start: number; end: number }[];
1330
+ cuts: number[];
1331
+ swaps: number[];
1332
+ /** the whole picture's motion summed over the segment's read steps: scale
1333
+ * (×) and shift (share of the frame); null when no step could be read */
1334
+ camera: { zoom: number; x: number; y: number; read: number } | null;
1335
+ runs: CameraRun[];
1336
+ /** the declared subject, when the segment names one */
1337
+ subjectSeen?: {
1338
+ how: "measured" | "estimated" | "not detected" | "not measured";
1339
+ /** page: a selector found on the page; curves/events: a declared track by name */
1340
+ source: "page" | "curves" | "events" | null;
1341
+ out: { start: number; end: number; how: "out" | "partly out" | "not visible"; edge?: string }[];
1342
+ };
1343
+ /** what the picture does at the segment's end, where its handoff is */
1344
+ handoffSeen?: {
1345
+ how: "measured" | "estimated";
1346
+ kind:
1347
+ | "hard cut"
1348
+ | "small swap"
1349
+ | "gradual: carried"
1350
+ | "gradual: background only"
1351
+ | "gradual: nothing carried"
1352
+ | "continuous, camera moving"
1353
+ | "continuous, no change"
1354
+ | "film ends";
1355
+ at: number | null;
1356
+ /** a hard cut: what crosses it */
1357
+ across?: CarryKind;
1358
+ nearestOnset: number | null;
1359
+ };
1360
+ };
1361
+
1362
+ /** set each segment beside what the picture did over it */
1363
+ export function readSegments(
1364
+ segments: readonly SheetSegment[],
1365
+ c: {
1366
+ duration: number;
1367
+ fps: number;
1368
+ t0: number;
1369
+ energy: Float32Array;
1370
+ stillUnder: number;
1371
+ cuts: readonly number[];
1372
+ swaps: readonly number[];
1373
+ changes: readonly PictureChange[];
1374
+ path: CameraPath;
1375
+ runs: readonly CameraRun[];
1376
+ tracks: readonly SubjectTrack[];
1377
+ width: number;
1378
+ height: number;
1379
+ /** where the page drew each subject selector, sample by sample (box null:
1380
+ * not visible); null when no element on the page ever matches it */
1381
+ pageSubjects?: (
1382
+ sel: string,
1383
+ ) => { t: number; box: [number, number, number, number] | null }[] | null;
1384
+ onsets: readonly number[] | null;
1385
+ },
1386
+ ): SegmentReading[] {
1387
+ const win = Math.max(0.35, 3 / c.fps);
1388
+ return segments.map((s) => {
1389
+ const a = Math.max(0, Math.round((s.from - c.t0) * c.fps));
1390
+ const b = Math.min(c.energy.length, Math.round((s.to - c.t0) * c.fps));
1391
+ let moving = 0;
1392
+ const spans: { start: number; end: number }[] = [];
1393
+ let open: number | null = null;
1394
+ for (let i = a; i < b; i++) {
1395
+ const m = i > 0 && c.energy[i]! >= c.stillUnder;
1396
+ if (m) moving++;
1397
+ if (m && open == null) open = i;
1398
+ if ((!m || i === b - 1) && open != null) {
1399
+ const end = m ? i + 1 : i;
1400
+ if ((end - open) / c.fps >= 0.1)
1401
+ spans.push({ start: round3(c.t0 + open / c.fps), end: round3(c.t0 + end / c.fps) });
1402
+ open = null;
1403
+ }
1404
+ }
1405
+ let ls = 0;
1406
+ let x = 0;
1407
+ let y = 0;
1408
+ let read = 0;
1409
+ c.path.t.forEach((t, k) => {
1410
+ if (t <= s.from + 1e-9 || t > s.to + 1e-9) return;
1411
+ const v = c.path.logScale[k];
1412
+ if (v == null) return;
1413
+ ls += v;
1414
+ x += c.path.dx[k] ?? 0;
1415
+ y += c.path.dy[k] ?? 0;
1416
+ read++;
1417
+ });
1418
+ const r: SegmentReading = {
1419
+ ...s,
1420
+ moving: round2(b > a ? moving / (b - a) : 0),
1421
+ movingSpans: spans,
1422
+ cuts: c.cuts.filter((t) => t > s.from + 1e-9 && t < s.to - 1e-9),
1423
+ swaps: c.swaps.filter((t) => t > s.from + 1e-9 && t < s.to - 1e-9),
1424
+ camera: read ? { zoom: round3(Math.exp(ls)), x: round3(x), y: round3(y), read } : null,
1425
+ runs: c.runs.filter((u) => u.end > s.from && u.start < s.to),
1426
+ };
1427
+ if (s.subject) {
1428
+ const page = c.pageSubjects?.(s.subject) ?? null;
1429
+ const track = c.tracks.find((t) => t.name === s.subject);
1430
+ // the page's samples inside the segment (none: the segment falls between two)
1431
+ const inSeg = (page ?? []).filter((p) => p.t >= s.from - 1e-9 && p.t < s.to - 1e-9);
1432
+ if (inSeg.length) {
1433
+ const out: NonNullable<SegmentReading["subjectSeen"]>["out"] = [];
1434
+ // a stretch per state: not visible, or out / partly out by edge
1435
+ let cur: {
1436
+ start: number;
1437
+ how: "out" | "partly out" | "not visible";
1438
+ edge?: string;
1439
+ } | null = null;
1440
+ const close = (t: number) => {
1441
+ if (cur) out.push({ ...cur, end: round3(t) });
1442
+ cur = null;
1443
+ };
1444
+ for (const p of inSeg) {
1445
+ let st: { how: "out" | "partly out" | "not visible"; edge?: string } | null = null;
1446
+ if (!p.box) st = { how: "not visible" };
1447
+ else {
1448
+ const [bx, by, bw, bh] = p.box;
1449
+ const ex = subjectExits(
1450
+ [
1451
+ {
1452
+ name: "",
1453
+ source: "events",
1454
+ samples: [{ t: 0, x: bx + bw / 2, y: by + bh / 2, w: bw, h: bh }],
1455
+ },
1456
+ ],
1457
+ c.width,
1458
+ c.height,
1459
+ 0,
1460
+ )[0];
1461
+ if (ex) st = { how: ex.how, edge: ex.edge };
1462
+ }
1463
+ const same = (q: typeof cur) => !!q && !!st && q.how === st.how && q.edge === st.edge;
1464
+ if (cur && !same(cur)) close(p.t);
1465
+ if (st && !cur) cur = { start: round3(p.t), ...st };
1466
+ }
1467
+ close(s.to);
1468
+ r.subjectSeen = { how: out.length ? "measured" : "not detected", source: "page", out };
1469
+ } else if (track) {
1470
+ const ex = subjectExits([track], c.width, c.height, c.duration).filter(
1471
+ (e) => e.end > s.from && e.start < s.to,
1472
+ );
1473
+ r.subjectSeen = {
1474
+ how: ex.length ? "estimated" : "not detected",
1475
+ source: track.source,
1476
+ out: ex.map((e) => ({
1477
+ start: round3(Math.max(e.start, s.from)),
1478
+ end: round3(Math.min(e.end, s.to)),
1479
+ how: e.how,
1480
+ edge: e.edge,
1481
+ })),
1482
+ };
1483
+ } else r.subjectSeen = { how: "not measured", source: null, out: [] };
1484
+ }
1485
+ if (s.handoff) {
1486
+ const at = s.to;
1487
+ const nearestOnset = c.onsets?.length ? nearestOffset([...c.onsets], at) : null;
1488
+ const near = (t: number) => Math.abs(t - at) <= win;
1489
+ const cut = c.cuts.filter(near).sort((p, q) => Math.abs(p - at) - Math.abs(q - at))[0];
1490
+ const grad = c.changes.find(
1491
+ (ch) =>
1492
+ ch.kind !== "hard cut" &&
1493
+ c.t0 + ch.before / c.fps <= at + win &&
1494
+ c.t0 + ch.after / c.fps >= at - win,
1495
+ );
1496
+ const swap = c.swaps.filter(near)[0];
1497
+ const camMoves = c.runs.some((u) => u.start <= at + 0.05 && u.end >= at - 0.05);
1498
+ if (at >= c.duration - 1.5 / c.fps)
1499
+ r.handoffSeen = { how: "measured", kind: "film ends", at: null, nearestOnset };
1500
+ else if (cut != null) {
1501
+ const ch = c.changes.find(
1502
+ (x) => x.kind === "hard cut" && Math.abs(x.t - cut) < 0.5 / c.fps,
1503
+ );
1504
+ r.handoffSeen = {
1505
+ how: "measured",
1506
+ kind: "hard cut",
1507
+ at: round3(cut),
1508
+ ...(ch ? { across: ch.across } : {}),
1509
+ nearestOnset,
1510
+ };
1511
+ } else if (grad)
1512
+ r.handoffSeen = {
1513
+ how: "estimated",
1514
+ kind: `gradual: ${grad.kind as CarryKind}`,
1515
+ at: round3(grad.t),
1516
+ nearestOnset,
1517
+ };
1518
+ else if (swap != null)
1519
+ r.handoffSeen = { how: "measured", kind: "small swap", at: round3(swap), nearestOnset };
1520
+ else
1521
+ r.handoffSeen = {
1522
+ how: "estimated",
1523
+ kind: camMoves ? "continuous, camera moving" : "continuous, no change",
1524
+ at: null,
1525
+ nearestOnset,
1526
+ };
1527
+ }
1528
+ return r;
1529
+ });
1530
+ }
1531
+
1532
+ // --- text at film scale -----------------------------------------------------------------
1533
+
1534
+ export type TextSample = {
1535
+ t: number;
1536
+ /** share of the frame under text: the page's own, the product's (saved
1537
+ * screens), inside pictures (read off the film); null: not read */
1538
+ own: number | null;
1539
+ product: number | null;
1540
+ picture: number | null;
1541
+ /** all of it */
1542
+ share: number;
1543
+ /** characters visible: the same split */
1544
+ ownChars: number | null;
1545
+ productChars: number | null;
1546
+ pictureChars: number | null;
1547
+ chars: number | null;
1548
+ /** the smallest and the median (by character) text size, film px; where
1549
+ * each came from */
1550
+ smallest: { px: number; from: "page" | "picture"; text: string } | null;
1551
+ median: number | null;
1552
+ /** the median size (by character, film px) of the product's words alone:
1553
+ * the page's text less the film's own pieces, and text read in pictures;
1554
+ * null: none of it read */
1555
+ productMedian?: number | null;
1556
+ };
1557
+
1558
+ export type TextOverlap = {
1559
+ from: number;
1560
+ to: number;
1561
+ /** the page's own text */
1562
+ text: string;
1563
+ over: string;
1564
+ };
1565
+
1566
+ /** the page's text and the film's read text, sample by sample, put together */
1567
+ export function textTimeline(
1568
+ page: PageTextSample[] | null,
1569
+ frames: FrameText[] | null,
1570
+ o: {
1571
+ width: number;
1572
+ height: number;
1573
+ segments: readonly SheetSegment[];
1574
+ every: number;
1575
+ },
1576
+ ): { samples: TextSample[]; overlaps: TextOverlap[] } {
1577
+ const area = o.width * o.height;
1578
+ // every time either reader has (a page can leave a time out)
1579
+ const times = [...new Set([...(page ?? []), ...(frames ?? [])].map((s) => s.t))].sort(
1580
+ (a, b) => a - b,
1581
+ );
1582
+ const byT = (list: { t: number }[] | null, t: number) =>
1583
+ list?.find((s) => Math.abs(s.t - t) < 1e-6) ?? null;
1584
+ const samples: TextSample[] = [];
1585
+ const raw: { t: number; text: string; over: string }[] = [];
1586
+ for (const t of times) {
1587
+ const p = byT(page, t) as PageTextSample | null;
1588
+ const f = byT(frames, t) as FrameText | null;
1589
+ // the read lines that are not the page's own text: text in pictures
1590
+ // (a line over the product's live text is that text)
1591
+ const pictureLines = (f?.lines ?? []).filter((l) => {
1592
+ if (l.conf < 0.3 || l.box[3] < 4) return false;
1593
+ if (!p) return true;
1594
+ if (gridCover(p.grid, o.width, o.height, l.box) >= 0.3) return false;
1595
+ // the film's own text read back: mostly on its pieces at about the
1596
+ // line's size (a line the recognizer reads across two pieces side by
1597
+ // side included)
1598
+ const la = l.box[2] * l.box[3];
1599
+ const onOwn = p.own
1600
+ .filter((x) => l.box[3] >= 0.6 * x.px && l.box[3] <= 1.8 * x.px)
1601
+ .reduce((a, x) => a + x.boxes.reduce((s, b) => s + overlapArea(b, l.box), 0), 0);
1602
+ return onOwn < 0.5 * la;
1603
+ });
1604
+ const sizes: { px: number; chars: number; from: "page" | "picture"; text: string }[] = [];
1605
+ if (p) {
1606
+ for (const [px, chars] of p.sizes) sizes.push({ px, chars, from: "page", text: "" });
1607
+ // name the smallest piece of the film's own text, when it is that
1608
+ for (const x of p.own) {
1609
+ const hit = sizes.find((s) => s.from === "page" && Math.abs(s.px - x.px) < 0.26 && !s.text);
1610
+ if (hit) hit.text = x.text;
1611
+ }
1612
+ }
1613
+ for (const l of pictureLines)
1614
+ sizes.push({ px: l.box[3], chars: l.chars, from: "picture", text: l.text });
1615
+ let pictureShare: number | null = null;
1616
+ let pictureChars: number | null = null;
1617
+ if (f?.how === "ocr") {
1618
+ pictureShare = round3(
1619
+ Math.min(1, pictureLines.reduce((a, l) => a + l.box[2] * l.box[3], 0) / area),
1620
+ );
1621
+ pictureChars = pictureLines.reduce((a, l) => a + l.chars, 0);
1622
+ } else if (f?.how === "edges") pictureShare = f.share;
1623
+ const own = p ? p.ownShare : null;
1624
+ const product = p ? p.productShare : null;
1625
+ const share =
1626
+ f?.how === "edges"
1627
+ ? Math.max(f.share, (own ?? 0) + (product ?? 0))
1628
+ : Math.min(1, (own ?? 0) + (product ?? 0) + (pictureShare ?? 0));
1629
+ const ownChars = p ? p.own.reduce((a, x) => a + x.chars, 0) : null;
1630
+ const productChars = p ? p.product.chars : null;
1631
+ const chars =
1632
+ ownChars == null && pictureChars == null
1633
+ ? null
1634
+ : (ownChars ?? 0) + (productChars ?? 0) + (pictureChars ?? 0);
1635
+ const sorted = sizes.filter((s) => s.px > 0).sort((a, b) => a.px - b.px);
1636
+ const medianOf = (list: readonly { px: number; chars: number }[]): number | null => {
1637
+ const total = list.reduce((a, s) => a + s.chars, 0);
1638
+ let k = 0;
1639
+ for (const s of list) {
1640
+ k += s.chars;
1641
+ if (total && k >= total / 2) return round1(s.px);
1642
+ }
1643
+ return null;
1644
+ };
1645
+ const median = medianOf(sorted);
1646
+ // the product's words alone: the page's sizes less the film's own pieces
1647
+ // (each taken off the size it was drawn at), and the text in pictures
1648
+ const rest = sorted.map((s) => ({ px: s.px, chars: s.chars, from: s.from }));
1649
+ for (const x of p?.own ?? []) {
1650
+ let left = x.chars;
1651
+ for (const s of rest)
1652
+ if (left > 0 && s.from === "page" && Math.abs(s.px - x.px) < 0.26) {
1653
+ const take = Math.min(left, s.chars);
1654
+ s.chars -= take;
1655
+ left -= take;
1656
+ }
1657
+ }
1658
+ const productMedian = medianOf(
1659
+ rest.filter((s) => s.chars > 0 && (s.from === "page" || f?.how === "ocr")),
1660
+ );
1661
+ samples.push({
1662
+ t,
1663
+ own,
1664
+ product,
1665
+ picture: pictureShare,
1666
+ share: round3(share),
1667
+ ownChars,
1668
+ productChars,
1669
+ pictureChars,
1670
+ chars,
1671
+ smallest: sorted[0]
1672
+ ? { px: round1(sorted[0].px), from: sorted[0].from, text: sorted[0].text }
1673
+ : null,
1674
+ median,
1675
+ productMedian,
1676
+ });
1677
+ // the film's own text over pictures, the product's text, text in
1678
+ // pictures, the subject of the segment it is in
1679
+ if (p) {
1680
+ const subjects = o.segments
1681
+ .filter((s) => s.subject && t >= s.from - 1e-9 && t < s.to - 1e-9)
1682
+ .map((s) => [s.subject!, p.subjects[s.subject!] ?? null] as const);
1683
+ for (const x of p.own) {
1684
+ const a = x.boxes.reduce((s, b) => s + b[2] * b[3], 0);
1685
+ if (!a) continue;
1686
+ // over a picture: a share of the text; over a line or a subject: a
1687
+ // share of the smaller of the two
1688
+ const cover = (box: Box) => x.boxes.reduce((s, b) => s + overlapArea(b, box), 0) / a;
1689
+ const meet = (box: Box) =>
1690
+ x.boxes.reduce((s, b) => s + overlapArea(b, box), 0) / Math.min(a, box[2] * box[3]);
1691
+ const add = (over: string) => raw.push({ t, text: x.text, over });
1692
+ if (x.boxes.some((b) => gridCover(p.grid, o.width, o.height, b) >= 0.2))
1693
+ add("the product's text");
1694
+ if (pictureLines.some((l) => meet(l.box) >= 0.2)) add("text inside a picture");
1695
+ for (const [sel, box] of subjects) if (box && meet(box) >= 0.2) add(`the subject ${sel}`);
1696
+ for (const m of p.media)
1697
+ if (cover(m.box) >= 0.2 && m.box[2] * m.box[3] < 0.9 * area) add(`a picture: ${m.label}`);
1698
+ }
1699
+ }
1700
+ }
1701
+ // samples in a row with the same text over the same thing: one stretch
1702
+ const overlaps: TextOverlap[] = [];
1703
+ const openO = new Map<string, TextOverlap & { last: number }>();
1704
+ for (const t of times) {
1705
+ const now = raw.filter((r) => r.t === t);
1706
+ const keys = new Set<string>();
1707
+ for (const r of now) {
1708
+ const k = `${r.text}|${r.over}`;
1709
+ keys.add(k);
1710
+ const cur = openO.get(k);
1711
+ if (cur && t - cur.last <= o.every * 1.5 + 1e-6) {
1712
+ cur.last = t;
1713
+ cur.to = round3(t + o.every);
1714
+ } else {
1715
+ if (cur) overlaps.push({ from: cur.from, to: cur.to, text: cur.text, over: cur.over });
1716
+ openO.set(k, {
1717
+ from: round3(t),
1718
+ to: round3(t + o.every),
1719
+ text: r.text,
1720
+ over: r.over,
1721
+ last: t,
1722
+ });
1723
+ }
1724
+ }
1725
+ for (const [k, cur] of [...openO])
1726
+ if (!keys.has(k) && t - cur.last > o.every * 1.5) {
1727
+ overlaps.push({ from: cur.from, to: cur.to, text: cur.text, over: cur.over });
1728
+ openO.delete(k);
1729
+ }
1730
+ }
1731
+ for (const cur of openO.values())
1732
+ overlaps.push({ from: cur.from, to: cur.to, text: cur.text, over: cur.over });
1733
+ return { samples, overlaps: overlaps.sort((a, b) => a.from - b.from) };
1734
+ }
1735
+
1736
+ const overlapArea = (a: Box, b: Box) => {
1737
+ const w = Math.min(a[0] + a[2], b[0] + b[2]) - Math.max(a[0], b[0]);
1738
+ const h = Math.min(a[1] + a[3], b[1] + b[3]) - Math.max(a[1], b[1]);
1739
+ return w > 0 && h > 0 ? w * h : 0;
1740
+ };
1741
+
1742
+ /** the text samples per `binS` second: mean share, most characters at once,
1743
+ * the smallest size, the median of the samples' medians */
1744
+ export function textPerSecond(samples: readonly TextSample[], duration: number, binS = 1) {
1745
+ return Array.from({ length: Math.max(1, Math.ceil(duration / binS - 1e-9)) }, (_, k) => {
1746
+ const inBin = samples.filter((s) => s.t >= k * binS - 1e-9 && s.t < (k + 1) * binS - 1e-9);
1747
+ const meds = inBin.map((s) => s.median).filter((v): v is number => v != null);
1748
+ const smalls = inBin.map((s) => s.smallest?.px).filter((v): v is number => v != null);
1749
+ const chars = inBin.map((s) => s.chars).filter((v): v is number => v != null);
1750
+ return {
1751
+ t: k * binS,
1752
+ share: inBin.length ? round3(inBin.reduce((a, s) => a + s.share, 0) / inBin.length) : 0,
1753
+ chars: chars.length ? Math.max(...chars) : null,
1754
+ smallest: smalls.length ? Math.min(...smalls) : null,
1755
+ median: meds.length ? round1(median(meds)) : null,
1756
+ };
1757
+ });
1758
+ }
1759
+
1760
+ /** under this many px on the phone, a size is named beside the tools that act
1761
+ * on part of a screen: information, not a limit */
1762
+ export const PHONE_SMALL_PX = 8;
1763
+
1764
+ /** fewer characters of the product's than this in a sample read as the
1765
+ * recognizer's stray marks, not words */
1766
+ const PRODUCT_WORDS_MIN_CHARS = 20;
1767
+
1768
+ export type ProductTextSpan = {
1769
+ from: number;
1770
+ to: number;
1771
+ /** the share of the text on screen that is the product's (saved screens)
1772
+ * or in pictures, the most in the span */
1773
+ productShare: number;
1774
+ /** the product's words' median size, px on the phone: the smallest
1775
+ * sample's in the span */
1776
+ phoneMedian: number | null;
1777
+ };
1778
+
1779
+ /** where the product's own words (its saved screens, text read in pictures)
1780
+ * are most of the frame's text, or their median size reads under
1781
+ * PHONE_SMALL_PX on the phone. Samples next to each other run into one
1782
+ * span. `pictures: false` (pictures read by edges, which cannot tell the
1783
+ * film's own text from a picture's) counts the saved screens only.
1784
+ * Information only. */
1785
+ export function productTextSpans(
1786
+ samples: readonly TextSample[],
1787
+ phoneScale: number,
1788
+ every: number,
1789
+ o: { pictures?: boolean } = {},
1790
+ ): ProductTextSpan[] {
1791
+ const pictures = o.pictures ?? true;
1792
+ const spans: ProductTextSpan[] = [];
1793
+ let open: ProductTextSpan | null = null;
1794
+ for (const s of samples) {
1795
+ const words = (s.product ?? 0) + (pictures ? (s.picture ?? 0) : 0);
1796
+ const chars = (s.productChars ?? 0) + (pictures ? (s.pictureChars ?? 0) : 0);
1797
+ const share = s.share > 0.002 ? Math.min(1, words / s.share) : 0;
1798
+ const phone =
1799
+ s.productMedian == null || chars < PRODUCT_WORDS_MIN_CHARS
1800
+ ? null
1801
+ : round1(s.productMedian * phoneScale);
1802
+ const hit = (words > 0 && share >= 0.5) || (phone != null && phone < PHONE_SMALL_PX);
1803
+ if (!hit) {
1804
+ open = null;
1805
+ continue;
1806
+ }
1807
+ if (open && s.t <= open.to + every * 0.5 + 1e-6) {
1808
+ open.to = round3(s.t + every);
1809
+ open.productShare = Math.max(open.productShare, round2(share));
1810
+ if (phone != null)
1811
+ open.phoneMedian = open.phoneMedian == null ? phone : Math.min(open.phoneMedian, phone);
1812
+ } else {
1813
+ open = {
1814
+ from: s.t,
1815
+ to: round3(s.t + every),
1816
+ productShare: round2(share),
1817
+ phoneMedian: phone,
1818
+ };
1819
+ spans.push(open);
1820
+ }
1821
+ }
1822
+ return spans;
1823
+ }
1824
+
1825
+ // --- the whole probe ---------------------------------------------------------------------
1826
+
1827
+ type How = "measured" | "estimated" | "not detected" | "not measured";
1828
+
1829
+ export type FilmProbe = {
1830
+ input: string;
1831
+ duration: number;
1832
+ fps: number;
1833
+ /** the film time of the first frame */
1834
+ t0: number;
1835
+ size: { width: number; height: number };
1836
+ /** the grey copy everything is read on */
1837
+ read: { width: number; height: number; frames: number };
1838
+ energy: {
1839
+ how: How;
1840
+ /** mean of the per-frame change (0..1) in each `binS` bin */
1841
+ bins: number[];
1842
+ binS: number;
1843
+ /** the share of frames with any change at all (≥ 0.0015) */
1844
+ movingShare: number;
1845
+ };
1846
+ stills: {
1847
+ how: How;
1848
+ under: number;
1849
+ minS: number;
1850
+ list: { start: number; end: number }[];
1851
+ share: number;
1852
+ };
1853
+ cuts: {
1854
+ how: How;
1855
+ /** `changed`: the share of the frame's blocks the cut changes */
1856
+ list: { t: number; frame: number; changed: number; nearestOnset: number | null }[];
1857
+ perMin: number;
1858
+ /** cuts per 5 s */
1859
+ density: number[];
1860
+ /** of them, cuts that change at least NEW_PICTURE of the frame (a new
1861
+ * picture, not a word or a colour swapped inside a held one), per 5 s */
1862
+ densityNewPicture: number[];
1863
+ newPictureShare: number;
1864
+ densityBinS: number;
1865
+ };
1866
+ /** the stretches between hard cuts, film start and end included: every
1867
+ * one-frame jump ends one (a word swapped on a held picture too) */
1868
+ shots: ShotStats & {
1869
+ how: How;
1870
+ /** the same, ended only by the cuts that change at least NEW_PICTURE of
1871
+ * the frame */
1872
+ newPicture: ShotStats;
1873
+ /** the same, ended by small swaps too */
1874
+ withSwaps: ShotStats;
1875
+ };
1876
+ changes: { how: How; list: (PictureChange & { thumbs?: { before: string; after: string } })[] };
1877
+ sound: {
1878
+ how: How;
1879
+ onsets: number;
1880
+ onsetsPerS: number;
1881
+ /** share of the cuts with an onset within 40 / 80 ms */
1882
+ within40: number | null;
1883
+ within80: number | null;
1884
+ /** share of the film within 40 / 80 ms of an onset: what cuts at random times would get */
1885
+ chance40: number;
1886
+ chance80: number;
1887
+ medianAbsOffset: number | null;
1888
+ };
1889
+ /** at each hard cut: does either side move next to it, does anything cross */
1890
+ seams: { how: How; list: SeamSeen[] };
1891
+ declaredCuts: {
1892
+ how: How;
1893
+ file: string | null;
1894
+ list: number[];
1895
+ /** declared cuts with no picture cut within 1.5 frames, and the reverse */
1896
+ unseen: number[];
1897
+ undeclared: number[];
1898
+ };
1899
+ subjects: {
1900
+ how: How;
1901
+ tracks: { name: string; source: string; samples: number }[];
1902
+ exits: SubjectExit[];
1903
+ };
1904
+ marks: {
1905
+ how: How;
1906
+ list: { t: number; label: string; still: boolean; nearestCut: number | null }[];
1907
+ };
1908
+ /** one-frame jumps that change 2–12 % of the frame: too small for a cut */
1909
+ smallSwaps: { how: How; list: { t: number; changed: number }[]; perMin: number };
1910
+ /** the whole picture's scale and shift, read step by step (a camera move,
1911
+ * or anything large enough to carry the picture with it) */
1912
+ camera: {
1913
+ how: How;
1914
+ /** seconds between the frames compared */
1915
+ stepS: number;
1916
+ /** share of the steps a single motion could be read for */
1917
+ read: number;
1918
+ /** over the film: every read step's zoom in multiplied together, and
1919
+ * every zoom out (×), and how far the picture travelled (frame widths) */
1920
+ zoomIn: number | null;
1921
+ zoomOut: number | null;
1922
+ travel: number | null;
1923
+ runs: CameraRun[];
1924
+ reversals: { t: number; what: CameraRun["what"] }[];
1925
+ backAndForth: CameraBackForth[];
1926
+ repeated: CameraRepeat[];
1927
+ };
1928
+ /** the page's beat sheet beside what the picture did */
1929
+ segments: { how: How; source: "page" | "events file" | null; list: SegmentReading[] };
1930
+ /** how much of the frame is text, and how big */
1931
+ text: {
1932
+ how: How;
1933
+ every: number;
1934
+ /** the page's text (measured), read on the film clock */
1935
+ page: { how: How; file: string | null; note?: string };
1936
+ /** text read off the film's frames (estimated) */
1937
+ picture: { how: How; reader: "ocr" | "edges" | null };
1938
+ /** the width a phone is taken to show the film at (CSS px) */
1939
+ phoneWidth: number;
1940
+ /** film px × phoneScale = px on that phone */
1941
+ phoneScale: number;
1942
+ samples: TextSample[];
1943
+ perSecond: ReturnType<typeof textPerSecond>;
1944
+ overlaps: TextOverlap[];
1945
+ };
1946
+ /** where the numbers in the film's own text come from, as the page
1947
+ * declares (tl.source) and as the product's parts showed them
1948
+ * (components.json) — information only */
1949
+ provenance: FilmProvenance;
1950
+ /** the product's stills and saved screens on screen that their shoot
1951
+ * took while the screen was still changing (shots.json `moving`) */
1952
+ moving: MovingMaterial;
1953
+ };
1954
+
1955
+ export type ShotStats = {
1956
+ /** seconds of each shot */
1957
+ lengths: number[];
1958
+ median: number | null;
1959
+ shortest: number | null;
1960
+ longest: number | null;
1961
+ /** spread of the shot lengths (standard deviation / mean) */
1962
+ cv: number | null;
1963
+ };
1964
+
1965
+ function shotStats(cuts: readonly number[], duration: number): ShotStats {
1966
+ const bounds = [0, ...cuts, duration];
1967
+ const lengths = bounds.slice(1).map((b, i) => round3(b - bounds[i]!));
1968
+ const mean = lengths.reduce((a, b) => a + b, 0) / lengths.length;
1969
+ const sd = Math.sqrt(lengths.reduce((a, b) => a + (b - mean) ** 2, 0) / lengths.length);
1970
+ return {
1971
+ lengths,
1972
+ median: round3(median(lengths)),
1973
+ shortest: round3(Math.min(...lengths)),
1974
+ longest: round3(Math.max(...lengths)),
1975
+ cv: lengths.length > 1 && mean > 0 ? round2(sd / mean) : null,
1976
+ };
1977
+ }
1978
+
1979
+ export type FilmProbeOptions = {
1980
+ input: string;
1981
+ /** default: `<input without extension>.probe/` */
1982
+ out?: string;
1983
+ /** default: `<input without extension>.events.json` when it exists */
1984
+ events?: string;
1985
+ /** draws probe.png; without it only the text, data and thumbnails */
1986
+ chromePath?: string;
1987
+ /** the seconds between `film sheet`'s frames, to mark the same times */
1988
+ every?: number;
1989
+ /** the film's page (an .html file or its folder): its text is read on the
1990
+ * film clock (needs chromePath) and its beat sheet taken from it */
1991
+ page?: string;
1992
+ /** the directory the page is served from (as for `film render`) */
1993
+ root?: string;
1994
+ /** read the film's frames for text (default true): the system's text
1995
+ * recognizer on macOS, else an edge count */
1996
+ text?: boolean;
1997
+ /** seconds between text samples (default 0.5) */
1998
+ textEvery?: number;
1999
+ /** components.json files to set the film's numbers beside (default: those
2000
+ * the page's sources name, and those in the page's folder) */
2001
+ components?: readonly string[];
2002
+ onConsole?: (level: string, text: string) => void;
2003
+ };
2004
+
2005
+ export async function filmProbe(opts: FilmProbeOptions): Promise<{
2006
+ /** the ruler and the first changes' thumbnails */
2007
+ png: string | null;
2008
+ /** probe.png and, when the changes run past one picture, probe-2.png… */
2009
+ pages: string[];
2010
+ md: string;
2011
+ json: string;
2012
+ probe: FilmProbe;
2013
+ }> {
2014
+ const input = resolve(opts.input);
2015
+ if (!existsSync(input)) throw new Error(`film probe: no file at ${input}`);
2016
+ const stem = input.replace(/\.[^./]+$/, "");
2017
+ const outDir = resolve(opts.out ?? `${stem}.probe`);
2018
+ const [ffmpeg, ffprobe] = await Promise.all([resolveFfmpeg(), resolveFfprobe()]);
2019
+ const info = JSON.parse(
2020
+ await runTool(ffprobe, [
2021
+ "-v",
2022
+ "error",
2023
+ "-show_entries",
2024
+ "stream=codec_type,width,height,r_frame_rate,start_time:format=duration,start_time:format_tags",
2025
+ "-of",
2026
+ "json",
2027
+ input,
2028
+ ]),
2029
+ ) as {
2030
+ streams?: {
2031
+ codec_type?: string;
2032
+ width?: number;
2033
+ height?: number;
2034
+ r_frame_rate?: string;
2035
+ start_time?: string;
2036
+ }[];
2037
+ format?: { duration?: string; start_time?: string; tags?: Record<string, string> };
2038
+ };
2039
+ const video = info.streams?.find((s) => s.codec_type === "video");
2040
+ const audio = info.streams?.find((s) => s.codec_type === "audio");
2041
+ if (!video?.width || !video.height) throw new Error(`film probe: ${input} has no picture`);
2042
+ const duration = Number(info.format?.duration ?? 0);
2043
+ if (!(duration > 0)) throw new Error(`film probe: ${input} has no duration`);
2044
+ const fps = frameRate(video.r_frame_rate);
2045
+ // frame 0's time on the film's clock (the sound's clock): a stream may start late
2046
+ const t0 = Math.max(0, Number(video.start_time ?? 0) - Number(info.format?.start_time ?? 0)) || 0;
2047
+
2048
+ const eventsPath = opts.events
2049
+ ? resolve(opts.events)
2050
+ : existsSync(`${stem}.events.json`)
2051
+ ? `${stem}.events.json`
2052
+ : null;
2053
+ if (opts.events && !existsSync(eventsPath!))
2054
+ throw new Error(`film probe: no events file at ${eventsPath}`);
2055
+ const rawEvents: unknown = eventsPath ? JSON.parse(await readFile(eventsPath, "utf8")) : null;
2056
+
2057
+ const gh = Math.max(BLOCK, Math.round((PROBE_W * video.height) / video.width / 2) * 2);
2058
+ const [grey, pcm] = await Promise.all([
2059
+ decodeGrey(ffmpeg, input, PROBE_W, gh, fps).then((g) => ({ ...g, t0 })),
2060
+ audio ? decodeSound(ffmpeg, input) : Promise.resolve(null),
2061
+ ]);
2062
+
2063
+ const energy = frameEnergy(grey);
2064
+ const cutFrames = findCuts(grey, energy);
2065
+ const stillUnder = 0.0015;
2066
+ const stillMin = 0.5;
2067
+ const stillRanges = findStills(energy, fps, stillMin, stillUnder, grey);
2068
+ const changes = findChanges(grey, energy, cutFrames);
2069
+ const swaps = findSmallSwaps(grey, energy, cutFrames);
2070
+ const swapTimes = swaps.map((w) => round3(frameTime(grey, w.frame)));
2071
+ const path = cameraPath(grey, [...cutFrames, ...swaps.map((w) => w.frame)]);
2072
+ const runs = cameraRuns(path, fps);
2073
+ // what `film render` wrote into the film: where it starts on the page's
2074
+ // timeline and the size it was laid out at
2075
+ const record = filmRecordOf(info.format?.tags?.[FILM_TAG]);
2076
+
2077
+ // the sound's onsets, as `film listen` finds them
2078
+ let onsets: number[] = [];
2079
+ if (pcm) {
2080
+ const s = spectrum(pcm);
2081
+ onsets = pickOnsets(s, onsetStrength(s), pcm).map(round3);
2082
+ }
2083
+ const cutTimes = cutFrames.map((f) => round3(frameTime(grey, f)));
2084
+ const changedAt = new Map(
2085
+ changes.filter((c) => c.kind === "hard cut").map((c) => [c.frame, c.changed]),
2086
+ );
2087
+ const cutList = cutTimes.map((t, i) => ({
2088
+ t,
2089
+ frame: cutFrames[i]!,
2090
+ changed: round2(changedAt.get(cutFrames[i]!) ?? 0),
2091
+ nearestOnset: pcm ? nearestOffset(onsets, t) : null,
2092
+ }));
2093
+ const offs = cutList.map((c) => c.nearestOnset).filter((v): v is number => v != null);
2094
+ const share = (w: number) =>
2095
+ offs.length ? round2(offs.filter((o) => Math.abs(o) <= w + 1e-9).length / offs.length) : null;
2096
+
2097
+ const newPictureTimes = cutList.filter((c) => c.changed >= NEW_PICTURE).map((c) => c.t);
2098
+
2099
+ const binS = 1;
2100
+ const eBins = Array.from({ length: Math.ceil(duration / binS - 1e-9) }, (_, b) => {
2101
+ const a = Math.max(0, Math.floor((b * binS - t0) * fps));
2102
+ const z = Math.min(grey.count, Math.floor(((b + 1) * binS - t0) * fps));
2103
+ let s = 0;
2104
+ for (let i = a; i < z; i++) s += energy[i]!;
2105
+ return z > a ? round4(s / (z - a)) : 0;
2106
+ });
2107
+ let moving = 0;
2108
+ for (let i = 1; i < grey.count; i++) if (energy[i]! >= stillUnder) moving++;
2109
+ const stillFrames = stillRanges.reduce((a, r) => a + (r.b - r.a), 0);
2110
+
2111
+ // what the events file says
2112
+ const ev = rawEvents ? parseFilmEvents(rawEvents) : null;
2113
+ const rawObj = (rawEvents && typeof rawEvents === "object" ? rawEvents : {}) as Record<
2114
+ string,
2115
+ unknown
2116
+ >;
2117
+ const declared = (Array.isArray(rawObj.declaredCuts) ? rawObj.declaredCuts : (ev?.cuts ?? []))
2118
+ .filter((v): v is number => typeof v === "number" && Number.isFinite(v))
2119
+ .sort((a, b) => a - b);
2120
+ const tol = 1.5 / fps;
2121
+ // what the page declares beside its cuts, moved onto the film's clock as
2122
+ // parseFilmEvents moves its events (a render of part of the page)
2123
+ const range = Array.isArray(rawObj.range) ? (rawObj.range as unknown[]) : [];
2124
+ const shift = typeof range[0] === "number" && Number.isFinite(range[0]) ? range[0] : 0;
2125
+ const segs = (Array.isArray(rawObj.segments) ? rawObj.segments : [])
2126
+ .filter(
2127
+ (x): x is FilmSegment =>
2128
+ !!x &&
2129
+ typeof x === "object" &&
2130
+ Number.isFinite((x as FilmSegment).from) &&
2131
+ Number.isFinite((x as FilmSegment).to),
2132
+ )
2133
+ .map((x) => ({ ...x, from: x.from - shift, to: x.to - shift }));
2134
+ const hidden = hiddenCutTimes(ev?.events ?? [], segs);
2135
+ const lifts = liftSpans(segs);
2136
+ // each hard cut: does either side move next to it, does anything cross
2137
+ const seamList = seamsAtCuts(
2138
+ changes.filter((c) => c.kind === "hard cut"),
2139
+ energy,
2140
+ fps,
2141
+ (ev?.events ?? [])
2142
+ .filter((e) => e.kind === "cut")
2143
+ .map((e) => ({ t: e.t, label: e.label ?? "" })),
2144
+ );
2145
+ // the events file is on the page's clock; the film starts at `from` on it
2146
+ const tracks = (rawEvents ? subjectTracks(rawEvents) : []).map((tr) => ({
2147
+ ...tr,
2148
+ samples: tr.samples.map((x) => ({ ...x, t: x.t - (record?.from ?? 0) })),
2149
+ }));
2150
+ const exits = subjectExits(tracks, video.width, video.height, duration);
2151
+ const marks = (ev?.events ?? [])
2152
+ .filter((e) => e.kind === "mark")
2153
+ .map((e) => {
2154
+ const f = Math.round((e.t - t0) * fps);
2155
+ return {
2156
+ t: round3(e.t),
2157
+ label: e.label ?? "",
2158
+ still: stillRanges.some((r) => f >= r.a && f < r.b),
2159
+ nearestCut: cutTimes.length ? nearestOffset(cutTimes, e.t) : null,
2160
+ };
2161
+ });
2162
+
2163
+ // the camera over the film: its zoom against the start, its travel
2164
+ const vw = video.width;
2165
+ const vh = video.height;
2166
+ let zin = 0;
2167
+ let zout = 0;
2168
+ let travel = 0;
2169
+ let readSteps = 0;
2170
+ path.logScale.forEach((v, k) => {
2171
+ if (v == null) return;
2172
+ readSteps++;
2173
+ if (v > 0) zin += v;
2174
+ else zout += v;
2175
+ travel += Math.hypot(path.dx[k] ?? 0, ((path.dy[k] ?? 0) * vh) / vw);
2176
+ });
2177
+
2178
+ // the page: its text over the film's time, its beat sheet as it is now
2179
+ const textEvery = opts.textEvery ?? 0.5;
2180
+ const sampleTimes: number[] = [];
2181
+ for (let k = 0; k * textEvery < duration - 0.5 / fps; k++)
2182
+ sampleTimes.push(round3(k * textEvery));
2183
+ const from = record?.from ?? 0;
2184
+ let pageRead: Awaited<ReturnType<typeof readPageText>> | null = null;
2185
+ let pageNote: string | undefined;
2186
+ if (opts.page && !opts.chromePath) pageNote = "no Chrome to play the page in";
2187
+ else if (opts.page)
2188
+ pageRead = await readPageText({
2189
+ page: opts.page,
2190
+ root: opts.root,
2191
+ chromePath: opts.chromePath!,
2192
+ from,
2193
+ times: sampleTimes,
2194
+ width: record?.width || undefined,
2195
+ height: record?.height || undefined,
2196
+ fallback: { width: video.width, height: video.height },
2197
+ extra: PROVENANCE_PAGE_JS,
2198
+ onConsole: opts.onConsole,
2199
+ }).catch((e: Error) => {
2200
+ // the rest of the probe does not need the page
2201
+ pageNote = `the page could not be played: ${e.message.split("\n")[0]}`;
2202
+ return null;
2203
+ });
2204
+ if (pageRead?.failed.length)
2205
+ pageNote = `the page threw at ${pageRead.failed.length} of ${sampleTimes.length} sample time(s), left out (first at ${pageRead.failed[0]!.t} s: ${pageRead.failed[0]!.error})`;
2206
+ // the page's CSS px as the film's px
2207
+ const k = pageRead ? video.width / pageRead.width : 1;
2208
+ const pageSamples = pageRead?.samples.map((x) => scalePageSample(x, k)) ?? null;
2209
+ const sheetRaw =
2210
+ pageRead && Array.isArray(pageRead.segments) ? pageRead.segments : rawObj.segments;
2211
+ // on the film's clock; a segment wholly outside a film of part of the page is left out
2212
+ const sheet = sheetSegments(sheetRaw)
2213
+ .map((x) => ({ ...x, from: x.from - from, to: x.to - from }))
2214
+ .filter((x) => x.to > 0 && x.from < duration);
2215
+ const frameText =
2216
+ opts.text === false
2217
+ ? null
2218
+ : await readFrameText({
2219
+ ffmpeg,
2220
+ input,
2221
+ times: sampleTimes,
2222
+ width: video.width,
2223
+ height: video.height,
2224
+ });
2225
+ const text = textTimeline(pageSamples, frameText?.frames ?? null, {
2226
+ width: video.width,
2227
+ height: video.height,
2228
+ segments: sheet,
2229
+ every: textEvery,
2230
+ });
2231
+ const segReadings = readSegments(sheet, {
2232
+ duration,
2233
+ fps,
2234
+ t0,
2235
+ energy,
2236
+ stillUnder,
2237
+ cuts: cutTimes,
2238
+ swaps: swapTimes,
2239
+ changes,
2240
+ path,
2241
+ runs,
2242
+ tracks,
2243
+ width: video.width,
2244
+ height: video.height,
2245
+ pageSubjects: pageSamples
2246
+ ? (sel) =>
2247
+ pageSamples.some((x) => sel in x.subjects)
2248
+ ? pageSamples.map((x) => ({ t: x.t, box: x.subjects[sel] ?? null }))
2249
+ : null
2250
+ : undefined,
2251
+ onsets: pcm ? onsets : null,
2252
+ });
2253
+
2254
+ // where the numbers on screen come from: the page's sources as it says
2255
+ // them now (else the events file's), beside components.json's values
2256
+ const provSamples: ProvenanceSample[] | null = pageRead
2257
+ ? pageRead.samples.map((x) => {
2258
+ const e = (x.extra ?? {}) as Partial<ProvenanceSample>;
2259
+ return { t: x.t, items: Array.isArray(e.items) ? e.items : [], sources: e.sources };
2260
+ })
2261
+ : null;
2262
+ const pageSources = provSamples ? pageSourcesOf(provSamples) : null;
2263
+ const sources = pageSources?.sources ?? checkSources(rawObj.sources);
2264
+ const pageDir = opts.page ? pageDirOf(opts.page) : undefined;
2265
+ let served: string | undefined;
2266
+ try {
2267
+ served = opts.page ? resolveFilmPage(opts.page, opts.root).root : undefined;
2268
+ } catch {}
2269
+ const provenance = readProvenance(pageSources?.samples ?? provSamples, {
2270
+ sources,
2271
+ sourcesFrom: pageSources ? "page" : Array.isArray(rawObj.sources) ? "events file" : null,
2272
+ index: componentValueIndex([
2273
+ ...(opts.components ?? []).map((f) => resolve(f)),
2274
+ ...findComponentFiles({ pageDir, root: served, base: resolve(input, ".."), sources }),
2275
+ ]),
2276
+ every: textEvery,
2277
+ ...(pageNote ? { note: pageNote } : !opts.page ? { note: "no page given (--page)" } : {}),
2278
+ });
2279
+
2280
+ // the product's material on screen that was shot on its way (shots.json)
2281
+ const movingMaterial = readMovingMaterial(pageRead?.samples ?? null, pageRead?.root ?? null, {
2282
+ ...(pageNote ? { note: pageNote } : !opts.page ? { note: "no page given (--page)" } : {}),
2283
+ });
2284
+
2285
+ const probe: FilmProbe = {
2286
+ input,
2287
+ duration: round3(duration),
2288
+ fps: round2(fps),
2289
+ t0: round3(t0),
2290
+ size: { width: video.width, height: video.height },
2291
+ read: { width: grey.w, height: grey.h, frames: grey.count },
2292
+ energy: {
2293
+ how: grey.count > 1 ? "measured" : "not measured",
2294
+ bins: eBins,
2295
+ binS,
2296
+ movingShare: round2(moving / Math.max(1, grey.count - 1)),
2297
+ },
2298
+ stills: {
2299
+ how: stillRanges.length ? "measured" : "not detected",
2300
+ under: stillUnder,
2301
+ minS: stillMin,
2302
+ list: stillRanges.map((r) => ({
2303
+ start: round3(frameTime(grey, r.a)),
2304
+ end: round3(frameTime(grey, r.b)),
2305
+ })),
2306
+ share: round2(stillFrames / Math.max(1, grey.count)),
2307
+ },
2308
+ cuts: {
2309
+ how: cutList.length ? "measured" : "not detected",
2310
+ list: cutList,
2311
+ perMin: round1((cutList.length / duration) * 60),
2312
+ density: cutDensity(cutTimes, duration, 5),
2313
+ densityNewPicture: cutDensity(newPictureTimes, duration, 5),
2314
+ newPictureShare: NEW_PICTURE,
2315
+ densityBinS: 5,
2316
+ },
2317
+ shots: {
2318
+ how: "measured",
2319
+ ...shotStats(cutTimes, duration),
2320
+ newPicture: shotStats(newPictureTimes, duration),
2321
+ withSwaps: shotStats(
2322
+ [...cutTimes, ...swapTimes].sort((a, b) => a - b),
2323
+ duration,
2324
+ ),
2325
+ },
2326
+ changes: { how: changes.length ? "estimated" : "not detected", list: changes.map(roundChange) },
2327
+ sound: {
2328
+ how: !pcm ? "not measured" : onsets.length ? "measured" : "not detected",
2329
+ onsets: onsets.length,
2330
+ onsetsPerS: round1(onsets.length / duration),
2331
+ within40: share(0.04),
2332
+ within80: share(0.08),
2333
+ chance40: chanceWithin(onsets, duration, 0.04),
2334
+ chance80: chanceWithin(onsets, duration, 0.08),
2335
+ medianAbsOffset: offs.length ? round3(median(offs.map(Math.abs))) : null,
2336
+ },
2337
+ seams: { how: seamList.length ? "estimated" : "not detected", list: seamList },
2338
+ declaredCuts: {
2339
+ how: !rawEvents ? "not measured" : declared.length ? "measured" : "not detected",
2340
+ file: eventsPath,
2341
+ list: declared.map(round3),
2342
+ // a cut hidden under motion is meant not to show; a jump inside a
2343
+ // declared lift is the layer moving on its own
2344
+ unseen: declared
2345
+ .filter((d) => !cutTimes.some((c) => Math.abs(c - d) <= tol))
2346
+ .filter((d) => !hidden.some((h) => Math.abs(h - d) <= tol))
2347
+ .map(round3),
2348
+ undeclared: rawEvents
2349
+ ? cutTimes.filter(
2350
+ (c) =>
2351
+ !declared.some((d) => Math.abs(c - d) <= tol) &&
2352
+ !hidden.some((h) => Math.abs(h - c) <= tol) &&
2353
+ !lifts.some(([a, b]) => c >= a - tol && c <= b + tol),
2354
+ )
2355
+ : [],
2356
+ },
2357
+ subjects: {
2358
+ how: !tracks.length ? "not measured" : exits.length ? "estimated" : "not detected",
2359
+ tracks: tracks.map((t) => ({ name: t.name, source: t.source, samples: t.samples.length })),
2360
+ exits,
2361
+ },
2362
+ marks: {
2363
+ how: !rawEvents ? "not measured" : marks.length ? "measured" : "not detected",
2364
+ list: marks,
2365
+ },
2366
+ smallSwaps: {
2367
+ how: swaps.length ? "measured" : "not detected",
2368
+ list: swaps.map((w, i) => ({ t: swapTimes[i]!, changed: round2(w.changed) })),
2369
+ perMin: round1((swaps.length / duration) * 60),
2370
+ },
2371
+ camera: {
2372
+ how: !path.t.length ? "not measured" : readSteps ? "estimated" : "not detected",
2373
+ stepS: round3(path.step / fps),
2374
+ read: round2(path.t.length ? readSteps / path.t.length : 0),
2375
+ zoomIn: readSteps ? round3(Math.exp(zin)) : null,
2376
+ zoomOut: readSteps ? round3(Math.exp(zout)) : null,
2377
+ travel: readSteps ? round2(travel) : null,
2378
+ runs,
2379
+ reversals: reversals(runs),
2380
+ backAndForth: backAndForth(runs),
2381
+ repeated: repeatedRuns(runs),
2382
+ },
2383
+ segments: {
2384
+ how: sheet.length ? "measured" : pageRead || rawEvents ? "not detected" : "not measured",
2385
+ source: sheet.length
2386
+ ? pageRead && Array.isArray(pageRead.segments)
2387
+ ? "page"
2388
+ : "events file"
2389
+ : null,
2390
+ list: segReadings,
2391
+ },
2392
+ text: {
2393
+ how: pageSamples ? "measured" : frameText ? "estimated" : "not measured",
2394
+ every: textEvery,
2395
+ page: {
2396
+ how: pageSamples ? "measured" : "not measured",
2397
+ file: opts.page ? resolve(opts.page) : null,
2398
+ ...(pageNote ? { note: pageNote } : {}),
2399
+ },
2400
+ picture: { how: frameText ? "estimated" : "not measured", reader: frameText?.how ?? null },
2401
+ phoneWidth: PHONE_W,
2402
+ phoneScale: round4(PHONE_W / video.width),
2403
+ samples: text.samples,
2404
+ perSecond: textPerSecond(text.samples, duration),
2405
+ overlaps: text.overlaps,
2406
+ },
2407
+ provenance,
2408
+ moving: movingMaterial,
2409
+ };
2410
+
2411
+ await mkdir(outDir, { recursive: true });
2412
+ // before/after thumbnails of each change
2413
+ const thumbDir = join(outDir, "changes");
2414
+ await mkdir(thumbDir, { recursive: true });
2415
+ await writeThumbs(ffmpeg, input, fps, probe, thumbDir);
2416
+
2417
+ const md = join(outDir, "probe.md");
2418
+ const json = join(outDir, "probe.json");
2419
+ await writeFile(md, `${formatFilmProbe(probe)}\n`);
2420
+ await writeFile(
2421
+ json,
2422
+ `${JSON.stringify({
2423
+ ...probe,
2424
+ energyPerFrame: Array.from(energy, round4),
2425
+ cameraPerStep: {
2426
+ t: path.t.map(round3),
2427
+ logScale: path.logScale.map((v) => (v == null ? null : round6(v))),
2428
+ dx: path.dx.map((v) => (v == null ? null : round6(v))),
2429
+ dy: path.dy.map((v) => (v == null ? null : round6(v))),
2430
+ },
2431
+ })}\n`,
2432
+ );
2433
+ let png: string | null = null;
2434
+ let pages: string[] = [];
2435
+ if (opts.chromePath) {
2436
+ png = join(outDir, "probe.png");
2437
+ pages = await drawProbe(probe, {
2438
+ chromePath: opts.chromePath,
2439
+ out: png,
2440
+ energy,
2441
+ onsets,
2442
+ path,
2443
+ every: opts.every ?? defaultSheetEvery(duration),
2444
+ outDir,
2445
+ });
2446
+ }
2447
+ return { png, pages, md, json, probe };
2448
+ }
2449
+
2450
+ const roundChange = (c: PictureChange): PictureChange => ({
2451
+ ...c,
2452
+ t: round3(c.t),
2453
+ changed: round2(c.changed),
2454
+ stays: round2(c.stays),
2455
+ carried: round2(c.carried),
2456
+ background: round2(c.background),
2457
+ shift: c.shift ? { x: round1(c.shift.x), y: round1(c.shift.y) } : null,
2458
+ });
2459
+
2460
+ async function writeThumbs(
2461
+ ffmpeg: string,
2462
+ input: string,
2463
+ fps: number,
2464
+ probe: FilmProbe,
2465
+ dir: string,
2466
+ ): Promise<void> {
2467
+ const jobs: { frame: number; file: string }[] = [];
2468
+ probe.changes.list.forEach((c, i) => {
2469
+ const n = String(i + 1).padStart(3, "0");
2470
+ const before = join(dir, `${n}-before.jpg`);
2471
+ const after = join(dir, `${n}-after.jpg`);
2472
+ c.thumbs = { before: `changes/${basename(before)}`, after: `changes/${basename(after)}` };
2473
+ jobs.push({ frame: c.before, file: before }, { frame: c.after, file: after });
2474
+ });
2475
+ let next = 0;
2476
+ await Promise.all(
2477
+ Array.from({ length: Math.min(6, jobs.length) }, async () => {
2478
+ while (next < jobs.length) {
2479
+ const j = jobs[next++]!;
2480
+ // the first frame at or after a quarter frame before this one's time: this one
2481
+ await runTool(ffmpeg, [
2482
+ "-v",
2483
+ "error",
2484
+ "-ss",
2485
+ String(Math.max(0, probe.t0 + (j.frame - 0.25) / fps)),
2486
+ "-i",
2487
+ input,
2488
+ "-frames:v",
2489
+ "1",
2490
+ "-vf",
2491
+ "scale=480:-2",
2492
+ "-q:v",
2493
+ "4",
2494
+ "-y",
2495
+ j.file,
2496
+ ]).catch(() => {});
2497
+ }
2498
+ }),
2499
+ );
2500
+ for (const c of probe.changes.list)
2501
+ if (c.thumbs && !existsSync(join(dir, basename(c.thumbs.before)))) delete c.thumbs;
2502
+ }
2503
+
2504
+ /** every frame as grey w×h; frames past the stream's end are not invented */
2505
+ export function decodeGrey(
2506
+ ffmpeg: string,
2507
+ file: string,
2508
+ w: number,
2509
+ h: number,
2510
+ fps: number,
2511
+ ): Promise<GreyFrames> {
2512
+ return new Promise((ok, fail) => {
2513
+ const p = spawn(
2514
+ ffmpeg,
2515
+ [
2516
+ "-v",
2517
+ "error",
2518
+ "-i",
2519
+ file,
2520
+ "-an",
2521
+ "-vf",
2522
+ `scale=${w}:${h}:flags=area,format=gray`,
2523
+ "-vsync",
2524
+ "passthrough",
2525
+ "-f",
2526
+ "rawvideo",
2527
+ "-",
2528
+ ],
2529
+ { stdio: ["ignore", "pipe", "pipe"] },
2530
+ );
2531
+ const chunks: Buffer[] = [];
2532
+ let err = "";
2533
+ p.stdout.on("data", (d: Buffer) => chunks.push(d));
2534
+ p.stderr.on("data", (d: Buffer) => {
2535
+ err += d.toString();
2536
+ });
2537
+ p.on("error", fail);
2538
+ p.on("close", (code) => {
2539
+ if (code !== 0)
2540
+ return fail(new Error(`ffmpeg could not read ${file}: ${err.trim().slice(-400)}`));
2541
+ const all = Buffer.concat(chunks);
2542
+ const count = Math.floor(all.length / (w * h));
2543
+ ok({ w, h, fps, count, data: new Uint8Array(all.buffer, all.byteOffset, count * w * h) });
2544
+ });
2545
+ });
2546
+ }
2547
+
2548
+ function decodeSound(ffmpeg: string, file: string): Promise<Float32Array> {
2549
+ return new Promise((ok, fail) => {
2550
+ const p = spawn(
2551
+ ffmpeg,
2552
+ [
2553
+ "-v",
2554
+ "error",
2555
+ "-i",
2556
+ file,
2557
+ "-vn",
2558
+ "-ac",
2559
+ "1",
2560
+ "-ar",
2561
+ String(LISTEN_RATE),
2562
+ "-f",
2563
+ "f32le",
2564
+ "-",
2565
+ ],
2566
+ { stdio: ["ignore", "pipe", "pipe"] },
2567
+ );
2568
+ const chunks: Buffer[] = [];
2569
+ let err = "";
2570
+ p.stdout.on("data", (d: Buffer) => chunks.push(d));
2571
+ p.stderr.on("data", (d: Buffer) => {
2572
+ err += d.toString();
2573
+ });
2574
+ p.on("error", fail);
2575
+ p.on("close", (code) => {
2576
+ if (code !== 0)
2577
+ return fail(new Error(`ffmpeg could not decode ${file}: ${err.trim().slice(-400)}`));
2578
+ const all = Buffer.concat(chunks);
2579
+ ok(new Float32Array(all.buffer.slice(all.byteOffset, all.byteOffset + (all.length & ~3))));
2580
+ });
2581
+ });
2582
+ }
2583
+
2584
+ // --- the report ------------------------------------------------------------------------------
2585
+
2586
+ const fmtT = (t: number) => {
2587
+ if (t < 60) return `${t.toFixed(2)}s`;
2588
+ const m = Math.floor(t / 60);
2589
+ return `${m}:${(t - m * 60).toFixed(2).padStart(5, "0")}`;
2590
+ };
2591
+ const pct = (v: number | null) => (v == null ? "–" : `${Math.round(v * 100)}%`);
2592
+ const ms = (v: number | null) =>
2593
+ v == null ? "–" : `${v >= 0 ? "+" : ""}${Math.round(v * 1000)} ms`;
2594
+
2595
+ export function formatFilmProbe(p: FilmProbe): string {
2596
+ const L: string[] = [];
2597
+ const frameS = 1 / p.fps;
2598
+ L.push(`# film probe — ${basename(p.input)}`);
2599
+ L.push("");
2600
+ L.push(
2601
+ `${p.duration.toFixed(2)} s, ${p.size.width}×${p.size.height} at ${p.fps} fps; read as ${p.read.width}×${p.read.height} grey, ${p.read.frames} frames. Each line says how it was found: measured, estimated, not detected, not measured. Nothing here is a grade or a target.`,
2602
+ );
2603
+ L.push("");
2604
+ L.push("## Picture energy");
2605
+ L.push(
2606
+ `[${p.energy.how}] how much the picture changes each frame (mean grey difference, 0..1). The picture changes in ${pct(p.energy.movingShare)} of frames.`,
2607
+ );
2608
+ L.push(`Mean per second: ${p.energy.bins.map((v) => v.toFixed(3)).join(" ")}`);
2609
+ L.push("");
2610
+ L.push("## No change seen at 192 px");
2611
+ L.push(
2612
+ p.stills.list.length
2613
+ ? `[measured] ${p.stills.list.length} stretch(es) of ≥ ${p.stills.minS} s where no frame changes by ${p.stills.under} or more on the ${p.read.width}-px grey copy, from the frame before or from the frame ¼ s before, ${pct(p.stills.share)} of the film: ${p.stills.list.map((s) => `${fmtT(s.start)}–${fmtT(s.end)}`).join(", ")}. Motion slower than that over ¼ s can still sit under this line — the camera section reads slow motion that this does not.`
2614
+ : `[not detected] no stretch of ≥ ${p.stills.minS} s without a change on the ${p.read.width}-px grey copy`,
2615
+ );
2616
+ L.push("");
2617
+ L.push("## Cuts and shots");
2618
+ if (p.cuts.list.length) {
2619
+ L.push(
2620
+ `[measured] ${p.cuts.list.length} hard cuts (a one-frame jump of the picture), ${p.cuts.perMin} per minute: ${p.cuts.list.map((c) => fmtT(c.t)).join(" ")}`,
2621
+ );
2622
+ } else L.push("[not detected] no hard cut — the picture never jumps in one frame");
2623
+ L.push(
2624
+ p.smallSwaps.list.length
2625
+ ? `[measured] ${p.smallSwaps.list.length} small swap(s) besides — a one-frame jump of 2–12 % of the frame (a word, a number, a panel swapped while the picture holds), ${p.smallSwaps.perMin} per minute: ${p.smallSwaps.list.map((w) => `${fmtT(w.t)} (${pct(w.changed)})`).join(" ")}`
2626
+ : "[not detected] no small swap (a one-frame jump of 2–12 % of the frame)",
2627
+ );
2628
+ const shotLine = (what: string, s: ShotStats) =>
2629
+ `[measured] ${s.lengths.length} ${what}; length median ${s.median} s, shortest ${s.shortest} s, longest ${s.longest} s${s.cv != null ? `, spread (sd/mean) ${s.cv}` : ""}`;
2630
+ L.push(shotLine("stretch(es) between any two hard cuts", p.shots));
2631
+ L.push(`Lengths (s): ${p.shots.lengths.join(" ")}`);
2632
+ if (p.shots.withSwaps.lengths.length !== p.shots.lengths.length) {
2633
+ L.push(shotLine("stretch(es) between any jump, small swaps included", p.shots.withSwaps));
2634
+ L.push(`Lengths (s): ${p.shots.withSwaps.lengths.join(" ")}`);
2635
+ }
2636
+ if (p.cuts.list.length) {
2637
+ L.push(`[measured] cuts per ${p.cuts.densityBinS} s: ${p.cuts.density.join(" ")}`);
2638
+ const np = p.cuts.list.filter((c) => c.changed >= p.cuts.newPictureShare).length;
2639
+ L.push(
2640
+ `Of the cuts, ${np} change ≥ ${pct(p.cuts.newPictureShare)} of the frame (a new picture); per ${p.cuts.densityBinS} s: ${p.cuts.densityNewPicture.join(" ")}${p.shots.newPicture.lengths.length !== p.shots.lengths.length ? `; shots between them: median ${p.shots.newPicture.median} s, longest ${p.shots.newPicture.longest} s` : ""}`,
2641
+ );
2642
+ L.push(
2643
+ "Cut counts and shot lengths describe pace; on their own they have not gone one way with which films people preferred.",
2644
+ );
2645
+ }
2646
+ if (p.declaredCuts.how !== "not measured") {
2647
+ L.push(
2648
+ p.declaredCuts.list.length
2649
+ ? `[measured] the events file declares ${p.declaredCuts.list.length} cut(s); not seen in the picture (±1.5 frames): ${p.declaredCuts.unseen.map(fmtT).join(" ") || "none"}; seen but not declared: ${p.declaredCuts.undeclared.map(fmtT).join(" ") || "none"}`
2650
+ : "[not detected] the events file declares no cuts",
2651
+ );
2652
+ }
2653
+ if (p.seams.list.length) {
2654
+ const none = p.seams.list.filter((x) => x.nothing);
2655
+ const named = (x: SeamSeen) => `${fmtT(x.t)}${x.declared ? ` (declared "${x.declared}")` : ""}`;
2656
+ L.push(
2657
+ none.length
2658
+ ? `[estimated] nothing carried at ${none.map(named).join(", ")} — ${none.length} of ${p.seams.list.length} hard cut(s) where neither side moves in the 0.15 s next to the cut and no part of the picture crosses it (no textured region followed, no shared ground). Launch films people shared kept such cuts for punctuation; most of their seams were carried by a thing or a move (\`skill film craft\`: getting from one scene to the next; \`film gallery --blocks seams\`). To have one followed across, say on the segment that ends there what lives on and name it — \`tl.segment(from, to, { handoff: "…", carry: "#…" })\` — and \`film render\` says whether it was carried (kit/time.js).`
2659
+ : `[estimated] at every one of the ${p.seams.list.length} hard cut(s) one side moves next to the cut or something of the picture crosses it`,
2660
+ );
2661
+ }
2662
+ L.push("");
2663
+ L.push("## Camera");
2664
+ const cam = p.camera;
2665
+ if (cam.how === "estimated") {
2666
+ L.push(
2667
+ `[estimated] the whole picture's scale and shift, read every ${cam.stepS} s on the grey copy to a fraction of a pixel — a camera move, or anything large enough to carry the picture with it; read for ${pct(cam.read)} of the steps (not across cuts or swaps, nor where the picture changes otherwise). Over the film the zooming in adds up to ×${cam.zoomIn}, the zooming out to ×${cam.zoomOut} (sub-pixel steps included); the picture travels ${cam.travel} frame widths in all.`,
2668
+ );
2669
+ const runText = (r: CameraRun) =>
2670
+ r.what === "zoom"
2671
+ ? `zoom ${r.dir} ×${r.amount} ${fmtT(r.start)}–${fmtT(r.end)}`
2672
+ : `moves ${r.dir} ${pct(Math.abs(r.amount))} ${fmtT(r.start)}–${fmtT(r.end)}`;
2673
+ L.push(
2674
+ cam.runs.length
2675
+ ? `Runs (zoom ≥ 1 %/s adding up to ≥ 1.2 %; the picture moving ≥ 2 % of the frame a second, adding up to ≥ 3 %): ${cam.runs.map(runText).join(", ")}`
2676
+ : "[not detected] no run of zoom or movement",
2677
+ );
2678
+ if (cam.reversals.length)
2679
+ L.push(
2680
+ `Turns back (a run the other way within 1 s of the last of its kind), ${cam.reversals.length}: ${cam.reversals.map((r) => `${fmtT(r.t)} ${r.what}`).join(", ")}`,
2681
+ );
2682
+ for (const r of cam.repeated)
2683
+ L.push(
2684
+ `- the same ${r.what === "zoom" ? `zoom ${r.dir}` : `move ${r.dir}`} again and again ${fmtT(r.start)}–${fmtT(r.end)}: ${r.runs} times, one every ${r.every} s, each after a pause (information — a pulse on the beat can be meant)`,
2685
+ );
2686
+ for (const b of cam.backAndForth)
2687
+ L.push(
2688
+ `- ${b.what === "zoom" ? "zoom in and out" : `${b.what === "pan x" ? "side to side" : "up and down"}`} ${fmtT(b.start)}–${fmtT(b.end)}: ${b.runs} runs in a row, each the other way to the one before (information — it can be meant)`,
2689
+ );
2690
+ } else
2691
+ L.push(
2692
+ `[${cam.how}] no motion of the whole picture could be read${cam.how === "not detected" ? " (every step changed in a way no single scale and shift explains)" : ""}`,
2693
+ );
2694
+ L.push("");
2695
+ L.push("## Cuts against the sound");
2696
+ if (p.sound.how === "not measured") L.push("[not measured] the film has no sound");
2697
+ else if (!p.sound.onsets) L.push("[not detected] no onsets in the sound");
2698
+ else if (!p.cuts.list.length)
2699
+ L.push(
2700
+ `[measured] ${p.sound.onsets} onsets (${p.sound.onsetsPerS}/s); no cuts to set against them`,
2701
+ );
2702
+ else {
2703
+ const off = p.cuts.list.filter(
2704
+ (c) => c.nearestOnset != null && Math.abs(c.nearestOnset) > frameS + 1e-6,
2705
+ ).length;
2706
+ L.push(
2707
+ `[measured] median distance from a cut to the nearest onset ${ms(p.sound.medianAbsOffset)}; ${off} of ${p.cuts.list.length} cut(s) sit more than one frame (${Math.round(frameS * 1000)} ms) from any onset (${p.sound.onsets} onsets, ${p.sound.onsetsPerS}/s, as \`film listen\` finds them).`,
2708
+ );
2709
+ L.push(
2710
+ `Offset of each cut to its nearest onset (− = the onset comes first): ${p.cuts.list.map((c) => `${fmtT(c.t)} ${ms(c.nearestOnset)}`).join(", ")}`,
2711
+ );
2712
+ L.push(
2713
+ `Cuts with an onset within 40 ms: ${pct(p.sound.within40)} (a cut at a random time: ${pct(p.sound.chance40)}); within 80 ms: ${pct(p.sound.within80)} (random: ${pct(p.sound.chance80)}). Cutting on onsets is one way to cut; a film can cut across them on purpose.`,
2714
+ );
2715
+ }
2716
+ L.push("");
2717
+ L.push("## Beat sheet");
2718
+ if (p.segments.how === "not measured")
2719
+ L.push(
2720
+ "[not measured] no beat sheet: none in an events file and no page given (kit/time.js `tl.segment(from, to, { hold, handoff, subject, sound })`)",
2721
+ );
2722
+ else if (!p.segments.list.length) L.push("[not detected] the page declares no segments");
2723
+ else {
2724
+ L.push(
2725
+ `[measured] ${p.segments.list.length} segment(s) from the ${p.segments.source}, each set beside what the picture did. The sheet is yours; a difference is information, not an error.`,
2726
+ );
2727
+ for (const s of p.segments.list) L.push(...formatSegment(s, p));
2728
+ }
2729
+ L.push("");
2730
+ L.push(...formatText(p));
2731
+ L.push("");
2732
+ L.push(
2733
+ ...formatProvenance(p.provenance, p.text.page.file ? pageDirOf(p.text.page.file) : undefined),
2734
+ );
2735
+ L.push("");
2736
+ L.push(...formatMovingMaterial(p.moving));
2737
+ L.push("");
2738
+ L.push("## Declared subjects");
2739
+ if (p.subjects.how === "not measured")
2740
+ L.push(
2741
+ '[not measured] the events file declares no subject positions (curves `<name>.x`/`<name>.y`, optional `.w`/`.h`, or events of kind "subject" with x, y, label)',
2742
+ );
2743
+ else {
2744
+ L.push(
2745
+ `[${p.subjects.how}] from the positions the page declared (stage px, taken as the film's ${p.size.width}×${p.size.height}), not seen in the picture: ${p.subjects.tracks.map((t) => `${t.name} (${t.source}, ${t.samples} samples)`).join(", ")}`,
2746
+ );
2747
+ if (!p.subjects.exits.length) L.push("No declared subject leaves the frame.");
2748
+ for (const e of p.subjects.exits)
2749
+ L.push(`- ${e.name}: ${e.how} past the ${e.edge} edge ${fmtT(e.start)}–${fmtT(e.end)}`);
2750
+ }
2751
+ if (p.marks.how !== "not measured") {
2752
+ L.push("");
2753
+ L.push("## Named moments");
2754
+ if (!p.marks.list.length)
2755
+ L.push('[not detected] the events file names no moments (kind "mark")');
2756
+ for (const m of p.marks.list)
2757
+ L.push(
2758
+ `- [measured] ${fmtT(m.t)} ${m.label || "(unnamed)"}: ${m.still ? "no change seen at 192 px" : "picture changing"}${m.nearestCut != null ? `, nearest cut ${ms(m.nearestCut)}` : ""}`,
2759
+ );
2760
+ }
2761
+ L.push("");
2762
+ L.push("## Big changes of picture");
2763
+ L.push(
2764
+ "[estimated] every cut, and every moment where ≥ 40 % of the frame differs between ¼ s before and ¼ s after. What crosses each: carried = textured regions covering ≥ 10 % of the frame stay in place or are followed frame to frame into the new picture; background only = less than that, but ≥ 25 % of the frame is flat and keeps its grey; nothing carried = neither. The share numbers are the frame's blocks (8×8 on the grey copy). Thumbnails: changes/NNN-before.jpg, -after.jpg.",
2765
+ );
2766
+ if (!p.changes.list.length) L.push("[not detected] no big change of picture");
2767
+ p.changes.list.forEach((c, i) => {
2768
+ const across = c.kind === "hard cut" ? ` — across it: ${c.across}` : "";
2769
+ const shift =
2770
+ c.shift &&
2771
+ c.carried >= CARRIED_SHARE &&
2772
+ (Math.abs(c.shift.x) >= 1 || Math.abs(c.shift.y) >= 1)
2773
+ ? `, carried part moves ${c.shift.x > 0 ? "+" : ""}${c.shift.x}% x ${c.shift.y > 0 ? "+" : ""}${c.shift.y}% y`
2774
+ : "";
2775
+ const span =
2776
+ c.after - c.before > 1 ? ` (over ${((c.after - c.before) / p.fps).toFixed(2)} s)` : "";
2777
+ L.push(
2778
+ `${String(i + 1).padStart(3)}. ${fmtT(c.t)} ${c.kind}${across}${span}: changed ${pct(c.changed)}, stays ${pct(c.stays)}, carried ${pct(c.carried)}, background kept ${pct(c.background)}${shift}`,
2779
+ );
2780
+ });
2781
+ if (p.changes.list.length) {
2782
+ const counts = new Map<string, number>();
2783
+ for (const c of p.changes.list) counts.set(c.kind, (counts.get(c.kind) ?? 0) + 1);
2784
+ L.push(`Counts: ${[...counts].map(([k, n]) => `${k} ${n}`).join(", ")}`);
2785
+ }
2786
+ return L.join("\n");
2787
+ }
2788
+
2789
+ function formatSegment(s: SegmentReading, p: FilmProbe): string[] {
2790
+ const L: string[] = [];
2791
+ const said = [
2792
+ s.label ? `"${s.label}"` : "",
2793
+ s.hold ? "hold" : "",
2794
+ s.handoff ? `handoff: ${s.handoff}` : "",
2795
+ s.subject ? `subject: ${s.subject}` : "",
2796
+ s.sound ? `sound: ${s.sound}` : "",
2797
+ ].filter(Boolean);
2798
+ L.push(`- ${fmtT(s.from)}–${fmtT(s.to)}${said.length ? ` ${said.join(" · ")}` : ""}`);
2799
+ const cam = s.camera;
2800
+ const camText = cam
2801
+ ? Math.abs(cam.zoom - 1) < 0.003 && Math.abs(cam.x) < 0.003 && Math.abs(cam.y) < 0.003
2802
+ ? s.runs.length
2803
+ ? "the picture ends at the scale and place it started"
2804
+ : "no camera motion read (under ×1.003 and 0.3 % of the frame)"
2805
+ : `the picture ${Math.abs(cam.zoom - 1) >= 0.003 ? `scales ×${cam.zoom}` : "keeps its scale"}${Math.abs(cam.x) >= 0.003 || Math.abs(cam.y) >= 0.003 ? `, moves ${signed(cam.x)} x ${signed(cam.y)} y of the frame` : ""}`
2806
+ : "camera not read";
2807
+ const where = s.movingSpans.length
2808
+ ? ` (changing ${s.movingSpans
2809
+ .slice(0, 6)
2810
+ .map((m) => `${fmtT(m.start)}–${fmtT(m.end)}`)
2811
+ .join(", ")}${s.movingSpans.length > 6 ? ", …" : ""})`
2812
+ : "";
2813
+ const jumps = [
2814
+ s.cuts.length ? `${s.cuts.length} cut(s) ${s.cuts.map(fmtT).join(" ")}` : "",
2815
+ s.swaps.length ? `${s.swaps.length} small swap(s)` : "",
2816
+ ]
2817
+ .filter(Boolean)
2818
+ .join(", ");
2819
+ // the runs too: a zoom in and back out sums to no zoom over the segment
2820
+ const runs = s.runs.length
2821
+ ? ` — runs: ${s.runs.map((r) => (r.what === "zoom" ? `zoom ${r.dir} ×${r.amount}` : `moves ${r.dir}`)).join(", ")}`
2822
+ : "";
2823
+ if (s.hold) {
2824
+ const still = s.moving === 0 && !s.cuts.length && !s.swaps.length;
2825
+ const camStill =
2826
+ !s.runs.length &&
2827
+ (!cam ||
2828
+ (Math.abs(cam.zoom - 1) < 0.003 && Math.abs(cam.x) < 0.003 && Math.abs(cam.y) < 0.003));
2829
+ L.push(
2830
+ ` written to hold${still && camStill ? ":" : " —"} [measured] ${
2831
+ still
2832
+ ? `no change seen at ${p.read.width} px`
2833
+ : `the picture still changes in ${pct(s.moving)} of its frames${where}${jumps ? `; ${jumps}` : ""}`
2834
+ }; [estimated] ${camText}${runs}`,
2835
+ );
2836
+ } else
2837
+ L.push(
2838
+ ` [measured] the picture changes in ${pct(s.moving)} of its frames${jumps ? `; ${jumps}` : ""}; [estimated] ${camText}${runs}`,
2839
+ );
2840
+ if (s.subjectSeen) {
2841
+ const ss = s.subjectSeen;
2842
+ const src =
2843
+ ss.source === "page" ? "found on the page" : ss.source ? `declared ${ss.source}` : "";
2844
+ L.push(
2845
+ ss.how === "not measured"
2846
+ ? ` subject ${s.subject}: [not measured] no element on the page and no declared track has that name${p.text.page.how === "not measured" ? " (give the page to look it up)" : ""}`
2847
+ : ss.out.length
2848
+ ? ` subject ${s.subject} [${ss.how}, ${src}]: ${ss.out.map((o) => `${o.how}${o.edge ? ` past the ${o.edge} edge` : ""} ${fmtT(o.start)}–${fmtT(o.end)}`).join(", ")} (information — leaving can be meant)`
2849
+ : ` subject ${s.subject} [${ss.how === "not detected" ? (ss.source === "page" ? "measured" : "estimated") : ss.how}, ${src}]: stays in the frame`,
2850
+ );
2851
+ }
2852
+ if (s.handoff && s.handoffSeen) {
2853
+ const h = s.handoffSeen;
2854
+ L.push(
2855
+ ` handoff written: ${s.handoff} · seen at ${fmtT(s.to)} [${h.how}]: ${h.kind}${h.at != null ? ` at ${fmtT(h.at)}` : ""}${h.across ? `, across it: ${h.across}` : ""}${h.nearestOnset != null ? `; nearest onset ${ms(h.nearestOnset)}` : ""}`,
2856
+ );
2857
+ if (
2858
+ h.kind === "hard cut" &&
2859
+ !SEAM_KINDS.test(s.handoff.trim()) &&
2860
+ !handoffIs(s, "hidden-cut") &&
2861
+ !handoffIs(s, "lift")
2862
+ )
2863
+ L.push(
2864
+ ` (written in words, so nothing performs it: a seam's kind — curve, whip, depth, inverse, push, dip — on this handoff is performed by \`scenes(…, { tl, seams })\`, kit/time.js; \`film gallery --blocks seams\` draws each)`,
2865
+ );
2866
+ }
2867
+ return L;
2868
+ }
2869
+
2870
+ function formatText(p: FilmProbe): string[] {
2871
+ const L: string[] = [];
2872
+ const T = p.text;
2873
+ const ph = (px: number | null) =>
2874
+ px == null ? "–" : `${round1(px)} (${round1(px * T.phoneScale)})`;
2875
+ L.push("## Text at film scale");
2876
+ if (T.how === "not measured") {
2877
+ L.push(
2878
+ "[not measured] no text read: give the page (`film probe <film.mp4> --page film/`) and leave the frames' text reading on",
2879
+ );
2880
+ return L;
2881
+ }
2882
+ L.push(
2883
+ `[${T.how}] how much of the frame is text and how big it is drawn, every ${T.every} s. Sizes are film px (${p.size.width} wide), and in brackets as on a phone showing the film ${T.phoneWidth} px wide (×${T.phoneScale}; for scale, a phone's body text is about 17 px). Information, not a limit.`,
2884
+ );
2885
+ L.push(
2886
+ T.page.how === "measured"
2887
+ ? `Page text [measured]: read on the film clock where its glyphs are drawn, at the size drawn — the film's own text apart from the product's text in saved screens (iframes); its share counts its line boxes.${T.page.note ? ` Note: ${T.page.note}.` : ""}`
2888
+ : `Page text [not measured]: ${T.page.note ?? "no page given (--page <film folder>)"}`,
2889
+ );
2890
+ L.push(
2891
+ T.picture.reader === "ocr"
2892
+ ? `Text in pictures [estimated]: the frames read by the system's text recognizer${T.page.how === "measured" ? " — lines that are not page text" : " (all text: no page given to tell page text apart)"}; a size is the line's height as read (close to the font size); very small or stylised text can be missed.`
2893
+ : T.picture.reader === "edges"
2894
+ ? "Text in pictures [estimated]: an edge count of text-like cells — a share only, no size; photos and fine texture count too."
2895
+ : "Text in pictures [not measured]: the frames were not read.",
2896
+ );
2897
+ const S = T.samples;
2898
+ const withText = S.filter((s) => s.share > 0.002).length;
2899
+ const shares = S.map((s) => s.share);
2900
+ const busiest = [...S].sort((a, b) => b.share - a.share)[0];
2901
+ const mostChars = [...S].filter((s) => s.chars != null).sort((a, b) => b.chars! - a.chars!)[0];
2902
+ const smallest = [...S]
2903
+ .filter((s) => s.smallest)
2904
+ .sort((a, b) => a.smallest!.px - b.smallest!.px)[0];
2905
+ const meds = S.map((s) => s.median).filter((v): v is number => v != null);
2906
+ L.push(
2907
+ `Over the film: text on screen in ${withText} of ${S.length} samples; share of the frame median ${pct(median(shares))}, most ${pct(busiest?.share ?? 0)} at ${busiest ? fmtT(busiest.t) : "–"}${busiest && busiest.own != null ? ` (the film's own ${pct(busiest.own)}, the product's ${pct(busiest.product)}${busiest.picture != null ? `, in pictures ${pct(busiest.picture)}` : ""})` : busiest?.picture != null ? "" : ""}.`,
2908
+ );
2909
+ if (mostChars)
2910
+ L.push(
2911
+ `Most characters on screen at once: ${mostChars.chars} at ${fmtT(mostChars.t)}${mostChars.ownChars != null ? ` (own ${mostChars.ownChars}, product ${mostChars.productChars}${mostChars.pictureChars != null ? `, in pictures ${mostChars.pictureChars}` : ""})` : ""}; median over the samples ${median(S.map((s) => s.chars ?? 0))}.`,
2912
+ );
2913
+ if (smallest?.smallest)
2914
+ L.push(
2915
+ `Smallest text: ${ph(smallest.smallest.px)} px at ${fmtT(smallest.t)} (${smallest.smallest.from === "page" ? "page, measured" : "in a picture, estimated"})${smallest.smallest.text ? ` — ${smallest.smallest.text}` : ""}; median size over the samples ${ph(meds.length ? median(meds) : null)} px.`,
2916
+ );
2917
+ // the product's words are told from the film's own only with the page
2918
+ const parts =
2919
+ T.page.how === "measured"
2920
+ ? productTextSpans(S, T.phoneScale, T.every, { pictures: T.picture.reader === "ocr" })
2921
+ : [];
2922
+ if (parts.length)
2923
+ L.push(
2924
+ `Where the product's own words (saved screens${T.picture.reader === "ocr" ? ", text in pictures" : ""}) are most of the frame's text, or their median size reads under ${PHONE_SMALL_PX} px on the phone: ${parts
2925
+ .slice(0, 12)
2926
+ .map(
2927
+ (s) =>
2928
+ `${fmtT(s.from)}–${fmtT(s.to)} (up to ${pct(s.productShare)} of the text${s.phoneMedian != null ? `; their median down to ${s.phoneMedian} px on the phone` : ""})`,
2929
+ )
2930
+ .join(
2931
+ ", ",
2932
+ )}${parts.length > 12 ? `, … ${parts.length - 12} more` : ""}. What acts on part of a screen: \`lift\` (one part as a layer of its own) and \`isolate\` (the rest faded) in kit/media.js, \`cam.frame\` (the camera on one box) in kit/camera.js — \`skill film material\`. Information, not a target.`,
2933
+ );
2934
+ const ps = T.perSecond;
2935
+ L.push(
2936
+ `Per second, share of the frame that is text: ${ps.map((b) => Math.round(b.share * 100)).join(" ")} (%)`,
2937
+ );
2938
+ if (ps.some((b) => b.chars != null))
2939
+ L.push(`Per second, most characters at once: ${ps.map((b) => b.chars ?? "–").join(" ")}`);
2940
+ if (ps.some((b) => b.median != null)) {
2941
+ L.push(
2942
+ `Per second, median text size, film px: ${ps.map((b) => (b.median == null ? "–" : Math.round(b.median))).join(" ")}`,
2943
+ );
2944
+ L.push(
2945
+ `Per second, median text size on the phone, px: ${ps.map((b) => (b.median == null ? "–" : round1(b.median * T.phoneScale))).join(" ")}`,
2946
+ );
2947
+ L.push(
2948
+ `Per second, smallest text, film px: ${ps.map((b) => (b.smallest == null ? "–" : Math.round(b.smallest))).join(" ")}`,
2949
+ );
2950
+ }
2951
+ if (T.page.how === "measured")
2952
+ L.push(
2953
+ T.overlaps.length
2954
+ ? `The film's own text over something else [measured on the page; text in pictures estimated]: ${T.overlaps
2955
+ .slice(0, 40)
2956
+ .map((o) => `${o.text} over ${o.over} ${fmtT(o.from)}–${fmtT(o.to)}`)
2957
+ .join(
2958
+ "; ",
2959
+ )}${T.overlaps.length > 40 ? `; … ${T.overlaps.length - 40} more in probe.json` : ""}`
2960
+ : "[not detected] the film's own text never sits over pictures, the product's text, text in pictures or a segment's subject",
2961
+ );
2962
+ return L;
2963
+ }
2964
+
2965
+ const signed = (v: number) => `${v >= 0 ? "+" : "−"}${Math.round(Math.abs(v) * 1000) / 10}%`;
2966
+
2967
+ // --- the picture -----------------------------------------------------------------------------
2968
+
2969
+ // the same ruler as `film sheet` and `film listen`: the sheet's width, a label
2970
+ // gutter on the left, the film's time across the rest
2971
+ const GUTTER = 120;
2972
+ const PAD = 6;
2973
+ const sheetWidth = (w: number, h: number) => {
2974
+ const landscape = w >= h;
2975
+ const columns = landscape ? 6 : 10;
2976
+ const tileW = landscape ? 480 : 216;
2977
+ return columns * tileW + (columns + 1) * 6;
2978
+ };
2979
+ const defaultSheetEvery = (duration: number) => Math.max(0.25, Math.round((duration / 48) * 4) / 4);
2980
+ function sheetFrameTimes(duration: number, every: number, fps: number): number[] {
2981
+ const last = Math.max(0, duration - 1.5 / fps);
2982
+ const times = Array.from(
2983
+ { length: Math.floor(last / every) + 1 },
2984
+ (_, i) => Math.round(i * every * 1000) / 1000,
2985
+ );
2986
+ if (last - times[times.length - 1]! > every / 2) times.push(Math.round(last * 1000) / 1000);
2987
+ return times;
2988
+ }
2989
+
2990
+ const KIND_COLOR: Record<ChangeKind, string> = {
2991
+ "hard cut": "#e03131",
2992
+ carried: "#2f9e44",
2993
+ "background only": "#f08c00",
2994
+ "nothing carried": "#5c7cfa",
2995
+ };
2996
+
2997
+ async function drawProbe(
2998
+ p: FilmProbe,
2999
+ o: {
3000
+ chromePath: string;
3001
+ out: string;
3002
+ energy: Float32Array;
3003
+ onsets: number[];
3004
+ path: CameraPath;
3005
+ every: number;
3006
+ outDir: string;
3007
+ },
3008
+ ): Promise<string[]> {
3009
+ const D = p.duration;
3010
+ const width = sheetWidth(p.size.width, p.size.height);
3011
+ const W = width - GUTTER - PAD;
3012
+ const x = (t: number) => round1((Math.max(0, Math.min(D, t)) / D) * W);
3013
+ const rows: { label: string; h: number; svg: string }[] = [];
3014
+ const esc = (s: string) => s.replace(/[&<>"]/g, (c) => `&#${c.charCodeAt(0)};`);
3015
+
3016
+ const sheetTimes = sheetFrameTimes(D, o.every, p.fps);
3017
+ const labelEvery = Math.max(1, Math.ceil((sheetTimes.length * 46) / W));
3018
+ rows.push({
3019
+ label: "sheet times",
3020
+ h: 26,
3021
+ svg: sheetTimes
3022
+ .map(
3023
+ (t, i) =>
3024
+ `<line x1="${x(t)}" x2="${x(t)}" y1="${i % labelEvery ? 18 : 12}" y2="26" stroke="#555"/>` +
3025
+ (i % labelEvery
3026
+ ? ""
3027
+ : `<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>`),
3028
+ )
3029
+ .join(""),
3030
+ });
3031
+ // energy, the max of each column, on a square-root scale so small motion shows
3032
+ {
3033
+ const H = 110;
3034
+ const n = o.energy.length;
3035
+ const cols = Math.max(1, Math.floor(W));
3036
+ const peak = Math.max(1e-6, ...o.energy);
3037
+ let pts = `0,${H} `;
3038
+ for (let c = 0; c < cols; c++) {
3039
+ const a = Math.floor((c / cols) * n);
3040
+ const b = Math.max(a + 1, Math.floor(((c + 1) / cols) * n));
3041
+ let v = 0;
3042
+ for (let i = a; i < Math.min(n, b); i++) v = Math.max(v, o.energy[i]!);
3043
+ pts += `${c},${round1(H - Math.sqrt(v / peak) * (H - 6))} `;
3044
+ }
3045
+ pts += `${cols},${H}`;
3046
+ const stills = p.stills.list
3047
+ .map(
3048
+ (s) =>
3049
+ `<rect x="${x(s.start)}" y="0" width="${Math.max(1, x(s.end) - x(s.start))}" height="${H}" fill="#74c0fc" opacity="0.35"/>`,
3050
+ )
3051
+ .join("");
3052
+ rows.push({
3053
+ label: `energy<br><small>change/frame, √<br>blue: still<br>≥ ${p.stills.minS} s</small>`,
3054
+ h: H,
3055
+ svg: `${stills}<polygon points="${pts}" fill="#495057" opacity="0.85"/>`,
3056
+ });
3057
+ }
3058
+ // shots
3059
+ rows.push({
3060
+ label: `shots<br><small>any cut: ${p.shots.lengths.length}<br>new pic.: ${p.shots.newPicture.lengths.length}<br><span style="color:#f08c00">| small swap</span></small>`,
3061
+ h: 58,
3062
+ svg: (() => {
3063
+ let t = 0;
3064
+ const lower = p.shots.newPicture.lengths
3065
+ .map((len, i) => {
3066
+ const a = x(t);
3067
+ const b = x(t + len);
3068
+ t += len;
3069
+ return `<rect x="${a}" y="29" width="${Math.max(1, b - a - 1)}" height="11" fill="${i % 2 ? "#adb5bd" : "#ced4da"}"/>`;
3070
+ })
3071
+ .join("");
3072
+ t = 0;
3073
+ const swaps = p.smallSwaps.list
3074
+ .map(
3075
+ (w) =>
3076
+ `<line x1="${x(w.t)}" x2="${x(w.t)}" y1="0" y2="27" stroke="#f08c00" stroke-width="1.5"/>`,
3077
+ )
3078
+ .join("");
3079
+ return (
3080
+ lower +
3081
+ swaps +
3082
+ p.shots.lengths
3083
+ .map((len, i) => {
3084
+ const a = x(t);
3085
+ const b = x(t + len);
3086
+ t += len;
3087
+ return (
3088
+ `<rect x="${a}" y="3" width="${Math.max(1, b - a - 1)}" height="22" fill="${i % 2 ? "#dee2e6" : "#f1f3f5"}"/>` +
3089
+ (b - a > 30
3090
+ ? `<text x="${a + 3}" y="18" class="s">${len.toFixed(len < 10 ? 2 : 1)}</text>`
3091
+ : "")
3092
+ );
3093
+ })
3094
+ .join("")
3095
+ );
3096
+ })(),
3097
+ });
3098
+ // cut density per 5 s
3099
+ {
3100
+ const H = 60;
3101
+ const max = Math.max(1, ...p.cuts.density);
3102
+ const bs = p.cuts.densityBinS;
3103
+ rows.push({
3104
+ label: `cuts / ${bs} s<br><small>light: all<br>dark: new picture</small>`,
3105
+ h: H,
3106
+ svg: p.cuts.density
3107
+ .map((n, i) => {
3108
+ const a = x(i * bs);
3109
+ const b = x(Math.min(D, (i + 1) * bs));
3110
+ const hh = round1((n / max) * (H - 16));
3111
+ const nn = p.cuts.densityNewPicture[i] ?? 0;
3112
+ const hn = round1((nn / max) * (H - 16));
3113
+ return `<rect x="${a + 1}" y="${H - hh}" width="${Math.max(1, b - a - 2)}" height="${hh}" fill="#e03131" opacity="0.3"/><rect x="${a + 1}" y="${H - hn}" width="${Math.max(1, b - a - 2)}" height="${hn}" fill="#e03131" opacity="0.7"/><text x="${a + 4}" y="${H - hh - 3}" class="s">${n === nn ? n : `${n} (${nn})`}</text>`;
3114
+ })
3115
+ .join(""),
3116
+ });
3117
+ }
3118
+ // big changes by kind
3119
+ {
3120
+ const H = 36;
3121
+ rows.push({
3122
+ label: `changes<br><small style="line-height:1.1">${(Object.keys(KIND_COLOR) as ChangeKind[]).map((k) => `<span style="color:${KIND_COLOR[k]}">${k}</span>`).join("<br>")}</small>`,
3123
+ h: Math.max(H, 72),
3124
+ svg: p.changes.list
3125
+ .map((c, i) => {
3126
+ const a = x(p.t0 + c.before / p.fps);
3127
+ const b = x(p.t0 + c.after / p.fps);
3128
+ return `<rect x="${a}" y="4" width="${Math.max(2, b - a)}" height="18" fill="${KIND_COLOR[c.kind]}"/><text x="${a}" y="36" class="s">${i + 1}</text>`;
3129
+ })
3130
+ .join(""),
3131
+ });
3132
+ }
3133
+ // the camera: the picture's scale against the start (a log scale), its
3134
+ // runs, and where a run turns back
3135
+ if (p.camera.how === "estimated") {
3136
+ const H = 84;
3137
+ const path = o.path;
3138
+ let cum = 0;
3139
+ const pts: [number, number][] = [];
3140
+ path.t.forEach((t, k) => {
3141
+ cum += path.logScale[k] ?? 0;
3142
+ pts.push([t, cum]);
3143
+ });
3144
+ const lo = Math.min(0, ...pts.map((q) => q[1]));
3145
+ const hi = Math.max(0, ...pts.map((q) => q[1]));
3146
+ const span = Math.max(Math.log(1.05), hi - lo);
3147
+ const y = (v: number) => round1(H - 8 - ((v - lo) / span) * (H - 16));
3148
+ const line = pts.map(([t, v]) => `${x(t)},${y(v)}`).join(" ");
3149
+ const runs = p.camera.runs
3150
+ .map((r) => {
3151
+ const col = r.what === "zoom" ? (r.dir === "in" ? "#2f9e44" : "#9c36b5") : "#868e96";
3152
+ const yy = r.what === "zoom" ? 2 : r.what === "pan x" ? H - 6 : H - 3;
3153
+ return `<rect x="${x(r.start)}" y="${yy}" width="${Math.max(1, x(r.end) - x(r.start))}" height="3" fill="${col}"/>`;
3154
+ })
3155
+ .join("");
3156
+ const turns = p.camera.reversals
3157
+ .map(
3158
+ (r) =>
3159
+ `<line x1="${x(r.t)}" x2="${x(r.t)}" y1="0" y2="${H}" stroke="#e8590c" stroke-width="1.5" stroke-dasharray="3 2"/>`,
3160
+ )
3161
+ .join("");
3162
+ const rep = p.camera.repeated
3163
+ .map(
3164
+ (b) =>
3165
+ `<rect x="${x(b.start)}" y="0" width="${Math.max(1, x(b.end) - x(b.start))}" height="${H}" fill="#f59f00" opacity="0.15"/>`,
3166
+ )
3167
+ .join("");
3168
+ const bf = p.camera.backAndForth
3169
+ .map(
3170
+ (b) =>
3171
+ `<rect x="${x(b.start)}" y="0" width="${Math.max(1, x(b.end) - x(b.start))}" height="${H}" fill="#e8590c" opacity="0.12"/>`,
3172
+ )
3173
+ .join("");
3174
+ rows.push({
3175
+ label: `camera<br><small>summed scale<br><span style="color:#2f9e44">in</span>/<span style="color:#9c36b5">out</span>, grey: moves<br><span style="color:#e8590c">┆turn</span> <span style="color:#f59f00">▒repeat</span></small>`,
3176
+ h: H,
3177
+ svg: `${rep}${bf}<line x1="0" x2="${W}" y1="${y(0)}" y2="${y(0)}" stroke="#ced4da"/><polyline points="${line}" fill="none" stroke="#1971c2" stroke-width="1.5"/>${runs}${turns}<text x="2" y="10" class="s">×${round3(Math.exp(hi))}</text><text x="2" y="${H - 1}" class="s">×${round3(Math.exp(lo))}</text>`,
3178
+ });
3179
+ }
3180
+ // onsets and the cuts' offsets
3181
+ if (p.sound.how !== "not measured") {
3182
+ const H = 52;
3183
+ const ticks = o.onsets
3184
+ .map((t) => `<line x1="${x(t)}" x2="${x(t)}" y1="${H - 8}" y2="${H}" stroke="#d9480f"/>`)
3185
+ .join("");
3186
+ const cuts = p.cuts.list
3187
+ .map((c) => {
3188
+ const near = c.nearestOnset != null && Math.abs(c.nearestOnset) <= 0.04;
3189
+ return `<line x1="${x(c.t)}" x2="${x(c.t)}" y1="2" y2="${H - 10}" stroke="#e03131" stroke-width="${near ? 2.5 : 1}"${near ? "" : ' stroke-dasharray="2 2"'}/>`;
3190
+ })
3191
+ .join("");
3192
+ rows.push({
3193
+ label: `cuts × onsets<br><small>median ${ms(p.sound.medianAbsOffset)}<br>${pct(p.sound.within40)} ≤40ms (chance ${pct(p.sound.chance40)})</small>`,
3194
+ h: H,
3195
+ svg: cuts + ticks,
3196
+ });
3197
+ }
3198
+ // the beat sheet
3199
+ if (p.segments.list.length) {
3200
+ const H = 34;
3201
+ rows.push({
3202
+ label: `segments<br><small>blue: written to hold<br>▸ handoff</small>`,
3203
+ h: H,
3204
+ svg: p.segments.list
3205
+ .map((s, i) => {
3206
+ const a = x(s.from);
3207
+ const b = x(s.to);
3208
+ const moved = s.hold && (s.moving > 0 || s.cuts.length || s.swaps.length);
3209
+ return (
3210
+ `<rect x="${a}" y="${i % 2 ? 12 : 3}" width="${Math.max(1, b - a - 1)}" height="14" fill="${s.hold ? "#a5d8ff" : "#e9ecef"}" stroke="${moved ? "#e8590c" : "#adb5bd"}"/>` +
3211
+ (b - a > 24
3212
+ ? `<text x="${a + 3}" y="${i % 2 ? 23 : 14}" class="s">${esc((s.label ?? "").slice(0, Math.floor((b - a) / 6)))}</text>`
3213
+ : "") +
3214
+ (s.handoff
3215
+ ? `<text x="${b - 4}" y="${H - 1}" class="s">▸${esc(s.handoff.slice(0, 8))}</text>`
3216
+ : "")
3217
+ );
3218
+ })
3219
+ .join(""),
3220
+ });
3221
+ }
3222
+ // text: the share of the frame, stacked by where it is; the median size on a phone
3223
+ if (p.text.samples.length) {
3224
+ const H = 100;
3225
+ const S = p.text.samples;
3226
+ const top = Math.max(0.1, ...S.map((s) => s.share));
3227
+ const bw = Math.max(1, (W / p.duration) * p.text.every - 1);
3228
+ const hgt = (v: number) => (v / top) * (H - 26);
3229
+ const bars = S.map((s) => {
3230
+ const own = s.own ?? 0;
3231
+ const prod = s.product ?? 0;
3232
+ const pic = s.picture ?? (s.own == null ? s.share : 0);
3233
+ let yy = H - 12;
3234
+ let out = "";
3235
+ for (const [v, col] of [
3236
+ [own, "#1864ab"],
3237
+ [prod, "#74c0fc"],
3238
+ [pic, "#ffa94d"],
3239
+ ] as const) {
3240
+ const hh = hgt(v);
3241
+ if (hh > 0.2)
3242
+ out += `<rect x="${x(s.t)}" y="${round1(yy - hh)}" width="${round1(bw)}" height="${round1(hh)}" fill="${col}"/>`;
3243
+ yy -= hh;
3244
+ }
3245
+ return out;
3246
+ }).join("");
3247
+ const medLine = S.filter((s) => s.median != null)
3248
+ .map(
3249
+ (s) =>
3250
+ `${x(s.t + p.text.every / 2)},${round1(H - 12 - Math.min(1, (s.median! * p.text.phoneScale) / 20) * (H - 26))}`,
3251
+ )
3252
+ .join(" ");
3253
+ const every = Math.max(1, Math.ceil((p.text.perSecond.length * 34) / W));
3254
+ const labels = p.text.perSecond
3255
+ .map((b, i) =>
3256
+ i % every || b.median == null
3257
+ ? ""
3258
+ : `<text x="${x(b.t)}" y="${H - 1}" class="s">${round1(b.median * p.text.phoneScale)}</text>`,
3259
+ )
3260
+ .join("");
3261
+ rows.push({
3262
+ label: `text<br><small>share, top ${pct(top)}<br><span style="color:#1864ab">own</span> <span style="color:#4dabf7">product</span> <span style="color:#e8590c">pictures</span><br><span style="color:#c92a2a">median px, phone</span></small>`,
3263
+ h: H,
3264
+ svg: `${bars}${medLine ? `<polyline points="${medLine}" fill="none" stroke="#c92a2a" stroke-width="1.2"/>` : ""}${labels}`,
3265
+ });
3266
+ if (p.text.overlaps.length)
3267
+ rows.push({
3268
+ label: "<small>own text over</small>",
3269
+ h: 22,
3270
+ svg: p.text.overlaps
3271
+ .map(
3272
+ (ov) =>
3273
+ `<rect x="${x(ov.from)}" y="4" width="${Math.max(1, x(ov.to) - x(ov.from))}" height="14" fill="#c92a2a" opacity="0.35"/>`,
3274
+ )
3275
+ .join(""),
3276
+ });
3277
+ }
3278
+ // declared subjects
3279
+ for (const tr of p.subjects.tracks) {
3280
+ rows.push({
3281
+ label: `<small>${esc(tr.name)}<br>declared, out of frame</small>`,
3282
+ h: 22,
3283
+ svg: p.subjects.exits
3284
+ .filter((e) => e.name === tr.name)
3285
+ .map(
3286
+ (e) =>
3287
+ `<rect x="${x(e.start)}" y="3" width="${Math.max(1, x(e.end) - x(e.start))}" height="16" fill="${e.how === "out" ? "#862e9c" : "#da77f2"}"/>`,
3288
+ )
3289
+ .join(""),
3290
+ });
3291
+ }
3292
+ if (p.marks.list.length)
3293
+ rows.push({
3294
+ label: "marks",
3295
+ h: 30,
3296
+ svg: p.marks.list
3297
+ .map(
3298
+ (m) =>
3299
+ `<line x1="${x(m.t)}" x2="${x(m.t)}" y1="0" y2="30" stroke="#1971c2"/><text x="${x(m.t) + 2}" y="12" class="s">${esc(m.label)}</text>`,
3300
+ )
3301
+ .join(""),
3302
+ });
3303
+
3304
+ const gap = 4;
3305
+ let top = PAD;
3306
+ const body = rows
3307
+ .map((r) => {
3308
+ 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>`;
3309
+ top += r.h + gap;
3310
+ return html;
3311
+ })
3312
+ .join("");
3313
+ const rulerH = top;
3314
+ const over = `<svg class="over" width="${W}" height="${rulerH - PAD}" style="left:${GUTTER}px;top:${PAD}px">${p.cuts.list
3315
+ .map(
3316
+ (c) =>
3317
+ `<line x1="${x(c.t)}" x2="${x(c.t)}" y1="0" y2="100%" stroke="#e03131" stroke-width="1" opacity="0.35"/>`,
3318
+ )
3319
+ .join("")}</svg>`;
3320
+ const legend = `<div class="legend" style="top:${top}px">red lines: hard cuts read from the picture · cuts × onsets: solid = an onset within 40 ms, dashed = none; orange ticks = onsets · ${esc(basename(p.input))} ${p.duration.toFixed(2)}s · measured/estimated: see probe.md</div>`;
3321
+ top += 24;
3322
+ // the changes as before → after cards
3323
+ const cardW = 470;
3324
+ const perRow = Math.max(1, Math.floor((width - PAD) / (cardW + PAD)));
3325
+ const thumbW = Math.floor((cardW - 8) / 2);
3326
+ const thumbH = Math.round((thumbW * p.size.height) / p.size.width);
3327
+ const cardH = thumbH + 40;
3328
+ const src = (rel: string) => pathToFileURL(join(o.outDir, rel)).href;
3329
+ const card = (c: (typeof p.changes.list)[number], i: number, y0: number, slot: number) => {
3330
+ const r = Math.floor(slot / perRow);
3331
+ const k = slot % perRow;
3332
+ const imgs = c.thumbs
3333
+ ? `<img src="${src(c.thumbs.before)}" style="left:0"><img src="${src(c.thumbs.after)}" style="left:${thumbW + 8}px">`
3334
+ : "";
3335
+ return `<div class="card" style="left:${PAD + k * (cardW + PAD)}px;top:${y0 + r * (cardH + PAD)}px;border-color:${KIND_COLOR[c.kind]}">${imgs}<div class="cap"><b style="color:${KIND_COLOR[c.kind]}">${i + 1}. ${fmtT(c.t)} ${c.kind}</b>${c.kind === "hard cut" ? ` · ${c.across}` : ""}<br>stays ${pct(c.stays)} · carried ${pct(c.carried)} · bg ${pct(c.background)} · changed ${pct(c.changed)}</div></div>`;
3336
+ };
3337
+ // Chrome's screenshot stops at 4096 px: the cards go on over further pages
3338
+ const MAX_H = 4000;
3339
+ const pages: { html: string; height: number }[] = [];
3340
+ const firstRows = Math.max(0, Math.floor((MAX_H - top - PAD) / (cardH + PAD)));
3341
+ const laterRows = Math.max(1, Math.floor((MAX_H - PAD * 2) / (cardH + PAD)));
3342
+ let i = 0;
3343
+ {
3344
+ const n = Math.min(p.changes.list.length, firstRows * perRow);
3345
+ const cards = p.changes.list
3346
+ .slice(0, n)
3347
+ .map((c, k) => card(c, k, top, k))
3348
+ .join("");
3349
+ pages.push({
3350
+ html: `${body}${over}${legend}${cards}`,
3351
+ height: top + Math.ceil(n / perRow) * (cardH + PAD) + PAD,
3352
+ });
3353
+ i = n;
3354
+ }
3355
+ while (i < p.changes.list.length) {
3356
+ const n = Math.min(p.changes.list.length - i, laterRows * perRow);
3357
+ const cards = p.changes.list
3358
+ .slice(i, i + n)
3359
+ .map((c, k) => card(c, i + k, PAD, k))
3360
+ .join("");
3361
+ pages.push({ html: cards, height: Math.ceil(n / perRow) * (cardH + PAD) + PAD * 2 });
3362
+ i += n;
3363
+ }
3364
+ const files: string[] = [];
3365
+ const tmp = await mkdtemp(join(tmpdir(), "open-take-probe-"));
3366
+ try {
3367
+ for (const [k, pg] of pages.entries()) {
3368
+ await writeFile(
3369
+ join(tmp, `probe-${k}.html`),
3370
+ `<!doctype html><meta charset="utf-8"><style>
3371
+ html,body{margin:0;background:#fff}
3372
+ body{position:relative;width:${width}px;height:${pg.height}px;font:12px/1.25 ui-monospace,Menlo,monospace;color:#111}
3373
+ .row{position:absolute;left:0;width:${width}px}
3374
+ .row svg,.over{position:absolute;top:0}
3375
+ .row svg{background:#fafafa}
3376
+ .over{pointer-events:none}
3377
+ .lab{position:absolute;left:${PAD}px;width:${GUTTER - PAD * 2}px;top:2px;font-weight:600}
3378
+ small{font-weight:400;color:#555}
3379
+ .s{font-size:10px;fill:#333}
3380
+ .legend{position:absolute;left:${GUTTER}px;font-size:11px;color:#444}
3381
+ .card{position:absolute;width:${cardW}px;height:${cardH}px;border-top:3px solid;box-sizing:border-box}
3382
+ .card img{position:absolute;top:3px;width:${thumbW}px;height:${thumbH}px;object-fit:cover;background:#000}
3383
+ .cap{position:absolute;top:${thumbH + 5}px;left:0;font-size:11px}
3384
+ </style>${pg.html}`,
3385
+ );
3386
+ const browser = await launchHtmlBrowser({
3387
+ chromePath: o.chromePath,
3388
+ url: pathToFileURL(join(tmp, `probe-${k}.html`)).href,
3389
+ width,
3390
+ height: pg.height,
3391
+ profilePrefix: "open-take-probe-",
3392
+ });
3393
+ try {
3394
+ await browser.evaluate(
3395
+ "Promise.all([...document.images].map((i) => i.decode().catch(() => {}))).then(() => new Promise((ok) => requestAnimationFrame(() => requestAnimationFrame(() => ok(0)))))",
3396
+ );
3397
+ const file = k ? o.out.replace(/\.png$/, `-${k + 1}.png`) : o.out;
3398
+ await writeFile(file, await browser.screenshot({ format: "png" }));
3399
+ files.push(file);
3400
+ } finally {
3401
+ await browser.close();
3402
+ }
3403
+ }
3404
+ } finally {
3405
+ await rm(tmp, { recursive: true, force: true });
3406
+ }
3407
+ return files;
3408
+ }
3409
+
3410
+ // --- small arithmetic ----------------------------------------------------------------------
3411
+
3412
+ const frameRate = (r?: string) => {
3413
+ const [n, d] = String(r ?? "60/1")
3414
+ .split("/")
3415
+ .map(Number);
3416
+ return n && d ? n / d : 60;
3417
+ };
3418
+ function median(xs: readonly number[]): number {
3419
+ if (!xs.length) return 0;
3420
+ const s = [...xs].sort((a, b) => a - b);
3421
+ const m = s.length >> 1;
3422
+ return s.length % 2 ? s[m]! : (s[m - 1]! + s[m]!) / 2;
3423
+ }
3424
+ const round1 = (v: number) => Math.round(v * 10) / 10;
3425
+ const round2 = (v: number) => Math.round(v * 100) / 100;
3426
+ const round3 = (v: number) => Math.round(v * 1000) / 1000;
3427
+ const round4 = (v: number) => Math.round(v * 10000) / 10000;
3428
+ const round6 = (v: number) => Math.round(v * 1e6) / 1e6;
3429
+
3430
+ /** what `film render` wrote into a film about its page (FILM_TAG); null for
3431
+ * a film from anywhere else */
3432
+ function filmRecordOf(
3433
+ raw: string | undefined,
3434
+ ): { from: number; width: number; height: number } | null {
3435
+ if (!raw) return null;
3436
+ try {
3437
+ const r = JSON.parse(raw) as Record<string, unknown>;
3438
+ const pos = (v: unknown) => (typeof v === "number" && v > 0 ? v : 0);
3439
+ return { from: pos(r.from), width: pos(r.width), height: pos(r.height) };
3440
+ } catch {
3441
+ return null;
3442
+ }
3443
+ }
3444
+
3445
+ /** a page sample in the film's px: sizes and boxes times k */
3446
+ function scalePageSample(s: PageTextSample, k: number): PageTextSample {
3447
+ if (k === 1) return s;
3448
+ const b = (x: Box): Box => [x[0] * k, x[1] * k, x[2] * k, x[3] * k];
3449
+ return {
3450
+ ...s,
3451
+ own: s.own.map((o) => ({ ...o, px: o.px * k, boxes: o.boxes.map(b) })),
3452
+ sizes: s.sizes.map(([px, n]) => [px * k, n] as [number, number]),
3453
+ media: s.media.map((m) => ({ ...m, box: b(m.box), ...(m.drawn ? { drawn: b(m.drawn) } : {}) })),
3454
+ subjects: Object.fromEntries(Object.entries(s.subjects).map(([n, x]) => [n, x ? b(x) : null])),
3455
+ };
3456
+ }