@hyperframes/producer 0.10.2 → 0.10.6

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.
@@ -380,7 +380,7 @@ import {
380
380
  getSystemTotalMb,
381
381
  LOW_MEMORY_TOTAL_MB_THRESHOLD,
382
382
  assertConfiguredFfmpegBinariesExist,
383
- resolveBrowserGpuMode,
383
+ resolveBrowserGpuMode as resolveBrowserGpuMode2,
384
384
  probedHardwareGpu,
385
385
  resolveHeadlessShellPath,
386
386
  compositionRequiresWebGpu as compositionRequiresWebGpu2,
@@ -388,7 +388,8 @@ import {
388
388
  explainDrawElementDisabled,
389
389
  chromeMajorCeiling,
390
390
  scaleProtocolTimeoutForComposition,
391
- classifyCaptureFailure as classifyCaptureFailure3,
391
+ captureMemoryRetryWorkers as captureMemoryRetryWorkers2,
392
+ classifyCaptureFailure as classifyCaptureFailure4,
392
393
  cloneCaptureWarning,
393
394
  isMemoryExhaustionError as isMemoryExhaustionError2,
394
395
  isTransientBrowserError as isTransientBrowserError2,
@@ -2625,8 +2626,7 @@ import {
2625
2626
  initializeSession as initializeSession2,
2626
2627
  prepareCaptureSessionForReuse as prepareCaptureSessionForReuse2,
2627
2628
  resolveDeVerifyMinDb as resolveDeVerifyMinDb2,
2628
- shouldDisableBrowserPoolForParallelWorker,
2629
- spawnStreamingEncoder as spawnStreamingEncoder2
2629
+ shouldDisableBrowserPoolForParallelWorker
2630
2630
  } from "@hyperframes/engine";
2631
2631
 
2632
2632
  // src/services/render/captureStageError.ts
@@ -2950,6 +2950,9 @@ function buildRenderPerfSummary(input) {
2950
2950
  tmpPeakBytes: input.tmpPeakBytes,
2951
2951
  captureCalibration: input.captureCalibration ? {
2952
2952
  sampledFrames: input.captureCalibration.samples.map((sample) => sample.frameIndex),
2953
+ sampleMs: input.captureCalibration.samples.map(
2954
+ (sample) => Math.round(sample.captureTimeMs)
2955
+ ),
2953
2956
  p95Ms: input.captureCalibration.estimate.p95Ms,
2954
2957
  multiplier: input.captureCalibration.estimate.multiplier,
2955
2958
  reasons: input.captureCalibration.estimate.reasons
@@ -2995,6 +2998,7 @@ function buildRenderPerfSummary(input) {
2995
2998
  // src/services/render/captureStageError.ts
2996
2999
  var CaptureStageError = class extends CaptureFailure {
2997
3000
  browserConsole;
3001
+ memoryRetryUsed = false;
2998
3002
  constructor(input) {
2999
3003
  const classified = classifyCaptureFailure(input.cause);
3000
3004
  super({
@@ -4582,6 +4586,8 @@ import {
4582
4586
  captureFrameToBuffer,
4583
4587
  captureFrameToBufferPipelined,
4584
4588
  captureFramesBatchPipelined,
4589
+ captureMemoryRetryWorkers,
4590
+ classifyCaptureFailure as classifyCaptureFailure2,
4585
4591
  closeCaptureSession,
4586
4592
  createCaptureSession,
4587
4593
  createFrameReorderBuffer,
@@ -4595,8 +4601,7 @@ import {
4595
4601
  recaptureDrawElementFrameForVerify,
4596
4602
  completeDeferredDrawElementInit,
4597
4603
  initializeSession,
4598
- prepareCaptureSessionForReuse,
4599
- spawnStreamingEncoder
4604
+ prepareCaptureSessionForReuse
4600
4605
  } from "@hyperframes/engine";
4601
4606
 
4602
4607
  // src/services/render/stallClock.ts
@@ -4618,6 +4623,17 @@ function createStallClock(now = () => Date.now()) {
4618
4623
  };
4619
4624
  }
4620
4625
 
4626
+ // src/services/render/stages/captureEncoder.ts
4627
+ import { spawnStreamingEncoder } from "@hyperframes/engine";
4628
+ function spawnCaptureEncoder(...[outputPath, options, signal, config]) {
4629
+ return spawnStreamingEncoder(
4630
+ outputPath,
4631
+ { ...options, belowNormalPriority: true },
4632
+ signal,
4633
+ config
4634
+ );
4635
+ }
4636
+
4621
4637
  // src/services/render/stages/captureStreamingStage.ts
4622
4638
  var DEFAULT_CAPTURE_STALL_MS = 6e4;
4623
4639
  var SESSION_INIT_STALL_MS = 3e5;
@@ -5017,7 +5033,7 @@ async function runCaptureStreamingStage(input) {
5017
5033
  let streamingEncoder = null;
5018
5034
  let streamingEncoderClosed = false;
5019
5035
  try {
5020
- streamingEncoder = await spawnStreamingEncoder(
5036
+ streamingEncoder = await spawnCaptureEncoder(
5021
5037
  videoOnlyPath,
5022
5038
  streamingEncoderOptions,
5023
5039
  abortSignal,
@@ -5061,6 +5077,7 @@ async function runCaptureStreamingStage(input) {
5061
5077
  let writtenFrames = 0;
5062
5078
  let resumeFrom = 0;
5063
5079
  let resumes = 0;
5080
+ let memoryRetryUsed = false;
5064
5081
  let workerResults;
5065
5082
  for (; ; ) {
5066
5083
  const parallelReorder = createFrameReorderBuffer(resumeFrom, totalFrames);
@@ -5192,6 +5209,25 @@ async function runCaptureStreamingStage(input) {
5192
5209
  resumes++;
5193
5210
  continue;
5194
5211
  }
5212
+ const stop = parallelDrainError ?? err;
5213
+ const memoryStop = abortSignal?.aborted !== true && captureLabel === "screenshot" && classifyCaptureFailure2(stop).kind === "memory_exhaustion";
5214
+ const fitWorkers = memoryStop && !memoryRetryUsed ? captureMemoryRetryWorkers(stop) : void 0;
5215
+ if (workerCount > 1 && fitWorkers !== void 0) {
5216
+ memoryRetryUsed = true;
5217
+ const nextWorkers = Math.min(fitWorkers, workerCount - 1);
5218
+ log.warn(
5219
+ "[Render] Capture stopped before memory ran out; resuming from the first unwritten frame with fewer workers.",
5220
+ { fromWorkers: workerCount, toWorkers: nextWorkers, resumeFrom: writtenFrames }
5221
+ );
5222
+ workerCount = nextWorkers;
5223
+ resumeFrom = writtenFrames;
5224
+ continue;
5225
+ }
5226
+ if (memoryStop && memoryRetryUsed) {
5227
+ const failure = poolFailure(stop, probeSession);
5228
+ if (failure instanceof CaptureStageError) failure.memoryRetryUsed = true;
5229
+ throw failure;
5230
+ }
5195
5231
  if (parallelDrainError) throw poolFailure(parallelDrainError, probeSession);
5196
5232
  if (stalled && abortSignal?.aborted !== true) {
5197
5233
  throw new ParallelCaptureStallError({
@@ -5522,7 +5558,7 @@ async function captureSegmentToEncoder(ctx, segment) {
5522
5558
  }
5523
5559
  }
5524
5560
  var DEFAULT_DEPS = {
5525
- spawnEncoder: spawnStreamingEncoder2,
5561
+ spawnEncoder: spawnCaptureEncoder,
5526
5562
  captureFrame: captureFrameToBuffer2,
5527
5563
  concat: concatVideoFiles,
5528
5564
  // Through the import binding, not captured: a value captured at module load
@@ -5907,10 +5943,13 @@ import { fpsToNumber as fpsToNumber4 } from "@hyperframes/core";
5907
5943
  import {
5908
5944
  calculateOptimalWorkers,
5909
5945
  captureFrameToBuffer as captureFrameToBuffer3,
5946
+ clearStaticDedupAnchor,
5910
5947
  closeCaptureSession as closeCaptureSession3,
5911
5948
  computeWorkerSizing,
5912
5949
  createCaptureSession as createCaptureSession3,
5913
- initializeSession as initializeSession3
5950
+ initializeSession as initializeSession3,
5951
+ readChromeCpuSeconds,
5952
+ resolveBrowserGpuMode
5914
5953
  } from "@hyperframes/engine";
5915
5954
  var CAPTURE_CALIBRATION_TARGET_MS = 600;
5916
5955
  var MAX_MEASURED_CAPTURE_COST_MULTIPLIER = 8;
@@ -5950,13 +5989,20 @@ function combineCaptureCostEstimates(staticCost, measuredCost) {
5950
5989
  multiplier: measuredCost.multiplier,
5951
5990
  reasons: [...measuredCost.reasons, ...staticCost.reasons],
5952
5991
  p95Ms: measuredCost.p95Ms,
5953
- medianMs: measuredCost.medianMs
5992
+ medianMs: measuredCost.medianMs,
5993
+ // A hint names work the samples can miss, such as a shader transition between two of them.
5994
+ coresPerWorker: staticCost.multiplier > 1 ? void 0 : measuredCost.coresPerWorker,
5995
+ browserRssMb: measuredCost.browserRssMb
5954
5996
  };
5955
5997
  }
5956
5998
  function buildHeapAdvisoryWarning(sizing, requestedWorkers) {
5957
5999
  if (requestedWorkers !== void 0 || !sizing.exceedsHeapAdvisory) return void 0;
5958
6000
  return `[Render] ${sizing.workers} capture workers may exceed this process's V8 heap (limit ${sizing.heapLimitMb}MB supports ~${sizing.heapBasedWorkers}). If the render dies with "JavaScript heap out of memory", raise the heap (NODE_OPTIONS=--max-old-space-size=8192) or pass --workers ${sizing.heapBasedWorkers}.`;
5959
6001
  }
6002
+ function coresToSizeBy(cost, protocolTimeout) {
6003
+ if (cost.browserRssMb === void 0) return void 0;
6004
+ return 2 * (cost.p95Ms ?? Infinity) < protocolTimeout ? cost.coresPerWorker : void 0;
6005
+ }
5960
6006
  function resolveRenderWorkerCount(totalFrames, requestedWorkers, cfg, compiled, log = defaultLogger, measuredCaptureCost, onSizing) {
5961
6007
  const reasonCodes = new Set(compiled.renderModeHints.reasons.map((r) => r.code));
5962
6008
  if (reasonCodes.has("htmlInCanvas")) {
@@ -5978,7 +6024,9 @@ function resolveRenderWorkerCount(totalFrames, requestedWorkers, cfg, compiled,
5978
6024
  );
5979
6025
  const sizing = computeWorkerSizing(totalFrames, requestedWorkers, {
5980
6026
  ...cfg,
5981
- captureCostMultiplier: captureCost.multiplier
6027
+ captureCostMultiplier: captureCost.multiplier,
6028
+ measuredCoresPerWorker: coresToSizeBy(captureCost, cfg.protocolTimeout),
6029
+ measuredBrowserRssMb: captureCost.browserRssMb
5982
6030
  });
5983
6031
  onSizing?.(sizing);
5984
6032
  const workerCount = sizing.workers;
@@ -6077,7 +6125,7 @@ async function measureCaptureCostFromSession(session, totalFrames, fps, log, fir
6077
6125
  }
6078
6126
  } finally {
6079
6127
  session.staticFrames = savedStaticFrames;
6080
- session.lastFrameBuffer = void 0;
6128
+ clearStaticDedupAnchor(session);
6081
6129
  }
6082
6130
  const estimate = estimateMeasuredCaptureCostMultiplier(samples);
6083
6131
  if (estimate.p95Ms !== void 0) {
@@ -6088,17 +6136,28 @@ async function measureCaptureCostFromSession(session, totalFrames, fps, log, fir
6088
6136
  samples
6089
6137
  };
6090
6138
  }
6139
+ function chromeCoresUsed(before, after, elapsedMs) {
6140
+ if (!before || !after || elapsedMs <= 0) return void 0;
6141
+ for (const pid of before.keys()) if (!after.has(pid)) return void 0;
6142
+ const total = (cpu) => [...cpu.values()].reduce((a, b) => a + b, 0);
6143
+ const cores = (total(after) - total(before)) / (elapsedMs / 1e3);
6144
+ return cores > 0 ? cores : void 0;
6145
+ }
6091
6146
  function logCaptureCalibrationResult(calibration, log) {
6092
6147
  if (calibration.estimate.multiplier > 1) {
6093
6148
  log.warn("[Render] Measured slow frame capture during auto-worker calibration.", {
6094
6149
  multiplier: calibration.estimate.multiplier,
6095
6150
  p95Ms: calibration.estimate.p95Ms,
6096
- sampledFrames: calibration.samples.map((sample) => sample.frameIndex)
6151
+ coresPerWorker: calibration.estimate.coresPerWorker,
6152
+ browserRssMb: calibration.estimate.browserRssMb,
6153
+ sampledFrames: calibration.samples.map((sample) => sample.frameIndex),
6154
+ sampleMs: calibration.samples.map((sample) => Math.round(sample.captureTimeMs))
6097
6155
  });
6098
6156
  } else {
6099
6157
  log.debug("[Render] Auto-worker calibration kept baseline capture cost.", {
6100
6158
  p95Ms: calibration.estimate.p95Ms,
6101
- sampledFrames: calibration.samples.map((sample) => sample.frameIndex)
6159
+ sampledFrames: calibration.samples.map((sample) => sample.frameIndex),
6160
+ sampleMs: calibration.samples.map((sample) => Math.round(sample.captureTimeMs))
6102
6161
  });
6103
6162
  }
6104
6163
  }
@@ -6154,6 +6213,12 @@ async function runCaptureCalibration(input) {
6154
6213
  }
6155
6214
  assertNotAborted();
6156
6215
  log.info("Calibration session ready, capturing test frames...");
6216
+ const readCpu = () => readChromeCpuSeconds(() => session.browser.target().createCDPSession()).catch(
6217
+ () => void 0
6218
+ );
6219
+ const softwareGpu = await resolveBrowserGpuMode(sessionCfg.browserGpuMode) === "software";
6220
+ const cpuBefore = softwareGpu ? await readCpu() : void 0;
6221
+ const startedAt = performance.now();
6157
6222
  const result = await measureCaptureCostFromSession(
6158
6223
  session,
6159
6224
  totalFrames,
@@ -6161,6 +6226,15 @@ async function runCaptureCalibration(input) {
6161
6226
  log,
6162
6227
  job.frameWindow?.startFrame
6163
6228
  );
6229
+ const elapsedMs = performance.now() - startedAt;
6230
+ const cpuAfter = cpuBefore && await readCpu();
6231
+ result.estimate.coresPerWorker = chromeCoresUsed(cpuBefore, cpuAfter, elapsedMs);
6232
+ if (result.estimate.coresPerWorker !== void 0) {
6233
+ const before = session.chromeMemory?.stats().samples ?? 0;
6234
+ await session.chromeMemory?.sampleOnce();
6235
+ const memory = session.chromeMemory?.stats();
6236
+ if (memory && memory.samples > before) result.estimate.browserRssMb = memory.rssLastMb;
6237
+ }
6164
6238
  logCaptureCalibrationResult(result, log);
6165
6239
  return result;
6166
6240
  };
@@ -13486,7 +13560,7 @@ async function mixAudioForDelivery(input, duration, pcmSourcePath, window2) {
13486
13560
  import { existsSync as existsSync18, readdirSync as readdirSync4, statfsSync as statfsSync2 } from "node:fs";
13487
13561
  import { join as join30 } from "node:path";
13488
13562
  import {
13489
- classifyCaptureFailure as classifyCaptureFailure2,
13563
+ classifyCaptureFailure as classifyCaptureFailure3,
13490
13564
  frameFileExtension,
13491
13565
  captureFrame,
13492
13566
  captureFrameToBufferPipelined as captureFrameToBufferPipelined2,
@@ -13793,7 +13867,7 @@ function resolveCaptureRange(frameRange, totalFrames) {
13793
13867
  return { rangeStart: frameRange?.startFrame ?? 0, rangeEnd: frameRange?.endFrame ?? totalFrames };
13794
13868
  }
13795
13869
  function planTransientResume(error, ctx) {
13796
- const failure = classifyCaptureFailure2(error, { signal: ctx.abortSignal });
13870
+ const failure = classifyCaptureFailure3(error, { signal: ctx.abortSignal });
13797
13871
  const missing = findMissingFrameRanges(ctx.rangeFrames, ctx.framesDir, ctx.frameExt);
13798
13872
  const [firstMissing] = missing;
13799
13873
  if (!firstMissing) return null;
@@ -13889,8 +13963,7 @@ import {
13889
13963
  cloneCaptureWarnings as cloneCaptureWarnings2,
13890
13964
  createCaptureSession as createCaptureSession7,
13891
13965
  initTransparentBackground as initTransparentBackground2,
13892
- initializeSession as initializeSession7,
13893
- spawnStreamingEncoder as spawnStreamingEncoder3
13966
+ initializeSession as initializeSession7
13894
13967
  } from "@hyperframes/engine";
13895
13968
  import { fpsToNumber as fpsToNumber7 } from "@hyperframes/core";
13896
13969
 
@@ -14681,7 +14754,7 @@ async function runCaptureHdrStage(input) {
14681
14754
  }))
14682
14755
  });
14683
14756
  }
14684
- hdrEncoder = await spawnStreamingEncoder3(
14757
+ hdrEncoder = await spawnCaptureEncoder(
14685
14758
  videoOnlyPath,
14686
14759
  {
14687
14760
  fps: job.config.fps,
@@ -14920,8 +14993,7 @@ import {
14920
14993
  formatFfmpegError,
14921
14994
  MIXED_AUDIO_FILENAME as MIXED_AUDIO_FILENAME2,
14922
14995
  resolveConfig,
14923
- runFfmpeg as runFfmpeg6,
14924
- spawnStreamingEncoder as spawnStreamingEncoder4
14996
+ runFfmpeg as runFfmpeg6
14925
14997
  } from "@hyperframes/engine";
14926
14998
  import {
14927
14999
  clearGifFramesBeforeNext,
@@ -15061,10 +15133,7 @@ function startEncodeProgress(job, stage, onProgress) {
15061
15133
  function resolveEngineConfig(input) {
15062
15134
  return input.engineConfig ?? input.job.config.producerConfig ?? resolveConfig();
15063
15135
  }
15064
- function overlapEncoderThreads(workerCount, cpuCount) {
15065
- return Math.max(1, Math.floor(cpuCount) - Math.floor(workerCount));
15066
- }
15067
- function videoEncoderOptions(input, engineCfg, softwareEncoderThreads) {
15136
+ function videoEncoderOptions(input, engineCfg) {
15068
15137
  const { job, preset } = input;
15069
15138
  return {
15070
15139
  fps: job.config.fps,
@@ -15084,8 +15153,7 @@ function videoEncoderOptions(input, engineCfg, softwareEncoderThreads) {
15084
15153
  // keyframes that survive `-f concat -c copy` at assemble time. In-process
15085
15154
  // renders leave both undefined → preserves the existing open-GOP output.
15086
15155
  lockGopForChunkConcat: input.lockGopForChunkConcat === true,
15087
- gopSize: input.gopSize,
15088
- softwareEncoderThreads
15156
+ gopSize: input.gopSize
15089
15157
  };
15090
15158
  }
15091
15159
  function canEncodeWhileCapturing(input, workerCount, cpuCount) {
@@ -15101,9 +15169,8 @@ async function readLandedFrame(workerPath, mergedPath) {
15101
15169
  }
15102
15170
  return readFile2(mergedPath);
15103
15171
  }
15104
- function encodeWhileCapturing(input, totalFrames, captureBudget) {
15172
+ function encodeWhileCapturing(input, totalFrames) {
15105
15173
  const engineCfg = resolveEngineConfig(input);
15106
- const softwareEncoderThreads = captureBudget ? overlapEncoderThreads(captureBudget.workerCount, captureBudget.cpuCount) : void 0;
15107
15174
  const stop = new AbortController();
15108
15175
  const signal = input.abortSignal ? AbortSignal.any([input.abortSignal, stop.signal]) : stop.signal;
15109
15176
  const landed = /* @__PURE__ */ new Map();
@@ -15116,10 +15183,10 @@ function encodeWhileCapturing(input, totalFrames, captureBudget) {
15116
15183
  };
15117
15184
  signal.addEventListener("abort", nudge, { once: true });
15118
15185
  let reportFed = null;
15119
- const encoder = spawnStreamingEncoder4(
15186
+ const encoder = spawnCaptureEncoder(
15120
15187
  input.videoOnlyPath,
15121
15188
  {
15122
- ...videoEncoderOptions(input, engineCfg, softwareEncoderThreads),
15189
+ ...videoEncoderOptions(input, engineCfg),
15123
15190
  imageFormat: "jpeg"
15124
15191
  },
15125
15192
  signal,
@@ -15500,8 +15567,14 @@ var RenderQualityError = class extends Error {
15500
15567
  );
15501
15568
  this.warnings = warnings;
15502
15569
  this.name = "RenderQualityError";
15570
+ const failed = warnings.filter((warning) => warning.code === "sub_timeline_script_failure");
15571
+ if (failed.length > 0 && failed.every((warning) => warning.details?.scriptThrew === true)) {
15572
+ this.code = "COMPOSITION_SCRIPT_FAILED";
15573
+ }
15503
15574
  }
15504
15575
  warnings;
15576
+ /** Set only when the composition's own script threw: rendering it again fails the same way. */
15577
+ code;
15505
15578
  };
15506
15579
  var MIN_CPUS_TO_CAPTURE_DURING_MIX = 4;
15507
15580
  function applyRenderWarningPolicy(job, captureWarnings, log = defaultLogger) {
@@ -15731,7 +15804,7 @@ function isRecoverableParallelCaptureError(error) {
15731
15804
  if (error instanceof RenderStageStalledError) return true;
15732
15805
  const message = normalizeErrorMessage(error);
15733
15806
  if (!message.includes("[Parallel] Capture failed")) return false;
15734
- const kind = classifyCaptureFailure3(error).kind;
15807
+ const kind = classifyCaptureFailure4(error).kind;
15735
15808
  return kind === "transient_browser" || kind === "protocol_timeout";
15736
15809
  }
15737
15810
  function describeMemoryExhaustion(error, ctx) {
@@ -15763,6 +15836,7 @@ async function executeDiskCaptureWithAdaptiveRetry(options) {
15763
15836
  let attempt = 0;
15764
15837
  let transientRetriesUsed = 0;
15765
15838
  let initializationRetriesUsed = 0;
15839
+ let memoryRetriesUsed = 0;
15766
15840
  let pendingTransientRetry = false;
15767
15841
  const rangeStart = options.frameRangeStart ?? 0;
15768
15842
  while (true) {
@@ -15862,7 +15936,7 @@ async function executeDiskCaptureWithAdaptiveRetry(options) {
15862
15936
  attempt++;
15863
15937
  } catch (caught) {
15864
15938
  const error = attemptSignal?.aborted && !options.abortSignal?.aborted ? attemptSignal.reason : caught;
15865
- const failure = classifyCaptureFailure3(error, { signal: options.abortSignal });
15939
+ const failure = classifyCaptureFailure4(error, { signal: options.abortSignal });
15866
15940
  if (failure.kind === "cancelled") {
15867
15941
  throw error;
15868
15942
  }
@@ -15912,6 +15986,24 @@ async function executeDiskCaptureWithAdaptiveRetry(options) {
15912
15986
  pendingTransientRetry = true;
15913
15987
  continue;
15914
15988
  }
15989
+ const fitWorkers = memoryRetriesUsed === 0 && failure.kind === "memory_exhaustion" ? captureMemoryRetryWorkers2(error) : void 0;
15990
+ if (options.allowRetry && currentWorkers > 1 && fitWorkers !== void 0) {
15991
+ memoryRetriesUsed++;
15992
+ const nextWorkers2 = Math.min(fitWorkers, currentWorkers - 1);
15993
+ options.log.warn(
15994
+ "[Render] Capture stopped before memory ran out; retrying missing frames with fewer workers.",
15995
+ {
15996
+ fromWorkers: currentWorkers,
15997
+ toWorkers: nextWorkers2,
15998
+ missingFrames: remainingCount,
15999
+ error: failure.message
16000
+ }
16001
+ );
16002
+ currentWorkers = nextWorkers2;
16003
+ missingRanges = remaining;
16004
+ attempt++;
16005
+ continue;
16006
+ }
15915
16007
  if (!madeProgress) {
15916
16008
  options.log.warn(
15917
16009
  "[Render] Capture attempt made no forward progress; composition is likely structurally broken, not retrying.",
@@ -17021,7 +17113,7 @@ async function executeRenderPipeline(input) {
17021
17113
  updateJobStatus(job, "rendering", "Checking browser GPU", 25, onProgress, {
17022
17114
  code: "start_browsers"
17023
17115
  });
17024
- let resolvedBrowserGpuMode = await resolveBrowserGpuMode(cfg.browserGpuMode, {
17116
+ let resolvedBrowserGpuMode = await resolveBrowserGpuMode2(cfg.browserGpuMode, {
17025
17117
  chromePath: resolveHeadlessShellPath(cfg),
17026
17118
  browserTimeout: cfg.browserTimeout
17027
17119
  });
@@ -18241,6 +18333,7 @@ async function executeRenderPipeline(input) {
18241
18333
  const isParallelStall = isParallelCaptureStallError(err);
18242
18334
  const isEncoderDeath = isRetryableEncoderDeath(err);
18243
18335
  const isCancellation = err instanceof RenderCancelledError || executionSignal.aborted === true;
18336
+ if (err instanceof CaptureStageError && err.memoryRetryUsed) throw err;
18244
18337
  if (!shouldRetryViaPinnedFallback({
18245
18338
  isVerifyError,
18246
18339
  isDeCaptureError,
@@ -18384,10 +18477,7 @@ async function executeRenderPipeline(input) {
18384
18477
  assertNotAborted,
18385
18478
  onProgress
18386
18479
  };
18387
- const overlap = !cfg.useDrawElement && workerSizing !== void 0 && canEncodeWhileCapturing(encodeInput, capturePlan.workerCount, cpuBudget()) ? encodeWhileCapturing(encodeInput, totalFrames, {
18388
- workerCount: capturePlan.workerCount,
18389
- cpuCount: cpuBudget()
18390
- }) : null;
18480
+ const overlap = !cfg.useDrawElement && workerSizing !== void 0 && canEncodeWhileCapturing(encodeInput, capturePlan.workerCount, cpuBudget()) ? encodeWhileCapturing(encodeInput, totalFrames) : null;
18391
18481
  const captureFrameStart = Date.now();
18392
18482
  const invokeDiskCapture = (diskPlan) => observeRenderStage(
18393
18483
  observability,
@@ -19509,7 +19599,8 @@ var SAFE_RENDER_ERROR_CODES = /* @__PURE__ */ new Set([
19509
19599
  "VARIABLES_INVALID",
19510
19600
  "OUTPUT_DIMENSIONS_MISMATCH",
19511
19601
  "COMPOSITION_TOO_LARGE",
19512
- "COMPILE_TIMEOUT"
19602
+ "COMPILE_TIMEOUT",
19603
+ "COMPOSITION_SCRIPT_FAILED"
19513
19604
  ]);
19514
19605
  function extractSafeRenderErrorCode(error) {
19515
19606
  if (typeof error !== "object" || error === null || !("code" in error)) return void 0;
@@ -19964,6 +20055,14 @@ function createSseProgressReporter(stream, requestId) {
19964
20055
  });
19965
20056
  };
19966
20057
  }
20058
+ function renderFailureLogFields(job, safeError) {
20059
+ const failedPhase = job.errorDetails?.observability?.failedPhase;
20060
+ const errorCode = safeError?.errorCode;
20061
+ return {
20062
+ ...failedPhase ? { failedPhase } : {},
20063
+ ...errorCode ? { errorCode } : {}
20064
+ };
20065
+ }
19967
20066
  async function writeRenderStreamFailure(input) {
19968
20067
  const { error, job, stream, requestId, startedAtMs, log } = input;
19969
20068
  if (error instanceof RenderCancelledError) {
@@ -19985,7 +20084,8 @@ async function writeRenderStreamFailure(input) {
19985
20084
  requestId,
19986
20085
  elapsedMs,
19987
20086
  error: errorMsg,
19988
- stage: job.currentStage
20087
+ stage: job.currentStage,
20088
+ ...renderFailureLogFields(job, safeError)
19989
20089
  });
19990
20090
  await stream.writeSSE({
19991
20091
  data: JSON.stringify({
@@ -20130,7 +20230,8 @@ function createRenderHandlers(options = {}) {
20130
20230
  requestId,
20131
20231
  durationMs,
20132
20232
  error: errorMsg,
20133
- stage: job.currentStage
20233
+ stage: job.currentStage,
20234
+ ...renderFailureLogFields(job, safeError)
20134
20235
  });
20135
20236
  return c.json(
20136
20237
  {
@@ -18,6 +18,9 @@ export interface CaptureCostEstimate {
18
18
  reasons: string[];
19
19
  p95Ms?: number;
20
20
  medianMs?: number;
21
+ coresPerWorker?: number;
22
+ /** The browser's memory after the samples, which a page can allocate on its first drawn frame. */
23
+ browserRssMb?: number;
21
24
  }
22
25
  export interface CaptureCalibrationSample {
23
26
  frameIndex: number;
@@ -74,6 +77,7 @@ firstFrame?: number): Promise<{
74
77
  estimate: CaptureCostEstimate;
75
78
  samples: CaptureCalibrationSample[];
76
79
  }>;
80
+ export declare function chromeCoresUsed(before: ReadonlyMap<number, number> | undefined, after: ReadonlyMap<number, number> | undefined, elapsedMs: number): number | undefined;
77
81
  export declare function logCaptureCalibrationResult(calibration: {
78
82
  estimate: CaptureCostEstimate;
79
83
  samples: CaptureCalibrationSample[];
@@ -2,6 +2,7 @@ import { CaptureFailure } from "@hyperframes/engine";
2
2
  import { EncoderInterruptedError } from "./encoderInterruption.js";
3
3
  export declare class CaptureStageError extends CaptureFailure {
4
4
  readonly browserConsole: string[];
5
+ memoryRetryUsed: boolean;
5
6
  constructor(input: {
6
7
  cause: unknown;
7
8
  browserConsole: string[];
@@ -0,0 +1,3 @@
1
+ import { spawnStreamingEncoder } from "@hyperframes/engine";
2
+ /** Starts an encoder that runs while frames are still being captured, one step below the capture's priority. */
3
+ export declare function spawnCaptureEncoder(...[outputPath, options, signal, config]: Parameters<typeof spawnStreamingEncoder>): ReturnType<typeof spawnStreamingEncoder>;
@@ -1,12 +1,13 @@
1
- import { captureFrameToBuffer, closeCaptureSession, concatVideoFiles, spawnStreamingEncoder, type BeforeCaptureHook, type CaptureOptions, type CapturePerfSummary, type CaptureSession, type EngineConfig } from "@hyperframes/engine";
1
+ import { captureFrameToBuffer, closeCaptureSession, concatVideoFiles, type BeforeCaptureHook, type CaptureOptions, type CapturePerfSummary, type CaptureSession, type EngineConfig } from "@hyperframes/engine";
2
2
  import type { FileServerHandle } from "../../fileServer.js";
3
3
  import type { ProducerLogger } from "../../../logger.js";
4
4
  import type { ProgressCallback, RenderJob } from "../../renderOrchestrator.js";
5
5
  import type { SdrSegmentedCapturePlan } from "../capturePlan.js";
6
6
  import type { SegmentVideoFrames } from "../segmentVideoFrames.js";
7
7
  import { type StreamingEncoderOptions } from "./captureStreamingStage.js";
8
+ import { spawnCaptureEncoder } from "./captureEncoder.js";
8
9
  export interface SegmentedStageDeps {
9
- spawnEncoder: typeof spawnStreamingEncoder;
10
+ spawnEncoder: typeof spawnCaptureEncoder;
10
11
  captureFrame: typeof captureFrameToBuffer;
11
12
  concat: typeof concatVideoFiles;
12
13
  closeSession: typeof closeCaptureSession;
@@ -38,10 +38,11 @@
38
38
  * Safe at runtime; a subsequent change will move the capture helpers
39
39
  * into a shared module so the stages can import without reaching back.
40
40
  */
41
- import { type BeforeCaptureHook, type CaptureOptions, type CapturePerfSummary, type CaptureSession, type EngineConfig, spawnStreamingEncoder } from "@hyperframes/engine";
41
+ import { type BeforeCaptureHook, type CaptureOptions, type CapturePerfSummary, type CaptureSession, type EngineConfig } from "@hyperframes/engine";
42
42
  import type { FileServerHandle } from "../../fileServer.js";
43
43
  import type { ProducerLogger } from "../../../logger.js";
44
44
  import type { ProgressCallback, RenderJob } from "../../renderOrchestrator.js";
45
+ import { spawnCaptureEncoder } from "./captureEncoder.js";
45
46
  import type { SdrStreamingCapturePlan } from "../capturePlan.js";
46
47
  export declare function resolveCaptureStallTimeoutMs(): number;
47
48
  export type StalledSession = {
@@ -72,7 +73,7 @@ export declare function createSessionInitBudget(input: {
72
73
  * passes it through so the stage doesn't have to reach back for the
73
74
  * preset's internal shape.
74
75
  */
75
- export type StreamingEncoderOptions = Parameters<typeof spawnStreamingEncoder>[1];
76
+ export type StreamingEncoderOptions = Parameters<typeof spawnCaptureEncoder>[1];
76
77
  export interface CaptureStreamingStageInput {
77
78
  fileServer: FileServerHandle;
78
79
  workDir: string;
@@ -91,7 +92,7 @@ export interface CaptureStreamingStageInput {
91
92
  probeSession: CaptureSession | null;
92
93
  /** For the spawn-failure log message context only. */
93
94
  outputFormat: string;
94
- /** Pre-built encoder options; passed straight to `spawnStreamingEncoder`. */
95
+ /** Pre-built encoder options; passed straight to `spawnCaptureEncoder`. */
95
96
  streamingEncoderOptions: StreamingEncoderOptions;
96
97
  /**
97
98
  * What the parallel workers capture with — "drawElement", "BeginFrame" or
@@ -32,7 +32,6 @@
32
32
  * stage's encode if it fails.
33
33
  */
34
34
  import { getEncoderPreset, type EngineConfig, type LandedFrame } from "@hyperframes/engine";
35
- import { type Fps } from "@hyperframes/core";
36
35
  import type { ProducerLogger } from "../../../logger.js";
37
36
  import type { ProgressCallback, RenderJob } from "../../renderOrchestrator.js";
38
37
  export interface EncodeStageInput {
@@ -105,27 +104,6 @@ export interface EncodeStageResult {
105
104
  /** Wall-clock ms for the encode (or png-copy) phase. */
106
105
  encodeMs: number;
107
106
  }
108
- export declare function overlapEncoderThreads(workerCount: number, cpuCount: number): number;
109
- export declare function videoEncoderOptions(input: VideoEncodeInput, engineCfg: Pick<EngineConfig, "vp9CpuUsed">, softwareEncoderThreads?: number): {
110
- fps: Fps;
111
- width: number;
112
- height: number;
113
- codec: "h264" | "vp9" | "h265" | "prores";
114
- preset: string;
115
- quality: number;
116
- bitrate: string | undefined;
117
- maxBitrate: string | undefined;
118
- bufferSize: string | undefined;
119
- pixelFormat: string;
120
- vp9CpuUsed: number;
121
- useGpu: boolean | undefined;
122
- hdr: {
123
- transfer: import("@hyperframes/engine").HdrTransfer;
124
- } | undefined;
125
- lockGopForChunkConcat: boolean;
126
- gopSize: number | undefined;
127
- softwareEncoderThreads: number | undefined;
128
- };
129
107
  /**
130
108
  * h264 from JPEG only, software or GPU: the streaming encoder then runs the disk encoder's
131
109
  * arguments. Needs a core the capture workers leave free.
@@ -145,8 +123,5 @@ export interface EncodeWhileCapturing {
145
123
  * Feeds frames 0, 1, 2… to the encoder as each lands; capture never waits on it.
146
124
  * On failure `finish` re-runs `runEncodeStage` on the same frames.
147
125
  */
148
- export declare function encodeWhileCapturing(input: VideoEncodeInput, totalFrames: number, captureBudget?: {
149
- workerCount: number;
150
- cpuCount: number;
151
- }): EncodeWhileCapturing;
126
+ export declare function encodeWhileCapturing(input: VideoEncodeInput, totalFrames: number): EncodeWhileCapturing;
152
127
  export declare function runEncodeStage(input: EncodeStageInput): Promise<EncodeStageResult>;
@@ -223,6 +223,7 @@ export interface RenderPerfSummary {
223
223
  capturePeakMs?: number;
224
224
  captureCalibration?: {
225
225
  sampledFrames: number[];
226
+ sampleMs?: number[];
226
227
  p95Ms?: number;
227
228
  multiplier: number;
228
229
  reasons: string[];
@@ -485,6 +486,8 @@ export interface RenderJob extends Partial<ReferenceBackgroundResult> {
485
486
  export type ProgressCallback = (job: RenderJob, message: string) => void | Promise<void>;
486
487
  export declare class RenderQualityError extends Error {
487
488
  readonly warnings: readonly RenderWarning[];
489
+ /** Set only when the composition's own script threw: rendering it again fails the same way. */
490
+ readonly code?: "COMPOSITION_SCRIPT_FAILED";
488
491
  constructor(warnings: readonly RenderWarning[]);
489
492
  }
490
493
  export declare function applyRenderWarningPolicy(job: RenderJob, captureWarnings: readonly CaptureWarning[], log?: ProducerLogger): void;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hyperframes/producer",
3
- "version": "0.10.2",
3
+ "version": "0.10.6",
4
4
  "description": "HTML-to-video rendering engine using Chrome's BeginFrame API",
5
5
  "repository": {
6
6
  "type": "git",
@@ -35,12 +35,12 @@
35
35
  "postcss": "^8.4.0",
36
36
  "puppeteer": "~25.13.0",
37
37
  "puppeteer-core": "^25.13.0",
38
- "@hyperframes/lint": "0.10.2",
39
- "@hyperframes/engine": "0.10.2",
40
- "@hyperframes/share": "0.10.2",
41
- "@hyperframes/studio-server": "0.10.2",
42
- "@hyperframes/parsers": "0.10.2",
43
- "@hyperframes/core": "0.10.2"
38
+ "@hyperframes/engine": "0.10.6",
39
+ "@hyperframes/parsers": "0.10.6",
40
+ "@hyperframes/studio-server": "0.10.6",
41
+ "@hyperframes/share": "0.10.6",
42
+ "@hyperframes/lint": "0.10.6",
43
+ "@hyperframes/core": "0.10.6"
44
44
  },
45
45
  "devDependencies": {
46
46
  "@types/node": "^25.0.10",
@@ -49,7 +49,7 @@
49
49
  "tsx": "^4.21.0",
50
50
  "typescript": "^5.7.2",
51
51
  "vitest": "^4.1.12",
52
- "@hyperframes/aws-lambda": "0.10.2"
52
+ "@hyperframes/aws-lambda": "0.10.6"
53
53
  },
54
54
  "engines": {
55
55
  "node": ">=22.19.0"