swf2js 0.1.2 → 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 (416) hide show
  1. package/README.md +81 -14
  2. package/package.json +11 -7
  3. package/studio/actionscript-roundtrip.test.js +54 -0
  4. package/studio/actionscript-scripts.test.js +169 -0
  5. package/studio/animated-image.test.js +137 -0
  6. package/studio/arithmetic.test.js +16 -0
  7. package/studio/as3-import.test.js +110 -0
  8. package/studio/audio-info.test.js +44 -0
  9. package/studio/components.test.js +152 -0
  10. package/studio/document-editing.test.js +92 -0
  11. package/studio/examples/01-space-mission.json +1628 -0
  12. package/studio/examples/02-clockwork-vault.json +1079 -0
  13. package/studio/examples/03-neon-synth.json +1364 -0
  14. package/studio/examples/04-kinetic-poster.json +923 -0
  15. package/studio/examples/05-signal-relay.json +1131 -0
  16. package/studio/examples/06-calculator.json +564 -0
  17. package/studio/frame-editing.test.js +129 -0
  18. package/studio/frame-events.test.js +117 -0
  19. package/studio/groups.test.js +88 -0
  20. package/studio/index.html +962 -0
  21. package/studio/interaction-triggers.test.js +37 -0
  22. package/studio/linked-actions.test.js +48 -0
  23. package/studio/lottie.test.js +208 -0
  24. package/studio/masks.test.js +43 -0
  25. package/studio/media-assets.test.js +62 -0
  26. package/studio/paint-tools.test.js +60 -0
  27. package/studio/playback.test.js +17 -0
  28. package/studio/project-io.test.js +405 -0
  29. package/studio/project-preview.test.js +475 -0
  30. package/studio/scene-transition.test.js +32 -0
  31. package/studio/server/archive-companions.js +27 -0
  32. package/studio/server/as3-library.js +91 -0
  33. package/studio/server/assets.js +162 -0
  34. package/studio/server/audio-info.js +82 -0
  35. package/studio/server/font-files.js +332 -0
  36. package/studio/server/http.js +135 -0
  37. package/studio/server/linked-actions.js +93 -0
  38. package/studio/server/png-decode.js +1 -0
  39. package/studio/server/project-movie.js +1164 -0
  40. package/studio/server/project-preview.js +152 -0
  41. package/studio/server/projects.js +370 -0
  42. package/studio/server/report.js +29 -0
  43. package/studio/server/routes.js +93 -0
  44. package/studio/server/swf-authoring.js +90 -0
  45. package/studio/server/swf-control-runtime.as +513 -0
  46. package/studio/server/swf-controls.js +119 -0
  47. package/studio/server/swf-export.js +293 -0
  48. package/studio/server/swf-import.js +1675 -0
  49. package/studio/server/swf-morphs.js +64 -0
  50. package/studio/server/swf-routes.js +42 -0
  51. package/studio/server/swf-streams.js +80 -0
  52. package/studio/server/swf-transition-runtime.as +52 -0
  53. package/studio/server/tween-recovery.js +106 -0
  54. package/studio/server-api.test.js +283 -0
  55. package/studio/server.js +320 -0
  56. package/studio/src/animated-image.js +423 -0
  57. package/studio/src/appearance-inspector.js +63 -0
  58. package/studio/src/arithmetic.js +50 -0
  59. package/studio/src/authored-controls.js +42 -0
  60. package/studio/src/busy.js +41 -0
  61. package/studio/src/canvas.js +430 -0
  62. package/studio/src/clipper-browser.js +2 -0
  63. package/studio/src/color-transform.js +38 -0
  64. package/studio/src/component-inspector.js +126 -0
  65. package/studio/src/components.js +268 -0
  66. package/studio/src/display-frame.js +262 -0
  67. package/studio/src/document-editing.js +69 -0
  68. package/studio/src/event-editor.js +150 -0
  69. package/studio/src/frame-editing.js +150 -0
  70. package/studio/src/frame-events.js +128 -0
  71. package/studio/src/frame-image.js +28 -0
  72. package/studio/src/groups.js +125 -0
  73. package/studio/src/handler-editor.js +122 -0
  74. package/studio/src/history.js +83 -0
  75. package/studio/src/imported-paths.js +99 -0
  76. package/studio/src/index.js +3582 -0
  77. package/studio/src/interaction-triggers.js +42 -0
  78. package/studio/src/json-patch.js +77 -0
  79. package/studio/src/layer-icons.js +25 -0
  80. package/studio/src/lottie-export.js +948 -0
  81. package/studio/src/lottie-import.js +1138 -0
  82. package/studio/src/masks.js +69 -0
  83. package/studio/src/media-assets.js +188 -0
  84. package/studio/src/media-library.js +193 -0
  85. package/studio/src/model.js +431 -0
  86. package/studio/src/numeric-fields.js +46 -0
  87. package/studio/src/object-list.js +57 -0
  88. package/studio/src/paint-tools.js +76 -0
  89. package/studio/src/placement-effects.js +74 -0
  90. package/studio/src/playback.js +10 -0
  91. package/studio/src/preview-audio.js +64 -0
  92. package/studio/src/preview-interactions.js +106 -0
  93. package/studio/src/preview-recorder.js +335 -0
  94. package/studio/src/preview-surface.js +338 -0
  95. package/studio/src/project-io.js +905 -0
  96. package/studio/src/project-session.js +375 -0
  97. package/studio/src/projects-dialog.js +319 -0
  98. package/studio/src/scene-transition.js +129 -0
  99. package/studio/src/script-editor.js +175 -0
  100. package/studio/src/script-references.js +74 -0
  101. package/studio/src/scripted-controls.js +146 -0
  102. package/studio/src/scripts.js +185 -0
  103. package/studio/src/stage-guides.js +101 -0
  104. package/studio/src/svg-animation.js +416 -0
  105. package/studio/src/svg-context.js +522 -0
  106. package/studio/src/svg-frame.js +413 -0
  107. package/studio/src/svg-import.js +1208 -0
  108. package/studio/src/swf-recording.js +104 -0
  109. package/studio/src/symbol-library.js +39 -0
  110. package/studio/src/symbols.js +62 -0
  111. package/studio/src/text-fields.js +58 -0
  112. package/studio/src/theme.js +43 -0
  113. package/studio/src/timeline.js +321 -0
  114. package/studio/src/vector-cut.js +103 -0
  115. package/studio/src/vector-geometry.js +254 -0
  116. package/studio/src/vector-style.js +146 -0
  117. package/studio/src/video-encode.js +84 -0
  118. package/studio/src/video-export.js +331 -0
  119. package/studio/src/video-mux.js +339 -0
  120. package/studio/src/video-playback.js +281 -0
  121. package/studio/src/workspace.js +344 -0
  122. package/studio/stroke-style.test.js +119 -0
  123. package/studio/styles.css +1547 -0
  124. package/studio/svg-export.test.js +162 -0
  125. package/studio/svg-import.test.js +318 -0
  126. package/studio/swf-authoring.test.js +140 -0
  127. package/studio/swf-export.test.js +324 -0
  128. package/studio/swf-import.test.js +489 -0
  129. package/studio/symbols.test.js +68 -0
  130. package/studio/tests/accessibility-interactions.mjs +138 -0
  131. package/studio/tests/appearance-interactions.mjs +103 -0
  132. package/studio/tests/control-interactions.mjs +60 -0
  133. package/studio/tests/event-interactions.mjs +117 -0
  134. package/studio/tests/external-resources.mjs +174 -0
  135. package/studio/tests/frame-image.mjs +71 -0
  136. package/studio/tests/html-export.mjs +68 -0
  137. package/studio/tests/import-files.mjs +131 -0
  138. package/studio/tests/lottie.mjs +125 -0
  139. package/studio/tests/mask-interactions.mjs +148 -0
  140. package/studio/tests/media-interactions.mjs +109 -0
  141. package/studio/tests/paint-interactions.mjs +64 -0
  142. package/studio/tests/project-interactions.mjs +244 -0
  143. package/studio/tests/script-interactions.mjs +178 -0
  144. package/studio/tests/scripted-control-interactions.mjs +107 -0
  145. package/studio/tests/svg-export.mjs +149 -0
  146. package/studio/tests/text-field-interactions.mjs +64 -0
  147. package/studio/tests/theme-interactions.mjs +53 -0
  148. package/studio/tests/timeline-browser.mjs +507 -0
  149. package/studio/tests/transition-interactions.mjs +94 -0
  150. package/studio/tests/trigger-interactions.mjs +93 -0
  151. package/studio/tests/video-export.mjs +243 -0
  152. package/studio/tests/workspace-interactions.mjs +226 -0
  153. package/studio/tween-recovery.test.js +31 -0
  154. package/studio/vector-style.test.js +56 -0
  155. package/studio/video-export.test.js +326 -0
  156. package/studiospec/actionscript.md +88 -0
  157. package/studiospec/architecture.md +378 -0
  158. package/studiospec/controls.md +100 -0
  159. package/studiospec/file-support.md +268 -0
  160. package/studiospec/lottie.md +69 -0
  161. package/studiospec/requirements.md +135 -0
  162. package/studiospec/stroke-style.md +95 -0
  163. package/studiospec/svg-export.md +83 -0
  164. package/studiospec/svg-import.md +139 -0
  165. package/studiospec/swooflib-integration.md +115 -0
  166. package/studiospec/tasks.md +573 -0
  167. package/studiospec/video-export.md +127 -0
  168. package/swf2js/__tests__/actionscript.test.js +1609 -0
  169. package/swf2js/__tests__/adpcm-audio.test.js +43 -0
  170. package/swf2js/__tests__/as2-compiler.test.js +153 -0
  171. package/swf2js/__tests__/as3-mixed-depth.test.js +498 -0
  172. package/swf2js/__tests__/authored-sprite-hit.test.js +118 -0
  173. package/swf2js/__tests__/authored-sprite-sizing.test.js +164 -0
  174. package/swf2js/__tests__/avm1-action-prefix.test.js +134 -0
  175. package/swf2js/__tests__/avm1-attach-movie.test.js +1151 -0
  176. package/swf2js/__tests__/avm1-boxhead-budget.test.js +73 -0
  177. package/swf2js/__tests__/avm1-cfg-bubble-tanks.test.js +101 -0
  178. package/swf2js/__tests__/avm1-cfg-mario-kart.test.js +184 -0
  179. package/swf2js/__tests__/avm1-cfg-mario.test.js +31 -0
  180. package/swf2js/__tests__/avm1-cfg-pacman.test.js +49 -0
  181. package/swf2js/__tests__/avm1-checkers-gameplay.test.js +122 -0
  182. package/swf2js/__tests__/avm1-clip-actions.test.js +2002 -0
  183. package/swf2js/__tests__/avm1-clone-drag.test.js +626 -0
  184. package/swf2js/__tests__/avm1-decompiler.test.js +102 -0
  185. package/swf2js/__tests__/avm1-dynamic-locals.test.js +159 -0
  186. package/swf2js/__tests__/avm1-formal-parameters.test.js +71 -0
  187. package/swf2js/__tests__/avm1-key-events.test.js +52 -0
  188. package/swf2js/__tests__/avm1-load-bitmap.test.js +75 -0
  189. package/swf2js/__tests__/avm1-loading-host-actions.test.js +764 -0
  190. package/swf2js/__tests__/avm1-multibyte-strings.test.js +63 -0
  191. package/swf2js/__tests__/avm1-pacman-gameplay.test.js +115 -0
  192. package/swf2js/__tests__/avm1-shape-hittest.test.js +311 -0
  193. package/swf2js/__tests__/avm1-shared-bodies.test.js +57 -0
  194. package/swf2js/__tests__/avm1-shared-runtime.test.js +1364 -0
  195. package/swf2js/__tests__/avm1-snake-gameplay.test.js +139 -0
  196. package/swf2js/__tests__/avm1-super.test.js +70 -0
  197. package/swf2js/__tests__/avm1-target-path.test.js +325 -0
  198. package/swf2js/__tests__/avm1-try.test.js +229 -0
  199. package/swf2js/__tests__/avm2-activation-closures.test.js +65 -0
  200. package/swf2js/__tests__/avm2-applytype.test.js +180 -0
  201. package/swf2js/__tests__/avm2-call-ops.test.js +232 -0
  202. package/swf2js/__tests__/avm2-callsuperid.test.js +231 -0
  203. package/swf2js/__tests__/avm2-class-initializer.test.js +219 -0
  204. package/swf2js/__tests__/avm2-custom-namespace.test.js +139 -0
  205. package/swf2js/__tests__/avm2-describe-type.test.js +96 -0
  206. package/swf2js/__tests__/avm2-dictionary.test.js +96 -0
  207. package/swf2js/__tests__/avm2-domain-memory.test.js +332 -0
  208. package/swf2js/__tests__/avm2-e4x.test.js +326 -0
  209. package/swf2js/__tests__/avm2-exceptions.test.js +81 -0
  210. package/swf2js/__tests__/avm2-findprop.test.js +110 -0
  211. package/swf2js/__tests__/avm2-getlex.test.js +166 -0
  212. package/swf2js/__tests__/avm2-global-slot.test.js +106 -0
  213. package/swf2js/__tests__/avm2-interface.test.js +95 -0
  214. package/swf2js/__tests__/avm2-multiname-precedence.test.js +148 -0
  215. package/swf2js/__tests__/avm2-named-namespace-types.test.js +106 -0
  216. package/swf2js/__tests__/avm2-optional-args.test.js +100 -0
  217. package/swf2js/__tests__/avm2-outer-scopes.test.js +101 -0
  218. package/swf2js/__tests__/avm2-package-internal-class.test.js +106 -0
  219. package/swf2js/__tests__/avm2-protected-namespace.test.js +105 -0
  220. package/swf2js/__tests__/avm2-protected.test.js +214 -0
  221. package/swf2js/__tests__/avm2-qwop-gameplay.test.js +116 -0
  222. package/swf2js/__tests__/avm2-runtime-namespaces.test.js +159 -0
  223. package/swf2js/__tests__/avm2-script-traits.test.js +89 -0
  224. package/swf2js/__tests__/avm2-shared-runtime.test.js +52 -0
  225. package/swf2js/__tests__/avm2-slot-ops.test.js +117 -0
  226. package/swf2js/__tests__/avm2-type-ops.test.js +224 -0
  227. package/swf2js/__tests__/bevel-filter.test.js +116 -0
  228. package/swf2js/__tests__/bitmap-button-mask.test.js +106 -0
  229. package/swf2js/__tests__/bitmap-data-draw.test.js +388 -0
  230. package/swf2js/__tests__/bitmap-decoder.test.js +108 -0
  231. package/swf2js/__tests__/bitmapdata-color-bounds.test.js +70 -0
  232. package/swf2js/__tests__/bitmapdata-copy-channel.test.js +91 -0
  233. package/swf2js/__tests__/bitmapdata-copy-pixels.test.js +136 -0
  234. package/swf2js/__tests__/bitmapdata-fill-compare.test.js +241 -0
  235. package/swf2js/__tests__/bitmapdata-filter.test.js +232 -0
  236. package/swf2js/__tests__/bitmapdata-hit-test.test.js +71 -0
  237. package/swf2js/__tests__/bitmapdata-merge.test.js +84 -0
  238. package/swf2js/__tests__/bitmapdata-palette-map.test.js +92 -0
  239. package/swf2js/__tests__/bitmapdata-pixels-io.test.js +198 -0
  240. package/swf2js/__tests__/bitmapdata-threshold.test.js +97 -0
  241. package/swf2js/__tests__/bitmapdata-vector.test.js +82 -0
  242. package/swf2js/__tests__/blur-filter.test.js +48 -0
  243. package/swf2js/__tests__/bundle-emitter.test.js +394 -0
  244. package/swf2js/__tests__/button-actions.test.js +370 -0
  245. package/swf2js/__tests__/button-color-transform.test.js +48 -0
  246. package/swf2js/__tests__/button-decoder.test.js +106 -0
  247. package/swf2js/__tests__/button-hit-test.test.js +825 -0
  248. package/swf2js/__tests__/button-scaling-grid.test.js +124 -0
  249. package/swf2js/__tests__/button-sound.test.js +105 -0
  250. package/swf2js/__tests__/bytearray-coercion.test.js +23 -0
  251. package/swf2js/__tests__/bytearray-object-serialization.test.js +380 -0
  252. package/swf2js/__tests__/cfg-switch-loop.test.js +103 -0
  253. package/swf2js/__tests__/clip-depth-mask.test.js +119 -0
  254. package/swf2js/__tests__/clipped-bitmap-fill.test.js +118 -0
  255. package/swf2js/__tests__/companion-swf.test.js +638 -0
  256. package/swf2js/__tests__/context-menu.test.js +149 -0
  257. package/swf2js/__tests__/convolution-filter.test.js +74 -0
  258. package/swf2js/__tests__/definefont4.test.js +280 -0
  259. package/swf2js/__tests__/display-displacement.test.js +161 -0
  260. package/swf2js/__tests__/display-list.test.js +80 -0
  261. package/swf2js/__tests__/display-mask-render.test.js +656 -0
  262. package/swf2js/__tests__/displayobject-stage.test.js +320 -0
  263. package/swf2js/__tests__/embedded-script-audio.test.js +131 -0
  264. package/swf2js/__tests__/embedded-swf.test.js +202 -0
  265. package/swf2js/__tests__/embedded-textfield.test.js +107 -0
  266. package/swf2js/__tests__/embedded-timeline-audio.test.js +182 -0
  267. package/swf2js/__tests__/embedded-timeline-input.test.js +420 -0
  268. package/swf2js/__tests__/embedded-timer-lifecycle.test.js +145 -0
  269. package/swf2js/__tests__/event-priority-order.test.js +125 -0
  270. package/swf2js/__tests__/event-weak-listeners.test.js +53 -0
  271. package/swf2js/__tests__/event-will-trigger.test.js +43 -0
  272. package/swf2js/__tests__/flash-text-engine-content.test.js +115 -0
  273. package/swf2js/__tests__/flash-text-engine-format.test.js +95 -0
  274. package/swf2js/__tests__/flash-text-engine-line.test.js +314 -0
  275. package/swf2js/__tests__/font-encoder.test.js +95 -0
  276. package/swf2js/__tests__/font-outline-text.test.js +659 -0
  277. package/swf2js/__tests__/glow-shadow-filter.test.js +68 -0
  278. package/swf2js/__tests__/graphics-bitmap-smoothing.test.js +32 -0
  279. package/swf2js/__tests__/graphics-fill-lifetime.test.js +36 -0
  280. package/swf2js/__tests__/graphics-gradient-matrix.test.js +53 -0
  281. package/swf2js/__tests__/graphics-stroke-hit-test.test.js +457 -0
  282. package/swf2js/__tests__/hit-test-primitives.test.js +414 -0
  283. package/swf2js/__tests__/input-events.test.js +714 -0
  284. package/swf2js/__tests__/integration/corpus.test.js +41 -0
  285. package/swf2js/__tests__/loader-embedded-swf.test.js +210 -0
  286. package/swf2js/__tests__/loader-info.test.js +81 -0
  287. package/swf2js/__tests__/local-connection.test.js +122 -0
  288. package/swf2js/__tests__/morph-focal-gradient.test.js +51 -0
  289. package/swf2js/__tests__/morph-topology.test.js +267 -0
  290. package/swf2js/__tests__/movie-data-codec.test.js +128 -0
  291. package/swf2js/__tests__/nellymoser-audio.test.js +84 -0
  292. package/swf2js/__tests__/opaque-background-cache.test.js +352 -0
  293. package/swf2js/__tests__/path-stream.test.js +81 -0
  294. package/swf2js/__tests__/place-object-filters.test.js +88 -0
  295. package/swf2js/__tests__/place-object3-decoder.test.js +116 -0
  296. package/swf2js/__tests__/place-object3-image.test.js +85 -0
  297. package/swf2js/__tests__/player-version.test.js +46 -0
  298. package/swf2js/__tests__/root-textfield.test.js +287 -0
  299. package/swf2js/__tests__/scaling-grid.test.js +183 -0
  300. package/swf2js/__tests__/shape-decoder.test.js +361 -0
  301. package/swf2js/__tests__/shape-line-style2.test.js +138 -0
  302. package/swf2js/__tests__/shape-nonscaling-stroke.test.js +131 -0
  303. package/swf2js/__tests__/shape-pixel-hint.test.js +101 -0
  304. package/swf2js/__tests__/simplebutton-pointer.test.js +1477 -0
  305. package/swf2js/__tests__/socket-offline.test.js +67 -0
  306. package/swf2js/__tests__/sound-avm1-stop.test.js +99 -0
  307. package/swf2js/__tests__/sound-envelope.test.js +110 -0
  308. package/swf2js/__tests__/sound-extract.test.js +168 -0
  309. package/swf2js/__tests__/sound-id3.test.js +283 -0
  310. package/swf2js/__tests__/sound-load.test.js +259 -0
  311. package/swf2js/__tests__/sound-mixer-spectrum.test.js +261 -0
  312. package/swf2js/__tests__/sound-stream-sprite.test.js +624 -0
  313. package/swf2js/__tests__/sound-transform.test.js +104 -0
  314. package/swf2js/__tests__/speex-audio.test.js +77 -0
  315. package/swf2js/__tests__/stage-noscale.test.js +45 -0
  316. package/swf2js/__tests__/swf-encoder.test.js +134 -0
  317. package/swf2js/__tests__/swflib-assemble.test.js +20 -0
  318. package/swf2js/__tests__/textfield-html-text.test.js +368 -0
  319. package/swf2js/__tests__/textfield-line-layout.test.js +339 -0
  320. package/swf2js/__tests__/textfield-programmatic-overlay.test.js +2506 -0
  321. package/swf2js/__tests__/textfield-scroll.test.js +79 -0
  322. package/swf2js/__tests__/textfield-selection.test.js +383 -0
  323. package/swf2js/__tests__/timeline-effect-surfaces.test.js +295 -0
  324. package/swf2js/__tests__/timeline-named-anchor.test.js +139 -0
  325. package/swf2js/__tests__/timeline-scenes.test.js +1723 -0
  326. package/swf2js/__tests__/urlloader-http-status.test.js +236 -0
  327. package/{src → swf2js}/cli.js +43 -11
  328. package/swf2js/compiler/as2-classes.js +156 -0
  329. package/swf2js/compiler/as2-parser.js +598 -0
  330. package/swf2js/compiler/avm1-codegen.js +897 -0
  331. package/swf2js/compiler/index.js +28 -0
  332. package/{src → swf2js}/decoder/button-decoder.js +3 -1
  333. package/swf2js/decoder/png.js +114 -0
  334. package/{src → swf2js}/decoder/shape-decoder.js +20 -10
  335. package/{src → swf2js}/decoder/tag-decoder.js +5 -3
  336. package/{src → swf2js}/decoder/tag-types.js +4 -0
  337. package/swf2js/decompiler/avm1-decompiler.js +1138 -0
  338. package/{src → swf2js}/emitter/asset-encoder.js +66 -113
  339. package/{src → swf2js}/emitter/bundle-emitter.js +209 -78
  340. package/swf2js/emitter/external-resources.js +39 -0
  341. package/swf2js/emitter/movie-data-codec.js +91 -0
  342. package/swf2js/encoder/bit-writer.js +182 -0
  343. package/swf2js/encoder/shape-encoder.js +310 -0
  344. package/swf2js/encoder/swf-builder.js +639 -0
  345. package/swf2js/encoder/swf-writer.js +55 -0
  346. package/{src/runtime/swflib/assemble.js → swf2js/runtime/assemble-swooflib.js} +4 -3
  347. package/{src → swf2js}/runtime/avm1-runtime.js +102 -63
  348. package/{src → swf2js}/runtime/index.js +1 -1
  349. package/{src → swf2js}/runtime/movie-runtime.js +28 -2
  350. package/{src → swf2js}/transpiler/actionscript.js +82 -19
  351. package/{src → swf2js}/transpiler/avm1/avm1-opcodes.js +5 -3
  352. package/{src → swf2js}/transpiler/avm1/avm1-transpiler.js +69 -6
  353. package/{src → swf2js}/transpiler/avm2/avm2-transpiler.js +1 -1
  354. package/{src → swf2js}/transpiler/timeline/display-list.js +41 -22
  355. package/{src → swf2js}/transpiler/timeline/timeline-codegen.js +97 -36
  356. package/swooflib/README.md +569 -0
  357. package/swooflib/adpcm.js +147 -0
  358. package/{src/runtime/swflib → swooflib}/builtins.js +6 -0
  359. package/{src/runtime/swflib → swooflib}/context-menu.js +7 -1
  360. package/swooflib/control-definitions.js +42 -0
  361. package/swooflib/control-widget.js +763 -0
  362. package/swooflib/controls.js +300 -0
  363. package/{src/runtime/swflib → swooflib}/display.js +16 -10
  364. package/{src/runtime/swflib → swooflib}/events.js +11 -0
  365. package/{src/runtime/swflib → swooflib}/flash.js +6 -5
  366. package/{src/runtime/swflib → swooflib}/graphics.js +81 -19
  367. package/{src/runtime/swflib → swooflib}/input.js +12 -14
  368. package/{src/runtime/swflib → swooflib}/loader.js +52 -22
  369. package/swooflib/movie-network.js +86 -0
  370. package/swooflib/path-stream.js +169 -0
  371. package/{src/runtime/swflib → swooflib}/render.js +3 -13
  372. package/{src/runtime/swflib → swooflib}/sound.js +25 -2
  373. package/{src/runtime/swflib → swooflib}/stage.js +3 -3
  374. package/swooflib/stream-time.js +21 -0
  375. package/{src/runtime/swflib → swooflib}/system.js +88 -37
  376. package/{src/runtime/swflib → swooflib}/text-paint.js +14 -3
  377. package/{src/runtime/swflib → swooflib}/text.js +8 -0
  378. package/swooflib/xml-node.js +53 -0
  379. package/src/emitter/timeline-data-codec.js +0 -58
  380. /package/{src → swf2js}/decoder/symbol-table.js +0 -0
  381. /package/{src → swf2js}/emitter/embedded-swf.js +0 -0
  382. /package/{src → swf2js}/emitter/font-encoder.js +0 -0
  383. /package/{src → swf2js}/model/swf-document.js +0 -0
  384. /package/{src → swf2js}/model/transpile-result.js +0 -0
  385. /package/{src → swf2js}/parser/bit-reader.js +0 -0
  386. /package/{src → swf2js}/parser/decompressor.js +0 -0
  387. /package/{src → swf2js}/parser/swf-parser.js +0 -0
  388. /package/{src → swf2js}/pretty-printer/pretty-printer.js +0 -0
  389. /package/{src → swf2js}/runtime/avm2-runtime.js +0 -0
  390. /package/{src → swf2js}/runtime/embedded-movie-runtime.js +0 -0
  391. /package/{src → swf2js}/transpiler/avm1/avm1-ir.js +0 -0
  392. /package/{src → swf2js}/transpiler/avm1/avm1-rewrite.js +0 -0
  393. /package/{src → swf2js}/transpiler/avm2/abc-reader.js +0 -0
  394. /package/{src → swf2js}/transpiler/cfg-structurer.js +0 -0
  395. /package/{src → swf2js}/util/diagnostics.js +0 -0
  396. /package/{src → swf2js}/util/logger.js +0 -0
  397. /package/{src/runtime/swflib → swooflib}/bitmap-image.js +0 -0
  398. /package/{src/runtime/swflib → swooflib}/bitmap.js +0 -0
  399. /package/{src/runtime/swflib → swooflib}/bytearray.js +0 -0
  400. /package/{src/runtime/swflib → swooflib}/compiled-swf.js +0 -0
  401. /package/{src/runtime/swflib → swooflib}/cursor-flag.js +0 -0
  402. /package/{src/runtime/swflib → swooflib}/dictionary.js +0 -0
  403. /package/{src/runtime/swflib → swooflib}/filters.js +0 -0
  404. /package/{src/runtime/swflib → swooflib}/geom.js +0 -0
  405. /package/{src/runtime/swflib → swooflib}/glyph-metrics.js +0 -0
  406. /package/{src/runtime/swflib → swooflib}/host.js +0 -0
  407. /package/{src/runtime/swflib → swooflib}/inherit.js +0 -0
  408. /package/{src/runtime/swflib → swooflib}/marks.js +0 -0
  409. /package/{src/runtime/swflib → swooflib}/matrix3d.js +0 -0
  410. /package/{src/runtime/swflib → swooflib}/pointer-bridge.js +0 -0
  411. /package/{src/runtime/swflib → swooflib}/projection.js +0 -0
  412. /package/{src/runtime/swflib → swooflib}/sprite-drag.js +0 -0
  413. /package/{src/runtime/swflib → swooflib}/stage-ref.js +0 -0
  414. /package/{src/runtime/swflib → swooflib}/text-field.js +0 -0
  415. /package/{src/runtime/swflib → swooflib}/transform.js +0 -0
  416. /package/{src/runtime/swflib → swooflib}/xml.js +0 -0
@@ -0,0 +1,331 @@
1
+ // Video export (studiospec/video-export.md): plays the project headlessly with Preview's rules,
2
+ // renders every frame offline on its own canvas, encodes with WebCodecs and writes MP4 or WebM.
3
+ // Nothing is sent to the server, and the live stage is never touched.
4
+ import { renderCaptureFrame } from './canvas.js';
5
+ import { decodeAsset, decodedAsset } from './media-assets.js';
6
+ import { createAudioSchedule, playHeadless, projectHasSound, videoExportRefusal } from './video-playback.js';
7
+ import { AUDIO_CHANNELS, AUDIO_RATE, encoderSettings, hasWebCodecs, muxCodec, outputSize } from './video-encode.js';
8
+ import { writeMp4, writeWebm } from './video-mux.js';
9
+ import { ANIMATED_FORMATS, createAnimatedWriter } from './animated-image.js';
10
+ import { openRecording, recordFrames } from './swf-recording.js';
11
+
12
+ export { videoExportRefusal };
13
+
14
+ const AUDIO_FRAME = 1024;
15
+ const QUEUE_LIMIT = 4;
16
+
17
+ function abortError() {
18
+ return new DOMException('Video export was cancelled', 'AbortError');
19
+ }
20
+
21
+ function canvas(width, height) {
22
+ const element = document.createElement('canvas');
23
+ element.width = width;
24
+ element.height = height;
25
+ return element;
26
+ }
27
+
28
+ // Waits while the encoder holds more than a few frames, so memory stays bounded on slow encoders.
29
+ async function drain(encoder) {
30
+ while (encoder.encodeQueueSize > QUEUE_LIMIT) await new Promise(resolve => encoder.addEventListener('dequeue', resolve, { once: true }));
31
+ }
32
+
33
+ const timestampAt = (index, rate) => Math.round(index * 1e6 / rate);
34
+
35
+ function collect(onError) {
36
+ const stream = { chunks: [], description: null };
37
+ return {
38
+ stream,
39
+ output(chunk, metadata) {
40
+ const data = new Uint8Array(chunk.byteLength);
41
+ chunk.copyTo(data);
42
+ stream.chunks.push({ data, timestamp: chunk.timestamp, duration: chunk.duration ?? 0, key: chunk.type === 'key' });
43
+ const description = metadata?.decoderConfig?.description;
44
+ if (description && !stream.description) {
45
+ stream.description = description instanceof ArrayBuffer ? new Uint8Array(description.slice(0))
46
+ : new Uint8Array(description.buffer.slice(description.byteOffset, description.byteOffset + description.byteLength));
47
+ }
48
+ },
49
+ error: onError,
50
+ };
51
+ }
52
+
53
+ // A Flash sound envelope: left and right levels (0–32768) at sample positions, ramped linearly and
54
+ // restarted on each loop, as swooflib/sound.js plays it.
55
+ function applyEnvelope(context, source, segment, end) {
56
+ const points = [...segment.envelope].sort((a, b) => a.position - b.position);
57
+ const level = value => Math.max(0, Math.min(1, value / 32768));
58
+ const levelsAt = position => {
59
+ if (position <= points[0].position) return [points[0].leftLevel, points[0].rightLevel];
60
+ const next = points.findIndex(point => point.position >= position);
61
+ if (next < 0) return [points.at(-1).leftLevel, points.at(-1).rightLevel];
62
+ const before = points[next - 1], after = points[next];
63
+ const t = (position - before.position) / Math.max(1, after.position - before.position);
64
+ return [before.leftLevel + (after.leftLevel - before.leftLevel) * t, before.rightLevel + (after.rightLevel - before.rightLevel) * t];
65
+ };
66
+ const merger = context.createChannelMerger(2);
67
+ const splitter = source.buffer.numberOfChannels > 1 ? context.createChannelSplitter(2) : null;
68
+ if (splitter) source.connect(splitter);
69
+ const gains = [0, 1].map(channel => {
70
+ const gain = context.createGain();
71
+ if (splitter) splitter.connect(gain, channel);
72
+ else source.connect(gain);
73
+ gain.connect(merger, 0, channel);
74
+ return gain.gain;
75
+ });
76
+ merger.connect(context.destination);
77
+ const length = segment.loopEnd - segment.loopStart;
78
+ for (let base = segment.start; base < end; base += length) {
79
+ gains.forEach((gain, channel) => {
80
+ gain.setValueAtTime(level(levelsAt(segment.loopStart * 44100)[channel]), base);
81
+ for (const point of points) {
82
+ const at = point.position / 44100 - segment.loopStart;
83
+ if (at > 0 && at < length) gain.linearRampToValueAtTime(level([point.leftLevel, point.rightLevel][channel]), base + at);
84
+ }
85
+ });
86
+ }
87
+ }
88
+
89
+ async function mixAudio(project, segments, seconds) {
90
+ const length = Math.max(1, Math.ceil(seconds * AUDIO_RATE));
91
+ const context = new OfflineAudioContext(AUDIO_CHANNELS, length, AUDIO_RATE);
92
+ for (const segment of segments) {
93
+ const buffer = decodedAsset(project.assets.find(asset => asset.id === segment.assetId));
94
+ const end = Math.min(segment.end, seconds);
95
+ if (!buffer || end <= segment.start) continue;
96
+ const source = context.createBufferSource();
97
+ source.buffer = buffer;
98
+ source.loop = segment.loop;
99
+ if (segment.loopEnd != null) {
100
+ source.loopStart = segment.loopStart;
101
+ source.loopEnd = segment.loopEnd;
102
+ }
103
+ if (segment.envelope) applyEnvelope(context, source, segment, end);
104
+ else source.connect(context.destination);
105
+ source.start(segment.start, segment.offset);
106
+ source.stop(end);
107
+ }
108
+ return context.startRendering();
109
+ }
110
+
111
+ async function encodeAudio(config, buffer, signal) {
112
+ let failure;
113
+ const sink = collect(error => { failure = error; });
114
+ const encoder = new AudioEncoder(sink);
115
+ encoder.configure(config);
116
+ try {
117
+ const channels = Array.from({ length: buffer.numberOfChannels }, (_, i) => buffer.getChannelData(i));
118
+ for (let start = 0; start < buffer.length; start += AUDIO_FRAME) {
119
+ if (signal?.aborted) throw abortError();
120
+ if (failure) throw failure;
121
+ const frames = Math.min(AUDIO_FRAME, buffer.length - start);
122
+ const planes = new Float32Array(frames * channels.length);
123
+ channels.forEach((data, i) => planes.set(data.subarray(start, start + frames), i * frames));
124
+ const data = new AudioData({ format: 'f32-planar', sampleRate: AUDIO_RATE, numberOfFrames: frames,
125
+ numberOfChannels: channels.length, timestamp: timestampAt(start, AUDIO_RATE), data: planes });
126
+ encoder.encode(data);
127
+ data.close();
128
+ await drain(encoder);
129
+ }
130
+ await encoder.flush();
131
+ if (failure) throw failure;
132
+ } finally {
133
+ if (encoder.state !== 'closed') encoder.close();
134
+ }
135
+ return { codec: muxCodec(config), sampleRate: AUDIO_RATE, channels: AUDIO_CHANNELS, ...sink.stream };
136
+ }
137
+
138
+ /**
139
+ * Plays the project from the start and calls `emit(canvas)` once per video frame. Studio's own
140
+ * renderer draws it, as Preview does, or, for projects that play on the swf2js player (scripts,
141
+ * nine-slice scaling), the Preview movie is recorded with a virtual clock (swf-recording.js);
142
+ * `recordPreview()` builds that movie and returns its URL. Returns `{ frames, ending, mixed }`,
143
+ * where `mixed` is the sound as an AudioBuffer when `sound` is set and there is any.
144
+ */
145
+ async function produceFrames(project, { width, height, scale, maxFrames, signal, sound, recordPreview, onProgress }, emit) {
146
+ const { stage } = project;
147
+ const fps = stage.frameRate;
148
+ const frameCanvas = canvas(width, height);
149
+ const refusal = videoExportRefusal(project);
150
+ if (refusal) {
151
+ if (!recordPreview) throw new Error(refusal);
152
+ onProgress(0, 'Building the movie…');
153
+ const url = await recordPreview();
154
+ onProgress(0, 'Loading the movie…');
155
+ const recording = await openRecording(url, { fps, width: stage.width, height: stage.height, signal });
156
+ try {
157
+ const ctx = frameCanvas.getContext('2d');
158
+ ctx.imageSmoothingQuality = 'high';
159
+ const result = await recordFrames(recording, { maxFrames, holdFrames: Math.round(fps), fps, signal, onFrame: async bitmap => {
160
+ ctx.fillStyle = stage.background ?? '#ffffff';
161
+ ctx.fillRect(0, 0, width, height);
162
+ ctx.drawImage(bitmap, 0, 0, Math.round(stage.width * scale), Math.round(stage.height * scale));
163
+ await emit(frameCanvas);
164
+ } });
165
+ let mixed = null;
166
+ if (sound) {
167
+ onProgress(0.92, 'Mixing sound…');
168
+ const { channels, sampleRate } = await recording.audio(result.frames / fps);
169
+ if (channels) {
170
+ mixed = new AudioBuffer({ numberOfChannels: channels.length, length: channels[0].length, sampleRate });
171
+ channels.forEach((data, channel) => mixed.copyToChannel(data, channel));
172
+ }
173
+ }
174
+ return { ...result, mixed };
175
+ } finally {
176
+ recording.close();
177
+ }
178
+ }
179
+
180
+ onProgress(0, 'Loading media…');
181
+ await Promise.all((project.assets ?? []).map(asset => decodeAsset(asset).catch(() => null)));
182
+ const outgoing = canvas(width, height);
183
+ const composite = canvas(width, height);
184
+ const audio = sound ? createAudioSchedule({ fps, durationOf: id => {
185
+ const buffer = decodedAsset(project.assets.find(asset => asset.id === id));
186
+ return buffer?.duration ?? 0;
187
+ } }) : null;
188
+ const result = await playHeadless({
189
+ project, maxFrames, holdFrames: Math.round(fps), audio,
190
+ render: ({ scene, playhead, hiddenIds, clocks }) => renderCaptureFrame(frameCanvas, {
191
+ stage, scene, symbols: project.symbols ?? [], assets: project.assets ?? [], clocks, playhead, hiddenIds, scale,
192
+ }),
193
+ snapshot: () => {
194
+ const ctx = outgoing.getContext('2d');
195
+ ctx.clearRect(0, 0, width, height);
196
+ ctx.drawImage(frameCanvas, 0, 0);
197
+ },
198
+ emit: async transition => {
199
+ if (!transition) return emit(frameCanvas);
200
+ // As in Preview, the outgoing image lies over the incoming scene and fades or wipes away.
201
+ compositeFrame(composite, frameCanvas, outgoing, transition, width, height);
202
+ return emit(composite);
203
+ },
204
+ });
205
+ let mixed = null;
206
+ if (audio) {
207
+ audio.finish(result.frames / fps);
208
+ if (audio.segments.length) {
209
+ onProgress(0.92, 'Mixing sound…');
210
+ mixed = await mixAudio(project, audio.segments, result.frames / fps);
211
+ }
212
+ }
213
+ return { ...result, mixed };
214
+ }
215
+
216
+ /**
217
+ * Renders and encodes `project` as a video Blob.
218
+ * options: { format: 'mp4' | 'webm' | 'gif' | 'apng' | 'webp' | 'svg' | 'lottie', scale: 0.5 | 1 | 2, includeSound, maxSeconds, signal,
219
+ * recordPreview, onProgress(fraction, message), studioData (SVG and Lottie: embed the project; SVG off, Lottie on by default) }. Animated images (GIF, APNG, WebP) are silent and loop.
220
+ */
221
+ export async function exportVideo(project, { format = 'mp4', scale = 1, includeSound = true, maxSeconds = 60, signal, recordPreview = null, onProgress = () => {}, studioData } = {}) {
222
+ if (format === 'svg') return (await import('./svg-animation.js')).exportAnimatedSvg(project, { scale, maxSeconds, signal, onProgress, studioData: studioData ?? false });
223
+ if (format === 'lottie') return (await import('./lottie-export.js')).exportLottie(project, { maxSeconds, signal, onProgress, studioData: studioData ?? true });
224
+ const refusal = videoExportRefusal(project);
225
+ if (refusal && !recordPreview) throw new Error(refusal);
226
+ if (ANIMATED_FORMATS[format]) return exportAnimatedImage(project, { format, scale, maxSeconds, signal, recordPreview, onProgress });
227
+ if (!hasWebCodecs()) throw new Error('This browser cannot encode video. Use a recent Chrome or Edge.');
228
+ const { stage } = project;
229
+ const fps = stage.frameRate;
230
+ const { width, height } = outputSize(stage, scale);
231
+ const maxFrames = Math.max(1, Math.round(maxSeconds * fps));
232
+ const wantsAudio = includeSound && projectHasSound(project);
233
+ const settings = await encoderSettings(format, width, height, fps, wantsAudio);
234
+ if (!settings) throw new Error(`This browser cannot encode ${format.toUpperCase()} video at ${width} × ${height}. Choose another format or size.`);
235
+
236
+ let failure;
237
+ const video = collect(error => { failure = error; });
238
+ const encoder = new VideoEncoder(video);
239
+ encoder.configure(settings.video);
240
+ const keyInterval = Math.max(1, Math.round(fps * 2));
241
+ let index = 0;
242
+ let result;
243
+ try {
244
+ result = await produceFrames(project, { width, height, scale, maxFrames, signal, sound: Boolean(wantsAudio && settings.audio), recordPreview, onProgress },
245
+ async source => {
246
+ if (signal?.aborted) throw abortError();
247
+ if (failure) throw failure;
248
+ const timestamp = timestampAt(index, fps);
249
+ const frame = new VideoFrame(source, { timestamp, duration: timestampAt(index + 1, fps) - timestamp });
250
+ encoder.encode(frame, { keyFrame: index % keyInterval === 0 });
251
+ frame.close();
252
+ index++;
253
+ await drain(encoder);
254
+ if (index % 15 === 0) {
255
+ onProgress(index / maxFrames * 0.9, `Rendering frame ${index}…`);
256
+ await new Promise(resolve => setTimeout(resolve, 0));
257
+ }
258
+ });
259
+ onProgress(0.9, 'Finishing the video…');
260
+ await encoder.flush();
261
+ if (failure) throw failure;
262
+ } finally {
263
+ if (encoder.state !== 'closed') encoder.close();
264
+ }
265
+
266
+ const seconds = result.frames / fps;
267
+ let audioStream = null;
268
+ if (result.mixed) {
269
+ if (signal?.aborted) throw abortError();
270
+ onProgress(0.95, 'Encoding sound…');
271
+ audioStream = await encodeAudio(settings.audio, result.mixed, signal);
272
+ }
273
+ if (signal?.aborted) throw abortError();
274
+ onProgress(0.98, 'Writing the file…');
275
+ const movie = { width, height, video: { codec: muxCodec(settings.video), ...video.stream }, audio: audioStream };
276
+ const bytes = format === 'mp4' ? writeMp4(movie) : writeWebm(movie);
277
+ onProgress(1, 'Done');
278
+ return {
279
+ blob: new Blob([bytes], { type: format === 'mp4' ? 'video/mp4' : 'video/webm' }),
280
+ frames: result.frames, seconds, ending: result.ending, width, height, audio: Boolean(audioStream),
281
+ audioUnavailable: wantsAudio && !settings.audio, recorded: Boolean(refusal),
282
+ };
283
+ }
284
+
285
+ // Draws the frame Preview would show into `target`: the scene, with a transition's outgoing
286
+ // image over it when one is running.
287
+ function compositeFrame(target, frameCanvas, outgoing, transition, width, height) {
288
+ const ctx = target.getContext('2d', { willReadFrequently: true });
289
+ ctx.globalAlpha = 1;
290
+ ctx.drawImage(frameCanvas, 0, 0);
291
+ if (!transition) return;
292
+ if (transition.type === 'crossfade') {
293
+ ctx.globalAlpha = 1 - transition.progress;
294
+ ctx.drawImage(outgoing, 0, 0);
295
+ ctx.globalAlpha = 1;
296
+ } else {
297
+ const left = Math.round(transition.progress * width);
298
+ if (left < width) ctx.drawImage(outgoing, left, 0, width - left, height, left, 0, width - left, height);
299
+ }
300
+ }
301
+
302
+ /** GIF, APNG or animated WebP: the same playback, written frame by frame without sound. */
303
+ async function exportAnimatedImage(project, { format, scale, maxSeconds, signal, recordPreview, onProgress }) {
304
+ const { stage } = project;
305
+ const fps = stage.frameRate;
306
+ const { width, height } = outputSize(stage, scale);
307
+ const maxFrames = Math.max(1, Math.round(maxSeconds * fps));
308
+ const writer = createAnimatedWriter(format, width, height);
309
+ const reader = canvas(width, height).getContext('2d', { willReadFrequently: true });
310
+ let index = 0;
311
+ const result = await produceFrames(project, { width, height, scale, maxFrames, signal, sound: false, recordPreview, onProgress }, async source => {
312
+ if (signal?.aborted) throw abortError();
313
+ reader.drawImage(source, 0, 0);
314
+ const pixels = new Uint8Array(reader.getImageData(0, 0, width, height).data.buffer);
315
+ await writer.add(pixels, index * 1000 / fps);
316
+ index++;
317
+ if (index % 5 === 0) {
318
+ onProgress(index / maxFrames * 0.95, `Writing frame ${index}…`);
319
+ await new Promise(resolve => setTimeout(resolve, 0));
320
+ }
321
+ });
322
+ if (signal?.aborted) throw abortError();
323
+ onProgress(0.97, 'Writing the file…');
324
+ const bytes = await writer.finish(result.frames * 1000 / fps);
325
+ onProgress(1, 'Done');
326
+ return {
327
+ blob: new Blob([bytes], { type: ANIMATED_FORMATS[format].type }),
328
+ frames: result.frames, seconds: result.frames / fps, ending: result.ending, width, height, audio: false, audioUnavailable: false,
329
+ recorded: Boolean(videoExportRefusal(project)),
330
+ };
331
+ }
@@ -0,0 +1,339 @@
1
+ // MP4 (ISO BMFF) and WebM (Matroska) writers for video export (studiospec/video-export.md).
2
+ // Pure functions over encoded chunks: no DOM, no WebCodecs.
3
+ //
4
+ // Input shape, shared by both writers:
5
+ // { width, height,
6
+ // video: { codec: 'avc' | 'vp9' | 'vp8', description?: Uint8Array, chunks },
7
+ // audio?: { codec: 'aac' | 'opus', sampleRate, channels, description?: Uint8Array, chunks } }
8
+ // Each chunk is { data: Uint8Array, timestamp, duration, key } with times in microseconds,
9
+ // in decode order.
10
+
11
+ class ByteWriter {
12
+ constructor() { this.parts = []; this.length = 0; }
13
+ bytes(data) { this.parts.push(data); this.length += data.length; return this; }
14
+ u8(value) { return this.bytes(Uint8Array.of(value & 255)); }
15
+ u16(value) { return this.bytes(Uint8Array.of((value >>> 8) & 255, value & 255)); }
16
+ u24(value) { return this.bytes(Uint8Array.of((value >>> 16) & 255, (value >>> 8) & 255, value & 255)); }
17
+ u32(value) { return this.bytes(Uint8Array.of((value >>> 24) & 255, (value >>> 16) & 255, (value >>> 8) & 255, value & 255)); }
18
+ u64(value) { return this.u32(Math.floor(value / 2 ** 32)).u32(value % 2 ** 32); }
19
+ ascii(text) { return this.bytes(Uint8Array.from(text, char => char.charCodeAt(0))); }
20
+ zeros(count) { return this.bytes(new Uint8Array(count)); }
21
+ finish() { return concat(this.parts, this.length); }
22
+ }
23
+
24
+ function concat(parts, length = parts.reduce((sum, part) => sum + part.length, 0)) {
25
+ const out = new Uint8Array(length);
26
+ let offset = 0;
27
+ for (const part of parts) {
28
+ out.set(part, offset);
29
+ offset += part.length;
30
+ }
31
+ return out;
32
+ }
33
+
34
+ const utf8 = text => new TextEncoder().encode(text);
35
+
36
+ // ---------------------------------------------------------------------------------------------
37
+ // MP4
38
+
39
+ function box(type, ...children) {
40
+ const body = concat(children.map(child => child instanceof ByteWriter ? child.finish() : child));
41
+ return new ByteWriter().u32(body.length + 8).ascii(type).bytes(body).finish();
42
+ }
43
+ const fullBox = (type, version, flags, ...children) =>
44
+ box(type, new ByteWriter().u8(version).u24(flags).finish(), ...children);
45
+
46
+ const MATRIX = [0x10000, 0, 0, 0, 0x10000, 0, 0, 0, 0x40000000];
47
+ const VIDEO_TIMESCALE = 90000;
48
+ const MOVIE_TIMESCALE = 1000;
49
+ const INTERLEAVE_US = 500000;
50
+
51
+ function mp4Track(stream, kind, id) {
52
+ const timescale = kind === 'video' ? VIDEO_TIMESCALE : stream.sampleRate;
53
+ // Cumulative rounding keeps every decode time exact to the timescale, so durations never drift.
54
+ const tick = us => Math.round(us * timescale / 1e6);
55
+ const samples = stream.chunks.map(chunk => ({ chunk, start: tick(chunk.timestamp), end: tick(chunk.timestamp + chunk.duration) }));
56
+ const first = samples[0]?.start ?? 0;
57
+ for (const sample of samples) sample.start -= first, sample.end -= first;
58
+ samples.forEach((sample, i) => {
59
+ sample.delta = (samples[i + 1]?.start ?? sample.end) - sample.start;
60
+ // An encoder may leave the last chunk's duration unset: reuse the previous sample's.
61
+ if (sample.delta <= 0 && i > 0) sample.delta = samples[i - 1].delta;
62
+ });
63
+ const last = samples.at(-1);
64
+ if (last) last.end = last.start + last.delta;
65
+ return { kind, id, stream, timescale, samples, duration: samples.at(-1)?.end ?? 0, chunks: [] };
66
+ }
67
+
68
+ function avcSampleEntry({ width, height }, description) {
69
+ if (!description) throw new Error('H.264 export needs the encoder’s avcC record');
70
+ return box('avc1', new ByteWriter()
71
+ .zeros(6).u16(1) // SampleEntry: reserved, data_reference_index
72
+ .u16(0).u16(0).zeros(12) // pre_defined, reserved, pre_defined
73
+ .u16(width).u16(height)
74
+ .u32(0x00480000).u32(0x00480000).u32(0) // 72 dpi, reserved
75
+ .u16(1).zeros(32) // frame_count, compressorname
76
+ .u16(0x18).u16(0xffff), // depth, pre_defined = -1
77
+ box('avcC', description));
78
+ }
79
+
80
+ function descriptor(tag, body) {
81
+ // Four-byte lengths are always valid and keep sizes easy to read in a hex dump.
82
+ const n = body.length;
83
+ return new ByteWriter().u8(tag).u8(0x80 | (n >>> 21) & 127).u8(0x80 | (n >>> 14) & 127).u8(0x80 | (n >>> 7) & 127).u8(n & 127).bytes(body).finish();
84
+ }
85
+
86
+ function audioSampleEntryHeader(type, { channels, sampleRate }) {
87
+ return new ByteWriter().zeros(6).u16(1).zeros(8).u16(channels).u16(16).u16(0).u16(0)
88
+ .u32(Math.min(sampleRate, 65535) * 65536);
89
+ }
90
+
91
+ function aacSampleEntry(audio) {
92
+ if (!audio.description) throw new Error('AAC export needs the encoder’s AudioSpecificConfig');
93
+ const decoderConfig = descriptor(4, concat([
94
+ new ByteWriter().u8(0x40).u8(0x15).u24(0).u32(0).u32(0).finish(), // MPEG-4 audio, audio stream
95
+ descriptor(5, audio.description),
96
+ ]));
97
+ const es = descriptor(3, concat([new ByteWriter().u16(2).u8(0).finish(), decoderConfig, descriptor(6, Uint8Array.of(2))]));
98
+ return box('mp4a', audioSampleEntryHeader('mp4a', audio), fullBox('esds', 0, 0, es));
99
+ }
100
+
101
+ // Opus in ISO BMFF stores its header big-endian in `dOps` (unlike OpusHead in WebM and Ogg).
102
+ function opusSampleEntry(audio) {
103
+ const head = opusHead(audio);
104
+ const view = new DataView(head.buffer, head.byteOffset, head.byteLength);
105
+ const dOps = new ByteWriter().u8(0).u8(head[9]).u16(view.getUint16(10, true)).u32(view.getUint32(12, true))
106
+ .u16(view.getInt16(16, true) & 0xffff).u8(head[18]);
107
+ if (head[18]) dOps.bytes(head.subarray(19));
108
+ return box('Opus', audioSampleEntryHeader('Opus', audio), box('dOps', dOps));
109
+ }
110
+
111
+ export function opusHead({ description, channels, sampleRate }) {
112
+ if (description?.length >= 19 && String.fromCharCode(...description.subarray(0, 8)) === 'OpusHead') return description;
113
+ const head = new Uint8Array(19);
114
+ head.set(utf8('OpusHead'));
115
+ const view = new DataView(head.buffer);
116
+ head[8] = 1;
117
+ head[9] = channels;
118
+ view.setUint16(10, 312, true); // libopus's encoder lookahead at 48 kHz
119
+ view.setUint32(12, sampleRate, true);
120
+ return head;
121
+ }
122
+
123
+ function sampleTable(track, entry) {
124
+ const { samples } = track;
125
+ const stts = [];
126
+ for (const { delta } of samples) {
127
+ if (stts.at(-1)?.delta === delta) stts.at(-1).count++;
128
+ else stts.push({ count: 1, delta });
129
+ }
130
+ const sttsBox = new ByteWriter().u32(stts.length);
131
+ for (const run of stts) sttsBox.u32(run.count).u32(run.delta);
132
+ const stsc = [];
133
+ track.chunks.forEach((chunk, i) => {
134
+ if (stsc.at(-1)?.count !== chunk.samples.length) stsc.push({ first: i + 1, count: chunk.samples.length });
135
+ });
136
+ const stscBox = new ByteWriter().u32(stsc.length);
137
+ for (const run of stsc) stscBox.u32(run.first).u32(run.count).u32(1);
138
+ const stszBox = new ByteWriter().u32(0).u32(samples.length);
139
+ for (const { chunk } of samples) stszBox.u32(chunk.data.length);
140
+ const stcoBox = new ByteWriter().u32(track.chunks.length);
141
+ for (const chunk of track.chunks) stcoBox.u32(chunk.offset);
142
+ const children = [fullBox('stsd', 0, 0, new ByteWriter().u32(1).finish(), entry), fullBox('stts', 0, 0, sttsBox)];
143
+ if (track.kind === 'video' && samples.some(sample => !sample.chunk.key)) {
144
+ const keys = samples.flatMap((sample, i) => sample.chunk.key ? [i + 1] : []);
145
+ const stss = new ByteWriter().u32(keys.length);
146
+ for (const index of keys) stss.u32(index);
147
+ children.push(fullBox('stss', 0, 0, stss));
148
+ }
149
+ children.push(fullBox('stsc', 0, 0, stscBox), fullBox('stsz', 0, 0, stszBox), fullBox('stco', 0, 0, stcoBox));
150
+ return box('stbl', ...children);
151
+ }
152
+
153
+ // Audio encoders put priming samples before the first sound: 2112 for AAC (the usual
154
+ // AudioToolbox and iTunes value) and the pre-skip for Opus. An edit list starts playback after them.
155
+ const AAC_PRIMING = 2112;
156
+ function primingSamples(track) {
157
+ if (track.kind !== 'audio') return 0;
158
+ const audio = track.stream;
159
+ if (audio.codec === 'aac') return audio.priming ?? AAC_PRIMING;
160
+ const head = opusHead(audio);
161
+ return new DataView(head.buffer, head.byteOffset, head.byteLength).getUint16(10, true);
162
+ }
163
+
164
+ function trakBox(track, movie, nextEntry) {
165
+ const video = track.kind === 'video';
166
+ const skip = Math.min(primingSamples(track), track.duration);
167
+ const movieDuration = Math.round((track.duration - skip) * MOVIE_TIMESCALE / track.timescale);
168
+ const edits = skip ? [box('edts', fullBox('elst', 0, 0, new ByteWriter().u32(1).u32(movieDuration).u32(skip).u16(1).u16(0)))] : [];
169
+ const tkhd = new ByteWriter().u32(0).u32(0).u32(track.id).u32(0).u32(movieDuration).zeros(8)
170
+ .u16(0).u16(video ? 0 : 1).u16(video ? 0 : 0x0100).u16(0);
171
+ for (const value of MATRIX) tkhd.u32(value);
172
+ tkhd.u32(video ? movie.width * 65536 : 0).u32(video ? movie.height * 65536 : 0);
173
+ const mdhd = new ByteWriter().u32(0).u32(0).u32(track.timescale).u32(track.duration).u16(0x55c4).u16(0); // language "und"
174
+ const hdlr = new ByteWriter().u32(0).ascii(video ? 'vide' : 'soun').zeros(12).bytes(utf8(video ? 'VideoHandler\0' : 'SoundHandler\0'));
175
+ const header = video ? fullBox('vmhd', 0, 1, new ByteWriter().zeros(8)) : fullBox('smhd', 0, 0, new ByteWriter().zeros(4));
176
+ const dinf = box('dinf', fullBox('dref', 0, 0, new ByteWriter().u32(1).finish(), fullBox('url ', 0, 1)));
177
+ return box('trak', fullBox('tkhd', 0, 3, tkhd), ...edits,
178
+ box('mdia', fullBox('mdhd', 0, 0, mdhd), fullBox('hdlr', 0, 0, hdlr),
179
+ box('minf', header, dinf, sampleTable(track, nextEntry))));
180
+ }
181
+
182
+ /** An MP4 file with `moov` before `mdat`. Samples are interleaved in half-second chunks. */
183
+ export function writeMp4(movie) {
184
+ const tracks = [mp4Track(movie.video, 'video', 1)];
185
+ if (movie.audio?.chunks.length) tracks.push(mp4Track(movie.audio, 'audio', 2));
186
+ const entries = tracks.map(track => track.kind === 'video'
187
+ ? avcSampleEntry(movie, movie.video.description)
188
+ : movie.audio.codec === 'aac' ? aacSampleEntry(movie.audio) : opusSampleEntry(movie.audio));
189
+ // Group each track's samples into chunks, then order chunks by start time.
190
+ const all = [];
191
+ for (const track of tracks) {
192
+ for (const sample of track.samples) {
193
+ const slot = Math.floor(sample.chunk.timestamp / INTERLEAVE_US);
194
+ let chunk = track.chunks.at(-1);
195
+ if (!chunk || chunk.slot !== slot) {
196
+ chunk = { slot, track, samples: [], time: sample.chunk.timestamp };
197
+ track.chunks.push(chunk);
198
+ all.push(chunk);
199
+ }
200
+ chunk.samples.push(sample);
201
+ }
202
+ }
203
+ all.sort((a, b) => a.time - b.time || a.track.id - b.track.id);
204
+ const ftyp = box('ftyp', new ByteWriter().ascii('isom').u32(0x200).ascii('isomiso2avc1mp41'));
205
+ const duration = Math.max(...tracks.map(track =>
206
+ Math.round((track.duration - Math.min(primingSamples(track), track.duration)) * MOVIE_TIMESCALE / track.timescale)));
207
+ const buildMoov = () => {
208
+ const mvhd = new ByteWriter().u32(0).u32(0).u32(MOVIE_TIMESCALE).u32(duration).u32(0x10000).u16(0x0100).zeros(10);
209
+ for (const value of MATRIX) mvhd.u32(value);
210
+ mvhd.zeros(24).u32(tracks.length + 1);
211
+ return box('moov', fullBox('mvhd', 0, 0, mvhd), ...tracks.map((track, i) => trakBox(track, movie, entries[i])));
212
+ };
213
+ // The chunk offsets live in `moov`, whose size does not depend on their values.
214
+ const moovSize = buildMoov().length;
215
+ const mdatSize = all.reduce((sum, chunk) => sum + chunk.samples.reduce((n, s) => n + s.chunk.data.length, 0), 0) + 8;
216
+ if (ftyp.length + moovSize + mdatSize > 2 ** 32 - 1) throw new Error('The video is larger than 4 GB: choose a shorter length or a smaller size');
217
+ let offset = ftyp.length + moovSize + 8;
218
+ for (const chunk of all) {
219
+ chunk.offset = offset;
220
+ for (const sample of chunk.samples) offset += sample.chunk.data.length;
221
+ }
222
+ const mdat = [new ByteWriter().u32(mdatSize).ascii('mdat').finish()];
223
+ for (const chunk of all) for (const sample of chunk.samples) mdat.push(sample.chunk.data);
224
+ return concat([ftyp, buildMoov(), ...mdat]);
225
+ }
226
+
227
+ // ---------------------------------------------------------------------------------------------
228
+ // WebM
229
+
230
+ function vintSize(value, width) {
231
+ width ??= value < 127 ? 1 : value < 16383 ? 2 : value < 2097151 ? 3 : value < 268435455 ? 4 : 8;
232
+ const out = new Uint8Array(width);
233
+ let rest = value;
234
+ for (let i = width - 1; i >= 0; i--) {
235
+ out[i] = rest % 256;
236
+ rest = Math.floor(rest / 256);
237
+ }
238
+ out[0] |= 1 << (8 - width);
239
+ return out;
240
+ }
241
+
242
+ function idBytes(id) {
243
+ const out = [];
244
+ for (let rest = id; rest > 0; rest = Math.floor(rest / 256)) out.unshift(rest % 256);
245
+ return Uint8Array.from(out);
246
+ }
247
+
248
+ function element(id, payload, sizeWidth) {
249
+ const body = payload instanceof Uint8Array ? payload : concat(payload);
250
+ return concat([idBytes(id), vintSize(body.length, sizeWidth), body]);
251
+ }
252
+ function uint(id, value, width) {
253
+ width ??= Math.max(1, Math.ceil(Math.log2(value + 1) / 8));
254
+ const out = new Uint8Array(width);
255
+ for (let i = width - 1, rest = value; i >= 0; i--, rest = Math.floor(rest / 256)) out[i] = rest % 256;
256
+ return element(id, out);
257
+ }
258
+ function float(id, value) {
259
+ const out = new Uint8Array(8);
260
+ new DataView(out.buffer).setFloat64(0, value);
261
+ return element(id, out);
262
+ }
263
+ const string = (id, text) => element(id, utf8(text));
264
+
265
+ const EBML = {
266
+ Header: 0x1a45dfa3, Version: 0x4286, ReadVersion: 0x42f7, MaxIDLength: 0x42f2, MaxSizeLength: 0x42f3,
267
+ DocType: 0x4282, DocTypeVersion: 0x4287, DocTypeReadVersion: 0x4285,
268
+ Segment: 0x18538067, SeekHead: 0x114d9b74, Seek: 0x4dbb, SeekID: 0x53ab, SeekPosition: 0x53ac,
269
+ Info: 0x1549a966, TimecodeScale: 0x2ad7b1, MuxingApp: 0x4d80, WritingApp: 0x5741, Duration: 0x4489,
270
+ Tracks: 0x1654ae6b, TrackEntry: 0xae, TrackNumber: 0xd7, TrackUID: 0x73c5, TrackType: 0x83, FlagLacing: 0x9c,
271
+ CodecID: 0x86, CodecPrivate: 0x63a2, CodecDelay: 0x56aa, SeekPreRoll: 0x56bb,
272
+ Video: 0xe0, PixelWidth: 0xb0, PixelHeight: 0xba, Audio: 0xe1, SamplingFrequency: 0xb5, Channels: 0x9f,
273
+ Cluster: 0x1f43b675, Timecode: 0xe7, SimpleBlock: 0xa3,
274
+ Cues: 0x1c53bb6b, CuePoint: 0xbb, CueTime: 0xb3, CueTrackPositions: 0xb7, CueTrack: 0xf7, CueClusterPosition: 0xf1,
275
+ };
276
+
277
+ /** A WebM file with a seek head, cues and one cluster per video key frame. Times are in ms. */
278
+ export function writeWebm(movie) {
279
+ const { video, audio } = movie;
280
+ const hasAudio = Boolean(audio?.chunks.length);
281
+ const end = Math.max(...[video, ...(hasAudio ? [audio] : [])].map(stream => {
282
+ const last = stream.chunks.at(-1);
283
+ return last ? last.timestamp + last.duration : 0;
284
+ }));
285
+ const info = element(EBML.Info, [uint(EBML.TimecodeScale, 1000000), string(EBML.MuxingApp, 'Swoof Studio'),
286
+ string(EBML.WritingApp, 'Swoof Studio'), float(EBML.Duration, end / 1000)]);
287
+ const videoTrack = [uint(EBML.TrackNumber, 1), uint(EBML.TrackUID, 1), uint(EBML.TrackType, 1), uint(EBML.FlagLacing, 0),
288
+ string(EBML.CodecID, video.codec === 'vp8' ? 'V_VP8' : 'V_VP9'), element(EBML.Video, [uint(EBML.PixelWidth, movie.width), uint(EBML.PixelHeight, movie.height)])];
289
+ if (video.description?.length) videoTrack.push(element(EBML.CodecPrivate, video.description));
290
+ const trackEntries = [element(EBML.TrackEntry, videoTrack)];
291
+ if (hasAudio) {
292
+ const head = opusHead(audio);
293
+ const preSkip = new DataView(head.buffer, head.byteOffset).getUint16(10, true);
294
+ trackEntries.push(element(EBML.TrackEntry, [uint(EBML.TrackNumber, 2), uint(EBML.TrackUID, 2), uint(EBML.TrackType, 2),
295
+ uint(EBML.FlagLacing, 0), string(EBML.CodecID, 'A_OPUS'), element(EBML.CodecPrivate, head),
296
+ uint(EBML.CodecDelay, Math.round(preSkip / 48000 * 1e9)), uint(EBML.SeekPreRoll, 80000000),
297
+ element(EBML.Audio, [float(EBML.SamplingFrequency, audio.sampleRate), uint(EBML.Channels, audio.channels)])]));
298
+ }
299
+ const tracks = element(EBML.Tracks, trackEntries);
300
+
301
+ // Blocks in time order. A video key frame starts a new cluster.
302
+ const blocks = [
303
+ ...video.chunks.map(chunk => ({ chunk, track: 1, video: true })),
304
+ ...(hasAudio ? audio.chunks.map(chunk => ({ chunk, track: 2, video: false })) : []),
305
+ ].sort((a, b) => a.chunk.timestamp - b.chunk.timestamp || a.track - b.track);
306
+ const clusters = [];
307
+ let current;
308
+ for (const block of blocks) {
309
+ const ms = Math.round(block.chunk.timestamp / 1000);
310
+ if (!current || (block.video && block.chunk.key) || ms - current.time > 32000) {
311
+ current = { time: ms, blocks: [], key: block.video && block.chunk.key };
312
+ clusters.push(current);
313
+ }
314
+ const header = new Uint8Array(4);
315
+ header[0] = 0x80 | block.track;
316
+ new DataView(header.buffer).setInt16(1, ms - current.time);
317
+ header[3] = block.chunk.key || !block.video ? 0x80 : 0;
318
+ current.blocks.push(element(EBML.SimpleBlock, [header, block.chunk.data]));
319
+ }
320
+ const clusterBytes = clusters.map(cluster => element(EBML.Cluster, [uint(EBML.Timecode, cluster.time), ...cluster.blocks]));
321
+
322
+ // The seek head uses fixed-width positions, so its size is known before the positions are.
323
+ const seekHead = positions => element(EBML.SeekHead, Object.entries(positions).map(([id, position]) =>
324
+ element(EBML.Seek, [element(EBML.SeekID, idBytes(Number(id))), uint(EBML.SeekPosition, position, 8)])));
325
+ const placeholder = { [EBML.Info]: 0, [EBML.Tracks]: 0, [EBML.Cues]: 0 };
326
+ const headSize = seekHead(placeholder).length;
327
+ let position = headSize + info.length + tracks.length;
328
+ const cuePoints = [];
329
+ clusters.forEach((cluster, i) => {
330
+ if (cluster.key) cuePoints.push(element(EBML.CuePoint, [uint(EBML.CueTime, cluster.time),
331
+ element(EBML.CueTrackPositions, [uint(EBML.CueTrack, 1), uint(EBML.CueClusterPosition, position, 8)])]));
332
+ position += clusterBytes[i].length;
333
+ });
334
+ const cues = element(EBML.Cues, cuePoints);
335
+ const head = seekHead({ [EBML.Info]: headSize, [EBML.Tracks]: headSize + info.length, [EBML.Cues]: position });
336
+ const header = element(EBML.Header, [uint(EBML.Version, 1), uint(EBML.ReadVersion, 1), uint(EBML.MaxIDLength, 4),
337
+ uint(EBML.MaxSizeLength, 8), string(EBML.DocType, 'webm'), uint(EBML.DocTypeVersion, 4), uint(EBML.DocTypeReadVersion, 2)]);
338
+ return concat([header, element(EBML.Segment, [head, info, tracks, ...clusterBytes, cues], 8)]);
339
+ }