@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,864 @@
1
+ // `open-take film study`: a reference pack for a film already made. Read the
2
+ // picture once on its native clock, giving the probe a grey copy and keeping
3
+ // colour frames for shot stills and candidate strips. Set the shot table
4
+ // beside the sound of the mix, with the reading's status written down.
5
+ // The frames let someone check the boundaries and read the story, materials
6
+ // and intentions that the measurements cannot see.
7
+
8
+ import { spawn, spawnSync } from "node:child_process";
9
+ import { createHash } from "node:crypto";
10
+ import { createReadStream, existsSync } from "node:fs";
11
+ import { copyFile, mkdir, mkdtemp, readFile, rename, rm, stat, writeFile } from "node:fs/promises";
12
+ import { tmpdir } from "node:os";
13
+ import { join, resolve } from "node:path";
14
+ import { createInterface } from "node:readline";
15
+ import { resolveFfmpeg, resolveFfprobe, runTool } from "../ffmpeg";
16
+ import { type BeatsHow, LISTEN_RATE, median } from "./beats";
17
+ import { cameraRuns } from "./probe";
18
+ import { type DeclaredBoundary, type Declarations, type DeclarationsSkipped, readDeclarations } from "./study-declared";
19
+ import {
20
+ type AcrossKind,
21
+ analyzeStudyPicture,
22
+ boundaryMotion,
23
+ cameraReadings,
24
+ KEPT_WIDTH,
25
+ keptInPlace,
26
+ motionShares,
27
+ motionStates,
28
+ stateSteps,
29
+ type Step,
30
+ type PictureCandidate,
31
+ type StudyFrames,
32
+ studyTime,
33
+ } from "./study-picture";
34
+ import {
35
+ analyzeStudySound,
36
+ eventTimes,
37
+ shuffledNull,
38
+ SOUND_KINDS,
39
+ soundOffsets,
40
+ type SoundKind,
41
+ } from "./study-sound";
42
+
43
+ type Mark<T> = { value: T; how: BeatsHow };
44
+ function mark<T>(value: T, how: BeatsHow = "measured"): Mark<T> {
45
+ return { value, how: value == null ? "not detected" : how };
46
+ }
47
+ const estimate = <T>(value: T) => mark(value, "estimated");
48
+
49
+ function estimatedFields<T extends object>(fields: T): { [K in keyof T]: Mark<T[K]> } {
50
+ return Object.fromEntries(Object.entries(fields).map(([k, v]) => [k, estimate(v)])) as {
51
+ [K in keyof T]: Mark<T[K]>;
52
+ };
53
+ }
54
+
55
+ const round = (n: number, places = 6) => Number(n.toFixed(places));
56
+ const frameFile = "native-%09d.jpg"; // image2 needs a zero-based sequence
57
+ const stripName = (index: number, time: number) =>
58
+ `${String(index).padStart(3, "0")}-${time.toFixed(3)}.jpg`;
59
+ const shotStill = (index: number) => `shots/${String(index).padStart(3, "0")}.jpg`;
60
+ const sides = { before: 3, after: 5 }; // a look at both sides of a whip or jump
61
+
62
+ type Identity = {
63
+ file: string;
64
+ bytes: number;
65
+ width: number;
66
+ height: number;
67
+ duration: number;
68
+ sha256: string;
69
+ audioPresent: boolean;
70
+ timingMeasured: boolean;
71
+ endMeasured?: boolean;
72
+ durationMeasured?: boolean;
73
+ fpsMeasured?: boolean;
74
+ };
75
+
76
+ function soundReading(pcm: Float32Array | null, duration: number, t0: number, lengths: number[],
77
+ start: number, frameS: number) {
78
+ const sound = pcm?.length ? analyzeStudySound(pcm, duration, t0) : null;
79
+ const events = sound?.events.map((e) => ({
80
+ kind: estimate(e.kind),
81
+ time: estimate(round(e.time)),
82
+ changeDb: estimate(e.changeDb == null ? null : round(e.changeDb, 2)),
83
+ // what the change is read against: the sub before it, or the mix where no sub was
84
+ changeAgainst: estimate(e.changeDb == null ? null : (e.against ?? "sub")),
85
+ })) ?? [];
86
+ const alignment = SOUND_KINDS.map((kind) => {
87
+ const n = shuffledNull(lengths, eventTimes(sound, kind), frameS, { start });
88
+ return {
89
+ kind: mark(kind),
90
+ realShare: estimate(n?.realShare ?? null),
91
+ nullMean: estimate(n?.nullMean ?? null),
92
+ nullP95: estimate(n?.nullP95 ?? null),
93
+ p: estimate(n?.p ?? null),
94
+ uniformShare: estimate(n?.uniformShare ?? null),
95
+ windowS: mark(n?.windowS ?? null),
96
+ shuffles: mark(n?.shuffles ?? null),
97
+ seed: mark(n?.seed ?? null),
98
+ // A per-event upper-tail test at the usual five percent level.
99
+ reading: estimate(n ? n.p <= 0.05 && n.realShare > n.nullMean
100
+ ? "above the shuffled chance range"
101
+ : "no better than chance on this test" : null),
102
+ };
103
+ });
104
+ return {
105
+ sound,
106
+ report: {
107
+ bedShare: mark(sound?.bedShare ?? null),
108
+ bedSpreadDb: mark(sound?.bedSpreadDb ?? null),
109
+ subShare: estimate(sound?.subShare ?? null),
110
+ subRelativeDb: estimate(sound?.subRelativeDb ?? null),
111
+ bpm: estimate(sound?.bpm ?? null),
112
+ events,
113
+ gaps: sound?.gaps.map(estimatedFields) ?? [],
114
+ sections: sound?.sections.map(estimatedFields) ?? [],
115
+ changes: sound?.changes.map((c) => ({
116
+ time: estimate(c.t), size: estimate(c.size), parts: c.parts.map(estimate), leadIn: estimate(c.leadIn),
117
+ })) ?? [],
118
+ alignment,
119
+ },
120
+ };
121
+ }
122
+
123
+ /** what the page wrote about a boundary, and what its render measured of the carry */
124
+ function declaredReading(d: DeclaredBoundary) {
125
+ return {
126
+ time: mark(round(d.at)),
127
+ as: mark(d.labels.join("; ") || d.kinds.join(", ") || null),
128
+ handoff: mark(d.handoff ?? null),
129
+ carry: mark(d.carry ?? null),
130
+ carried: mark(d.carried?.kind ?? null),
131
+ change: mark(d.carried ? d.carried.change || d.carried.note || null : null),
132
+ };
133
+ }
134
+
135
+ function candidateReading(g: StudyFrames, c: PictureCandidate, index: number, clock: "measured" | "estimated",
136
+ kept: number | null) {
137
+ const time = studyTime(g, c.frame);
138
+ // a cut the grey copy saw nothing cross, with a small part seen staying put
139
+ const across: AcrossKind | null = kept && c.across && c.across !== "carried" ? "small part kept" : c.across;
140
+ const lo = Math.max(0, c.frame - sides.before);
141
+ const hi = Math.min(g.count - 1, c.frame + sides.after);
142
+ return {
143
+ index: mark(index),
144
+ frame: mark(c.frame),
145
+ time: mark(round(time), clock),
146
+ verified: estimate(c.verified),
147
+ verdict: mark(c.verdict, c.verdict === "unresolved" ? "not detected" : "estimated"),
148
+ across: estimate(across),
149
+ nominations: c.nominations.map(({ source, frame, from, to }) => ({
150
+ source: mark(source), frame: mark(frame), from: mark(from), to: mark(to),
151
+ })),
152
+ evidence: {
153
+ previousFrame: mark(c.frame - 1),
154
+ change: mark(round(c.energy)),
155
+ nearbyChange: mark(round(c.nearbyEnergy)),
156
+ changedBlocks: mark(round(c.changed)),
157
+ alignedSupport: estimate(c.fit ? round(c.fit.support) : null),
158
+ alignedResidual: estimate(c.fit ? round(c.fit.error) : null),
159
+ scale: estimate(c.fit ? round(c.fit.s) : null),
160
+ keptInPlace: estimate(kept == null ? null : round(kept, 4)),
161
+ },
162
+ strip: mark(`strips/${stripName(index, time)}`),
163
+ stripFrames: Array.from({ length: hi - lo + 1 }, (_, k) => ({
164
+ frame: mark(lo + k), time: mark(round(studyTime(g, lo + k)), clock),
165
+ })),
166
+ };
167
+ }
168
+
169
+ /** The reference pack as data. Frame ranges are zero-based and end-exclusive.
170
+ * Times may be native PTS; the end of the picture is supplied separately. */
171
+ export function analyzeStudy(
172
+ g: StudyFrames,
173
+ identity: Identity,
174
+ pictureEnd: number,
175
+ pcm: Float32Array | null = null,
176
+ soundStart = 0,
177
+ /** `declared`: what the film's own events file says of its boundaries.
178
+ * `keptAt`: for a cut at this frame, the share of the picture seen staying
179
+ * put on a finer copy (keptInPlace), or null where it was not read. */
180
+ also: {
181
+ declared?: Declarations | DeclarationsSkipped | null;
182
+ keptAt?: (frame: number) => number | null;
183
+ } = {},
184
+ ) {
185
+ const { candidates, steps, means } = analyzeStudyPicture(g);
186
+ const cuts = candidates.filter((c) => c.verified);
187
+ const edges = [0, ...cuts.map((c) => c.frame), g.count];
188
+ const clock = identity.timingMeasured ? "measured" : "estimated";
189
+ const endClock = identity.endMeasured === false ? "estimated" : clock;
190
+ const edgeTime = (f: number) => f === g.count ? pictureEnd : studyTime(g, f);
191
+ const lengths = edges.slice(1).map((edge, i) => edgeTime(edge) - edgeTime(edges[i]!));
192
+ // Step i compares frames i − 1 and i: it took the time between them. A
193
+ // frame held long on a variable-rate film is a long step of no motion,
194
+ // not more of the move before it.
195
+ const durations = steps.map((_, i) => i > 0 ? edgeTime(i) - edgeTime(i - 1) : edgeTime(1) - edgeTime(0));
196
+ // Millisecond containers round the native interval. Allow that rounding
197
+ // when checking cadence, and keep the actual PTS in the shot table.
198
+ const intervals = durations.slice(1);
199
+ const cadence = identity.timingMeasured && intervals.length >= 2
200
+ ? intervals.every((dt) => Math.abs(dt - intervals[0]!) <= 0.001001)
201
+ : null;
202
+ const frameSeconds = intervals.length ? median(intervals) || 1 / g.fps : 1 / g.fps;
203
+ const { sound, report } = soundReading(pcm, identity.duration, soundStart, lengths, edgeTime(0), 1 / g.fps);
204
+ const cutFrames = new Set(cuts.map((c) => c.frame));
205
+ // each shot's steps over a thirtieth of a second or more: its travel, drift
206
+ // and hold, and the camera's path on a film faster than 30 fps
207
+ const spanned = edges.slice(0, -1).map((from, i) => stateSteps(g, steps, from, edges[i + 1]!, frameSeconds));
208
+ const spans = new Map<number, { step: Step; seconds: number }>();
209
+ spanned.forEach((span, i) => {
210
+ span.steps.forEach((step, k) => {
211
+ if (span.seconds[k]! > frameSeconds * 1.5) spans.set(edges[i]! + 1 + k, { step, seconds: span.seconds[k]! });
212
+ });
213
+ });
214
+ const runs = cameraRuns(cameraReadings(g, steps, cutFrames, spans), g.fps);
215
+ const table = candidates.map((c, i) => candidateReading(g, c, i + 1, clock,
216
+ c.verified && c.across !== "carried" ? also.keptAt?.(c.frame) ?? null : null));
217
+ const byFrame = new Map(table.map((c) => [c.frame.value, c]));
218
+ // The page's declarations against the picture's cuts: a declared boundary
219
+ // within a frame and a half of a cut is that cut (film probe's window);
220
+ // one with no cut there keeps the reading of a candidate at that frame.
221
+ // declared times are the page's, from 0; the picture's clock may start later
222
+ const declarations = also.declared && "boundaries" in also.declared
223
+ ? { file: also.declared.file, boundaries: also.declared.boundaries.map((d) => ({ ...d, at: d.at + edgeTime(0) })) }
224
+ : null;
225
+ const near = 1.5 * frameSeconds;
226
+ const nearest = <T>(list: readonly T[], time: (v: T) => number, t: number) => {
227
+ const best = list.reduce<T | null>((b, v) =>
228
+ Math.abs(time(v) - t) < (b == null ? Infinity : Math.abs(time(b) - t)) ? v : b, null);
229
+ return best != null && Math.abs(time(best) - t) <= near ? best : null;
230
+ };
231
+ const declaredAt = (t: number) => nearest(declarations?.boundaries ?? [], (d) => d.at, t);
232
+ const detected = (c: (typeof table)[number]) => ({
233
+ candidate: c.index, verdict: c.verdict, whatMovesAcross: c.across, strip: c.strip,
234
+ });
235
+ const boundaryList = [
236
+ ...cuts.map((c) => {
237
+ const d = declaredAt(studyTime(g, c.frame));
238
+ return {
239
+ time: mark(round(studyTime(g, c.frame)), clock),
240
+ source: mark(d ? "both" as const : "detected" as const),
241
+ declared: d ? declaredReading(d) : mark(null),
242
+ detected: detected(byFrame.get(c.frame)!),
243
+ };
244
+ }),
245
+ ...(declarations?.boundaries ?? [])
246
+ .filter((d) => !nearest(cuts, (c) => studyTime(g, c.frame), d.at))
247
+ .map((d) => {
248
+ const c = nearest(table, (v) => v.time.value, d.at);
249
+ return {
250
+ time: mark(round(d.at)),
251
+ source: mark("declared" as const),
252
+ declared: declaredReading(d),
253
+ detected: c ? detected(c) : mark(null),
254
+ };
255
+ }),
256
+ ].sort((a, b) => a.time.value - b.time.value);
257
+ const frameStates: ReturnType<typeof motionStates> = [];
258
+ const motionSeconds: number[] = [];
259
+ const motionRuns: {
260
+ state: Mark<string>;
261
+ from: Mark<number>;
262
+ to: Mark<number>;
263
+ seconds: Mark<number>;
264
+ }[] = [];
265
+ const readShares = (share: ReturnType<typeof motionShares>) => ({
266
+ travel: estimate(share?.travel ?? null),
267
+ drift: estimate(share?.drift ?? null),
268
+ hold: estimate(share?.hold ?? null),
269
+ sampledSeconds: mark(share ? round(share.seconds) : 0, endClock),
270
+ });
271
+ const shots = edges.slice(0, -1).map((from, i) => {
272
+ const to = edges[i + 1]!;
273
+ const a = edgeTime(from);
274
+ const b = edgeTime(to);
275
+ const seconds = durations.slice(from + 1, to);
276
+ const span = spanned[i]!;
277
+ const states = motionStates(span.steps, g.w, seconds, span.seconds);
278
+ // one by one: a shot of hours has more steps than a call takes arguments
279
+ for (const v of states) frameStates.push(v);
280
+ for (const v of seconds) motionSeconds.push(v);
281
+ // Keep the display frame convention at constant cadence. On a
282
+ // variable-rate film the run covers the intervals the steps measured.
283
+ const motionEdge = (k: number) => edgeTime(from + k + (cadence === false ? 0 : 1));
284
+ for (let k = 0; k < states.length;) {
285
+ let end = k + 1;
286
+ while (end < states.length && states[end] === states[k]) end++;
287
+ // Shorter stretches are in the shares. Half a second reads as a run
288
+ // on the launch reel motion tables.
289
+ const startTime = motionEdge(k);
290
+ const atPictureEnd = from + 1 + end === g.count;
291
+ const endTime = atPictureEnd ? edgeTime(g.count) : motionEdge(end);
292
+ if (endTime - startTime >= 0.5) motionRuns.push({
293
+ state: estimate(states[k]!),
294
+ from: mark(round(startTime), clock),
295
+ to: mark(round(endTime), atPictureEnd ? endClock : clock),
296
+ seconds: mark(round(endTime - startTime), atPictureEnd ? endClock : clock),
297
+ });
298
+ k = end;
299
+ }
300
+ const share = motionShares(states, seconds);
301
+ const dominant = runs.reduce<{ label: string; length: number } | null>((best, r) => {
302
+ const length = Math.min(r.end, b) - Math.max(r.start, a);
303
+ return length > (best?.length ?? 0) ? { label: `${r.what} ${r.dir}`, length } : best;
304
+ }, null);
305
+ const c = cuts[i];
306
+ const evidence = c && byFrame.get(c.frame);
307
+ const boundary = c && evidence ? (() => {
308
+ const m = boundaryMotion(g, steps, c, from, edges[i + 2]!);
309
+ const s = soundOffsets(sound, b);
310
+ const nearestByKind = Object.fromEntries(SOUND_KINDS.map((k) => [k, estimate(s.byKind[k])])) as
311
+ Record<SoundKind, Mark<number | null>>;
312
+ const d = declaredAt(b);
313
+ // The thing the page named, followed across by its render, is a
314
+ // measurement of that one thing; the picture's own reading stays beside it.
315
+ const crossed = d?.carried && d.carried.kind !== "bare";
316
+ return {
317
+ candidate: evidence.index,
318
+ kind: estimate("picture_cut" as const),
319
+ source: mark(d ? "both" as const : "detected" as const),
320
+ declared: d ? declaredReading(d) : mark(null),
321
+ verdict: evidence.verdict,
322
+ whatMovesAcross: crossed ? mark<AcrossKind | null>("carried") : evidence.across,
323
+ pictureReading: evidence.across,
324
+ before: m.before ? estimatedFields(m.before) : mark(null),
325
+ after: m.after ? estimatedFields(m.after) : mark(null),
326
+ directionContinues: estimate(m.continues),
327
+ atPeakSpeed: estimate(m.atPeak),
328
+ scaleStep: estimate(m.scale == null ? null : round(m.scale)),
329
+ sound: {
330
+ nearest: estimate(s.event?.kind ?? null),
331
+ time: estimate(s.event ? round(s.event.time) : null),
332
+ offset: estimate(s.offset == null ? null : round(s.offset)),
333
+ nearestByKind,
334
+ },
335
+ strip: evidence.strip,
336
+ };
337
+ })() : mark(null);
338
+ return {
339
+ index: mark(i + 1),
340
+ fromFrame: mark(from),
341
+ toFrame: mark(to),
342
+ from: mark(round(a), clock),
343
+ to: mark(round(b), to === g.count ? endClock : clock),
344
+ length: mark(round(b - a), to === g.count ? endClock : clock),
345
+ frames: mark(to - from),
346
+ picture: {
347
+ middleFrame: mark(Math.floor((from + to - 1) / 2)),
348
+ medianGrey: mark(round(median(Array.from(means.subarray(from, to))))),
349
+ still: mark(shotStill(i + 1)),
350
+ },
351
+ camera: {
352
+ ...readShares(share),
353
+ dominantMove: estimate(dominant?.label ?? (share?.hold === 1 ? "hold" : null)),
354
+ },
355
+ boundaryOut: boundary,
356
+ };
357
+ });
358
+ return {
359
+ version: mark(1),
360
+ identity: {
361
+ file: mark(identity.file),
362
+ bytes: mark(identity.bytes),
363
+ width: mark(identity.width),
364
+ height: mark(identity.height),
365
+ fps: mark(g.fps, identity.fpsMeasured === false ? "estimated" : "measured"),
366
+ frames: mark(g.count),
367
+ duration: mark(identity.duration, identity.durationMeasured ? "measured" : endClock),
368
+ pictureStart: mark(round(edgeTime(0)), clock),
369
+ pictureEnd: mark(round(pictureEnd), endClock),
370
+ constantCadence: mark(cadence),
371
+ sha256: mark(identity.sha256),
372
+ audioPresent: mark(identity.audioPresent),
373
+ },
374
+ picture: {
375
+ candidates: mark(candidates.length),
376
+ verified: estimate(cuts.length),
377
+ shares: readShares(motionShares(frameStates, motionSeconds)),
378
+ runs: runs.map(estimatedFields),
379
+ motionRuns,
380
+ },
381
+ sound: report,
382
+ boundaries: {
383
+ eventsFile: mark(declarations?.file ?? null),
384
+ unread: mark(also.declared && "skipped" in also.declared
385
+ ? `${also.declared.file}: ${also.declared.skipped}` : null),
386
+ list: boundaryList,
387
+ },
388
+ shots,
389
+ candidates: table,
390
+ };
391
+ }
392
+
393
+ export type FilmStudy = ReturnType<typeof analyzeStudy>;
394
+
395
+ const show = <T>(v: Mark<T>, fmt: (value: NonNullable<T>) => string = String) =>
396
+ v.value == null ? "[not detected]" : `${fmt(v.value!)} [${v.how}]`;
397
+ const cell = <T>(v: Mark<T>, how: BeatsHow, fmt: (value: NonNullable<T>) => string = String) =>
398
+ v.how === how && v.value != null ? fmt(v.value!) : show(v, fmt);
399
+ const estimated = <T>(v: Mark<T>, fmt?: (value: NonNullable<T>) => string) =>
400
+ cell(v, "estimated", fmt);
401
+ const reading = <T>(name: string, v: Mark<T>, fmt: (value: NonNullable<T>) => string = String) =>
402
+ `- [${v.how}] ${name}${v.value == null ? "" : ` — ${fmt(v.value!)}`}`;
403
+ const secs = (v: number) => `${v.toFixed(3)} s`;
404
+ const pct = (v: number) => `${(v * 100).toFixed(1)}%`;
405
+ const db = (v: number) => `${v.toFixed(1)} dB`;
406
+ const signed = (v: number) => `${v >= 0 ? "+" : "−"}${Math.abs(v * 1000).toFixed(1)} ms`;
407
+ const sharesText = (
408
+ s: FilmStudy["picture"]["shares"],
409
+ format = (v: Mark<number | null>) => show(v, pct),
410
+ ) => `${format(s.travel)} travel, ${format(s.drift)} drift, ${format(s.hold)} hold`;
411
+ const escapeCell = (s: string) => s.replace(/[\\|`\n\r]/g, (c) => c === "\n" || c === "\r" ? " " : `\\${c}`);
412
+
413
+ type Boundary = Exclude<FilmStudy["shots"][number]["boundaryOut"], Mark<null>>;
414
+
415
+ // The reading is of what was seen on a small copy, and says so on the page.
416
+ const acrossWords = (v: string) => v === "nothing carried" ? "nothing seen carried" : v;
417
+ const carriedBy = (d: ReturnType<typeof declaredReading>) => d.carried.value == null ? ""
418
+ : `${escapeCell(d.carry.value ?? "the thing named")} ${d.carried.value === "bare" ? "not across" : d.carried.value}${
419
+ d.change.value ? ` (${escapeCell(d.change.value)})` : ""}`;
420
+
421
+ function describeBoundary(b: Boundary) {
422
+ const side = (s: Boundary["before"]) => "dir" in s
423
+ ? `${estimated(s.dir)} at ${estimated(s.pxPerSecond, (v) => `${v.toFixed(2)} px/s`)}`
424
+ : estimated(s);
425
+ const direction = b.directionContinues.value == null ? "" : ` · direction continues ${estimated(b.directionContinues)}`;
426
+ const peak = b.atPeakSpeed.value == null ? "" : ` · peak at boundary ${estimated(b.atPeakSpeed)}`;
427
+ // what the page declared here and what its render measured, before the picture's reading
428
+ const declared = "as" in b.declared
429
+ ? `declared${b.declared.as.value ?? b.declared.handoff.value
430
+ ? ` “${escapeCell((b.declared.as.value ?? b.declared.handoff.value)!)}”` : ""}${
431
+ b.declared.carried.value ? `, the render followed ${carriedBy(b.declared)}` : ""} [measured] · picture: `
432
+ : "";
433
+ return `${declared}[${estimated(b.verdict)}](${b.strip.value}) · ${estimated(b.pictureReading, acrossWords)} · ${side(b.before)} → ${side(b.after)}${direction}${peak} · scale ${estimated(b.scaleStep, (v) => `${v.toFixed(2)}×`)}`;
434
+ }
435
+
436
+ export function formatStudyMarkdown(study: FilmStudy): string {
437
+ const id = study.identity;
438
+ const s = study.sound;
439
+ const motion = study.picture.shares;
440
+ const l = [
441
+ "# Film study", "",
442
+ "## Identity & provenance", "",
443
+ reading("File", id.file, (v) => `\`${escapeCell(v)}\``),
444
+ `- [measured] Encoded size — ${id.width.value} × ${id.height.value} px, ${id.bytes.value} bytes`,
445
+ reading("Frame count", id.frames),
446
+ reading("Frame rate", id.fps, (v) => `${v.toFixed(3)} fps`),
447
+ reading("Duration", id.duration, secs),
448
+ reading("Picture start", id.pictureStart, secs),
449
+ reading("Picture end", id.pictureEnd, secs),
450
+ reading("SHA-256", id.sha256, (v) => `\`${v}\``), "",
451
+ "## Brand Kit", "",
452
+ "- [not detected] Logo, type, colour and voice: read them in the frames and the shot stills.", "",
453
+ "## Narrative grammar", "",
454
+ "### Story & timing", "",
455
+ "The rows follow boundaries read from adjacent frames. Each still shows the middle frame of its shot. Follow the boundary link for the consecutive frames around it.", "",
456
+ "| Time [measured] | Shot [measured] | Picture [measured] | Camera [estimated] | Boundary out [estimated] | Sound at boundary [estimated] |",
457
+ "| --- | --- | --- | --- | --- | --- |",
458
+ ];
459
+ for (const shot of study.shots) {
460
+ const b = shot.boundaryOut;
461
+ const boundary = "verdict" in b ? describeBoundary(b) : "End of picture";
462
+ const sound = "sound" in b && b.sound.nearest.value != null
463
+ ? `${estimated(b.sound.nearest)} ${estimated(b.sound.offset, signed)}` : "[not detected]";
464
+ const camera = shot.camera.travel.value == null ? "[not detected]"
465
+ : `${sharesText(shot.camera, (v) => estimated(v, pct))} · ${estimated(shot.camera.dominantMove)}`;
466
+ const time = shot.from.how === shot.to.how
467
+ ? cell(mark(`${secs(shot.from.value)}–${secs(shot.to.value)}`, shot.from.how), "measured")
468
+ : `${cell(shot.from, "measured", secs)}–${cell(shot.to, "measured", secs)}`;
469
+ l.push(`| ${time} | ${cell(shot.index, "measured")} | [Still](${shot.picture.still.value}) | ${camera} | ${boundary} | ${sound} |`);
470
+ }
471
+ const bs = study.boundaries;
472
+ l.push("", "### Declared and detected boundaries", "");
473
+ if (bs.eventsFile.value == null) {
474
+ l.push(bs.unread.value == null
475
+ ? "- [not detected] The film's own declarations: no events file beside it, so every boundary here is read from the picture alone."
476
+ : `- [not detected] The film's own declarations: the events file beside it was not read (${escapeCell(bs.unread.value)}).`);
477
+ } else {
478
+ l.push(reading("The film's own declarations", bs.eventsFile, (v) => `\`${escapeCell(v)}\``), "",
479
+ "Both: the page declared a boundary and the picture shows a cut within a frame and a half of it. Declared: the page wrote one and the picture shows no cut there (a whip, a lift, a push through). Detected: a cut in the picture the page did not write down. The carry is the one thing the page named, followed across by its render: carried (it crossed and moved or changed size), anchored (it crossed unchanged) or not across.", "",
480
+ "| Time [measured] | Source [measured] | Declared [measured] | Carry followed by the render [measured] | Picture reading [estimated] |",
481
+ "| --- | --- | --- | --- | --- |");
482
+ for (const b of bs.list) {
483
+ const d = "as" in b.declared ? b.declared : null;
484
+ const p = "verdict" in b.detected ? b.detected : null;
485
+ const words = d ? [d.as.value, d.handoff.value && d.handoff.value !== d.as.value ? `handoff: ${d.handoff.value}` : null]
486
+ .filter(Boolean).map((v) => escapeCell(v!)).join(" · ") || "a segment ends" : "—";
487
+ const picture = p
488
+ ? `[${estimated(p.verdict)}](${p.strip.value})${p.whatMovesAcross.value ? ` · ${estimated(p.whatMovesAcross, acrossWords)}` : ""}`
489
+ : "no candidate at this frame";
490
+ l.push(`| ${cell(b.time, "measured", secs)} | ${b.source.value} | ${words} | ${d && carriedBy(d) || "—"} | ${picture} |`);
491
+ }
492
+ }
493
+ l.push("", "## Visual hierarchy", "",
494
+ "- [not detected] What leads each frame, what supports it and what is background: read it in the shot stills.");
495
+ l.push("", "## Timing & motion", "",
496
+ motion.travel.value == null ? "- [not detected] Picture motion shares"
497
+ : `- [estimated] Picture across the film — ${sharesText(motion, (v) => estimated(v, pct))}.`,
498
+ reading("Time covered by within-shot steps", motion.sampledSeconds, secs), "",
499
+ "Travel reads the whole picture’s shift and scale, or median local displacement. Drift includes changes below the travel thresholds. A hold is a picture below the change and motion floors. Closing fills holes left by repeated frames within a shot.",
500
+ "Direction follows the picture on screen. Speeds use a common-width picture ruler.", "");
501
+ for (const r of study.picture.runs) l.push(
502
+ `- [estimated] ${r.what.value} ${r.dir.value}, ${secs(r.start.value)}–${secs(r.end.value)}, ${r.what.value === "zoom" ? `${r.amount.value.toFixed(3)}×` : pct(r.amount.value)}`,
503
+ );
504
+ if (!study.picture.runs.length) l.push("- [not detected] Camera runs");
505
+ if (study.picture.motionRuns.length) {
506
+ l.push("", "Longer stretches of travel, drift and hold", "",
507
+ "| Motion [estimated] | Start [measured] | End [measured] | Length [measured] |",
508
+ "| --- | --- | --- | --- |");
509
+ for (const r of study.picture.motionRuns) l.push(
510
+ `| ${estimated(r.state)} | ${cell(r.from, "measured", secs)} | ${cell(r.to, "measured", secs)} | ${cell(r.seconds, "measured", secs)} |`,
511
+ );
512
+ }
513
+ l.push("", "## Materials & sound", "",
514
+ "- [not detected] Sources of the picture’s materials",
515
+ reading("Time above the silence floor", s.bedShare, pct),
516
+ reading("Active level spread between deciles", s.bedSpreadDb, db),
517
+ reading("Time with sub present", s.subShare, pct),
518
+ reading("Sub level relative to the mix", s.subRelativeDb, db),
519
+ reading("Tempo", s.bpm, (v) => `${v} BPM`), "",
520
+ "### Sound structure", "");
521
+ for (const sec of s.sections) l.push(`- [estimated] ${secs(sec.start.value)}–${secs(sec.end.value)}, ${sec.levelDb.value.toFixed(1)} dBFS, ${sec.onsetsPerS.value} onsets/s.`);
522
+ for (const kind of SOUND_KINDS) {
523
+ const events = s.events.filter((e) => e.kind.value === kind);
524
+ const list = kind === "onset" || !events.length ? "" : ` at ${events.map((e) =>
525
+ `${secs(e.time.value)}${e.changeDb.value == null ? "" : ` (${db(e.changeDb.value)}${
526
+ e.changeAgainst?.value === "mix"
527
+ ? kind === "sub_exit" ? " against the mix after it, no sub there" : " against the mix before it, no sub there"
528
+ : ""})`}`).join(", ")}`;
529
+ const name = kind.replaceAll("_", " ");
530
+ l.push(events.length ? `- [estimated] ${name} — ${events.length}${list}.` : `- [not detected] ${name}`);
531
+ }
532
+ for (const gap of s.gaps) l.push(`- [estimated] ${gap.kind.value.replaceAll("_", " ")} ${secs(gap.start.value)}–${secs(gap.end.value)}, low point ${gap.deepestDb.value.toFixed(1)} ${gap.kind.value === "silence" ? "dBFS" : "dB"}.`);
533
+ if (!s.gaps.length) l.push("- [not detected] Absolute silences and relative gaps");
534
+ for (const c of s.changes) l.push(`- [estimated] Sound changes at ${secs(c.time.value)}. See the spectral reading in \`study.json\`.`);
535
+ l.push("", "### Cuts against sound", "",
536
+ "The chance test permutes the shot lengths with a fixed seed, keeping the picture’s start and end. It checks the fraction of cuts within one nominal frame of each kind of event. Shares, p values and readings are estimated.", "",
537
+ "| Event | Cut share | Shuffled mean | Shuffled 95th percentile | Empirical p | Reading |",
538
+ "| --- | --- | --- | --- | --- | --- |");
539
+ for (const row of s.alignment) l.push(`| ${row.kind.value} | ${estimated(row.realShare, pct)} | ${estimated(row.nullMean, pct)} | ${estimated(row.nullP95, pct)} | ${estimated(row.p, (v) => v.toFixed(3))} | ${estimated(row.reading)} |`);
540
+ const test = s.alignment.find((row) => row.windowS.value != null);
541
+ if (test?.windowS.value != null)
542
+ l.push("", `- [measured] Window ±${secs(test.windowS.value)}, ${test.shuffles.value} shuffles, seed ${test.seed.value}.`);
543
+ l.push("", "The offsets below are estimated. A positive offset puts the sound after the cut.", "",
544
+ "| Boundary [measured] | Onset | Hit | Sub entry | Sub exit | Drop |",
545
+ "| --- | --- | --- | --- | --- | --- |");
546
+ for (const shot of study.shots) {
547
+ const b = shot.boundaryOut;
548
+ if ("sound" in b) l.push(`| ${cell(shot.to, "measured", secs)} | ${SOUND_KINDS.map((k) => estimated(b.sound.nearestByKind[k], signed)).join(" | ")} |`);
549
+ }
550
+ l.push("", "## Invariants", "");
551
+ if (id.constantCadence.value) l.push("- [measured] The native picture cadence holds across the film.");
552
+ if (!id.audioPresent.value) l.push("- [measured] The file has no audio stream.");
553
+ const continuousBed = s.bedShare.value != null && Math.abs(s.bedShare.value - 1) < 1e-9;
554
+ if (continuousBed) l.push("- [measured] The sound stays over the silence floor across the film.");
555
+ if (!id.constantCadence.value && id.audioPresent.value && !continuousBed)
556
+ l.push("- [not detected] Film-wide invariants");
557
+ const onsets = s.events.filter((e) => e.kind.value === "onset").map((e) => e.time.value);
558
+ const near = test?.windowS.value ?? 1 / id.fps.value;
559
+ const heard = id.duration.value;
560
+ l.push("",
561
+ "## Replaceable inputs", "",
562
+ "- [not detected] Which footage, copy, product screens and music could be swapped for another product's: decide it from the story.", "",
563
+ "## Review", "",
564
+ reading("Candidate count", study.picture.candidates),
565
+ reading("Cuts after the adjacent-frame check", study.picture.verified),
566
+ "",
567
+ "What this reading does not see, in any film (found by checking it frame by frame against launch reels where every boundary was known):", "",
568
+ "1. A dissolve (one of 6 frames was missed) and a morph over about 10 frames: no single pair of frames differs enough.",
569
+ "2. A cut hidden in blur during a 3D camera move, a white flash of 1–2 frames, and a scale jump whose two sides do not register on the 96 px grey copy: these come out unresolved, fast_move, flash_or_fade or in_picture_change, not as cuts. Read the strip of every candidate that is not a cut where you suspect one.",
570
+ "3. Stems: voice, music and effects are not told apart; the sound is read from the mono mix.",
571
+ onsets.length && heard > 0
572
+ ? `4. This film has ${(onsets.length / heard).toFixed(1)} onsets a second. A time picked uniformly across the film has a ${pct(coveredShare(onsets, near, heard))} chance of lying within ±${secs(near)} of an onset. Read cut closeness beside the shuffled baseline.`
573
+ : "4. No onsets were found, so closeness to them says nothing here.",
574
+ "5. A small thing carried across a cut. “Carried” needs textured picture over a tenth of the frame to stay or be followed; “small part kept” needs a patch to stay exactly where it was (a pinned caption, a logo, an avatar the next scene opens on). An avatar that flies across a cut, or lands on a different ground, is read as nothing seen carried. Where the film's own events file sits beside it, the carry its page named and its render followed is shown instead.", "",
575
+ "Look at the strips for ambiguous boundaries, colour-only changes and small carried objects. Read the story, words, depth and subjects in the film.", "",
576
+ "| Time [measured] | Adjacent frames [measured] | Verdict [estimated] | Strip [measured] |",
577
+ "| --- | --- | --- | --- |");
578
+ for (const c of study.candidates) l.push(`| ${cell(c.time, "measured", secs)} | f${cell(c.evidence.previousFrame, "measured")} → f${cell(c.frame, "measured")} | ${estimated(c.verdict)} | [frames](${c.strip.value}) |`);
579
+ return `${l.join("\n")}\n`;
580
+ }
581
+
582
+ /** the share of [0, duration) within ±window of some time */
583
+ export function coveredShare(times: readonly number[], window: number, duration: number): number {
584
+ if (!(duration > 0)) return 0;
585
+ let covered = 0;
586
+ let reach = 0;
587
+ for (const t of [...times].sort((a, b) => a - b)) {
588
+ const a = Math.max(reach, t - window, 0);
589
+ const b = Math.min(t + window, duration);
590
+ if (b > a) covered += b - a;
591
+ reach = Math.max(reach, b);
592
+ }
593
+ return covered / duration;
594
+ }
595
+
596
+ export function formatFilmStudy(s: FilmStudy): string {
597
+ return [
598
+ `picture — ${show(s.identity.frames)} frames, ${show(s.identity.duration, secs)}`,
599
+ `boundaries — ${show(s.picture.candidates)} candidates, ${show(s.picture.verified)} cuts from adjacent frames`,
600
+ ...(s.boundaries.eventsFile.value == null
601
+ ? [s.boundaries.unread.value == null ? "declared — no events file beside the film; boundaries are read from the picture alone"
602
+ : `declared — events file not read (${s.boundaries.unread.value})`]
603
+ : [`declared — ${(["both", "declared", "detected"] as const).map((k) =>
604
+ `${s.boundaries.list.filter((b) => b.source.value === k).length} ${k === "both" ? "declared and detected" : `${k} only`}`).join(", ")}`]),
605
+ `motion — ${sharesText(s.picture.shares)}`,
606
+ `sound — bed ${show(s.sound.bedShare, pct)}, sub present ${show(s.sound.subShare, pct)}`,
607
+ ...s.sound.alignment.filter((r) => r.p.value != null).map((r) =>
608
+ `cuts near ${r.kind.value} — ${show(r.realShare, pct)}, shuffled ${show(r.nullMean, pct)}, p ${show(r.p, (v) => v.toFixed(3))} · ${show(r.reading)}`),
609
+ ].join("\n");
610
+ }
611
+
612
+ export type FilmStudyOptions = {
613
+ input: string;
614
+ /** default is <input without extension>.study/ */
615
+ out?: string;
616
+ };
617
+
618
+ type Stream = {
619
+ index?: number;
620
+ codec_type: string;
621
+ width?: number;
622
+ height?: number;
623
+ avg_frame_rate?: string;
624
+ r_frame_rate?: string;
625
+ duration?: string;
626
+ start_time?: string;
627
+ sample_aspect_ratio?: string;
628
+ disposition?: { attached_pic?: number; default?: number };
629
+ side_data_list?: { rotation?: number }[];
630
+ };
631
+ const ratio = (s: string | undefined, divider: string) => {
632
+ const [a, b] = (s ?? "").split(divider).map(Number);
633
+ return a && b ? a / b : 0;
634
+ };
635
+
636
+ /** One audio stream as mono samples at LISTEN_RATE, on the stream's own
637
+ * clock: a gap in its timestamps is filled with silence, so what follows
638
+ * stays at its time instead of moving up to meet what came before. */
639
+ function decodeSound(ffmpeg: string, file: string, index = 0): Promise<Float32Array> {
640
+ return new Promise((ok, fail) => {
641
+ const p = spawn(ffmpeg, [
642
+ "-v", "error", "-i", file, "-map", `0:${index}`, "-af", "aresample=async=1",
643
+ "-ac", "1", "-ar", String(LISTEN_RATE), "-f", "f32le", "-",
644
+ ], { stdio: ["ignore", "pipe", "pipe"] });
645
+ const chunks: Buffer[] = [];
646
+ let err = "";
647
+ p.stdout.on("data", (d: Buffer) => chunks.push(d));
648
+ p.stderr.on("data", (d: Buffer) => { err += d.toString(); });
649
+ p.on("error", fail);
650
+ p.on("close", (code) => {
651
+ if (code !== 0) return fail(new Error(`film study: ffmpeg could not decode the sound of ${file}: ${err.trim().slice(-400)}`));
652
+ const all = Buffer.concat(chunks);
653
+ ok(new Float32Array(all.buffer.slice(all.byteOffset, all.byteOffset + (all.length & ~3))));
654
+ });
655
+ });
656
+ }
657
+
658
+ async function sha256(file: string) {
659
+ const hash = createHash("sha256");
660
+ for await (const chunk of createReadStream(file)) hash.update(chunk);
661
+ return hash.digest("hex");
662
+ }
663
+
664
+ // legible tiled frames on the contact sheet, and the copy keptInPlace reads
665
+ const thumbSize = (displayRatio: number) =>
666
+ ({ w: KEPT_WIDTH, h: Math.max(2, Math.round(KEPT_WIDTH / displayRatio / 2) * 2) });
667
+
668
+ /** The share of the picture that stays put across the cut into `frame`, read
669
+ * from the two colour frames already written for the strips (their label
670
+ * band cropped off); null when they cannot be read. */
671
+ function keptAcross(ffmpeg: string, tmp: string, frame: number, displayRatio: number): number | null {
672
+ const { w, h } = thumbSize(displayRatio);
673
+ const r = spawnSync(ffmpeg, [
674
+ "-v", "error", "-start_number", String(frame - 1), "-i", join(tmp, frameFile), "-frames:v", "2",
675
+ "-vf", `crop=${w}:${h}:0:0,format=gray`, "-f", "rawvideo", "-",
676
+ ], { maxBuffer: 2 * w * h + 4096 });
677
+ if (r.status !== 0 || r.stdout.length !== 2 * w * h) return null;
678
+ return keptInPlace(r.stdout.subarray(0, w * h), r.stdout.subarray(w * h), w, h);
679
+ }
680
+
681
+ function decodePicture(
682
+ ffmpeg: string, input: string, tmp: string, width: number, height: number, displayRatio: number,
683
+ fps: number, videoStart: number,
684
+ ): Promise<StudyFrames> {
685
+ const font = [
686
+ "/System/Library/Fonts/Supplemental/Arial.ttf",
687
+ "/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf",
688
+ "/Windows/Fonts/arial.ttf",
689
+ ].find(existsSync);
690
+ const fontArg = font ? `fontfile='${font}':` : "";
691
+ // A small colour copy to look at, and a grey copy to measure. Both branches
692
+ // use passthrough timing and read from the same video decoder.
693
+ const { w: thumbW, h: thumbH } = thumbSize(displayRatio);
694
+ // Round before splitting seconds and milliseconds so they carry together.
695
+ const ms = "round(t*1000)";
696
+ const label = `f%{n} %{eif\\:floor(${ms}/1000)\\:d}.%{eif\\:mod(${ms},1000)\\:d\\:3} s`;
697
+ const filters = "[0:V:0]showinfo=checksum=0,split[measure][strip];" +
698
+ `[measure]scale=${width}:${height}:flags=area,format=gray[gray];` +
699
+ `[strip]scale=${thumbW}:${thumbH}:flags=area,setsar=1,pad=iw:ih+24:0:0:color=0x181818,` +
700
+ `drawtext=${fontArg}text='${label}':fontcolor=white:fontsize=15:x=8:y=h-20[jpeg]`;
701
+ return new Promise((ok, fail) => {
702
+ const p = spawn(ffmpeg, [
703
+ "-hide_banner", "-nostats", "-loglevel", "info", "-copyts", "-start_at_zero",
704
+ "-i", input, "-filter_complex", filters,
705
+ "-map", "[gray]", "-fps_mode", "passthrough", "-c:v", "rawvideo", "-threads", "1", "-f", "rawvideo", "-",
706
+ "-map", "[jpeg]", "-fps_mode", "passthrough", "-q:v", "4", "-start_number", "0", join(tmp, frameFile),
707
+ ], { stdio: ["ignore", "pipe", "pipe"] });
708
+ const chunks: Buffer[] = [];
709
+ const times: number[] = [];
710
+ const tail: string[] = [];
711
+ let timebase = 0;
712
+ p.stdout.on("data", (d: Buffer) => chunks.push(d));
713
+ createInterface({ input: p.stderr }).on("line", (line) => {
714
+ const tb = /config in time_base: (\d+\/\d+)/.exec(line);
715
+ if (tb) timebase = ratio(tb[1], "/");
716
+ const pts = /\bn:\s*(\d+)\s+pts:\s*(-?\d+)\s+pts_time:\s*(\S+)/.exec(line);
717
+ if (pts) times[Number(pts[1])] = timebase ? Number(pts[2]) * timebase : Number(pts[3]);
718
+ tail.push(line);
719
+ if (tail.length > 12) tail.shift();
720
+ });
721
+ p.on("error", fail);
722
+ p.on("close", (code) => {
723
+ if (code !== 0) return fail(new Error(`film study: ffmpeg could not read ${input}\n${tail.join("\n")}`));
724
+ const data = Buffer.concat(chunks);
725
+ const count = data.length / (width * height);
726
+ if (!Number.isInteger(count) || count < 1)
727
+ return fail(new Error(`film study: ${input} has no complete decoded frame`));
728
+ const clock = times.length === count && Array.from(times).every((t, i) =>
729
+ Number.isFinite(t) && (i === 0 || t > times[i - 1]!)) ? times : undefined;
730
+ ok({ w: width, h: height, count, fps, data, times: clock, t0: clock?.[0] ?? videoStart });
731
+ });
732
+ });
733
+ }
734
+
735
+ async function writeStrips(ffmpeg: string, tmp: string, stage: string, study: FilmStudy) {
736
+ await mkdir(join(stage, "strips"));
737
+ // A three-by-three sheet keeps the first three frames together above the
738
+ // boundary. Start at the first available native frame near the ends.
739
+ for (const c of study.candidates) {
740
+ const n = c.stripFrames.length;
741
+ await runTool(ffmpeg, [
742
+ "-v", "error", "-start_number", String(c.stripFrames[0]!.frame.value),
743
+ "-i", join(tmp, frameFile), "-frames:v", "1", "-update", "1", "-q:v", "3",
744
+ "-vf", `tile=3x${Math.ceil(n / 3)}:nb_frames=${n}:padding=3:margin=3:color=0x222222`,
745
+ join(stage, c.strip.value),
746
+ ]);
747
+ }
748
+ }
749
+
750
+ async function writeShotStills(tmp: string, stage: string, study: FilmStudy) {
751
+ await mkdir(join(stage, "shots"));
752
+ for (const { picture } of study.shots) {
753
+ const frame = frameFile.replace("%09d", String(picture.middleFrame.value).padStart(9, "0"));
754
+ await copyFile(join(tmp, frame), join(stage, picture.still.value));
755
+ }
756
+ }
757
+
758
+ function imagePaths(study: Partial<Pick<FilmStudy, "candidates" | "shots">>): string[] {
759
+ return [
760
+ ...(Array.isArray(study.candidates) ? study.candidates.flatMap((c) => {
761
+ const path = c?.strip?.value;
762
+ return typeof path === "string" && /^strips\/\d+-\d+\.\d{3}\.jpg$/.test(path) ? [path] : [];
763
+ }) : []),
764
+ ...(Array.isArray(study.shots) ? study.shots.flatMap((s) => {
765
+ const path = s?.picture?.still?.value;
766
+ return typeof path === "string" && /^shots\/\d{3,}\.jpg$/.test(path) ? [path] : [];
767
+ }) : []),
768
+ ];
769
+ }
770
+
771
+ export async function filmStudy(opts: FilmStudyOptions) {
772
+ const input = resolve(opts.input);
773
+ const file = await stat(input).catch(() => null);
774
+ if (!file?.isFile()) throw new Error(`film study: no file at ${input}`);
775
+ const out = resolve(opts.out ?? `${input.replace(/\.[^./]+$/, "")}.study`);
776
+ const [ffmpeg, ffprobe] = await Promise.all([resolveFfmpeg(), resolveFfprobe()]);
777
+ const info = JSON.parse(await runTool(ffprobe, [
778
+ "-v", "error", "-show_entries",
779
+ "stream=index,codec_type,width,height,avg_frame_rate,r_frame_rate,duration,start_time,sample_aspect_ratio:stream_disposition=attached_pic,default:stream_side_data=rotation:format=duration,start_time",
780
+ "-of", "json", input,
781
+ ])) as { streams?: Stream[]; format?: { duration?: string; start_time?: string } };
782
+ const video = info.streams?.find((s) => s.codec_type === "video" && !s.disposition?.attached_pic);
783
+ // the sound ffmpeg would play: the default audio stream, else the first;
784
+ // its start and its samples are read from that one stream
785
+ const sounds = info.streams?.filter((s) => s.codec_type === "audio") ?? [];
786
+ const audio = sounds.find((s) => s.disposition?.default) ?? sounds[0];
787
+ if (!video?.width || !video.height) throw new Error(`film study: ${input} has no picture`);
788
+ const formatStart = Number(info.format?.start_time) || 0;
789
+ const relativeStart = (stream?: Stream) => {
790
+ const start = Number(stream?.start_time);
791
+ return Number.isFinite(start) ? Math.max(0, start - formatStart) : 0;
792
+ };
793
+ const videoStart = relativeStart(video);
794
+ const audioStart = relativeStart(audio);
795
+ const metadataFps = ratio(video.avg_frame_rate, "/") || ratio(video.r_frame_rate, "/");
796
+ const fps = metadataFps || 30; // only when the container names neither rate
797
+ const aspect = video.width / video.height * (ratio(video.sample_aspect_ratio, ":") || 1);
798
+ const rotation = video.side_data_list?.find((s) => s.rotation != null)?.rotation ?? 0;
799
+ const displayRatio = Math.abs(rotation) % 180 === 90 ? 1 / aspect : aspect;
800
+ // A 96 px-wide grey copy keeps registration practical at native cadence.
801
+ // For a tall picture the longer edge uses the same pixel budget.
802
+ const greyW = Math.max(16, Math.round(Math.min(96, 96 * displayRatio) / 8) * 8);
803
+ const greyH = Math.max(16, Math.round(Math.min(96, 96 / displayRatio) / 8) * 8);
804
+ await mkdir(out, { recursive: true });
805
+ const tmp = await mkdtemp(join(tmpdir(), "open-take-study-"));
806
+ let stage: string | undefined;
807
+ try {
808
+ const readings = await Promise.allSettled([
809
+ decodePicture(ffmpeg, input, tmp, greyW, greyH, displayRatio, fps, videoStart),
810
+ audio ? decodeSound(ffmpeg, input, audio.index) : Promise.resolve(null),
811
+ sha256(input),
812
+ ] as const);
813
+ const [g, pcm, sha] = readings.map((r) => {
814
+ if (r.status === "rejected") throw r.reason;
815
+ return r.value;
816
+ }) as [StudyFrames, Float32Array | null, string];
817
+ const last = studyTime(g, g.count - 1);
818
+ const namedEnd = g.t0! + (Number(video.duration) || 0);
819
+ const containerEnd = Number(info.format?.duration) || 0;
820
+ // the last frame shows for a usual frame's time, not for the gap before
821
+ // it, which on a variable-rate file can be a held second
822
+ const lastStep = g.count > 1
823
+ ? median(Array.from({ length: g.count - 1 }, (_, i) => studyTime(g, i + 1) - studyTime(g, i)))
824
+ : 1 / fps;
825
+ const pictureEnd = namedEnd > last ? namedEnd :
826
+ !audio && containerEnd > last ? containerEnd : last + lastStep;
827
+ const duration = Math.max(pictureEnd, containerEnd);
828
+ const study = analyzeStudy(g, {
829
+ file: input, bytes: file.size, width: video.width, height: video.height, duration,
830
+ sha256: sha, audioPresent: !!audio, timingMeasured: g.times != null, fpsMeasured: !!metadataFps,
831
+ endMeasured: namedEnd > last || (!audio && containerEnd > last),
832
+ durationMeasured: containerEnd >= pictureEnd,
833
+ }, pictureEnd, pcm, audioStart, {
834
+ declared: await readDeclarations(input, pictureEnd - studyTime(g, 0), 1 / fps),
835
+ keptAt: (frame) => keptAcross(ffmpeg, tmp, frame, displayRatio),
836
+ });
837
+ stage = await mkdtemp(join(out, ".study-"));
838
+ await writeStrips(ffmpeg, tmp, stage, study);
839
+ await writeShotStills(tmp, stage, study);
840
+ await writeFile(join(stage, "STUDY.md"), formatStudyMarkdown(study));
841
+ await writeFile(join(stage, "study.json"), `${JSON.stringify(study, null, 2)}\n`);
842
+ const md = join(out, "STUDY.md");
843
+ const json = join(out, "study.json");
844
+ const strips = join(out, "strips");
845
+ // Only clear files named by an earlier pack. A folder can hold the
846
+ // author's own notes or other images beside the generated files.
847
+ const previous = await readFile(json, "utf8").then((raw) => {
848
+ try { return JSON.parse(raw) as Partial<Pick<FilmStudy, "candidates" | "shots">> | null; }
849
+ catch { return undefined; }
850
+ }, () => undefined);
851
+ await mkdir(strips, { recursive: true });
852
+ await mkdir(join(out, "shots"), { recursive: true });
853
+ const nextFiles = new Set(imagePaths(study));
854
+ for (const path of nextFiles) await rename(join(stage, path), join(out, path));
855
+ await rename(join(stage, "STUDY.md"), md);
856
+ await rename(join(stage, "study.json"), json);
857
+ for (const path of imagePaths(previous ?? {}))
858
+ if (!nextFiles.has(path)) await rm(join(out, path), { force: true });
859
+ return { study, md, json, strips };
860
+ } finally {
861
+ await Promise.all([rm(tmp, { recursive: true, force: true }),
862
+ stage ? rm(stage, { recursive: true, force: true }) : Promise.resolve()]);
863
+ }
864
+ }