@bydiorama/motion 0.0.0-stage → 0.4.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 (354) hide show
  1. package/CREDITS.md +62 -0
  2. package/LICENSE +21 -0
  3. package/README.md +142 -2
  4. package/catalog.json +4697 -0
  5. package/dist/npm/brief/brief.d.ts +28 -0
  6. package/dist/npm/brief/brief.js +159 -0
  7. package/dist/npm/brief/types.d.ts +75 -0
  8. package/dist/npm/brief/types.js +2 -0
  9. package/dist/npm/browser/motion.js +1039 -0
  10. package/dist/npm/browser/page.js +4821 -0
  11. package/dist/npm/browser/wizard.js +1511 -0
  12. package/dist/npm/build/design.d.ts +54 -0
  13. package/dist/npm/build/design.js +91 -0
  14. package/dist/npm/build/index.d.ts +39 -0
  15. package/dist/npm/build/index.js +66 -0
  16. package/dist/npm/build/iso.d.ts +41 -0
  17. package/dist/npm/build/iso.js +71 -0
  18. package/dist/npm/catalog.d.ts +24 -0
  19. package/dist/npm/catalog.js +23 -0
  20. package/dist/npm/cli/browser.d.ts +26 -0
  21. package/dist/npm/cli/browser.js +66 -0
  22. package/dist/npm/cli/capture.d.ts +26 -0
  23. package/dist/npm/cli/capture.js +94 -0
  24. package/dist/npm/cli/files.d.ts +14 -0
  25. package/dist/npm/cli/files.js +87 -0
  26. package/dist/npm/cli/frames.d.ts +27 -0
  27. package/dist/npm/cli/frames.js +125 -0
  28. package/dist/npm/cli/guard.d.ts +23 -0
  29. package/dist/npm/cli/guard.js +158 -0
  30. package/dist/npm/cli/library.d.ts +2 -0
  31. package/dist/npm/cli/library.js +55 -0
  32. package/dist/npm/cli/main.d.ts +17 -0
  33. package/dist/npm/cli/main.js +964 -0
  34. package/dist/npm/cli/motion.d.ts +2 -0
  35. package/dist/npm/cli/motion.js +6 -0
  36. package/dist/npm/cli/record.d.ts +36 -0
  37. package/dist/npm/cli/record.js +142 -0
  38. package/dist/npm/cli/review.d.ts +45 -0
  39. package/dist/npm/cli/review.js +139 -0
  40. package/dist/npm/cli/schema.d.ts +852 -0
  41. package/dist/npm/cli/schema.js +120 -0
  42. package/dist/npm/cli/server.d.ts +17 -0
  43. package/dist/npm/cli/server.js +135 -0
  44. package/dist/npm/core/ease.d.ts +39 -0
  45. package/dist/npm/core/ease.js +176 -0
  46. package/dist/npm/core/frame.d.ts +52 -0
  47. package/dist/npm/core/frame.js +60 -0
  48. package/dist/npm/core/shapes.d.ts +8 -0
  49. package/dist/npm/core/shapes.js +88 -0
  50. package/dist/npm/core/stagger.d.ts +19 -0
  51. package/dist/npm/core/stagger.js +77 -0
  52. package/dist/npm/core/tap.d.ts +19 -0
  53. package/dist/npm/core/tap.js +42 -0
  54. package/dist/npm/core/track.d.ts +4 -0
  55. package/dist/npm/core/track.js +23 -0
  56. package/dist/npm/dom/mount.d.ts +127 -0
  57. package/dist/npm/dom/mount.js +950 -0
  58. package/dist/npm/dom/page.d.ts +37 -0
  59. package/dist/npm/dom/page.js +77 -0
  60. package/dist/npm/dom/soundtrack.d.ts +13 -0
  61. package/dist/npm/dom/soundtrack.js +37 -0
  62. package/dist/npm/dom/stage.css.d.ts +1 -0
  63. package/dist/npm/dom/stage.css.js +44 -0
  64. package/dist/npm/dom/tokens.d.ts +10 -0
  65. package/dist/npm/dom/tokens.js +38 -0
  66. package/dist/npm/dom/ui-themes.css.d.ts +8 -0
  67. package/dist/npm/dom/ui-themes.css.js +9 -0
  68. package/dist/npm/film/beats.d.ts +64 -0
  69. package/dist/npm/film/beats.js +282 -0
  70. package/dist/npm/film/pace.d.ts +94 -0
  71. package/dist/npm/film/pace.js +396 -0
  72. package/dist/npm/film/resolve.d.ts +16 -0
  73. package/dist/npm/film/resolve.js +997 -0
  74. package/dist/npm/film/tempo.d.ts +19 -0
  75. package/dist/npm/film/tempo.js +34 -0
  76. package/dist/npm/film/tune.d.ts +17 -0
  77. package/dist/npm/film/tune.js +68 -0
  78. package/dist/npm/film/types.d.ts +416 -0
  79. package/dist/npm/film/types.js +16 -0
  80. package/dist/npm/index.d.ts +18 -0
  81. package/dist/npm/index.js +11 -0
  82. package/dist/npm/primitives/blur.d.ts +14 -0
  83. package/dist/npm/primitives/blur.js +59 -0
  84. package/dist/npm/primitives/canvas.d.ts +5 -0
  85. package/dist/npm/primitives/canvas.js +13 -0
  86. package/dist/npm/primitives/el/box.d.ts +2 -0
  87. package/dist/npm/primitives/el/box.js +24 -0
  88. package/dist/npm/primitives/el/frames.d.ts +15 -0
  89. package/dist/npm/primitives/el/frames.js +71 -0
  90. package/dist/npm/primitives/el/html.d.ts +2 -0
  91. package/dist/npm/primitives/el/html.js +14 -0
  92. package/dist/npm/primitives/el/image.d.ts +2 -0
  93. package/dist/npm/primitives/el/image.js +43 -0
  94. package/dist/npm/primitives/el/slot.d.ts +2 -0
  95. package/dist/npm/primitives/el/slot.js +25 -0
  96. package/dist/npm/primitives/el/text.d.ts +2 -0
  97. package/dist/npm/primitives/el/text.js +13 -0
  98. package/dist/npm/primitives/el/video.d.ts +6 -0
  99. package/dist/npm/primitives/el/video.js +179 -0
  100. package/dist/npm/primitives/fx/counter-roll.d.ts +2 -0
  101. package/dist/npm/primitives/fx/counter-roll.js +32 -0
  102. package/dist/npm/primitives/fx/depth-drift.d.ts +2 -0
  103. package/dist/npm/primitives/fx/depth-drift.js +44 -0
  104. package/dist/npm/primitives/fx/grid-ripple.d.ts +2 -0
  105. package/dist/npm/primitives/fx/grid-ripple.js +59 -0
  106. package/dist/npm/primitives/fx/odometer.d.ts +2 -0
  107. package/dist/npm/primitives/fx/odometer.js +80 -0
  108. package/dist/npm/primitives/fx/pan-across.d.ts +17 -0
  109. package/dist/npm/primitives/fx/pan-across.js +76 -0
  110. package/dist/npm/primitives/fx/path-draw.d.ts +2 -0
  111. package/dist/npm/primitives/fx/path-draw.js +105 -0
  112. package/dist/npm/primitives/fx/pin-drop.d.ts +2 -0
  113. package/dist/npm/primitives/fx/pin-drop.js +92 -0
  114. package/dist/npm/primitives/fx/shape-morph.d.ts +2 -0
  115. package/dist/npm/primitives/fx/shape-morph.js +65 -0
  116. package/dist/npm/primitives/fx/slow-push.d.ts +13 -0
  117. package/dist/npm/primitives/fx/slow-push.js +56 -0
  118. package/dist/npm/primitives/fx/stagger-fill.d.ts +2 -0
  119. package/dist/npm/primitives/fx/stagger-fill.js +33 -0
  120. package/dist/npm/primitives/index.d.ts +4 -0
  121. package/dist/npm/primitives/index.js +78 -0
  122. package/dist/npm/primitives/rig/browser-window.d.ts +2 -0
  123. package/dist/npm/primitives/rig/browser-window.js +142 -0
  124. package/dist/npm/primitives/rig/camera.d.ts +36 -0
  125. package/dist/npm/primitives/rig/camera.js +81 -0
  126. package/dist/npm/primitives/rig/footage-plane.d.ts +27 -0
  127. package/dist/npm/primitives/rig/footage-plane.js +257 -0
  128. package/dist/npm/primitives/rig/layer-stack.d.ts +39 -0
  129. package/dist/npm/primitives/rig/layer-stack.js +276 -0
  130. package/dist/npm/primitives/rig/orbit-ring.d.ts +2 -0
  131. package/dist/npm/primitives/rig/orbit-ring.js +59 -0
  132. package/dist/npm/primitives/rig/tab-stack.d.ts +9 -0
  133. package/dist/npm/primitives/rig/tab-stack.js +143 -0
  134. package/dist/npm/primitives/scene/bar-chart.d.ts +2 -0
  135. package/dist/npm/primitives/scene/bar-chart.js +83 -0
  136. package/dist/npm/primitives/scene/bento-grid.d.ts +49 -0
  137. package/dist/npm/primitives/scene/bento-grid.js +293 -0
  138. package/dist/npm/primitives/scene/grid-wall.d.ts +18 -0
  139. package/dist/npm/primitives/scene/grid-wall.js +110 -0
  140. package/dist/npm/primitives/scene/line-chart.d.ts +2 -0
  141. package/dist/npm/primitives/scene/line-chart.js +121 -0
  142. package/dist/npm/primitives/scene/logo-reveal.d.ts +2 -0
  143. package/dist/npm/primitives/scene/logo-reveal.js +117 -0
  144. package/dist/npm/primitives/scene/marquee-wall.d.ts +2 -0
  145. package/dist/npm/primitives/scene/marquee-wall.js +82 -0
  146. package/dist/npm/primitives/scene/post-carousel.d.ts +16 -0
  147. package/dist/npm/primitives/scene/post-carousel.js +195 -0
  148. package/dist/npm/primitives/scene/strip-cycle.d.ts +49 -0
  149. package/dist/npm/primitives/scene/strip-cycle.js +237 -0
  150. package/dist/npm/primitives/split.d.ts +34 -0
  151. package/dist/npm/primitives/split.js +105 -0
  152. package/dist/npm/primitives/texture/beat-field.d.ts +13 -0
  153. package/dist/npm/primitives/texture/beat-field.js +113 -0
  154. package/dist/npm/primitives/texture/gradient-drift.d.ts +2 -0
  155. package/dist/npm/primitives/texture/gradient-drift.js +56 -0
  156. package/dist/npm/primitives/texture/grain.d.ts +2 -0
  157. package/dist/npm/primitives/texture/grain.js +54 -0
  158. package/dist/npm/primitives/texture/halftone-field.d.ts +2 -0
  159. package/dist/npm/primitives/texture/halftone-field.js +36 -0
  160. package/dist/npm/primitives/texture/signal-field.d.ts +4 -0
  161. package/dist/npm/primitives/texture/signal-field.js +107 -0
  162. package/dist/npm/primitives/texture/vignette.d.ts +2 -0
  163. package/dist/npm/primitives/texture/vignette.js +23 -0
  164. package/dist/npm/primitives/transition/band-sweep.d.ts +22 -0
  165. package/dist/npm/primitives/transition/band-sweep.js +111 -0
  166. package/dist/npm/primitives/transition/beat-cut.d.ts +2 -0
  167. package/dist/npm/primitives/transition/beat-cut.js +10 -0
  168. package/dist/npm/primitives/transition/blur-dissolve.d.ts +2 -0
  169. package/dist/npm/primitives/transition/blur-dissolve.js +28 -0
  170. package/dist/npm/primitives/transition/camera-travel.d.ts +2 -0
  171. package/dist/npm/primitives/transition/camera-travel.js +69 -0
  172. package/dist/npm/primitives/transition/cover-reveal.d.ts +2 -0
  173. package/dist/npm/primitives/transition/cover-reveal.js +52 -0
  174. package/dist/npm/primitives/transition/curtain.d.ts +2 -0
  175. package/dist/npm/primitives/transition/curtain.js +40 -0
  176. package/dist/npm/primitives/transition/dive-in.d.ts +2 -0
  177. package/dist/npm/primitives/transition/dive-in.js +52 -0
  178. package/dist/npm/primitives/transition/fly-past.d.ts +2 -0
  179. package/dist/npm/primitives/transition/fly-past.js +87 -0
  180. package/dist/npm/primitives/transition/iris.d.ts +2 -0
  181. package/dist/npm/primitives/transition/iris.js +38 -0
  182. package/dist/npm/primitives/transition/overlay.d.ts +4 -0
  183. package/dist/npm/primitives/transition/overlay.js +24 -0
  184. package/dist/npm/primitives/transition/push.d.ts +2 -0
  185. package/dist/npm/primitives/transition/push.js +35 -0
  186. package/dist/npm/primitives/transition/signal-wipe.d.ts +2 -0
  187. package/dist/npm/primitives/transition/signal-wipe.js +67 -0
  188. package/dist/npm/primitives/transition/slant-wipe.d.ts +2 -0
  189. package/dist/npm/primitives/transition/slant-wipe.js +30 -0
  190. package/dist/npm/primitives/transition/stack-over.d.ts +2 -0
  191. package/dist/npm/primitives/transition/stack-over.js +38 -0
  192. package/dist/npm/primitives/transition/step-wipe.d.ts +2 -0
  193. package/dist/npm/primitives/transition/step-wipe.js +29 -0
  194. package/dist/npm/primitives/transition/strip-wipe.d.ts +40 -0
  195. package/dist/npm/primitives/transition/strip-wipe.js +121 -0
  196. package/dist/npm/primitives/transition/whip-pan.d.ts +2 -0
  197. package/dist/npm/primitives/transition/whip-pan.js +45 -0
  198. package/dist/npm/primitives/type/block-reveal.d.ts +2 -0
  199. package/dist/npm/primitives/type/block-reveal.js +61 -0
  200. package/dist/npm/primitives/type/char-cascade.d.ts +2 -0
  201. package/dist/npm/primitives/type/char-cascade.js +45 -0
  202. package/dist/npm/primitives/type/echo.d.ts +2 -0
  203. package/dist/npm/primitives/type/echo.js +57 -0
  204. package/dist/npm/primitives/type/fill-text.d.ts +14 -0
  205. package/dist/npm/primitives/type/fill-text.js +82 -0
  206. package/dist/npm/primitives/type/mask-reveal.d.ts +2 -0
  207. package/dist/npm/primitives/type/mask-reveal.js +58 -0
  208. package/dist/npm/primitives/type/scramble.d.ts +2 -0
  209. package/dist/npm/primitives/type/scramble.js +34 -0
  210. package/dist/npm/primitives/type/scribble-highlight.d.ts +2 -0
  211. package/dist/npm/primitives/type/scribble-highlight.js +84 -0
  212. package/dist/npm/primitives/type/shimmer.d.ts +2 -0
  213. package/dist/npm/primitives/type/shimmer.js +35 -0
  214. package/dist/npm/primitives/type/tracking-in.d.ts +2 -0
  215. package/dist/npm/primitives/type/tracking-in.js +37 -0
  216. package/dist/npm/primitives/type/typed-title.d.ts +2 -0
  217. package/dist/npm/primitives/type/typed-title.js +33 -0
  218. package/dist/npm/primitives/type/word-build.d.ts +2 -0
  219. package/dist/npm/primitives/type/word-build.js +44 -0
  220. package/dist/npm/primitives/type/word-roller.d.ts +2 -0
  221. package/dist/npm/primitives/type/word-roller.js +80 -0
  222. package/dist/npm/primitives/types.d.ts +183 -0
  223. package/dist/npm/primitives/types.js +5 -0
  224. package/dist/npm/primitives/ui/cursor-click.d.ts +4 -0
  225. package/dist/npm/primitives/ui/cursor-click.js +68 -0
  226. package/dist/npm/primitives/ui/page-scroll.d.ts +17 -0
  227. package/dist/npm/primitives/ui/page-scroll.js +98 -0
  228. package/dist/npm/review/fft.d.ts +4 -0
  229. package/dist/npm/review/fft.js +71 -0
  230. package/dist/npm/review/measure.d.ts +170 -0
  231. package/dist/npm/review/measure.js +577 -0
  232. package/dist/npm/tokens.d.ts +50 -0
  233. package/dist/npm/tokens.js +49 -0
  234. package/dist/npm/version.d.ts +1 -0
  235. package/dist/npm/version.js +1 -0
  236. package/examples/builder.film.mjs +18 -0
  237. package/films/feature-announcement.film.json +70 -0
  238. package/library/narratives/app-demo.md +64 -0
  239. package/library/narratives/brand-identity.md +78 -0
  240. package/library/narratives/capability-through-type.md +53 -0
  241. package/library/narratives/data-story.md +59 -0
  242. package/library/narratives/explainer.md +64 -0
  243. package/library/narratives/feature-announcement.md +68 -0
  244. package/library/narratives/infinite-loop.md +28 -0
  245. package/library/narratives/platform-launch.md +81 -0
  246. package/library/narratives/social-teaser.md +45 -0
  247. package/library/narratives/title-sequence.md +55 -0
  248. package/library/narratives/website-launch.md +65 -0
  249. package/library/primitives/fx/card-arrangements.md +26 -0
  250. package/library/primitives/fx/counter-roll.md +27 -0
  251. package/library/primitives/fx/depth-drift.md +32 -0
  252. package/library/primitives/fx/grid-ripple.md +58 -0
  253. package/library/primitives/fx/letter-interleave.md +26 -0
  254. package/library/primitives/fx/marquee-highlight.md +27 -0
  255. package/library/primitives/fx/mosaic-fill.md +23 -0
  256. package/library/primitives/fx/odometer.md +44 -0
  257. package/library/primitives/fx/pan-across.md +63 -0
  258. package/library/primitives/fx/path-draw.md +54 -0
  259. package/library/primitives/fx/pin-drop.md +51 -0
  260. package/library/primitives/fx/radial-burst.md +33 -0
  261. package/library/primitives/fx/shape-morph.md +45 -0
  262. package/library/primitives/fx/slow-push.md +63 -0
  263. package/library/primitives/fx/stagger-fill.md +28 -0
  264. package/library/primitives/rig/browser-window.md +113 -0
  265. package/library/primitives/rig/flip-ticker.md +26 -0
  266. package/library/primitives/rig/footage-plane.md +90 -0
  267. package/library/primitives/rig/layer-stack.md +168 -0
  268. package/library/primitives/rig/orbit-ring.md +43 -0
  269. package/library/primitives/rig/rolodex.md +31 -0
  270. package/library/primitives/rig/tab-stack.md +116 -0
  271. package/library/primitives/rig/tumbling-object.md +27 -0
  272. package/library/primitives/scene/bar-chart.md +49 -0
  273. package/library/primitives/scene/bento-grid.md +74 -0
  274. package/library/primitives/scene/end-card.md +28 -0
  275. package/library/primitives/scene/grid-wall.md +61 -0
  276. package/library/primitives/scene/hero-object.md +33 -0
  277. package/library/primitives/scene/kinetic-headline.md +34 -0
  278. package/library/primitives/scene/line-chart.md +47 -0
  279. package/library/primitives/scene/logo-reveal.md +53 -0
  280. package/library/primitives/scene/marquee-wall.md +33 -0
  281. package/library/primitives/scene/mosaic.md +28 -0
  282. package/library/primitives/scene/post-carousel.md +68 -0
  283. package/library/primitives/scene/specimen-grid.md +28 -0
  284. package/library/primitives/scene/stat-with-evidence.md +34 -0
  285. package/library/primitives/scene/strip-cycle.md +122 -0
  286. package/library/primitives/scene/zoomed-ui.md +29 -0
  287. package/library/primitives/texture/ascii.md +22 -0
  288. package/library/primitives/texture/beat-field.md +85 -0
  289. package/library/primitives/texture/depth-fade.md +23 -0
  290. package/library/primitives/texture/dither.md +27 -0
  291. package/library/primitives/texture/gradient-drift.md +50 -0
  292. package/library/primitives/texture/grain.md +39 -0
  293. package/library/primitives/texture/halftone-field.md +26 -0
  294. package/library/primitives/texture/signal-field.md +61 -0
  295. package/library/primitives/texture/vignette.md +53 -0
  296. package/library/primitives/transition/band-sweep.md +63 -0
  297. package/library/primitives/transition/beat-cut.md +27 -0
  298. package/library/primitives/transition/blur-dissolve.md +36 -0
  299. package/library/primitives/transition/camera-travel.md +57 -0
  300. package/library/primitives/transition/collapse-to-anchor.md +27 -0
  301. package/library/primitives/transition/cover-reveal.md +47 -0
  302. package/library/primitives/transition/curtain.md +42 -0
  303. package/library/primitives/transition/dive-in.md +51 -0
  304. package/library/primitives/transition/fly-past.md +51 -0
  305. package/library/primitives/transition/iris.md +49 -0
  306. package/library/primitives/transition/layout-locked-swap.md +28 -0
  307. package/library/primitives/transition/light-dark-flip.md +27 -0
  308. package/library/primitives/transition/push.md +47 -0
  309. package/library/primitives/transition/signal-wipe.md +52 -0
  310. package/library/primitives/transition/slant-wipe.md +44 -0
  311. package/library/primitives/transition/stack-over.md +51 -0
  312. package/library/primitives/transition/step-wipe.md +32 -0
  313. package/library/primitives/transition/strip-wipe.md +80 -0
  314. package/library/primitives/transition/torn-edge.md +26 -0
  315. package/library/primitives/transition/whip-pan.md +47 -0
  316. package/library/primitives/transition/zoom-through-letter.md +27 -0
  317. package/library/primitives/type/accent-number.md +22 -0
  318. package/library/primitives/type/block-reveal.md +41 -0
  319. package/library/primitives/type/char-cascade.md +65 -0
  320. package/library/primitives/type/echo.md +44 -0
  321. package/library/primitives/type/fill-text.md +63 -0
  322. package/library/primitives/type/focus-blur.md +22 -0
  323. package/library/primitives/type/inline-chips.md +27 -0
  324. package/library/primitives/type/mask-reveal.md +65 -0
  325. package/library/primitives/type/parting.md +23 -0
  326. package/library/primitives/type/per-word-restyle.md +28 -0
  327. package/library/primitives/type/scramble.md +26 -0
  328. package/library/primitives/type/scribble-highlight.md +47 -0
  329. package/library/primitives/type/shimmer.md +39 -0
  330. package/library/primitives/type/split-flap.md +26 -0
  331. package/library/primitives/type/style-multiply.md +23 -0
  332. package/library/primitives/type/tracking-in.md +40 -0
  333. package/library/primitives/type/typed-title.md +27 -0
  334. package/library/primitives/type/word-build.md +37 -0
  335. package/library/primitives/type/word-roller.md +52 -0
  336. package/library/primitives/type/writing-ticker.md +27 -0
  337. package/library/primitives/ui/collab-cursors.md +27 -0
  338. package/library/primitives/ui/cursor-click.md +61 -0
  339. package/library/primitives/ui/page-scroll.md +58 -0
  340. package/library/primitives/ui/prompt-typing.md +29 -0
  341. package/library/primitives/ui/streamed-result.md +23 -0
  342. package/library/primitives/ui/tour-hold.md +27 -0
  343. package/library/styles/brand-system.md +49 -0
  344. package/library/styles/clean-explainer.md +42 -0
  345. package/library/styles/dark-showcase.md +48 -0
  346. package/library/styles/editorial-type.md +37 -0
  347. package/library/styles/kinetic-poster.md +54 -0
  348. package/library/styles/product-ui.md +44 -0
  349. package/library/styles/studio-loop.md +41 -0
  350. package/library.json +1467 -0
  351. package/package.json +64 -4
  352. package/schema/film.schema.json +1316 -0
  353. package/showcase/vendor/DIALKIT-LICENSE +21 -0
  354. package/src/studio/theme/fonts/OFL.txt +94 -0
@@ -0,0 +1,964 @@
1
+ var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExtension) || function (path, preserveJsx) {
2
+ if (typeof path === "string" && /^\.\.?\//.test(path)) {
3
+ return path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) {
4
+ return tsx ? preserveJsx ? ".jsx" : ".js" : d && (!ext || !cm) ? m : (d + ext + "." + cm.toLowerCase() + "js");
5
+ });
6
+ }
7
+ return path;
8
+ };
9
+ // The command line. Every command that reports on a film can print JSON
10
+ // (--json), so an agent reads results as data and a person reads them as text.
11
+ import { spawn } from 'node:child_process';
12
+ import { createHash } from 'node:crypto';
13
+ import { once } from 'node:events';
14
+ import fs from 'node:fs';
15
+ import { registerHooks } from 'node:module';
16
+ import path from 'node:path';
17
+ import { pathToFileURL } from 'node:url';
18
+ import { buildCatalog } from "../catalog.js";
19
+ import { describeTimeline, resolveFilm } from "../film/resolve.js";
20
+ import { applyTune, bake } from "../film/tune.js";
21
+ import { describePace, pace } from "../film/pace.js";
22
+ import { sceneFromDesign } from "../build/design.js";
23
+ import { analyseBeats, loopWindows, offDownbeat, seams } from "../film/beats.js";
24
+ import { open } from "./browser.js";
25
+ import { capture } from "./capture.js";
26
+ import { record } from "./record.js";
27
+ import { describe as describeReview, filmCuts, review } from "./review.js";
28
+ import { Analyser, findings, REFERENCE_SHORT } from "../review/measure.js";
29
+ import { bundle, wizardPage, filmName, inlineCss, readFilm, readJson, readTune, ROOT, tunePath, writeJson } from "./files.js";
30
+ import { filmSchema } from "./schema.js";
31
+ import { readLibrary } from "./library.js";
32
+ import { checkAnswers, writeBrief } from "../brief/brief.js";
33
+ import { serve, shell } from "./server.js";
34
+ const HELP = `motion <command> [film.json] [options]
35
+
36
+ Start
37
+ wizard [--port n] [--out file.html] Answer a few questions; get a brief to paste into Claude or ChatGPT
38
+ brief <answers.json> [--out file.md] The same brief from saved answers, for scripts and agents
39
+
40
+ Write and check
41
+ catalog [--json|--write|--check] What a film may use: primitives, params, tokens, eases
42
+ make <script.mjs> [--out f.json] Run a script that returns a film; check it and write the JSON
43
+ validate <film...> [--json] Check films without a browser
44
+ import <design.json> [--id scene] [--step 0.5b] [--fit cover] [--align 0,50] [--out scene.json]
45
+ A scene that builds a layout from its exported parts, on its artboard
46
+ inspect <film> [--json] The resolved timeline: where every scene and layer lands
47
+ beats <audio|film> [--bars n] [--bar 4] [--json] A soundtrack's tempo, downbeats and the
48
+ stretches that loop; for a film, its tempo, audio.from and seam
49
+ pace <film> [--json] The rhythm: hand-overs against scenes, lengths of changes and rests,
50
+ share in motion, and with a tempo, the beat grid
51
+ notes <film> [--json] The person's open notes, with where each one points
52
+
53
+ Look
54
+ preview <film> [--port n] The studio: scrub, tune, pin notes. Saves <film>.tune.json
55
+ stills <film> [--at 1.2,3] [--scale n] Frames as PNG plus a contact sheet, in out/<film>/
56
+ check <film> [--json] [--loop] Draw it and test: repeatable frames, layers on stage, page errors;
57
+ --loop (or "loop": true) measures the seam from last frame to first
58
+ review <film|video.mp4> [--json] [--loop] [--video file]
59
+ Watch the motion frame by frame: a camera that wiggles, jumps or
60
+ stalls, parts floating against the rest, frames that blink, flicker
61
+ or shimmer. Run it on every render and on recorded footage
62
+
63
+ Collect
64
+ capture <url> [--sections] [--selector css] [--out dir] [--width 1440] [--scale 2]
65
+ [--hide sel,sel] [--keep-banners] [--keep-header]
66
+ Screenshots of a page, or of each section, for a film to use
67
+ record <url> [--out file.mp4|dir] [--duration 4] [--fps 60] [--size 1080x1920] [--scale 1]
68
+ [--scheme light|dark] [--lead 0] [--crf 12] [--marks sel,sel] [--no-guard]
69
+ Footage of a live page on a virtual clock: its timers, frames and
70
+ CSS animations step a frame at a time, so the footage is exact.
71
+ The guard reports layout moves, re-wraps, CSS zoom and scaled
72
+ stages; --marks writes those elements' boxes per frame to
73
+ <out>.marks.json, for a footage plane to aim at
74
+
75
+ Deliver
76
+ render <film> [--out file.mp4] [--scale 2] [--crf 15] [--fast] MP4 through ffmpeg, plus a report;
77
+ frames go as PNG, or JPEG with --fast for drafts
78
+ build <film> [--out file.html] One self-contained page that plays the film
79
+ bake <film> Write the tuning into the film and empty the tune file
80
+
81
+ Options for every command that draws
82
+ --css <file> A stylesheet to load, e.g. a bydiorama/ui theme. Repeat for more.
83
+ --no-tune Ignore <film>.tune.json
84
+ --browser <path> A Chromium-based browser to draw with (Chrome, Brave, Edge),
85
+ when Playwright's own is not installed. Or set MOTION_CHROMIUM.
86
+ `;
87
+ function parse(argv) {
88
+ const out = { _: [], flags: {}, css: [] };
89
+ const BOOL = new Set(['json', 'write', 'check', 'no-tune', 'help', 'loop', 'sections', 'keep-banners', 'keep-header', 'fast', 'no-guard']);
90
+ for (let i = 0; i < argv.length; i++) {
91
+ const a = argv[i];
92
+ if (!a.startsWith('--')) {
93
+ out._.push(a);
94
+ continue;
95
+ }
96
+ const key = a.slice(2);
97
+ if (BOOL.has(key)) {
98
+ out.flags[key] = true;
99
+ continue;
100
+ }
101
+ const value = argv[++i];
102
+ if (value === undefined)
103
+ throw new Error(`--${key} needs a value`);
104
+ if (key === 'css')
105
+ out.css.push(value);
106
+ else
107
+ out.flags[key] = value;
108
+ }
109
+ return out;
110
+ }
111
+ const print = (data) => console.log(JSON.stringify(data, null, 2));
112
+ const line = (i) => `${i.level === 'error' ? 'ERROR' : 'warn '} ${i.path || 'film'}: ${i.message}${i.hint ? ` ${i.hint}` : ''}`;
113
+ function load(file, args) {
114
+ const film = readFilm(file);
115
+ const { film: tuned, orphans } = args.flags['no-tune'] ? { film, orphans: [] } : applyTune(film, readTune(file));
116
+ const res = resolveFilm(tuned);
117
+ for (const p of orphans) {
118
+ res.issues.push({ level: 'warning', code: 'orphan-override', path: p, message: 'This tuning override points at something the film no longer has.', hint: `Remove it from ${path.basename(tunePath(file))}, or restore the scene or layer id.` });
119
+ }
120
+ return { file, res, orphans };
121
+ }
122
+ const browserOpt = (args) => (typeof args.flags.browser === 'string' ? { browser: args.flags.browser } : {});
123
+ function need(args) {
124
+ const file = args._[1];
125
+ if (!file)
126
+ throw new Error('Name a film file.\n\n' + HELP);
127
+ return file;
128
+ }
129
+ function timelineOrExit(l, json) {
130
+ if (l.res.timeline)
131
+ return l.res.timeline;
132
+ if (json)
133
+ print({ ok: false, file: l.file, issues: l.res.issues });
134
+ else
135
+ l.res.issues.forEach((i) => console.error(line(i)));
136
+ process.exit(1);
137
+ }
138
+ /** The moments worth looking at: each layer settled, each scene's middle and end, each hand-over's middle. */
139
+ export function keyMoments(t) {
140
+ const frame = 1 / t.fps, moments = new Map();
141
+ const add = (time, label) => {
142
+ const snapped = Math.min(t.duration - frame, Math.max(0, Math.round(time * t.fps) / t.fps));
143
+ const key = Math.round(snapped * t.fps);
144
+ if (!moments.has(key))
145
+ moments.set(key, label);
146
+ };
147
+ for (const s of t.scenes) {
148
+ for (const l of s.layers)
149
+ add(s.start + Math.min(l.end, s.length - frame), `${s.id} › ${l.id} settled`);
150
+ add(s.start + s.length / 2, `${s.id} middle`);
151
+ add(s.end - (s.out ? s.out.duration / 2 : frame), s.out ? `${s.id} → ${s.out.use}` : `${s.id} end`);
152
+ }
153
+ return [...moments.entries()].sort((a, b) => a[0] - b[0]).map(([k, label]) => ({ t: k / t.fps, label }));
154
+ }
155
+ // ---- commands -------------------------------------------------------------------
156
+ function catalog(args) {
157
+ const data = buildCatalog();
158
+ const files = [
159
+ [path.join(ROOT, 'catalog.json'), data],
160
+ [path.join(ROOT, 'library.json'), readLibrary()],
161
+ [path.join(ROOT, 'schema/film.schema.json'), filmSchema(data)],
162
+ ];
163
+ if (args.flags.write) {
164
+ for (const [f, d] of files)
165
+ writeJson(f, d);
166
+ console.log('catalog.json, library.json and schema/film.schema.json written');
167
+ }
168
+ else if (args.flags.check) {
169
+ const stale = files.filter(([f, d]) => !fs.existsSync(f) || fs.readFileSync(f, 'utf8') !== `${JSON.stringify(d, null, 2)}\n`).map(([f]) => path.relative(ROOT, f));
170
+ if (stale.length) {
171
+ console.error(`Out of date: ${stale.join(', ')}. Run: pnpm catalog`);
172
+ process.exit(1);
173
+ }
174
+ console.log('catalog is up to date');
175
+ }
176
+ else if (args.flags.json)
177
+ print(data);
178
+ else {
179
+ const params = (p) => Object.entries(p).map(([k, s]) => `${k}=${String(s.default)}${s.min !== undefined ? ` (${s.min}–${s.max}${s.unit ? ` ${s.unit}` : ''})` : ''}`).join(', ');
180
+ console.log(`motion ${data.motion}\n\nPrimitives`);
181
+ for (const p of data.primitives) {
182
+ console.log(` ${p.slug.padEnd(22)} ${p.summary}`);
183
+ console.log(` props: ${Object.entries(p.props).map(([k, s]) => `${k}${s.required ? '*' : ''}: ${s.type}`).join(', ') || 'none'}`);
184
+ if (Object.keys(p.params).length)
185
+ console.log(` params: ${params(p.params)}`);
186
+ }
187
+ console.log('\nTransitions');
188
+ for (const p of data.transitions)
189
+ console.log(` ${p.slug.padEnd(26)} ${p.summary}\n params: ${params(p.params)}`);
190
+ console.log(`\nMoves ${data.moves.join(', ')}\nTracks ${data.tracks.join(', ')}\nEases ${data.eases.join(', ')}\nSizes ${data.sizes.join(', ')}\nColors ${data.colors.join(', ')}\n\nFull detail: motion catalog --json`);
191
+ }
192
+ }
193
+ /** Where `make` writes: beside the script, as <name>.film.json. */
194
+ export const madePath = (script) => script.replace(/(\.film)?\.(m?js|m?ts)$/, '') + '.film.json';
195
+ /**
196
+ * `@bydiorama/motion` and `@bydiorama/motion/build`, for a script outside this repository
197
+ * (from the Claude plugin, for example), resolve to this copy of the library.
198
+ */
199
+ const moduleExtension = path.extname(import.meta.filename);
200
+ export const LIBRARY_ENTRIES = {
201
+ '@bydiorama/motion': path.resolve(import.meta.dirname, `../index${moduleExtension}`),
202
+ '@bydiorama/motion/build': path.resolve(import.meta.dirname, `../build/index${moduleExtension}`),
203
+ };
204
+ let libraryResolved = false;
205
+ function resolveLibraryImports() {
206
+ if (libraryResolved)
207
+ return;
208
+ libraryResolved = true;
209
+ registerHooks({
210
+ resolve: (specifier, context, next) => specifier in LIBRARY_ENTRIES
211
+ ? { url: pathToFileURL(LIBRARY_ENTRIES[specifier]).href, shortCircuit: true }
212
+ : next(specifier, context),
213
+ });
214
+ }
215
+ async function make(args) {
216
+ const script = need(args), json = !!args.flags.json;
217
+ resolveLibraryImports();
218
+ const mod = await import(__rewriteRelativeImportExtension(pathToFileURL(path.resolve(script)).href));
219
+ let value = mod.default;
220
+ if (typeof value === 'function')
221
+ value = await value();
222
+ if (value === undefined)
223
+ throw new Error(`${script} has no default export. End it with: export default film({ ... })`);
224
+ const out = path.resolve(typeof args.flags.out === 'string' ? args.flags.out : madePath(script));
225
+ const res = resolveFilm(value);
226
+ if (json)
227
+ print({ ok: res.ok, file: out, written: res.ok, issues: res.issues, ...(res.timeline ? { duration: res.timeline.duration } : {}) });
228
+ else
229
+ res.issues.forEach((i) => console.log(line(i)));
230
+ if (!res.ok) {
231
+ if (!json)
232
+ console.error(`Nothing written: the film has ${res.issues.filter((i) => i.level === 'error').length} error(s).`);
233
+ process.exit(1);
234
+ }
235
+ writeJson(out, value);
236
+ if (!json)
237
+ console.log(`${path.relative(process.cwd(), out)} written: ${res.timeline.duration.toFixed(2)} s, ${res.issues.length} warning(s).`);
238
+ }
239
+ async function captureCmd(args) {
240
+ const url = args._[1];
241
+ if (!url)
242
+ throw new Error('Name a page to capture: motion capture https://example.com --sections');
243
+ const href = /^[a-z]+:\/\//i.test(url) ? url : fs.existsSync(url) ? pathToFileURL(path.resolve(url)).href : `https://${url}`;
244
+ const host = new URL(href).hostname || filmName(url).replace(/\.html?$/, '') || 'page';
245
+ const num = (k, d) => { const v = Number(args.flags[k] ?? d); if (!(v > 0))
246
+ throw new Error(`--${k} takes a number above zero.`); return v; };
247
+ const shots = await capture({
248
+ url: href, out: path.resolve(typeof args.flags.out === 'string' ? args.flags.out : path.join('out', 'capture', host)),
249
+ sections: !!args.flags.sections, ...(typeof args.flags.selector === 'string' ? { selector: args.flags.selector } : {}),
250
+ width: num('width', 1440), scale: num('scale', 2),
251
+ hide: typeof args.flags.hide === 'string' ? args.flags.hide.split(',').map((x) => x.trim()).filter(Boolean) : [],
252
+ keepBanners: !!args.flags['keep-banners'], keepHeader: !!args.flags['keep-header'], ...browserOpt(args),
253
+ });
254
+ const dir = path.dirname(shots[0].file);
255
+ writeJson(path.join(dir, 'capture.json'), { url: href, width: num('width', 1440), scale: num('scale', 2), shots: shots.map((x) => ({ ...x, file: path.basename(x.file) })) });
256
+ if (args.flags.json)
257
+ return print({ url: href, dir, shots });
258
+ console.log(`${shots.length} screenshot(s) at ${num('scale', 2)}× in ${path.relative(process.cwd(), dir) || '.'}/`);
259
+ for (const x of shots)
260
+ console.log(` ${path.basename(x.file).padEnd(32)} ${x.width}×${x.height} px at y ${x.y}`);
261
+ }
262
+ async function recordCmd(args) {
263
+ const url = args._[1];
264
+ if (!url)
265
+ throw new Error('Name a page to record: motion record http://localhost:5173/ --duration 4 --out shot.mp4');
266
+ const href = /^[a-z]+:\/\//i.test(url) ? url : fs.existsSync(url) ? pathToFileURL(path.resolve(url)).href : `https://${url}`;
267
+ const num = (k, d, min = 0) => { const v = Number(args.flags[k] ?? d); if (!(v >= min) || !Number.isFinite(v))
268
+ throw new Error(`--${k} takes a number of at least ${min}.`); return v; };
269
+ const size = String(args.flags.size ?? '1080x1920').split('x').map(Number);
270
+ if (size.length !== 2 || !size.every((n) => n > 0))
271
+ throw new Error('--size is width x height in CSS px, e.g. 1080x1920.');
272
+ const scheme = args.flags.scheme ?? 'light';
273
+ if (scheme !== 'light' && scheme !== 'dark')
274
+ throw new Error('--scheme is light or dark.');
275
+ const out = path.resolve(typeof args.flags.out === 'string' ? args.flags.out : path.join('out', 'record', 'footage.mp4'));
276
+ const json = !!args.flags.json;
277
+ const res = await record({
278
+ url: href, out, duration: num('duration', 4, 1 / 120), fps: num('fps', 60, 1), size: [size[0], size[1]], scale: num('scale', 1, 0.25),
279
+ scheme, lead: num('lead', 0), crf: num('crf', 12), ...browserOpt(args), guard: !args.flags['no-guard'],
280
+ ...(typeof args.flags.marks === 'string' ? { marks: args.flags.marks.split(',').map((m) => m.trim()).filter(Boolean) } : {}),
281
+ ...(json ? {} : { onProgress: (d, n) => { if (d === n || d % 30 === 0)
282
+ process.stderr.write(`\r frame ${d}/${n}`); if (d === n)
283
+ process.stderr.write('\n'); } }),
284
+ });
285
+ if (json)
286
+ return print(res);
287
+ console.log(`${res.frames} frame(s) at ${res.size[0]}×${res.size[1]} → ${path.relative(process.cwd(), res.out) || res.out}`);
288
+ for (const e of res.errors)
289
+ console.log(`warn page: ${e}`);
290
+ for (const g of res.guard)
291
+ console.log(`warn ${g}`);
292
+ if (res.marks)
293
+ console.log(`Marks: ${path.relative(process.cwd(), res.marks) || res.marks}`);
294
+ if (!res.guard.length)
295
+ console.log('Guard: the page moved by transforms only, with no re-wraps or CSS zoom.');
296
+ }
297
+ function validate(args) {
298
+ const files = args._.slice(1);
299
+ if (!files.length)
300
+ throw new Error('Name one or more film files.');
301
+ const results = files.map((f) => load(f, args));
302
+ // The rhythm checks are warnings: a film that stumbles still plays.
303
+ for (const r of results)
304
+ if (r.res.timeline)
305
+ r.res.issues.push(...pace(r.res.timeline).issues);
306
+ if (args.flags.json)
307
+ print(results.map((r) => ({ file: r.file, ok: r.res.ok, issues: r.res.issues })));
308
+ else
309
+ for (const r of results) {
310
+ r.res.issues.forEach((i) => console.log(line(i)));
311
+ const e = r.res.issues.filter((i) => i.level === 'error').length;
312
+ console.log(`${r.file}: ${e ? `${e} error(s)` : 'ok'}, ${r.res.issues.length - e} warning(s)${r.res.timeline ? `, ${r.res.timeline.duration.toFixed(2)} s` : ''}`);
313
+ }
314
+ if (results.some((r) => !r.res.ok))
315
+ process.exit(1);
316
+ }
317
+ function inspect(args) {
318
+ const l = load(need(args), args), json = !!args.flags.json;
319
+ const t = timelineOrExit(l, json);
320
+ if (json) {
321
+ print({
322
+ ok: true, file: l.file, duration: t.duration, fps: t.fps, frames: t.frames, size: t.size, issues: l.res.issues,
323
+ scenes: t.scenes.map((s) => ({
324
+ id: s.id, start: s.start, end: s.end, length: s.length, ...(s.out ? { out: s.out } : {}),
325
+ layers: s.layers.map((x) => ({ id: x.id, use: x.use, start: s.start + x.start, end: s.start + x.end, params: x.params, ...(x.enter ? { enter: x.enter } : {}), ...(x.exit ? { exit: x.exit } : {}) })),
326
+ })),
327
+ });
328
+ }
329
+ else {
330
+ console.log(describeTimeline(t));
331
+ if (l.res.issues.length) {
332
+ console.log('');
333
+ l.res.issues.forEach((i) => console.log(line(i)));
334
+ }
335
+ }
336
+ }
337
+ /** Decodes an audio file to mono samples with ffmpeg. */
338
+ async function decode(file, rate) {
339
+ const ff = spawn('ffmpeg', ['-v', 'error', '-i', file, '-ac', '1', '-ar', String(rate), '-f', 'f32le', 'pipe:1']);
340
+ const chunks = [];
341
+ let err = '';
342
+ ff.stdout.on('data', (c) => chunks.push(c));
343
+ ff.stderr.on('data', (c) => { err += c; });
344
+ const [code] = await once(ff, 'close');
345
+ if (code !== 0)
346
+ throw new Error(`ffmpeg could not read ${file}: ${err.trim()}`);
347
+ const buf = Buffer.concat(chunks);
348
+ return new Float32Array(buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.length - (buf.length % 4)));
349
+ }
350
+ async function beatsCmd(args) {
351
+ const target = need(args), json = !!args.flags.json, RATE = 22050;
352
+ const isFilm = target.endsWith('.json');
353
+ const film = isFilm ? readFilm(target) : undefined;
354
+ if (film && !film.audio)
355
+ throw new Error(`${target} has no audio. Name an audio file, or give the film a soundtrack.`);
356
+ const sound = film ? path.resolve(path.dirname(path.resolve(target)), film.audio.src) : target;
357
+ if (!fs.existsSync(sound))
358
+ throw new Error(`${sound} not found.`);
359
+ const bar = Number(args.flags.bar ?? film?.tempo?.bar ?? 4);
360
+ const samples = await decode(sound, RATE);
361
+ const a = analyseBeats(samples, RATE, { bar });
362
+ const barLen = a.beat * a.bar;
363
+ // The film, measured against its music.
364
+ let filmReport;
365
+ let bars = args.flags.bars !== undefined ? Number(args.flags.bars) : undefined;
366
+ if (film) {
367
+ const t = timelineOrExit(load(target, args), json);
368
+ const from = film.audio.from ?? 0, off = offDownbeat(a, from);
369
+ const beatOff = Math.round(((from - a.downbeat) / a.beat) % a.bar + a.bar) % a.bar;
370
+ const filmBars = t.duration / barLen;
371
+ bars ??= Math.round(filmBars);
372
+ const seam = t.loop ? seams(samples, RATE, a)(from, from + t.duration) : undefined;
373
+ filmReport = {
374
+ tempo: film.tempo?.bpm, measured: a.bpm, tempoOff: film.tempo ? Math.round((film.tempo.bpm - a.bpm) * 100) / 100 : undefined,
375
+ from, offBeat: Math.round((((from - a.downbeat) % a.beat) + a.beat * 1.5) % a.beat * 1000 - a.beat * 500) / 1000, barBeat: beatOff + 1,
376
+ nearestDownbeat: Math.round((from - off) * 1000) / 1000, bars: Math.round(filmBars * 100) / 100, ...(seam !== undefined ? { seam } : {}),
377
+ };
378
+ }
379
+ const loops = bars ? loopWindows(samples, RATE, a, bars) : [];
380
+ if (json)
381
+ return print({ file: sound, ...a, downbeats: undefined, loops, ...(filmReport ? { film: filmReport } : {}) });
382
+ console.log(`${path.basename(sound)}: ${a.bpm} bpm (a beat ${a.beat.toFixed(4)} s, a bar of ${a.bar} ${barLen.toFixed(3)} s), confidence ${a.confidence.toFixed(2)}${a.confidence < 0.3 ? ': check by ear' : ''}`);
383
+ console.log(`First downbeat at ${a.downbeat.toFixed(3)} s, then every ${barLen.toFixed(3)} s.`);
384
+ if (filmReport) {
385
+ const f = filmReport;
386
+ console.log(`\nThe film`);
387
+ console.log(f.tempo === undefined ? ` No tempo: set "tempo": { "bpm": ${a.bpm} }.` : Math.abs(f.tempoOff) <= 0.02 ? ` tempo ${f.tempo} matches the music.` : ` tempo ${f.tempo} is ${f.tempoOff > 0 ? 'above' : 'below'} the music's ${a.bpm} by ${Math.abs(f.tempoOff)} bpm: cuts drift ${(Math.abs(f.tempoOff) / a.bpm * 100).toFixed(2)}% a beat. Set it to ${a.bpm}.`);
388
+ const ms = Math.round(f.offBeat * 1000);
389
+ console.log(` audio.from ${f.from} is ${Math.abs(ms) <= 5 ? 'on a beat' : `${Math.abs(ms)} ms ${ms > 0 ? 'after' : 'before'} a beat`}, beat ${f.barBeat} of the bar as measured${f.barBeat === 1 ? '' : ` (the nearest downbeat is ${f.nearestDownbeat} s)`}.${Math.abs(ms) > 5 ? ` To put the film's start on the beat: ${Math.round((f.from - f.offBeat) * 1000) / 1000}.` : ''}`);
390
+ console.log(` The film runs ${f.bars} bars of the music.${Math.abs(f.bars - Math.round(f.bars)) > 0.02 ? ' A loop that is not whole bars will not loop in the music.' : ''}`);
391
+ if (f.seam !== undefined)
392
+ console.log(` Across its loop the music matches ${f.seam.toFixed(2)} (1 is the same either side of the seam; the best windows below).`);
393
+ }
394
+ if (loops.length) {
395
+ console.log(`\nThe ${bars} bars that loop best (from: set as audio.from)`);
396
+ for (const w of loops)
397
+ console.log(` from ${w.from.toFixed(3)} s to ${w.to.toFixed(3)} s match ${w.match.toFixed(2)}`);
398
+ }
399
+ console.log(`\nThe downbeat is the beat where the harmony turns and the low end hits; when it is ambiguous it may be read a beat or two out. Trust the tempo; check the bar by ear.`);
400
+ }
401
+ function importCmd(args) {
402
+ const file = need(args);
403
+ const design = readJson(file);
404
+ if (!design || !(design.width > 0) || !(design.height > 0) || !Array.isArray(design.layers)) {
405
+ throw new Error(`${file} is not a design: it needs width, height and layers ([{ name, x, y, width, height, src | fill }], bottom to top).`);
406
+ }
407
+ const id = typeof args.flags.id === 'string' ? args.flags.id : path.basename(file).replace(/\.json$/, '').toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '') || 'design';
408
+ const stepFlag = args.flags.step, step = typeof stepFlag === 'string' ? (/^\d+(\.\d+)?$/.test(stepFlag) ? Number(stepFlag) : stepFlag) : undefined;
409
+ const fit = typeof args.flags.fit === 'string' ? args.flags.fit : undefined;
410
+ const alignFlag = typeof args.flags.align === 'string' ? args.flags.align.split(',').map(Number) : undefined;
411
+ if (alignFlag && (alignFlag.length !== 2 || alignFlag.some((v) => !(v >= 0 && v <= 100))))
412
+ throw new Error('--align is x,y in % of the stage, e.g. 0,50.');
413
+ const scene = sceneFromDesign(id, design, { ...(step !== undefined ? { step } : {}), ...(fit ? { fit } : {}), ...(alignFlag ? { align: alignFlag } : {}) });
414
+ if (typeof args.flags.out === 'string') {
415
+ writeJson(args.flags.out, scene);
416
+ console.log(`${args.flags.out} written: scene "${id}", ${scene.layers.length} layers on a ${design.width} × ${design.height} artboard. Add it to a film's scenes.`);
417
+ }
418
+ else
419
+ print(scene);
420
+ }
421
+ function paceCmd(args) {
422
+ const l = load(need(args), args), json = !!args.flags.json;
423
+ const t = timelineOrExit(l, json);
424
+ const p = pace(t);
425
+ if (json)
426
+ return print({ ok: true, file: l.file, ...p, issues: [...l.res.issues, ...p.issues] });
427
+ console.log(describePace(t, p));
428
+ const all = [...l.res.issues.filter((i) => i.level === 'error'), ...p.issues];
429
+ console.log(all.length ? '' : '\nThe rhythm checks pass.');
430
+ all.forEach((i) => console.log(line(i)));
431
+ }
432
+ function notes(args) {
433
+ const file = need(args), tune = readTune(file);
434
+ const l = load(file, args);
435
+ const list = (tune.notes ?? []).map((n) => {
436
+ const scene = l.res.timeline?.scenes.findLast((s) => n.t >= s.start && n.t < s.end);
437
+ const onScreen = scene?.layers.filter((x) => n.t >= scene.start + x.start).map((x) => x.id) ?? [];
438
+ return { ...n, at: scene ? { scene: scene.id, sceneTime: Number((n.t - scene.start).toFixed(3)), layersOnScreen: onScreen } : null };
439
+ });
440
+ if (args.flags.json)
441
+ return print({ file: tunePath(file), overrides: tune.set ?? {}, notes: list });
442
+ const open_ = list.filter((n) => n.status === 'open');
443
+ console.log(`${open_.length} open note(s), ${Object.keys(tune.set ?? {}).length} override(s) in ${tunePath(file)}`);
444
+ for (const n of open_)
445
+ console.log(` ${n.t.toFixed(2)} s ${n.at ? `${n.at.scene}${n.layer ? ` › ${n.layer}` : ''}` : '?'} ${n.text}`);
446
+ for (const [p, v] of Object.entries(tune.set ?? {}))
447
+ console.log(` set ${p} = ${JSON.stringify(v)}`);
448
+ }
449
+ async function preview(args) {
450
+ const file = need(args);
451
+ const p = await serve({ film: file, css: args.css, watch: true, ...(args.flags.port ? { port: Number(args.flags.port) } : {}) });
452
+ console.log(`Studio for ${file}: ${p.url}\nDials and notes are saved to ${tunePath(file)}. The page follows edits to the film file. Ctrl+C stops it.`);
453
+ }
454
+ async function stills(args) {
455
+ const file = need(args), l = load(file, args), t = timelineOrExit(l, false);
456
+ const at = typeof args.flags.at === 'string' ? args.flags.at.split(',').map(Number).map((x) => ({ t: x, label: '' })) : keyMoments(t);
457
+ if (at.some((m) => !Number.isFinite(m.t) || m.t < 0 || m.t > t.duration))
458
+ throw new Error(`--at takes times in seconds between 0 and ${t.duration.toFixed(2)}, separated by commas.`);
459
+ const dir = path.join(path.dirname(path.resolve(file)), 'out', filmName(file), 'stills');
460
+ fs.rmSync(dir, { recursive: true, force: true });
461
+ fs.mkdirSync(dir, { recursive: true });
462
+ const s = await open(file, { css: args.css, size: t.size, scale: Number(args.flags.scale ?? 1), timeline: t, ...browserOpt(args), ...(args.flags['no-tune'] ? { noTune: true } : {}) });
463
+ try {
464
+ const shots = [];
465
+ for (const m of at) {
466
+ await s.seek(m.t);
467
+ const png = await s.page.screenshot({ type: 'png' });
468
+ const name = path.join(dir, `t${m.t.toFixed(2).padStart(6, '0')}.png`);
469
+ fs.writeFileSync(name, png);
470
+ // The sheet uses small JPEGs so it stays a reasonable size.
471
+ shots.push({ t: m.t, label: m.label, file: name, data: (await s.page.screenshot({ type: 'jpeg', quality: 80 })).toString('base64') });
472
+ }
473
+ const cols = Math.min(4, shots.length), cell = Math.round(1600 / cols), sheet = path.join(dir, '..', 'sheet.png');
474
+ const page = await s.page.context().newPage();
475
+ await page.setViewportSize({ width: cols * cell + 24, height: 200 });
476
+ await page.setContent(`<body style="margin:12px;background:#15171b;font:12px ui-monospace,Menlo,monospace;color:#cfd3da"><div style="display:grid;grid-template-columns:repeat(${cols},1fr);gap:12px">${shots.map((x) => `<figure style="margin:0"><img src="data:image/jpeg;base64,${x.data}" style="display:block;width:100%"><figcaption style="padding-top:4px">${x.t.toFixed(2)} s${x.label ? ` · ${x.label.replace(/[<&]/g, '')}` : ''}</figcaption></figure>`).join('')}</div></body>`);
477
+ await page.screenshot({ path: sheet, fullPage: true });
478
+ await page.close();
479
+ if (args.flags.json)
480
+ print({ sheet, stills: shots.map(({ t: time, label, file: f }) => ({ t: time, label, file: f })), errors: s.errors });
481
+ else
482
+ console.log(`${shots.length} stills in ${path.relative(process.cwd(), dir)}/\nContact sheet: ${path.relative(process.cwd(), sheet)}${s.errors.length ? `\nPage errors:\n ${s.errors.join('\n ')}` : ''}`);
483
+ }
484
+ finally {
485
+ await s.close();
486
+ }
487
+ }
488
+ /** Two draws of one frame count as the same when no pixel is more than this many levels (of 255) apart … */
489
+ const REPEAT_LEVELS = 2;
490
+ /** … and no more than this share of the pixels differ at all. */
491
+ const REPEAT_SHARE = 0.001;
492
+ /** Above this difference in the mean of any 16 px block (levels of 255), whole areas differ: that is state, not rasterising. */
493
+ const REPEAT_AREA = 24;
494
+ async function check(args) {
495
+ const file = need(args), json = !!args.flags.json, l = load(file, args), t = timelineOrExit(l, json);
496
+ const issues = [...l.res.issues];
497
+ let loop;
498
+ const s = await open(file, { css: args.css, size: t.size, timeline: t, ...browserOpt(args), ...(args.flags['no-tune'] ? { noTune: true } : {}) });
499
+ try {
500
+ // 1. A frame must depend on its time alone: draw the same moments in two orders and compare.
501
+ const times = Array.from({ length: 6 }, (_, k) => Math.round((t.duration * k / 5) * t.fps) / t.fps);
502
+ // Two things are compared. The page's state: every element's box, opacity, visibility, filter and
503
+ // transform, which must match exactly. And the pixels, with room: a browser does not always rasterise
504
+ // the same state the same way (a card that has just become its own layer can land a pixel aside, a blur
505
+ // a level off), which no one can see and no primitive caused. So pixels only fail the film when whole
506
+ // areas differ, as they do when a canvas or a picture holds state the page's boxes do not show.
507
+ const state = () => s.page.evaluate(() => [...document.querySelectorAll('.m-scene, .m-cam, .m-layer, .m-layer *')].map((e) => {
508
+ // What is not shown may keep whatever it was last drawn with: only its being hidden is state.
509
+ if (!e.checkVisibility({ visibilityProperty: true }))
510
+ return 'hidden';
511
+ const r = e.getBoundingClientRect(), c = getComputedStyle(e);
512
+ return [r.x.toFixed(2), r.y.toFixed(2), r.width.toFixed(2), r.height.toFixed(2), c.opacity, c.visibility, c.display, c.filter, c.clipPath, e.style.transform, e.getAttribute('stroke-dashoffset') ?? ''].join('|');
513
+ }).join('\n'));
514
+ const shot = async (time) => { await s.seek(time); return { state: await state(), png: (await s.page.screenshot({ type: 'png' })).toString('base64') }; };
515
+ const probe = await s.page.context().newPage();
516
+ const differ = (a, b) => a === b ? Promise.resolve({ share: 0, max: 0, area: 0 }) : probe.evaluate(async ([x, y]) => {
517
+ const read = async (data) => {
518
+ const bmp = await createImageBitmap(await (await fetch(`data:image/png;base64,${data}`)).blob());
519
+ const c = new OffscreenCanvas(bmp.width, bmp.height).getContext('2d');
520
+ c.drawImage(bmp, 0, 0);
521
+ return { data: c.getImageData(0, 0, bmp.width, bmp.height).data, w: bmp.width, h: bmp.height };
522
+ };
523
+ const [p, q] = [await read(x), await read(y)];
524
+ if (p.data.length !== q.data.length)
525
+ return { share: 1, max: 255, area: 255 };
526
+ // `area` is the largest difference between the two frames' means over 16 px blocks.
527
+ const B = 16, bw = Math.ceil(p.w / B), sums = new Float64Array(bw * Math.ceil(p.h / B)), counts = new Uint32Array(sums.length);
528
+ let count = 0, max = 0;
529
+ for (let i = 0, n = 0; i < p.data.length; i += 4, n++) {
530
+ const d = Math.max(Math.abs(p.data[i] - q.data[i]), Math.abs(p.data[i + 1] - q.data[i + 1]), Math.abs(p.data[i + 2] - q.data[i + 2]));
531
+ if (d > 0) {
532
+ count++;
533
+ if (d > max)
534
+ max = d;
535
+ }
536
+ const k = Math.floor(Math.floor(n / p.w) / B) * bw + Math.floor((n % p.w) / B);
537
+ sums[k] += (p.data[i] + p.data[i + 1] + p.data[i + 2]) - (q.data[i] + q.data[i + 1] + q.data[i + 2]);
538
+ counts[k]++;
539
+ }
540
+ let area = 0;
541
+ for (let k = 0; k < sums.length; k++)
542
+ if (counts[k])
543
+ area = Math.max(area, Math.abs(sums[k]) / (3 * counts[k]));
544
+ return { share: count / (p.data.length / 4), max, area };
545
+ }, [a, b]);
546
+ const forward = new Map();
547
+ for (const time of times)
548
+ forward.set(time, await shot(time));
549
+ for (const time of [...times].reverse()) {
550
+ const now = await shot(time), was = forward.get(time);
551
+ const d = await differ(now.png, was.png);
552
+ const how = `${(d.share * 100).toFixed(2)}% of its pixels, by up to ${d.max} of 255 levels`;
553
+ if (now.state !== was.state || d.area > REPEAT_AREA)
554
+ issues.push({ level: 'error', code: 'not-repeatable', path: 'film', t: time, message: `The frame at ${time.toFixed(2)} s differs depending on what was drawn before it${now.state !== was.state ? ': elements sit or look different' : ''} (${how}).`, hint: 'A primitive keeps state between seeks, or uses a clock or unseeded randomness.' });
555
+ else if (d.max > REPEAT_LEVELS || d.share > REPEAT_SHARE)
556
+ issues.push({ level: 'warning', code: 'raster-differs', path: 'film', t: time, message: `The frame at ${time.toFixed(2)} s is rasterised a little differently depending on what was drawn before it (${how}); every element sits and looks the same.`, hint: 'This is the browser, not the film: usually a layer that has just started to fade or scale landing a pixel aside. Look at the two frames if it matters.' });
557
+ }
558
+ await probe.close();
559
+ // 2. Layers must be on the stage and have a size once they have settled. In a
560
+ // scene whose camera moves, a layer is expected to be off stage for part of the
561
+ // time (a canvas the camera travels over), so it is reported only if the camera
562
+ // never brings any of it into view.
563
+ const seen = new Set();
564
+ const roving = new Set(t.scenes.filter(movesCamera).map((sc) => sc.id));
565
+ const inView = new Map();
566
+ const [W, H] = t.size;
567
+ for (const m of auditMoments(t, roving)) {
568
+ for (const b of await s.audit(m.t)) {
569
+ const p = `scenes.${b.scene}.layers.${b.layer}`;
570
+ const sides = Object.entries(b.off).filter(([, px]) => px > 1);
571
+ if (b.empty && !seen.has(`${p}:empty`)) {
572
+ seen.add(`${p}:empty`);
573
+ issues.push({ level: 'warning', code: 'empty-layer', path: p, t: m.t, message: `Layer "${b.layer}" has no size at ${m.t.toFixed(2)} s, so it shows nothing.` });
574
+ }
575
+ else if (roving.has(b.scene)) {
576
+ const visible = b.x < W && b.x + b.width > 0 && b.y < H && b.y + b.height > 0;
577
+ if (visible)
578
+ inView.set(p, null);
579
+ else if (!inView.has(p))
580
+ inView.set(p, { b, t: m.t });
581
+ }
582
+ else if (sides.length && !seen.has(`${p}:off`)) {
583
+ seen.add(`${p}:off`);
584
+ issues.push({ level: 'warning', code: 'off-stage', path: p, t: m.t, message: `Layer "${b.layer}" runs off the stage at ${m.t.toFixed(2)} s: ${sides.map(([side, px]) => `${px} px past the ${side}`).join(', ')}.`, hint: 'Shorten the text, pick a smaller style.size, or set style.width (in % of the stage). A placed layer is as wide as its text, up to style.width.' });
585
+ }
586
+ }
587
+ }
588
+ for (const [p, first] of inView) {
589
+ if (!first)
590
+ continue;
591
+ issues.push({ level: 'warning', code: 'never-in-view', path: p, t: first.t, message: `Layer "${first.b.layer}" is never on stage: the camera does not bring it into view while it is shown.`, hint: 'Move it where the camera passes, move the camera to it, or remove it.' });
592
+ }
593
+ // 3. Layout must not flip: a layer whose own size (before transforms) changes and changes back
594
+ // re-wraps a line or re-centres a block, and the eye sees the words jump. Sizes are sampled
595
+ // through the film; a change that returns within a second is reported.
596
+ const sizes = () => s.page.evaluate(() => Object.fromEntries([...document.querySelectorAll('.m-scene')].flatMap((sc) => [...sc.querySelectorAll('.m-layer')].filter((e) => e.checkVisibility()).map((e) => [`scenes.${sc.dataset.scene}.layers.${e.dataset.layer}`, `${e.offsetWidth}×${e.offsetHeight}`]))));
597
+ const history = new Map();
598
+ const every = Math.max(1 / 12, t.duration / 240);
599
+ for (let time = 0; time < t.duration; time += every) {
600
+ await s.seek(Math.round(time * t.fps) / t.fps);
601
+ for (const [p, size] of Object.entries(await sizes())) {
602
+ const h = history.get(p) ?? [];
603
+ if (h[h.length - 1]?.size !== size)
604
+ h.push({ t: time, size });
605
+ history.set(p, h);
606
+ }
607
+ }
608
+ for (const [p, h] of history) {
609
+ const flip = h.findIndex((x, k) => k >= 2 && h[k - 2].size === x.size && x.t - h[k - 1].t <= 1);
610
+ if (flip < 0)
611
+ continue;
612
+ const [a, b] = [h[flip - 2], h[flip - 1]];
613
+ issues.push({ level: 'warning', code: 'relayout-flip', path: p, t: b.t, message: `Layer "${p.split('.').pop()}" changes its laid-out size from ${a.size} to ${b.size} at ${b.t.toFixed(2)} s and back by ${h[flip].t.toFixed(2)} s: a line re-wraps, and the words jump.`,
614
+ hint: 'Lay text out whole from the first frame and reveal it with opacity or a mask; move things with transforms, never by changing size, zoom or font size.' });
615
+ }
616
+ // 4. A light motion pass: runs of consecutive frames inside each camera move, through the same
617
+ // measures as `motion review`, so a wiggle or a jump shows before a render.
618
+ const moving = t.scenes.filter(movesCamera);
619
+ if (moving.length) {
620
+ const decoder = await s.page.context().newPage();
621
+ const [vw, vh] = t.size, k = 360 / Math.min(vw, vh), aw = Math.round((vw * k) / 2) * 2, ah = Math.round((vh * k) / 2) * 2;
622
+ const gray = async (png) => {
623
+ const b64 = await decoder.evaluate(async ([data, w, h]) => {
624
+ const bmp = await createImageBitmap(await (await fetch(`data:image/png;base64,${data}`)).blob(), { resizeWidth: w, resizeHeight: h, resizeQuality: 'medium' });
625
+ const c = new OffscreenCanvas(w, h).getContext('2d');
626
+ c.drawImage(bmp, 0, 0);
627
+ const d = c.getImageData(0, 0, w, h).data, g = new Uint8Array(w * h);
628
+ for (let i = 0; i < g.length; i++)
629
+ g[i] = Math.round(0.299 * d[i * 4] + 0.587 * d[i * 4 + 1] + 0.114 * d[i * 4 + 2]);
630
+ let out = '';
631
+ for (let i = 0; i < g.length; i += 0x8000)
632
+ out += String.fromCharCode(...g.subarray(i, i + 0x8000));
633
+ return btoa(out);
634
+ }, [png.toString('base64'), aw, ah]);
635
+ return Float32Array.from(Buffer.from(b64, 'base64'));
636
+ };
637
+ const reported = new Set();
638
+ try {
639
+ for (const sc of moving)
640
+ for (const at of [1 / 3, 2 / 3]) {
641
+ const first = Math.round((sc.start + sc.length * at) * t.fps) - 6;
642
+ if (first < 0 || first + 12 > t.frames)
643
+ continue;
644
+ const an = new Analyser(aw, ah, REFERENCE_SHORT / Math.min(aw, ah));
645
+ for (let i = first; i < first + 12; i++) {
646
+ await s.seek(i / t.fps);
647
+ an.push(await gray(await s.page.screenshot({ type: 'png' })));
648
+ }
649
+ for (const f of findings(an.result(), { fps: t.fps })) {
650
+ if (f.level !== 'fault' || reported.has(`${sc.id}:${f.kind}`))
651
+ continue;
652
+ reported.add(`${sc.id}:${f.kind}`);
653
+ const time = (first + f.frame) / t.fps;
654
+ issues.push({ level: 'warning', code: `motion-${f.kind}`, path: `scenes.${sc.id}`, t: Number(time.toFixed(2)), message: `At ${time.toFixed(2)} s: ${f.message}`,
655
+ hint: 'This samples a few frames of each camera move; render and run motion review for the whole film.' });
656
+ }
657
+ }
658
+ }
659
+ finally {
660
+ await decoder.close();
661
+ }
662
+ }
663
+ // 5. A loop's last frame must lead into its first as a normal frame leads into the next.
664
+ if (args.flags.loop || readFilm(file).loop === true)
665
+ loop = await seam(s, t);
666
+ for (const e of s.errors)
667
+ issues.push({ level: 'error', code: 'page-error', path: 'film', message: e });
668
+ }
669
+ finally {
670
+ await s.close();
671
+ }
672
+ const errors = issues.filter((i) => i.level === 'error').length;
673
+ if (loop && !loop.seamless) {
674
+ const still = loop.step < 0.05;
675
+ issues.push({ level: 'warning', code: 'loop-seam', path: 'film', t: t.duration, message: `The loop jumps: last frame to first changes ${loop.seam} (mean per channel, 0–255), ${still ? 'while the frames at both ends hold still' : `${loop.ratio}× the largest frame-to-frame step around it (${loop.step})`}.`,
676
+ hint: 'End each move where the film began, or end footage on the frame before the opening shot (el/video "continues").' });
677
+ }
678
+ if (json)
679
+ print({ ok: errors === 0, file, duration: t.duration, frames: t.frames, issues, ...(loop ? { loop } : {}) });
680
+ else {
681
+ issues.forEach((i) => console.log(line(i)));
682
+ if (loop)
683
+ console.log(`Loop seam: last frame to first changes ${loop.seam}; the largest step nearby changes ${loop.step} (of ${loop.steps.length} steps at both ends)${loop.step >= 0.05 ? `, so the seam is ${loop.ratio}× a step` : ''}: ${loop.seamless ? 'seamless' : 'it shows'}.`);
684
+ console.log(`${file}: ${errors ? `${errors} error(s)` : 'ok'}, ${issues.length - errors} warning(s). Frames repeat exactly: ${issues.some((i) => i.code === 'not-repeatable') ? 'NO' : 'yes'}.`);
685
+ }
686
+ if (errors)
687
+ process.exit(1);
688
+ }
689
+ /** A scene whose camera moves: tracks that move or turn the whole scene, or a camera that follows a line. */
690
+ function movesCamera(sc) {
691
+ const tr = sc.source.tracks ?? {};
692
+ return !!sc.source.follow || (sc.camera?.length ?? 0) > 1 || !!sc.camera?.some((k) => k.drift) || ['x', 'y', 'scale', 'rotate', 'rotateX', 'rotateY'].some((k) => (tr[k]?.length ?? 0) > 1);
693
+ }
694
+ /** Key moments, plus every quarter second of scenes whose camera moves. */
695
+ function auditMoments(t, roving) {
696
+ const out = keyMoments(t), have = new Set(out.map((m) => Math.round(m.t * t.fps)));
697
+ for (const sc of t.scenes) {
698
+ if (!roving.has(sc.id))
699
+ continue;
700
+ for (let x = sc.start; x < sc.end; x += 0.25) {
701
+ const f = Math.min(t.frames - 1, Math.round(x * t.fps));
702
+ if (!have.has(f)) {
703
+ have.add(f);
704
+ out.push({ t: f / t.fps, label: `${sc.id} camera` });
705
+ }
706
+ }
707
+ }
708
+ return out.sort((a, b) => a.t - b.t);
709
+ }
710
+ /**
711
+ * How much the picture changes from the last frame to the first, next to how much
712
+ * it changes from one frame to the next at both ends of the film. A raw score
713
+ * misleads: handheld footage changes a lot every frame, a still title not at all.
714
+ * The seam is held against the largest step nearby, not the usual one: footage shot at
715
+ * 24 fps in a 60 fps film changes on two frames in five and holds on the rest, so its
716
+ * usual step is nearly nothing while a sound seam is one of its real steps.
717
+ */
718
+ async function seam(s, t) {
719
+ const n = Math.min(Math.max(6, Math.ceil(t.fps / 5) + 1), Math.floor(t.frames / 2));
720
+ const shot = async (f) => { await s.seek(f / t.fps); return (await s.page.screenshot({ type: 'png' })).toString('base64'); };
721
+ const head = [], tail = [];
722
+ for (let f = 0; f < n; f++)
723
+ head.push(await shot(f));
724
+ for (let f = t.frames - n; f < t.frames; f++)
725
+ tail.push(await shot(f));
726
+ const pairs = [...tail.slice(0, -1).map((a, i) => [a, tail[i + 1]]), ...head.slice(0, -1).map((a, i) => [a, head[i + 1]]), [tail[tail.length - 1], head[0]]];
727
+ const page = await s.page.context().newPage();
728
+ try {
729
+ // One pair at a time: every frame is a PNG of several megabytes, and all of them in one call is more than a page takes.
730
+ const diffs = [];
731
+ for (const pair of pairs) {
732
+ diffs.push(await page.evaluate(async ([a, b]) => {
733
+ const pixels = async (b64) => {
734
+ const bmp = await createImageBitmap(await (await fetch(`data:image/png;base64,${b64}`)).blob());
735
+ const w = 480, h = Math.max(1, Math.round((bmp.height / bmp.width) * w));
736
+ const c = new OffscreenCanvas(w, h), g = c.getContext('2d');
737
+ g.drawImage(bmp, 0, 0, w, h);
738
+ return g.getImageData(0, 0, w, h).data;
739
+ };
740
+ const [pa, pb] = await Promise.all([pixels(a), pixels(b)]);
741
+ let sum = 0;
742
+ for (let i = 0; i < pa.length; i += 4)
743
+ sum += Math.abs(pa[i] - pb[i]) + Math.abs(pa[i + 1] - pb[i + 1]) + Math.abs(pa[i + 2] - pb[i + 2]);
744
+ return sum / ((pa.length / 4) * 3);
745
+ }, pair));
746
+ }
747
+ const r2 = (x) => Number(x.toFixed(2));
748
+ const steps = diffs.slice(0, -1), sorted = [...steps].sort((a, b) => a - b);
749
+ const step = sorted.length ? sorted[sorted.length - 1] : 0, value = diffs[diffs.length - 1];
750
+ // Seamless when the seam is no bigger than one and a half of the largest steps around it, or too small to see.
751
+ return { seam: r2(value), step: r2(step), ratio: r2(value / Math.max(step, 0.05)), seamless: value <= Math.max(1.5 * step, 0.5), steps: steps.map(r2) };
752
+ }
753
+ finally {
754
+ await page.close();
755
+ }
756
+ }
757
+ async function reviewCmd(args) {
758
+ const target = need(args), json = !!args.flags.json;
759
+ let file = target, cuts, spans, loop = !!args.flags.loop, out;
760
+ if (/\.json$/i.test(target)) {
761
+ // A film: review its render, judging cuts and hand-overs as the film declares them.
762
+ const t = timelineOrExit(load(target, args), json);
763
+ const dir = path.join(path.dirname(path.resolve(target)), 'out', filmName(target));
764
+ file = typeof args.flags.video === 'string' ? path.resolve(args.flags.video) : path.join(dir, `${filmName(target)}-${t.size[0] - (t.size[0] % 2)}x${t.size[1] - (t.size[1] % 2)}-${t.fps}fps.mp4`);
765
+ if (!fs.existsSync(file))
766
+ throw new Error(`No render at ${path.relative(process.cwd(), file)}. Run: motion render ${target}`);
767
+ if (fs.statSync(file).mtimeMs < fs.statSync(target).mtimeMs)
768
+ console.error(`warn: the render is older than ${path.basename(target)}; render again to review the film as it is now.`);
769
+ ({ cuts, spans } = filmCuts(t));
770
+ loop ||= t.loop === true;
771
+ out = path.join(dir, 'review');
772
+ }
773
+ else {
774
+ if (!fs.existsSync(target))
775
+ throw new Error(`${target} not found.`);
776
+ out = path.join(path.dirname(path.resolve(target)), `${path.basename(target).replace(/\.[^.]+$/, '')}.review`);
777
+ }
778
+ const res = await review({ file, out, loop, ...(cuts ? { cuts } : {}), ...(spans ? { spans } : {}),
779
+ ...(json ? {} : { onProgress: (d, n) => { if (d === n || d % 60 === 0)
780
+ process.stderr.write(`\r frame ${d}/${n}`); if (d === n)
781
+ process.stderr.write('\n'); } }) });
782
+ if (json)
783
+ print(res);
784
+ else
785
+ console.log(describeReview(res));
786
+ if (!res.ok)
787
+ process.exit(1);
788
+ }
789
+ async function render(args) {
790
+ const file = need(args), l = load(file, args), t = timelineOrExit(l, false);
791
+ const scale = Number(args.flags.scale ?? 1), crf = String(args.flags.crf ?? 15);
792
+ const dir = path.join(path.dirname(path.resolve(file)), 'out', filmName(file));
793
+ const out = path.resolve(typeof args.flags.out === 'string' ? args.flags.out : path.join(dir, `${filmName(file)}-${t.size[0]}x${t.size[1]}-${t.fps}fps.mp4`));
794
+ fs.mkdirSync(path.dirname(out), { recursive: true });
795
+ const [w, h] = [t.size[0] - (t.size[0] % 2), t.size[1] - (t.size[1] % 2)]; // H.264 4:2:0 needs even sides
796
+ const s = await open(file, { css: args.css, size: t.size, scale, timeline: t, ...browserOpt(args), ...(args.flags['no-tune'] ? { noTune: true } : {}) });
797
+ // The soundtrack, cut to the film: from its `from`, as long as the film, faded and levelled.
798
+ const a = t.audio, sound = a ? path.resolve(path.dirname(path.resolve(file)), a.src) : undefined;
799
+ if (sound && !fs.existsSync(sound)) {
800
+ console.error(`audio.src: ${a.src} not found next to the film.`);
801
+ process.exit(1);
802
+ }
803
+ const audioIn = a && sound ? ['-ss', String(a.from), '-t', String(t.duration), '-i', sound] : [];
804
+ const audioOut = a && sound ? [
805
+ '-map', '0:v', '-map', '1:a', '-c:a', 'aac', '-b:a', '256k',
806
+ // A few milliseconds of fade even when none is asked for, so the cut ends never click.
807
+ '-af', [`volume=${a.gain}dB`, `afade=t=in:st=0:d=${Math.max(0.005, a.fade_in)}`, `afade=t=out:st=${Math.max(0, t.duration - Math.max(0.005, a.fade_out)).toFixed(4)}:d=${Math.max(0.005, a.fade_out)}`, `apad=whole_dur=${t.duration}`].join(','),
808
+ ] : ['-an'];
809
+ // Frames go to ffmpeg as PNG: JPEG's noise is different in every frame and crawls on fine type and
810
+ // flat fills (the review's shimmer). --fast keeps JPEG for drafts, at about twice the speed.
811
+ const fast = !!args.flags.fast;
812
+ const ff = spawn('ffmpeg', ['-v', 'error', '-y', '-f', 'image2pipe', '-framerate', String(t.fps), '-vcodec', fast ? 'mjpeg' : 'png', '-i', 'pipe:0', ...audioIn,
813
+ '-vf', `scale=${w}:${h}:flags=lanczos+accurate_rnd+full_chroma_int:in_color_matrix=bt601:in_range=pc:out_color_matrix=bt709:out_range=tv,format=yuv420p`,
814
+ '-c:v', 'libx264', '-preset', 'slow', '-crf', crf, '-colorspace', 'bt709', '-color_primaries', 'bt709', '-color_trc', 'bt709', '-movflags', '+faststart', ...audioOut, '-t', String(t.duration), out]);
815
+ let ffErr = '';
816
+ ff.stderr.on('data', (d) => { ffErr += d.toString(); });
817
+ const closed = once(ff, 'close');
818
+ const started = Date.now();
819
+ const still = [];
820
+ let runStart = -1, prev = '';
821
+ try {
822
+ for (let i = 0; i < t.frames; i++) {
823
+ await s.seek(i / t.fps);
824
+ const img = fast ? await s.page.screenshot({ type: 'jpeg', quality: 95 }) : await s.page.screenshot({ type: 'png' });
825
+ const hash = createHash('sha1').update(img).digest('hex');
826
+ if (hash === prev) {
827
+ if (runStart < 0)
828
+ runStart = i - 1;
829
+ }
830
+ else if (runStart >= 0) {
831
+ still.push([runStart, i - 1]);
832
+ runStart = -1;
833
+ }
834
+ prev = hash;
835
+ if (!ff.stdin.write(img))
836
+ await once(ff.stdin, 'drain');
837
+ if (i % t.fps === 0)
838
+ process.stderr.write(`\r${i}/${t.frames} frames`);
839
+ }
840
+ if (runStart >= 0)
841
+ still.push([runStart, t.frames - 1]);
842
+ ff.stdin.end();
843
+ const [code] = await closed;
844
+ process.stderr.write('\r');
845
+ if (code !== 0)
846
+ throw new Error(`ffmpeg failed: ${ffErr.trim()}`);
847
+ }
848
+ finally {
849
+ await s.close();
850
+ if (ff.exitCode === null)
851
+ ff.kill();
852
+ }
853
+ // Runs of identical frames a second or longer: holds are expected, an unplanned freeze is not.
854
+ const still_runs_s = still.filter(([a, b]) => b - a + 1 >= t.fps).map(([a, b]) => [Number((a / t.fps).toFixed(2)), Number(((b + 1) / t.fps).toFixed(2))]);
855
+ const report = {
856
+ file: out, size: `${w}x${h}`, fps: t.fps, frames: t.frames, duration_s: t.duration, megabytes: Number((fs.statSync(out).size / 1e6).toFixed(2)),
857
+ supersample: scale, frames_as: fast ? 'jpeg' : 'png', render_s: Number(((Date.now() - started) / 1000).toFixed(1)), still_runs_s, page_errors: s.errors,
858
+ };
859
+ writeJson(out.replace(/\.mp4$/, '.report.json'), report);
860
+ print(report);
861
+ if (s.errors.length)
862
+ process.exit(1);
863
+ }
864
+ async function build(args) {
865
+ const file = need(args), l = load(file, args);
866
+ timelineOrExit(l, false);
867
+ const js = fs.readFileSync(await bundle(), 'utf8');
868
+ const data = JSON.stringify({ film: readFilm(file), tune: args.flags['no-tune'] ? {} : readTune(file) }).replace(/</g, '\\u003c');
869
+ const head = args.css.map((f) => `<style>${inlineCss(path.resolve(f))}</style>`).join('\n');
870
+ const out = path.resolve(typeof args.flags.out === 'string' ? args.flags.out : path.join(path.dirname(path.resolve(file)), 'out', filmName(file), `${filmName(file)}.html`));
871
+ fs.mkdirSync(path.dirname(out), { recursive: true });
872
+ fs.writeFileSync(out, shell(head, `<script type="application/json" id="film-data">${data}</script>\n<script type="module">${js.replace(/<\/script/g, '<\\/script')}</script>`));
873
+ console.log(`${path.relative(process.cwd(), out)} written. Open it to play the film; add #render for the bare stage.`);
874
+ }
875
+ async function wizard(args) {
876
+ const html = await wizardPage({ catalog: buildCatalog(), library: readLibrary() });
877
+ if (typeof args.flags.out === 'string') {
878
+ fs.mkdirSync(path.dirname(path.resolve(args.flags.out)), { recursive: true });
879
+ fs.writeFileSync(args.flags.out, html);
880
+ return console.log(`${args.flags.out} written. It is one file: open it, or share it.`);
881
+ }
882
+ const http = await import('node:http');
883
+ const port = Number(args.flags.port ?? 4322);
884
+ const server = http.createServer((_req, res) => { res.writeHead(200, { 'content-type': 'text/html; charset=utf-8', 'cache-control': 'no-store' }); res.end(html); });
885
+ await new Promise((resolve) => server.listen(port, '127.0.0.1', resolve));
886
+ console.log(`Wizard: http://127.0.0.1:${port}\nAnswer the questions, then copy the brief into Claude or ChatGPT. Ctrl+C stops it.`);
887
+ }
888
+ function briefCmd(args) {
889
+ const file = need(args);
890
+ const answers = readJson(file);
891
+ const ctx = { catalog: buildCatalog(), library: readLibrary() };
892
+ const problems = checkAnswers(answers, ctx);
893
+ if (problems.length) {
894
+ problems.forEach((p) => console.error(`ERROR ${p}`));
895
+ process.exit(1);
896
+ }
897
+ const text = writeBrief(answers, ctx);
898
+ if (typeof args.flags.out === 'string') {
899
+ fs.writeFileSync(args.flags.out, text);
900
+ console.log(`${args.flags.out} written`);
901
+ }
902
+ else
903
+ process.stdout.write(text);
904
+ }
905
+ function bakeCmd(args) {
906
+ const file = need(args), result = bake(readFilm(file), readTune(file));
907
+ const res = resolveFilm(result.film);
908
+ if (!res.ok) {
909
+ res.issues.forEach((i) => console.error(line(i)));
910
+ throw new Error('The tuned film has errors, so nothing was written.');
911
+ }
912
+ writeJson(file, result.film);
913
+ writeJson(tunePath(file), result.tune);
914
+ console.log(`Tuning written into ${file}.${result.orphans.length ? ` ${result.orphans.length} override(s) pointed at nothing and were left in the tune file.` : ''} Notes were kept.`);
915
+ }
916
+ export async function main(argv) {
917
+ const args = parse(argv);
918
+ const cmd = args._[0];
919
+ if (!cmd || args.flags.help)
920
+ return console.log(HELP);
921
+ if (cmd === 'catalog')
922
+ return catalog(args);
923
+ if (cmd === 'make')
924
+ return make(args);
925
+ if (cmd === 'capture')
926
+ return captureCmd(args);
927
+ if (cmd === 'record')
928
+ return recordCmd(args);
929
+ if (cmd === 'validate')
930
+ return validate(args);
931
+ if (cmd === 'inspect')
932
+ return inspect(args);
933
+ if (cmd === 'pace')
934
+ return paceCmd(args);
935
+ if (cmd === 'beats')
936
+ return beatsCmd(args);
937
+ if (cmd === 'import')
938
+ return importCmd(args);
939
+ if (cmd === 'notes')
940
+ return notes(args);
941
+ if (cmd === 'preview')
942
+ return preview(args);
943
+ if (cmd === 'stills')
944
+ return stills(args);
945
+ if (cmd === 'check')
946
+ return check(args);
947
+ if (cmd === 'review')
948
+ return reviewCmd(args);
949
+ if (cmd === 'render')
950
+ return render(args);
951
+ if (cmd === 'build')
952
+ return build(args);
953
+ if (cmd === 'bake')
954
+ return bakeCmd(args);
955
+ if (cmd === 'brief')
956
+ return briefCmd(args);
957
+ if (cmd === 'wizard')
958
+ return wizard(args);
959
+ if (cmd === 'bundle') {
960
+ await bundle(path.resolve('dist'));
961
+ return console.log('dist/page.js and dist/motion.js written');
962
+ }
963
+ throw new Error(`Unknown command "${cmd}".\n\n${HELP}`);
964
+ }