hyperframes 0.8.197 → 0.8.199

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 (170) hide show
  1. package/dist/{add-5GQIR5OE.js → add-7LA5CGDM.js} +12 -12
  2. package/dist/{animatedGifPrep-MGFQWIGJ.js → animatedGifPrep-NB2MZTMQ.js} +6 -6
  3. package/dist/api.js +14 -14
  4. package/dist/{asset-ADX55DGH.js → asset-4BIOI6GN.js} +2 -2
  5. package/dist/{assetCataloger-GGBWBQZW.js → assetCataloger-TX5KL5VV.js} +6 -6
  6. package/dist/{audio-SPB4CLRU.js → audio-ZGMIIDNU.js} +13 -13
  7. package/dist/{auth-WBAB35QA.js → auth-OQ5PWEUG.js} +1 -1
  8. package/dist/{autoUpdate-5VUDX7JO.js → autoUpdate-QREPD6I4.js} +3 -3
  9. package/dist/{backgroundChecks-ATZQQUMR.js → backgroundChecks-5CJPJX2O.js} +4 -4
  10. package/dist/backgroundChecksWorker.js +4 -4
  11. package/dist/{batchRender-6S2XULOE.js → batchRender-BW2ZK4MA.js} +3 -3
  12. package/dist/{beats-WJPHWDZ6.js → beats-I5XARMDB.js} +9 -9
  13. package/dist/{benchmark-LZVR7PF6.js → benchmark-S2WWY4U7.js} +9 -9
  14. package/dist/{browser-QJ3PFVDY.js → browser-PAXVQYQZ.js} +4 -4
  15. package/dist/{bundleWithLocalizedFonts-564BQ73K.js → bundleWithLocalizedFonts-3ED26VCR.js} +2 -2
  16. package/dist/{capture-3PUQLQNM.js → capture-23574YLP.js} +9 -9
  17. package/dist/{capture-IRAYPK52.js → capture-OVITDMKK.js} +2 -2
  18. package/dist/{captureCompositionFrame-OHS3WBTA.js → captureCompositionFrame-KAUUHCOL.js} +11 -11
  19. package/dist/{catalog-IQKJLTSF.js → catalog-CM3VXSQE.js} +12 -12
  20. package/dist/{catch-up-C4JJJNP3.js → catch-up-HMFREOC2.js} +5 -5
  21. package/dist/{check-46Z5CAA4.js → check-CYJZ6CGT.js} +34 -34
  22. package/dist/{checkBrowser-KAC54SLQ.js → checkBrowser-GZJ3W2OP.js} +29 -29
  23. package/dist/{chunk-AHE4R7PV.js → chunk-2KZSKIYY.js} +1 -1
  24. package/dist/chunk-2ONVJ7NT.js +3901 -0
  25. package/dist/{chunk-5FY7ARKL.js → chunk-3CFTCM7X.js} +1 -1
  26. package/dist/{chunk-SD2IVQXM.js → chunk-4QG64APO.js} +2 -2
  27. package/dist/{chunk-ZE6CLWXL.js → chunk-65HUC64P.js} +1 -1
  28. package/dist/{chunk-PRURJIVL.js → chunk-6RRO4GE3.js} +1 -1
  29. package/dist/{chunk-6UX32GRW.js → chunk-7QB46WTF.js} +1 -1
  30. package/dist/{chunk-B6D7KOXQ.js → chunk-7SKOZHIY.js} +2 -2
  31. package/dist/{chunk-IY2NZKMG.js → chunk-7YZME6DE.js} +1 -1
  32. package/dist/{chunk-DTC4KKFP.js → chunk-AHZLNYZY.js} +1 -1
  33. package/dist/{chunk-4FXJ54L4.js → chunk-BFYDVTD3.js} +1 -1
  34. package/dist/{chunk-2R7QYR2D.js → chunk-BYLC52GJ.js} +1 -1
  35. package/dist/{chunk-MGSQPE6P.js → chunk-CMHVLASW.js} +1 -1
  36. package/dist/{chunk-POYHL7UJ.js → chunk-D5CZCYYT.js} +2 -2
  37. package/dist/{chunk-NAZ54XAE.js → chunk-DMRDGGNM.js} +6 -6
  38. package/dist/{chunk-XE5DW6UC.js → chunk-DWUOGV3M.js} +3 -3
  39. package/dist/{chunk-46J53I7B.js → chunk-FHDKRWQN.js} +54 -16
  40. package/dist/{chunk-GC4NUZAR.js → chunk-FV5GKRAO.js} +3 -3
  41. package/dist/{chunk-WWE73ZFN.js → chunk-FZ2VPLXL.js} +2 -2
  42. package/dist/{chunk-4MNF7ALL.js → chunk-GQACWAOC.js} +1 -1
  43. package/dist/{chunk-33BFEUCL.js → chunk-HK45GJMI.js} +748 -432
  44. package/dist/{chunk-BF3ACZAB.js → chunk-HOAXHVRR.js} +9 -9
  45. package/dist/{chunk-GI2WXOY5.js → chunk-HRZ6ZBKO.js} +2 -2
  46. package/dist/{chunk-YUODO5H2.js → chunk-IC6BO4GU.js} +25 -2
  47. package/dist/{chunk-IFOJM6PV.js → chunk-IELYOY6S.js} +3 -3
  48. package/dist/{chunk-RHYXITPN.js → chunk-ILFDFMYJ.js} +3 -3
  49. package/dist/{chunk-3DEBV7RH.js → chunk-IMVTN367.js} +2 -2
  50. package/dist/{chunk-454VK7CA.js → chunk-JFIEV2J4.js} +7 -7
  51. package/dist/{chunk-WNLHEUZU.js → chunk-JN63IPHT.js} +1 -1
  52. package/dist/{chunk-3HOQ5ZMS.js → chunk-K5O6JTJQ.js} +5 -5
  53. package/dist/{chunk-ZAY376M4.js → chunk-K65XUUJX.js} +1 -1
  54. package/dist/{chunk-BNMVX4JK.js → chunk-KFZPWUPN.js} +7 -7
  55. package/dist/{chunk-GM6WM6YH.js → chunk-KG3BVLA4.js} +1 -1
  56. package/dist/{chunk-T3CBCGU4.js → chunk-L6FG62QM.js} +43 -24
  57. package/dist/{chunk-PDDVEHWJ.js → chunk-LPDNR3R4.js} +2 -2
  58. package/dist/{chunk-WKHPW2BC.js → chunk-M2GO2AAS.js} +1 -1
  59. package/dist/{chunk-AXJMD32I.js → chunk-M6IMQBK6.js} +1 -1
  60. package/dist/{chunk-VFSFTVOT.js → chunk-NUZMP7SV.js} +17 -17
  61. package/dist/{chunk-5L6UY76S.js → chunk-NY2OH5XD.js} +1 -1
  62. package/dist/{chunk-BXXEQFRW.js → chunk-OZVRCLEN.js} +2 -2
  63. package/dist/{chunk-FUAS4KCJ.js → chunk-PO5PAROC.js} +3 -3
  64. package/dist/{chunk-6NLPPKBO.js → chunk-PSX5SF2N.js} +36 -0
  65. package/dist/{chunk-WY6X5Q33.js → chunk-QH4425AL.js} +1 -1
  66. package/dist/{chunk-7JMUJID2.js → chunk-QYOUK3UO.js} +1 -1
  67. package/dist/{chunk-X73MOLUS.js → chunk-RYCANWOM.js} +4 -4
  68. package/dist/{chunk-6DMFWXDH.js → chunk-S5WSJVHP.js} +3 -3
  69. package/dist/{chunk-UP7IRMTI.js → chunk-SQQZUUK6.js} +9 -9
  70. package/dist/{chunk-RNPTRRLX.js → chunk-T4IJMVCB.js} +1 -1
  71. package/dist/{chunk-FFPKJU7T.js → chunk-TF7LCULS.js} +2 -2
  72. package/dist/{chunk-6LN4GQH3.js → chunk-TTWFTEUG.js} +5 -5
  73. package/dist/{chunk-IHSFWHXI.js → chunk-TVR744AS.js} +2 -2
  74. package/dist/{chunk-C4REI4HU.js → chunk-UBSAHYWA.js} +2 -2
  75. package/dist/{chunk-2C4VIQ2H.js → chunk-UMBCYIFE.js} +1 -1
  76. package/dist/{chunk-IK4Q7EKF.js → chunk-UVQLSMAR.js} +27 -4
  77. package/dist/{chunk-J756NYRP.js → chunk-VWPU6URV.js} +5 -5
  78. package/dist/{chunk-GGURM4ZM.js → chunk-XP55QWOB.js} +13 -13
  79. package/dist/{chunk-OEC7RJVD.js → chunk-XVZZQVT4.js} +1 -1
  80. package/dist/{chunk-X56HO2IP.js → chunk-YAMRODVV.js} +3 -2
  81. package/dist/{chunk-KBVJ6G65.js → chunk-Z6Q4ASCD.js} +107 -44
  82. package/dist/{clean-JM6Y5V2G.js → clean-QX6LKOWJ.js} +15 -15
  83. package/dist/cli.js +54 -54
  84. package/dist/{cloud-DWKTRWWB.js → cloud-ASA7Y3HA.js} +4 -4
  85. package/dist/{cloudrun-HLUQOVRO.js → cloudrun-LK4GJWUZ.js} +4 -4
  86. package/dist/{compare-GVTQBP4N.js → compare-426Z2ND6.js} +26 -26
  87. package/dist/{compiler-3MDCAKFB.js → compiler-WER7FC5O.js} +3 -3
  88. package/dist/{component-QSRD6BSP.js → component-HTDWZMEG.js} +3 -3
  89. package/dist/{compositions-BDITIWMO.js → compositions-EKRLQ5TU.js} +11 -11
  90. package/dist/{delete-G2MXPSLU.js → delete-KHXM6R7A.js} +3 -3
  91. package/dist/{deploy-Q7RDYGFL.js → deploy-WJ5JQJBD.js} +1 -1
  92. package/dist/{dist-WHAM6TAE.js → dist-EYJATCTF.js} +2 -2
  93. package/dist/{dist-XPD7X6JB.js → dist-ONHJ6ZDA.js} +1 -1
  94. package/dist/{doctor-Q7SJW3MZ.js → doctor-NB3G2GDG.js} +11 -11
  95. package/dist/{events-DOABLVUG.js → events-6EL5NIJV.js} +3 -3
  96. package/dist/{events-XEAJVOX2.js → events-LH6W5ZCV.js} +4 -4
  97. package/dist/{feedback-K7I2FQQF.js → feedback-2GNY725M.js} +7 -7
  98. package/dist/{ffmpeg-2LKYJYAF.js → ffmpeg-XX3O53B3.js} +6 -6
  99. package/dist/{figma-LXJRAIDI.js → figma-X7KKOOXB.js} +3 -3
  100. package/dist/fontLocalizeCli.js +8 -8
  101. package/dist/{get-EDCTYZB6.js → get-M57U7QCX.js} +3 -3
  102. package/dist/{gpuPolicy-4YOOXLBX.js → gpuPolicy-GIBBYBI5.js} +6 -6
  103. package/dist/{grade-compare-ZWUXB3MD.js → grade-compare-XNY37UYQ.js} +27 -27
  104. package/dist/{help-LEZ3E433.js → help-ZXSPZBUG.js} +1 -1
  105. package/dist/{history-YD7OKO74.js → history-G5B4IPBH.js} +7 -7
  106. package/dist/hyperframe.manifest.json +1 -1
  107. package/dist/hyperframe.runtime.iife.js +59 -59
  108. package/dist/hyperframes-player.global.js +1 -1
  109. package/dist/{info-SI2KU7J7.js → info-ZWZDG54W.js} +8 -8
  110. package/dist/{init-INX5WA2G.js → init-F4XMU6SV.js} +27 -27
  111. package/dist/{inspect-SJENYN3F.js → inspect-6VXFMQRR.js} +27 -27
  112. package/dist/{installer-JQ6DMFZ2.js → installer-4M3Y5T5F.js} +4 -4
  113. package/dist/{keyframes-EAVHD4PM.js → keyframes-3U466AWX.js} +7 -7
  114. package/dist/{lambda-323RMLN5.js → lambda-OPSTAEF6.js} +6 -6
  115. package/dist/{layout-JGCQYWWK.js → layout-B3MXD3F3.js} +27 -27
  116. package/dist/{lint-SFE43W5P.js → lint-TVOEGW63.js} +8 -8
  117. package/dist/{lintProject-Q4ZVEF3G.js → lintProject-FKPKSU6M.js} +1 -1
  118. package/dist/{list-N2NSYK6G.js → list-M5GQSFVT.js} +3 -3
  119. package/dist/{login-QGISW3KF.js → login-HBHGZIDN.js} +4 -4
  120. package/dist/{manager-IXZJADWC.js → manager-VLIJARMF.js} +7 -7
  121. package/dist/{media-treatment-BTA7BV52.js → media-treatment-RQZ437VS.js} +13 -13
  122. package/dist/{models-NZEBSWXZ.js → models-2CCKVBTR.js} +10 -10
  123. package/dist/{motionShot-E4GNRX4N.js → motionShot-3IFRSICA.js} +14 -14
  124. package/dist/{normalize-audio-F4Q5ZX5R.js → normalize-audio-23H2MBDP.js} +5 -5
  125. package/dist/{open-A4U2RXCG.js → open-J33KT3G7.js} +12 -12
  126. package/dist/{parakeetRunner-OVNNGTEB.js → parakeetRunner-QTXNEMVY.js} +11 -11
  127. package/dist/{pipeline-Z76DCEY7.js → pipeline-2ECWWEBD.js} +7 -7
  128. package/dist/{play-NWSZMZZG.js → play-G5777L7A.js} +18 -18
  129. package/dist/{preflight-I6UXFNYV.js → preflight-NVFB4HXQ.js} +7 -7
  130. package/dist/{present-QFZQ5VRM.js → present-4EI2BE4Z.js} +14 -14
  131. package/dist/{preview-GXNG3UOV.js → preview-HYCIDZ52.js} +18 -18
  132. package/dist/{producer-MGXGNSQX.js → producer-6JAATJVD.js} +1 -1
  133. package/dist/{projectConfig-TNL3ZDIP.js → projectConfig-XPGN76VV.js} +6 -6
  134. package/dist/{publication-OO772CBM.js → publication-YRZ7EBUV.js} +2 -2
  135. package/dist/{publish-X33ZCMFO.js → publish-UIDHN7KD.js} +8 -8
  136. package/dist/{remove-background-JAD2RBYP.js → remove-background-LPQP4WBN.js} +8 -8
  137. package/dist/{render-OJEKVJNG.js → render-DT3OCUCV.js} +117 -37
  138. package/dist/{render-2FX26ITP.js → render-LFJQNVCK.js} +5 -5
  139. package/dist/{render-BZCK6XNT.js → render-NZSNQFYW.js} +14 -14
  140. package/dist/{render-batch-SP6HKIF4.js → render-batch-QI2A45WH.js} +5 -5
  141. package/dist/renderSetupWorker.js +1 -1
  142. package/dist/{resolver-QB7L6U4Q.js → resolver-4YDXG4PP.js} +4 -4
  143. package/dist/{sherpa-BZLXBJTD.js → sherpa-XLKWFYFO.js} +10 -10
  144. package/dist/skills/media-use/references/mixing.md +1 -0
  145. package/dist/{skills-OMKCU4HZ.js → skills-OVVLZHF5.js} +6 -6
  146. package/dist/{skillsUpdateCheck-NNURJXBS.js → skillsUpdateCheck-Y2UQA7I5.js} +4 -4
  147. package/dist/{snapshot-J7Y3PCCI.js → snapshot-7NVB5WSO.js} +50 -36
  148. package/dist/{src-T5WHBOD2.js → src-ACAFJXAJ.js} +7 -7
  149. package/dist/{src-2YZVFDNC.js → src-QQPHMIJ7.js} +11 -5
  150. package/dist/{staticProjectServer-PHNKV2NL.js → staticProjectServer-JUN6BRTW.js} +14 -14
  151. package/dist/studio/assets/{hyperframes-player-Cyi8HgFo.js → hyperframes-player-BDtBfwof.js} +1 -1
  152. package/dist/studio/assets/{index-DG6ZXBnu.js → index--W_0fuR8.js} +1 -1
  153. package/dist/studio/assets/{index-6njHuMnJ.js → index-BFfBBQMu.js} +4 -4
  154. package/dist/studio/index.html +1 -1
  155. package/dist/{studio-api-VLJJP2GQ.js → studio-api-D76Q4Q2N.js} +7 -7
  156. package/dist/{studioServer-G7RGGTWJ.js → studioServer-HG3RFAOY.js} +45 -45
  157. package/dist/{telemetry-4K6CPMNT.js → telemetry-IHU4HL3R.js} +1 -1
  158. package/dist/{telemetry-2R6G2A54.js → telemetry-Q2EHWVO4.js} +4 -4
  159. package/dist/{timeline-B2CM5IZO.js → timeline-WDQCCETQ.js} +16 -16
  160. package/dist/{tokens-7EOFUTMX.js → tokens-2GJWP2HY.js} +2 -2
  161. package/dist/{transcribe-7GTD3CEW.js → transcribe-SRLAY6RG.js} +9 -9
  162. package/dist/{transcribe-YJM673R7.js → transcribe-Z63Y53GQ.js} +16 -16
  163. package/dist/{updateCheck-JBIJ7L2D.js → updateCheck-MJ6NDE3T.js} +3 -3
  164. package/dist/{upgrade-WF2CBHOE.js → upgrade-D5XEX3XE.js} +3 -3
  165. package/dist/{urlDownloader-HMXLCV4T.js → urlDownloader-R7BZ47TY.js} +5 -5
  166. package/dist/{validate-OHWQ7DQO.js → validate-F5BIDZLN.js} +21 -21
  167. package/dist/{video-OEEM43V6.js → video-QUG5OG5Q.js} +6 -6
  168. package/dist/warmCheck.js +34 -34
  169. package/package.json +1 -1
  170. package/dist/chunk-G5RNOVAV.js +0 -3901
@@ -8,7 +8,7 @@ import {
8
8
  EncoderInterruptedError,
9
9
  encoderFailureError,
10
10
  prepareAnimatedGifInputs
11
- } from "./chunk-B6D7KOXQ.js";
11
+ } from "./chunk-7SKOZHIY.js";
12
12
  import {
13
13
  GENERIC_FAMILIES,
14
14
  collectFontFamilyCustomProperties,
@@ -144,6 +144,7 @@ import {
144
144
  resolveConfig,
145
145
  resolveDeVerifyMinDb,
146
146
  resolveFinalFrameExtractionWindow,
147
+ resolveFrameFormat,
147
148
  resolveHeadlessShellPath,
148
149
  resolvePlayableVideoDuration,
149
150
  resolveVideoExtractionWindow,
@@ -160,7 +161,7 @@ import {
160
161
  verifyDiskDrawElementSamples,
161
162
  videoAudioId,
162
163
  writeCapturedFrame
163
- } from "./chunk-T3CBCGU4.js";
164
+ } from "./chunk-L6FG62QM.js";
164
165
  import {
165
166
  DISTRIBUTED_FPS,
166
167
  HF_VFX_ATTR,
@@ -176,7 +177,7 @@ import {
176
177
  parseVfxChain,
177
178
  resolveAuthoredTimingWindow,
178
179
  toFps
179
- } from "./chunk-IK4Q7EKF.js";
180
+ } from "./chunk-UVQLSMAR.js";
180
181
  import {
181
182
  assignBundledRuntimeCompositionIds,
182
183
  buildVariablesByCompScript,
@@ -188,7 +189,7 @@ import {
188
189
  inlineSubCompositions,
189
190
  parsesAsScript,
190
191
  prepareFlattenedInnerRoot
191
- } from "./chunk-GI2WXOY5.js";
192
+ } from "./chunk-HRZ6ZBKO.js";
192
193
  import {
193
194
  COMPOSITION_SOURCE_URL,
194
195
  HF_COLOR_GRADING_ATTR,
@@ -219,7 +220,7 @@ import {
219
220
  sourceTimeAt,
220
221
  styleElementsFor,
221
222
  timeAtSourceTime
222
- } from "./chunk-G5RNOVAV.js";
223
+ } from "./chunk-2ONVJ7NT.js";
223
224
  import {
224
225
  MAX_AUDIO_GAIN
225
226
  } from "./chunk-X7HBSTCZ.js";
@@ -249,7 +250,7 @@ import {
249
250
  import {
250
251
  lintHyperframeHtml,
251
252
  resolveReferencedStart
252
- } from "./chunk-YUODO5H2.js";
253
+ } from "./chunk-IC6BO4GU.js";
253
254
  import {
254
255
  isUnresolvedAssetPlaceholder,
255
256
  readProjectFile,
@@ -289,14 +290,14 @@ import {
289
290
  mkdirSync as mkdirSync8,
290
291
  readFileSync as readFileSync7,
291
292
  readdirSync as readdirSync5,
292
- rmSync as rmSync9,
293
- statSync as statSync5,
293
+ rmSync as rmSync10,
294
+ statSync as statSync6,
294
295
  writeFileSync as writeFileSync5,
295
296
  copyFileSync as copyFileSync3,
296
297
  appendFileSync
297
298
  } from "fs";
298
299
  import { tmpdir as tmpdir2 } from "os";
299
- import { join as join24, dirname as dirname9, resolve as resolve6 } from "path";
300
+ import { join as join25, dirname as dirname9, resolve as resolve6 } from "path";
300
301
  import { totalmem as totalmem2 } from "os";
301
302
  import { randomUUID } from "crypto";
302
303
  import { fileURLToPath as fileURLToPath4 } from "url";
@@ -2093,8 +2094,8 @@ function replanAfterFailure(plan2, failure) {
2093
2094
  }
2094
2095
 
2095
2096
  // ../producer/src/services/render/stages/captureSegmentedStage.ts
2096
- import { existsSync as existsSync6, mkdirSync as mkdirSync3, rmSync as rmSync5, statSync as statSync2 } from "fs";
2097
- import { join as join9 } from "path";
2097
+ import { existsSync as existsSync6, mkdirSync as mkdirSync3, rmSync as rmSync6, statSync as statSync3 } from "fs";
2098
+ import { join as join10 } from "path";
2098
2099
 
2099
2100
  // ../producer/src/services/render/perfSummary.ts
2100
2101
  import { arch, cpus, platform, totalmem } from "os";
@@ -2452,7 +2453,7 @@ function getCaptureStageBrowserConsole(error) {
2452
2453
  }
2453
2454
 
2454
2455
  // ../producer/src/services/hdrCompositor.ts
2455
- import { readSync as readSync2, closeSync as closeSync3 } from "fs";
2456
+ import { readSync as readSync2 } from "fs";
2456
2457
  import { join as join6 } from "path";
2457
2458
  function countNonZeroAlpha(rgba) {
2458
2459
  let n = 0;
@@ -2492,10 +2493,10 @@ function cropRgb48le(src, srcW, srcH, cropX, cropY, cropW, cropH) {
2492
2493
  }
2493
2494
  function closeHdrVideoFrameSource(source, log) {
2494
2495
  try {
2495
- closeSync3(source.fd);
2496
+ source.windows.close();
2496
2497
  } catch (err) {
2497
- log?.warn("Failed to close HDR raw frame file", {
2498
- rawPath: source.rawPath,
2498
+ log?.warn("Failed to close HDR raw frame windows", {
2499
+ dir: source.dir,
2499
2500
  error: err instanceof Error ? err.message : String(err)
2500
2501
  });
2501
2502
  }
@@ -2505,7 +2506,7 @@ function resolveHdrVideoFrameIndex(time, startTime, fps, frameCount, loop = fals
2505
2506
  if (frameIndex < 0 || frameCount < 1) return null;
2506
2507
  return loop ? frameIndex % frameCount : Math.min(frameIndex, frameCount - 1);
2507
2508
  }
2508
- function blitHdrVideoLayer(canvas, el, time, fps, hdrVideoFrameSources, hdrStartTimes, width, height, log, sourceTransfer, targetTransfer, hdrPerf) {
2509
+ async function blitHdrVideoLayer(canvas, el, time, fps, hdrVideoFrameSources, hdrStartTimes, width, height, log, sourceTransfer, targetTransfer, hdrPerf) {
2509
2510
  const frameSource = hdrVideoFrameSources.get(el.id);
2510
2511
  const startTime = hdrStartTimes.get(el.id);
2511
2512
  if (!frameSource || startTime === void 0 || el.opacity <= 0) {
@@ -2521,13 +2522,32 @@ function blitHdrVideoLayer(canvas, el, time, fps, hdrVideoFrameSources, hdrStart
2521
2522
  if (effectiveIndex === null) return;
2522
2523
  const mediaTime = (frameSource.mediaStart ?? 0) + effectiveIndex / fps;
2523
2524
  if (isVideoHiddenBeforeStreamStart(frameSource.videoStreamLeadSeconds, mediaTime)) return;
2524
- const frameOffset = effectiveIndex * frameSource.frameSize;
2525
+ if (hdrPerf) hdrPerf.hdrVideoLayerBlits += 1;
2526
+ const lease = await frameSource.windows.lease(effectiveIndex);
2527
+ if (!lease) return;
2528
+ try {
2529
+ blitScratchFrameWithoutYielding(
2530
+ canvas,
2531
+ el,
2532
+ frameSource,
2533
+ lease,
2534
+ width,
2535
+ height,
2536
+ log,
2537
+ sourceTransfer,
2538
+ targetTransfer,
2539
+ hdrPerf
2540
+ );
2541
+ } finally {
2542
+ lease.release();
2543
+ }
2544
+ }
2545
+ function blitScratchFrameWithoutYielding(canvas, el, frameSource, lease, width, height, log, sourceTransfer, targetTransfer, hdrPerf) {
2525
2546
  try {
2526
- if (hdrPerf) hdrPerf.hdrVideoLayerBlits += 1;
2527
2547
  const bytesRead = timeHdrPhase(
2528
2548
  hdrPerf,
2529
2549
  "hdrVideoReadDecodeMs",
2530
- () => readSync2(frameSource.fd, frameSource.scratch, 0, frameSource.frameSize, frameOffset)
2550
+ () => readSync2(lease.fd, frameSource.scratch, 0, frameSource.frameSize, lease.offset)
2531
2551
  );
2532
2552
  if (bytesRead !== frameSource.frameSize) return;
2533
2553
  const hdrRgb = frameSource.scratch;
@@ -2756,7 +2776,7 @@ async function compositeHdrFrame(ctx, canvas, time, fullStacking, elementFilter,
2756
2776
  hdrPerf
2757
2777
  );
2758
2778
  } else {
2759
- blitHdrVideoLayer(
2779
+ await blitHdrVideoLayer(
2760
2780
  canvas,
2761
2781
  layer.element,
2762
2782
  time,
@@ -2800,7 +2820,7 @@ async function compositeHdrFrame(ctx, canvas, time, fullStacking, elementFilter,
2800
2820
  startTime,
2801
2821
  localTime: localTime.toFixed(3),
2802
2822
  hdrFrameNum: frameNum,
2803
- rawPath: frameSource?.rawPath ?? null,
2823
+ dir: frameSource?.dir ?? null,
2804
2824
  frameCount: frameSource?.frameCount ?? null
2805
2825
  });
2806
2826
  }
@@ -2896,19 +2916,92 @@ async function compositeHdrFrame(ctx, canvas, time, fullStacking, elementFilter,
2896
2916
  }
2897
2917
 
2898
2918
  // ../producer/src/services/render/stages/captureHdrResources.ts
2899
- import {
2900
- closeSync as closeSync4,
2901
- constants as constants2,
2902
- fstatSync as fstatSync3,
2903
- mkdirSync as mkdirSync2,
2904
- mkdtempSync as mkdtempSync2,
2905
- openSync as openSync3,
2906
- readFileSync as readFileSync3,
2907
- rmSync as rmSync4,
2908
- statfsSync
2909
- } from "fs";
2919
+ import { mkdirSync as mkdirSync2, mkdtempSync as mkdtempSync2, readFileSync as readFileSync3, rmSync as rmSync5, statSync as statSync2, statfsSync } from "fs";
2920
+ import { join as join8 } from "path";
2921
+
2922
+ // ../producer/src/services/hdrFrameWindows.ts
2923
+ import { closeSync as closeSync3, constants as constants2, openSync as openSync3, rmSync as rmSync4 } from "fs";
2910
2924
  import { join as join7 } from "path";
2911
- var NO_FOLLOW_FLAG = constants2.O_NOFOLLOW ?? 0;
2925
+ function createHdrFrameWindows(opts) {
2926
+ const { dir, frameSize, windowFrames, maxResident, extract } = opts;
2927
+ let totalFrames = opts.totalFrames;
2928
+ const windows = /* @__PURE__ */ new Map();
2929
+ const drop = (index, w) => {
2930
+ windows.delete(index);
2931
+ if (w.fd >= 0) closeSync3(w.fd);
2932
+ rmSync4(w.path, { force: true });
2933
+ };
2934
+ const open2 = (index) => {
2935
+ const known = windows.get(index);
2936
+ if (known) {
2937
+ windows.delete(index);
2938
+ windows.set(index, known);
2939
+ return known;
2940
+ }
2941
+ for (const [i, w2] of windows) {
2942
+ if (windows.size < maxResident) break;
2943
+ if (w2.pins === 0) drop(i, w2);
2944
+ }
2945
+ const firstFrame = index * windowFrames;
2946
+ const w = {
2947
+ firstFrame,
2948
+ path: join7(dir, `window-${index}.rgb48le`),
2949
+ frames: 0,
2950
+ fd: -1,
2951
+ pins: 0,
2952
+ ready: Promise.resolve()
2953
+ };
2954
+ w.ready = extract({
2955
+ firstFrame,
2956
+ frames: Math.min(windowFrames, totalFrames - firstFrame),
2957
+ path: w.path
2958
+ }).then((produced) => {
2959
+ if (produced < 1) return;
2960
+ w.fd = openSync3(w.path, constants2.O_RDONLY | (constants2.O_NOFOLLOW ?? 0));
2961
+ w.frames = produced;
2962
+ });
2963
+ windows.set(index, w);
2964
+ return w;
2965
+ };
2966
+ return {
2967
+ get totalFrames() {
2968
+ return totalFrames;
2969
+ },
2970
+ async lease(frameIndex) {
2971
+ for (; ; ) {
2972
+ if (totalFrames < 1) return null;
2973
+ const index = Math.min(Math.max(0, frameIndex), totalFrames - 1);
2974
+ const key = Math.floor(index / windowFrames);
2975
+ const w = open2(key);
2976
+ w.pins += 1;
2977
+ try {
2978
+ await w.ready;
2979
+ } catch (error) {
2980
+ w.pins -= 1;
2981
+ windows.delete(key);
2982
+ throw error;
2983
+ }
2984
+ const local = index - w.firstFrame;
2985
+ if (local < w.frames) {
2986
+ return {
2987
+ fd: w.fd,
2988
+ offset: local * frameSize,
2989
+ release: () => {
2990
+ w.pins -= 1;
2991
+ }
2992
+ };
2993
+ }
2994
+ w.pins -= 1;
2995
+ totalFrames = Math.min(totalFrames, w.firstFrame + w.frames);
2996
+ }
2997
+ },
2998
+ close() {
2999
+ for (const [i, w] of [...windows]) drop(i, w);
3000
+ }
3001
+ };
3002
+ }
3003
+
3004
+ // ../producer/src/services/render/stages/captureHdrResources.ts
2912
3005
  function tempDirSafePrefix(id) {
2913
3006
  const safe = id.replace(/[^A-Za-z0-9_.-]/g, "_").slice(0, 80);
2914
3007
  return safe || "video";
@@ -2953,10 +3046,16 @@ async function probeHdrExtractionDims(args) {
2953
3046
  const stacking = await queryElementStacking(domSession.page, nativeHdrIds);
2954
3047
  for (const el of stacking) {
2955
3048
  if (el.isHdr && el.layoutWidth > 0 && el.layoutHeight > 0 && !prep.hdrExtractionDims.has(el.id)) {
2956
- prep.hdrExtractionDims.set(el.id, { width: el.layoutWidth, height: el.layoutHeight });
3049
+ prep.hdrExtractionDims.set(el.id, {
3050
+ width: el.layoutWidth,
3051
+ height: el.layoutHeight
3052
+ });
2957
3053
  }
2958
3054
  if (el.isHdr && nativeHdrImageIds.has(el.id) && !prep.hdrImageFitInfo.has(el.id)) {
2959
- prep.hdrImageFitInfo.set(el.id, { fit: el.objectFit, position: el.objectPosition });
3055
+ prep.hdrImageFitInfo.set(el.id, {
3056
+ fit: el.objectFit,
3057
+ position: el.objectPosition
3058
+ });
2960
3059
  }
2961
3060
  }
2962
3061
  }
@@ -2975,23 +3074,21 @@ async function probeHdrExtractionDims(args) {
2975
3074
  const retryStacking = await queryElementStacking(domSession.page, nativeHdrIds);
2976
3075
  for (const el of retryStacking) {
2977
3076
  if (el.id === imageId && el.isHdr && el.layoutWidth > 0 && el.layoutHeight > 0) {
2978
- prep.hdrExtractionDims.set(el.id, { width: el.layoutWidth, height: el.layoutHeight });
3077
+ prep.hdrExtractionDims.set(el.id, {
3078
+ width: el.layoutWidth,
3079
+ height: el.layoutHeight
3080
+ });
2979
3081
  if (!prep.hdrImageFitInfo.has(el.id)) {
2980
- prep.hdrImageFitInfo.set(el.id, { fit: el.objectFit, position: el.objectPosition });
3082
+ prep.hdrImageFitInfo.set(el.id, {
3083
+ fit: el.objectFit,
3084
+ position: el.objectPosition
3085
+ });
2981
3086
  }
2982
3087
  break;
2983
3088
  }
2984
3089
  }
2985
3090
  }
2986
3091
  }
2987
- function estimateHdrExtractionBytes(videos, fps) {
2988
- let total = 0;
2989
- for (const v of videos) {
2990
- const frames = Math.ceil(Math.max(0, v.durationSeconds) * fps);
2991
- total += frames * v.width * v.height * 6;
2992
- }
2993
- return total;
2994
- }
2995
3092
  var HDR_EXTRACTION_HEADROOM_FRACTION = 0.9;
2996
3093
  var HDR_EXTRACTION_CGROUP_BUDGET_FRACTION = 0.5;
2997
3094
  var HDR_EXTRACTION_WARN_BYTES = 1e10;
@@ -3055,24 +3152,22 @@ function resolveHdrExtractionWindow(video, compositionDuration, metadata) {
3055
3152
  }
3056
3153
  return window2;
3057
3154
  }
3058
- function cleanupHdrFrameDirectory(frameDir, rawPath, log) {
3155
+ function cleanupHdrFrameDirectory(frameDir, log) {
3059
3156
  if (process.env.KEEP_TEMP === "1") return;
3060
3157
  try {
3061
- rmSync4(frameDir, { recursive: true, force: true });
3158
+ rmSync5(frameDir, { recursive: true, force: true });
3062
3159
  } catch (err) {
3063
3160
  log?.warn("Failed to clean up HDR raw frame directory", {
3064
3161
  frameDir,
3065
- rawPath,
3066
3162
  error: err instanceof Error ? err.message : String(err)
3067
3163
  });
3068
3164
  }
3069
3165
  }
3070
3166
  function cleanupHdrVideoFrameSource(source, log) {
3071
3167
  closeHdrVideoFrameSource(source, log);
3072
- cleanupHdrFrameDirectory(source.dir, source.rawPath, log);
3168
+ cleanupHdrFrameDirectory(source.dir, log);
3073
3169
  }
3074
- function assertHdrExtractionDiskHeadroom(framesDir, plannedVideos, fps, log) {
3075
- const estimatedBytes = estimateHdrExtractionBytes(plannedVideos, fps);
3170
+ function assertHdrExtractionDiskHeadroom(framesDir, estimatedBytes, log) {
3076
3171
  const configuredBudget = resolveHdrExtractionBudgetBytes(
3077
3172
  process.env[HDR_EXTRACTION_MAX_BYTES_ENV]
3078
3173
  );
@@ -3106,14 +3201,29 @@ function assertHdrExtractionDiskHeadroom(framesDir, plannedVideos, fps, log) {
3106
3201
  budgetBytes: resolveHdrExtractionActiveBudgetBytes(configuredBudget, freeBytes)
3107
3202
  };
3108
3203
  }
3204
+ var DEFAULT_HDR_WINDOW_BYTES = 512 * BYTES_PER_MIB;
3205
+ function hdrWindowFrames(frameSize, windowBytes) {
3206
+ return Math.max(8, Math.floor(windowBytes / frameSize));
3207
+ }
3208
+ async function probeFirstTick(srcPath, mediaStart, fps, runFfmpegImpl, abortSignal) {
3209
+ const args = ["-ss", String(mediaStart), "-i", srcPath, "-frames:v", "1"];
3210
+ const result = await runFfmpegImpl([...args, ...["-vf", "showinfo", "-f", "null", "-"]], {
3211
+ signal: abortSignal
3212
+ });
3213
+ const match = /pts_time:(-?[\d.]+)/.exec(result.stderr);
3214
+ return match ? Math.max(0, Math.floor(Number(match[1]) * fps + 0.5)) : 0;
3215
+ }
3109
3216
  async function extractHdrVideoFrames(args) {
3110
3217
  const { job, log, framesDir, composition, prep, width, height, abortSignal, hdrDiagnostics } = args;
3218
+ const maxResident = Math.max(2, args.maxResidentWindows ?? 2);
3219
+ const windowBytes = args.windowBytes ?? DEFAULT_HDR_WINDOW_BYTES;
3111
3220
  const runFfmpegImpl = args.runFfmpegImpl ?? runFfmpeg;
3112
3221
  const extractMediaMetadataImpl = args.extractMediaMetadataImpl ?? extractMediaMetadata;
3113
3222
  const resolveFinalFrameExtractionWindowImpl = args.resolveFinalFrameExtractionWindowImpl ?? resolveFinalFrameExtractionWindow;
3223
+ const fps = fpsToNumber(job.config.fps);
3114
3224
  const out = /* @__PURE__ */ new Map();
3115
3225
  mkdirSync2(framesDir, { recursive: true });
3116
- const plannedVideos = [];
3226
+ let scratchBytes = 0;
3117
3227
  const extractionWindows = /* @__PURE__ */ new Map();
3118
3228
  for (const [videoId, srcPath] of prep.hdrVideoSrcPaths) {
3119
3229
  const video = composition.videos.find((v) => v.id === videoId);
@@ -3134,16 +3244,13 @@ async function extractHdrVideoFrames(args) {
3134
3244
  videoStreamLeadSeconds: metadata.videoStreamLeadSeconds
3135
3245
  });
3136
3246
  prep.hdrVideoStartTimes.set(videoId, window2.compositionStart);
3137
- plannedVideos.push({
3138
- durationSeconds: window2.durationSeconds,
3139
- width: dims.width,
3140
- height: dims.height
3141
- });
3247
+ const frameSize = dims.width * dims.height * 6;
3248
+ const frames = window2.finalFrameOnly ? 1 : Math.ceil(window2.durationSeconds * fps);
3249
+ scratchBytes += Math.min(frames, maxResident * hdrWindowFrames(frameSize, windowBytes)) * frameSize;
3142
3250
  }
3143
3251
  const { estimatedBytes, budgetBytes } = assertHdrExtractionDiskHeadroom(
3144
3252
  framesDir,
3145
- plannedVideos,
3146
- fpsToNumber(job.config.fps),
3253
+ scratchBytes,
3147
3254
  log
3148
3255
  );
3149
3256
  const releaseReservation = reserveHdrExtractionBytes(estimatedBytes, budgetBytes);
@@ -3155,79 +3262,79 @@ async function extractHdrVideoFrames(args) {
3155
3262
  if (!video || !planned) continue;
3156
3263
  const { window: window2 } = planned;
3157
3264
  mkdirSync2(framesDir, { recursive: true });
3158
- const frameDir = mkdtempSync2(join7(framesDir, `hdr_${tempDirSafePrefix(videoId)}-`));
3265
+ const frameDir = mkdtempSync2(join8(framesDir, `hdr_${tempDirSafePrefix(videoId)}-`));
3159
3266
  createdFrameDirs.add(frameDir);
3160
3267
  const dims = prep.hdrExtractionDims.get(videoId) ?? { width, height };
3161
- const rawPath = join7(frameDir, "frames.rgb48le");
3162
- const extractionMediaStart = window2.extractionMediaStart ?? window2.mediaStart;
3163
- const extractionStart = String(extractionMediaStart);
3164
- const ffmpegArgs = [];
3165
- if (window2.finalFrameOnly) {
3166
- ffmpegArgs.push("-i", srcPath, "-ss", extractionStart, "-frames:v", "1");
3167
- } else {
3168
- ffmpegArgs.push(
3169
- "-ss",
3170
- extractionStart,
3171
- "-i",
3172
- srcPath,
3173
- "-t",
3174
- String(window2.durationSeconds)
3175
- );
3176
- }
3177
- if (!window2.finalFrameOnly) {
3178
- ffmpegArgs.push("-r", fpsToFfmpegArg(job.config.fps));
3179
- }
3180
- ffmpegArgs.push(
3181
- "-vf",
3182
- `scale=${dims.width}:${dims.height}:force_original_aspect_ratio=increase,crop=${dims.width}:${dims.height}`,
3183
- "-pix_fmt",
3184
- "rgb48le",
3185
- "-f",
3186
- "rawvideo",
3187
- "-y",
3188
- rawPath
3189
- );
3190
- const result = await runFfmpegImpl(ffmpegArgs, { signal: abortSignal });
3191
- if (!result.success) {
3192
- hdrDiagnostics.videoExtractionFailures += 1;
3193
- log.error("HDR frame pre-extraction failed; aborting render", {
3194
- videoId,
3195
- srcPath,
3196
- stderr: result.stderr.slice(-400)
3197
- });
3198
- throw encoderFailureError(`HDR frame extraction failed for video "${videoId}"`, {
3199
- error: `Aborting render to avoid shipping black HDR layers: ${result.stderr.slice(-400)}`,
3200
- failureReason: result.failureReason
3201
- });
3202
- }
3203
3268
  const frameSize = dims.width * dims.height * 6;
3204
- const fd = openSync3(rawPath, constants2.O_RDONLY | NO_FOLLOW_FLAG);
3205
- let handedOff = false;
3206
- try {
3207
- const frameCount = Math.floor(fstatSync3(fd).size / frameSize);
3208
- if (frameCount < 1) {
3209
- hdrDiagnostics.videoExtractionFailures += 1;
3210
- throw new Error(
3211
- `HDR frame extraction produced no frames for video "${videoId}". Aborting render to avoid shipping black HDR layers.`
3269
+ const extractionMediaStart = window2.extractionMediaStart ?? window2.mediaStart;
3270
+ const scale = `scale=${dims.width}:${dims.height}:force_original_aspect_ratio=increase,crop=${dims.width}:${dims.height}`;
3271
+ const firstTick = window2.finalFrameOnly ? 0 : await probeFirstTick(srcPath, extractionMediaStart, fps, runFfmpegImpl, abortSignal);
3272
+ const totalFrames = window2.finalFrameOnly ? 1 : Math.max(1, Math.ceil(window2.durationSeconds * fps - firstTick - 1e-9)) + Number(video.loop);
3273
+ const windowFrames = Math.min(totalFrames, hdrWindowFrames(frameSize, windowBytes));
3274
+ const windows = createHdrFrameWindows({
3275
+ dir: frameDir,
3276
+ frameSize,
3277
+ totalFrames,
3278
+ windowFrames,
3279
+ maxResident,
3280
+ extract: async (spec) => {
3281
+ const ffmpegArgs = window2.finalFrameOnly ? (
3282
+ // Decode before seeking for the one-frame path. Input-side seeking can
3283
+ // return zero frames for valid unindexed/negative-base transports.
3284
+ ["-i", srcPath, "-ss", String(extractionMediaStart), "-frames:v", "1", "-vf", scale]
3285
+ ) : hdrWindowFfmpegArgs({
3286
+ srcPath,
3287
+ mediaStart: extractionMediaStart,
3288
+ fps,
3289
+ fpsArg: fpsToFfmpegArg(job.config.fps),
3290
+ firstTick,
3291
+ firstFrame: spec.firstFrame,
3292
+ frames: spec.frames,
3293
+ scale
3294
+ });
3295
+ const result = await runFfmpegImpl(
3296
+ [...ffmpegArgs, "-pix_fmt", "rgb48le", "-f", "rawvideo", "-y", spec.path],
3297
+ { signal: abortSignal }
3212
3298
  );
3299
+ if (!result.success) {
3300
+ hdrDiagnostics.videoExtractionFailures += 1;
3301
+ log.error("HDR frame extraction failed; aborting render", {
3302
+ videoId,
3303
+ srcPath,
3304
+ firstFrame: spec.firstFrame,
3305
+ stderr: result.stderr.slice(-400)
3306
+ });
3307
+ throw encoderFailureError(`HDR frame extraction failed for video "${videoId}"`, {
3308
+ error: `Aborting render to avoid shipping black HDR layers: ${result.stderr.slice(-400)}`,
3309
+ failureReason: result.failureReason
3310
+ });
3311
+ }
3312
+ return Math.min(Math.floor(statSync2(spec.path).size / frameSize), spec.frames);
3213
3313
  }
3214
- out.set(videoId, {
3215
- dir: frameDir,
3216
- rawPath,
3217
- fd,
3218
- width: dims.width,
3219
- height: dims.height,
3220
- frameSize,
3221
- frameCount,
3222
- scratch: Buffer.allocUnsafe(frameSize),
3223
- loop: video.loop,
3224
- mediaStart: extractionMediaStart,
3225
- videoStreamLeadSeconds: planned.videoStreamLeadSeconds
3226
- });
3227
- handedOff = true;
3228
- } finally {
3229
- if (!handedOff) closeSync4(fd);
3314
+ });
3315
+ const first = await windows.lease(0);
3316
+ if (!first) {
3317
+ hdrDiagnostics.videoExtractionFailures += 1;
3318
+ throw new Error(
3319
+ `HDR frame extraction produced no frames for video "${videoId}". Aborting render to avoid shipping black HDR layers.`
3320
+ );
3230
3321
  }
3322
+ first.release();
3323
+ if (video.loop) (await windows.lease(totalFrames - 1))?.release();
3324
+ out.set(videoId, {
3325
+ dir: frameDir,
3326
+ windows,
3327
+ width: dims.width,
3328
+ height: dims.height,
3329
+ frameSize,
3330
+ get frameCount() {
3331
+ return windows.totalFrames;
3332
+ },
3333
+ scratch: Buffer.allocUnsafe(frameSize),
3334
+ loop: video.loop,
3335
+ mediaStart: extractionMediaStart,
3336
+ videoStreamLeadSeconds: planned.videoStreamLeadSeconds
3337
+ });
3231
3338
  }
3232
3339
  return { sources: out, estimatedBytes, releaseReservation };
3233
3340
  } catch (error) {
@@ -3236,12 +3343,23 @@ async function extractHdrVideoFrames(args) {
3236
3343
  createdFrameDirs.delete(source.dir);
3237
3344
  }
3238
3345
  for (const frameDir of createdFrameDirs) {
3239
- cleanupHdrFrameDirectory(frameDir, void 0, log);
3346
+ cleanupHdrFrameDirectory(frameDir, log);
3240
3347
  }
3241
3348
  releaseReservation();
3242
3349
  throw error;
3243
3350
  }
3244
3351
  }
3352
+ function hdrWindowFfmpegArgs(a) {
3353
+ const unit = Math.ceil(a.fps);
3354
+ const seekFrame = a.firstFrame < unit ? 0 : (Math.floor(a.firstFrame / unit) - 1) * unit;
3355
+ const trim = a.firstFrame - seekFrame;
3356
+ const filters = [`fps=${a.fpsArg}:start_time=${(a.firstTick / a.fps).toFixed(6)}`, a.scale];
3357
+ if (trim > 0) filters.push(`trim=start_frame=${trim}`);
3358
+ return [
3359
+ ...["-ss", (a.mediaStart + seekFrame / a.fps).toFixed(6), "-i", a.srcPath],
3360
+ ...["-vf", filters.join(","), "-frames:v", String(a.frames)]
3361
+ ];
3362
+ }
3245
3363
  function decodeHdrImageBuffers(args) {
3246
3364
  const { log, hdrImageSrcPaths, prep, hdrDiagnostics } = args;
3247
3365
  const out = /* @__PURE__ */ new Map();
@@ -3261,7 +3379,11 @@ function decodeHdrImageBuffers(args) {
3261
3379
  fit,
3262
3380
  fitInfo?.position
3263
3381
  );
3264
- out.set(imageId, { data: resampled, width: layout.width, height: layout.height });
3382
+ out.set(imageId, {
3383
+ data: resampled,
3384
+ width: layout.width,
3385
+ height: layout.height
3386
+ });
3265
3387
  } else {
3266
3388
  out.set(imageId, {
3267
3389
  data: Buffer.from(decoded.data),
@@ -3373,7 +3495,7 @@ async function captureSceneIntoBuffer(a) {
3373
3495
  hdrPerf
3374
3496
  );
3375
3497
  } else {
3376
- blitHdrVideoLayer(
3498
+ await blitHdrVideoLayer(
3377
3499
  sceneBuf,
3378
3500
  el,
3379
3501
  time,
@@ -3575,7 +3697,7 @@ function isTargetLossError(error) {
3575
3697
  // ../producer/src/services/render/stages/captureStreamingStage.ts
3576
3698
  import { mkdtemp, writeFile } from "fs/promises";
3577
3699
  import { tmpdir } from "os";
3578
- import { join as join8 } from "path";
3700
+ import { join as join9 } from "path";
3579
3701
  var DEFAULT_CAPTURE_STALL_MS = 6e4;
3580
3702
  var DE_STALL_POLL_MS = 5e3;
3581
3703
  var STALL_ADVICE = "Chrome stopped answering. If another app is keeping the GPU or CPU busy (a 3D render, a game, another export), let it finish or render one job at a time, then retry.";
@@ -3717,11 +3839,11 @@ function createDrainFrameGuard(args) {
3717
3839
  return buf;
3718
3840
  }
3719
3841
  if (db < verifyMinDb) {
3720
- const dumpDir = await mkdtemp(join8(tmpdir(), "hf-de-verify-fail-")).catch(() => null);
3842
+ const dumpDir = await mkdtemp(join9(tmpdir(), "hf-de-verify-fail-")).catch(() => null);
3721
3843
  if (dumpDir) {
3722
3844
  await Promise.all([
3723
- writeFile(join8(dumpDir, `frame-${idx}-de.jpg`), buf),
3724
- writeFile(join8(dumpDir, `frame-${idx}-truth.jpg`), truth)
3845
+ writeFile(join9(dumpDir, `frame-${idx}-de.jpg`), buf),
3846
+ writeFile(join9(dumpDir, `frame-${idx}-truth.jpg`), truth)
3725
3847
  ]).catch(() => {
3726
3848
  });
3727
3849
  }
@@ -4170,7 +4292,7 @@ async function runCaptureStreamingStage(input) {
4170
4292
 
4171
4293
  // ../producer/src/services/render/stages/captureSegmentedStage.ts
4172
4294
  function segmentOutputPath(segmentDir, index) {
4173
- return join9(segmentDir, `segment_${String(index).padStart(5, "0")}.mp4`);
4295
+ return join10(segmentDir, `segment_${String(index).padStart(5, "0")}.mp4`);
4174
4296
  }
4175
4297
  function segmentEncoderOptions(base, segment) {
4176
4298
  return {
@@ -4246,7 +4368,7 @@ async function captureSegment(ctx, segment) {
4246
4368
  path: segmentPath,
4247
4369
  // Recorded so resume can prove the file on disk is the one that
4248
4370
  // finished; absent only in unit tests, whose fake encoder writes none.
4249
- bytes: existsSync6(segmentPath) ? statSync2(segmentPath).size : 0
4371
+ bytes: existsSync6(segmentPath) ? statSync3(segmentPath).size : 0
4250
4372
  });
4251
4373
  return encodeResult.durationMs;
4252
4374
  } finally {
@@ -4264,7 +4386,7 @@ var DEFAULT_DEPS = {
4264
4386
  // is invisible to a test that swaps the engine module after this file has
4265
4387
  // been evaluated (bun updates live bindings, not copies).
4266
4388
  closeSession: (session) => closeCaptureSession(session),
4267
- removeFile: (path) => rmSync5(path, { force: true })
4389
+ removeFile: (path) => rmSync6(path, { force: true })
4268
4390
  };
4269
4391
  function defaultSessionFactory(input) {
4270
4392
  let probeSession = input.probeSession;
@@ -4431,7 +4553,7 @@ async function runCaptureSegmentedStage(input) {
4431
4553
  const { log, dedupPerfs, assertNotAborted } = input;
4432
4554
  const deps = { ...DEFAULT_DEPS, ...input.deps };
4433
4555
  const segments = planSegments(input.totalFrames, input.segmentFrames);
4434
- const segmentDir = input.segmentDir ?? join9(input.workDir, "segments");
4556
+ const segmentDir = input.segmentDir ?? join10(input.workDir, "segments");
4435
4557
  mkdirSync3(segmentDir, { recursive: true });
4436
4558
  const skip = input.completedSegments ?? /* @__PURE__ */ new Set();
4437
4559
  const pending = segments.filter((s) => !skip.has(s.index));
@@ -4502,10 +4624,83 @@ async function runCaptureSegmentedStage(input) {
4502
4624
  };
4503
4625
  }
4504
4626
 
4627
+ // ../producer/src/services/render/renderEtaGuard.ts
4628
+ var RENDER_TOO_SLOW = "RENDER_TOO_SLOW";
4629
+ var ETA_MARGIN = 1.2;
4630
+ var MIN_SAMPLE_MS = 6e4;
4631
+ var MIN_SAMPLE_FRAMES = 3;
4632
+ var POLL_MS = 5e3;
4633
+ var RenderTooSlowError = class extends Error {
4634
+ code = RENDER_TOO_SLOW;
4635
+ // The producer server reads these off the error for the wire envelope.
4636
+ // fallow-ignore-next-line unused-class-member
4637
+ owner = "user";
4638
+ // fallow-ignore-next-line unused-class-member
4639
+ retryable = false;
4640
+ publicMetadata;
4641
+ constructor(stage, input) {
4642
+ const { framesCompleted, totalFrames, msPerFrame, etaMs, maxRenderMs } = input;
4643
+ super(
4644
+ `render too slow: stage ${stage}, ${framesCompleted}/${totalFrames} frames, ${Math.round(msPerFrame)} ms/frame, ETA ${etaMs} ms exceeds maxRenderMs ${maxRenderMs}`
4645
+ );
4646
+ this.name = "RenderTooSlowError";
4647
+ this.publicMetadata = { stage, framesCompleted, totalFrames, msPerFrame, etaMs, maxRenderMs };
4648
+ }
4649
+ };
4650
+ function checkRenderEta(stage, input) {
4651
+ const { maxRenderMs, elapsedMs, framesCompleted, totalFrames, msPerFrame } = input;
4652
+ if (!maxRenderMs || maxRenderMs <= 0 || !(msPerFrame > 0)) return void 0;
4653
+ const etaMs = Math.round(elapsedMs + (totalFrames - framesCompleted) * msPerFrame);
4654
+ if (etaMs <= maxRenderMs * ETA_MARGIN) return void 0;
4655
+ return new RenderTooSlowError(stage, { ...input, maxRenderMs, etaMs });
4656
+ }
4657
+ function createRateSampler() {
4658
+ let base;
4659
+ let lastFrames = 0;
4660
+ return {
4661
+ observe(done, at) {
4662
+ if (done === 0 || done < lastFrames) base = void 0;
4663
+ lastFrames = done;
4664
+ if (done === 0) return void 0;
4665
+ base ??= { at, frames: done };
4666
+ const sampleMs = at - base.at;
4667
+ const sampleFrames = done - base.frames;
4668
+ if (sampleMs < MIN_SAMPLE_MS || sampleFrames < MIN_SAMPLE_FRAMES) return void 0;
4669
+ return sampleMs / sampleFrames;
4670
+ }
4671
+ };
4672
+ }
4673
+ function startRenderEtaGuard(options) {
4674
+ const { maxRenderMs, job, totalFrames, pipelineStartMs, onTooSlow, now = Date.now } = options;
4675
+ if (!maxRenderMs || maxRenderMs <= 0) return () => {
4676
+ };
4677
+ const sampler = createRateSampler();
4678
+ const stop = () => clearInterval(timer);
4679
+ const timer = setInterval(() => {
4680
+ const done = job.framesRendered ?? 0;
4681
+ if (done >= totalFrames) return stop();
4682
+ const at = now();
4683
+ const msPerFrame = sampler.observe(done, at);
4684
+ if (msPerFrame === void 0) return;
4685
+ const error = checkRenderEta("capture", {
4686
+ maxRenderMs,
4687
+ elapsedMs: at - pipelineStartMs,
4688
+ framesCompleted: done,
4689
+ totalFrames,
4690
+ msPerFrame
4691
+ });
4692
+ if (!error) return;
4693
+ stop();
4694
+ onTooSlow(error);
4695
+ }, options.pollMs ?? POLL_MS);
4696
+ timer.unref?.();
4697
+ return stop;
4698
+ }
4699
+
4505
4700
  // ../producer/src/services/render/segmentManifest.ts
4506
4701
  import { createHash as createHash2 } from "crypto";
4507
- import { existsSync as existsSync7, mkdirSync as mkdirSync4, readFileSync as readFileSync4, statSync as statSync3, writeFileSync as writeFileSync3 } from "fs";
4508
- import { join as join10 } from "path";
4702
+ import { existsSync as existsSync7, mkdirSync as mkdirSync4, readFileSync as readFileSync4, statSync as statSync4, writeFileSync as writeFileSync3 } from "fs";
4703
+ import { join as join11 } from "path";
4509
4704
  var MANIFEST_FILENAME = "segments.json";
4510
4705
  function computeSegmentPlanHash(input) {
4511
4706
  const ordered = [
@@ -4530,7 +4725,7 @@ function computeSegmentPlanHash(input) {
4530
4725
  return createHash2("sha256").update(ordered).digest("hex").slice(0, 16);
4531
4726
  }
4532
4727
  function segmentDirFor(projectRendersDir, planHash) {
4533
- return join10(projectRendersDir, ".hf-segments", planHash);
4728
+ return join11(projectRendersDir, ".hf-segments", planHash);
4534
4729
  }
4535
4730
  function hasNumber(value, key) {
4536
4731
  return key in value && typeof Reflect.get(value, key) === "number";
@@ -4548,7 +4743,7 @@ function isManifest(value) {
4548
4743
  return Reflect.get(value, "version") === 1 && hasString(value, "planHash") && hasNumber(value, "totalFrames") && hasNumber(value, "segmentFrames") && Array.isArray(completed) && completed.every(isEntry);
4549
4744
  }
4550
4745
  function readSegmentManifest(segmentDir) {
4551
- const path = join10(segmentDir, MANIFEST_FILENAME);
4746
+ const path = join11(segmentDir, MANIFEST_FILENAME);
4552
4747
  if (!existsSync7(path)) return null;
4553
4748
  try {
4554
4749
  const parsed = JSON.parse(readFileSync4(path, "utf-8"));
@@ -4559,9 +4754,9 @@ function readSegmentManifest(segmentDir) {
4559
4754
  }
4560
4755
  function writeSegmentManifest(segmentDir, manifest) {
4561
4756
  mkdirSync4(segmentDir, { recursive: true });
4562
- const tmp = join10(segmentDir, `${MANIFEST_FILENAME}.${process.pid}.tmp`);
4757
+ const tmp = join11(segmentDir, `${MANIFEST_FILENAME}.${process.pid}.tmp`);
4563
4758
  writeFileSync3(tmp, JSON.stringify(manifest, null, 2), "utf-8");
4564
- renameWithRetry(tmp, join10(segmentDir, MANIFEST_FILENAME));
4759
+ renameWithRetry(tmp, join11(segmentDir, MANIFEST_FILENAME));
4565
4760
  }
4566
4761
  async function probeSegmentFrameCount(path, probe) {
4567
4762
  try {
@@ -4579,7 +4774,7 @@ async function validateCompletedSegments(manifest, expectedHash, probeFrames) {
4579
4774
  if (manifest.planHash !== expectedHash) return ok;
4580
4775
  for (const entry of manifest.completed) {
4581
4776
  if (!existsSync7(entry.path)) continue;
4582
- const size = statSync3(entry.path).size;
4777
+ const size = statSync4(entry.path).size;
4583
4778
  if (size <= 0 || size !== entry.bytes) continue;
4584
4779
  const frames = await probeFrames(entry.path);
4585
4780
  if (frames !== entry.endFrame - entry.startFrame) continue;
@@ -4666,7 +4861,7 @@ function resolveVideoCaptureBeyondViewport(videoCount) {
4666
4861
  }
4667
4862
 
4668
4863
  // ../producer/src/services/render/captureCost.ts
4669
- import { join as join11 } from "path";
4864
+ import { join as join12 } from "path";
4670
4865
  var CAPTURE_CALIBRATION_TARGET_MS = 600;
4671
4866
  var MAX_MEASURED_CAPTURE_COST_MULTIPLIER = 8;
4672
4867
  var CAPTURE_CALIBRATION_PROTOCOL_TIMEOUT_MS = 3e4;
@@ -4902,7 +5097,7 @@ async function runCaptureCalibration(input) {
4902
5097
  });
4903
5098
  let calibration;
4904
5099
  try {
4905
- calibration = await runOneCalibration(join11(workDir, "capture-calibration"), calibrationCfg);
5100
+ calibration = await runOneCalibration(join12(workDir, "capture-calibration"), calibrationCfg);
4906
5101
  } catch (error) {
4907
5102
  const shouldFallback = !forceScreenshot && shouldFallbackToScreenshotAfterCalibrationError(error);
4908
5103
  if (!shouldFallback) {
@@ -4935,7 +5130,7 @@ async function runCaptureCalibration(input) {
4935
5130
  const screenshotCfg = createCaptureCalibrationConfig({ ...cfg, forceScreenshot: true });
4936
5131
  try {
4937
5132
  calibration = await runOneCalibration(
4938
- join11(workDir, "capture-calibration-screenshot"),
5133
+ join12(workDir, "capture-calibration-screenshot"),
4939
5134
  screenshotCfg
4940
5135
  );
4941
5136
  } catch (fallbackError) {
@@ -5355,12 +5550,12 @@ function countAuthoredTimedClips(html) {
5355
5550
  }
5356
5551
 
5357
5552
  // ../producer/src/services/render/stages/compileStage.ts
5358
- import { join as join13 } from "path";
5553
+ import { join as join14 } from "path";
5359
5554
 
5360
5555
  // ../producer/src/services/htmlCompiler.ts
5361
5556
  import { createHash as createHash4 } from "crypto";
5362
5557
  import { createReadStream as createReadStream2, existsSync as existsSync9, mkdirSync as mkdirSync5, readFileSync as readFileSync5 } from "fs";
5363
- import { join as join12, dirname as dirname5, resolve as resolve5, basename as basename4, relative as relative2 } from "path";
5558
+ import { join as join13, dirname as dirname5, resolve as resolve5, basename as basename4, relative as relative2 } from "path";
5364
5559
 
5365
5560
  // ../producer/src/services/renderMediaCollector.ts
5366
5561
  function resolveHostEnd(host, hostStart) {
@@ -5865,7 +6060,7 @@ async function resolveMediaDuration(src, mediaStart, playbackRate, baseDir, down
5865
6060
  }
5866
6061
  } else {
5867
6062
  filePath = decodedUrlPath(src);
5868
- if (!filePath.startsWith("/")) filePath = join12(baseDir, filePath);
6063
+ if (!filePath.startsWith("/")) filePath = join13(baseDir, filePath);
5869
6064
  filePath = urlByAbsentLocalPath?.get(filePath) ?? filePath;
5870
6065
  }
5871
6066
  if (!isHttpUrl(filePath) && !existsSync9(filePath)) {
@@ -6485,7 +6680,7 @@ async function localizeRemoteMediaSources(html, downloadDir) {
6485
6680
  return downloadAndRewriteUrls(
6486
6681
  urlSet,
6487
6682
  html,
6488
- join12(downloadDir, REMOTE_MEDIA_SUBDIR),
6683
+ join13(downloadDir, REMOTE_MEDIA_SUBDIR),
6489
6684
  "Remote media download failed",
6490
6685
  "Localized remote media source(s)"
6491
6686
  );
@@ -6500,7 +6695,7 @@ async function localizeRemoteImageSources(html, downloadDir) {
6500
6695
  return downloadAndRewriteUrls(
6501
6696
  urlSet,
6502
6697
  html,
6503
- join12(downloadDir, REMOTE_MEDIA_SUBDIR),
6698
+ join13(downloadDir, REMOTE_MEDIA_SUBDIR),
6504
6699
  "Remote image download failed",
6505
6700
  "Localized remote image source(s)"
6506
6701
  );
@@ -6516,7 +6711,7 @@ async function localizeRemoteBackgroundImages(html, downloadDir) {
6516
6711
  return downloadAndRewriteUrls(
6517
6712
  urlSet,
6518
6713
  html,
6519
- join12(downloadDir, REMOTE_MEDIA_SUBDIR),
6714
+ join13(downloadDir, REMOTE_MEDIA_SUBDIR),
6520
6715
  "Remote background-image download failed",
6521
6716
  "Localized remote background-image(s)",
6522
6717
  // Quoted url('..')/url("..") are rewritten by downloadAndRewriteUrls' default
@@ -6651,7 +6846,7 @@ async function localizeRemoteFontFaces(html, downloadDir) {
6651
6846
  return downloadAndRewriteUrls(
6652
6847
  urlSet,
6653
6848
  processed,
6654
- join12(downloadDir, REMOTE_MEDIA_SUBDIR),
6849
+ join13(downloadDir, REMOTE_MEDIA_SUBDIR),
6655
6850
  "Remote font download failed",
6656
6851
  "Localized remote font face(s)",
6657
6852
  (h, url, relPath) => h.replaceAll(`url(${url})`, `url("${relPath}")`)
@@ -7318,7 +7513,7 @@ async function runCompileStage(input) {
7318
7513
  abortSignal
7319
7514
  } = input;
7320
7515
  const compileStart = Date.now();
7321
- const compiled = await compileForRender(projectDir, htmlPath, join13(workDir, "downloads"), {
7516
+ const compiled = await compileForRender(projectDir, htmlPath, join14(workDir, "downloads"), {
7322
7517
  log,
7323
7518
  failClosedFontFetch: failClosedFontFetch === true,
7324
7519
  allowSystemFontCapture,
@@ -7326,7 +7521,7 @@ async function runCompileStage(input) {
7326
7521
  variables: input.variables,
7327
7522
  urlByAbsentLocalPath: input.urlByAbsentLocalPath,
7328
7523
  pageMotionBlur: input.pageMotionBlur,
7329
- animatedGifCacheDir: cfg.extractCacheDir ? join13(cfg.extractCacheDir, "animated-gif") : void 0,
7524
+ animatedGifCacheDir: cfg.extractCacheDir ? join14(cfg.extractCacheDir, "animated-gif") : void 0,
7330
7525
  ffmpegProcessTimeout: cfg.ffmpegProcessTimeout
7331
7526
  });
7332
7527
  assertNotAborted();
@@ -7389,7 +7584,7 @@ async function runCompileStage(input) {
7389
7584
  };
7390
7585
  await preflightCompositionAssetMediaTypes({
7391
7586
  projectDir,
7392
- compiledDir: join13(workDir, "compiled"),
7587
+ compiledDir: join14(workDir, "compiled"),
7393
7588
  composition,
7394
7589
  signal: abortSignal
7395
7590
  });
@@ -7434,7 +7629,7 @@ async function runCompileStage(input) {
7434
7629
  }
7435
7630
 
7436
7631
  // ../producer/src/services/render/stages/probeStage.ts
7437
- import { join as join14 } from "path";
7632
+ import { join as join15 } from "path";
7438
7633
 
7439
7634
  // ../producer/src/services/render/stages/probeFailures.ts
7440
7635
  var NETWORK_FAILURE_PATTERN = /404|ERR_NAME_NOT_RESOLVED|ERR_CONNECTION_REFUSED|net::ERR_/i;
@@ -7604,7 +7799,7 @@ async function runProbeStage(input) {
7604
7799
  });
7605
7800
  fileServer = await createFileServer({
7606
7801
  projectDir,
7607
- compiledDir: join14(workDir, "compiled"),
7802
+ compiledDir: join15(workDir, "compiled"),
7608
7803
  port: 0,
7609
7804
  preHeadScripts: [VIRTUAL_TIME_SHIM],
7610
7805
  fps: job.config.fps
@@ -7632,7 +7827,7 @@ async function runProbeStage(input) {
7632
7827
  log.info("Creating capture session...", { attempt, maxAttempts: PROBE_MAX_ATTEMPTS });
7633
7828
  probeSession = await createCaptureSession(
7634
7829
  fileServer.url,
7635
- join14(workDir, "probe"),
7830
+ join15(workDir, "probe"),
7636
7831
  captureOpts,
7637
7832
  null,
7638
7833
  probeCfg
@@ -7717,7 +7912,7 @@ async function runProbeStage(input) {
7717
7912
  });
7718
7913
  probeSession = await createCaptureSession(
7719
7914
  fileServer.url,
7720
- join14(workDir, "probe-screenshot"),
7915
+ join15(workDir, "probe-screenshot"),
7721
7916
  captureOpts,
7722
7917
  null,
7723
7918
  { ...probeCfg, forceScreenshot: true }
@@ -7753,7 +7948,7 @@ async function runProbeStage(input) {
7753
7948
  compiled,
7754
7949
  resolutions,
7755
7950
  projectDir,
7756
- join14(workDir, "downloads")
7951
+ join15(workDir, "downloads")
7757
7952
  );
7758
7953
  assertNotAborted();
7759
7954
  composition.videos = compiled.videos;
@@ -7944,7 +8139,7 @@ async function runProbeStage(input) {
7944
8139
  }
7945
8140
  await preflightCompositionAssetMediaTypes({
7946
8141
  projectDir,
7947
- compiledDir: join14(workDir, "compiled"),
8142
+ compiledDir: join15(workDir, "compiled"),
7948
8143
  composition,
7949
8144
  signal: abortSignal
7950
8145
  });
@@ -8100,7 +8295,7 @@ function validateDistributedDuration(input) {
8100
8295
 
8101
8296
  // ../producer/src/services/render/stages/extractVideosStage.ts
8102
8297
  import { existsSync as existsSync10 } from "fs";
8103
- import { join as join15 } from "path";
8298
+ import { join as join16 } from "path";
8104
8299
 
8105
8300
  // ../producer/src/services/render/extractionFailureMetadata.ts
8106
8301
  function stringOrEmpty(value) {
@@ -8403,14 +8598,14 @@ async function runExtractVideosStage(input) {
8403
8598
  // because short boundary counts can differ by one frame.
8404
8599
  {
8405
8600
  fps: job.config.fps,
8406
- outputDir: join15(compiledDir, "__hyperframes_video_frames"),
8601
+ outputDir: join16(compiledDir, "__hyperframes_video_frames"),
8407
8602
  format: job.config.videoFrameFormat ?? "auto",
8408
8603
  toneMapHdrToSdr: job.config.hdrMode === "force-sdr",
8409
8604
  timelineEnd: composition.duration,
8410
8605
  maxTransientRetries: extractionPolicy.maxTransientRetries,
8411
8606
  collectProbeFailures: extractionPolicy.failureMode === "enforce",
8412
8607
  deferRangeExtraction,
8413
- contentKeyedDirs: [join15(compiledDir, REMOTE_MEDIA_SUBDIR)],
8608
+ contentKeyedDirs: [join16(compiledDir, REMOTE_MEDIA_SUBDIR)],
8414
8609
  urlByAbsentLocalPath
8415
8610
  },
8416
8611
  abortSignal,
@@ -8477,13 +8672,13 @@ function appendAutoDetectedVideoAudio(composition, extracted) {
8477
8672
  }
8478
8673
 
8479
8674
  // ../producer/src/services/render/stages/audioStage.ts
8480
- import { join as join17 } from "path";
8481
- import { rmSync as rmSync7 } from "fs";
8675
+ import { join as join18 } from "path";
8676
+ import { rmSync as rmSync8 } from "fs";
8482
8677
 
8483
8678
  // ../producer/src/services/render/audioPadTrim.ts
8484
8679
  import { spawn } from "child_process";
8485
- import { mkdtempSync as mkdtempSync3, rmSync as rmSync6 } from "fs";
8486
- import { dirname as dirname6, join as join16 } from "path";
8680
+ import { mkdtempSync as mkdtempSync3, rmSync as rmSync7 } from "fs";
8681
+ import { dirname as dirname6, join as join17 } from "path";
8487
8682
 
8488
8683
  // ../producer/src/services/render/audioTruePeak.ts
8489
8684
  var toDbfs = (token) => token.toLowerCase() === "-inf" ? Number.NEGATIVE_INFINITY : Number(token);
@@ -8668,7 +8863,7 @@ async function padOrTrimAudioToVideoFrameCount(input) {
8668
8863
  error: `audioPadTrim: failed to materialize ${plan2.operation}: ${err instanceof Error ? err.message : String(err)}`
8669
8864
  };
8670
8865
  } finally {
8671
- for (const path of plan2.cleanupPaths) rmSync6(path, { force: true });
8866
+ for (const path of plan2.cleanupPaths) rmSync7(path, { force: true });
8672
8867
  }
8673
8868
  let loweredDb = 0;
8674
8869
  if (probeTruePeak) {
@@ -8714,8 +8909,8 @@ async function constrainAacTruePeak(input) {
8714
8909
  async function enforceAacTruePeak(input) {
8715
8910
  let scratchDir;
8716
8911
  try {
8717
- scratchDir = mkdtempSync3(join16(dirname6(input.audioPath), ".true-peak-"));
8718
- const correctedPath = join16(scratchDir, "audio.m4a");
8912
+ scratchDir = mkdtempSync3(join17(dirname6(input.audioPath), ".true-peak-"));
8913
+ const correctedPath = join17(scratchDir, "audio.m4a");
8719
8914
  const measurements = [];
8720
8915
  let attenuationDb = 0;
8721
8916
  let measuredPath = input.audioPath;
@@ -8766,7 +8961,7 @@ async function enforceAacTruePeak(input) {
8766
8961
  )}`
8767
8962
  };
8768
8963
  } finally {
8769
- if (scratchDir) rmSync6(scratchDir, { recursive: true, force: true });
8964
+ if (scratchDir) rmSync7(scratchDir, { recursive: true, force: true });
8770
8965
  }
8771
8966
  }
8772
8967
  function failResult(outputPath, target, source, error) {
@@ -8913,7 +9108,7 @@ function assertAudioNotInterrupted(failures) {
8913
9108
  }
8914
9109
  async function runAudioStage(input) {
8915
9110
  const stageStart = Date.now();
8916
- const pcmSourcePath = join17(input.workDir, "audio-source.wav");
9111
+ const pcmSourcePath = join18(input.workDir, "audio-source.wav");
8917
9112
  const duration = input.totalFrames * input.fps.den / input.fps.num;
8918
9113
  try {
8919
9114
  const result = await mixAudioForDelivery(input, duration, pcmSourcePath);
@@ -8933,7 +9128,7 @@ async function runAudioStage(input) {
8933
9128
  }
8934
9129
  return { ...result, audioLoweredDb, audioProcessMs: Date.now() - stageStart };
8935
9130
  } finally {
8936
- rmSync7(pcmSourcePath, { force: true });
9131
+ rmSync8(pcmSourcePath, { force: true });
8937
9132
  }
8938
9133
  }
8939
9134
  async function mixAudioForDelivery(input, duration, pcmSourcePath) {
@@ -8951,7 +9146,7 @@ async function mixAudioForDelivery(input, duration, pcmSourcePath) {
8951
9146
  assertNotAborted,
8952
9147
  log
8953
9148
  } = input;
8954
- const audioOutputPath = join17(workDir, MIXED_AUDIO_FILENAME);
9149
+ const audioOutputPath = join18(workDir, MIXED_AUDIO_FILENAME);
8955
9150
  let hasAudio = false;
8956
9151
  let audioError;
8957
9152
  let audioFailures;
@@ -8962,7 +9157,7 @@ async function mixAudioForDelivery(input, duration, pcmSourcePath) {
8962
9157
  audioResult = await processCompositionAudio(
8963
9158
  audios,
8964
9159
  projectDir,
8965
- join17(workDir, "audio-work"),
9160
+ join18(workDir, "audio-work"),
8966
9161
  audioOutputPath,
8967
9162
  duration,
8968
9163
  abortSignal,
@@ -9031,7 +9226,7 @@ async function mixAudioForDelivery(input, duration, pcmSourcePath) {
9031
9226
 
9032
9227
  // ../producer/src/services/render/stages/captureStage.ts
9033
9228
  import { existsSync as existsSync11, readdirSync as readdirSync3, statfsSync as statfsSync2 } from "fs";
9034
- import { join as join18 } from "path";
9229
+ import { join as join19 } from "path";
9035
9230
  function shouldAllowAdaptiveCaptureRetry(workerCount, _explicitlyConfigured) {
9036
9231
  return workerCount > 1;
9037
9232
  }
@@ -9090,13 +9285,13 @@ function measureCaptureFrameBytes(workDir, framesDir) {
9090
9285
  if (!existsSync11(workDir)) return total;
9091
9286
  for (const attempt of readdirSync3(workDir)) {
9092
9287
  if (/^retry-\d+-batch-\d+-worker-\d+$/.test(attempt)) {
9093
- total += sampleDirectoryBytes(join18(workDir, attempt));
9288
+ total += sampleDirectoryBytes(join19(workDir, attempt));
9094
9289
  continue;
9095
9290
  }
9096
9291
  if (!/^capture-attempt-\d+$/.test(attempt)) continue;
9097
- const attemptDir = join18(workDir, attempt);
9292
+ const attemptDir = join19(workDir, attempt);
9098
9293
  for (const name of readdirSync3(attemptDir)) {
9099
- if (/^worker-\d+$/.test(name)) total += sampleDirectoryBytes(join18(attemptDir, name));
9294
+ if (/^worker-\d+$/.test(name)) total += sampleDirectoryBytes(join19(attemptDir, name));
9100
9295
  }
9101
9296
  }
9102
9297
  return total;
@@ -9383,7 +9578,7 @@ async function captureSessionFrames(session, { input, rangeStart, rangeEnd, resu
9383
9578
 
9384
9579
  // ../producer/src/services/render/stages/captureHdrStage.ts
9385
9580
  import { existsSync as existsSync13, mkdirSync as mkdirSync6 } from "fs";
9386
- import { join as join22 } from "path";
9581
+ import { join as join23 } from "path";
9387
9582
 
9388
9583
  // ../producer/src/services/hdrImageTransferCache.ts
9389
9584
  var DEFAULT_MAX_BYTES = 200 * 1024 * 1024;
@@ -9445,7 +9640,7 @@ function createHdrImageTransferCache(options = {}) {
9445
9640
  }
9446
9641
 
9447
9642
  // ../producer/src/services/render/stages/captureHdrSequentialLoop.ts
9448
- import { join as join19 } from "path";
9643
+ import { join as join20 } from "path";
9449
9644
  async function runSequentialLayeredFrameLoop(input) {
9450
9645
  const {
9451
9646
  job,
@@ -9566,7 +9761,7 @@ async function runSequentialLayeredFrameLoop(input) {
9566
9761
  );
9567
9762
  if (debugDumpEnabled && debugDumpDir && i % 30 === 0) {
9568
9763
  writeFileExclusiveSync(
9569
- join19(debugDumpDir, `frame_${String(i).padStart(4, "0")}_final_rgb48le.bin`),
9764
+ join20(debugDumpDir, `frame_${String(i).padStart(4, "0")}_final_rgb48le.bin`),
9570
9765
  normalCanvas
9571
9766
  );
9572
9767
  }
@@ -9598,12 +9793,12 @@ async function runSequentialLayeredFrameLoop(input) {
9598
9793
  }
9599
9794
 
9600
9795
  // ../producer/src/services/render/stages/captureHdrHybridLoop.ts
9601
- import { join as join21 } from "path";
9796
+ import { join as join22 } from "path";
9602
9797
 
9603
9798
  // ../producer/src/services/shaderTransitionWorkerPool.ts
9604
9799
  import { Worker } from "worker_threads";
9605
9800
  import { fileURLToPath as fileURLToPath3, pathToFileURL } from "url";
9606
- import { dirname as dirname7, join as join20 } from "path";
9801
+ import { dirname as dirname7, join as join21 } from "path";
9607
9802
  import { createRequire } from "module";
9608
9803
  import { existsSync as existsSync12 } from "fs";
9609
9804
  import { cpus as cpus2 } from "os";
@@ -9617,9 +9812,9 @@ function resolveWorkerEntry(explicit) {
9617
9812
  return { path: override, isTs };
9618
9813
  }
9619
9814
  const moduleDir = dirname7(fileURLToPath3(import.meta.url));
9620
- const jsPath = join20(moduleDir, "shaderTransitionWorker.js");
9815
+ const jsPath = join21(moduleDir, "shaderTransitionWorker.js");
9621
9816
  if (existsSync12(jsPath)) return { path: jsPath, isTs: false };
9622
- const tsPath = join20(moduleDir, "shaderTransitionWorker.ts");
9817
+ const tsPath = join21(moduleDir, "shaderTransitionWorker.ts");
9623
9818
  return { path: tsPath, isTs: true };
9624
9819
  }
9625
9820
  function buildExecArgv(entryIsTs) {
@@ -9987,7 +10182,7 @@ async function runHybridLayeredFrameLoop(input) {
9987
10182
  );
9988
10183
  if (debugDumpEnabled && debugDumpDir && i % 30 === 0) {
9989
10184
  writeFileExclusiveSync(
9990
- join21(debugDumpDir, `frame_${String(i).padStart(4, "0")}_final_rgb48le.bin`),
10185
+ join22(debugDumpDir, `frame_${String(i).padStart(4, "0")}_final_rgb48le.bin`),
9991
10186
  canvas
9992
10187
  );
9993
10188
  }
@@ -10156,7 +10351,8 @@ async function runCaptureHdrStage(input) {
10156
10351
  width,
10157
10352
  height,
10158
10353
  abortSignal,
10159
- hdrDiagnostics
10354
+ hdrDiagnostics,
10355
+ maxResidentWindows: Math.max(1, workerCount) + 1
10160
10356
  });
10161
10357
  releaseHdrExtractionReservation = extracted.releaseReservation;
10162
10358
  for (const [id, source] of extracted.sources) hdrVideoFrameSources.set(id, source);
@@ -10174,7 +10370,7 @@ async function runCaptureHdrStage(input) {
10174
10370
  if (hdrVideoFrameSources.has(v.id)) hdrVideoEndTimes.set(v.id, v.end);
10175
10371
  }
10176
10372
  const debugDumpEnabled = process.env.KEEP_TEMP === "1";
10177
- const debugDumpDir = debugDumpEnabled ? join22(framesDir, "debug-composite") : null;
10373
+ const debugDumpDir = debugDumpEnabled ? join23(framesDir, "debug-composite") : null;
10178
10374
  if (debugDumpDir && !existsSync13(debugDumpDir)) {
10179
10375
  mkdirSync6(debugDumpDir, { recursive: true });
10180
10376
  }
@@ -10334,12 +10530,12 @@ import {
10334
10530
  mkdirSync as mkdirSync7,
10335
10531
  readdirSync as readdirSync4,
10336
10532
  readFileSync as readFileSync6,
10337
- rmSync as rmSync8,
10338
- statSync as statSync4,
10533
+ rmSync as rmSync9,
10534
+ statSync as statSync5,
10339
10535
  writeFileSync as writeFileSync4
10340
10536
  } from "fs";
10341
10537
  import { readFile as readFile2 } from "fs/promises";
10342
- import { dirname as dirname8, join as join23 } from "path";
10538
+ import { dirname as dirname8, join as join24 } from "path";
10343
10539
 
10344
10540
  // ../producer/src/services/render/stages/gifEncodeArgs.ts
10345
10541
  function fpsToFfmpegArg2(fps) {
@@ -10449,7 +10645,7 @@ async function encodeGifFromDir(framesDir, framePattern, outputPath, input) {
10449
10645
  const failure = await reencodeWithClearedWholeFrames(argsInput, run, startTime);
10450
10646
  if (failure) return failure;
10451
10647
  }
10452
- const fileSize = existsSync14(outputPath) ? statSync4(outputPath).size : 0;
10648
+ const fileSize = existsSync14(outputPath) ? statSync5(outputPath).size : 0;
10453
10649
  return {
10454
10650
  success: true,
10455
10651
  outputPath,
@@ -10458,7 +10654,7 @@ async function encodeGifFromDir(framesDir, framePattern, outputPath, input) {
10458
10654
  fileSize
10459
10655
  };
10460
10656
  } finally {
10461
- rmSync8(input.palettePath, { force: true });
10657
+ rmSync9(input.palettePath, { force: true });
10462
10658
  }
10463
10659
  }
10464
10660
  function startEncodeProgress(job, stage, onProgress) {
@@ -10533,7 +10729,7 @@ function encodeWhileCapturing(input, totalFrames) {
10533
10729
  await new Promise((resolve11) => wake = resolve11);
10534
10730
  }
10535
10731
  if (signal.aborted) return;
10536
- const mergedPath = join23(input.framesDir, formatCaptureFrameName(next, "jpg"));
10732
+ const mergedPath = join24(input.framesDir, formatCaptureFrameName(next, "jpg"));
10537
10733
  const frame = await readLandedFrame(landed.get(next), mergedPath);
10538
10734
  landed.delete(next);
10539
10735
  if (!await stream.writeFrame(frame)) {
@@ -10616,11 +10812,11 @@ async function runEncodeStage(input) {
10616
10812
  );
10617
10813
  }
10618
10814
  captured.forEach((name, i) => {
10619
- const dst = join23(outputPath, formatExportFrameName(i, "png"));
10620
- copyFileSync2(join23(framesDir, name), dst);
10815
+ const dst = join24(outputPath, formatExportFrameName(i, "png"));
10816
+ copyFileSync2(join24(framesDir, name), dst);
10621
10817
  });
10622
10818
  if (hasAudio && audioOutputPath && existsSync14(audioOutputPath)) {
10623
- copyFileSync2(audioOutputPath, join23(outputPath, MIXED_AUDIO_FILENAME));
10819
+ copyFileSync2(audioOutputPath, join24(outputPath, MIXED_AUDIO_FILENAME));
10624
10820
  log.info(
10625
10821
  `[Render] png-sequence: ${MIXED_AUDIO_FILENAME} sidecar written to ${outputPath}/${MIXED_AUDIO_FILENAME}`
10626
10822
  );
@@ -10640,7 +10836,7 @@ async function runEncodeStage(input) {
10640
10836
  const encodeResult2 = await encodeGifFromDir(framesDir, framePattern2, outputPath, {
10641
10837
  fps: job.config.fps,
10642
10838
  loop,
10643
- palettePath: join23(dirname8(videoOnlyPath), "gif-palette.png"),
10839
+ palettePath: join24(dirname8(videoOnlyPath), "gif-palette.png"),
10644
10840
  preserveAlpha: needsAlpha,
10645
10841
  signal: abortSignal,
10646
10842
  timeout: engineCfg.ffmpegEncodeTimeout
@@ -10852,9 +11048,9 @@ function sampleDirectoryBytes(dir) {
10852
11048
  continue;
10853
11049
  }
10854
11050
  for (const name of entries) {
10855
- const full = join24(current, name);
11051
+ const full = join25(current, name);
10856
11052
  try {
10857
- const st = statSync5(full);
11053
+ const st = statSync6(full);
10858
11054
  if (st.isDirectory()) {
10859
11055
  stack.push(full);
10860
11056
  } else if (st.isFile()) {
@@ -11001,8 +11197,8 @@ function findMissingFrameRanges(totalFrames, framesDir, frameExt) {
11001
11197
  const ranges = [];
11002
11198
  let rangeStart = null;
11003
11199
  for (let frameIndex = 0; frameIndex < totalFrames; frameIndex++) {
11004
- const framePath = join24(framesDir, formatCaptureFrameName(frameIndex, frameExt));
11005
- const missing = !existsSync15(framePath) || statSync5(framePath).size <= 8;
11200
+ const framePath = join25(framesDir, formatCaptureFrameName(frameIndex, frameExt));
11201
+ const missing = !existsSync15(framePath) || statSync6(framePath).size <= 8;
11006
11202
  if (missing && rangeStart === null) {
11007
11203
  rangeStart = frameIndex;
11008
11204
  } else if (!missing && rangeStart !== null) {
@@ -11024,7 +11220,7 @@ function buildMissingFrameRetryBatches(ranges, maxWorkers, workDir, attempt, ran
11024
11220
  workerId,
11025
11221
  startFrame: rangeStart + range.startFrame,
11026
11222
  endFrame: rangeStart + range.endFrame,
11027
- outputDir: join24(workDir, `retry-${attempt}-batch-${batchIndex}-worker-${workerId}`),
11223
+ outputDir: join25(workDir, `retry-${attempt}-batch-${batchIndex}-worker-${workerId}`),
11028
11224
  outputFrameOffset: rangeStart
11029
11225
  }));
11030
11226
  batches.push(batch);
@@ -11052,8 +11248,8 @@ function getNextRetryWorkerCount(currentWorkers) {
11052
11248
  return Math.max(1, Math.floor(currentWorkers / 2));
11053
11249
  }
11054
11250
  function resolveRenderWorkDirPrefix(outputPath, jobId, platform2 = process.platform, systemTempDir = tmpdir2()) {
11055
- if (platform2 === "win32" || platform2 === "darwin") return join24(systemTempDir, "hf-render-");
11056
- return join24(dirname9(outputPath), `work-${jobId}-`);
11251
+ if (platform2 === "win32" || platform2 === "darwin") return join25(systemTempDir, "hf-render-");
11252
+ return join25(dirname9(outputPath), `work-${jobId}-`);
11057
11253
  }
11058
11254
  var MAX_TRANSIENT_CAPTURE_RETRIES = 1;
11059
11255
  function isTransientCaptureRetryEligible(failureKind, missing, retriesUsed) {
@@ -11085,7 +11281,7 @@ The composition is too large for the available memory. To reduce memory pressure
11085
11281
  function countCapturedFrames(totalFrames, framesDir, frameExt) {
11086
11282
  let captured = 0;
11087
11283
  for (let frameIndex = 0; frameIndex < totalFrames; frameIndex++) {
11088
- const framePath = join24(framesDir, formatCaptureFrameName(frameIndex, frameExt));
11284
+ const framePath = join25(framesDir, formatCaptureFrameName(frameIndex, frameExt));
11089
11285
  if (existsSync15(framePath)) captured++;
11090
11286
  }
11091
11287
  return captured;
@@ -11111,7 +11307,7 @@ async function executeDiskCaptureWithAdaptiveRetry(options) {
11111
11307
  reason: attempt === 0 ? "initial" : pendingTransientRetry ? "transient-retry" : "retry"
11112
11308
  });
11113
11309
  pendingTransientRetry = false;
11114
- const attemptWorkDir = join24(options.workDir, `capture-attempt-${attempt}`);
11310
+ const attemptWorkDir = join25(options.workDir, `capture-attempt-${attempt}`);
11115
11311
  const batches = missingRanges ? buildMissingFrameRetryBatches(
11116
11312
  missingRanges,
11117
11313
  currentWorkers,
@@ -11568,7 +11764,7 @@ function resolveDeShortBand(args) {
11568
11764
  return args.bandOpen ? "applied" : "skipped_elements";
11569
11765
  }
11570
11766
  function shouldPreferSingleWorkerDrawElement(args) {
11571
- return args.workerCount > 1 && typeof args.requestedWorkers !== "number" && args.useDrawElement && !args.deCompileGate && !args.forceScreenshot && outputUsesH264Pipeline(args.outputFormat) && args.minFrames > 0 && args.totalFrames >= args.minFrames && args.singleWorkerStreamingOk && !args.layeredOrEffectRoute && !args.supersampling && !args.probeDeGated && !args.experimentalParallelDeOptIn;
11767
+ return args.workerCount > 1 && args.useDrawElement && !args.deCompileGate && !args.forceScreenshot && outputUsesH264Pipeline(args.outputFormat) && args.minFrames > 0 && args.totalFrames >= args.minFrames && args.singleWorkerStreamingOk && !args.layeredOrEffectRoute && !args.supersampling && !args.probeDeGated && !args.experimentalParallelDeOptIn;
11572
11768
  }
11573
11769
  function isProbeDeGated(session) {
11574
11770
  return session !== null && session.captureMode !== "drawelement" && !session.deInitDeferred;
@@ -11704,17 +11900,17 @@ function deVerifyFallbackTelemetry(err) {
11704
11900
  }
11705
11901
  function resolveRenderDebugDir() {
11706
11902
  const producerRoot = process.env.PRODUCER_RENDERS_DIR ? resolve6(process.env.PRODUCER_RENDERS_DIR, "..") : resolve6(dirname9(fileURLToPath4(import.meta.url)), "../..");
11707
- return join24(producerRoot, ".debug");
11903
+ return join25(producerRoot, ".debug");
11708
11904
  }
11709
11905
  async function executeRenderJob(job, projectDir, outputPath, progressSink, abortSignal, assertRenderActive) {
11710
11906
  validateHlsRenderConfig(job.config);
11711
11907
  const debugDir = resolveRenderDebugDir();
11712
11908
  const outputDir = dirname9(outputPath);
11713
11909
  if (!existsSync15(outputDir)) mkdirSync8(outputDir, { recursive: true });
11714
- const workDir = job.config.debug ? join24(debugDir, job.id) : createRenderWorkDir(resolveRenderWorkDirPrefix(outputPath, job.id), outputDir);
11910
+ const workDir = job.config.debug ? join25(debugDir, job.id) : createRenderWorkDir(resolveRenderWorkDirPrefix(outputPath, job.id), outputDir);
11715
11911
  const pipelineStart = Date.now();
11716
11912
  const baseLog = job.config.logger ?? defaultLogger;
11717
- const logPath = job.config.debug ? join24(workDir, "render.log") : null;
11913
+ const logPath = job.config.debug ? join25(workDir, "render.log") : null;
11718
11914
  const execution = new RenderExecutionContext({
11719
11915
  request: { renderJobId: job.id, projectDir, outputPath },
11720
11916
  logger: logPath ? createRenderFileLogger(logPath, baseLog) : baseLog,
@@ -11728,7 +11924,7 @@ async function executeRenderJob(job, projectDir, outputPath, progressSink, abort
11728
11924
  log.info("KEEP_TEMP=1, leaving workDir on disk for inspection", { workDir });
11729
11925
  return;
11730
11926
  }
11731
- rmSync9(workDir, { recursive: true, force: true, maxRetries: 3, retryDelay: 100 });
11927
+ rmSync10(workDir, { recursive: true, force: true, maxRetries: 3, retryDelay: 100 });
11732
11928
  });
11733
11929
  try {
11734
11930
  await executeRenderPipeline({
@@ -11759,7 +11955,9 @@ async function executeRenderPipeline(input) {
11759
11955
  const log = execution.logger;
11760
11956
  const eventPublisher = execution.events;
11761
11957
  const onProgress = execution.onProgress;
11762
- const executionSignal = execution.signal;
11958
+ const tooSlow = new AbortController();
11959
+ let tooSlowError;
11960
+ const executionSignal = job.config.maxRenderMs ? AbortSignal.any([tooSlow.signal, ...execution.signal ? [execution.signal] : []]) : execution.signal;
11763
11961
  let fileServer = null;
11764
11962
  let probeSession = null;
11765
11963
  let lastBrowserConsole = [];
@@ -11772,7 +11970,7 @@ async function executeRenderPipeline(input) {
11772
11970
  imageDecodeFailures: 0
11773
11971
  };
11774
11972
  let hdrPerf;
11775
- const perfOutputPath = join24(workDir, "perf-summary.json");
11973
+ const perfOutputPath = join25(workDir, "perf-summary.json");
11776
11974
  const cfg = { ...job.config.producerConfig ?? resolveConfig() };
11777
11975
  const observability = new RenderObservabilityRecorder({
11778
11976
  pipelineStartMs: pipelineStart,
@@ -11874,15 +12072,15 @@ async function executeRenderPipeline(input) {
11874
12072
  requestedWorkers: job.config.workers ?? "auto"
11875
12073
  });
11876
12074
  const entryFile = job.config.entryFile || "index.html";
11877
- let htmlPath = join24(projectDir, entryFile);
12075
+ let htmlPath = join25(projectDir, entryFile);
11878
12076
  if (!existsSync15(htmlPath)) {
11879
12077
  throw new Error(`Entry file not found: ${htmlPath}`);
11880
12078
  }
11881
12079
  assertNotAborted();
11882
12080
  const rawEntry = readFileSync7(htmlPath, "utf-8");
11883
12081
  if (entryFile !== "index.html" && isTemplateEntry(rawEntry)) {
11884
- const wrapperPath = join24(workDir, "standalone-entry.html");
11885
- const projectIndexPath = join24(projectDir, "index.html");
12082
+ const wrapperPath = join25(workDir, "standalone-entry.html");
12083
+ const projectIndexPath = join25(projectDir, "index.html");
11886
12084
  if (!existsSync15(projectIndexPath)) {
11887
12085
  throw new Error(
11888
12086
  `Template entry file "${entryFile}" requires a project index.html to extract its render shell.`
@@ -12045,7 +12243,7 @@ async function executeRenderPipeline(input) {
12045
12243
  updateJobStatus(job, "preprocessing", "Extracting video frames", 10, onProgress, {
12046
12244
  code: "extract_video"
12047
12245
  });
12048
- const compiledDir = join24(workDir, "compiled");
12246
+ const compiledDir = join25(workDir, "compiled");
12049
12247
  const extractResult = await observeRenderStage(
12050
12248
  observability,
12051
12249
  "video_extract",
@@ -12179,7 +12377,7 @@ async function executeRenderPipeline(input) {
12179
12377
  try {
12180
12378
  fileServer = await createFileServer({
12181
12379
  projectDir,
12182
- compiledDir: join24(workDir, "compiled"),
12380
+ compiledDir: join25(workDir, "compiled"),
12183
12381
  port: 0,
12184
12382
  preHeadScripts: [VIRTUAL_TIME_SHIM],
12185
12383
  fps: job.config.fps
@@ -12197,7 +12395,7 @@ async function executeRenderPipeline(input) {
12197
12395
  if (!activeFileServer) {
12198
12396
  throw new Error("File server failed to initialize before frame capture");
12199
12397
  }
12200
- const framesDir = join24(workDir, "captured-frames");
12398
+ const framesDir = join25(workDir, "captured-frames");
12201
12399
  if (!existsSync15(framesDir)) mkdirSync8(framesDir, { recursive: true });
12202
12400
  updateJobStatus(job, "rendering", "Checking browser GPU", 25, onProgress, {
12203
12401
  code: "start_browsers"
@@ -12301,7 +12499,6 @@ async function executeRenderPipeline(input) {
12301
12499
  const WOULD_RESOLVE_MULTI_WORKER = 2;
12302
12500
  const deInversionArgs = {
12303
12501
  workerCount: WOULD_RESOLVE_MULTI_WORKER,
12304
- requestedWorkers: job.config.workers,
12305
12502
  useDrawElement: cfg.useDrawElement,
12306
12503
  deCompileGate,
12307
12504
  forceScreenshot: captureForceScreenshot,
@@ -12507,7 +12704,7 @@ async function executeRenderPipeline(input) {
12507
12704
  } else if (deInversionEligible && workerCount > 1) {
12508
12705
  deWorkerInversion = "inverted";
12509
12706
  log.info(
12510
- `[Render] Fast capture: single-worker drawElement streaming preferred over ${workerCount}-worker screenshot capture (${totalFrames} frames >= ${deInversionEffectiveMinFrames}; verified path, measured faster at every worker count). Set HF_DE_SINGLE_MIN_FRAMES=0 or --workers N to override.`
12707
+ `[Render] Fast capture: single-worker drawElement streaming preferred over ${workerCount}-worker screenshot capture (${totalFrames} frames >= ${deInversionEffectiveMinFrames}; verified path, measured faster at every worker count). Set HF_DE_SINGLE_MIN_FRAMES=0 to override.`
12511
12708
  );
12512
12709
  workerCount = 1;
12513
12710
  }
@@ -12551,6 +12748,27 @@ async function executeRenderPipeline(input) {
12551
12748
  deWorkerInversion: deWorkerInversion ?? "none",
12552
12749
  deParallelRouter: deParallelRouter ?? "none"
12553
12750
  });
12751
+ const calibratedTooSlow = checkRenderEta("capture_calibration", {
12752
+ maxRenderMs: job.config.maxRenderMs,
12753
+ elapsedMs: Date.now() - pipelineStart,
12754
+ framesCompleted: 0,
12755
+ totalFrames,
12756
+ msPerFrame: (captureCalibration?.estimate.p95Ms ?? 0) / workerCount
12757
+ });
12758
+ if (calibratedTooSlow) throw calibratedTooSlow;
12759
+ execution.defer(
12760
+ "stop render ETA guard",
12761
+ startRenderEtaGuard({
12762
+ maxRenderMs: job.config.maxRenderMs,
12763
+ job,
12764
+ totalFrames,
12765
+ pipelineStartMs: pipelineStart,
12766
+ onTooSlow: (error) => {
12767
+ tooSlowError = error;
12768
+ tooSlow.abort(error);
12769
+ }
12770
+ })
12771
+ );
12554
12772
  let useStreamingEncode = shouldUseStreamingEncode(
12555
12773
  cfg,
12556
12774
  outputFormat,
@@ -12644,7 +12862,7 @@ async function executeRenderPipeline(input) {
12644
12862
  hls: ".mp4"
12645
12863
  };
12646
12864
  const videoExt = FORMAT_EXT[outputFormat] ?? ".mp4";
12647
- const videoOnlyPath = join24(workDir, `video-only${videoExt}`);
12865
+ const videoOnlyPath = join25(workDir, `video-only${videoExt}`);
12648
12866
  const usePageSideCompositingForTransitions = (cfg.enablePageSideCompositing || isGif) && compiled.hasShaderTransitions && !hasHdrContent && outputSupportsPageSideShaderCompositing(outputFormat);
12649
12867
  if (usePageSideCompositingForTransitions) {
12650
12868
  activeFileServer.addPreHeadScript(HF_PAGE_SIDE_COMPOSITING_STUB);
@@ -12890,7 +13108,7 @@ async function executeRenderPipeline(input) {
12890
13108
  pageMotionBlur: job.config.pageMotionBlur,
12891
13109
  captureQuality: captureOptions.quality
12892
13110
  });
12893
- const segmentDir = segmentDirFor(join24(projectDir, "renders"), segmentPlanHash);
13111
+ const segmentDir = segmentDirFor(join25(projectDir, "renders"), segmentPlanHash);
12894
13112
  let completedSegments = /* @__PURE__ */ new Set();
12895
13113
  if (job.config.resumeSegments === true) {
12896
13114
  const existing = readSegmentManifest(segmentDir);
@@ -12905,10 +13123,10 @@ async function executeRenderPipeline(input) {
12905
13123
  });
12906
13124
  }
12907
13125
  if (completedSegments.size === 0) {
12908
- rmSync9(segmentDir, { recursive: true, force: true });
13126
+ rmSync10(segmentDir, { recursive: true, force: true });
12909
13127
  }
12910
13128
  } else {
12911
- rmSync9(segmentDir, { recursive: true, force: true });
13129
+ rmSync10(segmentDir, { recursive: true, force: true });
12912
13130
  }
12913
13131
  const segmentManifest = readSegmentManifest(segmentDir) ?? {
12914
13132
  version: 1,
@@ -12989,7 +13207,7 @@ async function executeRenderPipeline(input) {
12989
13207
  );
12990
13208
  updateCaptureObservability({ segmentRetries: segmentedRes.segmentRetries });
12991
13209
  if (job.config.keepSegments !== true) {
12992
- rmSync9(segmentDir, { recursive: true, force: true });
13210
+ rmSync10(segmentDir, { recursive: true, force: true });
12993
13211
  }
12994
13212
  } else {
12995
13213
  capturePlan = replanAfterFailure(capturePlan, { kind: "streaming_unavailable" });
@@ -13258,7 +13476,7 @@ async function executeRenderPipeline(input) {
13258
13476
  "capture_disk",
13259
13477
  "drawElement capture failed; retrying with a fresh screenshot session"
13260
13478
  );
13261
- rmSync9(framesDir, { recursive: true, force: true });
13479
+ rmSync10(framesDir, { recursive: true, force: true });
13262
13480
  mkdirSync8(framesDir, { recursive: true });
13263
13481
  resetCaptureAttemptProgress(job);
13264
13482
  dedupPerfs.length = 0;
@@ -13445,7 +13663,7 @@ async function executeRenderPipeline(input) {
13445
13663
  }
13446
13664
  if (job.config.debug) {
13447
13665
  if (!isPngSequence && !isHls && existsSync15(stagedOutputPath)) {
13448
- const debugOutput = join24(workDir, `output${videoExt}`);
13666
+ const debugOutput = join25(workDir, `output${videoExt}`);
13449
13667
  copyFileSync3(stagedOutputPath, debugOutput);
13450
13668
  }
13451
13669
  }
@@ -13456,8 +13674,9 @@ async function executeRenderPipeline(input) {
13456
13674
  job.outputPath = outputPath;
13457
13675
  updateJobStatus(job, "complete", "Render complete", 100, onProgress);
13458
13676
  await eventPublisher.flush();
13459
- } catch (error) {
13460
- if (error instanceof RenderCancelledError || executionSignal?.aborted) {
13677
+ } catch (caught) {
13678
+ const error = tooSlowError ?? caught;
13679
+ if (!tooSlowError && (error instanceof RenderCancelledError || executionSignal?.aborted)) {
13461
13680
  job.error = error instanceof Error ? error.message : "render_cancelled";
13462
13681
  updateJobStatus(job, "cancelled", "Render cancelled", job.progress, onProgress);
13463
13682
  await eventPublisher.flush();
@@ -13554,21 +13773,21 @@ import {
13554
13773
  existsSync as existsSync20,
13555
13774
  linkSync,
13556
13775
  mkdirSync as mkdirSync12,
13557
- rmSync as rmSync11,
13776
+ rmSync as rmSync12,
13558
13777
  writeFileSync as writeFileSync8
13559
13778
  } from "fs";
13560
- import { extname as extname6, isAbsolute as isAbsolute2, join as join32, relative as relative5, sep as sep2 } from "path";
13779
+ import { extname as extname6, isAbsolute as isAbsolute2, join as join33, relative as relative5, sep as sep2 } from "path";
13561
13780
 
13562
13781
  // ../producer/src/services/distributed/planFrameCost.ts
13563
- import { join as join27 } from "path";
13782
+ import { join as join28 } from "path";
13564
13783
 
13565
13784
  // ../producer/src/services/distributed/chunkFrames.ts
13566
13785
  import { existsSync as existsSync17, readdirSync as readdirSync6 } from "fs";
13567
- import { extname as extname4, join as join26 } from "path";
13786
+ import { extname as extname4, join as join27 } from "path";
13568
13787
 
13569
13788
  // ../producer/src/services/distributed/shared.ts
13570
13789
  import { execFile as execFileCallback } from "child_process";
13571
- import { dirname as dirname10, join as join25 } from "path";
13790
+ import { dirname as dirname10, join as join26 } from "path";
13572
13791
  import { existsSync as existsSync16, readFileSync as readFileSync8 } from "fs";
13573
13792
  import { fileURLToPath as fileURLToPath5 } from "url";
13574
13793
  import { promisify as promisify2 } from "util";
@@ -13580,7 +13799,7 @@ function isPlanAudioArtifactPath(path) {
13580
13799
  }
13581
13800
  function resolvePlanAudioPath(planDir) {
13582
13801
  for (const name of [PLAN_AUDIO_RELATIVE_PATH, PLAN_AUDIO_LEGACY_RELATIVE_PATH]) {
13583
- const candidate = join25(planDir, name);
13802
+ const candidate = join26(planDir, name);
13584
13803
  if (existsSync16(candidate)) return candidate;
13585
13804
  }
13586
13805
  return null;
@@ -13840,7 +14059,7 @@ function readProducerVersion() {
13840
14059
  const startDir = dirname10(fileURLToPath5(import.meta.url));
13841
14060
  let current = startDir;
13842
14061
  for (let i = 0; i < 10; i++) {
13843
- const candidate = join25(current, "package.json");
14062
+ const candidate = join26(current, "package.json");
13844
14063
  if (existsSync16(candidate)) {
13845
14064
  try {
13846
14065
  const pkg = JSON.parse(readFileSync8(candidate, "utf-8"));
@@ -13894,7 +14113,7 @@ function frameNumberFromFileName(name) {
13894
14113
  function rebuildExtractedFramesFromPlanDir(planDir, videos, indexMode = "dense-v1") {
13895
14114
  const result = [];
13896
14115
  for (const v of videos) {
13897
- const outputDir = join26(planDir, "video-frames", v.videoId);
14116
+ const outputDir = join27(planDir, "video-frames", v.videoId);
13898
14117
  if (!existsSync17(outputDir)) {
13899
14118
  throw new Error(
13900
14119
  `[renderChunk] planDir missing extracted video frames for ${JSON.stringify(v.videoId)}: ${outputDir} not present. plan() should have written frames here; the planDir is malformed.`
@@ -13913,7 +14132,7 @@ function rebuildExtractedFramesFromPlanDir(planDir, videos, indexMode = "dense-v
13913
14132
  if (!frameName) continue;
13914
14133
  const frameNumber = indexMode === "sparse-v2" ? frameNumberFromFileName(frameName) : null;
13915
14134
  const frameIndex = frameNumber === null ? i : frameNumber - 1;
13916
- framePaths.set(frameIndex, join26(outputDir, frameName));
14135
+ framePaths.set(frameIndex, join27(outputDir, frameName));
13917
14136
  }
13918
14137
  result.push({
13919
14138
  videoId: v.videoId,
@@ -14003,14 +14222,14 @@ async function extractDeferredVideoFramesForChunk(input) {
14003
14222
  const shown = shownDeferredFrameIndexes(input.planVideos, input.frames, input.fps);
14004
14223
  return Promise.all(
14005
14224
  deferred.map(async (video) => {
14006
- const outputDir = join26(input.outputRoot, video.videoId);
14225
+ const outputDir = join27(input.outputRoot, video.videoId);
14007
14226
  const indexes = [...shown.get(video.videoId) ?? []].sort((a, b) => a - b);
14008
14227
  if (indexes.length === 0) {
14009
14228
  return { ...video, outputDir, framePaths: /* @__PURE__ */ new Map(), ownedByLookup: false };
14010
14229
  }
14011
14230
  const range = video.deferredRange;
14012
14231
  const remoteUrl = remoteSources[range.sourcePath];
14013
- const sourcePath = remoteUrl ?? join26(input.planDir, ...range.sourcePath.split("/"));
14232
+ const sourcePath = remoteUrl ?? join27(input.planDir, ...range.sourcePath.split("/"));
14014
14233
  if (remoteUrl === void 0 && !existsSync17(sourcePath)) {
14015
14234
  throw new RenderChunkValidationError(
14016
14235
  MISSING_PLAN_ARTIFACT,
@@ -14059,12 +14278,12 @@ async function measurePlanSecondsPerFrame(input) {
14059
14278
  planVideos,
14060
14279
  frames: sampled,
14061
14280
  fps: fpsRatio,
14062
- outputRoot: join27(workDir, "frame-cost-video-frames"),
14281
+ outputRoot: join28(workDir, "frame-cost-video-frames"),
14063
14282
  cfg: input.cfg
14064
14283
  })
14065
14284
  ];
14066
14285
  const lookup = extracted.length > 0 ? createFrameLookupTable(planVideos.videos, extracted, resolveRenderFpsConfig(fpsRatio).value) : null;
14067
- const compiledDir = join27(planDir, "compiled");
14286
+ const compiledDir = join28(planDir, "compiled");
14068
14287
  const fileServer = await createFileServer({
14069
14288
  projectDir: compiledDir,
14070
14289
  compiledDir,
@@ -14076,7 +14295,7 @@ async function measurePlanSecondsPerFrame(input) {
14076
14295
  try {
14077
14296
  session = await createCaptureSession(
14078
14297
  fileServer.url,
14079
- join27(workDir, "frame-cost"),
14298
+ join28(workDir, "frame-cost"),
14080
14299
  buildChunkCaptureOptions({
14081
14300
  dimensions: { ...input, fpsNum: fps, fpsDen: 1 },
14082
14301
  encoder: input,
@@ -14096,9 +14315,72 @@ async function measurePlanSecondsPerFrame(input) {
14096
14315
  }
14097
14316
  }
14098
14317
 
14318
+ // ../producer/src/services/distributed/chunkWeights.ts
14319
+ var PAGE_BASE_WEIGHT = 0.7;
14320
+ var PNG_WEIGHT_FACTOR = 1.5;
14321
+ function isUniformFrameCost(weights) {
14322
+ let lightest = Infinity;
14323
+ let heaviest = 0;
14324
+ for (const weight of weights) {
14325
+ lightest = Math.min(lightest, weight);
14326
+ heaviest = Math.max(heaviest, weight);
14327
+ }
14328
+ return heaviest <= lightest * 1.05;
14329
+ }
14330
+ function planFrameWeights(input) {
14331
+ const { totalFrames, fps } = input;
14332
+ const delta = new Float64Array(totalFrames + 1);
14333
+ const outputPixels = input.width * input.height;
14334
+ const extractedById = new Map(input.extracted.map((entry) => [entry.videoId, entry]));
14335
+ for (const video of input.videos) {
14336
+ const entry = extractedById.get(video.id);
14337
+ if (!entry || video.hidden) continue;
14338
+ const start = Math.max(0, Math.round(video.start * fps));
14339
+ const end = Math.min(totalFrames, Math.round(video.end * fps));
14340
+ if (!(end > start)) continue;
14341
+ const { width, height } = entry.metadata;
14342
+ const factor = resolveFrameFormat(entry.metadata) === "png" ? PNG_WEIGHT_FACTOR : 1;
14343
+ const weight = Math.min(width * height, outputPixels) / 1e6 * factor;
14344
+ delta[start] = delta[start] + weight;
14345
+ delta[end] = delta[end] - weight;
14346
+ }
14347
+ const weights = new Float64Array(totalFrames);
14348
+ let active = 0;
14349
+ for (let frame = 0; frame < totalFrames; frame++) {
14350
+ active += delta[frame];
14351
+ weights[frame] = PAGE_BASE_WEIGHT + active;
14352
+ }
14353
+ return weights;
14354
+ }
14355
+ function buildWeightedChunkSlices(weights, chunkCount, minFrames, maxFrames) {
14356
+ if (isUniformFrameCost(weights)) return null;
14357
+ const totalFrames = weights.length;
14358
+ const total = weights.reduce((sum2, weight) => sum2 + weight, 0);
14359
+ const minSize = Math.max(1, Math.min(minFrames, Math.floor(totalFrames / chunkCount)));
14360
+ const maxSize = Math.max(maxFrames, Math.ceil(totalFrames / chunkCount));
14361
+ const slices = [];
14362
+ let startFrame = 0;
14363
+ let frame = 0;
14364
+ let costBefore = 0;
14365
+ for (let index = 0; index < chunkCount - 1; index++) {
14366
+ const target = (index + 1) * total / chunkCount;
14367
+ while (frame < totalFrames && costBefore + weights[frame] / 2 < target) {
14368
+ costBefore += weights[frame++];
14369
+ }
14370
+ const remaining = chunkCount - index - 1;
14371
+ const low = Math.max(startFrame + minSize, totalFrames - remaining * maxSize);
14372
+ const high = Math.min(startFrame + maxSize, totalFrames - remaining * minSize);
14373
+ const endFrame = Math.min(high, Math.max(low, frame));
14374
+ slices.push({ index, startFrame, endFrame });
14375
+ startFrame = endFrame;
14376
+ }
14377
+ slices.push({ index: chunkCount - 1, startFrame, endFrame: totalFrames });
14378
+ return slices;
14379
+ }
14380
+
14099
14381
  // ../producer/src/services/render/stages/freezePlan.ts
14100
14382
  import { existsSync as existsSync18, mkdirSync as mkdirSync9, readFileSync as readFileSync9, readdirSync as readdirSync7, writeFileSync as writeFileSync6 } from "fs";
14101
- import { join as join28, relative as relative3, resolve as resolve7 } from "path";
14383
+ import { join as join29, relative as relative3, resolve as resolve7 } from "path";
14102
14384
 
14103
14385
  // ../producer/src/services/distributed/planProtocol.ts
14104
14386
  var PLAN_SCHEMA_VERSION = 1;
@@ -14197,7 +14479,7 @@ function readPlanProtocolV1(planJson, capabilities = DISTRIBUTED_RENDER_CAPABILI
14197
14479
 
14198
14480
  // ../producer/src/services/render/stages/planHash.ts
14199
14481
  import { createHash as createHash5 } from "crypto";
14200
- import { closeSync as closeSync5, createReadStream as createReadStream3, openSync as openSync4, readSync as readSync3 } from "fs";
14482
+ import { closeSync as closeSync4, createReadStream as createReadStream3, openSync as openSync4, readSync as readSync3 } from "fs";
14201
14483
  var PLAN_HASH_SCHEMA_PREFIX = "hyperframes-plan-hash-v1\0";
14202
14484
  var FIELD_DELIMITER = Buffer.from([0]);
14203
14485
  function computePlanHash(input) {
@@ -14263,7 +14545,7 @@ function sha256File(path) {
14263
14545
  if (bytesRead > 0) hash.update(buffer.subarray(0, bytesRead));
14264
14546
  } while (bytesRead > 0);
14265
14547
  } finally {
14266
- closeSync5(fd);
14548
+ closeSync4(fd);
14267
14549
  }
14268
14550
  return hash.digest("hex");
14269
14551
  }
@@ -14316,7 +14598,7 @@ function listPlanFiles(planDir) {
14316
14598
  function walk(dir) {
14317
14599
  const entries = readdirSync7(dir, { withFileTypes: true });
14318
14600
  for (const entry of entries) {
14319
- const full = join28(dir, entry.name);
14601
+ const full = join29(dir, entry.name);
14320
14602
  if (entry.isDirectory()) {
14321
14603
  walk(full);
14322
14604
  } else if (entry.isFile()) {
@@ -14357,15 +14639,15 @@ var PLAN_REMOTE_FILES_RELATIVE_PATH = "meta/remote-files.json";
14357
14639
  function writePlanRemoteFiles(planDir, files) {
14358
14640
  if (files.length === 0) return;
14359
14641
  const sorted = [...files].sort((a, b) => a.path < b.path ? -1 : 1);
14360
- writeFileSync6(join28(planDir, PLAN_REMOTE_FILES_RELATIVE_PATH), JSON.stringify(sorted), "utf-8");
14642
+ writeFileSync6(join29(planDir, PLAN_REMOTE_FILES_RELATIVE_PATH), JSON.stringify(sorted), "utf-8");
14361
14643
  }
14362
14644
  function readPlanRemoteFiles(planDir) {
14363
- const path = join28(planDir, PLAN_REMOTE_FILES_RELATIVE_PATH);
14645
+ const path = join29(planDir, PLAN_REMOTE_FILES_RELATIVE_PATH);
14364
14646
  return existsSync18(path) ? JSON.parse(readFileSync9(path, "utf-8")) : [];
14365
14647
  }
14366
14648
  function recomputePlanHashFromPlanDir(planDir, digests) {
14367
- const planJsonPath = join28(planDir, "plan.json");
14368
- const encoderJsonPath = join28(planDir, "meta", "encoder.json");
14649
+ const planJsonPath = join29(planDir, "plan.json");
14650
+ const encoderJsonPath = join29(planDir, "meta", "encoder.json");
14369
14651
  if (!existsSync18(planJsonPath)) {
14370
14652
  throw new Error(`[freezePlan] plan.json missing: ${planJsonPath}`);
14371
14653
  }
@@ -14402,18 +14684,18 @@ async function freezePlan(input) {
14402
14684
  if (!existsSync18(planDir)) {
14403
14685
  throw new Error(`[freezePlan] planDir does not exist: ${planDir}`);
14404
14686
  }
14405
- const metaDir = join28(planDir, "meta");
14687
+ const metaDir = join29(planDir, "meta");
14406
14688
  if (!existsSync18(metaDir)) mkdirSync9(metaDir, { recursive: true });
14407
14689
  writeFileSync6(
14408
- join28(metaDir, "composition.json"),
14690
+ join29(metaDir, "composition.json"),
14409
14691
  `${JSON.stringify(composition, null, 2)}
14410
14692
  `,
14411
14693
  "utf-8"
14412
14694
  );
14413
14695
  const encoderForCanonical = stripUndefined(encoder);
14414
14696
  const encoderConfigCanonicalJson = canonicalJsonStringify(encoderForCanonical);
14415
- writeFileSync6(join28(metaDir, "encoder.json"), encoderConfigCanonicalJson, "utf-8");
14416
- writeFileSync6(join28(metaDir, "chunks.json"), `${JSON.stringify(chunks, null, 2)}
14697
+ writeFileSync6(join29(metaDir, "encoder.json"), encoderConfigCanonicalJson, "utf-8");
14698
+ writeFileSync6(join29(metaDir, "chunks.json"), `${JSON.stringify(chunks, null, 2)}
14417
14699
  `, "utf-8");
14418
14700
  const { compositionHtml, assets } = collectPlanAssetShas(planDir, digests);
14419
14701
  const planHash = computePlanHash({
@@ -14437,7 +14719,7 @@ async function freezePlan(input) {
14437
14719
  duration: durationSeconds,
14438
14720
  hasAudio
14439
14721
  };
14440
- const planJsonPath = join28(planDir, "plan.json");
14722
+ const planJsonPath = join29(planDir, "plan.json");
14441
14723
  writeFileSync6(planJsonPath, `${JSON.stringify(planJson, null, 2)}
14442
14724
  `, "utf-8");
14443
14725
  return { planJsonPath, planHash };
@@ -14479,14 +14761,14 @@ function applyRuntimeEnvSnapshot(snapshot, env = process.env) {
14479
14761
  }
14480
14762
 
14481
14763
  // ../producer/src/services/distributed/chunkAudio.ts
14482
- import { closeSync as closeSync6, existsSync as existsSync19, ftruncateSync, mkdirSync as mkdirSync11, openSync as openSync5, readFileSync as readFileSync10 } from "fs";
14764
+ import { closeSync as closeSync5, existsSync as existsSync19, ftruncateSync, mkdirSync as mkdirSync11, openSync as openSync5, readFileSync as readFileSync10 } from "fs";
14483
14765
  import { writeFileSync as writeFileSync7, writeSync } from "fs";
14484
- import { join as join30 } from "path";
14766
+ import { join as join31 } from "path";
14485
14767
 
14486
14768
  // ../producer/src/services/distributed/mp4Stitch.ts
14487
- import { createReadStream as createReadStream4, createWriteStream, mkdirSync as mkdirSync10, mkdtempSync as mkdtempSync4, rmSync as rmSync10 } from "fs";
14769
+ import { createReadStream as createReadStream4, createWriteStream, mkdirSync as mkdirSync10, mkdtempSync as mkdtempSync4, rmSync as rmSync11 } from "fs";
14488
14770
  import { open } from "fs/promises";
14489
- import { dirname as dirname11, join as join29 } from "path";
14771
+ import { dirname as dirname11, join as join30 } from "path";
14490
14772
  import { finished, pipeline } from "stream/promises";
14491
14773
  function boxAt(src, off, at, limit) {
14492
14774
  let size = src.readUInt32BE(off);
@@ -14852,16 +15134,16 @@ async function writeStitchedMp4(chunkPaths, outputPath, audioPath) {
14852
15134
  const header = audioPath ? buildStitchedHeader(layouts.slice(1), layouts[0]) : buildStitchedHeader(layouts);
14853
15135
  mkdirSync10(dirname11(outputPath), { recursive: true });
14854
15136
  const workDir = mkdtempSync4(`${outputPath}.stitch-`);
14855
- const out = createWriteStream(join29(workDir, "out.mp4"));
15137
+ const out = createWriteStream(join30(workDir, "out.mp4"));
14856
15138
  try {
14857
15139
  out.write(header);
14858
15140
  for (const [i, path] of sourcePaths.entries()) await copyPayload(path, layouts[i], i, out);
14859
15141
  out.end();
14860
15142
  await finished(out);
14861
- renameWithRetry(join29(workDir, "out.mp4"), outputPath);
15143
+ renameWithRetry(join30(workDir, "out.mp4"), outputPath);
14862
15144
  } finally {
14863
15145
  out.destroy();
14864
- rmSync10(workDir, { recursive: true, force: true });
15146
+ rmSync11(workDir, { recursive: true, force: true });
14865
15147
  }
14866
15148
  }
14867
15149
 
@@ -14952,7 +15234,7 @@ async function writeChunkAudioSlices(input) {
14952
15234
  });
14953
15235
  const bytes = readFileSync10(input.audioPath);
14954
15236
  const layout = { sizeBytes: bytes.length, payloadStart, payloadEnd, partStarts: {} };
14955
- mkdirSync11(join30(input.planDir, SLICE_DIR), { recursive: true });
15237
+ mkdirSync11(join31(input.planDir, SLICE_DIR), { recursive: true });
14956
15238
  input.chunks.forEach((_, index) => {
14957
15239
  const cut = audioCutForChunk(grid, input.chunks, index, input.fps);
14958
15240
  if (!cut) return;
@@ -14960,17 +15242,17 @@ async function writeChunkAudioSlices(input) {
14960
15242
  const start = offsets[cut.firstPacket];
14961
15243
  layout.partStarts[index] = start;
14962
15244
  const end = offsets[last] + track.sizes[last];
14963
- writeFileSync7(join30(input.planDir, chunkAudioSlicePath(index)), bytes.subarray(start, end));
15245
+ writeFileSync7(join31(input.planDir, chunkAudioSlicePath(index)), bytes.subarray(start, end));
14964
15246
  });
14965
15247
  const frame = [bytes.subarray(0, payloadStart), bytes.subarray(payloadEnd)];
14966
- writeFileSync7(join30(input.planDir, SLICE_FRAME), Buffer.concat(frame));
14967
- writeFileSync7(join30(input.planDir, SLICE_LAYOUT), JSON.stringify(layout));
15248
+ writeFileSync7(join31(input.planDir, SLICE_FRAME), Buffer.concat(frame));
15249
+ writeFileSync7(join31(input.planDir, SLICE_LAYOUT), JSON.stringify(layout));
14968
15250
  }
14969
15251
  function chunkAudioSource(planDir, chunkIndex, scratchPath) {
14970
- const layoutPath = join30(planDir, SLICE_LAYOUT);
15252
+ const layoutPath = join31(planDir, SLICE_LAYOUT);
14971
15253
  if (!existsSync19(layoutPath)) return resolvePlanAudioPath(planDir);
14972
15254
  const layout = JSON.parse(readFileSync10(layoutPath, "utf-8"));
14973
- const frame = readFileSync10(join30(planDir, SLICE_FRAME));
15255
+ const frame = readFileSync10(join31(planDir, SLICE_FRAME));
14974
15256
  const fd = openSync5(scratchPath, "w");
14975
15257
  try {
14976
15258
  writeSync(fd, frame, 0, layout.payloadStart, 0);
@@ -14983,12 +15265,12 @@ function chunkAudioSource(planDir, chunkIndex, scratchPath) {
14983
15265
  );
14984
15266
  const start = layout.partStarts[chunkIndex];
14985
15267
  if (start !== void 0) {
14986
- const part = readFileSync10(join30(planDir, chunkAudioSlicePath(chunkIndex)));
15268
+ const part = readFileSync10(join31(planDir, chunkAudioSlicePath(chunkIndex)));
14987
15269
  writeSync(fd, part, 0, part.length, start);
14988
15270
  }
14989
15271
  ftruncateSync(fd, layout.sizeBytes);
14990
15272
  } finally {
14991
- closeSync6(fd);
15273
+ closeSync5(fd);
14992
15274
  }
14993
15275
  return scratchPath;
14994
15276
  }
@@ -15039,7 +15321,7 @@ async function muxChunkWithAudio(input) {
15039
15321
  // ../producer/src/services/distributed/planSize.ts
15040
15322
  import { createHash as createHash6 } from "crypto";
15041
15323
  import { lstatSync as lstatSync2, readdirSync as readdirSync8 } from "fs";
15042
- import { extname as extname5, join as join31, relative as relative4 } from "path";
15324
+ import { extname as extname5, join as join32, relative as relative4 } from "path";
15043
15325
  var MAX_TOP_COMPONENTS = 10;
15044
15326
  var SOURCE_MEDIA_EXTENSIONS = /* @__PURE__ */ new Set([
15045
15327
  ".aac",
@@ -15151,7 +15433,7 @@ function walkRegularFiles(dir, visit) {
15151
15433
  return;
15152
15434
  }
15153
15435
  for (const entry of entries) {
15154
- const full = join31(dir, entry.name);
15436
+ const full = join32(dir, entry.name);
15155
15437
  if (entry.isDirectory()) {
15156
15438
  walkRegularFiles(full, visit);
15157
15439
  } else if (entry.isFile()) {
@@ -15208,6 +15490,7 @@ var PLAN_PROJECT_DIR_SKIP_SEGMENTS = /* @__PURE__ */ new Set([
15208
15490
  ]);
15209
15491
  var DEFAULT_MAX_PARALLEL_CHUNKS = 16;
15210
15492
  var MIN_CHUNK_SIZE = 10;
15493
+ var MAX_CHUNK_SIZE = 3600;
15211
15494
  var MAX_PARALLEL_CHUNKS_CEILING = 256;
15212
15495
  var ESTIMATED_SECONDS_PER_MEGAPIXEL_FRAME = 0.11;
15213
15496
  var ESTIMATED_CHUNK_OVERHEAD_SECONDS = 60;
@@ -15234,6 +15517,11 @@ var ChunkExceedsWorkerTimeoutError = class extends Error {
15234
15517
  this.name = "ChunkExceedsWorkerTimeoutError";
15235
15518
  }
15236
15519
  };
15520
+ function framesWithinWorkerTimeout(workerTimeoutSeconds, secondsPerFrame) {
15521
+ return Math.floor(
15522
+ (workerTimeoutSeconds * WORKER_TIMEOUT_MARGIN - ESTIMATED_CHUNK_OVERHEAD_SECONDS) / secondsPerFrame
15523
+ );
15524
+ }
15237
15525
  function resolveMaxParallelChunks(config, totalFrames, megapixels, log = defaultLogger, measuredSecondsPerFrame) {
15238
15526
  if (config.maxParallelChunks !== void 0) return config.maxParallelChunks;
15239
15527
  const { workerTimeoutSeconds, workerConcurrency } = config;
@@ -15246,9 +15534,7 @@ function resolveMaxParallelChunks(config, totalFrames, megapixels, log = default
15246
15534
  const minFramesPerChunk = Math.ceil(ESTIMATED_CHUNK_OVERHEAD_SECONDS / secondsPerFrame);
15247
15535
  const wide = Math.max(1, Math.min(wave, Math.floor(totalFrames / minFramesPerChunk)));
15248
15536
  if (workerTimeoutSeconds === void 0) return wide;
15249
- const maxFramesPerChunk = Math.floor(
15250
- (workerTimeoutSeconds * WORKER_TIMEOUT_MARGIN - ESTIMATED_CHUNK_OVERHEAD_SECONDS) / secondsPerFrame
15251
- );
15537
+ const maxFramesPerChunk = framesWithinWorkerTimeout(workerTimeoutSeconds, secondsPerFrame);
15252
15538
  const needed = maxFramesPerChunk < 1 ? Infinity : Math.ceil(totalFrames / maxFramesPerChunk);
15253
15539
  if (needed > MAX_PARALLEL_CHUNKS_CEILING) {
15254
15540
  const framesAtCeiling = Math.ceil(totalFrames / MAX_PARALLEL_CHUNKS_CEILING);
@@ -15359,13 +15645,13 @@ function assertPositiveInteger2(name, value) {
15359
15645
  }
15360
15646
  var FREEZE_OWNED_PLAN_FILES = [
15361
15647
  "plan.json",
15362
- join32("meta", "composition.json"),
15363
- join32("meta", "encoder.json"),
15364
- join32("meta", "chunks.json")
15648
+ join33("meta", "composition.json"),
15649
+ join33("meta", "encoder.json"),
15650
+ join33("meta", "chunks.json")
15365
15651
  ];
15366
15652
  function removeFreezeOwnedPlanFiles(planDir) {
15367
15653
  for (const relativePath of FREEZE_OWNED_PLAN_FILES) {
15368
- rmSync11(join32(planDir, relativePath), { force: true });
15654
+ rmSync12(join33(planDir, relativePath), { force: true });
15369
15655
  }
15370
15656
  }
15371
15657
  function buildChunkSlices(totalFrames, chunkCount, effectiveChunkSize) {
@@ -15377,6 +15663,15 @@ function buildChunkSlices(totalFrames, chunkCount, effectiveChunkSize) {
15377
15663
  }
15378
15664
  return slices;
15379
15665
  }
15666
+ function buildPlanChunkSlices(frameWeights, config, chunkCount, effectiveChunkSize, maxFramesPerChunk = Infinity) {
15667
+ const weighted = config.chunkSize === void 0 ? buildWeightedChunkSlices(
15668
+ frameWeights,
15669
+ chunkCount,
15670
+ MIN_CHUNK_SIZE,
15671
+ Math.min(config.targetChunkFrames ?? MAX_CHUNK_SIZE, MAX_CHUNK_SIZE, maxFramesPerChunk)
15672
+ ) : null;
15673
+ return weighted ?? buildChunkSlices(frameWeights.length, chunkCount, effectiveChunkSize);
15674
+ }
15380
15675
  async function readFontSnapshotSha() {
15381
15676
  const module = await import("./fontData.generated-NXAOI4GH.js");
15382
15677
  const data = module.EMBEDDED_FONT_DATA;
@@ -15498,19 +15793,19 @@ function createVideoSourceShipper(input) {
15498
15793
  const known = shipped.get(srcPath);
15499
15794
  if (known) return known;
15500
15795
  const stagedRel = pathInside(input.workVideoFramesDir, srcPath);
15501
- const current = stagedRel === null ? srcPath : join32(input.planDir, "video-frames", stagedRel);
15796
+ const current = stagedRel === null ? srcPath : join33(input.planDir, "video-frames", stagedRel);
15502
15797
  let result = null;
15503
15798
  for (const root of stagedRel === null ? [input.workCompiledDir, input.projectDir] : []) {
15504
15799
  const rel = pathInside(root, srcPath);
15505
- if (rel !== null && (existsSync20(join32(input.planDir, "compiled", rel)) || input.isRemote(srcPath))) {
15800
+ if (rel !== null && (existsSync20(join33(input.planDir, "compiled", rel)) || input.isRemote(srcPath))) {
15506
15801
  result = ["compiled", ...rel.split(sep2)].join("/");
15507
15802
  break;
15508
15803
  }
15509
15804
  }
15510
15805
  if (result === null) {
15511
15806
  result = `video-sources/${shipped.size}${extname6(current)}`;
15512
- const destination = join32(input.planDir, ...result.split("/"));
15513
- mkdirSync12(join32(input.planDir, "video-sources"), { recursive: true });
15807
+ const destination = join33(input.planDir, ...result.split("/"));
15808
+ mkdirSync12(join33(input.planDir, "video-sources"), { recursive: true });
15514
15809
  try {
15515
15810
  linkSync(current, destination);
15516
15811
  } catch {
@@ -15559,14 +15854,14 @@ async function compilePlanComposition(projectDir, config, planDir, options) {
15559
15854
  variables: config.variables
15560
15855
  });
15561
15856
  const entryFile = config.entryFile ?? "index.html";
15562
- const htmlPath = join32(projectDir, entryFile);
15857
+ const htmlPath = join33(projectDir, entryFile);
15563
15858
  if (!existsSync20(htmlPath)) {
15564
15859
  throw new Error(`[plan] entry file not found: ${htmlPath}`);
15565
15860
  }
15566
- const workDir = join32(planDir, ".plan-work");
15567
- rmSync11(workDir, { recursive: true, force: true });
15861
+ const workDir = join33(planDir, ".plan-work");
15862
+ rmSync12(workDir, { recursive: true, force: true });
15568
15863
  mkdirSync12(workDir, { recursive: true });
15569
- const compiledDir = join32(workDir, "compiled");
15864
+ const compiledDir = join33(workDir, "compiled");
15570
15865
  mkdirSync12(compiledDir, { recursive: true });
15571
15866
  let stageStarted = Date.now();
15572
15867
  cpSync2(projectDir, compiledDir, {
@@ -15580,10 +15875,10 @@ async function compilePlanComposition(projectDir, config, planDir, options) {
15580
15875
  }
15581
15876
  });
15582
15877
  logPlanStage(log, "copy", stageStarted);
15583
- const finalCompiledDir = join32(planDir, "compiled");
15878
+ const finalCompiledDir = join33(planDir, "compiled");
15584
15879
  const needsAlpha = outputNeedsAlpha(config.format);
15585
15880
  const remoteFiles = Object.entries(options.remoteFiles ?? {});
15586
- const remoteLocalPath = (rel) => join32(projectDir, ...rel.split("/"));
15881
+ const remoteLocalPath = (rel) => join33(projectDir, ...rel.split("/"));
15587
15882
  for (const [, file] of remoteFiles) {
15588
15883
  declareContentAddressedUrl(file.url, file.sha256);
15589
15884
  if (file.probeFactsUrl) declareProbeFactsUrl(file.url, file.probeFactsUrl);
@@ -15662,7 +15957,7 @@ async function compilePlanComposition(projectDir, config, planDir, options) {
15662
15957
  if (probeResult.fileServer) closeFileServerSafely(probeResult.fileServer, "plan", log);
15663
15958
  if (probeResult.probeSession) {
15664
15959
  try {
15665
- const { closeCaptureSession: closeCaptureSession2 } = await import("./src-2YZVFDNC.js");
15960
+ const { closeCaptureSession: closeCaptureSession2 } = await import("./src-QQPHMIJ7.js");
15666
15961
  await closeCaptureSession2(probeResult.probeSession);
15667
15962
  } catch (err) {
15668
15963
  log.warn("[plan] probe session close failed", {
@@ -15769,17 +16064,17 @@ async function buildLocalExecutionPlan(projectDir, config, executionPlanDir, opt
15769
16064
  let stageStarted = Date.now();
15770
16065
  const extractResult = await extractPlanVideos(c, options.deferVideoExtraction);
15771
16066
  logPlanStage(log, "extract", stageStarted);
15772
- const stagedVideoFrames = join32(compiledDir, "__hyperframes_video_frames");
15773
- const videoFramesDst = join32(planDir, "video-frames");
15774
- if (existsSync20(videoFramesDst)) rmSync11(videoFramesDst, { recursive: true, force: true });
15775
- const videoSourcesDir = join32(planDir, "video-sources");
15776
- rmSync11(videoSourcesDir, { recursive: true, force: true });
16067
+ const stagedVideoFrames = join33(compiledDir, "__hyperframes_video_frames");
16068
+ const videoFramesDst = join33(planDir, "video-frames");
16069
+ if (existsSync20(videoFramesDst)) rmSync12(videoFramesDst, { recursive: true, force: true });
16070
+ const videoSourcesDir = join33(planDir, "video-sources");
16071
+ rmSync12(videoSourcesDir, { recursive: true, force: true });
15777
16072
  if (existsSync20(stagedVideoFrames)) {
15778
16073
  renameWithRetry(stagedVideoFrames, videoFramesDst);
15779
16074
  } else {
15780
16075
  mkdirSync12(videoFramesDst, { recursive: true });
15781
16076
  }
15782
- if (existsSync20(finalCompiledDir)) rmSync11(finalCompiledDir, { recursive: true, force: true });
16077
+ if (existsSync20(finalCompiledDir)) rmSync12(finalCompiledDir, { recursive: true, force: true });
15783
16078
  renameWithRetry(compiledDir, finalCompiledDir);
15784
16079
  const shipVideoSource = createVideoSourceShipper({
15785
16080
  planDir,
@@ -15809,7 +16104,7 @@ async function buildLocalExecutionPlan(projectDir, config, executionPlanDir, opt
15809
16104
  };
15810
16105
  })
15811
16106
  });
15812
- mkdirSync12(join32(planDir, "meta"), { recursive: true });
16107
+ mkdirSync12(join33(planDir, "meta"), { recursive: true });
15813
16108
  writePlanRemoteFiles(
15814
16109
  planDir,
15815
16110
  remoteFiles.map(([rel, { sha256, sizeBytes }]) => ({
@@ -15819,13 +16114,21 @@ async function buildLocalExecutionPlan(projectDir, config, executionPlanDir, opt
15819
16114
  }))
15820
16115
  );
15821
16116
  writeFileSync8(
15822
- join32(planDir, PLAN_VIDEOS_META_RELATIVE_PATH),
16117
+ join33(planDir, PLAN_VIDEOS_META_RELATIVE_PATH),
15823
16118
  JSON.stringify(planVideosJson, null, 2),
15824
16119
  "utf-8"
15825
16120
  );
15826
16121
  const digests = options.digests ?? /* @__PURE__ */ new Map();
15827
16122
  const separateAudio = plansSeparateAudio(config, options);
15828
16123
  const chunksCarryAudio = !separateAudio && carriesChunkAudio(config, options);
16124
+ const frameWeights = planFrameWeights({
16125
+ videos: planVideosJson.videos,
16126
+ extracted: planVideosJson.extracted,
16127
+ totalFrames,
16128
+ fps: config.fps,
16129
+ width,
16130
+ height
16131
+ });
15829
16132
  stageStarted = Date.now();
15830
16133
  const [audioOutcome, overlapOutcome, frameCostOutcome] = await Promise.allSettled([
15831
16134
  separateAudio ? null : mixPlanAudio(c, finalCompiledDir).finally(() => logPlanStage(log, "audio", stageStarted)),
@@ -15876,12 +16179,21 @@ async function buildLocalExecutionPlan(projectDir, config, executionPlanDir, opt
15876
16179
  maxParallel,
15877
16180
  config.targetChunkFrames
15878
16181
  );
15879
- const chunks = buildChunkSlices(totalFrames, chunkCount, effectiveChunkSize);
16182
+ const chunks = buildPlanChunkSlices(
16183
+ frameWeights,
16184
+ config,
16185
+ chunkCount,
16186
+ effectiveChunkSize,
16187
+ chunkSizingUsesFrameCost(config) && config.workerTimeoutSeconds !== void 0 ? framesWithinWorkerTimeout(
16188
+ config.workerTimeoutSeconds,
16189
+ estimateFrameSeconds(megapixels, frameCostOutcome.value)
16190
+ ) : void 0
16191
+ );
15880
16192
  const audioResult = audioOutcome.value;
15881
16193
  if (audioResult?.audioError) {
15882
16194
  applyDistributedAudioWarningPolicy(job, audioResult.audioError, audioResult.audioFailures, log);
15883
16195
  }
15884
- const planAudioPath = join32(planDir, PLAN_AUDIO_RELATIVE_PATH);
16196
+ const planAudioPath = join33(planDir, PLAN_AUDIO_RELATIVE_PATH);
15885
16197
  if (audioResult?.hasAudio && existsSync20(audioResult.audioOutputPath)) {
15886
16198
  renameWithRetry(audioResult.audioOutputPath, planAudioPath);
15887
16199
  }
@@ -15930,7 +16242,7 @@ async function buildLocalExecutionPlan(projectDir, config, executionPlanDir, opt
15930
16242
  format: config.format
15931
16243
  };
15932
16244
  try {
15933
- rmSync11(workDir, { recursive: true, force: true });
16245
+ rmSync12(workDir, { recursive: true, force: true });
15934
16246
  } catch (err) {
15935
16247
  log.warn("[plan] failed to remove temp work dir", {
15936
16248
  workDir,
@@ -16022,7 +16334,6 @@ var ALLOWED_RUNTIME_CAPS = ["lambda", "temporal", "cloud-run-job", "k8s-job", "n
16022
16334
  var ALLOWED_HDR_MODES = ["auto", "force-sdr"];
16023
16335
  var MAX_DIMENSION = 7680;
16024
16336
  var MIN_DIMENSION = 16;
16025
- var MAX_CHUNK_SIZE = 3600;
16026
16337
  function validateDistributedRenderConfig(config) {
16027
16338
  if (config === null || typeof config !== "object") {
16028
16339
  throw new InvalidConfigError("config", "must be an object");
@@ -16306,6 +16617,7 @@ function assertRequestOptionScalars(options) {
16306
16617
  assertOptionalInteger(options, "gifLoop");
16307
16618
  assertOptionalInteger(options, "hlsSegmentSeconds", 1);
16308
16619
  assertOptionalInteger(options, "workers", 1);
16620
+ assertOptionalInteger(options, "maxRenderMs");
16309
16621
  assertOptionalInteger(options, "crf");
16310
16622
  for (const field of ["useGpu", "debug", "outputResolutionAspectAgnostic"]) {
16311
16623
  assertOptionalBoolean(options, field);
@@ -16480,13 +16792,13 @@ function renderRequestFromDistributedConfig(input) {
16480
16792
  import {
16481
16793
  existsSync as existsSync23,
16482
16794
  mkdirSync as mkdirSync13,
16483
- statSync as statSync7,
16795
+ statSync as statSync8,
16484
16796
  mkdtempSync as mkdtempSync5,
16485
16797
  writeFileSync as writeFileSync9,
16486
- rmSync as rmSync12,
16798
+ rmSync as rmSync13,
16487
16799
  createReadStream as createReadStream5
16488
16800
  } from "fs";
16489
- import { resolve as resolve9, dirname as dirname13, join as join35 } from "path";
16801
+ import { resolve as resolve9, dirname as dirname13, join as join36 } from "path";
16490
16802
  import { tmpdir as tmpdir3 } from "os";
16491
16803
  import { parseArgs } from "util";
16492
16804
  import crypto from "crypto";
@@ -16498,13 +16810,13 @@ import { serve as serve2 } from "@hono/node-server";
16498
16810
  import {
16499
16811
  existsSync as existsSync21,
16500
16812
  readFileSync as readFileSync11,
16501
- statSync as statSync6,
16813
+ statSync as statSync7,
16502
16814
  openSync as openSync6,
16503
- fstatSync as fstatSync4,
16504
- closeSync as closeSync7,
16815
+ fstatSync as fstatSync3,
16816
+ closeSync as closeSync6,
16505
16817
  constants as constants3
16506
16818
  } from "fs";
16507
- import { resolve as resolve8, join as join33, relative as relative6, isAbsolute as isAbsolute3, sep as sep3 } from "path";
16819
+ import { resolve as resolve8, join as join34, relative as relative6, isAbsolute as isAbsolute3, sep as sep3 } from "path";
16508
16820
  function isStringRecord(value) {
16509
16821
  if (!value || typeof value !== "object" || Array.isArray(value)) {
16510
16822
  return false;
@@ -16537,19 +16849,19 @@ function readEntryHtml(filePath) {
16537
16849
  } catch (error) {
16538
16850
  if (error instanceof Error && "code" in error && (error.code === "ENOENT" || error.code === "ENOTDIR"))
16539
16851
  return null;
16540
- if (!statSync6(filePath, { throwIfNoEntry: false })?.isFile()) return null;
16852
+ if (!statSync7(filePath, { throwIfNoEntry: false })?.isFile()) return null;
16541
16853
  throw error;
16542
16854
  }
16543
16855
  try {
16544
- if (!fstatSync4(fd).isFile()) return null;
16856
+ if (!fstatSync3(fd).isFile()) return null;
16545
16857
  return readFileSync11(fd, "utf-8");
16546
16858
  } finally {
16547
- closeSync7(fd);
16859
+ closeSync6(fd);
16548
16860
  }
16549
16861
  }
16550
16862
  function readProjectEntryFile(projectDir, preferredEntryFile) {
16551
16863
  const absProjectDir = resolve8(projectDir);
16552
- if (!existsSync21(absProjectDir) || !statSync6(absProjectDir).isDirectory()) {
16864
+ if (!existsSync21(absProjectDir) || !statSync7(absProjectDir).isDirectory()) {
16553
16865
  return { error: `Project directory not found: ${absProjectDir}` };
16554
16866
  }
16555
16867
  const entryCandidates = [preferredEntryFile, "index.html", "src/index.html"].filter(
@@ -16571,7 +16883,7 @@ function readProjectEntryFile(projectDir, preferredEntryFile) {
16571
16883
  }
16572
16884
  }
16573
16885
  return {
16574
- error: `No HTML entry file found in project directory: ${join33(absProjectDir, preferredEntryFile || "index.html")}`
16886
+ error: `No HTML entry file found in project directory: ${join34(absProjectDir, preferredEntryFile || "index.html")}`
16575
16887
  };
16576
16888
  }
16577
16889
  function prepareHyperframeLintBody(body) {
@@ -16617,7 +16929,7 @@ async function runHyperframeLint(prepared) {
16617
16929
  // ../producer/src/services/healthWorker.ts
16618
16930
  import { Worker as Worker2 } from "worker_threads";
16619
16931
  import { fileURLToPath as fileURLToPath6 } from "url";
16620
- import { dirname as dirname12, join as join34 } from "path";
16932
+ import { dirname as dirname12, join as join35 } from "path";
16621
16933
  import { existsSync as existsSync22 } from "fs";
16622
16934
  var DEFAULT_HEALTH_PORT = 9848;
16623
16935
  async function startHealthWorker(options = {}) {
@@ -16693,7 +17005,7 @@ function defaultLogger2() {
16693
17005
  }
16694
17006
  function resolveWorkerEntry2() {
16695
17007
  const here = dirname12(fileURLToPath6(import.meta.url));
16696
- const candidates = [join34(here, "healthWorkerThread.js"), join34(here, "healthWorkerThread.ts")];
17008
+ const candidates = [join35(here, "healthWorkerThread.js"), join35(here, "healthWorkerThread.ts")];
16697
17009
  for (const candidate of candidates) {
16698
17010
  if (existsSync22(candidate)) return candidate;
16699
17011
  }
@@ -16708,7 +17020,8 @@ var SAFE_RENDER_ERROR_CODES = /* @__PURE__ */ new Set([
16708
17020
  "INVALID_VIDEO_METADATA",
16709
17021
  "VIDEO_SOURCE_UNRENDERABLE",
16710
17022
  "VIDEO_EXTRACTION_FAILED",
16711
- "ENCODER_INTERRUPTED"
17023
+ "ENCODER_INTERRUPTED",
17024
+ "RENDER_TOO_SLOW"
16712
17025
  ]);
16713
17026
  function extractSafeRenderErrorCode(error) {
16714
17027
  if (typeof error !== "object" || error === null || !("code" in error)) return void 0;
@@ -16767,6 +17080,7 @@ function parseRenderOptions(body) {
16767
17080
  const fps = parseServerFps(body.fps);
16768
17081
  const quality = parseServerQuality(body.quality);
16769
17082
  const workers = typeof body.workers === "number" ? body.workers : void 0;
17083
+ const maxRenderMs = typeof body.maxRenderMs === "number" ? body.maxRenderMs : void 0;
16770
17084
  const useGpu = body.gpu === true;
16771
17085
  const debug = body.debug === true;
16772
17086
  const strictness = body.bestEffort === false ? "strict" : "best-effort";
@@ -16782,6 +17096,7 @@ function parseRenderOptions(body) {
16782
17096
  fps,
16783
17097
  quality,
16784
17098
  workers,
17099
+ maxRenderMs,
16785
17100
  crf,
16786
17101
  videoBitrate,
16787
17102
  useGpu,
@@ -16815,6 +17130,7 @@ function buildRenderJobConfig(input, outputPath, log) {
16815
17130
  quality: input.quality,
16816
17131
  format: input.format ?? "mp4",
16817
17132
  workers: input.workers,
17133
+ maxRenderMs: input.maxRenderMs,
16818
17134
  crf: input.crf,
16819
17135
  videoBitrate: input.videoBitrate,
16820
17136
  useGpu: input.useGpu,
@@ -16841,6 +17157,9 @@ function resolvePreparedRenderOutput(prepared, rendersDir, log) {
16841
17157
  function validateRenderOverrides(body) {
16842
17158
  const encoder = parseEncoderOptions(body, parseServerFormat(body.format) ?? "mp4");
16843
17159
  if (!encoder.ok) return encoder.error;
17160
+ if (body.maxRenderMs !== void 0 && (typeof body.maxRenderMs !== "number" || !Number.isInteger(body.maxRenderMs) || body.maxRenderMs < 0)) {
17161
+ return "maxRenderMs must be a non-negative integer number of milliseconds";
17162
+ }
16844
17163
  if (body.variables !== void 0 && !isPlainObject2(body.variables)) {
16845
17164
  return 'variables must be a JSON object keyed by variable id (e.g. {"title":"Hello"})';
16846
17165
  }
@@ -16868,11 +17187,12 @@ function validateOutputResolutionOverride(body) {
16868
17187
  }
16869
17188
  return void 0;
16870
17189
  }
17190
+ var MAX_PREVIEW_HTML_BYTES = 20 * 1024 * 1024;
16871
17191
  function prepareProjectDirectory(projectDir, options) {
16872
17192
  const candidate = nonEmptyString(projectDir);
16873
17193
  if (!candidate) return null;
16874
17194
  const absProjectDir = resolve9(candidate);
16875
- if (!existsSync23(absProjectDir) || !statSync7(absProjectDir).isDirectory()) {
17195
+ if (!existsSync23(absProjectDir) || !statSync8(absProjectDir).isDirectory()) {
16876
17196
  return { error: `Project directory not found: ${absProjectDir}` };
16877
17197
  }
16878
17198
  const entry = options.entryFile || "index.html";
@@ -16888,11 +17208,7 @@ async function resolveInlineRenderHtml(body) {
16888
17208
  if (!previewUrl)
16889
17209
  return { error: "Missing render source: provide projectDir, previewUrl, or html" };
16890
17210
  try {
16891
- const response = await fetch(previewUrl, { method: "GET" });
16892
- if (!response.ok) {
16893
- return { error: `Failed to fetch previewUrl: ${response.status} ${response.statusText}` };
16894
- }
16895
- return { html: await response.text() };
17211
+ return { html: await fetchPublicHttpsText(previewUrl, { maxBytes: MAX_PREVIEW_HTML_BYTES }) };
16896
17212
  } catch (error) {
16897
17213
  return {
16898
17214
  error: `Failed to fetch previewUrl: ${error instanceof Error ? error.message : String(error)}`
@@ -16901,8 +17217,8 @@ async function resolveInlineRenderHtml(body) {
16901
17217
  }
16902
17218
  function materializeInlineProject(html, options) {
16903
17219
  const tempRoot = process.env.PRODUCER_TMP_PROJECT_DIR || tmpdir3();
16904
- const tempProjectDir = mkdtempSync5(join35(tempRoot, "producer-project-"));
16905
- writeFileSync9(join35(tempProjectDir, "index.html"), html, "utf-8");
17220
+ const tempProjectDir = mkdtempSync5(join36(tempRoot, "producer-project-"));
17221
+ writeFileSync9(join36(tempProjectDir, "index.html"), html, "utf-8");
16906
17222
  return {
16907
17223
  prepared: {
16908
17224
  input: { projectDir: tempProjectDir, ...options },
@@ -16963,7 +17279,7 @@ function createArtifactStore(ttlMs) {
16963
17279
  function cleanupTempDir(dir, log) {
16964
17280
  if (!dir) return;
16965
17281
  try {
16966
- rmSync12(dir, { recursive: true, force: true });
17282
+ rmSync13(dir, { recursive: true, force: true });
16967
17283
  } catch (error) {
16968
17284
  log.warn("Failed to cleanup temp project dir", {
16969
17285
  cleanupProjectDir: dir,
@@ -16972,7 +17288,7 @@ function cleanupTempDir(dir, log) {
16972
17288
  }
16973
17289
  }
16974
17290
  function outputFileSize(path) {
16975
- return existsSync23(path) ? statSync7(path).size : 0;
17291
+ return existsSync23(path) ? statSync8(path).size : 0;
16976
17292
  }
16977
17293
  function createBlockingProgressReporter(log, requestId) {
16978
17294
  let lastLoggedPct = -10;
@@ -17272,7 +17588,7 @@ function createRenderHandlers(options = {}) {
17272
17588
  store.delete(token);
17273
17589
  return c.json({ success: false, error: "Output artifact file missing" }, 404);
17274
17590
  }
17275
- const stats = statSync7(artifact.path);
17591
+ const stats = statSync8(artifact.path);
17276
17592
  return new Response(createReadStream5(artifact.path), {
17277
17593
  headers: {
17278
17594
  "content-type": "video/mp4",
@@ -17315,7 +17631,7 @@ function startServer(options = {}) {
17315
17631
  });
17316
17632
  async function shutdown(signal) {
17317
17633
  log.info(`Received ${signal}, shutting down`);
17318
- const { drainBrowserPool } = await import("./src-2YZVFDNC.js");
17634
+ const { drainBrowserPool } = await import("./src-QQPHMIJ7.js");
17319
17635
  await drainBrowserPool().catch(() => {
17320
17636
  });
17321
17637
  const handle = await Promise.race([
@@ -17359,12 +17675,12 @@ import {
17359
17675
  mkdtempSync as mkdtempSync7,
17360
17676
  readFileSync as readFileSync12,
17361
17677
  readdirSync as readdirSync9,
17362
- rmSync as rmSync14,
17363
- statSync as statSync9,
17678
+ rmSync as rmSync15,
17679
+ statSync as statSync10,
17364
17680
  writeFileSync as writeFileSync11
17365
17681
  } from "fs";
17366
17682
  import { tmpdir as tmpdir4 } from "os";
17367
- import { dirname as dirname15, isAbsolute as isAbsolute4, join as join38, relative as relative7, resolve as resolve10, sep as sep4 } from "path";
17683
+ import { dirname as dirname15, isAbsolute as isAbsolute4, join as join39, relative as relative7, resolve as resolve10, sep as sep4 } from "path";
17368
17684
 
17369
17685
  // ../producer/src/services/distributed/planV2Publisher.ts
17370
17686
  import {
@@ -17373,11 +17689,11 @@ import {
17373
17689
  linkSync as linkSync2,
17374
17690
  mkdirSync as mkdirSync14,
17375
17691
  mkdtempSync as mkdtempSync6,
17376
- rmSync as rmSync13,
17377
- statSync as statSync8,
17692
+ rmSync as rmSync14,
17693
+ statSync as statSync9,
17378
17694
  writeFileSync as writeFileSync10
17379
17695
  } from "fs";
17380
- import { dirname as dirname14, join as join37 } from "path";
17696
+ import { dirname as dirname14, join as join38 } from "path";
17381
17697
 
17382
17698
  // ../producer/src/services/distributed/planV2Errors.ts
17383
17699
  var PLAN_V2_INTEGRITY_UNRECOVERABLE = "PLAN_V2_INTEGRITY_UNRECOVERABLE";
@@ -17392,7 +17708,7 @@ var PlanV2IntegrityError = class extends Error {
17392
17708
  };
17393
17709
 
17394
17710
  // ../producer/src/services/distributed/planV2Layout.ts
17395
- import { join as join36 } from "path";
17711
+ import { join as join37 } from "path";
17396
17712
  var SHA256_PATTERN = /^[0-9a-f]{64}$/;
17397
17713
  function assertPlanV2Sha256(value, field) {
17398
17714
  if (typeof value !== "string" || !SHA256_PATTERN.test(value)) {
@@ -17402,7 +17718,7 @@ function assertPlanV2Sha256(value, field) {
17402
17718
  }
17403
17719
  function planV2BlobPath(root, sha256) {
17404
17720
  const digest = assertPlanV2Sha256(sha256, "artifact sha256");
17405
- return join36(root, "artifacts", "sha256", digest.slice(0, 2), digest);
17721
+ return join37(root, "artifacts", "sha256", digest.slice(0, 2), digest);
17406
17722
  }
17407
17723
 
17408
17724
  // ../producer/src/services/distributed/planV2Publisher.ts
@@ -17443,11 +17759,11 @@ var LocalPlanV2ArtifactPublisher = class {
17443
17759
  this.destinationDir = destinationDir;
17444
17760
  this.#linkFile = options.linkFile ?? linkSync2;
17445
17761
  mkdirSync14(dirname14(destinationDir), { recursive: true });
17446
- this.temporaryDir = mkdtempSync6(join37(dirname14(destinationDir), ".plan-v2-publish-"));
17762
+ this.temporaryDir = mkdtempSync6(join38(dirname14(destinationDir), ".plan-v2-publish-"));
17447
17763
  }
17448
17764
  async putBlob(blob) {
17449
17765
  const digest = assertPlanV2Sha256(blob.sha256, "published blob sha256");
17450
- const sourceSize = statSync8(blob.sourcePath).size;
17766
+ const sourceSize = statSync9(blob.sourcePath).size;
17451
17767
  if (sourceSize !== blob.sizeBytes) {
17452
17768
  throw new PlanV2IntegrityError(
17453
17769
  `published blob size changed for ${digest}: expected ${blob.sizeBytes}, got ${sourceSize}`
@@ -17456,8 +17772,8 @@ var LocalPlanV2ArtifactPublisher = class {
17456
17772
  const destinationPath = planV2BlobPath(this.temporaryDir, digest);
17457
17773
  if (existsSync24(destinationPath)) return;
17458
17774
  mkdirSync14(dirname14(destinationPath), { recursive: true });
17459
- const stagingDir = mkdtempSync6(join37(dirname14(destinationPath), ".plan-v2-blob-"));
17460
- const temporaryPath = join37(stagingDir, "blob");
17775
+ const stagingDir = mkdtempSync6(join38(dirname14(destinationPath), ".plan-v2-blob-"));
17776
+ const temporaryPath = join38(stagingDir, "blob");
17461
17777
  try {
17462
17778
  try {
17463
17779
  this.#linkFile(blob.sourcePath, temporaryPath);
@@ -17467,7 +17783,7 @@ var LocalPlanV2ArtifactPublisher = class {
17467
17783
  }
17468
17784
  renameWithRetry(temporaryPath, destinationPath);
17469
17785
  } finally {
17470
- rmSync13(stagingDir, { recursive: true, force: true });
17786
+ rmSync14(stagingDir, { recursive: true, force: true });
17471
17787
  }
17472
17788
  }
17473
17789
  async commitManifest(manifestBytes) {
@@ -17478,13 +17794,13 @@ var LocalPlanV2ArtifactPublisher = class {
17478
17794
  );
17479
17795
  }
17480
17796
  }
17481
- writeFileSync10(join37(this.temporaryDir, "plan.json"), manifestBytes, "utf-8");
17797
+ writeFileSync10(join38(this.temporaryDir, "plan.json"), manifestBytes, "utf-8");
17482
17798
  renameWithRetry(this.temporaryDir, this.destinationDir);
17483
17799
  this.#committed = true;
17484
17800
  }
17485
17801
  async abort() {
17486
17802
  if (!this.#committed) {
17487
- rmSync13(this.temporaryDir, { recursive: true, force: true });
17803
+ rmSync14(this.temporaryDir, { recursive: true, force: true });
17488
17804
  }
17489
17805
  }
17490
17806
  };
@@ -17523,7 +17839,7 @@ function listFiles(root) {
17523
17839
  const rootResolved = resolve10(root);
17524
17840
  function walk(dir) {
17525
17841
  for (const entry of readdirSync9(dir, { withFileTypes: true })) {
17526
- const absolutePath = join38(dir, entry.name);
17842
+ const absolutePath = join39(dir, entry.name);
17527
17843
  if (entry.isDirectory()) {
17528
17844
  walk(absolutePath);
17529
17845
  } else if (entry.isFile()) {
@@ -17550,13 +17866,13 @@ function assertValidExtractionCacheCompleteSentinel(path) {
17550
17866
  }
17551
17867
  }
17552
17868
  function validateExtractionCacheCompleteSentinels(executionPlanDir) {
17553
- const videoRoot = join38(executionPlanDir, "video-frames");
17869
+ const videoRoot = join39(executionPlanDir, "video-frames");
17554
17870
  if (!existsSync25(videoRoot)) return;
17555
17871
  for (const videoEntry of readdirSync9(videoRoot, { withFileTypes: true })) {
17556
17872
  if (!videoEntry.isDirectory()) continue;
17557
- const videoDir = join38(videoRoot, videoEntry.name);
17873
+ const videoDir = join39(videoRoot, videoEntry.name);
17558
17874
  if (readdirSync9(videoDir).includes(EXTRACTION_CACHE_COMPLETE_SENTINEL)) {
17559
- const sentinelPath = join38(videoDir, EXTRACTION_CACHE_COMPLETE_SENTINEL);
17875
+ const sentinelPath = join39(videoDir, EXTRACTION_CACHE_COMPLETE_SENTINEL);
17560
17876
  assertValidExtractionCacheCompleteSentinel(sentinelPath);
17561
17877
  }
17562
17878
  }
@@ -17603,7 +17919,7 @@ function listVideoFramePaths(executionPlanDir, videos) {
17603
17919
  if (video.deferredRange) {
17604
17920
  const framePaths2 = /* @__PURE__ */ new Map();
17605
17921
  for (let index = 0; index < video.totalFrames; index++) {
17606
- framePaths2.set(index, join38(outputDir, String(index)));
17922
+ framePaths2.set(index, join39(outputDir, String(index)));
17607
17923
  }
17608
17924
  return { ...video, outputDir, framePaths: framePaths2, ownedByLookup: false };
17609
17925
  }
@@ -17611,7 +17927,7 @@ function listVideoFramePaths(executionPlanDir, videos) {
17611
17927
  const framePaths = /* @__PURE__ */ new Map();
17612
17928
  for (const frameName of frameNames) {
17613
17929
  if (frameName === EXTRACTION_CACHE_COMPLETE_SENTINEL) {
17614
- assertValidExtractionCacheCompleteSentinel(join38(outputDir, frameName));
17930
+ assertValidExtractionCacheCompleteSentinel(join39(outputDir, frameName));
17615
17931
  continue;
17616
17932
  }
17617
17933
  const match = /(\d+)(?=\.[^.]+$)/.exec(frameName);
@@ -17630,7 +17946,7 @@ function listVideoFramePaths(executionPlanDir, videos) {
17630
17946
  `duplicate extracted frame index ${frameIndex} in ${outputDir}`
17631
17947
  );
17632
17948
  }
17633
- framePaths.set(frameIndex, join38(outputDir, frameName));
17949
+ framePaths.set(frameIndex, join39(outputDir, frameName));
17634
17950
  }
17635
17951
  return {
17636
17952
  ...video,
@@ -17651,7 +17967,7 @@ function parsePlanVideosJson2(value) {
17651
17967
  }
17652
17968
  }
17653
17969
  function materializeExtractedVideoDirectories(planDir) {
17654
- const videosPath = join38(planDir, PLAN_VIDEOS_META_RELATIVE_PATH);
17970
+ const videosPath = join39(planDir, PLAN_VIDEOS_META_RELATIVE_PATH);
17655
17971
  if (!existsSync25(videosPath)) return;
17656
17972
  const videos = parsePlanVideosJson2(readJsonFile(videosPath, PLAN_VIDEOS_META_RELATIVE_PATH));
17657
17973
  for (const video of videos.extracted) {
@@ -17680,13 +17996,13 @@ function parseChunkSlices(value) {
17680
17996
  });
17681
17997
  }
17682
17998
  function buildVideoChunkDependencies(executionPlanDir, dimensions) {
17683
- const videoRoot = join38(executionPlanDir, "video-frames");
17999
+ const videoRoot = join39(executionPlanDir, "video-frames");
17684
18000
  const hasExtractedFrames = existsSync25(videoRoot) && listFiles(videoRoot).length > 0;
17685
- const videosPath = join38(executionPlanDir, PLAN_VIDEOS_META_RELATIVE_PATH);
18001
+ const videosPath = join39(executionPlanDir, PLAN_VIDEOS_META_RELATIVE_PATH);
17686
18002
  if (!existsSync25(videosPath)) {
17687
18003
  return hasExtractedFrames ? { mode: "full-source-pack", dependencies: null } : { mode: "exact-rendered-frames", dependencies: /* @__PURE__ */ new Map() };
17688
18004
  }
17689
- const chunksPath = join38(executionPlanDir, "meta", "chunks.json");
18005
+ const chunksPath = join39(executionPlanDir, "meta", "chunks.json");
17690
18006
  const videos = readJsonFile(videosPath, PLAN_VIDEOS_META_RELATIVE_PATH);
17691
18007
  const chunks = readJsonFile(chunksPath, "meta/chunks.json");
17692
18008
  const parsedVideos = parsePlanVideosJson2(videos);
@@ -17742,20 +18058,20 @@ function computeManifestHash(manifest) {
17742
18058
  function writeBlob(sourcePath, destinationPath) {
17743
18059
  if (existsSync25(destinationPath)) return;
17744
18060
  mkdirSync15(dirname15(destinationPath), { recursive: true });
17745
- const temporaryDir = mkdtempSync7(join38(dirname15(destinationPath), ".plan-v2-blob-"));
17746
- const temporaryPath = join38(temporaryDir, "blob");
18061
+ const temporaryDir = mkdtempSync7(join39(dirname15(destinationPath), ".plan-v2-blob-"));
18062
+ const temporaryPath = join39(temporaryDir, "blob");
17747
18063
  try {
17748
18064
  copyFileSync6(sourcePath, temporaryPath);
17749
18065
  renameWithRetry(temporaryPath, destinationPath);
17750
18066
  } finally {
17751
- rmSync14(temporaryDir, { recursive: true, force: true });
18067
+ rmSync15(temporaryDir, { recursive: true, force: true });
17752
18068
  }
17753
18069
  }
17754
18070
  function publishBlobFor(absolutePath, digests) {
17755
18071
  return {
17756
18072
  sourcePath: absolutePath,
17757
18073
  sha256: planFileSha256(absolutePath, digests),
17758
- sizeBytes: statSync9(absolutePath).size
18074
+ sizeBytes: statSync10(absolutePath).size
17759
18075
  };
17760
18076
  }
17761
18077
  async function putBlobs(publisher, blobs) {
@@ -17779,7 +18095,7 @@ async function putTasks(tasks) {
17779
18095
  if (failure) throw failure.reason;
17780
18096
  }
17781
18097
  function buildPlanV2Publication(executionPlanDir, digests) {
17782
- const executionPlanPath = join38(executionPlanDir, "plan.json");
18098
+ const executionPlanPath = join39(executionPlanDir, "plan.json");
17783
18099
  if (!existsSync25(executionPlanPath)) {
17784
18100
  throw new PlanV2IntegrityError(`execution plan is missing plan.json: ${executionPlanPath}`);
17785
18101
  }
@@ -17807,7 +18123,7 @@ function buildPlanV2Publication(executionPlanDir, digests) {
17807
18123
  }
17808
18124
  validateExtractionCacheCompleteSentinels(executionPlanDir);
17809
18125
  const videoDependencyPlan = buildVideoChunkDependencies(executionPlanDir, dimensions);
17810
- const encoder = readJsonFile(join38(executionPlanDir, "meta", "encoder.json"), "meta/encoder.json");
18126
+ const encoder = readJsonFile(join39(executionPlanDir, "meta", "encoder.json"), "meta/encoder.json");
17811
18127
  const files = listFiles(executionPlanDir);
17812
18128
  const chunkAudio = !isRecord3(encoder) || encoder.chunksCarryAudio !== true ? "none" : files.some((file) => chunkAudioSliceTarget(file.path) !== null) ? "sliced" : "whole";
17813
18129
  for (const file of files) {
@@ -17868,20 +18184,20 @@ function createPlanV2FromExecutionPlan(executionPlanDir, planV2Dir) {
17868
18184
  throw new PlanV2IntegrityError("a local plan v2 directory cannot reference remote files");
17869
18185
  }
17870
18186
  mkdirSync15(dirname15(planV2Dir), { recursive: true });
17871
- const tempDir = mkdtempSync7(join38(dirname15(planV2Dir), ".plan-v2-build-"));
18187
+ const tempDir = mkdtempSync7(join39(dirname15(planV2Dir), ".plan-v2-build-"));
17872
18188
  try {
17873
18189
  for (const blob of publication.blobs) {
17874
18190
  writeBlob(blob.sourcePath, planV2BlobPath(tempDir, blob.sha256));
17875
18191
  }
17876
18192
  writeFileSync11(
17877
- join38(tempDir, "plan.json"),
18193
+ join39(tempDir, "plan.json"),
17878
18194
  canonicalJsonStringify(publication.manifest),
17879
18195
  "utf-8"
17880
18196
  );
17881
18197
  renameWithRetry(tempDir, planV2Dir);
17882
18198
  return resultFromManifest(planV2Dir, publication.manifest);
17883
18199
  } catch (error) {
17884
- rmSync14(tempDir, { recursive: true, force: true });
18200
+ rmSync15(tempDir, { recursive: true, force: true });
17885
18201
  throw error;
17886
18202
  }
17887
18203
  }
@@ -17921,7 +18237,7 @@ async function publishPlanV2FromV1(executionPlanDir, publisher) {
17921
18237
  return publishPlanV2FromExecutionPlan(executionPlanDir, publisher);
17922
18238
  }
17923
18239
  async function planV2WithPublisher(projectDir, config, publisher, options = {}) {
17924
- const stagingRoot = mkdtempSync7(join38(options.stagingParentDir ?? tmpdir4(), ".execution-plan-"));
18240
+ const stagingRoot = mkdtempSync7(join39(options.stagingParentDir ?? tmpdir4(), ".execution-plan-"));
17925
18241
  const digests = /* @__PURE__ */ new Map();
17926
18242
  try {
17927
18243
  await buildLocalExecutionPlan(projectDir, config, stagingRoot, {
@@ -17932,7 +18248,7 @@ async function planV2WithPublisher(projectDir, config, publisher, options = {})
17932
18248
  // artifactTargets ships every compiled/ file to all chunks, so each is in the manifest.
17933
18249
  whileAudioMixes: () => putBlobs(
17934
18250
  publisher,
17935
- listFiles(join38(stagingRoot, "compiled")).map(
18251
+ listFiles(join39(stagingRoot, "compiled")).map(
17936
18252
  (file) => publishBlobFor(file.absolutePath, digests)
17937
18253
  )
17938
18254
  ),
@@ -17948,7 +18264,7 @@ async function planV2WithPublisher(projectDir, config, publisher, options = {})
17948
18264
  }
17949
18265
  throw error;
17950
18266
  } finally {
17951
- rmSync14(stagingRoot, { recursive: true, force: true });
18267
+ rmSync15(stagingRoot, { recursive: true, force: true });
17952
18268
  }
17953
18269
  }
17954
18270
  async function planV2(projectDir, config, planV2Dir) {
@@ -17964,7 +18280,7 @@ async function planV2(projectDir, config, planV2Dir) {
17964
18280
  function resultFromManifest(planV2Dir, manifest) {
17965
18281
  return {
17966
18282
  planDir: planV2Dir,
17967
- manifestPath: join38(planV2Dir, "plan.json"),
18283
+ manifestPath: join39(planV2Dir, "plan.json"),
17968
18284
  planProtocol: PLAN_PROTOCOL_V2,
17969
18285
  planHash: manifest.planHash,
17970
18286
  sourcePlanV1Hash: getPlanV2ExecutionPlanHash(manifest),
@@ -18100,7 +18416,7 @@ function parsePlanV2Manifest(value) {
18100
18416
  return parsed;
18101
18417
  }
18102
18418
  function readPlanV2Manifest(planV2Dir) {
18103
- const manifestPath = join38(planV2Dir, "plan.json");
18419
+ const manifestPath = join39(planV2Dir, "plan.json");
18104
18420
  if (!existsSync25(manifestPath)) {
18105
18421
  throw new PlanV2IntegrityError(`missing v2 manifest: ${manifestPath}`);
18106
18422
  }
@@ -18123,7 +18439,7 @@ function verifyBlob(planV2Dir, artifact) {
18123
18439
  if (!existsSync25(sourcePath)) {
18124
18440
  throw new PlanV2IntegrityError(`missing content-addressed artifact ${artifact.sha256}`);
18125
18441
  }
18126
- const stats = statSync9(sourcePath);
18442
+ const stats = statSync10(sourcePath);
18127
18443
  if (!stats.isFile() || stats.size !== artifact.sizeBytes) {
18128
18444
  throw new PlanV2IntegrityError(`artifact size mismatch for ${artifact.path}`);
18129
18445
  }
@@ -18146,16 +18462,16 @@ function materializePlanV2Target(planV2Dir, target, destinationDir, options = {}
18146
18462
  sourcePath: verifyBlob(planV2Dir, artifact)
18147
18463
  }));
18148
18464
  mkdirSync15(dirname15(destinationDir), { recursive: true });
18149
- const tempDir = mkdtempSync7(join38(dirname15(destinationDir), ".plan-v2-materialize-"));
18465
+ const tempDir = mkdtempSync7(join39(dirname15(destinationDir), ".plan-v2-materialize-"));
18150
18466
  try {
18151
18467
  for (const { artifact, sourcePath } of verified) {
18152
- const destinationPath = join38(tempDir, ...artifact.path.split("/"));
18468
+ const destinationPath = join39(tempDir, ...artifact.path.split("/"));
18153
18469
  mkdirSync15(dirname15(destinationPath), { recursive: true });
18154
18470
  copyFileSync6(sourcePath, destinationPath);
18155
18471
  }
18156
18472
  if (target.role === "chunk") materializeExtractedVideoDirectories(tempDir);
18157
18473
  writeFileSync11(
18158
- join38(tempDir, PLAN_V2_MATERIALIZATION_MARKER),
18474
+ join39(tempDir, PLAN_V2_MATERIALIZATION_MARKER),
18159
18475
  canonicalJsonStringify({
18160
18476
  manifest,
18161
18477
  target,
@@ -18165,7 +18481,7 @@ function materializePlanV2Target(planV2Dir, target, destinationDir, options = {}
18165
18481
  );
18166
18482
  renameWithRetry(tempDir, destinationDir);
18167
18483
  } catch (error) {
18168
- rmSync14(tempDir, { recursive: true, force: true });
18484
+ rmSync15(tempDir, { recursive: true, force: true });
18169
18485
  throw error;
18170
18486
  }
18171
18487
  return {
@@ -18178,7 +18494,7 @@ function materializePlanV2Target(planV2Dir, target, destinationDir, options = {}
18178
18494
  // Join the artifact's OWN name, not the current constant: a plan written
18179
18495
  // before the container change carries the legacy name, and materializing it
18180
18496
  // under the new one would point at a file that was never written.
18181
- audioPath: target.role === "assembler" ? audioArtifact ? join38(destinationDir, audioArtifact.path) : null : null
18497
+ audioPath: target.role === "assembler" ? audioArtifact ? join39(destinationDir, audioArtifact.path) : null : null
18182
18498
  };
18183
18499
  }
18184
18500
  function assertRemoteSources(remoteSources, artifacts) {
@@ -18197,7 +18513,7 @@ function validatePlanV2MaterializedTarget(planDir, expectedTarget) {
18197
18513
  return readValidatedPlanV2Materialization(planDir, expectedTarget)?.manifest ?? null;
18198
18514
  }
18199
18515
  function readValidatedPlanV2Materialization(planDir, expectedTarget) {
18200
- const markerPath = join38(planDir, PLAN_V2_MATERIALIZATION_MARKER);
18516
+ const markerPath = join39(planDir, PLAN_V2_MATERIALIZATION_MARKER);
18201
18517
  if (!existsSync25(markerPath)) return null;
18202
18518
  const marker = readJsonFile(markerPath, "materialization marker");
18203
18519
  if (!isRecord3(marker) || !isRecord3(marker.manifest) || !isRecord3(marker.target)) {
@@ -18215,8 +18531,8 @@ function readValidatedPlanV2Materialization(planDir, expectedTarget) {
18215
18531
  assertRemoteSources(remoteSources, required);
18216
18532
  for (const artifact of required) {
18217
18533
  if (Object.hasOwn(remoteSources, artifact.path)) continue;
18218
- const path = join38(planDir, ...artifact.path.split("/"));
18219
- if (!existsSync25(path) || statSync9(path).size !== artifact.sizeBytes) {
18534
+ const path = join39(planDir, ...artifact.path.split("/"));
18535
+ if (!existsSync25(path) || statSync10(path).size !== artifact.sizeBytes) {
18220
18536
  throw new PlanV2IntegrityError(
18221
18537
  `materialized artifact missing or truncated: ${artifact.path}`
18222
18538
  );
@@ -18229,9 +18545,9 @@ function readValidatedPlanV2Materialization(planDir, expectedTarget) {
18229
18545
  }
18230
18546
 
18231
18547
  // ../producer/src/services/distributed/planV2Execution.ts
18232
- import { mkdtempSync as mkdtempSync9, rmSync as rmSync17 } from "fs";
18548
+ import { mkdtempSync as mkdtempSync9, rmSync as rmSync18 } from "fs";
18233
18549
  import { tmpdir as tmpdir5 } from "os";
18234
- import { join as join41 } from "path";
18550
+ import { join as join42 } from "path";
18235
18551
 
18236
18552
  // ../producer/src/services/distributed/assemble.ts
18237
18553
  import {
@@ -18241,11 +18557,11 @@ import {
18241
18557
  mkdtempSync as mkdtempSync8,
18242
18558
  readFileSync as readFileSync13,
18243
18559
  readdirSync as readdirSync10,
18244
- rmSync as rmSync15,
18245
- statSync as statSync10,
18560
+ rmSync as rmSync16,
18561
+ statSync as statSync11,
18246
18562
  writeFileSync as writeFileSync12
18247
18563
  } from "fs";
18248
- import { dirname as dirname16, join as join39 } from "path";
18564
+ import { dirname as dirname16, join as join40 } from "path";
18249
18565
  function cfrRateControlArgs(locked) {
18250
18566
  const preset = getEncoderPreset(locked.quality ?? "standard", "mp4");
18251
18567
  if (locked.crf == null && locked.bitrate) {
@@ -18269,7 +18585,7 @@ async function assemble(planDir, chunkOutputs, audioPath, outputPath, options) {
18269
18585
  outputPath,
18270
18586
  durationMs: Date.now() - start,
18271
18587
  framesEncoded: plan2.totalFrames,
18272
- fileSize: statSync10(outputPath).size
18588
+ fileSize: statSync11(outputPath).size
18273
18589
  };
18274
18590
  }
18275
18591
  const format = plan2.dimensions.format;
@@ -18297,7 +18613,7 @@ async function assemble(planDir, chunkOutputs, audioPath, outputPath, options) {
18297
18613
  };
18298
18614
  try {
18299
18615
  const videoSources = cfrEncoder ? [await reencodeCfr(ctx, chunkPaths, cfrEncoder)] : chunkPaths;
18300
- const finalPath = join39(workDir, `output.${format}`);
18616
+ const finalPath = join40(workDir, `output.${format}`);
18301
18617
  const audio = audioPath !== null && existsSync26(audioPath) ? audioPath : null;
18302
18618
  await writeJoined(ctx, videoSources, audio, finalPath);
18303
18619
  renameWithRetry(finalPath, outputPath);
@@ -18308,7 +18624,7 @@ async function assemble(planDir, chunkOutputs, audioPath, outputPath, options) {
18308
18624
  });
18309
18625
  } finally {
18310
18626
  try {
18311
- rmSync15(workDir, { recursive: true, force: true });
18627
+ rmSync16(workDir, { recursive: true, force: true });
18312
18628
  } catch (err) {
18313
18629
  log.warn("[assemble] failed to remove work dir", {
18314
18630
  workDir,
@@ -18316,7 +18632,7 @@ async function assemble(planDir, chunkOutputs, audioPath, outputPath, options) {
18316
18632
  });
18317
18633
  }
18318
18634
  }
18319
- const fileSize = existsSync26(outputPath) ? statSync10(outputPath).size : 0;
18635
+ const fileSize = existsSync26(outputPath) ? statSync11(outputPath).size : 0;
18320
18636
  return {
18321
18637
  outputPath,
18322
18638
  durationMs: Date.now() - start,
@@ -18325,8 +18641,8 @@ async function assemble(planDir, chunkOutputs, audioPath, outputPath, options) {
18325
18641
  };
18326
18642
  }
18327
18643
  function readAssemblePlan(planDir, chunkPaths) {
18328
- const planJsonPath = join39(planDir, "plan.json");
18329
- const chunksJsonPath = join39(planDir, "meta", "chunks.json");
18644
+ const planJsonPath = join40(planDir, "plan.json");
18645
+ const chunksJsonPath = join40(planDir, "meta", "chunks.json");
18330
18646
  if (!existsSync26(planJsonPath)) {
18331
18647
  throw new Error(`[assemble] planDir missing plan.json: ${planJsonPath}`);
18332
18648
  }
@@ -18374,7 +18690,7 @@ function cfrEncodeArgs(inputArgs, encoder, fpsArg) {
18374
18690
  return args;
18375
18691
  }
18376
18692
  async function reencodeCfr(ctx, chunkPaths, encoder) {
18377
- const cfrOutputPath = join39(ctx.workDir, `cfr.${ctx.format}`);
18693
+ const cfrOutputPath = join40(ctx.workDir, `cfr.${ctx.format}`);
18378
18694
  const cfrArgs = cfrEncodeArgs(videoInputArgs(ctx, chunkPaths), encoder, ctx.fpsArg);
18379
18695
  appendRenderProvenanceArgs(cfrArgs, cfrOutputPath);
18380
18696
  cfrArgs.push("-y", cfrOutputPath);
@@ -18401,7 +18717,7 @@ async function writeJoined(ctx, videoSources, audioPath, finalPath) {
18401
18717
  );
18402
18718
  return;
18403
18719
  }
18404
- const paddedAudioPath = join39(ctx.workDir, "audio-padded.m4a");
18720
+ const paddedAudioPath = join40(ctx.workDir, "audio-padded.m4a");
18405
18721
  const padTrimResult = await ctx.timed(
18406
18722
  "audioMs",
18407
18723
  () => padOrTrimAudioToVideoFrameCount({
@@ -18441,7 +18757,7 @@ async function writeJoined(ctx, videoSources, audioPath, finalPath) {
18441
18757
  }
18442
18758
  }
18443
18759
  function concatDemuxerInput(chunkPaths, workDir, fpsArg) {
18444
- const listPath = join39(workDir, "concat-list.txt");
18760
+ const listPath = join40(workDir, "concat-list.txt");
18445
18761
  const body = chunkPaths.map((path) => `file '${path.replace(/'/g, "'\\''")}'`).join("\n");
18446
18762
  writeFileSync12(listPath, `${body}
18447
18763
  `, "utf-8");
@@ -18479,11 +18795,11 @@ function stitchesSeparateAudio(planDir) {
18479
18795
  return lockedAudio(planDir).separateAudio === true;
18480
18796
  }
18481
18797
  function planFormat(planDir) {
18482
- const plan2 = JSON.parse(readFileSync13(join39(planDir, "plan.json"), "utf-8"));
18798
+ const plan2 = JSON.parse(readFileSync13(join40(planDir, "plan.json"), "utf-8"));
18483
18799
  return plan2.dimensions.format;
18484
18800
  }
18485
18801
  function lockedAudio(planDir) {
18486
- const encoderJsonPath = join39(planDir, "meta", "encoder.json");
18802
+ const encoderJsonPath = join40(planDir, "meta", "encoder.json");
18487
18803
  if (!existsSync26(encoderJsonPath)) return {};
18488
18804
  return JSON.parse(readFileSync13(encoderJsonPath, "utf-8"));
18489
18805
  }
@@ -18493,7 +18809,7 @@ function readCfrEncoder(planDir, format) {
18493
18809
  `[assemble] cfr=true is only supported for format="mp4" (got "${format}"). Stream-copy paths for webm and mov already produce exact avg_frame_rate; cfr re-encode is not needed.`
18494
18810
  );
18495
18811
  }
18496
- const encoderJsonPath = join39(planDir, "meta", "encoder.json");
18812
+ const encoderJsonPath = join40(planDir, "meta", "encoder.json");
18497
18813
  if (!existsSync26(encoderJsonPath)) {
18498
18814
  throw new Error(`[assemble] planDir missing meta/encoder.json: ${encoderJsonPath}`);
18499
18815
  }
@@ -18506,11 +18822,11 @@ function readCfrEncoder(planDir, format) {
18506
18822
  return encoderJson;
18507
18823
  }
18508
18824
  function mergePngFrameDirs(chunkPaths, outputPath, totalFrames, audioPath, startTimeMs) {
18509
- if (existsSync26(outputPath)) rmSync15(outputPath, { recursive: true, force: true });
18825
+ if (existsSync26(outputPath)) rmSync16(outputPath, { recursive: true, force: true });
18510
18826
  mkdirSync16(outputPath, { recursive: true });
18511
18827
  let globalIdx = 0;
18512
18828
  for (const chunkDir of chunkPaths) {
18513
- if (!statSync10(chunkDir).isDirectory()) {
18829
+ if (!statSync11(chunkDir).isDirectory()) {
18514
18830
  throw new Error(
18515
18831
  `[assemble] png-sequence chunk must be a directory: ${chunkDir} (got a file)`
18516
18832
  );
@@ -18520,8 +18836,8 @@ function mergePngFrameDirs(chunkPaths, outputPath, totalFrames, audioPath, start
18520
18836
  throw new Error(`[assemble] png-sequence chunk has no frames: ${chunkDir}`);
18521
18837
  }
18522
18838
  for (const frame of frames) {
18523
- const dst = join39(outputPath, formatExportFrameName(globalIdx, "png"));
18524
- cpSync3(join39(chunkDir, frame), dst);
18839
+ const dst = join40(outputPath, formatExportFrameName(globalIdx, "png"));
18840
+ cpSync3(join40(chunkDir, frame), dst);
18525
18841
  globalIdx += 1;
18526
18842
  }
18527
18843
  }
@@ -18531,13 +18847,13 @@ function mergePngFrameDirs(chunkPaths, outputPath, totalFrames, audioPath, start
18531
18847
  );
18532
18848
  }
18533
18849
  if (audioPath !== null && existsSync26(audioPath)) {
18534
- const sidecar = join39(outputPath, MIXED_AUDIO_FILENAME);
18850
+ const sidecar = join40(outputPath, MIXED_AUDIO_FILENAME);
18535
18851
  cpSync3(audioPath, sidecar);
18536
18852
  }
18537
18853
  let fileSize = 0;
18538
18854
  for (const name of readdirSync10(outputPath)) {
18539
18855
  try {
18540
- fileSize += statSync10(join39(outputPath, name)).size;
18856
+ fileSize += statSync11(join40(outputPath, name)).size;
18541
18857
  } catch {
18542
18858
  }
18543
18859
  }
@@ -18551,9 +18867,9 @@ function mergePngFrameDirs(chunkPaths, outputPath, totalFrames, audioPath, start
18551
18867
 
18552
18868
  // ../producer/src/services/distributed/renderChunk.ts
18553
18869
  import { randomBytes } from "crypto";
18554
- import { existsSync as existsSync27, mkdirSync as mkdirSync17, readFileSync as readFileSync14, readdirSync as readdirSync11, rmSync as rmSync16, writeFileSync as writeFileSync13 } from "fs";
18870
+ import { existsSync as existsSync27, mkdirSync as mkdirSync17, readFileSync as readFileSync14, readdirSync as readdirSync11, rmSync as rmSync17, writeFileSync as writeFileSync13 } from "fs";
18555
18871
  import { cpus as cpus3 } from "os";
18556
- import { join as join40 } from "path";
18872
+ import { join as join41 } from "path";
18557
18873
  var LEGACY_DISTRIBUTED_VP9_CPU_USED = 2;
18558
18874
  function validatePlanVideosForChunk(value) {
18559
18875
  try {
@@ -18655,7 +18971,7 @@ function hashChunkOutput(outputPath, kind) {
18655
18971
  if (kind === "file") return sha256Hex(readFileSync14(outputPath));
18656
18972
  const entries = readdirSync11(outputPath).filter((name) => /\.(png|jpg|jpeg)$/i.test(name)).sort();
18657
18973
  const lines = entries.map(
18658
- (name) => `${name}\0${sha256Hex(readFileSync14(join40(outputPath, name)))}`
18974
+ (name) => `${name}\0${sha256Hex(readFileSync14(join41(outputPath, name)))}`
18659
18975
  );
18660
18976
  return sha256Hex(lines.join("\0"));
18661
18977
  }
@@ -18672,9 +18988,9 @@ function resolveLockedVp9CpuUsed(lockedEncoder) {
18672
18988
  async function renderChunk(planDir, chunkIndex, outputChunkPath, options) {
18673
18989
  const start = Date.now();
18674
18990
  const log = defaultLogger;
18675
- const planJsonPath = join40(planDir, "plan.json");
18676
- const encoderJsonPath = join40(planDir, "meta", "encoder.json");
18677
- const chunksJsonPath = join40(planDir, "meta", "chunks.json");
18991
+ const planJsonPath = join41(planDir, "plan.json");
18992
+ const encoderJsonPath = join41(planDir, "meta", "encoder.json");
18993
+ const chunksJsonPath = join41(planDir, "meta", "chunks.json");
18678
18994
  if (!existsSync27(planJsonPath)) {
18679
18995
  throw new RenderChunkValidationError(
18680
18996
  MISSING_PLAN_ARTIFACT,
@@ -18700,7 +19016,7 @@ async function renderChunk(planDir, chunkIndex, outputChunkPath, options) {
18700
19016
  }
18701
19017
  const encoder = JSON.parse(readFileSync14(encoderJsonPath, "utf-8"));
18702
19018
  const chunks = JSON.parse(readFileSync14(chunksJsonPath, "utf-8"));
18703
- const videosJsonPath = join40(planDir, PLAN_VIDEOS_META_RELATIVE_PATH);
19019
+ const videosJsonPath = join41(planDir, PLAN_VIDEOS_META_RELATIVE_PATH);
18704
19020
  let planVideos = null;
18705
19021
  if (existsSync27(videosJsonPath)) {
18706
19022
  try {
@@ -18732,7 +19048,7 @@ async function renderChunk(planDir, chunkIndex, outputChunkPath, options) {
18732
19048
  }
18733
19049
  const range = resolveChunkFrameRange(slice, chunkIndex, options?.frameRange);
18734
19050
  const framesInChunk = range.endFrame - range.startFrame;
18735
- const compiledDir = join40(planDir, "compiled");
19051
+ const compiledDir = join41(planDir, "compiled");
18736
19052
  if (!existsSync27(compiledDir)) {
18737
19053
  throw new RenderChunkValidationError(
18738
19054
  MISSING_PLAN_ARTIFACT,
@@ -18790,7 +19106,7 @@ async function renderChunk(planDir, chunkIndex, outputChunkPath, options) {
18790
19106
  };
18791
19107
  const workDir = `${outputChunkPath}.work.${process.pid}.${randomBytes(4).toString("hex")}`;
18792
19108
  mkdirSync17(workDir, { recursive: true });
18793
- const framesDir = join40(workDir, "captured-frames");
19109
+ const framesDir = join41(workDir, "captured-frames");
18794
19110
  mkdirSync17(framesDir, { recursive: true });
18795
19111
  const videoFramesDir = `${workDir}.video-frames`;
18796
19112
  const chunkFrameNumbers = Array.from({ length: framesInChunk }, (_, i) => range.startFrame + i);
@@ -18815,7 +19131,7 @@ async function renderChunk(planDir, chunkIndex, outputChunkPath, options) {
18815
19131
  dimensions: plan2.dimensions,
18816
19132
  encoder,
18817
19133
  videoCount: planVideos?.videos.length ?? 0,
18818
- html: readFileSync14(join40(compiledDir, "index.html"), "utf-8"),
19134
+ html: readFileSync14(join41(compiledDir, "index.html"), "utf-8"),
18819
19135
  // The plan ships a deferred source only to chunks that show it; don't wait on the rest.
18820
19136
  skipReadinessVideoIds: deferredVideos.filter(
18821
19137
  (video) => !shownFrames.get(video.videoId)?.size || remoteVideoIds.has(video.videoId)
@@ -18940,7 +19256,7 @@ async function renderChunk(planDir, chunkIndex, outputChunkPath, options) {
18940
19256
  if (isPngSequence) {
18941
19257
  if (!existsSync27(outputChunkPath)) mkdirSync17(outputChunkPath, { recursive: true });
18942
19258
  } else {
18943
- const outDir = join40(outputChunkPath, "..");
19259
+ const outDir = join41(outputChunkPath, "..");
18944
19260
  if (!existsSync27(outDir)) mkdirSync17(outDir, { recursive: true });
18945
19261
  }
18946
19262
  const encodeInput = {
@@ -19044,7 +19360,7 @@ async function renderChunk(planDir, chunkIndex, outputChunkPath, options) {
19044
19360
  return observedChunkCaptureMode(capturePerfs);
19045
19361
  },
19046
19362
  resetForScreenshotRetry: () => {
19047
- rmSync16(workDir, { recursive: true, force: true, maxRetries: 3, retryDelay: 100 });
19363
+ rmSync17(workDir, { recursive: true, force: true, maxRetries: 3, retryDelay: 100 });
19048
19364
  mkdirSync17(framesDir, { recursive: true });
19049
19365
  capturePerfs.length = 0;
19050
19366
  captureAttempts.length = 0;
@@ -19087,8 +19403,8 @@ async function renderChunk(planDir, chunkIndex, outputChunkPath, options) {
19087
19403
  fps: { num: plan2.dimensions.fpsNum, den: plan2.dimensions.fpsDen },
19088
19404
  timeoutMs: cfg.ffmpegProcessTimeout
19089
19405
  });
19090
- rmSync16(videoOnlyPath, { force: true });
19091
- rmSync16(audioScratchPath, { force: true });
19406
+ rmSync17(videoOnlyPath, { force: true });
19407
+ rmSync17(audioScratchPath, { force: true });
19092
19408
  }
19093
19409
  encodeStageMs = Date.now() - encodeStarted;
19094
19410
  } finally {
@@ -19136,8 +19452,8 @@ async function renderChunk(planDir, chunkIndex, outputChunkPath, options) {
19136
19452
  writeFileSync13(perfPath, `${JSON.stringify(perfPayload, null, 2)}
19137
19453
  `, "utf-8");
19138
19454
  try {
19139
- rmSync16(workDir, { recursive: true, force: true, maxRetries: 3, retryDelay: 100 });
19140
- rmSync16(videoFramesDir, { recursive: true, force: true, maxRetries: 3, retryDelay: 100 });
19455
+ rmSync17(workDir, { recursive: true, force: true, maxRetries: 3, retryDelay: 100 });
19456
+ rmSync17(videoFramesDir, { recursive: true, force: true, maxRetries: 3, retryDelay: 100 });
19141
19457
  } catch (err) {
19142
19458
  log.warn("[renderChunk] failed to remove work dir", {
19143
19459
  workDir,
@@ -19166,18 +19482,18 @@ async function renderChunk(planDir, chunkIndex, outputChunkPath, options) {
19166
19482
 
19167
19483
  // ../producer/src/services/distributed/planV2Execution.ts
19168
19484
  async function renderChunkV2(planV2Dir, chunkIndex, outputChunkPath, options) {
19169
- const workRoot = mkdtempSync9(join41(tmpdir5(), "hf-plan-v2-chunk-"));
19170
- const materializedPlanDir = join41(workRoot, "plan");
19485
+ const workRoot = mkdtempSync9(join42(tmpdir5(), "hf-plan-v2-chunk-"));
19486
+ const materializedPlanDir = join42(workRoot, "plan");
19171
19487
  try {
19172
19488
  materializePlanV2Target(planV2Dir, { role: "chunk", chunkIndex }, materializedPlanDir);
19173
19489
  return await renderChunk(materializedPlanDir, chunkIndex, outputChunkPath, options);
19174
19490
  } finally {
19175
- rmSync17(workRoot, { recursive: true, force: true });
19491
+ rmSync18(workRoot, { recursive: true, force: true });
19176
19492
  }
19177
19493
  }
19178
19494
  async function assembleV2(planV2Dir, chunkPaths, outputPath, options) {
19179
- const workRoot = mkdtempSync9(join41(tmpdir5(), "hf-plan-v2-assembler-"));
19180
- const materializedPlanDir = join41(workRoot, "plan");
19495
+ const workRoot = mkdtempSync9(join42(tmpdir5(), "hf-plan-v2-assembler-"));
19496
+ const materializedPlanDir = join42(workRoot, "plan");
19181
19497
  try {
19182
19498
  const materialized = materializePlanV2Target(
19183
19499
  planV2Dir,
@@ -19192,14 +19508,14 @@ async function assembleV2(planV2Dir, chunkPaths, outputPath, options) {
19192
19508
  options
19193
19509
  );
19194
19510
  } finally {
19195
- rmSync17(workRoot, { recursive: true, force: true });
19511
+ rmSync18(workRoot, { recursive: true, force: true });
19196
19512
  }
19197
19513
  }
19198
19514
 
19199
19515
  // ../producer/src/services/distributed/projectHash.ts
19200
- import { closeSync as closeSync8, openSync as openSync7, readdirSync as readdirSync12, readSync as readSync5, realpathSync as realpathSync2, statSync as statSync11 } from "fs";
19516
+ import { closeSync as closeSync7, openSync as openSync7, readdirSync as readdirSync12, readSync as readSync5, realpathSync as realpathSync2, statSync as statSync12 } from "fs";
19201
19517
  import { createHash as createHash7 } from "crypto";
19202
- import { join as join42 } from "path";
19518
+ import { join as join43 } from "path";
19203
19519
  var READ_CHUNK_BYTES = 256 * 1024;
19204
19520
 
19205
19521
  // ../producer/src/services/distributed/audioSidecar.ts