hyperframes 0.8.211 → 0.8.212

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 (210) hide show
  1. package/dist/{add-WERDY37C.js → add-JSM7YBQX.js} +14 -13
  2. package/dist/{agentPromptGenerator-SEAPWYY5.js → agentPromptGenerator-NTPYCKOI.js} +5 -5
  3. package/dist/{animatedGifPrep-LC43PROA.js → animatedGifPrep-XTK7UWXF.js} +5 -5
  4. package/dist/api.js +17 -17
  5. package/dist/{asset-IVDQNYHP.js → asset-SMY2EGPH.js} +5 -4
  6. package/dist/{assetCataloger-PPE7M2WM.js → assetCataloger-CVPWY34W.js} +6 -6
  7. package/dist/{audio-IJ22GXO6.js → audio-Y4OYLTWN.js} +20 -19
  8. package/dist/{auth-FZMDHX2H.js → auth-MDEHZR7R.js} +4 -4
  9. package/dist/{autoUpdate-EO6SFALF.js → autoUpdate-3FL6EDPM.js} +4 -2
  10. package/dist/{backgroundChecks-YW5VIAYF.js → backgroundChecks-A6TG2BT3.js} +5 -3
  11. package/dist/backgroundChecksWorker.js +5 -3
  12. package/dist/{batchRender-OOXYNZOT.js → batchRender-K2PBRRTQ.js} +8 -7
  13. package/dist/{beats-X7GRQA4J.js → beats-RA6XK6J5.js} +13 -12
  14. package/dist/{benchmark-JGGBMRZO.js → benchmark-EHU5O4PP.js} +19 -17
  15. package/dist/{browser-FQ5JPTME.js → browser-7RUIZT2H.js} +12 -10
  16. package/dist/{bundleWithLocalizedFonts-XA73ZJ4S.js → bundleWithLocalizedFonts-O2U2FYY2.js} +2 -2
  17. package/dist/{capture-GUVCA5JQ.js → capture-77KDKKNK.js} +13 -12
  18. package/dist/{capture-KKVB3MKM.js → capture-JGYBORAG.js} +12 -9
  19. package/dist/{captureCompositionFrame-LNKWWCXE.js → captureCompositionFrame-DZ7EHPZV.js} +13 -12
  20. package/dist/{catalog-LKJEMEOC.js → catalog-CUP3SYAI.js} +18 -17
  21. package/dist/{catch-up-FA6KWX4S.js → catch-up-ZGUCWH5Q.js} +8 -7
  22. package/dist/{check-6GIDKL6S.js → check-ITGFVBT6.js} +41 -40
  23. package/dist/{checkAudio-H3AUFC4M.js → checkAudio-CTLPD6YT.js} +8 -8
  24. package/dist/{checkBrowser-YWWF63S6.js → checkBrowser-G2N4JI6N.js} +34 -33
  25. package/dist/{chunk-Q52ISCT4.js → chunk-25MKZTRT.js} +1 -1
  26. package/dist/{chunk-KSNIYQRB.js → chunk-26AQTUU4.js} +5 -7
  27. package/dist/{chunk-3LACB6HG.js → chunk-2YDIEZSF.js} +3 -3
  28. package/dist/{chunk-QVHC77IF.js → chunk-3JQ2YOKL.js} +2 -2
  29. package/dist/{chunk-FI7SSV73.js → chunk-3YBXKWAF.js} +1 -1
  30. package/dist/{chunk-5KOZRJR7.js → chunk-45JN2GIZ.js} +1 -1
  31. package/dist/{chunk-MMJAHBH2.js → chunk-5SKC4G26.js} +4 -1
  32. package/dist/{chunk-ZNSKOXFW.js → chunk-5TQ4AEPF.js} +3 -3
  33. package/dist/{chunk-J2JG4XGP.js → chunk-5ZBMHUY2.js} +4 -0
  34. package/dist/{chunk-KZBBY72Q.js → chunk-64XQS7AP.js} +1 -1
  35. package/dist/{chunk-ABBVDJMG.js → chunk-6SG3RRAQ.js} +2 -2
  36. package/dist/{chunk-JMD5HDPB.js → chunk-6ZLDIMPL.js} +2 -2
  37. package/dist/{chunk-CJ5QZRY7.js → chunk-7KBS6ZLB.js} +2 -2
  38. package/dist/{chunk-OOA6C4AG.js → chunk-7Q5TBUC2.js} +2 -2
  39. package/dist/{chunk-FBN5AQJL.js → chunk-7TWX4Y7I.js} +3 -3
  40. package/dist/{chunk-BGC5S3OZ.js → chunk-7W7ANGR4.js} +48 -35
  41. package/dist/{chunk-DJ3H6EW3.js → chunk-7ZAVTGGT.js} +10 -9
  42. package/dist/{chunk-3NIESDKN.js → chunk-A2WPZE2R.js} +1 -1
  43. package/dist/{chunk-CNU65QE2.js → chunk-AJAXP4HF.js} +9 -5
  44. package/dist/{chunk-2QAR7ZNY.js → chunk-BLVHVXRU.js} +2 -2
  45. package/dist/{chunk-472C35EW.js → chunk-BYRXSKIY.js} +1 -1
  46. package/dist/{chunk-5AKWJHRJ.js → chunk-CODPTVC2.js} +1 -1
  47. package/dist/{chunk-LALLQUSK.js → chunk-DP5LF7GF.js} +2 -0
  48. package/dist/{chunk-AIY2Y5UY.js → chunk-DS7ANFBV.js} +5 -5
  49. package/dist/{chunk-6J2G57BB.js → chunk-DVVTBVKA.js} +7 -7
  50. package/dist/{chunk-CGAUUUDL.js → chunk-DXPC7Z6L.js} +3 -3
  51. package/dist/{chunk-3R5MYOJN.js → chunk-EC77ZBCP.js} +2 -2
  52. package/dist/{chunk-VWG7OQKU.js → chunk-EQGKUPBJ.js} +4 -1
  53. package/dist/{chunk-CZCRSS3U.js → chunk-F5XADOGC.js} +1 -1
  54. package/dist/chunk-FJ646TIT.js +201 -0
  55. package/dist/{chunk-77KGX4A3.js → chunk-FKFGGAXN.js} +50 -8
  56. package/dist/{chunk-PICG2XRD.js → chunk-FW6CYA5D.js} +2 -2
  57. package/dist/{chunk-VUEWZXZG.js → chunk-G6HUXX3L.js} +1 -1
  58. package/dist/{chunk-5YHQBCWH.js → chunk-G6OKQMJI.js} +12 -2
  59. package/dist/{chunk-DPYI2HRJ.js → chunk-GQ724553.js} +5 -5
  60. package/dist/{chunk-SXJJTFV4.js → chunk-GVE6I5EL.js} +4 -4
  61. package/dist/{chunk-NEQIJUV2.js → chunk-HXZNCXQX.js} +1 -1
  62. package/dist/{chunk-LAR5VTCN.js → chunk-J7GPSY5N.js} +4 -4
  63. package/dist/{chunk-4JWKC3GH.js → chunk-JZNQQI5M.js} +5 -5
  64. package/dist/{chunk-IEVU4FXB.js → chunk-KZZWYIEB.js} +3 -3
  65. package/dist/{chunk-AHPGAESX.js → chunk-L72RQ45A.js} +1 -1
  66. package/dist/{chunk-4D46TX6Q.js → chunk-MJCIAZSK.js} +1 -1
  67. package/dist/{chunk-5LITFBMY.js → chunk-MX2GMAAW.js} +9 -9
  68. package/dist/{chunk-B2B4MN3R.js → chunk-N3J2MLXC.js} +2 -2
  69. package/dist/{chunk-JZVUSRZ5.js → chunk-N7XJHZ35.js} +1 -1
  70. package/dist/{chunk-RQNFW6YC.js → chunk-NGSENR4J.js} +8 -3
  71. package/dist/{chunk-VGKQFZCC.js → chunk-NXDKBFEO.js} +14 -14
  72. package/dist/{chunk-UI7X4L4M.js → chunk-OL5E4Y4L.js} +2074 -2060
  73. package/dist/{chunk-XNFDDVJS.js → chunk-ONMTNYGR.js} +4 -1
  74. package/dist/{chunk-PKWZG642.js → chunk-ORJY6Z6G.js} +3 -3
  75. package/dist/{chunk-YWPCMOX4.js → chunk-OSCWTA2O.js} +5 -5
  76. package/dist/{chunk-SJK64HHG.js → chunk-OWV36OJP.js} +5 -2
  77. package/dist/{chunk-DAXKGMJL.js → chunk-P2VGMOX7.js} +5 -5
  78. package/dist/{chunk-OE5EHGDG.js → chunk-PW7FCVHR.js} +1 -1
  79. package/dist/{chunk-K43XLAQV.js → chunk-Q55JNFDV.js} +3 -3
  80. package/dist/{chunk-VBC3DQFS.js → chunk-QUXWS5UG.js} +1 -1
  81. package/dist/{chunk-DMIFCIG6.js → chunk-R5B6GXQM.js} +1 -1
  82. package/dist/{chunk-5MCR5DA5.js → chunk-RDZKBIEB.js} +5 -5
  83. package/dist/{chunk-B4KGJHTE.js → chunk-RJILJ4OR.js} +2 -2
  84. package/dist/{chunk-6EN2LWOM.js → chunk-RQC4PHO3.js} +1 -1
  85. package/dist/{chunk-ORXLO64X.js → chunk-S2HWGG5O.js} +1 -1
  86. package/dist/chunk-SJGE5I5F.js +131 -0
  87. package/dist/{chunk-ZPXXWUQ3.js → chunk-SPDSRBIN.js} +30 -4
  88. package/dist/{chunk-WNDTMINP.js → chunk-SXTWQ7CH.js} +2 -2
  89. package/dist/{chunk-22OGII5H.js → chunk-T7KNW7PE.js} +1 -1
  90. package/dist/{chunk-2RQZQJHV.js → chunk-TPO32Z65.js} +1 -1
  91. package/dist/{chunk-66KMYUNO.js → chunk-UBUKKTNW.js} +2 -2
  92. package/dist/{chunk-T2L2GJ4C.js → chunk-UE4CXHMF.js} +7 -7
  93. package/dist/{chunk-K3LLHG6I.js → chunk-UULZKCBI.js} +1 -1
  94. package/dist/{chunk-DDRCX7P2.js → chunk-UXH6E5HC.js} +2 -2
  95. package/dist/{chunk-AQMGYRX6.js → chunk-V6OSE6VT.js} +1 -1
  96. package/dist/{chunk-67JTGRNM.js → chunk-VKD23SIO.js} +1 -1
  97. package/dist/{chunk-3JYKWNFR.js → chunk-VVDHSRKD.js} +1 -1
  98. package/dist/{chunk-KF6I5WA7.js → chunk-W2VJTKIW.js} +15 -18
  99. package/dist/{chunk-FIC3E7IM.js → chunk-W55BW7KA.js} +9 -9
  100. package/dist/{chunk-FWKZ3O52.js → chunk-W5OBRMZ6.js} +1 -1
  101. package/dist/{chunk-YPNBEBQ6.js → chunk-WVIH5BBZ.js} +25 -18
  102. package/dist/{chunk-Z2UZAY2Q.js → chunk-XEWMJWNW.js} +2 -2
  103. package/dist/{chunk-DWIMUPFK.js → chunk-XGXTZNES.js} +2 -2
  104. package/dist/{chunk-GSXA4YLV.js → chunk-Y3U7ECBH.js} +1 -1
  105. package/dist/{chunk-KDDO3UYI.js → chunk-YACECUHX.js} +3 -3
  106. package/dist/{chunk-3WL7WU6K.js → chunk-YVT5IU6J.js} +19 -20
  107. package/dist/{chunk-4EO7DNRJ.js → chunk-YX5ELTKV.js} +2 -2
  108. package/dist/{chunk-FVY2XRX4.js → chunk-ZCYSQ3NQ.js} +2 -2
  109. package/dist/{clean-SVEOBRPM.js → clean-FBZ7GHRY.js} +21 -20
  110. package/dist/cli.js +143 -77
  111. package/dist/{cloud-ADFJGIEH.js → cloud-VYSWJ7UO.js} +4 -4
  112. package/dist/{cloudrun-BNY7Q5RK.js → cloudrun-U6LI7KLV.js} +23 -20
  113. package/dist/{compare-QC3T22KV.js → compare-YR7BMEHJ.js} +44 -45
  114. package/dist/{compiler-4ITKK4XI.js → compiler-6YCAUK7Z.js} +2 -2
  115. package/dist/{component-CNZCB3RY.js → component-HVSM6FJV.js} +6 -5
  116. package/dist/{compositions-UO32IP6Z.js → compositions-QTFL2VNL.js} +13 -12
  117. package/dist/{delete-RWTOSI24.js → delete-2FHCQ72T.js} +13 -11
  118. package/dist/{deploy-OKWS53NP.js → deploy-6S45QWG6.js} +5 -5
  119. package/dist/{destroy-4RL5VOXQ.js → destroy-BQ5R7LUF.js} +3 -3
  120. package/dist/{dist-AEE3QTRB.js → dist-B4KLCLZ5.js} +2 -2
  121. package/dist/{docs-UMIA66EZ.js → docs-6EM6FDNI.js} +5 -4
  122. package/dist/{doctor-SIF72ESZ.js → doctor-4MRS6RED.js} +11 -9
  123. package/dist/{events-S3VUTFEG.js → events-4VBBY7PP.js} +5 -3
  124. package/dist/{events-34PIVLZQ.js → events-FN45HVPM.js} +6 -5
  125. package/dist/{feedback-VS4LRXHW.js → feedback-T67P2CDA.js} +20 -19
  126. package/dist/{ffmpeg-YVQOKNV6.js → ffmpeg-ED7ZK6XH.js} +5 -5
  127. package/dist/{figma-AF4JKDBA.js → figma-UXAWKPOY.js} +3 -3
  128. package/dist/fontLocalizeCli.js +9 -9
  129. package/dist/{get-UQGCS6Q4.js → get-EFH3PPJA.js} +8 -7
  130. package/dist/{gpuPolicy-Q4B3D6PW.js → gpuPolicy-ZADQMXQT.js} +5 -5
  131. package/dist/{grade-compare-G34673XC.js → grade-compare-425BFHSF.js} +46 -44
  132. package/dist/{heifImagePrep-XD4DGOUS.js → heifImagePrep-ZJM7N2XY.js} +6 -6
  133. package/dist/{help-3QSD26IC.js → help-23PPB2BD.js} +11 -7
  134. package/dist/{history-6DC24UCF.js → history-CHJV33M5.js} +15 -12
  135. package/dist/hyperframe.manifest.json +1 -1
  136. package/dist/hyperframe.runtime.iife.js +63 -63
  137. package/dist/hyperframes-player.global.js +1 -1
  138. package/dist/{info-6JUHWWJK.js → info-36YPISVA.js} +11 -10
  139. package/dist/{init-2DPX6U3J.js → init-U6EE2EIU.js} +37 -36
  140. package/dist/{inspect-Z55YUSXC.js → inspect-NI2RMUFR.js} +32 -31
  141. package/dist/{installer-XVKYJU7S.js → installer-K3HIZ5CF.js} +4 -4
  142. package/dist/{keyframes-YHF4AQIL.js → keyframes-I6T2IT6I.js} +10 -9
  143. package/dist/{lambda-JITTS37E.js → lambda-WL64Z2F3.js} +31 -29
  144. package/dist/{layout-V5NYJXIX.js → layout-R2YZ4N6P.js} +32 -31
  145. package/dist/{lint-V4WMO7YL.js → lint-IAAG6Z65.js} +17 -14
  146. package/dist/{list-W7UCIYKA.js → list-3O6743DJ.js} +11 -10
  147. package/dist/{live-LAHBXVK2.js → live-WWPFZQ74.js} +33 -7
  148. package/dist/{localPage-BLQFFIDF.js → localPage-L5FRBCNP.js} +5 -5
  149. package/dist/{login-IX3MOREU.js → login-27TRFTYB.js} +11 -11
  150. package/dist/{logout-46NLNY2K.js → logout-C6P6ERZ3.js} +5 -5
  151. package/dist/{manager-WJOWZNHM.js → manager-D6TE4ENP.js} +7 -7
  152. package/dist/{media-treatment-XBO6EXL4.js → media-treatment-E3YLZVXC.js} +43 -33
  153. package/dist/{media-use-3RFKY7XJ.js → media-use-ZRHFRO46.js} +1 -1
  154. package/dist/{models-P3NSHDQS.js → models-2Q3TGNH5.js} +26 -19
  155. package/dist/{motionShot-D4QMLTQP.js → motionShot-XYW2HMVI.js} +16 -15
  156. package/dist/{normalize-audio-Q4VUR3QJ.js → normalize-audio-D5WNUNDM.js} +30 -19
  157. package/dist/{open-LGKX534P.js → open-3KO7UUPC.js} +17 -16
  158. package/dist/{parakeetRunner-FAOQMPS6.js → parakeetRunner-WX6L6MW5.js} +11 -11
  159. package/dist/{pipeline-2YONKZYC.js → pipeline-WYIO4KGN.js} +10 -10
  160. package/dist/{play-PJOUIY55.js → play-ZM3ZUJSZ.js} +31 -33
  161. package/dist/{policies-UPNRQ7IW.js → policies-J5BWAZHM.js} +11 -10
  162. package/dist/{preflight-3PPM7QBU.js → preflight-7OMCIXNM.js} +6 -6
  163. package/dist/{present-323D6OE2.js → present-E2PLH2GJ.js} +27 -29
  164. package/dist/{preview-E42QP2KX.js → preview-TVRM75FN.js} +24 -23
  165. package/dist/{producer-MTMNLJSC.js → producer-M5F6KZEF.js} +1 -1
  166. package/dist/{progress-LMQ2DXM4.js → progress-X3QFO3FE.js} +4 -4
  167. package/dist/{projectConfig-5QRVB5KY.js → projectConfig-VFKGY3XE.js} +6 -6
  168. package/dist/{prompts-P3IT5H36.js → prompts-VAO7RDKX.js} +2 -2
  169. package/dist/{publication-AUZLFOG5.js → publication-AF33R7LF.js} +2 -2
  170. package/dist/{publish-H5P7UHRV.js → publish-Z7HGDQ5R.js} +17 -17
  171. package/dist/{refresh-4XRQS3N6.js → refresh-IYRGLHG5.js} +5 -5
  172. package/dist/{remove-background-T2RV476S.js → remove-background-PN3KCBT4.js} +21 -17
  173. package/dist/{render-4XEB3XWI.js → render-I3HBIJX3.js} +59 -57
  174. package/dist/{render-GJH7446R.js → render-IZNPEXMU.js} +11 -10
  175. package/dist/{render-3FRGIWES.js → render-SEODWRRR.js} +27 -26
  176. package/dist/{render-batch-77X5453X.js → render-batch-MQSORY55.js} +12 -11
  177. package/dist/{resolver-DIUNK525.js → resolver-HXE4F2G4.js} +4 -4
  178. package/dist/{sam-FHJ7IL7T.js → sam-QA7JT7IM.js} +2 -1
  179. package/dist/{sherpa-SUS3YSEP.js → sherpa-NPT6S3RP.js} +10 -10
  180. package/dist/{sites-V42IFVTK.js → sites-MTLVMYJ6.js} +2 -2
  181. package/dist/{skills-YCGSIOCE.js → skills-P3BI55YP.js} +17 -13
  182. package/dist/{skillsUpdateCheck-VCQIZGOL.js → skillsUpdateCheck-43Q4ZHWN.js} +5 -3
  183. package/dist/{snapshot-H6R5PWNS.js → snapshot-YLT64YQS.js} +71 -53
  184. package/dist/{src-ED5VCIRC.js → src-7S7K4QUN.js} +8 -8
  185. package/dist/{src-HHDLJV4L.js → src-OHJ7USRX.js} +6 -4
  186. package/dist/{state-D5SYQFCB.js → state-6QHNNHDA.js} +2 -2
  187. package/dist/{staticProjectServer-VY7QG5XH.js → staticProjectServer-RP3MW2EW.js} +17 -17
  188. package/dist/{status-GEZNVPII.js → status-SLILCDBZ.js} +12 -7
  189. package/dist/studio/assets/{hyperframes-player-CzrqgMUX.js → hyperframes-player-DHfuW7Lt.js} +1 -1
  190. package/dist/studio/assets/{index-k4nVfS2D.js → index-CWgIsKzV.js} +4 -4
  191. package/dist/studio/assets/{index-B3SPHPi1.js → index-CkjUY33q.js} +1 -1
  192. package/dist/studio/index.html +1 -1
  193. package/dist/{studio-api-TR5RPX57.js → studio-api-BZPZCJL6.js} +9 -9
  194. package/dist/{studioServer-4SZLLQOV.js → studioServer-QLRIXNYM.js} +50 -49
  195. package/dist/{synthesize-QALK5SQR.js → synthesize-FQML2LN2.js} +2 -2
  196. package/dist/{telemetry-KGY7G3UR.js → telemetry-NTO4FJFN.js} +5 -4
  197. package/dist/{telemetry-7HUKOQ6X.js → telemetry-QOBPRUWF.js} +6 -5
  198. package/dist/{timeline-CGIKWCQI.js → timeline-OLQFVWVU.js} +30 -26
  199. package/dist/{tokens-AZALDJEK.js → tokens-BAHLVGEC.js} +5 -4
  200. package/dist/{transcribe-CTF5EIXJ.js → transcribe-3NHUWW4J.js} +27 -24
  201. package/dist/{transcribe-V6K5547L.js → transcribe-HR6BFDUR.js} +9 -9
  202. package/dist/{tts-C2HBLFKK.js → tts-K5HRN6NQ.js} +17 -13
  203. package/dist/{updateCheck-5I563YLB.js → updateCheck-BGHPCA7J.js} +4 -2
  204. package/dist/{upgrade-GRPVQE7Z.js → upgrade-NFI6JOME.js} +7 -6
  205. package/dist/{urlDownloader-EP6Q4WES.js → urlDownloader-P35K74RS.js} +4 -4
  206. package/dist/{validate-TVCDSQS3.js → validate-Q57ZCI4Q.js} +26 -25
  207. package/dist/{video-CFEIRKAE.js → video-OO2M2AKD.js} +9 -9
  208. package/dist/warmCheck.js +43 -42
  209. package/package.json +1 -1
  210. package/dist/chunk-WQ6ZXHFQ.js +0 -133
@@ -40,7 +40,7 @@ import {
40
40
  renderFrameIdForRenderId,
41
41
  resolveAuthoredTimingWindow,
42
42
  toFps
43
- } from "./chunk-472C35EW.js";
43
+ } from "./chunk-BYRXSKIY.js";
44
44
  import {
45
45
  AUDIO_GROUP_RENDER_ID_ATTR,
46
46
  AUTHORED_SOURCE_BEGIN,
@@ -83,7 +83,7 @@ import {
83
83
  sourceTimeAt,
84
84
  timeAtSourceTime,
85
85
  volumeSegmentSampleCount
86
- } from "./chunk-FWKZ3O52.js";
86
+ } from "./chunk-W5OBRMZ6.js";
87
87
  import {
88
88
  redactTelemetryString,
89
89
  redactUrlQueryStrings
@@ -677,7 +677,14 @@ ${lines}`].filter(Boolean).join("\n")
677
677
  }
678
678
  }
679
679
  async function explainChromeLaunchFailure(error, executablePath, args, signal) {
680
- if (!executablePath || !(error instanceof Error)) return error;
680
+ if (!(error instanceof Error)) return error;
681
+ const { code, errno, syscall } = error;
682
+ if (code === "UNKNOWN" && syscall === "spawn")
683
+ return new Error(
684
+ `Windows refused to start the browser${executablePath ? ` at ${executablePath}` : ""} (error ${errno ?? "unknown"}, spawn UNKNOWN). Security software may be blocking it, or the computer may be out of memory. Close other apps and retry; if it persists, run \`hyperframes browser ensure --force\` to download it again.`,
685
+ { cause: error }
686
+ );
687
+ if (!executablePath) return error;
681
688
  const diagnosis = await diagnoseChromeStartup(executablePath, args ?? [], { signal });
682
689
  return new Error(`${error.message}
683
690
  ${diagnosis}`, { cause: error });
@@ -1901,2187 +1908,2192 @@ identically under Docker. Consider:
1901
1908
  `;
1902
1909
  }
1903
1910
 
1904
- // ../engine/src/services/frameCapture.ts
1905
- import { existsSync as existsSync3, mkdirSync, writeFileSync } from "fs";
1906
- import { join as join4 } from "path";
1907
-
1908
- // ../engine/src/services/renderFrameVideoHold.ts
1909
- function holdRenderFrameVideos(ids, renderIdAttr) {
1910
- const held = new Set(ids);
1911
- window.__HF_RENDER_FRAME_VIDEO_IDS = ids;
1912
- const hold = (el) => {
1913
- if (el instanceof HTMLVideoElement && held.has(el.getAttribute(renderIdAttr) || el.id))
1914
- el.preload = "none";
1915
- };
1916
- new MutationObserver((records) => {
1917
- for (const record2 of records)
1918
- for (const node of record2.addedNodes) {
1919
- if (node.nodeType !== 1) continue;
1920
- hold(node);
1921
- for (const video of node.querySelectorAll("video")) hold(video);
1922
- }
1923
- }).observe(document, { childList: true, subtree: true });
1924
- }
1925
-
1926
- // ../engine/src/services/drawElementCaptureError.ts
1927
- var DrawElementCaptureError = class extends Error {
1928
- frameIndex;
1929
- constructor(frameIndex, reason, cause) {
1930
- super(
1931
- `drawElement capture failed at frame ${frameIndex}: ${reason}; fresh screenshot capture required`,
1932
- { cause }
1933
- );
1934
- this.name = "DrawElementCaptureError";
1935
- Object.defineProperty(this, "deCaptureFailure", { value: true, enumerable: true });
1936
- this.frameIndex = frameIndex;
1937
- }
1938
- };
1939
- function markRejectionHandled(promise) {
1940
- promise.catch(() => {
1941
- });
1911
+ // ../engine/src/services/drawElementService.ts
1912
+ var DE_CANVAS_NOT_INITIALIZED_CODE = "HF_DE_CANVAS_NOT_INITIALIZED";
1913
+ function resolveDrawElementCaptureMode(isSwiftShader, transparent) {
1914
+ void transparent;
1915
+ if (isSwiftShader) return "screenshot";
1916
+ return "drawelement";
1942
1917
  }
1943
- function asDrawElementCaptureFailure(frameIndex, encodeResult) {
1944
- const wrapped = encodeResult.catch((cause) => {
1945
- if (isDrawElementCaptureError(cause)) throw cause;
1946
- const reason = cause instanceof Error ? cause.message : String(cause);
1947
- throw new DrawElementCaptureError(frameIndex, reason, cause);
1948
- });
1949
- markRejectionHandled(wrapped);
1950
- return wrapped;
1918
+ function instrumentAcceleratedCanvases() {
1919
+ const w = window;
1920
+ w.__hf_accel_canvases = [];
1921
+ w.__hf_canvas_2d = [];
1922
+ const orig = HTMLCanvasElement.prototype.getContext;
1923
+ HTMLCanvasElement.prototype.getContext = function(type, attrs) {
1924
+ const isAccel = type === "webgl" || type === "webgl2" || type === "experimental-webgl" || type === "webgpu";
1925
+ const ctx = orig.call(this, type, attrs);
1926
+ if (ctx && isAccel) {
1927
+ const list = w.__hf_accel_canvases ?? [];
1928
+ if (!list.includes(this)) list.push(this);
1929
+ w.__hf_accel_canvases = list;
1930
+ }
1931
+ if (ctx && type === "2d") {
1932
+ const list2d = w.__hf_canvas_2d ?? [];
1933
+ if (!list2d.includes(this)) list2d.push(this);
1934
+ w.__hf_canvas_2d = list2d;
1935
+ }
1936
+ return ctx;
1937
+ };
1951
1938
  }
1952
- function isDrawElementCaptureError(error) {
1953
- let current = error;
1954
- for (let depth = 0; depth < 5 && typeof current === "object" && current !== null; depth++) {
1955
- if ("deCaptureFailure" in current && current.deCaptureFailure === true) return true;
1956
- current = "cause" in current ? current.cause : void 0;
1957
- }
1958
- return false;
1939
+ function forcePreservedDrawingBuffer() {
1940
+ const orig = HTMLCanvasElement.prototype.getContext;
1941
+ HTMLCanvasElement.prototype.getContext = function(type, attrs) {
1942
+ const isGl = type === "webgl" || type === "webgl2" || type === "experimental-webgl";
1943
+ return orig.call(this, type, isGl ? { ...attrs, preserveDrawingBuffer: true } : attrs);
1944
+ };
1959
1945
  }
1960
-
1961
- // ../engine/src/utils/alphaBlit.ts
1962
- import { deflateSync, inflateSync } from "zlib";
1963
-
1964
- // ../engine/src/utils/crc32.ts
1965
- import * as zlib from "zlib";
1966
- var nativeCrc32 = typeof zlib.crc32 === "function" ? zlib.crc32 : void 0;
1967
- function crc32Fallback(data, seed) {
1968
- let crc = seed ^ 4294967295;
1969
- for (let i = 0; i < data.length; i++) {
1970
- crc ^= data[i] ?? 0;
1971
- for (let bit = 0; bit < 8; bit++) {
1972
- const mask = -(crc & 1);
1973
- crc = crc >>> 1 ^ 3988292384 & mask;
1974
- }
1975
- }
1976
- return (crc ^ 4294967295) >>> 0;
1946
+ function classifyGpuRenderer(renderer) {
1947
+ if (!renderer) return void 0;
1948
+ const r = renderer.toLowerCase();
1949
+ const backend = r.includes("swiftshader") ? "swiftshader" : r.includes("metal") ? "metal" : r.includes("direct3d11") || r.includes("d3d11") ? "d3d11" : r.includes("direct3d9") || r.includes("d3d9") ? "d3d9" : r.includes("vulkan") ? "vulkan" : r.includes("opengl") || r.includes("angle") ? "opengl" : "other";
1950
+ const vendor = r.includes("apple") ? "apple" : r.includes("nvidia") ? "nvidia" : r.includes("amd") || r.includes("radeon") ? "amd" : r.includes("intel") ? "intel" : r.includes("microsoft") ? "microsoft" : "other";
1951
+ return `${backend}/${vendor}`;
1977
1952
  }
1978
- function chunkCrc32(chunkType, chunkData) {
1979
- const typeBytes = Buffer.from(chunkType, "ascii");
1980
- if (nativeCrc32) return nativeCrc32(chunkData, nativeCrc32(typeBytes));
1981
- return crc32Fallback(chunkData, crc32Fallback(typeBytes, 0));
1953
+ async function detectGpuBackend(page) {
1954
+ return page.evaluate(() => {
1955
+ const canvas = document.createElement("canvas");
1956
+ const gl = canvas.getContext("webgl") || canvas.getContext("experimental-webgl");
1957
+ if (!gl) return { isSwiftShader: false, renderer: null };
1958
+ const ext = gl.getExtension("WEBGL_debug_renderer_info");
1959
+ if (!ext) return { isSwiftShader: false, renderer: null };
1960
+ const renderer = gl.getParameter(ext.UNMASKED_RENDERER_WEBGL);
1961
+ return { isSwiftShader: renderer.toLowerCase().includes("swiftshader"), renderer };
1962
+ });
1982
1963
  }
1983
-
1984
- // ../engine/src/utils/alphaBlit.ts
1985
- function paeth(a, b, c) {
1986
- const p = a + b - c;
1987
- const pa = Math.abs(p - a);
1988
- const pb = Math.abs(p - b);
1989
- const pc = Math.abs(p - c);
1990
- if (pa <= pb && pa <= pc) return a;
1991
- if (pb <= pc) return b;
1992
- return c;
1964
+ async function injectDrawElementCanvas(page, width, height) {
1965
+ await page.evaluate(
1966
+ ({ w, h }) => {
1967
+ const root = document.querySelector("[data-composition-id]");
1968
+ if (!root || document.getElementById("__hf_de_canvas")) return;
1969
+ try {
1970
+ window.__HF_ROOT_BASE_OPACITY__ = parseFloat(getComputedStyle(root).opacity) || 1;
1971
+ } catch {
1972
+ }
1973
+ const parent = root.parentNode;
1974
+ if (!parent) throw new Error("drawElement: composition root has no parent node");
1975
+ const canvas = document.createElement("canvas");
1976
+ canvas.id = "__hf_de_canvas";
1977
+ canvas.setAttribute("layoutsubtree", "");
1978
+ canvas.width = w;
1979
+ canvas.height = h;
1980
+ canvas.style.cssText = "display:block;position:absolute;top:0;left:0;z-index:0";
1981
+ parent.insertBefore(canvas, root);
1982
+ canvas.appendChild(root);
1983
+ const tick = document.createElement("div");
1984
+ tick.id = "__hf_de_tick";
1985
+ tick.style.cssText = "position:absolute;left:0px;top:0;width:1px;height:1px;background:#000;opacity:0.01;pointer-events:none";
1986
+ canvas.appendChild(tick);
1987
+ window.__hfDeInvalidate = () => {
1988
+ tick.style.backgroundColor = tick.style.backgroundColor === "rgb(0, 0, 0)" ? "rgb(1, 1, 1)" : "rgb(0, 0, 0)";
1989
+ const cvp = canvas;
1990
+ if (typeof cvp.requestPaint === "function") {
1991
+ try {
1992
+ cvp.requestPaint();
1993
+ return true;
1994
+ } catch {
1995
+ }
1996
+ }
1997
+ return false;
1998
+ };
1999
+ },
2000
+ { w: width, h: height }
2001
+ );
1993
2002
  }
1994
- function decodePngRaw(buf, caller) {
1995
- if (buf[0] !== 137 || buf[1] !== 80 || buf[2] !== 78 || buf[3] !== 71 || buf[4] !== 13 || buf[5] !== 10 || buf[6] !== 26 || buf[7] !== 10) {
1996
- throw new Error(`${caller}: not a PNG file`);
1997
- }
1998
- let pos = 8;
1999
- let width = 0;
2000
- let height = 0;
2001
- let bitDepth = 0;
2002
- let colorType = 0;
2003
- let interlace = 0;
2004
- let sawIhdr = false;
2005
- const idatChunks = [];
2006
- while (pos + 12 <= buf.length) {
2007
- const chunkLen = buf.readUInt32BE(pos);
2008
- const chunkType = buf.toString("ascii", pos + 4, pos + 8);
2009
- const chunkData = buf.subarray(pos + 8, pos + 8 + chunkLen);
2010
- if (chunkType === "IHDR") {
2011
- width = chunkData.readUInt32BE(0);
2012
- height = chunkData.readUInt32BE(4);
2013
- bitDepth = chunkData[8] ?? 0;
2014
- colorType = chunkData[9] ?? 0;
2015
- interlace = chunkData[12] ?? 0;
2016
- sawIhdr = true;
2017
- } else if (chunkType === "IDAT") {
2018
- idatChunks.push(Buffer.from(chunkData));
2019
- } else if (chunkType === "IEND") {
2020
- break;
2021
- }
2022
- pos += 12 + chunkLen;
2023
- }
2024
- if (!sawIhdr) {
2025
- throw new Error(`${caller}: PNG missing IHDR chunk`);
2026
- }
2027
- if (colorType !== 2 && colorType !== 6) {
2028
- throw new Error(`${caller}: unsupported color type ${colorType} (expected 2=RGB or 6=RGBA)`);
2029
- }
2030
- if (interlace !== 0) {
2031
- throw new Error(
2032
- `${caller}: Adam7-interlaced PNGs are not supported (interlace method ${interlace})`
2033
- );
2034
- }
2035
- const channels = colorType === 6 ? 4 : 3;
2036
- const bpp = channels * (bitDepth / 8);
2037
- const stride = width * bpp;
2038
- const compressed = Buffer.concat(idatChunks);
2039
- const decompressed = inflateSync(compressed);
2040
- const rawPixels = Buffer.allocUnsafe(height * stride);
2041
- const prevRow = new Uint8Array(stride);
2042
- const currRow = new Uint8Array(stride);
2043
- let srcPos = 0;
2044
- for (let y = 0; y < height; y++) {
2045
- const filterType = decompressed[srcPos++] ?? 0;
2046
- const rawRow = decompressed.subarray(srcPos, srcPos + stride);
2047
- srcPos += stride;
2048
- switch (filterType) {
2049
- case 0:
2050
- currRow.set(rawRow);
2051
- break;
2052
- case 1:
2053
- for (let x = 0; x < stride; x++) {
2054
- currRow[x] = (rawRow[x] ?? 0) + (x >= bpp ? currRow[x - bpp] ?? 0 : 0) & 255;
2003
+ async function captureDrawElementFrame(page, width, height, format = "jpeg", quality = 80, syncToPaintEvent = true) {
2004
+ const dataUrl = await page.evaluate(
2005
+ ({
2006
+ w,
2007
+ h,
2008
+ fmt,
2009
+ q,
2010
+ sync
2011
+ }) => {
2012
+ const canvas = document.getElementById("__hf_de_canvas");
2013
+ const root = document.querySelector("[data-composition-id]");
2014
+ if (!root) {
2015
+ throw new Error("HF_DE_COMPOSITION_ROOT_MISSING: drawElement composition root not found");
2016
+ }
2017
+ if (!canvas) {
2018
+ throw new Error("HF_DE_CANVAS_NOT_INITIALIZED: drawElement canvas not initialized");
2019
+ }
2020
+ const ctx = canvas.getContext("2d");
2021
+ if (!ctx) throw new Error("drawElement: 2d context unavailable");
2022
+ const aw = window;
2023
+ let usedRequestPaint = false;
2024
+ aw.__hf3d?.update();
2025
+ const accel = (aw.__hf_accel_canvases ?? []).filter((c) => root.contains(c));
2026
+ if (!sync) {
2027
+ for (const c of (aw.__hf_canvas_2d ?? []).filter((c2) => root.contains(c2))) {
2028
+ if (!accel.includes(c)) accel.push(c);
2055
2029
  }
2056
- break;
2057
- case 2:
2058
- for (let x = 0; x < stride; x++) {
2059
- currRow[x] = (rawRow[x] ?? 0) + (prevRow[x] ?? 0) & 255;
2060
- }
2061
- break;
2062
- case 3:
2063
- for (let x = 0; x < stride; x++) {
2064
- const left = x >= bpp ? currRow[x - bpp] ?? 0 : 0;
2065
- const up = prevRow[x] ?? 0;
2066
- currRow[x] = (rawRow[x] ?? 0) + Math.floor((left + up) / 2) & 255;
2067
- }
2068
- break;
2069
- case 4:
2070
- for (let x = 0; x < stride; x++) {
2071
- const left = x >= bpp ? currRow[x - bpp] ?? 0 : 0;
2072
- const up = prevRow[x] ?? 0;
2073
- const upLeft = x >= bpp ? prevRow[x - bpp] ?? 0 : 0;
2074
- currRow[x] = (rawRow[x] ?? 0) + paeth(left, up, upLeft) & 255;
2030
+ accel.sort(
2031
+ (a, b) => a.compareDocumentPosition(b) & Node.DOCUMENT_POSITION_FOLLOWING ? -1 : 1
2032
+ );
2033
+ }
2034
+ for (const c of accel) {
2035
+ if (c.style.visibility !== "hidden") c.style.visibility = "hidden";
2036
+ }
2037
+ return new Promise((resolveCapture, rejectCapture) => {
2038
+ let settled = false;
2039
+ const drawAndEncode = () => {
2040
+ if (settled) return;
2041
+ settled = true;
2042
+ try {
2043
+ ctx.clearRect(0, 0, w, h);
2044
+ let bg = "";
2045
+ for (let el = root.parentElement; el; el = el.parentElement) {
2046
+ const c = getComputedStyle(el).backgroundColor;
2047
+ if (c && c !== "transparent" && c !== "rgba(0, 0, 0, 0)") {
2048
+ bg = c;
2049
+ break;
2050
+ }
2051
+ }
2052
+ if (!bg && fmt === "jpeg") bg = "#fff";
2053
+ if (bg) {
2054
+ ctx.fillStyle = bg;
2055
+ ctx.fillRect(0, 0, w, h);
2056
+ }
2057
+ const rootRect = root.getBoundingClientRect();
2058
+ for (const c of accel) {
2059
+ if (c.hasAttribute("data-hf-3d")) continue;
2060
+ const r = c.getBoundingClientRect();
2061
+ try {
2062
+ ctx.drawImage(c, r.left - rootRect.left, r.top - rootRect.top, r.width, r.height);
2063
+ } catch {
2064
+ }
2065
+ }
2066
+ let __appliedTransform = false;
2067
+ let __appliedAlpha = false;
2068
+ if (aw.__HF_ROOT_PROPS__) {
2069
+ try {
2070
+ const rcs = getComputedStyle(root);
2071
+ if (!usedRequestPaint) {
2072
+ const baseOp = aw.__HF_ROOT_BASE_OPACITY__ ?? 1;
2073
+ const curOp = parseFloat(rcs.opacity);
2074
+ if (baseOp > 1e-3 && Number.isFinite(curOp)) {
2075
+ const ratio = curOp / baseOp;
2076
+ if (Math.abs(ratio - 1) > 2e-3) {
2077
+ ctx.globalAlpha = Math.max(0, Math.min(1, ratio));
2078
+ __appliedAlpha = true;
2079
+ }
2080
+ }
2081
+ }
2082
+ const curTransform = rcs.transform;
2083
+ if (curTransform && curTransform !== "none") {
2084
+ const m = new DOMMatrix(curTransform);
2085
+ const origin = rcs.transformOrigin.split(" ");
2086
+ const ox = parseFloat(origin[0] ?? "0") || 0;
2087
+ const oy = parseFloat(origin[1] ?? "0") || 0;
2088
+ ctx.translate(ox, oy);
2089
+ ctx.transform(m.a, m.b, m.c, m.d, m.e, m.f);
2090
+ ctx.translate(-ox, -oy);
2091
+ __appliedTransform = true;
2092
+ }
2093
+ } catch {
2094
+ }
2095
+ }
2096
+ ctx.drawElementImage(root, 0, 0);
2097
+ if (__appliedAlpha) ctx.globalAlpha = 1;
2098
+ if (__appliedTransform) ctx.setTransform(1, 0, 0, 1, 0, 0);
2099
+ for (const c of accel) {
2100
+ if (!c.hasAttribute("data-hf-3d")) continue;
2101
+ const r = c.getBoundingClientRect();
2102
+ try {
2103
+ ctx.drawImage(c, r.left - rootRect.left, r.top - rootRect.top, r.width, r.height);
2104
+ } catch {
2105
+ }
2106
+ }
2107
+ } catch (e) {
2108
+ rejectCapture(e instanceof Error ? e : new Error(String(e)));
2109
+ return;
2110
+ }
2111
+ setTimeout(() => {
2112
+ try {
2113
+ resolveCapture(
2114
+ fmt === "png" ? canvas.toDataURL("image/png") : canvas.toDataURL("image/jpeg", q / 100)
2115
+ );
2116
+ } catch (e) {
2117
+ rejectCapture(e instanceof Error ? e : new Error(String(e)));
2118
+ }
2119
+ }, 0);
2120
+ };
2121
+ if (!sync) {
2122
+ drawAndEncode();
2123
+ return;
2075
2124
  }
2076
- break;
2077
- default:
2078
- throw new Error(`${caller}: unknown filter type ${filterType} at row ${y}`);
2125
+ const onPaint = () => {
2126
+ canvas.removeEventListener("paint", onPaint);
2127
+ drawAndEncode();
2128
+ };
2129
+ canvas.addEventListener("paint", onPaint);
2130
+ usedRequestPaint = aw.__hfDeInvalidate?.() === true;
2131
+ setTimeout(() => {
2132
+ canvas.removeEventListener("paint", onPaint);
2133
+ drawAndEncode();
2134
+ }, 250);
2135
+ });
2136
+ },
2137
+ { w: width, h: height, fmt: format, q: quality, sync: syncToPaintEvent }
2138
+ );
2139
+ const base64 = dataUrl.split(",")[1];
2140
+ if (!base64) throw new Error("drawElement: toDataURL returned no base64 payload");
2141
+ return Buffer.from(base64, "base64");
2142
+ }
2143
+ var workerEncodeStates = /* @__PURE__ */ new WeakMap();
2144
+ var workerEncodeBoundPages = /* @__PURE__ */ new WeakSet();
2145
+ async function initDrawElementWorkerEncode(page) {
2146
+ const existing = workerEncodeStates.get(page);
2147
+ if (existing) {
2148
+ for (const entry of existing.pending.values()) {
2149
+ entry.reject(new Error("drawElement worker encode: session reused, frame dropped"));
2079
2150
  }
2080
- rawPixels.set(currRow, y * stride);
2081
- prevRow.set(currRow);
2151
+ existing.pending.clear();
2152
+ existing.nextId = 0;
2153
+ } else {
2154
+ const state = { nextId: 0, pending: /* @__PURE__ */ new Map() };
2155
+ workerEncodeStates.set(page, state);
2082
2156
  }
2083
- return { width, height, bitDepth, colorType, rawPixels };
2084
- }
2085
- function decodePng(buf) {
2086
- const { width, height, bitDepth, colorType, rawPixels } = decodePngRaw(buf, "decodePng");
2087
- if (bitDepth !== 8) {
2088
- throw new Error(`decodePng: unsupported bit depth ${bitDepth} (expected 8)`);
2157
+ if (!workerEncodeBoundPages.has(page)) {
2158
+ workerEncodeBoundPages.add(page);
2159
+ await page.exposeFunction("__hfFrameReady", (id, b64, error) => {
2160
+ const s = workerEncodeStates.get(page);
2161
+ if (!s) return;
2162
+ if (id < 0) {
2163
+ for (const entry2 of s.pending.values()) {
2164
+ entry2.reject(new Error(`drawElement worker encode failed: ${error ?? "worker error"}`));
2165
+ }
2166
+ s.pending.clear();
2167
+ return;
2168
+ }
2169
+ const entry = s.pending.get(id);
2170
+ if (!entry) return;
2171
+ s.pending.delete(id);
2172
+ if (error) {
2173
+ entry.reject(new Error(`drawElement worker encode failed: ${error}`));
2174
+ } else if (!b64) {
2175
+ entry.reject(new Error(`drawElement worker encode returned empty frame (frame ${id})`));
2176
+ } else {
2177
+ entry.resolve(Buffer.from(b64, "base64"));
2178
+ }
2179
+ });
2089
2180
  }
2090
- const output = new Uint8Array(width * height * 4);
2091
- if (colorType === 6) {
2092
- output.set(rawPixels);
2093
- } else {
2094
- for (let i = 0; i < width * height; i++) {
2095
- output[i * 4 + 0] = rawPixels[i * 3 + 0] ?? 0;
2096
- output[i * 4 + 1] = rawPixels[i * 3 + 1] ?? 0;
2097
- output[i * 4 + 2] = rawPixels[i * 3 + 2] ?? 0;
2098
- output[i * 4 + 3] = 255;
2181
+ await page.evaluate(() => {
2182
+ const ew = window;
2183
+ if (ew.__hfEncWorker) {
2184
+ ew.__hfEncWorker.terminate();
2185
+ ew.__hfEncWorker = void 0;
2099
2186
  }
2100
- }
2101
- return { width, height, data: output };
2187
+ const workerSrc = `
2188
+ // Reuse one OffscreenCanvas across frames (dimensions are constant for a
2189
+ // render): a fresh canvas per frame churns ~w*h*4 bytes of backing store
2190
+ // every frame and pressures GC on the encode hot path.
2191
+ let oc = null, c = null;
2192
+ self.onmessage = async (e) => {
2193
+ const { bmp, id, w, h, q } = e.data;
2194
+ try {
2195
+ if (!oc || oc.width !== w || oc.height !== h) {
2196
+ oc = new OffscreenCanvas(w, h);
2197
+ c = oc.getContext('2d');
2198
+ }
2199
+ if (!c) throw new Error('OffscreenCanvas 2d context unavailable');
2200
+ c.drawImage(bmp, 0, 0);
2201
+ bmp.close();
2202
+ const blob = await oc.convertToBlob({ type: 'image/jpeg', quality: q });
2203
+ const ab = await blob.arrayBuffer();
2204
+ const u = new Uint8Array(ab);
2205
+ let s = ''; const CH = 0x8000;
2206
+ for (let i = 0; i < u.length; i += CH)
2207
+ s += String.fromCharCode.apply(null, u.subarray(i, i + CH));
2208
+ self.postMessage({ id, b64: btoa(s) });
2209
+ } catch (err) {
2210
+ try { if (bmp) bmp.close(); } catch (_) {}
2211
+ self.postMessage({ id, error: (err && err.message) || String(err) });
2212
+ }
2213
+ };
2214
+ `;
2215
+ const url = URL.createObjectURL(new Blob([workerSrc], { type: "text/javascript" }));
2216
+ const worker = new Worker(url);
2217
+ URL.revokeObjectURL(url);
2218
+ ew.__hfEncWorker = worker;
2219
+ worker.onmessage = (ev) => {
2220
+ const d = ev.data;
2221
+ ew.__hfFrameReady?.(d.id, d.b64 ?? "", d.error);
2222
+ };
2223
+ worker.onerror = (err) => {
2224
+ ew.__hfFrameReady?.(-1, "", err.message || "worker fatal error");
2225
+ };
2226
+ });
2102
2227
  }
2103
- var PNG_DEFLATE_LEVEL = 1;
2104
- function pngChunk(type, body) {
2105
- const header = Buffer.alloc(8);
2106
- header.writeUInt32BE(body.length, 0);
2107
- header.write(type, 4, "ascii");
2108
- const trailer = Buffer.alloc(4);
2109
- trailer.writeUInt32BE(chunkCrc32(type, body), 0);
2110
- return Buffer.concat([header, body, trailer]);
2228
+ function cleanupDrawElementWorkerEncode(page) {
2229
+ const state = workerEncodeStates.get(page);
2230
+ if (!state) return;
2231
+ for (const entry of state.pending.values()) {
2232
+ entry.reject(new Error("drawElement worker encode: session closed"));
2233
+ }
2234
+ state.pending.clear();
2235
+ workerEncodeStates.delete(page);
2111
2236
  }
2112
- function encodePng(width, height, rgba) {
2113
- const expected = width * height * 4;
2114
- if (rgba.length !== expected) {
2237
+ async function produceDrawElementFrame(page, width, height, quality = 80, syncToPaintEvent = true) {
2238
+ const state = workerEncodeStates.get(page);
2239
+ if (!state) {
2115
2240
  throw new Error(
2116
- `encodePng: expected ${expected} bytes for ${width}x${height}, got ${rgba.length}`
2241
+ "drawElement worker encode not initialized; call initDrawElementWorkerEncode first"
2117
2242
  );
2118
2243
  }
2119
- const stride = width * 4;
2120
- const filtered = Buffer.alloc((stride + 1) * height);
2121
- for (let y = 0; y < height; y++) {
2122
- filtered[y * (stride + 1)] = 0;
2123
- filtered.set(rgba.subarray(y * stride, (y + 1) * stride), y * (stride + 1) + 1);
2124
- }
2125
- const ihdr = Buffer.alloc(13);
2126
- ihdr.writeUInt32BE(width, 0);
2127
- ihdr.writeUInt32BE(height, 4);
2128
- ihdr[8] = 8;
2129
- ihdr[9] = 6;
2130
- return Buffer.concat([
2131
- Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]),
2132
- pngChunk("IHDR", ihdr),
2133
- pngChunk("IDAT", deflateSync(filtered, { level: PNG_DEFLATE_LEVEL })),
2134
- pngChunk("IEND", Buffer.alloc(0))
2135
- ]);
2136
- }
2137
- function decodePngToRgb48le(buf) {
2138
- const { width, height, bitDepth, colorType, rawPixels } = decodePngRaw(buf, "decodePngToRgb48le");
2139
- if (bitDepth !== 16) {
2140
- throw new Error(`decodePngToRgb48le: unsupported bit depth ${bitDepth} (expected 16)`);
2141
- }
2142
- const bpp = colorType === 6 ? 8 : 6;
2143
- const output = Buffer.allocUnsafe(width * height * 6);
2144
- for (let y = 0; y < height; y++) {
2145
- const dstBase = y * width * 6;
2146
- const srcRowBase = y * width * bpp;
2147
- for (let x = 0; x < width; x++) {
2148
- const srcBase = srcRowBase + x * bpp;
2149
- output[dstBase + x * 6 + 0] = rawPixels[srcBase + 1] ?? 0;
2150
- output[dstBase + x * 6 + 1] = rawPixels[srcBase + 0] ?? 0;
2151
- output[dstBase + x * 6 + 2] = rawPixels[srcBase + 3] ?? 0;
2152
- output[dstBase + x * 6 + 3] = rawPixels[srcBase + 2] ?? 0;
2153
- output[dstBase + x * 6 + 4] = rawPixels[srcBase + 5] ?? 0;
2154
- output[dstBase + x * 6 + 5] = rawPixels[srcBase + 4] ?? 0;
2155
- }
2156
- }
2157
- return { width, height, data: output };
2158
- }
2159
- function srgbByteToLinear(value) {
2160
- const v = value / 255;
2161
- return v <= 0.04045 ? v / 12.92 : Math.pow((v + 0.055) / 1.055, 2.4);
2162
- }
2163
- function buildSrgbToSignalLut(transfer) {
2164
- const lut = new Uint16Array(256);
2165
- const hlgA = 0.17883277;
2166
- const hlgB = 1 - 4 * hlgA;
2167
- const hlgC = 0.5 - hlgA * Math.log(4 * hlgA);
2168
- const hlgSdrWhite = (Math.exp((0.75 - hlgC) / hlgA) + hlgB) / 12;
2169
- const pqM1 = 0.1593017578125;
2170
- const pqM2 = 78.84375;
2171
- const pqC1 = 0.8359375;
2172
- const pqC2 = 18.8515625;
2173
- const pqC3 = 18.6875;
2174
- const pqMaxNits = 1e4;
2175
- const sdrNits = 203;
2176
- for (let i = 0; i < 256; i++) {
2177
- if (transfer === "srgb") {
2178
- lut[i] = i * 257;
2179
- continue;
2180
- }
2181
- const linear = srgbByteToLinear(i);
2182
- let signal;
2183
- if (transfer === "hlg") {
2184
- const scene = linear * hlgSdrWhite;
2185
- signal = scene <= 1 / 12 ? Math.sqrt(3 * scene) : hlgA * Math.log(12 * scene - hlgB) + hlgC;
2186
- } else {
2187
- const Lp = Math.max(0, linear * sdrNits / pqMaxNits);
2188
- const Lm1 = Math.pow(Lp, pqM1);
2189
- signal = Math.pow((pqC1 + pqC2 * Lm1) / (1 + pqC3 * Lm1), pqM2);
2190
- }
2191
- lut[i] = Math.min(65535, Math.round(signal * 65535));
2192
- }
2193
- return lut;
2194
- }
2195
- var SRGB_TO_SRGB_16 = buildSrgbToSignalLut("srgb");
2196
- var SRGB_TO_HLG = buildSrgbToSignalLut("hlg");
2197
- var SRGB_TO_PQ = buildSrgbToSignalLut("pq");
2198
- function getSrgbToSignalLut(transfer) {
2199
- if (transfer === "pq") return SRGB_TO_PQ;
2200
- if (transfer === "hlg") return SRGB_TO_HLG;
2201
- return SRGB_TO_SRGB_16;
2202
- }
2203
- function blitRgba8OverRgb48le(domRgba, canvas, width, height, transfer = "hlg") {
2204
- const pixelCount = width * height;
2205
- const lut = getSrgbToSignalLut(transfer);
2206
- for (let i = 0; i < pixelCount; i++) {
2207
- const da = domRgba[i * 4 + 3] ?? 0;
2208
- if (da === 0) {
2209
- continue;
2210
- } else if (da === 255) {
2211
- const r16 = lut[domRgba[i * 4 + 0] ?? 0] ?? 0;
2212
- const g16 = lut[domRgba[i * 4 + 1] ?? 0] ?? 0;
2213
- const b16 = lut[domRgba[i * 4 + 2] ?? 0] ?? 0;
2214
- canvas.writeUInt16LE(r16, i * 6);
2215
- canvas.writeUInt16LE(g16, i * 6 + 2);
2216
- canvas.writeUInt16LE(b16, i * 6 + 4);
2217
- } else {
2218
- const alpha = da / 255;
2219
- const invAlpha = 1 - alpha;
2220
- const hdrR = (canvas[i * 6 + 0] ?? 0) | (canvas[i * 6 + 1] ?? 0) << 8;
2221
- const hdrG = (canvas[i * 6 + 2] ?? 0) | (canvas[i * 6 + 3] ?? 0) << 8;
2222
- const hdrB = (canvas[i * 6 + 4] ?? 0) | (canvas[i * 6 + 5] ?? 0) << 8;
2223
- const domR = lut[domRgba[i * 4 + 0] ?? 0] ?? 0;
2224
- const domG = lut[domRgba[i * 4 + 1] ?? 0] ?? 0;
2225
- const domB = lut[domRgba[i * 4 + 2] ?? 0] ?? 0;
2226
- canvas.writeUInt16LE(Math.round(domR * alpha + hdrR * invAlpha), i * 6);
2227
- canvas.writeUInt16LE(Math.round(domG * alpha + hdrG * invAlpha), i * 6 + 2);
2228
- canvas.writeUInt16LE(Math.round(domB * alpha + hdrB * invAlpha), i * 6 + 4);
2229
- }
2230
- }
2231
- }
2232
- function cornerAlpha(px, py, cx, cy, r) {
2233
- const dx = px - cx;
2234
- const dy = py - cy;
2235
- const dist = Math.sqrt(dx * dx + dy * dy);
2236
- if (dist > r + 0.5) return 0;
2237
- if (dist > r - 0.5) return r + 0.5 - dist;
2238
- return 1;
2239
- }
2240
- function roundedRectAlpha(px, py, w, h, radii) {
2241
- const [tl, tr, br, bl] = radii;
2242
- if (px < tl && py < tl) return cornerAlpha(px, py, tl, tl, tl);
2243
- if (px >= w - tr && py < tr) return cornerAlpha(px, py, w - tr, tr, tr);
2244
- if (px >= w - br && py >= h - br) return cornerAlpha(px, py, w - br, h - br, br);
2245
- if (px < bl && py >= h - bl) return cornerAlpha(px, py, bl, h - bl, bl);
2246
- return 1;
2247
- }
2248
- function blitRgb48leRegion(canvas, source, dx, dy, sw, sh, canvasWidth, canvasHeight, opacity, borderRadius) {
2249
- if (sw <= 0 || sh <= 0) return;
2250
- const op = opacity ?? 1;
2251
- if (op <= 0) return;
2252
- const x0 = Math.max(0, dx);
2253
- const y0 = Math.max(0, dy);
2254
- const x1 = Math.min(canvasWidth, dx + sw);
2255
- const y1 = Math.min(canvasHeight, dy + sh);
2256
- if (x0 >= x1 || y0 >= y1) return;
2257
- const clippedW = x1 - x0;
2258
- const srcOffsetX = x0 - dx;
2259
- const srcOffsetY = y0 - dy;
2260
- const hasMask = borderRadius !== void 0;
2261
- if (op >= 0.999 && !hasMask) {
2262
- for (let y = 0; y < y1 - y0; y++) {
2263
- const srcRowOff = ((srcOffsetY + y) * sw + srcOffsetX) * 6;
2264
- const dstRowOff = ((y0 + y) * canvasWidth + x0) * 6;
2265
- source.copy(canvas, dstRowOff, srcRowOff, srcRowOff + clippedW * 6);
2266
- }
2267
- } else if (!hasMask) {
2268
- const invOp = 1 - op;
2269
- for (let y = 0; y < y1 - y0; y++) {
2270
- let srcOff = ((srcOffsetY + y) * sw + srcOffsetX) * 6;
2271
- let dstOff = ((y0 + y) * canvasWidth + x0) * 6;
2272
- for (let x = 0; x < clippedW; x++) {
2273
- const sr = source[srcOff] | source[srcOff + 1] << 8;
2274
- const sg = source[srcOff + 2] | source[srcOff + 3] << 8;
2275
- const sb = source[srcOff + 4] | source[srcOff + 5] << 8;
2276
- const dr = canvas[dstOff] | canvas[dstOff + 1] << 8;
2277
- const dg = canvas[dstOff + 2] | canvas[dstOff + 3] << 8;
2278
- const db = canvas[dstOff + 4] | canvas[dstOff + 5] << 8;
2279
- const r = sr * op + dr * invOp + 0.5 | 0;
2280
- const g = sg * op + dg * invOp + 0.5 | 0;
2281
- const b = sb * op + db * invOp + 0.5 | 0;
2282
- canvas[dstOff] = r & 255;
2283
- canvas[dstOff + 1] = r >>> 8;
2284
- canvas[dstOff + 2] = g & 255;
2285
- canvas[dstOff + 3] = g >>> 8;
2286
- canvas[dstOff + 4] = b & 255;
2287
- canvas[dstOff + 5] = b >>> 8;
2288
- srcOff += 6;
2289
- dstOff += 6;
2244
+ const frameId = ++state.nextId;
2245
+ const encodeResult = new Promise((resolve2, reject) => {
2246
+ const timer = setTimeout(() => {
2247
+ if (state.pending.delete(frameId)) {
2248
+ reject(new Error(`drawElement worker encode timed out (frame ${frameId})`));
2290
2249
  }
2291
- }
2292
- } else {
2293
- for (let y = 0; y < y1 - y0; y++) {
2294
- for (let x = 0; x < clippedW; x++) {
2295
- let effectiveOp = op;
2296
- if (hasMask) {
2297
- const ma = roundedRectAlpha(srcOffsetX + x, srcOffsetY + y, sw, sh, borderRadius);
2298
- if (ma <= 0) continue;
2299
- effectiveOp *= ma;
2300
- }
2301
- const srcOff = ((srcOffsetY + y) * sw + srcOffsetX + x) * 6;
2302
- const dstOff = ((y0 + y) * canvasWidth + x0 + x) * 6;
2303
- if (effectiveOp >= 0.999) {
2304
- source.copy(canvas, dstOff, srcOff, srcOff + 6);
2305
- } else {
2306
- const invEff = 1 - effectiveOp;
2307
- const sr = source.readUInt16LE(srcOff);
2308
- const sg = source.readUInt16LE(srcOff + 2);
2309
- const sb = source.readUInt16LE(srcOff + 4);
2310
- const dr = canvas.readUInt16LE(dstOff);
2311
- const dg = canvas.readUInt16LE(dstOff + 2);
2312
- const db = canvas.readUInt16LE(dstOff + 4);
2313
- canvas.writeUInt16LE(Math.round(sr * effectiveOp + dr * invEff), dstOff);
2314
- canvas.writeUInt16LE(Math.round(sg * effectiveOp + dg * invEff), dstOff + 2);
2315
- canvas.writeUInt16LE(Math.round(sb * effectiveOp + db * invEff), dstOff + 4);
2250
+ }, 3e4);
2251
+ state.pending.set(frameId, {
2252
+ resolve: (b) => {
2253
+ clearTimeout(timer);
2254
+ resolve2(b);
2255
+ },
2256
+ reject: (e) => {
2257
+ clearTimeout(timer);
2258
+ reject(e);
2259
+ }
2260
+ });
2261
+ });
2262
+ void encodeResult.catch(() => {
2263
+ });
2264
+ await page.evaluate(
2265
+ ({ w, h, q, sync, fid }) => {
2266
+ const canvas = document.getElementById("__hf_de_canvas");
2267
+ const root = document.querySelector("[data-composition-id]");
2268
+ if (!root) {
2269
+ throw new Error("HF_DE_COMPOSITION_ROOT_MISSING: drawElement composition root not found");
2270
+ }
2271
+ if (!canvas) {
2272
+ throw new Error("HF_DE_CANVAS_NOT_INITIALIZED: drawElement canvas not initialized");
2273
+ }
2274
+ const ctx = canvas.getContext("2d");
2275
+ if (!ctx) throw new Error("drawElement: 2d context unavailable");
2276
+ const aw = window;
2277
+ aw.__hf3d?.update();
2278
+ const accel = (aw.__hf_accel_canvases ?? []).filter((c) => root.contains(c));
2279
+ if (!sync) {
2280
+ for (const c of (aw.__hf_canvas_2d ?? []).filter((c2) => root.contains(c2))) {
2281
+ if (!accel.includes(c)) accel.push(c);
2316
2282
  }
2283
+ accel.sort(
2284
+ (a, b) => a.compareDocumentPosition(b) & Node.DOCUMENT_POSITION_FOLLOWING ? -1 : 1
2285
+ );
2317
2286
  }
2318
- }
2319
- }
2320
- }
2321
- function blitRgb48leAffine(canvas, source, matrix, srcW, srcH, canvasW, canvasH, opacity, borderRadius) {
2322
- const a = matrix[0];
2323
- const b = matrix[1];
2324
- const c = matrix[2];
2325
- const d = matrix[3];
2326
- const tx = matrix[4];
2327
- const ty = matrix[5];
2328
- if (a === void 0 || b === void 0 || c === void 0 || d === void 0 || tx === void 0 || ty === void 0)
2329
- return;
2330
- const det = a * d - b * c;
2331
- if (Math.abs(det) < 1e-10) return;
2332
- const invA = d / det;
2333
- const invB = -b / det;
2334
- const invC = -c / det;
2335
- const invD = a / det;
2336
- const invTx = -(invA * tx + invC * ty);
2337
- const invTy = -(invB * tx + invD * ty);
2338
- const op = opacity ?? 1;
2339
- if (op <= 0) return;
2340
- const hasMask = borderRadius !== void 0;
2341
- const corners = [
2342
- [tx, ty],
2343
- [a * srcW + tx, b * srcW + ty],
2344
- [c * srcH + tx, d * srcH + ty],
2345
- [a * srcW + c * srcH + tx, b * srcW + d * srcH + ty]
2346
- ];
2347
- let minX = canvasW, maxX = 0, minY = canvasH, maxY = 0;
2348
- for (const corner of corners) {
2349
- const cx = corner[0] ?? 0;
2350
- const cy = corner[1] ?? 0;
2351
- if (cx < minX) minX = cx;
2352
- if (cx > maxX) maxX = cx;
2353
- if (cy < minY) minY = cy;
2354
- if (cy > maxY) maxY = cy;
2355
- }
2356
- const startX = Math.max(0, Math.floor(minX));
2357
- const endX = Math.min(canvasW, Math.ceil(maxX));
2358
- const startY = Math.max(0, Math.floor(minY));
2359
- const endY = Math.min(canvasH, Math.ceil(maxY));
2360
- for (let dy = startY; dy < endY; dy++) {
2361
- for (let dx = startX; dx < endX; dx++) {
2362
- const sx = invA * dx + invC * dy + invTx;
2363
- const sy = invB * dx + invD * dy + invTy;
2364
- if (sx < 0 || sy < 0 || sx >= srcW || sy >= srcH) continue;
2365
- let effectiveOp = op;
2366
- if (hasMask) {
2367
- const ma = roundedRectAlpha(sx, sy, srcW, srcH, borderRadius);
2368
- if (ma <= 0) continue;
2369
- effectiveOp *= ma;
2370
- }
2371
- const x0 = Math.floor(sx);
2372
- const y0 = Math.floor(sy);
2373
- const fx = sx - x0;
2374
- const fy = sy - y0;
2375
- const x1 = Math.min(x0 + 1, srcW - 1);
2376
- const y1 = Math.min(y0 + 1, srcH - 1);
2377
- const off00 = (y0 * srcW + x0) * 6;
2378
- const off10 = (y0 * srcW + x1) * 6;
2379
- const off01 = (y1 * srcW + x0) * 6;
2380
- const off11 = (y1 * srcW + x1) * 6;
2381
- const w00 = (1 - fx) * (1 - fy);
2382
- const w10 = fx * (1 - fy);
2383
- const w01 = (1 - fx) * fy;
2384
- const w11 = fx * fy;
2385
- const sr = source.readUInt16LE(off00) * w00 + source.readUInt16LE(off10) * w10 + source.readUInt16LE(off01) * w01 + source.readUInt16LE(off11) * w11;
2386
- const sg = source.readUInt16LE(off00 + 2) * w00 + source.readUInt16LE(off10 + 2) * w10 + source.readUInt16LE(off01 + 2) * w01 + source.readUInt16LE(off11 + 2) * w11;
2387
- const sb = source.readUInt16LE(off00 + 4) * w00 + source.readUInt16LE(off10 + 4) * w10 + source.readUInt16LE(off01 + 4) * w01 + source.readUInt16LE(off11 + 4) * w11;
2388
- const dstOff = (dy * canvasW + dx) * 6;
2389
- if (effectiveOp >= 0.999) {
2390
- canvas.writeUInt16LE(Math.round(sr), dstOff);
2391
- canvas.writeUInt16LE(Math.round(sg), dstOff + 2);
2392
- canvas.writeUInt16LE(Math.round(sb), dstOff + 4);
2393
- } else {
2394
- const invEff = 1 - effectiveOp;
2395
- const dr = canvas.readUInt16LE(dstOff);
2396
- const dg = canvas.readUInt16LE(dstOff + 2);
2397
- const db = canvas.readUInt16LE(dstOff + 4);
2398
- canvas.writeUInt16LE(Math.round(sr * effectiveOp + dr * invEff), dstOff);
2399
- canvas.writeUInt16LE(Math.round(sg * effectiveOp + dg * invEff), dstOff + 2);
2400
- canvas.writeUInt16LE(Math.round(sb * effectiveOp + db * invEff), dstOff + 4);
2287
+ for (const c of accel) {
2288
+ if (c.style.visibility !== "hidden") c.style.visibility = "hidden";
2401
2289
  }
2402
- }
2403
- }
2404
- }
2405
- function parseObjectPositionAxis(value, axis) {
2406
- const lower = value.trim().toLowerCase();
2407
- if (lower === "left" || lower === "top") return 0;
2408
- if (lower === "right" || lower === "bottom") return 1;
2409
- if (lower === "center" || lower === "") return 0.5;
2410
- if (lower.endsWith("%")) {
2411
- const pct = parseFloat(lower) / 100;
2412
- return Number.isFinite(pct) ? pct : 0.5;
2413
- }
2414
- if (axis === "x" || axis === "y") return 0.5;
2415
- return 0.5;
2416
- }
2417
- function parseObjectPosition(css) {
2418
- if (!css || !css.trim()) return { x: 0.5, y: 0.5 };
2419
- const tokens = css.trim().split(/\s+/);
2420
- if (tokens.length === 1) {
2421
- const single = tokens[0] ?? "";
2422
- const v = parseObjectPositionAxis(single, "x");
2423
- return { x: v, y: 0.5 };
2424
- }
2425
- return {
2426
- x: parseObjectPositionAxis(tokens[0] ?? "", "x"),
2427
- y: parseObjectPositionAxis(tokens[1] ?? "", "y")
2428
- };
2429
- }
2430
- function computeObjectFitRect(srcW, srcH, dstW, dstH, fit, pos) {
2431
- let renderedW = dstW;
2432
- let renderedH = dstH;
2433
- if (fit === "fill") {
2434
- return { dx: 0, dy: 0, dw: dstW, dh: dstH };
2435
- }
2436
- if (fit === "none") {
2437
- renderedW = srcW;
2438
- renderedH = srcH;
2439
- } else if (fit === "scale-down") {
2440
- const scale = Math.min(dstW / srcW, dstH / srcH, 1);
2441
- renderedW = srcW * scale;
2442
- renderedH = srcH * scale;
2443
- } else if (fit === "cover") {
2444
- const scale = Math.max(dstW / srcW, dstH / srcH);
2445
- renderedW = srcW * scale;
2446
- renderedH = srcH * scale;
2447
- } else {
2448
- const scale = Math.min(dstW / srcW, dstH / srcH);
2449
- renderedW = srcW * scale;
2450
- renderedH = srcH * scale;
2451
- }
2452
- const dx = (dstW - renderedW) * pos.x;
2453
- const dy = (dstH - renderedH) * pos.y;
2454
- return { dx, dy, dw: renderedW, dh: renderedH };
2455
- }
2456
- function resampleRgb48leObjectFit(source, srcW, srcH, dstW, dstH, fit = "fill", objectPosition) {
2457
- if (srcW <= 0 || srcH <= 0 || dstW <= 0 || dstH <= 0) {
2458
- return source;
2459
- }
2460
- if (fit === "fill" && srcW === dstW && srcH === dstH) {
2461
- return source;
2462
- }
2463
- const pos = parseObjectPosition(objectPosition);
2464
- const rect = computeObjectFitRect(srcW, srcH, dstW, dstH, fit, pos);
2465
- const dst = Buffer.alloc(dstW * dstH * 6);
2466
- const stride = dstW * 6;
2467
- const xMin = Math.max(0, Math.floor(rect.dx));
2468
- const yMin = Math.max(0, Math.floor(rect.dy));
2469
- const xMax = Math.min(dstW, Math.ceil(rect.dx + rect.dw));
2470
- const yMax = Math.min(dstH, Math.ceil(rect.dy + rect.dh));
2471
- if (rect.dw <= 0 || rect.dh <= 0) {
2472
- return dst;
2473
- }
2474
- const invScaleX = srcW / rect.dw;
2475
- const invScaleY = srcH / rect.dh;
2476
- for (let dy = yMin; dy < yMax; dy++) {
2477
- const rowOff = dy * stride;
2478
- const sy = (dy + 0.5 - rect.dy) * invScaleY - 0.5;
2479
- const syc = Math.max(0, Math.min(srcH - 1, sy));
2480
- const y0 = Math.floor(syc);
2481
- const y1 = Math.min(y0 + 1, srcH - 1);
2482
- const fy = syc - y0;
2483
- const ify = 1 - fy;
2484
- for (let dx = xMin; dx < xMax; dx++) {
2485
- const sx = (dx + 0.5 - rect.dx) * invScaleX - 0.5;
2486
- const sxc = Math.max(0, Math.min(srcW - 1, sx));
2487
- const x0 = Math.floor(sxc);
2488
- const x1 = Math.min(x0 + 1, srcW - 1);
2489
- const fx = sxc - x0;
2490
- const ifx = 1 - fx;
2491
- const off00 = (y0 * srcW + x0) * 6;
2492
- const off10 = (y0 * srcW + x1) * 6;
2493
- const off01 = (y1 * srcW + x0) * 6;
2494
- const off11 = (y1 * srcW + x1) * 6;
2495
- const w00 = ifx * ify;
2496
- const w10 = fx * ify;
2497
- const w01 = ifx * fy;
2498
- const w11 = fx * fy;
2499
- const r = source.readUInt16LE(off00) * w00 + source.readUInt16LE(off10) * w10 + source.readUInt16LE(off01) * w01 + source.readUInt16LE(off11) * w11;
2500
- const g = source.readUInt16LE(off00 + 2) * w00 + source.readUInt16LE(off10 + 2) * w10 + source.readUInt16LE(off01 + 2) * w01 + source.readUInt16LE(off11 + 2) * w11;
2501
- const b = source.readUInt16LE(off00 + 4) * w00 + source.readUInt16LE(off10 + 4) * w10 + source.readUInt16LE(off01 + 4) * w01 + source.readUInt16LE(off11 + 4) * w11;
2502
- const dstOff = rowOff + dx * 6;
2503
- dst.writeUInt16LE(Math.round(r), dstOff);
2504
- dst.writeUInt16LE(Math.round(g), dstOff + 2);
2505
- dst.writeUInt16LE(Math.round(b), dstOff + 4);
2506
- }
2507
- }
2508
- return dst;
2290
+ return new Promise((resolveCapture, rejectCapture) => {
2291
+ let settled = false;
2292
+ let usedRequestPaint = false;
2293
+ const drawAndKick = () => {
2294
+ if (settled) return;
2295
+ settled = true;
2296
+ try {
2297
+ ctx.clearRect(0, 0, w, h);
2298
+ let bg = "";
2299
+ for (let el = root.parentElement; el; el = el.parentElement) {
2300
+ const c = getComputedStyle(el).backgroundColor;
2301
+ if (c && c !== "transparent" && c !== "rgba(0, 0, 0, 0)") {
2302
+ bg = c;
2303
+ break;
2304
+ }
2305
+ }
2306
+ if (!bg) bg = "#fff";
2307
+ if (bg) {
2308
+ ctx.fillStyle = bg;
2309
+ ctx.fillRect(0, 0, w, h);
2310
+ }
2311
+ const rootRect = root.getBoundingClientRect();
2312
+ for (const c of accel) {
2313
+ if (c.hasAttribute("data-hf-3d")) continue;
2314
+ const r = c.getBoundingClientRect();
2315
+ try {
2316
+ ctx.drawImage(c, r.left - rootRect.left, r.top - rootRect.top, r.width, r.height);
2317
+ } catch {
2318
+ }
2319
+ }
2320
+ let __appliedTransform = false;
2321
+ let __appliedAlpha = false;
2322
+ if (aw.__HF_ROOT_PROPS__) {
2323
+ try {
2324
+ const rcs = getComputedStyle(root);
2325
+ if (!usedRequestPaint) {
2326
+ const baseOp = aw.__HF_ROOT_BASE_OPACITY__ ?? 1;
2327
+ const curOp = parseFloat(rcs.opacity);
2328
+ if (baseOp > 1e-3 && Number.isFinite(curOp)) {
2329
+ const ratio = curOp / baseOp;
2330
+ if (Math.abs(ratio - 1) > 2e-3) {
2331
+ ctx.globalAlpha = Math.max(0, Math.min(1, ratio));
2332
+ __appliedAlpha = true;
2333
+ }
2334
+ }
2335
+ }
2336
+ const curTransform = rcs.transform;
2337
+ if (curTransform && curTransform !== "none") {
2338
+ const m = new DOMMatrix(curTransform);
2339
+ const origin = rcs.transformOrigin.split(" ");
2340
+ const ox = parseFloat(origin[0] ?? "0") || 0;
2341
+ const oy = parseFloat(origin[1] ?? "0") || 0;
2342
+ ctx.translate(ox, oy);
2343
+ ctx.transform(m.a, m.b, m.c, m.d, m.e, m.f);
2344
+ ctx.translate(-ox, -oy);
2345
+ __appliedTransform = true;
2346
+ }
2347
+ } catch {
2348
+ }
2349
+ }
2350
+ ctx.drawElementImage(root, 0, 0);
2351
+ if (__appliedAlpha) ctx.globalAlpha = 1;
2352
+ if (__appliedTransform) ctx.setTransform(1, 0, 0, 1, 0, 0);
2353
+ for (const c of accel) {
2354
+ if (!c.hasAttribute("data-hf-3d")) continue;
2355
+ const r = c.getBoundingClientRect();
2356
+ try {
2357
+ ctx.drawImage(c, r.left - rootRect.left, r.top - rootRect.top, r.width, r.height);
2358
+ } catch {
2359
+ }
2360
+ }
2361
+ } catch (e) {
2362
+ rejectCapture(e instanceof Error ? e : new Error(String(e)));
2363
+ return;
2364
+ }
2365
+ createImageBitmap(canvas).then((bmp) => {
2366
+ const ew = window;
2367
+ if (!ew.__hfEncWorker) {
2368
+ bmp.close();
2369
+ rejectCapture(new Error("drawElement: encode worker not initialized"));
2370
+ return;
2371
+ }
2372
+ ew.__hfEncWorker.postMessage({ bmp, id: fid, w, h, q: q / 100 }, [bmp]);
2373
+ resolveCapture();
2374
+ }).catch((e) => {
2375
+ rejectCapture(e instanceof Error ? e : new Error(String(e)));
2376
+ });
2377
+ };
2378
+ if (!sync) {
2379
+ drawAndKick();
2380
+ return;
2381
+ }
2382
+ const onPaint = () => {
2383
+ canvas.removeEventListener("paint", onPaint);
2384
+ drawAndKick();
2385
+ };
2386
+ canvas.addEventListener("paint", onPaint);
2387
+ usedRequestPaint = aw.__hfDeInvalidate?.() === true;
2388
+ setTimeout(() => {
2389
+ canvas.removeEventListener("paint", onPaint);
2390
+ drawAndKick();
2391
+ }, 250);
2392
+ });
2393
+ },
2394
+ { w: width, h: height, q: quality, sync: syncToPaintEvent, fid: frameId }
2395
+ );
2396
+ return { encodeResult };
2509
2397
  }
2510
- function normalizeObjectFit(value) {
2511
- switch ((value ?? "").trim().toLowerCase()) {
2512
- case "cover":
2513
- return "cover";
2514
- case "contain":
2515
- return "contain";
2516
- case "none":
2517
- return "none";
2518
- case "scale-down":
2519
- return "scale-down";
2520
- default:
2521
- return "fill";
2398
+ async function produceDrawElementFrameBatch(page, times, width, height, quality = 80) {
2399
+ const state = workerEncodeStates.get(page);
2400
+ if (!state) {
2401
+ throw new Error(
2402
+ "drawElement worker encode not initialized; call initDrawElementWorkerEncode first"
2403
+ );
2522
2404
  }
2523
- }
2524
- function parseTransformMatrix(css) {
2525
- if (!css || css === "none") return null;
2526
- const match2d = css.match(/^matrix\(([^,]+),([^,]+),([^,]+),([^,]+),([^,]+),([^,)]+)\)$/);
2527
- if (match2d) {
2528
- const values = match2d.slice(1, 7).map(Number);
2529
- if (!values.every(Number.isFinite)) return null;
2530
- return values;
2405
+ const fids = [];
2406
+ const encodeResults = [];
2407
+ for (let i = 0; i < times.length; i++) {
2408
+ const frameId = ++state.nextId;
2409
+ fids.push(frameId);
2410
+ const p = new Promise((resolve2, reject) => {
2411
+ const timer = setTimeout(() => {
2412
+ if (state.pending.delete(frameId)) {
2413
+ reject(new Error(`drawElement worker encode timed out (frame ${frameId})`));
2414
+ }
2415
+ }, 3e4);
2416
+ state.pending.set(frameId, {
2417
+ resolve: (b) => {
2418
+ clearTimeout(timer);
2419
+ resolve2(b);
2420
+ },
2421
+ reject: (e) => {
2422
+ clearTimeout(timer);
2423
+ reject(e);
2424
+ }
2425
+ });
2426
+ });
2427
+ void p.catch(() => {
2428
+ });
2429
+ encodeResults.push(p);
2531
2430
  }
2532
- const match3d = css.match(/^matrix3d\(([^)]+)\)$/);
2533
- if (match3d) {
2534
- const raw = match3d[1];
2535
- if (!raw) return null;
2536
- const parts = raw.split(",").map((s) => Number(s.trim()));
2537
- if (parts.length !== 16 || !parts.every(Number.isFinite)) return null;
2538
- warnIfZSignificant(parts);
2539
- return [
2540
- parts[0],
2541
- parts[1],
2542
- parts[4],
2543
- parts[5],
2544
- parts[12],
2545
- parts[13]
2546
- ];
2431
+ const outcome = await page.evaluate(
2432
+ async ({
2433
+ frames,
2434
+ w,
2435
+ h,
2436
+ q
2437
+ }) => {
2438
+ const canvas = document.getElementById("__hf_de_canvas");
2439
+ const root = document.querySelector("[data-composition-id]");
2440
+ if (!root) {
2441
+ return {
2442
+ failedAt: 0,
2443
+ error: "HF_DE_COMPOSITION_ROOT_MISSING: drawElement composition root not found"
2444
+ };
2445
+ }
2446
+ if (!canvas) {
2447
+ return {
2448
+ failedAt: 0,
2449
+ error: "HF_DE_CANVAS_NOT_INITIALIZED: drawElement canvas not initialized"
2450
+ };
2451
+ }
2452
+ const ctx = canvas.getContext("2d");
2453
+ if (!ctx) return { failedAt: 0, error: "drawElement: 2d context unavailable" };
2454
+ const aw = window;
2455
+ let usedRequestPaint = false;
2456
+ const waitPaint = () => new Promise((res) => {
2457
+ let done = false;
2458
+ const settle = () => {
2459
+ if (done) return;
2460
+ done = true;
2461
+ canvas.removeEventListener("paint", settle);
2462
+ res();
2463
+ };
2464
+ canvas.addEventListener("paint", settle);
2465
+ usedRequestPaint = aw.__hfDeInvalidate?.() === true;
2466
+ setTimeout(settle, 250);
2467
+ });
2468
+ let prevBitmap = Promise.resolve();
2469
+ let prevBitmapIdx = -1;
2470
+ const errMsg = (e) => e instanceof Error ? e.message : String(e);
2471
+ for (let i = 0; i < frames.length; i++) {
2472
+ const frame = frames[i];
2473
+ if (!frame) return { failedAt: i, error: "batch frame missing" };
2474
+ const { t, fid } = frame;
2475
+ try {
2476
+ if (aw.__hf && typeof aw.__hf.seek === "function") aw.__hf.seek(t);
2477
+ await aw.__hfWaitForSeekCompletion?.();
2478
+ await aw.__hfDecodeDynamicCssBackgroundImages?.();
2479
+ aw.__hf3d?.update();
2480
+ const accel = (aw.__hf_accel_canvases ?? []).filter((c) => root.contains(c));
2481
+ for (const c of accel) {
2482
+ if (c.style.visibility !== "hidden") c.style.visibility = "hidden";
2483
+ }
2484
+ await waitPaint();
2485
+ try {
2486
+ await prevBitmap;
2487
+ } catch (e) {
2488
+ return { failedAt: prevBitmapIdx, error: errMsg(e) };
2489
+ }
2490
+ ctx.clearRect(0, 0, w, h);
2491
+ let bg = "";
2492
+ for (let el = root.parentElement; el; el = el.parentElement) {
2493
+ const c = getComputedStyle(el).backgroundColor;
2494
+ if (c && c !== "transparent" && c !== "rgba(0, 0, 0, 0)") {
2495
+ bg = c;
2496
+ break;
2497
+ }
2498
+ }
2499
+ ctx.fillStyle = bg || "#fff";
2500
+ ctx.fillRect(0, 0, w, h);
2501
+ const rootRect = root.getBoundingClientRect();
2502
+ for (const c of accel) {
2503
+ if (c.hasAttribute("data-hf-3d")) continue;
2504
+ const r = c.getBoundingClientRect();
2505
+ try {
2506
+ ctx.drawImage(c, r.left - rootRect.left, r.top - rootRect.top, r.width, r.height);
2507
+ } catch {
2508
+ }
2509
+ }
2510
+ let appliedTransform = false;
2511
+ let appliedAlpha = false;
2512
+ if (aw.__HF_ROOT_PROPS__) {
2513
+ try {
2514
+ const rcs = getComputedStyle(root);
2515
+ if (!usedRequestPaint) {
2516
+ const baseOp = aw.__HF_ROOT_BASE_OPACITY__ ?? 1;
2517
+ const curOp = parseFloat(rcs.opacity);
2518
+ if (baseOp > 1e-3 && Number.isFinite(curOp)) {
2519
+ const ratio = curOp / baseOp;
2520
+ if (Math.abs(ratio - 1) > 2e-3) {
2521
+ ctx.globalAlpha = Math.max(0, Math.min(1, ratio));
2522
+ appliedAlpha = true;
2523
+ }
2524
+ }
2525
+ }
2526
+ const curTransform = rcs.transform;
2527
+ if (curTransform && curTransform !== "none") {
2528
+ const m = new DOMMatrix(curTransform);
2529
+ const origin = rcs.transformOrigin.split(" ");
2530
+ const ox = parseFloat(origin[0] ?? "0") || 0;
2531
+ const oy = parseFloat(origin[1] ?? "0") || 0;
2532
+ ctx.translate(ox, oy);
2533
+ ctx.transform(m.a, m.b, m.c, m.d, m.e, m.f);
2534
+ ctx.translate(-ox, -oy);
2535
+ appliedTransform = true;
2536
+ }
2537
+ } catch {
2538
+ }
2539
+ }
2540
+ ctx.drawElementImage(root, 0, 0);
2541
+ if (appliedAlpha) ctx.globalAlpha = 1;
2542
+ if (appliedTransform) ctx.setTransform(1, 0, 0, 1, 0, 0);
2543
+ for (const c of accel) {
2544
+ if (!c.hasAttribute("data-hf-3d")) continue;
2545
+ const r = c.getBoundingClientRect();
2546
+ try {
2547
+ ctx.drawImage(c, r.left - rootRect.left, r.top - rootRect.top, r.width, r.height);
2548
+ } catch {
2549
+ }
2550
+ }
2551
+ prevBitmapIdx = i;
2552
+ prevBitmap = createImageBitmap(canvas).then((bmp) => {
2553
+ if (!aw.__hfEncWorker) {
2554
+ bmp.close();
2555
+ throw new Error("drawElement: encode worker not initialized");
2556
+ }
2557
+ aw.__hfEncWorker.postMessage({ bmp, id: fid, w, h, q: q / 100 }, [bmp]);
2558
+ });
2559
+ } catch (e) {
2560
+ try {
2561
+ await prevBitmap;
2562
+ } catch {
2563
+ }
2564
+ return { failedAt: i, error: errMsg(e) };
2565
+ }
2566
+ }
2567
+ try {
2568
+ await prevBitmap;
2569
+ } catch (e) {
2570
+ return { failedAt: prevBitmapIdx, error: errMsg(e) };
2571
+ }
2572
+ return { failedAt: null };
2573
+ },
2574
+ { frames: times.map((t, i) => ({ t, fid: fids[i] ?? 0 })), w: width, h: height, q: quality }
2575
+ );
2576
+ if (outcome.failedAt !== null) {
2577
+ for (let k = outcome.failedAt; k < fids.length; k++) {
2578
+ const fid = fids[k];
2579
+ if (fid === void 0) continue;
2580
+ const entry = state.pending.get(fid);
2581
+ if (entry) {
2582
+ state.pending.delete(fid);
2583
+ entry.reject(
2584
+ new Error(`drawElement batch produce failed at frame ${k}: ${outcome.error ?? "?"}`)
2585
+ );
2586
+ }
2587
+ }
2547
2588
  }
2548
- return null;
2589
+ return { encodeResults, failedAt: outcome.failedAt, error: outcome.error };
2549
2590
  }
2550
- var warnedZSignificant = false;
2551
- var Z_EPSILON = 1e-6;
2552
- function warnIfZSignificant(parts) {
2553
- if (warnedZSignificant) return;
2554
- const a3 = parts[8] ?? 0;
2555
- const b3 = parts[9] ?? 0;
2556
- const c1 = parts[2] ?? 0;
2557
- const c2 = parts[6] ?? 0;
2558
- const c3 = parts[10] ?? 1;
2559
- const d1 = parts[3] ?? 0;
2560
- const d2 = parts[7] ?? 0;
2561
- const d3 = parts[11] ?? 0;
2562
- const d4 = parts[15] ?? 1;
2563
- if (Math.abs(a3) > Z_EPSILON || Math.abs(b3) > Z_EPSILON || Math.abs(c1) > Z_EPSILON || Math.abs(c2) > Z_EPSILON || Math.abs(c3 - 1) > Z_EPSILON || Math.abs(d1) > Z_EPSILON || Math.abs(d2) > Z_EPSILON || Math.abs(d3) > Z_EPSILON || Math.abs(d4 - 1) > Z_EPSILON) {
2564
- warnedZSignificant = true;
2565
- console.warn(
2566
- `[alphaBlit] parseTransformMatrix received a matrix3d with non-trivial 3D components (a3=${a3}, b3=${b3}, c1=${c1}, c2=${c2}, c3=${c3}, d1=${d1}, d2=${d2}, d3=${d3}, d4=${d4}). The engine projects 3D transforms to 2D (m11, m12, m21, m22, m41, m42) and silently discards perspective and out-of-plane rotation. If your composition uses real 3D (rotateX/Y, perspective), the rendered output will not match the studio preview. Z translation (translateZ) is dropped by design and does not trigger this warning. This warning is emitted once per process.`
2591
+
2592
+ // ../engine/src/services/frameCapture.ts
2593
+ import { existsSync as existsSync3, mkdirSync, writeFileSync } from "fs";
2594
+ import { join as join4 } from "path";
2595
+
2596
+ // ../engine/src/services/renderFrameVideoHold.ts
2597
+ function holdRenderFrameVideos(ids, renderIdAttr) {
2598
+ const held = new Set(ids);
2599
+ window.__HF_RENDER_FRAME_VIDEO_IDS = ids;
2600
+ const hold = (el) => {
2601
+ if (el instanceof HTMLVideoElement && held.has(el.getAttribute(renderIdAttr) || el.id))
2602
+ el.preload = "none";
2603
+ };
2604
+ new MutationObserver((records) => {
2605
+ for (const record2 of records)
2606
+ for (const node of record2.addedNodes) {
2607
+ if (node.nodeType !== 1) continue;
2608
+ hold(node);
2609
+ for (const video of node.querySelectorAll("video")) hold(video);
2610
+ }
2611
+ }).observe(document, { childList: true, subtree: true });
2612
+ }
2613
+
2614
+ // ../engine/src/services/drawElementCaptureError.ts
2615
+ var DrawElementCaptureError = class extends Error {
2616
+ frameIndex;
2617
+ constructor(frameIndex, reason, cause) {
2618
+ super(
2619
+ `drawElement capture failed at frame ${frameIndex}: ${reason}; fresh screenshot capture required`,
2620
+ { cause }
2567
2621
  );
2622
+ this.name = "DrawElementCaptureError";
2623
+ Object.defineProperty(this, "deCaptureFailure", { value: true, enumerable: true });
2624
+ this.frameIndex = frameIndex;
2568
2625
  }
2626
+ };
2627
+ function markRejectionHandled(promise) {
2628
+ promise.catch(() => {
2629
+ });
2569
2630
  }
2570
-
2571
- // ../engine/src/services/motionBlur.ts
2572
- var MAX_SAMPLES_PER_FRAME = 64;
2573
- var DEFAULT_SAMPLES_PER_FRAME = 16;
2574
- var DEFAULT_SHUTTER_ANGLE = 180;
2575
- var DEFAULT_SHUTTER_PHASE = -90;
2576
- var SUB_FRAME_DIVISIONS = 4096;
2577
- function finiteOr(value, fallback) {
2578
- return Number.isFinite(value) ? value : fallback;
2631
+ function asDrawElementCaptureFailure(frameIndex, encodeResult) {
2632
+ const wrapped = encodeResult.catch((cause) => {
2633
+ if (isDrawElementCaptureError(cause)) throw cause;
2634
+ const reason = cause instanceof Error ? cause.message : String(cause);
2635
+ throw new DrawElementCaptureError(frameIndex, reason, cause);
2636
+ });
2637
+ markRejectionHandled(wrapped);
2638
+ return wrapped;
2579
2639
  }
2580
- function resolveMotionBlurPlan(options) {
2581
- if (!options) return null;
2582
- const fixedSamplesPerFrame = options.samplesPerFrame === void 0 ? null : Math.min(
2583
- MAX_SAMPLES_PER_FRAME,
2584
- Math.max(1, Math.round(finiteOr(options.samplesPerFrame, DEFAULT_SAMPLES_PER_FRAME)))
2585
- );
2586
- const shutterAngle = finiteOr(options.shutterAngle, DEFAULT_SHUTTER_ANGLE);
2587
- const shutterPhase = finiteOr(options.shutterPhase, DEFAULT_SHUTTER_PHASE);
2588
- const blend = options.blend === "linear" ? "linear" : "srgb";
2589
- return {
2590
- blend,
2591
- subFrameDivisions: SUB_FRAME_DIVISIONS,
2592
- windowStartFrames: shutterPhase / 360,
2593
- shutterFrames: shutterAngle / 360,
2594
- fixedSamplesPerFrame
2595
- };
2640
+ function isDrawElementCaptureError(error) {
2641
+ let current = error;
2642
+ for (let depth = 0; depth < 5 && typeof current === "object" && current !== null; depth++) {
2643
+ if ("deCaptureFailure" in current && current.deCaptureFailure === true) return true;
2644
+ current = "cause" in current ? current.cause : void 0;
2645
+ }
2646
+ return false;
2596
2647
  }
2597
- function sampleTickOffsets(plan, samplesPerFrame) {
2598
- const offsets = [];
2599
- for (let k = 0; k < samplesPerFrame; k++) {
2600
- const offsetFrames = plan.windowStartFrames + (k + 0.5) / samplesPerFrame * plan.shutterFrames;
2601
- offsets.push(Math.round(offsetFrames * plan.subFrameDivisions));
2648
+
2649
+ // ../engine/src/utils/alphaBlit.ts
2650
+ import { deflateSync, inflateSync } from "zlib";
2651
+
2652
+ // ../engine/src/utils/crc32.ts
2653
+ import * as zlib from "zlib";
2654
+ var nativeCrc32 = typeof zlib.crc32 === "function" ? zlib.crc32 : void 0;
2655
+ function crc32Fallback(data, seed) {
2656
+ let crc = seed ^ 4294967295;
2657
+ for (let i = 0; i < data.length; i++) {
2658
+ crc ^= data[i] ?? 0;
2659
+ for (let bit = 0; bit < 8; bit++) {
2660
+ const mask = -(crc & 1);
2661
+ crc = crc >>> 1 ^ 3988292384 & mask;
2662
+ }
2602
2663
  }
2603
- return offsets;
2664
+ return (crc ^ 4294967295) >>> 0;
2604
2665
  }
2605
- function motionBlurSampleTimes(plan, frameIndex, fps, samplesPerFrame) {
2606
- const grid = fps * plan.subFrameDivisions;
2607
- const frameTicks = frameIndex * plan.subFrameDivisions;
2608
- return sampleTickOffsets(plan, samplesPerFrame).map(
2609
- (offset) => Math.max(0, frameTicks + offset) / grid
2610
- );
2666
+ function chunkCrc32(chunkType, chunkData) {
2667
+ const typeBytes = Buffer.from(chunkType, "ascii");
2668
+ if (nativeCrc32) return nativeCrc32(chunkData, nativeCrc32(typeBytes));
2669
+ return crc32Fallback(chunkData, crc32Fallback(typeBytes, 0));
2611
2670
  }
2612
- function motionBlurProbeTimes(plan, frameIndex, fps) {
2613
- const grid = fps * plan.subFrameDivisions;
2614
- const frameTicks = frameIndex * plan.subFrameDivisions;
2615
- const startTick = Math.round(plan.windowStartFrames * plan.subFrameDivisions);
2616
- const endTick = Math.round(
2617
- (plan.windowStartFrames + plan.shutterFrames) * plan.subFrameDivisions
2618
- );
2619
- return {
2620
- windowStart: Math.max(0, frameTicks + startTick) / grid,
2621
- windowEnd: Math.max(0, frameTicks + endTick) / grid
2622
- };
2671
+
2672
+ // ../engine/src/utils/alphaBlit.ts
2673
+ function paeth(a, b, c) {
2674
+ const p = a + b - c;
2675
+ const pa = Math.abs(p - a);
2676
+ const pb = Math.abs(p - b);
2677
+ const pc = Math.abs(p - c);
2678
+ if (pa <= pb && pa <= pc) return a;
2679
+ if (pb <= pc) return b;
2680
+ return c;
2623
2681
  }
2624
- function motionBlurWindowIsStatic(plan, frameIndex, staticFrames) {
2625
- const worstCaseSamples = plan.fixedSamplesPerFrame ?? MAX_SAMPLES_PER_FRAME;
2626
- const inset = plan.shutterFrames / (2 * worstCaseSamples);
2627
- const minOffsetFrames = plan.windowStartFrames + inset;
2628
- const maxOffsetFrames = plan.windowStartFrames + plan.shutterFrames - inset;
2629
- const first = Math.floor(frameIndex - 1 + Math.min(0, minOffsetFrames));
2630
- const last = Math.floor(frameIndex + Math.max(0, maxOffsetFrames)) + 1;
2631
- for (let frame = first; frame <= last; frame++) {
2632
- if (!staticFrames.has(frame)) return false;
2682
+ function decodePngRaw(buf, caller) {
2683
+ if (buf[0] !== 137 || buf[1] !== 80 || buf[2] !== 78 || buf[3] !== 71 || buf[4] !== 13 || buf[5] !== 10 || buf[6] !== 26 || buf[7] !== 10) {
2684
+ throw new Error(`${caller}: not a PNG file`);
2633
2685
  }
2634
- return true;
2635
- }
2636
- var ADAPTIVE_SAMPLE_STEPS = [
2637
- { maxDiff: 3, samples: DEFAULT_SAMPLES_PER_FRAME },
2638
- { maxDiff: 6, samples: 32 },
2639
- { maxDiff: Infinity, samples: MAX_SAMPLES_PER_FRAME }
2640
- ];
2641
- function adaptiveSampleCount(diff) {
2642
- for (const step of ADAPTIVE_SAMPLE_STEPS) {
2643
- if (diff <= step.maxDiff) return step.samples;
2686
+ let pos = 8;
2687
+ let width = 0;
2688
+ let height = 0;
2689
+ let bitDepth = 0;
2690
+ let colorType = 0;
2691
+ let interlace = 0;
2692
+ let sawIhdr = false;
2693
+ const idatChunks = [];
2694
+ while (pos + 12 <= buf.length) {
2695
+ const chunkLen = buf.readUInt32BE(pos);
2696
+ const chunkType = buf.toString("ascii", pos + 4, pos + 8);
2697
+ const chunkData = buf.subarray(pos + 8, pos + 8 + chunkLen);
2698
+ if (chunkType === "IHDR") {
2699
+ width = chunkData.readUInt32BE(0);
2700
+ height = chunkData.readUInt32BE(4);
2701
+ bitDepth = chunkData[8] ?? 0;
2702
+ colorType = chunkData[9] ?? 0;
2703
+ interlace = chunkData[12] ?? 0;
2704
+ sawIhdr = true;
2705
+ } else if (chunkType === "IDAT") {
2706
+ idatChunks.push(Buffer.from(chunkData));
2707
+ } else if (chunkType === "IEND") {
2708
+ break;
2709
+ }
2710
+ pos += 12 + chunkLen;
2644
2711
  }
2645
- return MAX_SAMPLES_PER_FRAME;
2646
- }
2647
- var SPATIAL_TWEEN_PROPERTIES = [
2648
- "x",
2649
- "y",
2650
- "z",
2651
- "xPercent",
2652
- "yPercent",
2653
- "rotation",
2654
- "rotate",
2655
- "rotationX",
2656
- "rotationY",
2657
- "rotationZ",
2658
- "scale",
2659
- "scaleX",
2660
- "scaleY",
2661
- "scaleZ",
2662
- "skewX",
2663
- "skewY",
2664
- "perspective",
2665
- "transformPerspective",
2666
- "top",
2667
- "left",
2668
- "right",
2669
- "bottom",
2670
- "width",
2671
- "height",
2672
- "translate",
2673
- "translateX",
2674
- "translateY",
2675
- "translateZ",
2676
- "transform"
2677
- ];
2678
- function probeDiffMagnitude(a, b) {
2679
- const decodedA = decodePng(a);
2680
- const decodedB = decodePng(b);
2681
- if (decodedA.width !== decodedB.width || decodedA.height !== decodedB.height) {
2712
+ if (!sawIhdr) {
2713
+ throw new Error(`${caller}: PNG missing IHDR chunk`);
2714
+ }
2715
+ if (colorType !== 2 && colorType !== 6) {
2716
+ throw new Error(`${caller}: unsupported color type ${colorType} (expected 2=RGB or 6=RGBA)`);
2717
+ }
2718
+ if (interlace !== 0) {
2682
2719
  throw new Error(
2683
- `probeDiffMagnitude: sample geometry mismatch (${decodedA.width}x${decodedA.height} vs ${decodedB.width}x${decodedB.height})`
2720
+ `${caller}: Adam7-interlaced PNGs are not supported (interlace method ${interlace})`
2684
2721
  );
2685
2722
  }
2686
- let sum = 0;
2687
- for (let i = 0; i < decodedA.data.length; i++) {
2688
- sum += Math.abs(decodedA.data[i] - decodedB.data[i]);
2723
+ const channels = colorType === 6 ? 4 : 3;
2724
+ const bpp = channels * (bitDepth / 8);
2725
+ const stride = width * bpp;
2726
+ const compressed = Buffer.concat(idatChunks);
2727
+ const decompressed = inflateSync(compressed);
2728
+ const rawPixels = Buffer.allocUnsafe(height * stride);
2729
+ const prevRow = new Uint8Array(stride);
2730
+ const currRow = new Uint8Array(stride);
2731
+ let srcPos = 0;
2732
+ for (let y = 0; y < height; y++) {
2733
+ const filterType = decompressed[srcPos++] ?? 0;
2734
+ const rawRow = decompressed.subarray(srcPos, srcPos + stride);
2735
+ srcPos += stride;
2736
+ switch (filterType) {
2737
+ case 0:
2738
+ currRow.set(rawRow);
2739
+ break;
2740
+ case 1:
2741
+ for (let x = 0; x < stride; x++) {
2742
+ currRow[x] = (rawRow[x] ?? 0) + (x >= bpp ? currRow[x - bpp] ?? 0 : 0) & 255;
2743
+ }
2744
+ break;
2745
+ case 2:
2746
+ for (let x = 0; x < stride; x++) {
2747
+ currRow[x] = (rawRow[x] ?? 0) + (prevRow[x] ?? 0) & 255;
2748
+ }
2749
+ break;
2750
+ case 3:
2751
+ for (let x = 0; x < stride; x++) {
2752
+ const left = x >= bpp ? currRow[x - bpp] ?? 0 : 0;
2753
+ const up = prevRow[x] ?? 0;
2754
+ currRow[x] = (rawRow[x] ?? 0) + Math.floor((left + up) / 2) & 255;
2755
+ }
2756
+ break;
2757
+ case 4:
2758
+ for (let x = 0; x < stride; x++) {
2759
+ const left = x >= bpp ? currRow[x - bpp] ?? 0 : 0;
2760
+ const up = prevRow[x] ?? 0;
2761
+ const upLeft = x >= bpp ? prevRow[x - bpp] ?? 0 : 0;
2762
+ currRow[x] = (rawRow[x] ?? 0) + paeth(left, up, upLeft) & 255;
2763
+ }
2764
+ break;
2765
+ default:
2766
+ throw new Error(`${caller}: unknown filter type ${filterType} at row ${y}`);
2767
+ }
2768
+ rawPixels.set(currRow, y * stride);
2769
+ prevRow.set(currRow);
2689
2770
  }
2690
- return sum / decodedA.data.length;
2771
+ return { width, height, bitDepth, colorType, rawPixels };
2691
2772
  }
2692
- var SRGB_TO_LINEAR = (() => {
2693
- const lut = new Float64Array(256);
2694
- for (let i = 0; i < 256; i++) lut[i] = srgbByteToLinear(i);
2695
- return lut;
2696
- })();
2697
- var SRGB_PASSTHROUGH = (() => {
2698
- const lut = new Float64Array(256);
2699
- for (let i = 0; i < 256; i++) lut[i] = i;
2700
- return lut;
2701
- })();
2702
- function linearToByte(value) {
2703
- const c = value <= 31308e-7 ? value * 12.92 : 1.055 * Math.pow(value, 1 / 2.4) - 0.055;
2704
- return clampByte(c * 255);
2773
+ function decodePng(buf) {
2774
+ const { width, height, bitDepth, colorType, rawPixels } = decodePngRaw(buf, "decodePng");
2775
+ if (bitDepth !== 8) {
2776
+ throw new Error(`decodePng: unsupported bit depth ${bitDepth} (expected 8)`);
2777
+ }
2778
+ const output = new Uint8Array(width * height * 4);
2779
+ if (colorType === 6) {
2780
+ output.set(rawPixels);
2781
+ } else {
2782
+ for (let i = 0; i < width * height; i++) {
2783
+ output[i * 4 + 0] = rawPixels[i * 3 + 0] ?? 0;
2784
+ output[i * 4 + 1] = rawPixels[i * 3 + 1] ?? 0;
2785
+ output[i * 4 + 2] = rawPixels[i * 3 + 2] ?? 0;
2786
+ output[i * 4 + 3] = 255;
2787
+ }
2788
+ }
2789
+ return { width, height, data: output };
2705
2790
  }
2706
- function clampByte(value) {
2707
- return Math.min(255, Math.max(0, Math.round(value)));
2791
+ var PNG_DEFLATE_LEVEL = 1;
2792
+ function pngChunk(type, body) {
2793
+ const header = Buffer.alloc(8);
2794
+ header.writeUInt32BE(body.length, 0);
2795
+ header.write(type, 4, "ascii");
2796
+ const trailer = Buffer.alloc(4);
2797
+ trailer.writeUInt32BE(chunkCrc32(type, body), 0);
2798
+ return Buffer.concat([header, body, trailer]);
2708
2799
  }
2709
- var MotionBlurAccumulator = class {
2710
- toWorking;
2711
- fromWorking;
2712
- /** Premultiplied r, g, b and alpha sums per pixel. Null until the first sample sets the size. */
2713
- sums = null;
2714
- width = 0;
2715
- height = 0;
2716
- count = 0;
2717
- constructor(blend) {
2718
- this.toWorking = blend === "linear" ? SRGB_TO_LINEAR : SRGB_PASSTHROUGH;
2719
- this.fromWorking = blend === "linear" ? linearToByte : clampByte;
2800
+ function encodePng(width, height, rgba) {
2801
+ const expected = width * height * 4;
2802
+ if (rgba.length !== expected) {
2803
+ throw new Error(
2804
+ `encodePng: expected ${expected} bytes for ${width}x${height}, got ${rgba.length}`
2805
+ );
2720
2806
  }
2721
- /** Fold one captured sample PNG into the running average. */
2722
- add(png) {
2723
- const { width, height, data } = decodePng(png);
2724
- if (!this.sums) {
2725
- this.width = width;
2726
- this.height = height;
2727
- this.sums = new Float32Array(width * height * 4);
2728
- } else if (width !== this.width || height !== this.height) {
2729
- throw new Error(
2730
- `MotionBlurAccumulator: sample geometry mismatch (${width}x${height} vs ${this.width}x${this.height})`
2731
- );
2732
- }
2733
- const sums = this.sums;
2734
- const toWorking = this.toWorking;
2735
- for (let i = 0; i < sums.length; i += 4) {
2736
- const alpha = data[i + 3] / 255;
2737
- sums[i] = sums[i] + toWorking[data[i]] * alpha;
2738
- sums[i + 1] = sums[i + 1] + toWorking[data[i + 1]] * alpha;
2739
- sums[i + 2] = sums[i + 2] + toWorking[data[i + 2]] * alpha;
2740
- sums[i + 3] = sums[i + 3] + alpha;
2741
- }
2742
- this.count += 1;
2807
+ const stride = width * 4;
2808
+ const filtered = Buffer.alloc((stride + 1) * height);
2809
+ for (let y = 0; y < height; y++) {
2810
+ filtered[y * (stride + 1)] = 0;
2811
+ filtered.set(rgba.subarray(y * stride, (y + 1) * stride), y * (stride + 1) + 1);
2743
2812
  }
2744
- /** Un-premultiply and encode the average. Throws if no sample was ever added. */
2745
- finish() {
2746
- const sums = this.sums;
2747
- if (!sums) throw new Error("MotionBlurAccumulator: no samples");
2748
- const out = new Uint8Array(sums.length);
2749
- for (let i = 0; i < sums.length; i += 4) {
2750
- const alphaSum = sums[i + 3];
2751
- out[i + 3] = clampByte(alphaSum / this.count * 255);
2752
- if (alphaSum === 0) continue;
2753
- const scale = 1 / alphaSum;
2754
- out[i] = this.fromWorking(sums[i] * scale);
2755
- out[i + 1] = this.fromWorking(sums[i + 1] * scale);
2756
- out[i + 2] = this.fromWorking(sums[i + 2] * scale);
2813
+ const ihdr = Buffer.alloc(13);
2814
+ ihdr.writeUInt32BE(width, 0);
2815
+ ihdr.writeUInt32BE(height, 4);
2816
+ ihdr[8] = 8;
2817
+ ihdr[9] = 6;
2818
+ return Buffer.concat([
2819
+ Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]),
2820
+ pngChunk("IHDR", ihdr),
2821
+ pngChunk("IDAT", deflateSync(filtered, { level: PNG_DEFLATE_LEVEL })),
2822
+ pngChunk("IEND", Buffer.alloc(0))
2823
+ ]);
2824
+ }
2825
+ function decodePngToRgb48le(buf) {
2826
+ const { width, height, bitDepth, colorType, rawPixels } = decodePngRaw(buf, "decodePngToRgb48le");
2827
+ if (bitDepth !== 16) {
2828
+ throw new Error(`decodePngToRgb48le: unsupported bit depth ${bitDepth} (expected 16)`);
2829
+ }
2830
+ const bpp = colorType === 6 ? 8 : 6;
2831
+ const output = Buffer.allocUnsafe(width * height * 6);
2832
+ for (let y = 0; y < height; y++) {
2833
+ const dstBase = y * width * 6;
2834
+ const srcRowBase = y * width * bpp;
2835
+ for (let x = 0; x < width; x++) {
2836
+ const srcBase = srcRowBase + x * bpp;
2837
+ output[dstBase + x * 6 + 0] = rawPixels[srcBase + 1] ?? 0;
2838
+ output[dstBase + x * 6 + 1] = rawPixels[srcBase + 0] ?? 0;
2839
+ output[dstBase + x * 6 + 2] = rawPixels[srcBase + 3] ?? 0;
2840
+ output[dstBase + x * 6 + 3] = rawPixels[srcBase + 2] ?? 0;
2841
+ output[dstBase + x * 6 + 4] = rawPixels[srcBase + 5] ?? 0;
2842
+ output[dstBase + x * 6 + 5] = rawPixels[srcBase + 4] ?? 0;
2757
2843
  }
2758
- return { width: this.width, height: this.height, data: out };
2759
2844
  }
2760
- };
2761
-
2762
- // ../engine/src/services/pageMotionBlur.ts
2763
- function pageOffReason(options) {
2764
- if (options.motionBlur) return "engine-motion-blur";
2765
- if (options.pageMotionBlur === "off") return "preview-unsupported";
2766
- return options.pageMotionBlur ?? null;
2845
+ return { width, height, data: output };
2767
2846
  }
2768
- async function installPageMotionBlur(page, options) {
2769
- await page.evaluateOnNewDocument(acceleratedCanvasTrackerSource());
2770
- const scale = options.deviceScaleFactor ?? 1;
2771
- if (scale > 1) {
2772
- await page.evaluateOnNewDocument(
2773
- (key, v) => {
2774
- window[key] = v;
2775
- },
2776
- PAGE_DEVICE_SCALE_GLOBAL,
2777
- scale
2778
- );
2779
- }
2780
- const off = pageOffReason(options);
2781
- if (!off) return;
2782
- await page.evaluateOnNewDocument(
2783
- (key, v) => {
2784
- window[key] = v;
2785
- },
2786
- PAGE_MOTION_BLUR_OFF_GLOBAL,
2787
- off
2788
- );
2847
+ function srgbByteToLinear(value) {
2848
+ const v = value / 255;
2849
+ return v <= 0.04045 ? v / 12.92 : Math.pow((v + 0.055) / 1.055, 2.4);
2789
2850
  }
2790
- async function readPageMotionBlur(page) {
2791
- return page.evaluate(() => {
2792
- const api = Reflect.get(window, "__hfMotionBlur");
2793
- const report = api && typeof api === "object" ? Reflect.get(api, "report") : null;
2794
- const got = typeof report === "function" ? report() : null;
2795
- if (!got || typeof got !== "object") return null;
2796
- const tier = Reflect.get(got, "tier");
2797
- return {
2798
- state: String(Reflect.get(got, "state")),
2799
- code: String(Reflect.get(got, "reasonCode")),
2800
- movers: Number(Reflect.get(got, "movers")),
2801
- failedFrames: Number(Reflect.get(got, "failedFrames")) || 0,
2802
- tier: typeof tier === "string" ? tier : null
2803
- };
2804
- });
2851
+ function buildSrgbToSignalLut(transfer) {
2852
+ const lut = new Uint16Array(256);
2853
+ const hlgA = 0.17883277;
2854
+ const hlgB = 1 - 4 * hlgA;
2855
+ const hlgC = 0.5 - hlgA * Math.log(4 * hlgA);
2856
+ const hlgSdrWhite = (Math.exp((0.75 - hlgC) / hlgA) + hlgB) / 12;
2857
+ const pqM1 = 0.1593017578125;
2858
+ const pqM2 = 78.84375;
2859
+ const pqC1 = 0.8359375;
2860
+ const pqC2 = 18.8515625;
2861
+ const pqC3 = 18.6875;
2862
+ const pqMaxNits = 1e4;
2863
+ const sdrNits = 203;
2864
+ for (let i = 0; i < 256; i++) {
2865
+ if (transfer === "srgb") {
2866
+ lut[i] = i * 257;
2867
+ continue;
2868
+ }
2869
+ const linear = srgbByteToLinear(i);
2870
+ let signal;
2871
+ if (transfer === "hlg") {
2872
+ const scene = linear * hlgSdrWhite;
2873
+ signal = scene <= 1 / 12 ? Math.sqrt(3 * scene) : hlgA * Math.log(12 * scene - hlgB) + hlgC;
2874
+ } else {
2875
+ const Lp = Math.max(0, linear * sdrNits / pqMaxNits);
2876
+ const Lm1 = Math.pow(Lp, pqM1);
2877
+ signal = Math.pow((pqC1 + pqC2 * Lm1) / (1 + pqC3 * Lm1), pqM2);
2878
+ }
2879
+ lut[i] = Math.min(65535, Math.round(signal * 65535));
2880
+ }
2881
+ return lut;
2805
2882
  }
2806
- var formatPageMotionBlur = (r) => `[motion-blur] ${r.state} reasonCode=${r.code} movers=${r.movers} failedFrames=${r.failedFrames}${r.tier ? ` tier=${r.tier}` : ""}`;
2807
- async function describePageMotionBlur(page) {
2808
- const r = await readPageMotionBlur(page);
2809
- return r && formatPageMotionBlur(r);
2883
+ var SRGB_TO_SRGB_16 = buildSrgbToSignalLut("srgb");
2884
+ var SRGB_TO_HLG = buildSrgbToSignalLut("hlg");
2885
+ var SRGB_TO_PQ = buildSrgbToSignalLut("pq");
2886
+ function getSrgbToSignalLut(transfer) {
2887
+ if (transfer === "pq") return SRGB_TO_PQ;
2888
+ if (transfer === "hlg") return SRGB_TO_HLG;
2889
+ return SRGB_TO_SRGB_16;
2810
2890
  }
2811
- async function describePageMotionBlurAtEnd(page, timeoutMs = 1500) {
2812
- let timer;
2813
- const stuck = new Promise((resolve2) => {
2814
- timer = setTimeout(() => resolve2(null), timeoutMs);
2815
- });
2816
- try {
2817
- const r = await Promise.race([readPageMotionBlur(page), stuck]);
2818
- return r && r.failedFrames > 0 ? `${formatPageMotionBlur(r)} (session end)` : null;
2819
- } catch {
2820
- return null;
2821
- } finally {
2822
- clearTimeout(timer);
2891
+ function blitRgba8OverRgb48le(domRgba, canvas, width, height, transfer = "hlg") {
2892
+ const pixelCount = width * height;
2893
+ const lut = getSrgbToSignalLut(transfer);
2894
+ for (let i = 0; i < pixelCount; i++) {
2895
+ const da = domRgba[i * 4 + 3] ?? 0;
2896
+ if (da === 0) {
2897
+ continue;
2898
+ } else if (da === 255) {
2899
+ const r16 = lut[domRgba[i * 4 + 0] ?? 0] ?? 0;
2900
+ const g16 = lut[domRgba[i * 4 + 1] ?? 0] ?? 0;
2901
+ const b16 = lut[domRgba[i * 4 + 2] ?? 0] ?? 0;
2902
+ canvas.writeUInt16LE(r16, i * 6);
2903
+ canvas.writeUInt16LE(g16, i * 6 + 2);
2904
+ canvas.writeUInt16LE(b16, i * 6 + 4);
2905
+ } else {
2906
+ const alpha = da / 255;
2907
+ const invAlpha = 1 - alpha;
2908
+ const hdrR = (canvas[i * 6 + 0] ?? 0) | (canvas[i * 6 + 1] ?? 0) << 8;
2909
+ const hdrG = (canvas[i * 6 + 2] ?? 0) | (canvas[i * 6 + 3] ?? 0) << 8;
2910
+ const hdrB = (canvas[i * 6 + 4] ?? 0) | (canvas[i * 6 + 5] ?? 0) << 8;
2911
+ const domR = lut[domRgba[i * 4 + 0] ?? 0] ?? 0;
2912
+ const domG = lut[domRgba[i * 4 + 1] ?? 0] ?? 0;
2913
+ const domB = lut[domRgba[i * 4 + 2] ?? 0] ?? 0;
2914
+ canvas.writeUInt16LE(Math.round(domR * alpha + hdrR * invAlpha), i * 6);
2915
+ canvas.writeUInt16LE(Math.round(domG * alpha + hdrG * invAlpha), i * 6 + 2);
2916
+ canvas.writeUInt16LE(Math.round(domB * alpha + hdrB * invAlpha), i * 6 + 4);
2917
+ }
2823
2918
  }
2824
2919
  }
2825
-
2826
- // ../engine/src/services/videoFrameTransport.ts
2827
- import { randomUUID } from "crypto";
2828
- var base64ImagePrefix = /^data:(image\/[\w.+-]+);base64,/;
2829
- var transports = /* @__PURE__ */ new WeakMap();
2830
- async function createTransport(page) {
2831
- const pageUrl = new URL(page.url());
2832
- const origin = /^https?:$/.test(pageUrl.protocol) ? pageUrl.origin : "https://hyperframes-render.invalid";
2833
- const prefix = `${origin}/__hyperframes_video_frames__/${randomUUID()}/`;
2834
- const responses = /* @__PURE__ */ new Map();
2835
- const client = await page.createCDPSession();
2836
- client.on("Fetch.requestPaused", (event) => {
2837
- const frame = responses.get(event.request.url);
2838
- void fulfillFrame(client, event.requestId, frame);
2839
- });
2840
- try {
2841
- await client.send("Fetch.enable", {
2842
- patterns: [{ urlPattern: `${prefix}*`, requestStage: "Request" }]
2843
- });
2844
- } catch (error) {
2845
- await client.detach().catch(() => {
2846
- });
2847
- throw error;
2848
- }
2849
- page.once("close", () => responses.clear());
2850
- return { prefix, nextId: 0, responses };
2920
+ function cornerAlpha(px, py, cx, cy, r) {
2921
+ const dx = px - cx;
2922
+ const dy = py - cy;
2923
+ const dist = Math.sqrt(dx * dx + dy * dy);
2924
+ if (dist > r + 0.5) return 0;
2925
+ if (dist > r - 0.5) return r + 0.5 - dist;
2926
+ return 1;
2851
2927
  }
2852
- async function fulfillFrame(client, requestId, frame) {
2853
- try {
2854
- await client.send("Fetch.fulfillRequest", {
2855
- requestId,
2856
- responseCode: frame ? 200 : 404,
2857
- responseHeaders: [
2858
- { name: "Content-Type", value: frame?.contentType ?? "text/plain" },
2859
- { name: "Cache-Control", value: "no-store" },
2860
- { name: "Access-Control-Allow-Origin", value: "*" }
2861
- ],
2862
- body: frame?.body ?? ""
2863
- });
2864
- } catch (error) {
2865
- if (frame) frame.error = error;
2866
- await client.send("Fetch.failRequest", { requestId, errorReason: "Failed" }).catch(() => {
2867
- });
2868
- }
2928
+ function roundedRectAlpha(px, py, w, h, radii) {
2929
+ const [tl, tr, br, bl] = radii;
2930
+ if (px < tl && py < tl) return cornerAlpha(px, py, tl, tl, tl);
2931
+ if (px >= w - tr && py < tr) return cornerAlpha(px, py, w - tr, tr, tr);
2932
+ if (px >= w - br && py >= h - br) return cornerAlpha(px, py, w - br, h - br, br);
2933
+ if (px < bl && py >= h - bl) return cornerAlpha(px, py, bl, h - bl, bl);
2934
+ return 1;
2869
2935
  }
2870
- async function withVideoFrameSources(page, updates, inject) {
2871
- if (!updates.some((update) => base64ImagePrefix.test(update.dataUri))) return inject(updates);
2872
- let pending = transports.get(page);
2873
- if (!pending) {
2874
- pending = createTransport(page);
2875
- transports.set(page, pending);
2936
+ function blitRgb48leRegion(canvas, source, dx, dy, sw, sh, canvasWidth, canvasHeight, opacity, borderRadius) {
2937
+ if (sw <= 0 || sh <= 0) return;
2938
+ const op = opacity ?? 1;
2939
+ if (op <= 0) return;
2940
+ const x0 = Math.max(0, dx);
2941
+ const y0 = Math.max(0, dy);
2942
+ const x1 = Math.min(canvasWidth, dx + sw);
2943
+ const y1 = Math.min(canvasHeight, dy + sh);
2944
+ if (x0 >= x1 || y0 >= y1) return;
2945
+ const clippedW = x1 - x0;
2946
+ const srcOffsetX = x0 - dx;
2947
+ const srcOffsetY = y0 - dy;
2948
+ const hasMask = borderRadius !== void 0;
2949
+ if (op >= 0.999 && !hasMask) {
2950
+ for (let y = 0; y < y1 - y0; y++) {
2951
+ const srcRowOff = ((srcOffsetY + y) * sw + srcOffsetX) * 6;
2952
+ const dstRowOff = ((y0 + y) * canvasWidth + x0) * 6;
2953
+ source.copy(canvas, dstRowOff, srcRowOff, srcRowOff + clippedW * 6);
2954
+ }
2955
+ } else if (!hasMask) {
2956
+ const invOp = 1 - op;
2957
+ for (let y = 0; y < y1 - y0; y++) {
2958
+ let srcOff = ((srcOffsetY + y) * sw + srcOffsetX) * 6;
2959
+ let dstOff = ((y0 + y) * canvasWidth + x0) * 6;
2960
+ for (let x = 0; x < clippedW; x++) {
2961
+ const sr = source[srcOff] | source[srcOff + 1] << 8;
2962
+ const sg = source[srcOff + 2] | source[srcOff + 3] << 8;
2963
+ const sb = source[srcOff + 4] | source[srcOff + 5] << 8;
2964
+ const dr = canvas[dstOff] | canvas[dstOff + 1] << 8;
2965
+ const dg = canvas[dstOff + 2] | canvas[dstOff + 3] << 8;
2966
+ const db = canvas[dstOff + 4] | canvas[dstOff + 5] << 8;
2967
+ const r = sr * op + dr * invOp + 0.5 | 0;
2968
+ const g = sg * op + dg * invOp + 0.5 | 0;
2969
+ const b = sb * op + db * invOp + 0.5 | 0;
2970
+ canvas[dstOff] = r & 255;
2971
+ canvas[dstOff + 1] = r >>> 8;
2972
+ canvas[dstOff + 2] = g & 255;
2973
+ canvas[dstOff + 3] = g >>> 8;
2974
+ canvas[dstOff + 4] = b & 255;
2975
+ canvas[dstOff + 5] = b >>> 8;
2976
+ srcOff += 6;
2977
+ dstOff += 6;
2978
+ }
2979
+ }
2980
+ } else {
2981
+ for (let y = 0; y < y1 - y0; y++) {
2982
+ for (let x = 0; x < clippedW; x++) {
2983
+ let effectiveOp = op;
2984
+ if (hasMask) {
2985
+ const ma = roundedRectAlpha(srcOffsetX + x, srcOffsetY + y, sw, sh, borderRadius);
2986
+ if (ma <= 0) continue;
2987
+ effectiveOp *= ma;
2988
+ }
2989
+ const srcOff = ((srcOffsetY + y) * sw + srcOffsetX + x) * 6;
2990
+ const dstOff = ((y0 + y) * canvasWidth + x0 + x) * 6;
2991
+ if (effectiveOp >= 0.999) {
2992
+ source.copy(canvas, dstOff, srcOff, srcOff + 6);
2993
+ } else {
2994
+ const invEff = 1 - effectiveOp;
2995
+ const sr = source.readUInt16LE(srcOff);
2996
+ const sg = source.readUInt16LE(srcOff + 2);
2997
+ const sb = source.readUInt16LE(srcOff + 4);
2998
+ const dr = canvas.readUInt16LE(dstOff);
2999
+ const dg = canvas.readUInt16LE(dstOff + 2);
3000
+ const db = canvas.readUInt16LE(dstOff + 4);
3001
+ canvas.writeUInt16LE(Math.round(sr * effectiveOp + dr * invEff), dstOff);
3002
+ canvas.writeUInt16LE(Math.round(sg * effectiveOp + dg * invEff), dstOff + 2);
3003
+ canvas.writeUInt16LE(Math.round(sb * effectiveOp + db * invEff), dstOff + 4);
3004
+ }
3005
+ }
3006
+ }
2876
3007
  }
2877
- let transport;
2878
- try {
2879
- transport = await pending;
2880
- } catch (error) {
2881
- transports.delete(page);
2882
- throw error;
3008
+ }
3009
+ function blitRgb48leAffine(canvas, source, matrix, srcW, srcH, canvasW, canvasH, opacity, borderRadius) {
3010
+ const a = matrix[0];
3011
+ const b = matrix[1];
3012
+ const c = matrix[2];
3013
+ const d = matrix[3];
3014
+ const tx = matrix[4];
3015
+ const ty = matrix[5];
3016
+ if (a === void 0 || b === void 0 || c === void 0 || d === void 0 || tx === void 0 || ty === void 0)
3017
+ return;
3018
+ const det = a * d - b * c;
3019
+ if (Math.abs(det) < 1e-10) return;
3020
+ const invA = d / det;
3021
+ const invB = -b / det;
3022
+ const invC = -c / det;
3023
+ const invD = a / det;
3024
+ const invTx = -(invA * tx + invC * ty);
3025
+ const invTy = -(invB * tx + invD * ty);
3026
+ const op = opacity ?? 1;
3027
+ if (op <= 0) return;
3028
+ const hasMask = borderRadius !== void 0;
3029
+ const corners = [
3030
+ [tx, ty],
3031
+ [a * srcW + tx, b * srcW + ty],
3032
+ [c * srcH + tx, d * srcH + ty],
3033
+ [a * srcW + c * srcH + tx, b * srcW + d * srcH + ty]
3034
+ ];
3035
+ let minX = canvasW, maxX = 0, minY = canvasH, maxY = 0;
3036
+ for (const corner of corners) {
3037
+ const cx = corner[0] ?? 0;
3038
+ const cy = corner[1] ?? 0;
3039
+ if (cx < minX) minX = cx;
3040
+ if (cx > maxX) maxX = cx;
3041
+ if (cy < minY) minY = cy;
3042
+ if (cy > maxY) maxY = cy;
2883
3043
  }
2884
- const registered = [];
2885
- try {
2886
- const resolved = updates.map((update) => {
2887
- const match = base64ImagePrefix.exec(update.dataUri);
2888
- if (!match) return update;
2889
- const frame = {
2890
- contentType: match[1] ?? "image/png",
2891
- body: update.dataUri.slice(match[0].length)
2892
- };
2893
- const url = `${transport.prefix}${transport.nextId++}`;
2894
- transport.responses.set(url, frame);
2895
- registered.push({ url, frame });
2896
- return {
2897
- ...update,
2898
- dataUri: url,
2899
- crossOrigin: "anonymous",
2900
- sourceLabel: "inline frame"
2901
- };
2902
- });
2903
- return await inject(resolved);
2904
- } catch (error) {
2905
- throw registered.find(({ frame }) => frame.error !== void 0)?.frame.error ?? error;
2906
- } finally {
2907
- for (const { url } of registered) transport.responses.delete(url);
3044
+ const startX = Math.max(0, Math.floor(minX));
3045
+ const endX = Math.min(canvasW, Math.ceil(maxX));
3046
+ const startY = Math.max(0, Math.floor(minY));
3047
+ const endY = Math.min(canvasH, Math.ceil(maxY));
3048
+ for (let dy = startY; dy < endY; dy++) {
3049
+ for (let dx = startX; dx < endX; dx++) {
3050
+ const sx = invA * dx + invC * dy + invTx;
3051
+ const sy = invB * dx + invD * dy + invTy;
3052
+ if (sx < 0 || sy < 0 || sx >= srcW || sy >= srcH) continue;
3053
+ let effectiveOp = op;
3054
+ if (hasMask) {
3055
+ const ma = roundedRectAlpha(sx, sy, srcW, srcH, borderRadius);
3056
+ if (ma <= 0) continue;
3057
+ effectiveOp *= ma;
3058
+ }
3059
+ const x0 = Math.floor(sx);
3060
+ const y0 = Math.floor(sy);
3061
+ const fx = sx - x0;
3062
+ const fy = sy - y0;
3063
+ const x1 = Math.min(x0 + 1, srcW - 1);
3064
+ const y1 = Math.min(y0 + 1, srcH - 1);
3065
+ const off00 = (y0 * srcW + x0) * 6;
3066
+ const off10 = (y0 * srcW + x1) * 6;
3067
+ const off01 = (y1 * srcW + x0) * 6;
3068
+ const off11 = (y1 * srcW + x1) * 6;
3069
+ const w00 = (1 - fx) * (1 - fy);
3070
+ const w10 = fx * (1 - fy);
3071
+ const w01 = (1 - fx) * fy;
3072
+ const w11 = fx * fy;
3073
+ const sr = source.readUInt16LE(off00) * w00 + source.readUInt16LE(off10) * w10 + source.readUInt16LE(off01) * w01 + source.readUInt16LE(off11) * w11;
3074
+ const sg = source.readUInt16LE(off00 + 2) * w00 + source.readUInt16LE(off10 + 2) * w10 + source.readUInt16LE(off01 + 2) * w01 + source.readUInt16LE(off11 + 2) * w11;
3075
+ const sb = source.readUInt16LE(off00 + 4) * w00 + source.readUInt16LE(off10 + 4) * w10 + source.readUInt16LE(off01 + 4) * w01 + source.readUInt16LE(off11 + 4) * w11;
3076
+ const dstOff = (dy * canvasW + dx) * 6;
3077
+ if (effectiveOp >= 0.999) {
3078
+ canvas.writeUInt16LE(Math.round(sr), dstOff);
3079
+ canvas.writeUInt16LE(Math.round(sg), dstOff + 2);
3080
+ canvas.writeUInt16LE(Math.round(sb), dstOff + 4);
3081
+ } else {
3082
+ const invEff = 1 - effectiveOp;
3083
+ const dr = canvas.readUInt16LE(dstOff);
3084
+ const dg = canvas.readUInt16LE(dstOff + 2);
3085
+ const db = canvas.readUInt16LE(dstOff + 4);
3086
+ canvas.writeUInt16LE(Math.round(sr * effectiveOp + dr * invEff), dstOff);
3087
+ canvas.writeUInt16LE(Math.round(sg * effectiveOp + dg * invEff), dstOff + 2);
3088
+ canvas.writeUInt16LE(Math.round(sb * effectiveOp + db * invEff), dstOff + 4);
3089
+ }
3090
+ }
2908
3091
  }
2909
3092
  }
2910
-
2911
- // ../engine/src/services/screenshotService.ts
2912
- var cdpSessionCache = /* @__PURE__ */ new WeakMap();
2913
- async function getCdpSession(page) {
2914
- let client = cdpSessionCache.get(page);
2915
- if (!client) {
2916
- client = await page.createCDPSession();
2917
- cdpSessionCache.set(page, client);
3093
+ function parseObjectPositionAxis(value, axis) {
3094
+ const lower = value.trim().toLowerCase();
3095
+ if (lower === "left" || lower === "top") return 0;
3096
+ if (lower === "right" || lower === "bottom") return 1;
3097
+ if (lower === "center" || lower === "") return 0.5;
3098
+ if (lower.endsWith("%")) {
3099
+ const pct = parseFloat(lower) / 100;
3100
+ return Number.isFinite(pct) ? pct : 0.5;
2918
3101
  }
2919
- return client;
2920
- }
2921
- function shouldDefaultCaptureBeyondViewport(browserVersion, platform = process.platform) {
2922
- return platform === "darwin" && browserVersion.startsWith("Chrome/");
3102
+ if (axis === "x" || axis === "y") return 0.5;
3103
+ return 0.5;
2923
3104
  }
2924
- async function probeBeginFrameLiveness(page, timeoutMs, frameTimeTicks, intervalMs) {
2925
- const client = await getCdpSession(page);
2926
- const params = {};
2927
- if (typeof frameTimeTicks === "number") params.frameTimeTicks = frameTimeTicks;
2928
- if (typeof intervalMs === "number") params.interval = intervalMs;
2929
- let timer;
2930
- try {
2931
- return await Promise.race([
2932
- client.send("HeadlessExperimental.beginFrame", params).then(() => true).catch(() => false),
2933
- new Promise((resolve2) => {
2934
- timer = setTimeout(() => resolve2(false), timeoutMs);
2935
- })
2936
- ]);
2937
- } finally {
2938
- if (timer) clearTimeout(timer);
3105
+ function parseObjectPosition(css) {
3106
+ if (!css || !css.trim()) return { x: 0.5, y: 0.5 };
3107
+ const tokens = css.trim().split(/\s+/);
3108
+ if (tokens.length === 1) {
3109
+ const single = tokens[0] ?? "";
3110
+ const v = parseObjectPositionAxis(single, "x");
3111
+ return { x: v, y: 0.5 };
2939
3112
  }
3113
+ return {
3114
+ x: parseObjectPositionAxis(tokens[0] ?? "", "x"),
3115
+ y: parseObjectPositionAxis(tokens[1] ?? "", "y")
3116
+ };
2940
3117
  }
2941
- var lastFrameCache = /* @__PURE__ */ new WeakMap();
2942
- var PENDING_FRAME_RETRIES = 5;
2943
- async function sendBeginFrame(client, params) {
2944
- for (let attempt = 0; ; attempt++) {
2945
- try {
2946
- return await client.send("HeadlessExperimental.beginFrame", params);
2947
- } catch (err) {
2948
- const msg = err instanceof Error ? err.message : String(err);
2949
- const isPending = msg.includes("Another frame is pending");
2950
- if (isPending && attempt < PENDING_FRAME_RETRIES) {
2951
- await new Promise((r) => setTimeout(r, 50 * 2 ** attempt));
2952
- continue;
2953
- }
2954
- if (isPending) {
2955
- throw new Error(
2956
- `[BeginFrame] Frame still pending after ${PENDING_FRAME_RETRIES} retries: CPU overloaded by parallel renders. Reduce concurrent renders or use --docker for isolation.`
2957
- );
2958
- }
2959
- throw err;
2960
- }
3118
+ function computeObjectFitRect(srcW, srcH, dstW, dstH, fit, pos) {
3119
+ let renderedW = dstW;
3120
+ let renderedH = dstH;
3121
+ if (fit === "fill") {
3122
+ return { dx: 0, dy: 0, dw: dstW, dh: dstH };
2961
3123
  }
2962
- }
2963
- async function beginFrameCapture(page, options, frameTimeTicks, interval) {
2964
- const client = await getCdpSession(page);
2965
- const isPng = options.format === "png";
2966
- const screenshot = {
2967
- format: isPng ? "png" : "jpeg",
2968
- quality: isPng ? void 0 : options.quality ?? 80,
2969
- optimizeForSpeed: true
2970
- };
2971
- const result = await sendBeginFrame(client, { frameTimeTicks, interval, screenshot });
2972
- let buffer;
2973
- if (result.screenshotData) {
2974
- buffer = Buffer.from(result.screenshotData, "base64");
2975
- lastFrameCache.set(page, buffer);
3124
+ if (fit === "none") {
3125
+ renderedW = srcW;
3126
+ renderedH = srcH;
3127
+ } else if (fit === "scale-down") {
3128
+ const scale = Math.min(dstW / srcW, dstH / srcH, 1);
3129
+ renderedW = srcW * scale;
3130
+ renderedH = srcH * scale;
3131
+ } else if (fit === "cover") {
3132
+ const scale = Math.max(dstW / srcW, dstH / srcH);
3133
+ renderedW = srcW * scale;
3134
+ renderedH = srcH * scale;
2976
3135
  } else {
2977
- const cached = lastFrameCache.get(page);
2978
- if (cached) {
2979
- buffer = cached;
2980
- } else {
2981
- const fallback = await sendBeginFrame(client, {
2982
- frameTimeTicks: frameTimeTicks + 1e-3,
2983
- interval,
2984
- screenshot
2985
- });
2986
- buffer = fallback.screenshotData ? Buffer.from(fallback.screenshotData, "base64") : Buffer.alloc(0);
2987
- if (buffer.length > 0) lastFrameCache.set(page, buffer);
3136
+ const scale = Math.min(dstW / srcW, dstH / srcH);
3137
+ renderedW = srcW * scale;
3138
+ renderedH = srcH * scale;
3139
+ }
3140
+ const dx = (dstW - renderedW) * pos.x;
3141
+ const dy = (dstH - renderedH) * pos.y;
3142
+ return { dx, dy, dw: renderedW, dh: renderedH };
3143
+ }
3144
+ function resampleRgb48leObjectFit(source, srcW, srcH, dstW, dstH, fit = "fill", objectPosition) {
3145
+ if (srcW <= 0 || srcH <= 0 || dstW <= 0 || dstH <= 0) {
3146
+ return source;
3147
+ }
3148
+ if (fit === "fill" && srcW === dstW && srcH === dstH) {
3149
+ return source;
3150
+ }
3151
+ const pos = parseObjectPosition(objectPosition);
3152
+ const rect = computeObjectFitRect(srcW, srcH, dstW, dstH, fit, pos);
3153
+ const dst = Buffer.alloc(dstW * dstH * 6);
3154
+ const stride = dstW * 6;
3155
+ const xMin = Math.max(0, Math.floor(rect.dx));
3156
+ const yMin = Math.max(0, Math.floor(rect.dy));
3157
+ const xMax = Math.min(dstW, Math.ceil(rect.dx + rect.dw));
3158
+ const yMax = Math.min(dstH, Math.ceil(rect.dy + rect.dh));
3159
+ if (rect.dw <= 0 || rect.dh <= 0) {
3160
+ return dst;
3161
+ }
3162
+ const invScaleX = srcW / rect.dw;
3163
+ const invScaleY = srcH / rect.dh;
3164
+ for (let dy = yMin; dy < yMax; dy++) {
3165
+ const rowOff = dy * stride;
3166
+ const sy = (dy + 0.5 - rect.dy) * invScaleY - 0.5;
3167
+ const syc = Math.max(0, Math.min(srcH - 1, sy));
3168
+ const y0 = Math.floor(syc);
3169
+ const y1 = Math.min(y0 + 1, srcH - 1);
3170
+ const fy = syc - y0;
3171
+ const ify = 1 - fy;
3172
+ for (let dx = xMin; dx < xMax; dx++) {
3173
+ const sx = (dx + 0.5 - rect.dx) * invScaleX - 0.5;
3174
+ const sxc = Math.max(0, Math.min(srcW - 1, sx));
3175
+ const x0 = Math.floor(sxc);
3176
+ const x1 = Math.min(x0 + 1, srcW - 1);
3177
+ const fx = sxc - x0;
3178
+ const ifx = 1 - fx;
3179
+ const off00 = (y0 * srcW + x0) * 6;
3180
+ const off10 = (y0 * srcW + x1) * 6;
3181
+ const off01 = (y1 * srcW + x0) * 6;
3182
+ const off11 = (y1 * srcW + x1) * 6;
3183
+ const w00 = ifx * ify;
3184
+ const w10 = fx * ify;
3185
+ const w01 = ifx * fy;
3186
+ const w11 = fx * fy;
3187
+ const r = source.readUInt16LE(off00) * w00 + source.readUInt16LE(off10) * w10 + source.readUInt16LE(off01) * w01 + source.readUInt16LE(off11) * w11;
3188
+ const g = source.readUInt16LE(off00 + 2) * w00 + source.readUInt16LE(off10 + 2) * w10 + source.readUInt16LE(off01 + 2) * w01 + source.readUInt16LE(off11 + 2) * w11;
3189
+ const b = source.readUInt16LE(off00 + 4) * w00 + source.readUInt16LE(off10 + 4) * w10 + source.readUInt16LE(off01 + 4) * w01 + source.readUInt16LE(off11 + 4) * w11;
3190
+ const dstOff = rowOff + dx * 6;
3191
+ dst.writeUInt16LE(Math.round(r), dstOff);
3192
+ dst.writeUInt16LE(Math.round(g), dstOff + 2);
3193
+ dst.writeUInt16LE(Math.round(b), dstOff + 4);
2988
3194
  }
2989
3195
  }
2990
- return {
2991
- buffer,
2992
- hasDamage: result.hasDamage
2993
- };
3196
+ return dst;
2994
3197
  }
2995
- async function pageContentExceedsCaptureHeight(page, requestedHeight) {
2996
- const scrollHeight = await page.evaluate(() => document.documentElement.scrollHeight);
2997
- return scrollHeight > requestedHeight + 1;
3198
+ function normalizeObjectFit(value) {
3199
+ switch ((value ?? "").trim().toLowerCase()) {
3200
+ case "cover":
3201
+ return "cover";
3202
+ case "contain":
3203
+ return "contain";
3204
+ case "none":
3205
+ return "none";
3206
+ case "scale-down":
3207
+ return "scale-down";
3208
+ default:
3209
+ return "fill";
3210
+ }
2998
3211
  }
2999
- async function pageScreenshotCapture(page, options) {
3000
- const client = await getCdpSession(page);
3001
- const isPng = options.format === "png";
3002
- const dpr = options.deviceScaleFactor ?? 1;
3003
- const clip = { x: 0, y: 0, width: options.width, height: options.height, scale: dpr };
3004
- const result = await client.send("Page.captureScreenshot", {
3005
- format: isPng ? "png" : "jpeg",
3006
- quality: isPng ? void 0 : options.quality ?? 80,
3007
- fromSurface: true,
3008
- // Use Chrome's faster viewport-bound screenshot path by default. Callers
3009
- // opt into the beyond-viewport path only for known compositor edge cases,
3010
- // such as native video surfaces in tall portrait renders.
3011
- captureBeyondViewport: options.captureBeyondViewport ?? false,
3012
- optimizeForSpeed: !isPng,
3013
- clip
3014
- });
3015
- return Buffer.from(result.data, "base64");
3212
+ function parseTransformMatrix(css) {
3213
+ if (!css || css === "none") return null;
3214
+ const match2d = css.match(/^matrix\(([^,]+),([^,]+),([^,]+),([^,]+),([^,]+),([^,)]+)\)$/);
3215
+ if (match2d) {
3216
+ const values = match2d.slice(1, 7).map(Number);
3217
+ if (!values.every(Number.isFinite)) return null;
3218
+ return values;
3219
+ }
3220
+ const match3d = css.match(/^matrix3d\(([^)]+)\)$/);
3221
+ if (match3d) {
3222
+ const raw = match3d[1];
3223
+ if (!raw) return null;
3224
+ const parts = raw.split(",").map((s) => Number(s.trim()));
3225
+ if (parts.length !== 16 || !parts.every(Number.isFinite)) return null;
3226
+ warnIfZSignificant(parts);
3227
+ return [
3228
+ parts[0],
3229
+ parts[1],
3230
+ parts[4],
3231
+ parts[5],
3232
+ parts[12],
3233
+ parts[13]
3234
+ ];
3235
+ }
3236
+ return null;
3016
3237
  }
3017
- async function captureScreenshotWithAlpha(page, width, height) {
3018
- const client = await getCdpSession(page);
3019
- await client.send("Emulation.setDefaultBackgroundColorOverride", {
3020
- color: { r: 0, g: 0, b: 0, a: 0 }
3021
- });
3022
- try {
3023
- const result = await client.send("Page.captureScreenshot", {
3024
- format: "png",
3025
- fromSurface: true,
3026
- // Preserve the #1094 tall-portrait edge-clipping guard on HDR alpha captures.
3027
- captureBeyondViewport: true,
3028
- optimizeForSpeed: false,
3029
- // `true` uses a zero-alpha-aware fast path that crushes real alpha values — observed empirically, CDP docs don't spell it out
3030
- clip: { x: 0, y: 0, width, height, scale: 1 }
3031
- });
3032
- return Buffer.from(result.data, "base64");
3033
- } finally {
3034
- await client.send("Emulation.setDefaultBackgroundColorOverride", {}).catch(() => {
3035
- });
3238
+ var warnedZSignificant = false;
3239
+ var Z_EPSILON = 1e-6;
3240
+ function warnIfZSignificant(parts) {
3241
+ if (warnedZSignificant) return;
3242
+ const a3 = parts[8] ?? 0;
3243
+ const b3 = parts[9] ?? 0;
3244
+ const c1 = parts[2] ?? 0;
3245
+ const c2 = parts[6] ?? 0;
3246
+ const c3 = parts[10] ?? 1;
3247
+ const d1 = parts[3] ?? 0;
3248
+ const d2 = parts[7] ?? 0;
3249
+ const d3 = parts[11] ?? 0;
3250
+ const d4 = parts[15] ?? 1;
3251
+ if (Math.abs(a3) > Z_EPSILON || Math.abs(b3) > Z_EPSILON || Math.abs(c1) > Z_EPSILON || Math.abs(c2) > Z_EPSILON || Math.abs(c3 - 1) > Z_EPSILON || Math.abs(d1) > Z_EPSILON || Math.abs(d2) > Z_EPSILON || Math.abs(d3) > Z_EPSILON || Math.abs(d4 - 1) > Z_EPSILON) {
3252
+ warnedZSignificant = true;
3253
+ console.warn(
3254
+ `[alphaBlit] parseTransformMatrix received a matrix3d with non-trivial 3D components (a3=${a3}, b3=${b3}, c1=${c1}, c2=${c2}, c3=${c3}, d1=${d1}, d2=${d2}, d3=${d3}, d4=${d4}). The engine projects 3D transforms to 2D (m11, m12, m21, m22, m41, m42) and silently discards perspective and out-of-plane rotation. If your composition uses real 3D (rotateX/Y, perspective), the rendered output will not match the studio preview. Z translation (translateZ) is dropped by design and does not trigger this warning. This warning is emitted once per process.`
3255
+ );
3036
3256
  }
3037
3257
  }
3038
- function capturesAlpha(options) {
3039
- return options.transparent ?? options.format === "png";
3258
+
3259
+ // ../engine/src/services/motionBlur.ts
3260
+ var MAX_SAMPLES_PER_FRAME = 64;
3261
+ var DEFAULT_SAMPLES_PER_FRAME = 16;
3262
+ var DEFAULT_SHUTTER_ANGLE = 180;
3263
+ var DEFAULT_SHUTTER_PHASE = -90;
3264
+ var SUB_FRAME_DIVISIONS = 4096;
3265
+ function finiteOr(value, fallback) {
3266
+ return Number.isFinite(value) ? value : fallback;
3040
3267
  }
3041
- var TRANSPARENT_BG_STYLE_ID = "__hf_transparent_bg__";
3042
- async function initTransparentBackground(page, { clearCompositionRoot = false } = {}) {
3043
- const client = await getCdpSession(page);
3044
- await client.send("Emulation.setDefaultBackgroundColorOverride", {
3045
- color: { r: 0, g: 0, b: 0, a: 0 }
3046
- });
3047
- await page.evaluate(
3048
- (styleId, clearCompositionRoot2) => {
3049
- const selector = clearCompositionRoot2 ? "html,body,[data-composition-id]" : "html,body";
3050
- let style = document.getElementById(styleId);
3051
- if (!style) {
3052
- style = document.createElement("style");
3053
- style.id = styleId;
3054
- document.head.appendChild(style);
3055
- }
3056
- style.textContent = `${selector}{background:transparent !important;background-color:transparent !important;background-image:none !important;}`;
3057
- },
3058
- TRANSPARENT_BG_STYLE_ID,
3059
- clearCompositionRoot
3268
+ function resolveMotionBlurPlan(options) {
3269
+ if (!options) return null;
3270
+ const fixedSamplesPerFrame = options.samplesPerFrame === void 0 ? null : Math.min(
3271
+ MAX_SAMPLES_PER_FRAME,
3272
+ Math.max(1, Math.round(finiteOr(options.samplesPerFrame, DEFAULT_SAMPLES_PER_FRAME)))
3060
3273
  );
3274
+ const shutterAngle = finiteOr(options.shutterAngle, DEFAULT_SHUTTER_ANGLE);
3275
+ const shutterPhase = finiteOr(options.shutterPhase, DEFAULT_SHUTTER_PHASE);
3276
+ const blend = options.blend === "linear" ? "linear" : "srgb";
3277
+ return {
3278
+ blend,
3279
+ subFrameDivisions: SUB_FRAME_DIVISIONS,
3280
+ windowStartFrames: shutterPhase / 360,
3281
+ shutterFrames: shutterAngle / 360,
3282
+ fixedSamplesPerFrame
3283
+ };
3061
3284
  }
3062
- async function captureAlphaPng(page, width, height) {
3063
- const client = await getCdpSession(page);
3064
- const result = await client.send("Page.captureScreenshot", {
3065
- format: "png",
3066
- fromSurface: true,
3067
- // Preserve the #1094 tall-portrait edge-clipping guard on HDR alpha captures.
3068
- captureBeyondViewport: true,
3069
- optimizeForSpeed: false,
3070
- // must be false to preserve alpha
3071
- clip: { x: 0, y: 0, width, height, scale: 1 }
3072
- });
3073
- return Buffer.from(result.data, "base64");
3285
+ function sampleTickOffsets(plan, samplesPerFrame) {
3286
+ const offsets = [];
3287
+ for (let k = 0; k < samplesPerFrame; k++) {
3288
+ const offsetFrames = plan.windowStartFrames + (k + 0.5) / samplesPerFrame * plan.shutterFrames;
3289
+ offsets.push(Math.round(offsetFrames * plan.subFrameDivisions));
3290
+ }
3291
+ return offsets;
3074
3292
  }
3075
- var DOM_LAYER_MASK_STYLE_ID = "__hf_dom_layer_mask__";
3076
- var DOM_LAYER_MASK_HIDDEN_ATTR = "data-hf-dom-layer-mask-hidden";
3077
- var DOM_LAYER_MASK_PREV_VISIBILITY_ATTR = "data-hf-dom-layer-mask-prev-visibility";
3078
- var DOM_LAYER_MASK_PREV_PRIORITY_ATTR = "data-hf-dom-layer-mask-prev-priority";
3079
- async function applyDomLayerMask(page, showIds, extraHideIds) {
3080
- await page.evaluate(
3081
- // fallow-ignore-next-line complexity
3082
- (args) => {
3083
- const existing = document.getElementById(args.styleId);
3084
- if (existing) existing.remove();
3085
- const renderFrameId = (id) => `${args.renderFramePrefix}${id}${args.renderFrameSuffix}`;
3086
- const restoreMaskedElements = () => {
3087
- const masked = document.querySelectorAll(`[${args.hiddenAttr}="1"]`);
3088
- for (const node of masked) {
3089
- if (!(node instanceof HTMLElement)) continue;
3090
- const prevVisibility = node.getAttribute(args.prevVisibilityAttr);
3091
- const prevPriority = node.getAttribute(args.prevPriorityAttr);
3092
- if (prevVisibility === null) {
3093
- node.style.removeProperty("visibility");
3094
- } else {
3095
- node.style.setProperty("visibility", prevVisibility, prevPriority ?? "");
3096
- }
3097
- node.removeAttribute(args.hiddenAttr);
3098
- node.removeAttribute(args.prevVisibilityAttr);
3099
- node.removeAttribute(args.prevPriorityAttr);
3100
- }
3101
- };
3102
- restoreMaskedElements();
3103
- const rememberAndHideElement = (el) => {
3104
- if (el.getAttribute(args.hiddenAttr) !== "1") {
3105
- const prevVisibility = el.style.getPropertyValue("visibility");
3106
- const prevPriority = typeof el.style.getPropertyPriority === "function" ? el.style.getPropertyPriority("visibility") : "";
3107
- if (prevVisibility) {
3108
- el.setAttribute(args.prevVisibilityAttr, prevVisibility);
3109
- } else {
3110
- el.removeAttribute(args.prevVisibilityAttr);
3111
- }
3112
- if (prevPriority) {
3113
- el.setAttribute(args.prevPriorityAttr, prevPriority);
3114
- } else {
3115
- el.removeAttribute(args.prevPriorityAttr);
3116
- }
3117
- el.setAttribute(args.hiddenAttr, "1");
3118
- }
3119
- el.style.setProperty("visibility", "hidden", "important");
3120
- };
3121
- const hiddenTimedDescendants = [];
3122
- const rememberHiddenTimedDescendants = (root) => {
3123
- for (const node of root.querySelectorAll("[data-start]")) {
3124
- if (!(node instanceof HTMLElement)) continue;
3125
- const computed = window.getComputedStyle(node);
3126
- if (computed.visibility !== "hidden" && computed.display !== "none") continue;
3127
- hiddenTimedDescendants.push(node);
3128
- }
3129
- };
3130
- const showSelectors = [];
3131
- for (const id of args.show) {
3132
- const el = window.__hfMediaEl?.(id) ?? document.getElementById(id);
3133
- if (el) rememberHiddenTimedDescendants(el);
3134
- if (el?.hasAttribute(args.renderIdAttr)) {
3135
- const attrEscaped = id.replace(/\\/g, "\\\\").replace(/"/g, '\\"');
3136
- const byRenderId = `[${args.renderIdAttr}="${attrEscaped}"]`;
3137
- showSelectors.push(byRenderId, `${byRenderId} *`);
3138
- } else {
3139
- const escaped = CSS.escape(id);
3140
- showSelectors.push(`#${escaped}`, `#${escaped} *`);
3141
- }
3142
- const renderEscaped = CSS.escape(renderFrameId(id));
3143
- showSelectors.push(`#${renderEscaped}`, `#${renderEscaped} *`);
3144
- const colorGradingEscaped = CSS.escape(`${args.canvasIdPrefix}${id}`);
3145
- showSelectors.push(`#${colorGradingEscaped}`, `#${colorGradingEscaped} *`);
3146
- }
3147
- const massHideRule = "body *{visibility:hidden !important;}";
3148
- const showRule = showSelectors.length === 0 ? "" : `${showSelectors.join(",")}{visibility:visible !important;}`;
3149
- const style = document.createElement("style");
3150
- style.id = args.styleId;
3151
- style.textContent = `${massHideRule}
3152
- ${showRule}`;
3153
- document.head.appendChild(style);
3154
- for (const el of hiddenTimedDescendants) {
3155
- rememberAndHideElement(el);
3156
- }
3157
- for (const id of args.hide) {
3158
- const el = window.__hfMediaEl?.(id) ?? document.getElementById(id);
3159
- if (el instanceof HTMLElement) {
3160
- rememberAndHideElement(el);
3161
- }
3162
- const img = document.getElementById(renderFrameId(id));
3163
- if (img) {
3164
- rememberAndHideElement(img);
3165
- }
3166
- const colorGradingCanvas = document.getElementById(`${args.canvasIdPrefix}${id}`);
3167
- if (colorGradingCanvas instanceof HTMLElement) {
3168
- rememberAndHideElement(colorGradingCanvas);
3169
- }
3170
- }
3171
- },
3172
- {
3173
- show: showIds,
3174
- hide: extraHideIds,
3175
- renderIdAttr: MEDIA_RENDER_ID_ATTR,
3176
- renderFramePrefix: RENDER_FRAME_ID_PREFIX,
3177
- renderFrameSuffix: RENDER_FRAME_ID_SUFFIX,
3178
- styleId: DOM_LAYER_MASK_STYLE_ID,
3179
- hiddenAttr: DOM_LAYER_MASK_HIDDEN_ATTR,
3180
- prevVisibilityAttr: DOM_LAYER_MASK_PREV_VISIBILITY_ATTR,
3181
- prevPriorityAttr: DOM_LAYER_MASK_PREV_PRIORITY_ATTR,
3182
- canvasIdPrefix: HF_COLOR_GRADING_CANVAS_ID_PREFIX
3183
- }
3293
+ function motionBlurSampleTimes(plan, frameIndex, fps, samplesPerFrame) {
3294
+ const grid = fps * plan.subFrameDivisions;
3295
+ const frameTicks = frameIndex * plan.subFrameDivisions;
3296
+ return sampleTickOffsets(plan, samplesPerFrame).map(
3297
+ (offset) => Math.max(0, frameTicks + offset) / grid
3298
+ );
3299
+ }
3300
+ function motionBlurProbeTimes(plan, frameIndex, fps) {
3301
+ const grid = fps * plan.subFrameDivisions;
3302
+ const frameTicks = frameIndex * plan.subFrameDivisions;
3303
+ const startTick = Math.round(plan.windowStartFrames * plan.subFrameDivisions);
3304
+ const endTick = Math.round(
3305
+ (plan.windowStartFrames + plan.shutterFrames) * plan.subFrameDivisions
3184
3306
  );
3307
+ return {
3308
+ windowStart: Math.max(0, frameTicks + startTick) / grid,
3309
+ windowEnd: Math.max(0, frameTicks + endTick) / grid
3310
+ };
3311
+ }
3312
+ function motionBlurWindowIsStatic(plan, frameIndex, staticFrames) {
3313
+ const worstCaseSamples = plan.fixedSamplesPerFrame ?? MAX_SAMPLES_PER_FRAME;
3314
+ const inset = plan.shutterFrames / (2 * worstCaseSamples);
3315
+ const minOffsetFrames = plan.windowStartFrames + inset;
3316
+ const maxOffsetFrames = plan.windowStartFrames + plan.shutterFrames - inset;
3317
+ const first = Math.floor(frameIndex - 1 + Math.min(0, minOffsetFrames));
3318
+ const last = Math.floor(frameIndex + Math.max(0, maxOffsetFrames)) + 1;
3319
+ for (let frame = first; frame <= last; frame++) {
3320
+ if (!staticFrames.has(frame)) return false;
3321
+ }
3322
+ return true;
3323
+ }
3324
+ var ADAPTIVE_SAMPLE_STEPS = [
3325
+ { maxDiff: 3, samples: DEFAULT_SAMPLES_PER_FRAME },
3326
+ { maxDiff: 6, samples: 32 },
3327
+ { maxDiff: Infinity, samples: MAX_SAMPLES_PER_FRAME }
3328
+ ];
3329
+ function adaptiveSampleCount(diff) {
3330
+ for (const step of ADAPTIVE_SAMPLE_STEPS) {
3331
+ if (diff <= step.maxDiff) return step.samples;
3332
+ }
3333
+ return MAX_SAMPLES_PER_FRAME;
3334
+ }
3335
+ var SPATIAL_TWEEN_PROPERTIES = [
3336
+ "x",
3337
+ "y",
3338
+ "z",
3339
+ "xPercent",
3340
+ "yPercent",
3341
+ "rotation",
3342
+ "rotate",
3343
+ "rotationX",
3344
+ "rotationY",
3345
+ "rotationZ",
3346
+ "scale",
3347
+ "scaleX",
3348
+ "scaleY",
3349
+ "scaleZ",
3350
+ "skewX",
3351
+ "skewY",
3352
+ "perspective",
3353
+ "transformPerspective",
3354
+ "top",
3355
+ "left",
3356
+ "right",
3357
+ "bottom",
3358
+ "width",
3359
+ "height",
3360
+ "translate",
3361
+ "translateX",
3362
+ "translateY",
3363
+ "translateZ",
3364
+ "transform"
3365
+ ];
3366
+ function probeDiffMagnitude(a, b) {
3367
+ const decodedA = decodePng(a);
3368
+ const decodedB = decodePng(b);
3369
+ if (decodedA.width !== decodedB.width || decodedA.height !== decodedB.height) {
3370
+ throw new Error(
3371
+ `probeDiffMagnitude: sample geometry mismatch (${decodedA.width}x${decodedA.height} vs ${decodedB.width}x${decodedB.height})`
3372
+ );
3373
+ }
3374
+ let sum = 0;
3375
+ for (let i = 0; i < decodedA.data.length; i++) {
3376
+ sum += Math.abs(decodedA.data[i] - decodedB.data[i]);
3377
+ }
3378
+ return sum / decodedA.data.length;
3185
3379
  }
3186
- async function removeDomLayerMask(page, _extraHideIds) {
3187
- await page.evaluate(
3188
- (args) => {
3189
- const style = document.getElementById(args.styleId);
3190
- if (style) style.remove();
3191
- const masked = document.querySelectorAll(`[${args.hiddenAttr}="1"]`);
3192
- for (const node of masked) {
3193
- if (!(node instanceof HTMLElement)) continue;
3194
- const prevVisibility = node.getAttribute(args.prevVisibilityAttr);
3195
- const prevPriority = node.getAttribute(args.prevPriorityAttr);
3196
- if (prevVisibility === null) {
3197
- node.style.removeProperty("visibility");
3198
- } else {
3199
- node.style.setProperty("visibility", prevVisibility, prevPriority ?? "");
3200
- }
3201
- node.removeAttribute(args.hiddenAttr);
3202
- node.removeAttribute(args.prevVisibilityAttr);
3203
- node.removeAttribute(args.prevPriorityAttr);
3204
- }
3205
- },
3206
- {
3207
- styleId: DOM_LAYER_MASK_STYLE_ID,
3208
- hiddenAttr: DOM_LAYER_MASK_HIDDEN_ATTR,
3209
- prevVisibilityAttr: DOM_LAYER_MASK_PREV_VISIBILITY_ATTR,
3210
- prevPriorityAttr: DOM_LAYER_MASK_PREV_PRIORITY_ATTR
3211
- }
3212
- );
3380
+ var SRGB_TO_LINEAR = (() => {
3381
+ const lut = new Float64Array(256);
3382
+ for (let i = 0; i < 256; i++) lut[i] = srgbByteToLinear(i);
3383
+ return lut;
3384
+ })();
3385
+ var SRGB_PASSTHROUGH = (() => {
3386
+ const lut = new Float64Array(256);
3387
+ for (let i = 0; i < 256; i++) lut[i] = i;
3388
+ return lut;
3389
+ })();
3390
+ function linearToByte(value) {
3391
+ const c = value <= 31308e-7 ? value * 12.92 : 1.055 * Math.pow(value, 1 / 2.4) - 0.055;
3392
+ return clampByte(c * 255);
3213
3393
  }
3214
- async function ensureRenderFrameSiblings(page) {
3215
- await page.evaluate(
3216
- (prefix, suffix) => {
3217
- for (const video of Array.from(
3218
- document.querySelectorAll("video[data-start]")
3219
- )) {
3220
- const next = video.nextElementSibling;
3221
- if (next !== null && next.classList.contains("__render_frame__")) continue;
3222
- const img = document.createElement("img");
3223
- img.classList.add("__render_frame__");
3224
- img.id = `${prefix}${window.__hfMediaId?.(video) || video.id}${suffix}`;
3225
- img.style.pointerEvents = "none";
3226
- img.style.position = "absolute";
3227
- img.style.visibility = "hidden";
3228
- video.parentNode?.insertBefore(img, video.nextSibling);
3229
- }
3230
- },
3231
- RENDER_FRAME_ID_PREFIX,
3232
- RENDER_FRAME_ID_SUFFIX
3233
- );
3394
+ function clampByte(value) {
3395
+ return Math.min(255, Math.max(0, Math.round(value)));
3234
3396
  }
3235
- async function injectVideoFramesBatch(page, updates, restyleIds = []) {
3236
- if (updates.length === 0 && restyleIds.length === 0) return [];
3237
- return withVideoFrameSources(
3238
- page,
3239
- updates,
3240
- (resolved) => injectResolvedVideoFramesBatch(page, resolved, restyleIds)
3241
- );
3397
+ var MotionBlurAccumulator = class {
3398
+ toWorking;
3399
+ fromWorking;
3400
+ /** Premultiplied r, g, b and alpha sums per pixel. Null until the first sample sets the size. */
3401
+ sums = null;
3402
+ width = 0;
3403
+ height = 0;
3404
+ count = 0;
3405
+ constructor(blend) {
3406
+ this.toWorking = blend === "linear" ? SRGB_TO_LINEAR : SRGB_PASSTHROUGH;
3407
+ this.fromWorking = blend === "linear" ? linearToByte : clampByte;
3408
+ }
3409
+ /** Fold one captured sample PNG into the running average. */
3410
+ add(png) {
3411
+ const { width, height, data } = decodePng(png);
3412
+ if (!this.sums) {
3413
+ this.width = width;
3414
+ this.height = height;
3415
+ this.sums = new Float32Array(width * height * 4);
3416
+ } else if (width !== this.width || height !== this.height) {
3417
+ throw new Error(
3418
+ `MotionBlurAccumulator: sample geometry mismatch (${width}x${height} vs ${this.width}x${this.height})`
3419
+ );
3420
+ }
3421
+ const sums = this.sums;
3422
+ const toWorking = this.toWorking;
3423
+ for (let i = 0; i < sums.length; i += 4) {
3424
+ const alpha = data[i + 3] / 255;
3425
+ sums[i] = sums[i] + toWorking[data[i]] * alpha;
3426
+ sums[i + 1] = sums[i + 1] + toWorking[data[i + 1]] * alpha;
3427
+ sums[i + 2] = sums[i + 2] + toWorking[data[i + 2]] * alpha;
3428
+ sums[i + 3] = sums[i + 3] + alpha;
3429
+ }
3430
+ this.count += 1;
3431
+ }
3432
+ /** Un-premultiply and encode the average. Throws if no sample was ever added. */
3433
+ finish() {
3434
+ const sums = this.sums;
3435
+ if (!sums) throw new Error("MotionBlurAccumulator: no samples");
3436
+ const out = new Uint8Array(sums.length);
3437
+ for (let i = 0; i < sums.length; i += 4) {
3438
+ const alphaSum = sums[i + 3];
3439
+ out[i + 3] = clampByte(alphaSum / this.count * 255);
3440
+ if (alphaSum === 0) continue;
3441
+ const scale = 1 / alphaSum;
3442
+ out[i] = this.fromWorking(sums[i] * scale);
3443
+ out[i + 1] = this.fromWorking(sums[i + 1] * scale);
3444
+ out[i + 2] = this.fromWorking(sums[i + 2] * scale);
3445
+ }
3446
+ return { width: this.width, height: this.height, data: out };
3447
+ }
3448
+ };
3449
+
3450
+ // ../engine/src/services/pageMotionBlur.ts
3451
+ function pageOffReason(options) {
3452
+ if (options.motionBlur) return "engine-motion-blur";
3453
+ if (options.pageMotionBlur === "off") return "preview-unsupported";
3454
+ return options.pageMotionBlur ?? null;
3242
3455
  }
3243
- async function injectResolvedVideoFramesBatch(page, updates, restyleIds) {
3244
- const items = [
3245
- ...updates,
3246
- ...restyleIds.map((videoId) => ({ videoId }))
3247
- ].map((item) => ({ ...item, frameId: renderFrameIdForRenderId(item.videoId) }));
3248
- return await page.evaluate(
3249
- // fallow-ignore-next-line complexity
3250
- async (items2, visualProperties, colorGradingSourceHiddenAttr) => {
3251
- const injectedIds = [];
3252
- const pendingDecodes = [];
3253
- const imagesToPublish = [];
3254
- const replacementLayoutProperties = /* @__PURE__ */ new Set([
3255
- "width",
3256
- "height",
3257
- "top",
3258
- "left",
3259
- "right",
3260
- "bottom",
3261
- "inset"
3262
- ]);
3263
- const isVisualAncestorHidden = (el) => {
3264
- let parent = el.parentElement;
3265
- while (parent !== null && parent !== document.documentElement) {
3266
- const computed = window.getComputedStyle(parent);
3267
- if (computed.display === "none") return true;
3268
- if (computed.visibility === "hidden" && (parent.hasAttribute("data-composition-src") || parent.hasAttribute("data-composition-file"))) {
3269
- return true;
3270
- }
3271
- parent = parent.parentElement;
3272
- }
3273
- return false;
3274
- };
3275
- for (const item of items2) {
3276
- const video = window.__hfMediaEl?.(item.videoId) ?? document.getElementById(item.videoId);
3277
- if (!video) continue;
3278
- let img = video.nextElementSibling;
3279
- const hasImg = img !== null && img.classList.contains("__render_frame__");
3280
- const restyleOnly = item.dataUri === void 0;
3281
- if (restyleOnly && !hasImg) continue;
3282
- if (isVisualAncestorHidden(video)) {
3283
- if (hasImg && img) img.style.setProperty("visibility", "hidden", "important");
3284
- continue;
3285
- }
3286
- const isNewImage = !hasImg;
3287
- const computedStyle = window.getComputedStyle(video);
3288
- const opacityParsed = parseFloat(computedStyle.opacity);
3289
- const computedOpacity = video.hasAttribute(colorGradingSourceHiddenAttr) ? 1 : Number.isNaN(opacityParsed) ? 1 : opacityParsed;
3290
- const videoRect = video.getBoundingClientRect();
3291
- const videoBox = {
3292
- left: Number.isFinite(video.offsetLeft) ? video.offsetLeft : 0,
3293
- top: Number.isFinite(video.offsetTop) ? video.offsetTop : 0,
3294
- width: video.offsetWidth > 0 ? video.offsetWidth : videoRect.width,
3295
- height: video.offsetHeight > 0 ? video.offsetHeight : videoRect.height
3296
- };
3297
- if (isNewImage) {
3298
- img = document.createElement("img");
3299
- img.classList.add("__render_frame__");
3300
- img.id = item.frameId;
3301
- img.style.pointerEvents = "none";
3302
- video.parentNode?.insertBefore(img, video.nextSibling);
3303
- }
3304
- if (!img) continue;
3305
- for (const property of visualProperties) {
3306
- if (property === "opacity") continue;
3307
- if (replacementLayoutProperties.has(property)) {
3308
- continue;
3309
- }
3310
- const value = computedStyle.getPropertyValue(property);
3311
- if (value) {
3312
- img.style.setProperty(property, value);
3313
- }
3314
- }
3315
- img.style.position = "absolute";
3316
- img.style.inset = "auto";
3317
- img.style.left = `${videoBox.left}px`;
3318
- img.style.top = `${videoBox.top}px`;
3319
- img.style.right = "auto";
3320
- img.style.bottom = "auto";
3321
- img.style.width = `${videoBox.width}px`;
3322
- img.style.height = `${videoBox.height}px`;
3323
- img.style.boxSizing = "border-box";
3324
- img.style.objectFit = computedStyle.objectFit;
3325
- img.style.objectPosition = computedStyle.objectPosition;
3326
- img.style.zIndex = computedStyle.zIndex;
3327
- img.style.setProperty("visibility", "hidden", "important");
3328
- img.decoding = "sync";
3329
- if (item.dataUri !== void 0 && img.getAttribute("src") !== item.dataUri) {
3330
- if (item.crossOrigin) img.crossOrigin = item.crossOrigin;
3331
- else img.removeAttribute("crossorigin");
3332
- img.src = item.dataUri;
3333
- const source = item.sourceLabel ?? (item.dataUri.startsWith("data:") ? "inline frame" : item.dataUri);
3334
- pendingDecodes.push(
3335
- img.decode().catch((error) => {
3336
- throw new Error(
3337
- `Video frame for "${item.videoId}" failed to load (${source}): ${error instanceof Error ? error.message : String(error)}`
3338
- );
3339
- })
3340
- );
3341
- }
3342
- img.style.opacity = String(computedOpacity);
3343
- imagesToPublish.push(img);
3344
- video.style.setProperty("visibility", "hidden", "important");
3345
- video.style.setProperty("pointer-events", "none", "important");
3346
- if (!restyleOnly) injectedIds.push(item.videoId);
3347
- }
3348
- if (pendingDecodes.length > 0) {
3349
- await Promise.all(pendingDecodes);
3350
- }
3351
- for (const img of imagesToPublish) img.style.visibility = "visible";
3352
- if (imagesToPublish.length > 0) {
3353
- const redraw = window.__hf?.colorGrading?.redraw;
3354
- redraw?.();
3355
- }
3356
- return injectedIds;
3456
+ async function installPageMotionBlur(page, options) {
3457
+ await page.evaluateOnNewDocument(acceleratedCanvasTrackerSource());
3458
+ const scale = options.deviceScaleFactor ?? 1;
3459
+ if (scale > 1) {
3460
+ await page.evaluateOnNewDocument(
3461
+ (key, v) => {
3462
+ window[key] = v;
3463
+ },
3464
+ PAGE_DEVICE_SCALE_GLOBAL,
3465
+ scale
3466
+ );
3467
+ }
3468
+ const off = pageOffReason(options);
3469
+ if (!off) return;
3470
+ await page.evaluateOnNewDocument(
3471
+ (key, v) => {
3472
+ window[key] = v;
3357
3473
  },
3358
- items,
3359
- [...MEDIA_VISUAL_STYLE_PROPERTIES],
3360
- COLOR_GRADING_SOURCE_HIDDEN_ATTR
3474
+ PAGE_MOTION_BLUR_OFF_GLOBAL,
3475
+ off
3361
3476
  );
3362
3477
  }
3363
- async function syncVideoFrameVisibility(page, activeVideoIds) {
3364
- await page.evaluate(
3365
- // fallow-ignore-next-line complexity
3366
- (ids, colorGradingSourceHiddenAttr) => {
3367
- const isVisualAncestorHidden = (el) => {
3368
- let parent = el.parentElement;
3369
- while (parent !== null && parent !== document.documentElement) {
3370
- const computed = window.getComputedStyle(parent);
3371
- if (computed.display === "none") return true;
3372
- if (computed.visibility === "hidden" && (parent.hasAttribute("data-composition-src") || parent.hasAttribute("data-composition-file"))) {
3373
- return true;
3374
- }
3375
- parent = parent.parentElement;
3376
- }
3377
- return false;
3478
+ async function readPageMotionBlur(page) {
3479
+ return page.evaluate(() => {
3480
+ const api = Reflect.get(window, "__hfMotionBlur");
3481
+ const report = api && typeof api === "object" ? Reflect.get(api, "report") : null;
3482
+ const got = typeof report === "function" ? report() : null;
3483
+ if (!got || typeof got !== "object") return null;
3484
+ const tier = Reflect.get(got, "tier");
3485
+ return {
3486
+ state: String(Reflect.get(got, "state")),
3487
+ code: String(Reflect.get(got, "reasonCode")),
3488
+ movers: Number(Reflect.get(got, "movers")),
3489
+ failedFrames: Number(Reflect.get(got, "failedFrames")) || 0,
3490
+ tier: typeof tier === "string" ? tier : null
3491
+ };
3492
+ });
3493
+ }
3494
+ var formatPageMotionBlur = (r) => `[motion-blur] ${r.state} reasonCode=${r.code} movers=${r.movers} failedFrames=${r.failedFrames}${r.tier ? ` tier=${r.tier}` : ""}`;
3495
+ async function describePageMotionBlur(page) {
3496
+ const r = await readPageMotionBlur(page);
3497
+ return r && formatPageMotionBlur(r);
3498
+ }
3499
+ async function describePageMotionBlurAtEnd(page, timeoutMs = 1500) {
3500
+ let timer;
3501
+ const stuck = new Promise((resolve2) => {
3502
+ timer = setTimeout(() => resolve2(null), timeoutMs);
3503
+ });
3504
+ try {
3505
+ const r = await Promise.race([readPageMotionBlur(page), stuck]);
3506
+ return r && r.failedFrames > 0 ? `${formatPageMotionBlur(r)} (session end)` : null;
3507
+ } catch {
3508
+ return null;
3509
+ } finally {
3510
+ clearTimeout(timer);
3511
+ }
3512
+ }
3513
+
3514
+ // ../engine/src/services/videoFrameTransport.ts
3515
+ import { randomUUID } from "crypto";
3516
+ var base64ImagePrefix = /^data:(image\/[\w.+-]+);base64,/;
3517
+ var transports = /* @__PURE__ */ new WeakMap();
3518
+ async function createTransport(page) {
3519
+ const pageUrl = new URL(page.url());
3520
+ const origin = /^https?:$/.test(pageUrl.protocol) ? pageUrl.origin : "https://hyperframes-render.invalid";
3521
+ const prefix = `${origin}/__hyperframes_video_frames__/${randomUUID()}/`;
3522
+ const responses = /* @__PURE__ */ new Map();
3523
+ const client = await page.createCDPSession();
3524
+ client.on("Fetch.requestPaused", (event) => {
3525
+ const frame = responses.get(event.request.url);
3526
+ void fulfillFrame(client, event.requestId, frame);
3527
+ });
3528
+ try {
3529
+ await client.send("Fetch.enable", {
3530
+ patterns: [{ urlPattern: `${prefix}*`, requestStage: "Request" }]
3531
+ });
3532
+ } catch (error) {
3533
+ await client.detach().catch(() => {
3534
+ });
3535
+ throw error;
3536
+ }
3537
+ page.once("close", () => responses.clear());
3538
+ return { prefix, nextId: 0, responses };
3539
+ }
3540
+ async function fulfillFrame(client, requestId, frame) {
3541
+ try {
3542
+ await client.send("Fetch.fulfillRequest", {
3543
+ requestId,
3544
+ responseCode: frame ? 200 : 404,
3545
+ responseHeaders: [
3546
+ { name: "Content-Type", value: frame?.contentType ?? "text/plain" },
3547
+ { name: "Cache-Control", value: "no-store" },
3548
+ { name: "Access-Control-Allow-Origin", value: "*" }
3549
+ ],
3550
+ body: frame?.body ?? ""
3551
+ });
3552
+ } catch (error) {
3553
+ if (frame) frame.error = error;
3554
+ await client.send("Fetch.failRequest", { requestId, errorReason: "Failed" }).catch(() => {
3555
+ });
3556
+ }
3557
+ }
3558
+ async function withVideoFrameSources(page, updates, inject) {
3559
+ if (!updates.some((update) => base64ImagePrefix.test(update.dataUri))) return inject(updates);
3560
+ let pending = transports.get(page);
3561
+ if (!pending) {
3562
+ pending = createTransport(page);
3563
+ transports.set(page, pending);
3564
+ }
3565
+ let transport;
3566
+ try {
3567
+ transport = await pending;
3568
+ } catch (error) {
3569
+ transports.delete(page);
3570
+ throw error;
3571
+ }
3572
+ const registered = [];
3573
+ try {
3574
+ const resolved = updates.map((update) => {
3575
+ const match = base64ImagePrefix.exec(update.dataUri);
3576
+ if (!match) return update;
3577
+ const frame = {
3578
+ contentType: match[1] ?? "image/png",
3579
+ body: update.dataUri.slice(match[0].length)
3378
3580
  };
3379
- const active = new Set(ids);
3380
- const setColorGradingVisibility = window.__hf?.colorGrading?.setSourceVisibility;
3381
- const videos = Array.from(
3382
- document.querySelectorAll("video[data-start]")
3383
- );
3384
- for (const video of videos) {
3385
- const img = video.nextElementSibling;
3386
- const hasImg = img && img.classList.contains("__render_frame__");
3387
- const ancestorHidden = isVisualAncestorHidden(video);
3388
- const visible = active.has(window.__hfMediaId?.(video) || video.id) && !ancestorHidden;
3389
- if (visible) {
3390
- video.style.setProperty("visibility", "hidden", "important");
3391
- video.style.setProperty("pointer-events", "none", "important");
3392
- if (hasImg) {
3393
- if (video.hasAttribute(colorGradingSourceHiddenAttr)) img.style.opacity = "1";
3394
- img.style.visibility = "visible";
3395
- }
3396
- } else {
3397
- video.style.setProperty("visibility", "hidden", "important");
3398
- video.style.setProperty("pointer-events", "none", "important");
3399
- if (hasImg) {
3400
- img.style.setProperty("visibility", "hidden", "important");
3401
- }
3402
- }
3403
- setColorGradingVisibility?.(video, visible);
3404
- }
3405
- },
3406
- activeVideoIds,
3407
- COLOR_GRADING_SOURCE_HIDDEN_ATTR
3408
- );
3581
+ const url = `${transport.prefix}${transport.nextId++}`;
3582
+ transport.responses.set(url, frame);
3583
+ registered.push({ url, frame });
3584
+ return {
3585
+ ...update,
3586
+ dataUri: url,
3587
+ crossOrigin: "anonymous",
3588
+ sourceLabel: "inline frame"
3589
+ };
3590
+ });
3591
+ return await inject(resolved);
3592
+ } catch (error) {
3593
+ throw registered.find(({ frame }) => frame.error !== void 0)?.frame.error ?? error;
3594
+ } finally {
3595
+ for (const { url } of registered) transport.responses.delete(url);
3596
+ }
3409
3597
  }
3410
3598
 
3411
- // ../engine/src/services/drawElementService.ts
3412
- var DE_CANVAS_NOT_INITIALIZED_CODE = "HF_DE_CANVAS_NOT_INITIALIZED";
3413
- function resolveDrawElementCaptureMode(isSwiftShader, transparent) {
3414
- void transparent;
3415
- if (isSwiftShader) return "screenshot";
3416
- return "drawelement";
3599
+ // ../engine/src/services/screenshotService.ts
3600
+ var cdpSessionCache = /* @__PURE__ */ new WeakMap();
3601
+ async function getCdpSession(page) {
3602
+ let client = cdpSessionCache.get(page);
3603
+ if (!client) {
3604
+ client = await page.createCDPSession();
3605
+ cdpSessionCache.set(page, client);
3606
+ }
3607
+ return client;
3417
3608
  }
3418
- function instrumentAcceleratedCanvases() {
3419
- const w = window;
3420
- w.__hf_accel_canvases = [];
3421
- w.__hf_canvas_2d = [];
3422
- const orig = HTMLCanvasElement.prototype.getContext;
3423
- HTMLCanvasElement.prototype.getContext = function(type, attrs) {
3424
- const isGl = type === "webgl" || type === "webgl2" || type === "experimental-webgl";
3425
- const isAccel = isGl || type === "webgpu";
3426
- const finalAttrs = isGl ? { ...attrs, preserveDrawingBuffer: true } : attrs;
3427
- const ctx = orig.call(this, type, finalAttrs);
3428
- if (ctx && isAccel) {
3429
- const list = w.__hf_accel_canvases ?? [];
3430
- if (!list.includes(this)) list.push(this);
3431
- w.__hf_accel_canvases = list;
3609
+ function shouldDefaultCaptureBeyondViewport(browserVersion, platform = process.platform) {
3610
+ return platform === "darwin" && browserVersion.startsWith("Chrome/");
3611
+ }
3612
+ async function probeBeginFrameLiveness(page, timeoutMs, frameTimeTicks, intervalMs) {
3613
+ const client = await getCdpSession(page);
3614
+ const params = {};
3615
+ if (typeof frameTimeTicks === "number") params.frameTimeTicks = frameTimeTicks;
3616
+ if (typeof intervalMs === "number") params.interval = intervalMs;
3617
+ let timer;
3618
+ try {
3619
+ return await Promise.race([
3620
+ client.send("HeadlessExperimental.beginFrame", params).then(() => true).catch(() => false),
3621
+ new Promise((resolve2) => {
3622
+ timer = setTimeout(() => resolve2(false), timeoutMs);
3623
+ })
3624
+ ]);
3625
+ } finally {
3626
+ if (timer) clearTimeout(timer);
3627
+ }
3628
+ }
3629
+ var lastFrameCache = /* @__PURE__ */ new WeakMap();
3630
+ var PENDING_FRAME_RETRIES = 5;
3631
+ async function sendBeginFrame(client, params) {
3632
+ for (let attempt = 0; ; attempt++) {
3633
+ try {
3634
+ return await client.send("HeadlessExperimental.beginFrame", params);
3635
+ } catch (err) {
3636
+ const msg = err instanceof Error ? err.message : String(err);
3637
+ const isPending = msg.includes("Another frame is pending");
3638
+ if (isPending && attempt < PENDING_FRAME_RETRIES) {
3639
+ await new Promise((r) => setTimeout(r, 50 * 2 ** attempt));
3640
+ continue;
3641
+ }
3642
+ if (isPending) {
3643
+ throw new Error(
3644
+ `[BeginFrame] Frame still pending after ${PENDING_FRAME_RETRIES} retries: CPU overloaded by parallel renders. Reduce concurrent renders or use --docker for isolation.`
3645
+ );
3646
+ }
3647
+ throw err;
3432
3648
  }
3433
- if (ctx && type === "2d") {
3434
- const list2d = w.__hf_canvas_2d ?? [];
3435
- if (!list2d.includes(this)) list2d.push(this);
3436
- w.__hf_canvas_2d = list2d;
3649
+ }
3650
+ }
3651
+ async function beginFrameCapture(page, options, frameTimeTicks, interval) {
3652
+ const client = await getCdpSession(page);
3653
+ const isPng = options.format === "png";
3654
+ const screenshot = {
3655
+ format: isPng ? "png" : "jpeg",
3656
+ quality: isPng ? void 0 : options.quality ?? 80,
3657
+ optimizeForSpeed: true
3658
+ };
3659
+ const result = await sendBeginFrame(client, { frameTimeTicks, interval, screenshot });
3660
+ let buffer;
3661
+ if (result.screenshotData) {
3662
+ buffer = Buffer.from(result.screenshotData, "base64");
3663
+ lastFrameCache.set(page, buffer);
3664
+ } else {
3665
+ const cached = lastFrameCache.get(page);
3666
+ if (cached) {
3667
+ buffer = cached;
3668
+ } else {
3669
+ const fallback = await sendBeginFrame(client, {
3670
+ frameTimeTicks: frameTimeTicks + 1e-3,
3671
+ interval,
3672
+ screenshot
3673
+ });
3674
+ buffer = fallback.screenshotData ? Buffer.from(fallback.screenshotData, "base64") : Buffer.alloc(0);
3675
+ if (buffer.length > 0) lastFrameCache.set(page, buffer);
3437
3676
  }
3438
- return ctx;
3677
+ }
3678
+ return {
3679
+ buffer,
3680
+ hasDamage: result.hasDamage
3439
3681
  };
3440
3682
  }
3441
- function classifyGpuRenderer(renderer) {
3442
- if (!renderer) return void 0;
3443
- const r = renderer.toLowerCase();
3444
- const backend = r.includes("swiftshader") ? "swiftshader" : r.includes("metal") ? "metal" : r.includes("direct3d11") || r.includes("d3d11") ? "d3d11" : r.includes("direct3d9") || r.includes("d3d9") ? "d3d9" : r.includes("vulkan") ? "vulkan" : r.includes("opengl") || r.includes("angle") ? "opengl" : "other";
3445
- const vendor = r.includes("apple") ? "apple" : r.includes("nvidia") ? "nvidia" : r.includes("amd") || r.includes("radeon") ? "amd" : r.includes("intel") ? "intel" : r.includes("microsoft") ? "microsoft" : "other";
3446
- return `${backend}/${vendor}`;
3683
+ async function pageContentExceedsCaptureHeight(page, requestedHeight) {
3684
+ const scrollHeight = await page.evaluate(() => document.documentElement.scrollHeight);
3685
+ return scrollHeight > requestedHeight + 1;
3447
3686
  }
3448
- async function detectGpuBackend(page) {
3449
- return page.evaluate(() => {
3450
- const canvas = document.createElement("canvas");
3451
- const gl = canvas.getContext("webgl") || canvas.getContext("experimental-webgl");
3452
- if (!gl) return { isSwiftShader: false, renderer: null };
3453
- const ext = gl.getExtension("WEBGL_debug_renderer_info");
3454
- if (!ext) return { isSwiftShader: false, renderer: null };
3455
- const renderer = gl.getParameter(ext.UNMASKED_RENDERER_WEBGL);
3456
- return { isSwiftShader: renderer.toLowerCase().includes("swiftshader"), renderer };
3687
+ async function pageScreenshotCapture(page, options) {
3688
+ const client = await getCdpSession(page);
3689
+ const isPng = options.format === "png";
3690
+ const dpr = options.deviceScaleFactor ?? 1;
3691
+ const clip = { x: 0, y: 0, width: options.width, height: options.height, scale: dpr };
3692
+ const result = await client.send("Page.captureScreenshot", {
3693
+ format: isPng ? "png" : "jpeg",
3694
+ quality: isPng ? void 0 : options.quality ?? 80,
3695
+ fromSurface: true,
3696
+ // Use Chrome's faster viewport-bound screenshot path by default. Callers
3697
+ // opt into the beyond-viewport path only for known compositor edge cases,
3698
+ // such as native video surfaces in tall portrait renders.
3699
+ captureBeyondViewport: options.captureBeyondViewport ?? false,
3700
+ optimizeForSpeed: !isPng,
3701
+ clip
3457
3702
  });
3703
+ return Buffer.from(result.data, "base64");
3458
3704
  }
3459
- async function injectDrawElementCanvas(page, width, height) {
3460
- await page.evaluate(
3461
- ({ w, h }) => {
3462
- const root = document.querySelector("[data-composition-id]");
3463
- if (!root || document.getElementById("__hf_de_canvas")) return;
3464
- try {
3465
- window.__HF_ROOT_BASE_OPACITY__ = parseFloat(getComputedStyle(root).opacity) || 1;
3466
- } catch {
3467
- }
3468
- const parent = root.parentNode;
3469
- if (!parent) throw new Error("drawElement: composition root has no parent node");
3470
- const canvas = document.createElement("canvas");
3471
- canvas.id = "__hf_de_canvas";
3472
- canvas.setAttribute("layoutsubtree", "");
3473
- canvas.width = w;
3474
- canvas.height = h;
3475
- canvas.style.cssText = "display:block;position:absolute;top:0;left:0;z-index:0";
3476
- parent.insertBefore(canvas, root);
3477
- canvas.appendChild(root);
3478
- const tick = document.createElement("div");
3479
- tick.id = "__hf_de_tick";
3480
- tick.style.cssText = "position:absolute;left:0px;top:0;width:1px;height:1px;background:#000;opacity:0.01;pointer-events:none";
3481
- canvas.appendChild(tick);
3482
- window.__hfDeInvalidate = () => {
3483
- tick.style.backgroundColor = tick.style.backgroundColor === "rgb(0, 0, 0)" ? "rgb(1, 1, 1)" : "rgb(0, 0, 0)";
3484
- const cvp = canvas;
3485
- if (typeof cvp.requestPaint === "function") {
3486
- try {
3487
- cvp.requestPaint();
3488
- return true;
3489
- } catch {
3490
- }
3491
- }
3492
- return false;
3493
- };
3494
- },
3495
- { w: width, h: height }
3496
- );
3705
+ async function captureScreenshotWithAlpha(page, width, height) {
3706
+ const client = await getCdpSession(page);
3707
+ await client.send("Emulation.setDefaultBackgroundColorOverride", {
3708
+ color: { r: 0, g: 0, b: 0, a: 0 }
3709
+ });
3710
+ try {
3711
+ const result = await client.send("Page.captureScreenshot", {
3712
+ format: "png",
3713
+ fromSurface: true,
3714
+ // Preserve the #1094 tall-portrait edge-clipping guard on HDR alpha captures.
3715
+ captureBeyondViewport: true,
3716
+ optimizeForSpeed: false,
3717
+ // `true` uses a zero-alpha-aware fast path that crushes real alpha values — observed empirically, CDP docs don't spell it out
3718
+ clip: { x: 0, y: 0, width, height, scale: 1 }
3719
+ });
3720
+ return Buffer.from(result.data, "base64");
3721
+ } finally {
3722
+ await client.send("Emulation.setDefaultBackgroundColorOverride", {}).catch(() => {
3723
+ });
3724
+ }
3497
3725
  }
3498
- async function captureDrawElementFrame(page, width, height, format = "jpeg", quality = 80, syncToPaintEvent = true) {
3499
- const dataUrl = await page.evaluate(
3500
- ({
3501
- w,
3502
- h,
3503
- fmt,
3504
- q,
3505
- sync
3506
- }) => {
3507
- const canvas = document.getElementById("__hf_de_canvas");
3508
- const root = document.querySelector("[data-composition-id]");
3509
- if (!root) {
3510
- throw new Error("HF_DE_COMPOSITION_ROOT_MISSING: drawElement composition root not found");
3511
- }
3512
- if (!canvas) {
3513
- throw new Error("HF_DE_CANVAS_NOT_INITIALIZED: drawElement canvas not initialized");
3514
- }
3515
- const ctx = canvas.getContext("2d");
3516
- if (!ctx) throw new Error("drawElement: 2d context unavailable");
3517
- const aw = window;
3518
- let usedRequestPaint = false;
3519
- aw.__hf3d?.update();
3520
- const accel = (aw.__hf_accel_canvases ?? []).filter((c) => root.contains(c));
3521
- if (!sync) {
3522
- for (const c of (aw.__hf_canvas_2d ?? []).filter((c2) => root.contains(c2))) {
3523
- if (!accel.includes(c)) accel.push(c);
3524
- }
3525
- accel.sort(
3526
- (a, b) => a.compareDocumentPosition(b) & Node.DOCUMENT_POSITION_FOLLOWING ? -1 : 1
3527
- );
3528
- }
3529
- for (const c of accel) {
3530
- if (c.style.visibility !== "hidden") c.style.visibility = "hidden";
3531
- }
3532
- return new Promise((resolveCapture, rejectCapture) => {
3533
- let settled = false;
3534
- const drawAndEncode = () => {
3535
- if (settled) return;
3536
- settled = true;
3537
- try {
3538
- ctx.clearRect(0, 0, w, h);
3539
- let bg = "";
3540
- for (let el = root.parentElement; el; el = el.parentElement) {
3541
- const c = getComputedStyle(el).backgroundColor;
3542
- if (c && c !== "transparent" && c !== "rgba(0, 0, 0, 0)") {
3543
- bg = c;
3544
- break;
3545
- }
3546
- }
3547
- if (!bg && fmt === "jpeg") bg = "#fff";
3548
- if (bg) {
3549
- ctx.fillStyle = bg;
3550
- ctx.fillRect(0, 0, w, h);
3551
- }
3552
- const rootRect = root.getBoundingClientRect();
3553
- for (const c of accel) {
3554
- if (c.hasAttribute("data-hf-3d")) continue;
3555
- const r = c.getBoundingClientRect();
3556
- try {
3557
- ctx.drawImage(c, r.left - rootRect.left, r.top - rootRect.top, r.width, r.height);
3558
- } catch {
3559
- }
3560
- }
3561
- let __appliedTransform = false;
3562
- let __appliedAlpha = false;
3563
- if (aw.__HF_ROOT_PROPS__) {
3564
- try {
3565
- const rcs = getComputedStyle(root);
3566
- if (!usedRequestPaint) {
3567
- const baseOp = aw.__HF_ROOT_BASE_OPACITY__ ?? 1;
3568
- const curOp = parseFloat(rcs.opacity);
3569
- if (baseOp > 1e-3 && Number.isFinite(curOp)) {
3570
- const ratio = curOp / baseOp;
3571
- if (Math.abs(ratio - 1) > 2e-3) {
3572
- ctx.globalAlpha = Math.max(0, Math.min(1, ratio));
3573
- __appliedAlpha = true;
3574
- }
3575
- }
3576
- }
3577
- const curTransform = rcs.transform;
3578
- if (curTransform && curTransform !== "none") {
3579
- const m = new DOMMatrix(curTransform);
3580
- const origin = rcs.transformOrigin.split(" ");
3581
- const ox = parseFloat(origin[0] ?? "0") || 0;
3582
- const oy = parseFloat(origin[1] ?? "0") || 0;
3583
- ctx.translate(ox, oy);
3584
- ctx.transform(m.a, m.b, m.c, m.d, m.e, m.f);
3585
- ctx.translate(-ox, -oy);
3586
- __appliedTransform = true;
3587
- }
3588
- } catch {
3589
- }
3590
- }
3591
- ctx.drawElementImage(root, 0, 0);
3592
- if (__appliedAlpha) ctx.globalAlpha = 1;
3593
- if (__appliedTransform) ctx.setTransform(1, 0, 0, 1, 0, 0);
3594
- for (const c of accel) {
3595
- if (!c.hasAttribute("data-hf-3d")) continue;
3596
- const r = c.getBoundingClientRect();
3597
- try {
3598
- ctx.drawImage(c, r.left - rootRect.left, r.top - rootRect.top, r.width, r.height);
3599
- } catch {
3600
- }
3601
- }
3602
- } catch (e) {
3603
- rejectCapture(e instanceof Error ? e : new Error(String(e)));
3604
- return;
3605
- }
3606
- setTimeout(() => {
3607
- try {
3608
- resolveCapture(
3609
- fmt === "png" ? canvas.toDataURL("image/png") : canvas.toDataURL("image/jpeg", q / 100)
3610
- );
3611
- } catch (e) {
3612
- rejectCapture(e instanceof Error ? e : new Error(String(e)));
3613
- }
3614
- }, 0);
3615
- };
3616
- if (!sync) {
3617
- drawAndEncode();
3618
- return;
3619
- }
3620
- const onPaint = () => {
3621
- canvas.removeEventListener("paint", onPaint);
3622
- drawAndEncode();
3623
- };
3624
- canvas.addEventListener("paint", onPaint);
3625
- usedRequestPaint = aw.__hfDeInvalidate?.() === true;
3626
- setTimeout(() => {
3627
- canvas.removeEventListener("paint", onPaint);
3628
- drawAndEncode();
3629
- }, 250);
3630
- });
3726
+ function capturesAlpha(options) {
3727
+ return options.transparent ?? options.format === "png";
3728
+ }
3729
+ var TRANSPARENT_BG_STYLE_ID = "__hf_transparent_bg__";
3730
+ async function initTransparentBackground(page, { clearCompositionRoot = false } = {}) {
3731
+ const client = await getCdpSession(page);
3732
+ await client.send("Emulation.setDefaultBackgroundColorOverride", {
3733
+ color: { r: 0, g: 0, b: 0, a: 0 }
3734
+ });
3735
+ await page.evaluate(
3736
+ (styleId, clearCompositionRoot2) => {
3737
+ const selector = clearCompositionRoot2 ? "html,body,[data-composition-id]" : "html,body";
3738
+ let style = document.getElementById(styleId);
3739
+ if (!style) {
3740
+ style = document.createElement("style");
3741
+ style.id = styleId;
3742
+ document.head.appendChild(style);
3743
+ }
3744
+ style.textContent = `${selector}{background:transparent !important;background-color:transparent !important;background-image:none !important;}`;
3631
3745
  },
3632
- { w: width, h: height, fmt: format, q: quality, sync: syncToPaintEvent }
3746
+ TRANSPARENT_BG_STYLE_ID,
3747
+ clearCompositionRoot
3633
3748
  );
3634
- const base64 = dataUrl.split(",")[1];
3635
- if (!base64) throw new Error("drawElement: toDataURL returned no base64 payload");
3636
- return Buffer.from(base64, "base64");
3637
3749
  }
3638
- var workerEncodeStates = /* @__PURE__ */ new WeakMap();
3639
- var workerEncodeBoundPages = /* @__PURE__ */ new WeakSet();
3640
- async function initDrawElementWorkerEncode(page) {
3641
- const existing = workerEncodeStates.get(page);
3642
- if (existing) {
3643
- for (const entry of existing.pending.values()) {
3644
- entry.reject(new Error("drawElement worker encode: session reused, frame dropped"));
3645
- }
3646
- existing.pending.clear();
3647
- existing.nextId = 0;
3648
- } else {
3649
- const state = { nextId: 0, pending: /* @__PURE__ */ new Map() };
3650
- workerEncodeStates.set(page, state);
3651
- }
3652
- if (!workerEncodeBoundPages.has(page)) {
3653
- workerEncodeBoundPages.add(page);
3654
- await page.exposeFunction("__hfFrameReady", (id, b64, error) => {
3655
- const s = workerEncodeStates.get(page);
3656
- if (!s) return;
3657
- if (id < 0) {
3658
- for (const entry2 of s.pending.values()) {
3659
- entry2.reject(new Error(`drawElement worker encode failed: ${error ?? "worker error"}`));
3750
+ async function captureAlphaPng(page, width, height) {
3751
+ const client = await getCdpSession(page);
3752
+ const result = await client.send("Page.captureScreenshot", {
3753
+ format: "png",
3754
+ fromSurface: true,
3755
+ // Preserve the #1094 tall-portrait edge-clipping guard on HDR alpha captures.
3756
+ captureBeyondViewport: true,
3757
+ optimizeForSpeed: false,
3758
+ // must be false to preserve alpha
3759
+ clip: { x: 0, y: 0, width, height, scale: 1 }
3760
+ });
3761
+ return Buffer.from(result.data, "base64");
3762
+ }
3763
+ var DOM_LAYER_MASK_STYLE_ID = "__hf_dom_layer_mask__";
3764
+ var DOM_LAYER_MASK_HIDDEN_ATTR = "data-hf-dom-layer-mask-hidden";
3765
+ var DOM_LAYER_MASK_PREV_VISIBILITY_ATTR = "data-hf-dom-layer-mask-prev-visibility";
3766
+ var DOM_LAYER_MASK_PREV_PRIORITY_ATTR = "data-hf-dom-layer-mask-prev-priority";
3767
+ async function applyDomLayerMask(page, showIds, extraHideIds) {
3768
+ await page.evaluate(
3769
+ // fallow-ignore-next-line complexity
3770
+ (args) => {
3771
+ const existing = document.getElementById(args.styleId);
3772
+ if (existing) existing.remove();
3773
+ const renderFrameId = (id) => `${args.renderFramePrefix}${id}${args.renderFrameSuffix}`;
3774
+ const restoreMaskedElements = () => {
3775
+ const masked = document.querySelectorAll(`[${args.hiddenAttr}="1"]`);
3776
+ for (const node of masked) {
3777
+ if (!(node instanceof HTMLElement)) continue;
3778
+ const prevVisibility = node.getAttribute(args.prevVisibilityAttr);
3779
+ const prevPriority = node.getAttribute(args.prevPriorityAttr);
3780
+ if (prevVisibility === null) {
3781
+ node.style.removeProperty("visibility");
3782
+ } else {
3783
+ node.style.setProperty("visibility", prevVisibility, prevPriority ?? "");
3784
+ }
3785
+ node.removeAttribute(args.hiddenAttr);
3786
+ node.removeAttribute(args.prevVisibilityAttr);
3787
+ node.removeAttribute(args.prevPriorityAttr);
3660
3788
  }
3661
- s.pending.clear();
3662
- return;
3663
- }
3664
- const entry = s.pending.get(id);
3665
- if (!entry) return;
3666
- s.pending.delete(id);
3667
- if (error) {
3668
- entry.reject(new Error(`drawElement worker encode failed: ${error}`));
3669
- } else if (!b64) {
3670
- entry.reject(new Error(`drawElement worker encode returned empty frame (frame ${id})`));
3671
- } else {
3672
- entry.resolve(Buffer.from(b64, "base64"));
3673
- }
3674
- });
3675
- }
3676
- await page.evaluate(() => {
3677
- const ew = window;
3678
- if (ew.__hfEncWorker) {
3679
- ew.__hfEncWorker.terminate();
3680
- ew.__hfEncWorker = void 0;
3681
- }
3682
- const workerSrc = `
3683
- // Reuse one OffscreenCanvas across frames (dimensions are constant for a
3684
- // render): a fresh canvas per frame churns ~w*h*4 bytes of backing store
3685
- // every frame and pressures GC on the encode hot path.
3686
- let oc = null, c = null;
3687
- self.onmessage = async (e) => {
3688
- const { bmp, id, w, h, q } = e.data;
3689
- try {
3690
- if (!oc || oc.width !== w || oc.height !== h) {
3691
- oc = new OffscreenCanvas(w, h);
3692
- c = oc.getContext('2d');
3789
+ };
3790
+ restoreMaskedElements();
3791
+ const rememberAndHideElement = (el) => {
3792
+ if (el.getAttribute(args.hiddenAttr) !== "1") {
3793
+ const prevVisibility = el.style.getPropertyValue("visibility");
3794
+ const prevPriority = typeof el.style.getPropertyPriority === "function" ? el.style.getPropertyPriority("visibility") : "";
3795
+ if (prevVisibility) {
3796
+ el.setAttribute(args.prevVisibilityAttr, prevVisibility);
3797
+ } else {
3798
+ el.removeAttribute(args.prevVisibilityAttr);
3693
3799
  }
3694
- if (!c) throw new Error('OffscreenCanvas 2d context unavailable');
3695
- c.drawImage(bmp, 0, 0);
3696
- bmp.close();
3697
- const blob = await oc.convertToBlob({ type: 'image/jpeg', quality: q });
3698
- const ab = await blob.arrayBuffer();
3699
- const u = new Uint8Array(ab);
3700
- let s = ''; const CH = 0x8000;
3701
- for (let i = 0; i < u.length; i += CH)
3702
- s += String.fromCharCode.apply(null, u.subarray(i, i + CH));
3703
- self.postMessage({ id, b64: btoa(s) });
3704
- } catch (err) {
3705
- try { if (bmp) bmp.close(); } catch (_) {}
3706
- self.postMessage({ id, error: (err && err.message) || String(err) });
3800
+ if (prevPriority) {
3801
+ el.setAttribute(args.prevPriorityAttr, prevPriority);
3802
+ } else {
3803
+ el.removeAttribute(args.prevPriorityAttr);
3804
+ }
3805
+ el.setAttribute(args.hiddenAttr, "1");
3707
3806
  }
3807
+ el.style.setProperty("visibility", "hidden", "important");
3708
3808
  };
3709
- `;
3710
- const url = URL.createObjectURL(new Blob([workerSrc], { type: "text/javascript" }));
3711
- const worker = new Worker(url);
3712
- URL.revokeObjectURL(url);
3713
- ew.__hfEncWorker = worker;
3714
- worker.onmessage = (ev) => {
3715
- const d = ev.data;
3716
- ew.__hfFrameReady?.(d.id, d.b64 ?? "", d.error);
3717
- };
3718
- worker.onerror = (err) => {
3719
- ew.__hfFrameReady?.(-1, "", err.message || "worker fatal error");
3720
- };
3721
- });
3722
- }
3723
- function cleanupDrawElementWorkerEncode(page) {
3724
- const state = workerEncodeStates.get(page);
3725
- if (!state) return;
3726
- for (const entry of state.pending.values()) {
3727
- entry.reject(new Error("drawElement worker encode: session closed"));
3728
- }
3729
- state.pending.clear();
3730
- workerEncodeStates.delete(page);
3731
- }
3732
- async function produceDrawElementFrame(page, width, height, quality = 80, syncToPaintEvent = true) {
3733
- const state = workerEncodeStates.get(page);
3734
- if (!state) {
3735
- throw new Error(
3736
- "drawElement worker encode not initialized; call initDrawElementWorkerEncode first"
3737
- );
3738
- }
3739
- const frameId = ++state.nextId;
3740
- const encodeResult = new Promise((resolve2, reject) => {
3741
- const timer = setTimeout(() => {
3742
- if (state.pending.delete(frameId)) {
3743
- reject(new Error(`drawElement worker encode timed out (frame ${frameId})`));
3809
+ const hiddenTimedDescendants = [];
3810
+ const rememberHiddenTimedDescendants = (root) => {
3811
+ for (const node of root.querySelectorAll("[data-start]")) {
3812
+ if (!(node instanceof HTMLElement)) continue;
3813
+ const computed = window.getComputedStyle(node);
3814
+ if (computed.visibility !== "hidden" && computed.display !== "none") continue;
3815
+ hiddenTimedDescendants.push(node);
3816
+ }
3817
+ };
3818
+ const showSelectors = [];
3819
+ for (const id of args.show) {
3820
+ const el = window.__hfMediaEl?.(id) ?? document.getElementById(id);
3821
+ if (el) rememberHiddenTimedDescendants(el);
3822
+ if (el?.hasAttribute(args.renderIdAttr)) {
3823
+ const attrEscaped = id.replace(/\\/g, "\\\\").replace(/"/g, '\\"');
3824
+ const byRenderId = `[${args.renderIdAttr}="${attrEscaped}"]`;
3825
+ showSelectors.push(byRenderId, `${byRenderId} *`);
3826
+ } else {
3827
+ const escaped = CSS.escape(id);
3828
+ showSelectors.push(`#${escaped}`, `#${escaped} *`);
3829
+ }
3830
+ const renderEscaped = CSS.escape(renderFrameId(id));
3831
+ showSelectors.push(`#${renderEscaped}`, `#${renderEscaped} *`);
3832
+ const colorGradingEscaped = CSS.escape(`${args.canvasIdPrefix}${id}`);
3833
+ showSelectors.push(`#${colorGradingEscaped}`, `#${colorGradingEscaped} *`);
3744
3834
  }
3745
- }, 3e4);
3746
- state.pending.set(frameId, {
3747
- resolve: (b) => {
3748
- clearTimeout(timer);
3749
- resolve2(b);
3750
- },
3751
- reject: (e) => {
3752
- clearTimeout(timer);
3753
- reject(e);
3835
+ const massHideRule = "body *{visibility:hidden !important;}";
3836
+ const showRule = showSelectors.length === 0 ? "" : `${showSelectors.join(",")}{visibility:visible !important;}`;
3837
+ const style = document.createElement("style");
3838
+ style.id = args.styleId;
3839
+ style.textContent = `${massHideRule}
3840
+ ${showRule}`;
3841
+ document.head.appendChild(style);
3842
+ for (const el of hiddenTimedDescendants) {
3843
+ rememberAndHideElement(el);
3754
3844
  }
3755
- });
3756
- });
3757
- void encodeResult.catch(() => {
3758
- });
3845
+ for (const id of args.hide) {
3846
+ const el = window.__hfMediaEl?.(id) ?? document.getElementById(id);
3847
+ if (el instanceof HTMLElement) {
3848
+ rememberAndHideElement(el);
3849
+ }
3850
+ const img = document.getElementById(renderFrameId(id));
3851
+ if (img) {
3852
+ rememberAndHideElement(img);
3853
+ }
3854
+ const colorGradingCanvas = document.getElementById(`${args.canvasIdPrefix}${id}`);
3855
+ if (colorGradingCanvas instanceof HTMLElement) {
3856
+ rememberAndHideElement(colorGradingCanvas);
3857
+ }
3858
+ }
3859
+ },
3860
+ {
3861
+ show: showIds,
3862
+ hide: extraHideIds,
3863
+ renderIdAttr: MEDIA_RENDER_ID_ATTR,
3864
+ renderFramePrefix: RENDER_FRAME_ID_PREFIX,
3865
+ renderFrameSuffix: RENDER_FRAME_ID_SUFFIX,
3866
+ styleId: DOM_LAYER_MASK_STYLE_ID,
3867
+ hiddenAttr: DOM_LAYER_MASK_HIDDEN_ATTR,
3868
+ prevVisibilityAttr: DOM_LAYER_MASK_PREV_VISIBILITY_ATTR,
3869
+ prevPriorityAttr: DOM_LAYER_MASK_PREV_PRIORITY_ATTR,
3870
+ canvasIdPrefix: HF_COLOR_GRADING_CANVAS_ID_PREFIX
3871
+ }
3872
+ );
3873
+ }
3874
+ async function removeDomLayerMask(page, _extraHideIds) {
3759
3875
  await page.evaluate(
3760
- ({ w, h, q, sync, fid }) => {
3761
- const canvas = document.getElementById("__hf_de_canvas");
3762
- const root = document.querySelector("[data-composition-id]");
3763
- if (!root) {
3764
- throw new Error("HF_DE_COMPOSITION_ROOT_MISSING: drawElement composition root not found");
3765
- }
3766
- if (!canvas) {
3767
- throw new Error("HF_DE_CANVAS_NOT_INITIALIZED: drawElement canvas not initialized");
3768
- }
3769
- const ctx = canvas.getContext("2d");
3770
- if (!ctx) throw new Error("drawElement: 2d context unavailable");
3771
- const aw = window;
3772
- aw.__hf3d?.update();
3773
- const accel = (aw.__hf_accel_canvases ?? []).filter((c) => root.contains(c));
3774
- if (!sync) {
3775
- for (const c of (aw.__hf_canvas_2d ?? []).filter((c2) => root.contains(c2))) {
3776
- if (!accel.includes(c)) accel.push(c);
3876
+ (args) => {
3877
+ const style = document.getElementById(args.styleId);
3878
+ if (style) style.remove();
3879
+ const masked = document.querySelectorAll(`[${args.hiddenAttr}="1"]`);
3880
+ for (const node of masked) {
3881
+ if (!(node instanceof HTMLElement)) continue;
3882
+ const prevVisibility = node.getAttribute(args.prevVisibilityAttr);
3883
+ const prevPriority = node.getAttribute(args.prevPriorityAttr);
3884
+ if (prevVisibility === null) {
3885
+ node.style.removeProperty("visibility");
3886
+ } else {
3887
+ node.style.setProperty("visibility", prevVisibility, prevPriority ?? "");
3777
3888
  }
3778
- accel.sort(
3779
- (a, b) => a.compareDocumentPosition(b) & Node.DOCUMENT_POSITION_FOLLOWING ? -1 : 1
3780
- );
3889
+ node.removeAttribute(args.hiddenAttr);
3890
+ node.removeAttribute(args.prevVisibilityAttr);
3891
+ node.removeAttribute(args.prevPriorityAttr);
3781
3892
  }
3782
- for (const c of accel) {
3783
- if (c.style.visibility !== "hidden") c.style.visibility = "hidden";
3893
+ },
3894
+ {
3895
+ styleId: DOM_LAYER_MASK_STYLE_ID,
3896
+ hiddenAttr: DOM_LAYER_MASK_HIDDEN_ATTR,
3897
+ prevVisibilityAttr: DOM_LAYER_MASK_PREV_VISIBILITY_ATTR,
3898
+ prevPriorityAttr: DOM_LAYER_MASK_PREV_PRIORITY_ATTR
3899
+ }
3900
+ );
3901
+ }
3902
+ async function ensureRenderFrameSiblings(page) {
3903
+ await page.evaluate(
3904
+ (prefix, suffix) => {
3905
+ for (const video of Array.from(
3906
+ document.querySelectorAll("video[data-start]")
3907
+ )) {
3908
+ const next = video.nextElementSibling;
3909
+ if (next !== null && next.classList.contains("__render_frame__")) continue;
3910
+ const img = document.createElement("img");
3911
+ img.classList.add("__render_frame__");
3912
+ img.id = `${prefix}${window.__hfMediaId?.(video) || video.id}${suffix}`;
3913
+ img.style.pointerEvents = "none";
3914
+ img.style.position = "absolute";
3915
+ img.style.visibility = "hidden";
3916
+ video.parentNode?.insertBefore(img, video.nextSibling);
3784
3917
  }
3785
- return new Promise((resolveCapture, rejectCapture) => {
3786
- let settled = false;
3787
- let usedRequestPaint = false;
3788
- const drawAndKick = () => {
3789
- if (settled) return;
3790
- settled = true;
3791
- try {
3792
- ctx.clearRect(0, 0, w, h);
3793
- let bg = "";
3794
- for (let el = root.parentElement; el; el = el.parentElement) {
3795
- const c = getComputedStyle(el).backgroundColor;
3796
- if (c && c !== "transparent" && c !== "rgba(0, 0, 0, 0)") {
3797
- bg = c;
3798
- break;
3799
- }
3800
- }
3801
- if (!bg) bg = "#fff";
3802
- if (bg) {
3803
- ctx.fillStyle = bg;
3804
- ctx.fillRect(0, 0, w, h);
3805
- }
3806
- const rootRect = root.getBoundingClientRect();
3807
- for (const c of accel) {
3808
- if (c.hasAttribute("data-hf-3d")) continue;
3809
- const r = c.getBoundingClientRect();
3810
- try {
3811
- ctx.drawImage(c, r.left - rootRect.left, r.top - rootRect.top, r.width, r.height);
3812
- } catch {
3813
- }
3814
- }
3815
- let __appliedTransform = false;
3816
- let __appliedAlpha = false;
3817
- if (aw.__HF_ROOT_PROPS__) {
3818
- try {
3819
- const rcs = getComputedStyle(root);
3820
- if (!usedRequestPaint) {
3821
- const baseOp = aw.__HF_ROOT_BASE_OPACITY__ ?? 1;
3822
- const curOp = parseFloat(rcs.opacity);
3823
- if (baseOp > 1e-3 && Number.isFinite(curOp)) {
3824
- const ratio = curOp / baseOp;
3825
- if (Math.abs(ratio - 1) > 2e-3) {
3826
- ctx.globalAlpha = Math.max(0, Math.min(1, ratio));
3827
- __appliedAlpha = true;
3828
- }
3829
- }
3830
- }
3831
- const curTransform = rcs.transform;
3832
- if (curTransform && curTransform !== "none") {
3833
- const m = new DOMMatrix(curTransform);
3834
- const origin = rcs.transformOrigin.split(" ");
3835
- const ox = parseFloat(origin[0] ?? "0") || 0;
3836
- const oy = parseFloat(origin[1] ?? "0") || 0;
3837
- ctx.translate(ox, oy);
3838
- ctx.transform(m.a, m.b, m.c, m.d, m.e, m.f);
3839
- ctx.translate(-ox, -oy);
3840
- __appliedTransform = true;
3841
- }
3842
- } catch {
3843
- }
3844
- }
3845
- ctx.drawElementImage(root, 0, 0);
3846
- if (__appliedAlpha) ctx.globalAlpha = 1;
3847
- if (__appliedTransform) ctx.setTransform(1, 0, 0, 1, 0, 0);
3848
- for (const c of accel) {
3849
- if (!c.hasAttribute("data-hf-3d")) continue;
3850
- const r = c.getBoundingClientRect();
3851
- try {
3852
- ctx.drawImage(c, r.left - rootRect.left, r.top - rootRect.top, r.width, r.height);
3853
- } catch {
3854
- }
3855
- }
3856
- } catch (e) {
3857
- rejectCapture(e instanceof Error ? e : new Error(String(e)));
3858
- return;
3859
- }
3860
- createImageBitmap(canvas).then((bmp) => {
3861
- const ew = window;
3862
- if (!ew.__hfEncWorker) {
3863
- bmp.close();
3864
- rejectCapture(new Error("drawElement: encode worker not initialized"));
3865
- return;
3866
- }
3867
- ew.__hfEncWorker.postMessage({ bmp, id: fid, w, h, q: q / 100 }, [bmp]);
3868
- resolveCapture();
3869
- }).catch((e) => {
3870
- rejectCapture(e instanceof Error ? e : new Error(String(e)));
3871
- });
3872
- };
3873
- if (!sync) {
3874
- drawAndKick();
3875
- return;
3876
- }
3877
- const onPaint = () => {
3878
- canvas.removeEventListener("paint", onPaint);
3879
- drawAndKick();
3880
- };
3881
- canvas.addEventListener("paint", onPaint);
3882
- usedRequestPaint = aw.__hfDeInvalidate?.() === true;
3883
- setTimeout(() => {
3884
- canvas.removeEventListener("paint", onPaint);
3885
- drawAndKick();
3886
- }, 250);
3887
- });
3888
3918
  },
3889
- { w: width, h: height, q: quality, sync: syncToPaintEvent, fid: frameId }
3919
+ RENDER_FRAME_ID_PREFIX,
3920
+ RENDER_FRAME_ID_SUFFIX
3890
3921
  );
3891
- return { encodeResult };
3892
3922
  }
3893
- async function produceDrawElementFrameBatch(page, times, width, height, quality = 80) {
3894
- const state = workerEncodeStates.get(page);
3895
- if (!state) {
3896
- throw new Error(
3897
- "drawElement worker encode not initialized; call initDrawElementWorkerEncode first"
3898
- );
3899
- }
3900
- const fids = [];
3901
- const encodeResults = [];
3902
- for (let i = 0; i < times.length; i++) {
3903
- const frameId = ++state.nextId;
3904
- fids.push(frameId);
3905
- const p = new Promise((resolve2, reject) => {
3906
- const timer = setTimeout(() => {
3907
- if (state.pending.delete(frameId)) {
3908
- reject(new Error(`drawElement worker encode timed out (frame ${frameId})`));
3923
+ async function injectVideoFramesBatch(page, updates, restyleIds = []) {
3924
+ if (updates.length === 0 && restyleIds.length === 0) return [];
3925
+ return withVideoFrameSources(
3926
+ page,
3927
+ updates,
3928
+ (resolved) => injectResolvedVideoFramesBatch(page, resolved, restyleIds)
3929
+ );
3930
+ }
3931
+ async function injectResolvedVideoFramesBatch(page, updates, restyleIds) {
3932
+ const items = [
3933
+ ...updates,
3934
+ ...restyleIds.map((videoId) => ({ videoId }))
3935
+ ].map((item) => ({ ...item, frameId: renderFrameIdForRenderId(item.videoId) }));
3936
+ return await page.evaluate(
3937
+ // fallow-ignore-next-line complexity
3938
+ async (items2, visualProperties, colorGradingSourceHiddenAttr) => {
3939
+ const injectedIds = [];
3940
+ const pendingDecodes = [];
3941
+ const imagesToPublish = [];
3942
+ const replacementLayoutProperties = /* @__PURE__ */ new Set([
3943
+ "width",
3944
+ "height",
3945
+ "top",
3946
+ "left",
3947
+ "right",
3948
+ "bottom",
3949
+ "inset"
3950
+ ]);
3951
+ const isVisualAncestorHidden = (el) => {
3952
+ let parent = el.parentElement;
3953
+ while (parent !== null && parent !== document.documentElement) {
3954
+ const computed = window.getComputedStyle(parent);
3955
+ if (computed.display === "none") return true;
3956
+ if (computed.visibility === "hidden" && (parent.hasAttribute("data-composition-src") || parent.hasAttribute("data-composition-file"))) {
3957
+ return true;
3958
+ }
3959
+ parent = parent.parentElement;
3960
+ }
3961
+ return false;
3962
+ };
3963
+ for (const item of items2) {
3964
+ const video = window.__hfMediaEl?.(item.videoId) ?? document.getElementById(item.videoId);
3965
+ if (!video) continue;
3966
+ let img = video.nextElementSibling;
3967
+ const hasImg = img !== null && img.classList.contains("__render_frame__");
3968
+ const restyleOnly = item.dataUri === void 0;
3969
+ if (restyleOnly && !hasImg) continue;
3970
+ if (isVisualAncestorHidden(video)) {
3971
+ if (hasImg && img) img.style.setProperty("visibility", "hidden", "important");
3972
+ continue;
3973
+ }
3974
+ const isNewImage = !hasImg;
3975
+ const computedStyle = window.getComputedStyle(video);
3976
+ const opacityParsed = parseFloat(computedStyle.opacity);
3977
+ const computedOpacity = video.hasAttribute(colorGradingSourceHiddenAttr) ? 1 : Number.isNaN(opacityParsed) ? 1 : opacityParsed;
3978
+ const videoRect = video.getBoundingClientRect();
3979
+ const videoBox = {
3980
+ left: Number.isFinite(video.offsetLeft) ? video.offsetLeft : 0,
3981
+ top: Number.isFinite(video.offsetTop) ? video.offsetTop : 0,
3982
+ width: video.offsetWidth > 0 ? video.offsetWidth : videoRect.width,
3983
+ height: video.offsetHeight > 0 ? video.offsetHeight : videoRect.height
3984
+ };
3985
+ if (isNewImage) {
3986
+ img = document.createElement("img");
3987
+ img.classList.add("__render_frame__");
3988
+ img.id = item.frameId;
3989
+ img.style.pointerEvents = "none";
3990
+ video.parentNode?.insertBefore(img, video.nextSibling);
3991
+ }
3992
+ if (!img) continue;
3993
+ for (const property of visualProperties) {
3994
+ if (property === "opacity") continue;
3995
+ if (replacementLayoutProperties.has(property)) {
3996
+ continue;
3997
+ }
3998
+ const value = computedStyle.getPropertyValue(property);
3999
+ if (value) {
4000
+ img.style.setProperty(property, value);
4001
+ }
3909
4002
  }
3910
- }, 3e4);
3911
- state.pending.set(frameId, {
3912
- resolve: (b) => {
3913
- clearTimeout(timer);
3914
- resolve2(b);
3915
- },
3916
- reject: (e) => {
3917
- clearTimeout(timer);
3918
- reject(e);
4003
+ img.style.position = "absolute";
4004
+ img.style.inset = "auto";
4005
+ img.style.left = `${videoBox.left}px`;
4006
+ img.style.top = `${videoBox.top}px`;
4007
+ img.style.right = "auto";
4008
+ img.style.bottom = "auto";
4009
+ img.style.width = `${videoBox.width}px`;
4010
+ img.style.height = `${videoBox.height}px`;
4011
+ img.style.boxSizing = "border-box";
4012
+ img.style.objectFit = computedStyle.objectFit;
4013
+ img.style.objectPosition = computedStyle.objectPosition;
4014
+ img.style.zIndex = computedStyle.zIndex;
4015
+ img.style.setProperty("visibility", "hidden", "important");
4016
+ img.decoding = "sync";
4017
+ if (item.dataUri !== void 0 && img.getAttribute("src") !== item.dataUri) {
4018
+ if (item.crossOrigin) img.crossOrigin = item.crossOrigin;
4019
+ else img.removeAttribute("crossorigin");
4020
+ img.src = item.dataUri;
4021
+ const source = item.sourceLabel ?? (item.dataUri.startsWith("data:") ? "inline frame" : item.dataUri);
4022
+ pendingDecodes.push(
4023
+ img.decode().catch((error) => {
4024
+ throw new Error(
4025
+ `Video frame for "${item.videoId}" failed to load (${source}): ${error instanceof Error ? error.message : String(error)}`
4026
+ );
4027
+ })
4028
+ );
3919
4029
  }
3920
- });
3921
- });
3922
- void p.catch(() => {
3923
- });
3924
- encodeResults.push(p);
3925
- }
3926
- const outcome = await page.evaluate(
3927
- async ({
3928
- frames,
3929
- w,
3930
- h,
3931
- q
3932
- }) => {
3933
- const canvas = document.getElementById("__hf_de_canvas");
3934
- const root = document.querySelector("[data-composition-id]");
3935
- if (!root) {
3936
- return {
3937
- failedAt: 0,
3938
- error: "HF_DE_COMPOSITION_ROOT_MISSING: drawElement composition root not found"
3939
- };
4030
+ img.style.opacity = String(computedOpacity);
4031
+ imagesToPublish.push(img);
4032
+ video.style.setProperty("visibility", "hidden", "important");
4033
+ video.style.setProperty("pointer-events", "none", "important");
4034
+ if (!restyleOnly) injectedIds.push(item.videoId);
3940
4035
  }
3941
- if (!canvas) {
3942
- return {
3943
- failedAt: 0,
3944
- error: "HF_DE_CANVAS_NOT_INITIALIZED: drawElement canvas not initialized"
3945
- };
4036
+ if (pendingDecodes.length > 0) {
4037
+ await Promise.all(pendingDecodes);
3946
4038
  }
3947
- const ctx = canvas.getContext("2d");
3948
- if (!ctx) return { failedAt: 0, error: "drawElement: 2d context unavailable" };
3949
- const aw = window;
3950
- let usedRequestPaint = false;
3951
- const waitPaint = () => new Promise((res) => {
3952
- let done = false;
3953
- const settle = () => {
3954
- if (done) return;
3955
- done = true;
3956
- canvas.removeEventListener("paint", settle);
3957
- res();
3958
- };
3959
- canvas.addEventListener("paint", settle);
3960
- usedRequestPaint = aw.__hfDeInvalidate?.() === true;
3961
- setTimeout(settle, 250);
3962
- });
3963
- let prevBitmap = Promise.resolve();
3964
- let prevBitmapIdx = -1;
3965
- const errMsg = (e) => e instanceof Error ? e.message : String(e);
3966
- for (let i = 0; i < frames.length; i++) {
3967
- const frame = frames[i];
3968
- if (!frame) return { failedAt: i, error: "batch frame missing" };
3969
- const { t, fid } = frame;
3970
- try {
3971
- if (aw.__hf && typeof aw.__hf.seek === "function") aw.__hf.seek(t);
3972
- await aw.__hfWaitForSeekCompletion?.();
3973
- await aw.__hfDecodeDynamicCssBackgroundImages?.();
3974
- aw.__hf3d?.update();
3975
- const accel = (aw.__hf_accel_canvases ?? []).filter((c) => root.contains(c));
3976
- for (const c of accel) {
3977
- if (c.style.visibility !== "hidden") c.style.visibility = "hidden";
3978
- }
3979
- await waitPaint();
3980
- try {
3981
- await prevBitmap;
3982
- } catch (e) {
3983
- return { failedAt: prevBitmapIdx, error: errMsg(e) };
3984
- }
3985
- ctx.clearRect(0, 0, w, h);
3986
- let bg = "";
3987
- for (let el = root.parentElement; el; el = el.parentElement) {
3988
- const c = getComputedStyle(el).backgroundColor;
3989
- if (c && c !== "transparent" && c !== "rgba(0, 0, 0, 0)") {
3990
- bg = c;
3991
- break;
3992
- }
3993
- }
3994
- ctx.fillStyle = bg || "#fff";
3995
- ctx.fillRect(0, 0, w, h);
3996
- const rootRect = root.getBoundingClientRect();
3997
- for (const c of accel) {
3998
- if (c.hasAttribute("data-hf-3d")) continue;
3999
- const r = c.getBoundingClientRect();
4000
- try {
4001
- ctx.drawImage(c, r.left - rootRect.left, r.top - rootRect.top, r.width, r.height);
4002
- } catch {
4003
- }
4004
- }
4005
- let appliedTransform = false;
4006
- let appliedAlpha = false;
4007
- if (aw.__HF_ROOT_PROPS__) {
4008
- try {
4009
- const rcs = getComputedStyle(root);
4010
- if (!usedRequestPaint) {
4011
- const baseOp = aw.__HF_ROOT_BASE_OPACITY__ ?? 1;
4012
- const curOp = parseFloat(rcs.opacity);
4013
- if (baseOp > 1e-3 && Number.isFinite(curOp)) {
4014
- const ratio = curOp / baseOp;
4015
- if (Math.abs(ratio - 1) > 2e-3) {
4016
- ctx.globalAlpha = Math.max(0, Math.min(1, ratio));
4017
- appliedAlpha = true;
4018
- }
4019
- }
4020
- }
4021
- const curTransform = rcs.transform;
4022
- if (curTransform && curTransform !== "none") {
4023
- const m = new DOMMatrix(curTransform);
4024
- const origin = rcs.transformOrigin.split(" ");
4025
- const ox = parseFloat(origin[0] ?? "0") || 0;
4026
- const oy = parseFloat(origin[1] ?? "0") || 0;
4027
- ctx.translate(ox, oy);
4028
- ctx.transform(m.a, m.b, m.c, m.d, m.e, m.f);
4029
- ctx.translate(-ox, -oy);
4030
- appliedTransform = true;
4031
- }
4032
- } catch {
4033
- }
4039
+ for (const img of imagesToPublish) img.style.visibility = "visible";
4040
+ if (imagesToPublish.length > 0) {
4041
+ const redraw = window.__hf?.colorGrading?.redraw;
4042
+ redraw?.();
4043
+ }
4044
+ return injectedIds;
4045
+ },
4046
+ items,
4047
+ [...MEDIA_VISUAL_STYLE_PROPERTIES],
4048
+ COLOR_GRADING_SOURCE_HIDDEN_ATTR
4049
+ );
4050
+ }
4051
+ async function syncVideoFrameVisibility(page, activeVideoIds) {
4052
+ await page.evaluate(
4053
+ // fallow-ignore-next-line complexity
4054
+ (ids, colorGradingSourceHiddenAttr) => {
4055
+ const isVisualAncestorHidden = (el) => {
4056
+ let parent = el.parentElement;
4057
+ while (parent !== null && parent !== document.documentElement) {
4058
+ const computed = window.getComputedStyle(parent);
4059
+ if (computed.display === "none") return true;
4060
+ if (computed.visibility === "hidden" && (parent.hasAttribute("data-composition-src") || parent.hasAttribute("data-composition-file"))) {
4061
+ return true;
4034
4062
  }
4035
- ctx.drawElementImage(root, 0, 0);
4036
- if (appliedAlpha) ctx.globalAlpha = 1;
4037
- if (appliedTransform) ctx.setTransform(1, 0, 0, 1, 0, 0);
4038
- for (const c of accel) {
4039
- if (!c.hasAttribute("data-hf-3d")) continue;
4040
- const r = c.getBoundingClientRect();
4041
- try {
4042
- ctx.drawImage(c, r.left - rootRect.left, r.top - rootRect.top, r.width, r.height);
4043
- } catch {
4044
- }
4063
+ parent = parent.parentElement;
4064
+ }
4065
+ return false;
4066
+ };
4067
+ const active = new Set(ids);
4068
+ const setColorGradingVisibility = window.__hf?.colorGrading?.setSourceVisibility;
4069
+ const videos = Array.from(
4070
+ document.querySelectorAll("video[data-start]")
4071
+ );
4072
+ for (const video of videos) {
4073
+ const img = video.nextElementSibling;
4074
+ const hasImg = img && img.classList.contains("__render_frame__");
4075
+ const ancestorHidden = isVisualAncestorHidden(video);
4076
+ const visible = active.has(window.__hfMediaId?.(video) || video.id) && !ancestorHidden;
4077
+ if (visible) {
4078
+ video.style.setProperty("visibility", "hidden", "important");
4079
+ video.style.setProperty("pointer-events", "none", "important");
4080
+ if (hasImg) {
4081
+ if (video.hasAttribute(colorGradingSourceHiddenAttr)) img.style.opacity = "1";
4082
+ img.style.visibility = "visible";
4045
4083
  }
4046
- prevBitmapIdx = i;
4047
- prevBitmap = createImageBitmap(canvas).then((bmp) => {
4048
- if (!aw.__hfEncWorker) {
4049
- bmp.close();
4050
- throw new Error("drawElement: encode worker not initialized");
4051
- }
4052
- aw.__hfEncWorker.postMessage({ bmp, id: fid, w, h, q: q / 100 }, [bmp]);
4053
- });
4054
- } catch (e) {
4055
- try {
4056
- await prevBitmap;
4057
- } catch {
4084
+ } else {
4085
+ video.style.setProperty("visibility", "hidden", "important");
4086
+ video.style.setProperty("pointer-events", "none", "important");
4087
+ if (hasImg) {
4088
+ img.style.setProperty("visibility", "hidden", "important");
4058
4089
  }
4059
- return { failedAt: i, error: errMsg(e) };
4060
4090
  }
4091
+ setColorGradingVisibility?.(video, visible);
4061
4092
  }
4062
- try {
4063
- await prevBitmap;
4064
- } catch (e) {
4065
- return { failedAt: prevBitmapIdx, error: errMsg(e) };
4066
- }
4067
- return { failedAt: null };
4068
4093
  },
4069
- { frames: times.map((t, i) => ({ t, fid: fids[i] ?? 0 })), w: width, h: height, q: quality }
4094
+ activeVideoIds,
4095
+ COLOR_GRADING_SOURCE_HIDDEN_ATTR
4070
4096
  );
4071
- if (outcome.failedAt !== null) {
4072
- for (let k = outcome.failedAt; k < fids.length; k++) {
4073
- const fid = fids[k];
4074
- if (fid === void 0) continue;
4075
- const entry = state.pending.get(fid);
4076
- if (entry) {
4077
- state.pending.delete(fid);
4078
- entry.reject(
4079
- new Error(`drawElement batch produce failed at frame ${k}: ${outcome.error ?? "?"}`)
4080
- );
4081
- }
4082
- }
4083
- }
4084
- return { encodeResults, failedAt: outcome.failedAt, error: outcome.error };
4085
4097
  }
4086
4098
 
4087
4099
  // ../engine/src/services/threeDProjection.ts
@@ -5994,6 +6006,7 @@ async function constructCaptureSession(input) {
5994
6006
  });
5995
6007
  await installMediaPageHooks(page, options);
5996
6008
  if (useDrawElement) {
6009
+ await page.evaluateOnNewDocument(forcePreservedDrawingBuffer);
5997
6010
  await page.evaluateOnNewDocument(instrumentAcceleratedCanvases);
5998
6011
  }
5999
6012
  if (process.env.HF_FAST_CAPTURE_AUTOALPHA !== void 0) {
@@ -18788,6 +18801,7 @@ export {
18788
18801
  isProtocolTimeoutError,
18789
18802
  augmentPageNavigationTimeoutError,
18790
18803
  isPageNavigationTimeoutError,
18804
+ forcePreservedDrawingBuffer,
18791
18805
  DrawElementCaptureError,
18792
18806
  isDrawElementCaptureError,
18793
18807
  decodePng,