@hyperframes/producer 0.9.31 → 0.9.32

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.
@@ -2,7 +2,7 @@
2
2
 
3
3
  // src/server.ts
4
4
  import {
5
- existsSync as existsSync25,
5
+ existsSync as existsSync26,
6
6
  mkdirSync as mkdirSync13,
7
7
  statSync as statSync11,
8
8
  mkdtempSync,
@@ -10,7 +10,7 @@ import {
10
10
  rmSync as rmSync13,
11
11
  createReadStream as createReadStream3
12
12
  } from "node:fs";
13
- import { resolve as resolve10, dirname as dirname15, join as join35 } from "node:path";
13
+ import { resolve as resolve10, dirname as dirname16, join as join36 } from "node:path";
14
14
  import { tmpdir as tmpdir3 } from "node:os";
15
15
  import { parseArgs } from "node:util";
16
16
  import crypto from "node:crypto";
@@ -994,6 +994,33 @@ function resolveDeliveryEncoderOptions(config) {
994
994
  return { maxBitrate, bufferSize, ...gop };
995
995
  }
996
996
 
997
+ // src/services/render/chromaSubsampling.ts
998
+ function validateChromaSubsamplingConfig(config) {
999
+ if (config.chromaSubsampling !== "444") return;
1000
+ const format = config.format ?? "mp4";
1001
+ if (format !== "mp4") {
1002
+ throw new Error(
1003
+ `[Render] chromaSubsampling "444" supports format "mp4" only (got "${format}"). WebM, MOV and GIF use their own pixel formats, and HLS targets broad playback. Use --format mp4, or drop --chroma-subsampling 444.`
1004
+ );
1005
+ }
1006
+ if (config.hdrMode === "force-hdr") {
1007
+ throw new Error(
1008
+ `[Render] chromaSubsampling "444" is SDR only; HDR output stays 10-bit 4:2:0 H.265. Drop --hdr, or drop --chroma-subsampling 444.`
1009
+ );
1010
+ }
1011
+ if (config.useGpu === true) {
1012
+ throw new Error(
1013
+ `[Render] chromaSubsampling "444" requires the software encoder (libx264); GPU encoders do not reliably support 4:4:4. Re-run without --gpu.`
1014
+ );
1015
+ }
1016
+ }
1017
+ function assertChromaSubsamplingSdr(config, hasHdrContent) {
1018
+ if (config.chromaSubsampling !== "444" || !hasHdrContent) return;
1019
+ throw new Error(
1020
+ `[Render] chromaSubsampling "444" is SDR only, but this composition has HDR sources. Re-run with --sdr (hdrMode "force-sdr"), or drop --chroma-subsampling 444.`
1021
+ );
1022
+ }
1023
+
997
1024
  // src/services/render/shared.ts
998
1025
  import {
999
1026
  copyFileSync,
@@ -1009,6 +1036,9 @@ import {
1009
1036
  CANVAS_DIMENSIONS,
1010
1037
  checkOutputResolutionCompatibility
1011
1038
  } from "@hyperframes/core";
1039
+ import {
1040
+ mediaIdPathSegment
1041
+ } from "@hyperframes/engine";
1012
1042
 
1013
1043
  // src/utils/paths.ts
1014
1044
  import {
@@ -1103,6 +1133,10 @@ function writeCompiledArtifacts(compiled, workDir, includeSummary) {
1103
1133
  writeFileSync(join3(compileDir, "index.html"), compiled.html, "utf-8");
1104
1134
  for (const [srcPath, html] of compiled.subCompositions) {
1105
1135
  const outPath = join3(compileDir, srcPath);
1136
+ if (!isPathInside2(outPath, compileDir)) {
1137
+ console.warn(`[Render] Skipping sub-composition with unsafe path: ${srcPath}`);
1138
+ continue;
1139
+ }
1106
1140
  mkdirSync(dirname2(outPath), { recursive: true });
1107
1141
  writeFileSync(outPath, html, "utf-8");
1108
1142
  }
@@ -1364,7 +1398,7 @@ function materializeExtractedFramesForCompiledDir(extracted, compiledDir, option
1364
1398
  for (const ext of extracted) {
1365
1399
  const resolvedOut = pathModule.resolve(ext.outputDir);
1366
1400
  if (isPathInside2(resolvedOut, resolvedCompiledDir, { pathModule })) continue;
1367
- const linkPath = pathModule.join(compiledFrameRoot, ext.videoId);
1401
+ const linkPath = pathModule.join(compiledFrameRoot, mediaIdPathSegment(ext.videoId));
1368
1402
  if (!fileSystem.existsSync(linkPath)) {
1369
1403
  fileSystem.mkdirSync(pathModule.dirname(linkPath), { recursive: true });
1370
1404
  stageExtractedFrameDir(
@@ -5438,6 +5472,7 @@ import { dirname as dirname5, join as join11 } from "node:path";
5438
5472
  import {
5439
5473
  createFrameLookupTable,
5440
5474
  extractVideoFramesRange,
5475
+ mediaIdPathSegment as mediaIdPathSegment2,
5441
5476
  runVideoExtractionWithRetry
5442
5477
  } from "@hyperframes/engine";
5443
5478
  function contiguousRuns(sortedIndexes) {
@@ -5478,7 +5513,7 @@ async function extractDeferredFrames(input) {
5478
5513
  const shown = shownDeferredFrameIndexes(input, input.frames, input.fps);
5479
5514
  return Promise.all(
5480
5515
  deferred.map(async (video) => {
5481
- const outputDir = join11(input.outputRoot, video.videoId);
5516
+ const outputDir = join11(input.outputRoot, mediaIdPathSegment2(video.videoId));
5482
5517
  const indexes = [...shown.get(video.videoId) ?? []].sort((a, b) => a - b);
5483
5518
  if (indexes.length === 0) {
5484
5519
  return { ...video, outputDir, framePaths: /* @__PURE__ */ new Map(), ownedByLookup: false };
@@ -9124,6 +9159,14 @@ function resolveEntryHtmlPath(input) {
9124
9159
  log.info("Extracted standalone entry from index.html host context", { entryFile });
9125
9160
  return wrapperPath;
9126
9161
  }
9162
+ function applyChroma444Gate(cfg, chromaSubsampling, gate, log) {
9163
+ if (!cfg.useDrawElement || chromaSubsampling !== "444") return gate;
9164
+ cfg.useDrawElement = false;
9165
+ log.info(
9166
+ "[Render] Fast capture: chromaSubsampling 444 captures lossless PNG frames, so disabling drawElementImage for this render. Capture uses the platform's baseline route."
9167
+ );
9168
+ return "chroma_444";
9169
+ }
9127
9170
  async function runCompileStage(input) {
9128
9171
  const {
9129
9172
  projectDir,
@@ -9175,6 +9218,7 @@ async function runCompileStage(input) {
9175
9218
  "[Render] Fast capture: composition uses shader transitions, so disabling drawElementImage so page-side compositing stays available."
9176
9219
  );
9177
9220
  }
9221
+ deCompileGate = applyChroma444Gate(cfg, job.config.chromaSubsampling, deCompileGate, log);
9178
9222
  if (!cfg.useDrawElement && cfg.pageSideCompositingAutoDisabled) {
9179
9223
  cfg.enablePageSideCompositing = true;
9180
9224
  cfg.pageSideCompositingAutoDisabled = false;
@@ -9286,11 +9330,19 @@ function isActionableProbeFailure(line) {
9286
9330
 
9287
9331
  // src/services/render/captureImageFormat.ts
9288
9332
  function resolveCaptureImageFormat(input) {
9289
- return input.needsAlpha || input.motionBlur ? "png" : "jpeg";
9333
+ return input.needsAlpha || input.motionBlur || input.chromaSubsampling === "444" ? "png" : "jpeg";
9290
9334
  }
9291
9335
  function resolveCaptureJpegQuality(quality) {
9292
9336
  return quality === "draft" ? 80 : 100;
9293
9337
  }
9338
+ function resolveCaptureSurface(input, quality) {
9339
+ const format = resolveCaptureImageFormat(input);
9340
+ return {
9341
+ format,
9342
+ quality: format === "png" ? void 0 : resolveCaptureJpegQuality(quality),
9343
+ transparent: input.needsAlpha
9344
+ };
9345
+ }
9294
9346
 
9295
9347
  // src/services/render/stages/probeStage.ts
9296
9348
  var FRAME_BOUNDARY_EPSILON = 1e-3;
@@ -9467,15 +9519,15 @@ async function runProbeStage(input) {
9467
9519
  });
9468
9520
  assertNotAborted();
9469
9521
  const motionBlur = job.config.motionBlur;
9470
- const captureFormat = resolveCaptureImageFormat({ needsAlpha, motionBlur });
9471
9522
  const captureOpts = {
9472
9523
  recordReferenceBackground: input.recordReferenceBackground,
9473
9524
  width,
9474
9525
  height,
9475
9526
  fps: job.config.fps,
9476
- format: captureFormat,
9477
- transparent: needsAlpha,
9478
- quality: captureFormat === "png" ? void 0 : resolveCaptureJpegQuality(job.config.quality),
9527
+ ...resolveCaptureSurface(
9528
+ { needsAlpha, motionBlur, chromaSubsampling: job.config.chromaSubsampling },
9529
+ job.config.quality
9530
+ ),
9479
9531
  variables: job.config.variables,
9480
9532
  deviceScaleFactor,
9481
9533
  motionBlur,
@@ -13352,13 +13404,20 @@ function resetCaptureAttemptProgress(job) {
13352
13404
  job.framesRendered = 0;
13353
13405
  }
13354
13406
  var FIRST_FRAME_STALL_MS = 3e5;
13407
+ var FIRST_FRAME_STARTUP_FACTOR = 2;
13408
+ var FIRST_FRAME_STALL_CEILING_MS = 9e5;
13355
13409
  var TAIL_STALL_MS = FIRST_FRAME_STALL_MS;
13356
- function frameStallRule(job, totalFrames) {
13410
+ function firstFrameWindowMs(probeStartupMs) {
13411
+ const fromStartup = (probeStartupMs ?? 0) * FIRST_FRAME_STARTUP_FACTOR;
13412
+ if (!Number.isFinite(fromStartup)) return FIRST_FRAME_STALL_MS;
13413
+ return Math.max(FIRST_FRAME_STALL_MS, Math.min(FIRST_FRAME_STALL_CEILING_MS, fromStartup));
13414
+ }
13415
+ function frameStallRule(job, totalFrames, probeStartupMs) {
13357
13416
  const noProgressMs = resolveCaptureStallTimeoutMs();
13358
13417
  return {
13359
13418
  progress: () => job.framesRendered ?? 0,
13360
13419
  noProgressMs,
13361
- firstProgressMs: Math.max(FIRST_FRAME_STALL_MS, noProgressMs),
13420
+ firstProgressMs: Math.max(firstFrameWindowMs(probeStartupMs), noProgressMs),
13362
13421
  complete: () => (job.framesRendered ?? 0) >= totalFrames,
13363
13422
  tailMs: Math.max(TAIL_STALL_MS, noProgressMs),
13364
13423
  detail: () => describeWorkerPhases(job),
@@ -14050,6 +14109,7 @@ function resolveRenderDebugDir() {
14050
14109
  async function executeRenderJob(job, projectDir, outputPath, progressSink, abortSignal, assertRenderActive) {
14051
14110
  validateHlsRenderConfig(job.config);
14052
14111
  validateDeliveryEncoderConfig(job.config);
14112
+ validateChromaSubsamplingConfig(job.config);
14053
14113
  const debugDir = resolveRenderDebugDir();
14054
14114
  const outputDir = dirname13(outputPath);
14055
14115
  if (!existsSync22(outputDir)) mkdirSync12(outputDir, { recursive: true });
@@ -14587,18 +14647,28 @@ async function executeRenderPipeline(input) {
14587
14647
  forceScreenshot: captureForceScreenshot
14588
14648
  });
14589
14649
  const videoCaptureBeyondViewport = resolveVideoCaptureBeyondViewport(composition.videos.length);
14590
- const captureImageFormat = resolveCaptureImageFormat({
14591
- needsAlpha,
14592
- motionBlur: job.config.motionBlur
14593
- });
14650
+ const captureSurface = resolveCaptureSurface(
14651
+ {
14652
+ needsAlpha,
14653
+ motionBlur: job.config.motionBlur,
14654
+ chromaSubsampling: job.config.chromaSubsampling
14655
+ },
14656
+ job.config.quality
14657
+ );
14658
+ if (job.config.chromaSubsampling === "444") {
14659
+ log.info("[Render] Capture: png (chromaSubsampling 444, lossless)");
14660
+ }
14594
14661
  const captureOptions = {
14595
14662
  width,
14596
14663
  height,
14597
14664
  fps: job.config.fps,
14598
- format: videoLayer ? "png" : captureImageFormat,
14599
- transparent: needsAlpha || videoLayer !== void 0,
14600
- ...videoLayer ? { hiddenElementIds: [videoLayer.videoId] } : {},
14601
- quality: captureImageFormat === "png" ? void 0 : resolveCaptureJpegQuality(job.config.quality),
14665
+ ...captureSurface,
14666
+ ...videoLayer ? {
14667
+ format: "png",
14668
+ quality: void 0,
14669
+ transparent: true,
14670
+ hiddenElementIds: [videoLayer.videoId]
14671
+ } : {},
14602
14672
  variables: job.config.variables,
14603
14673
  deviceScaleFactor,
14604
14674
  motionBlur: job.config.motionBlur,
@@ -14705,6 +14775,7 @@ async function executeRenderPipeline(input) {
14705
14775
  );
14706
14776
  const nativeHdrIds = /* @__PURE__ */ new Set([...nativeHdrVideoIds, ...nativeHdrImageIds]);
14707
14777
  const hasHdrContent = Boolean(effectiveHdr && nativeHdrIds.size > 0);
14778
+ assertChromaSubsamplingSdr(job.config, hasHdrContent);
14708
14779
  if (hasHdrContent) assertOutputScaleSupported(deviceScaleFactor, "hdr_layered");
14709
14780
  routePageMotionBlur = pageMotionBlurForRoute({ hasHdrContent, useLayeredComposite: false });
14710
14781
  const deSingleMinFrames = resolveDeSingleMinFrames(process.env);
@@ -15287,7 +15358,9 @@ async function executeRenderPipeline(input) {
15287
15358
  usePageSideCompositing: capturePlan.usePageSideCompositing,
15288
15359
  hasHdrContent: capturePlan.hasHdrContent,
15289
15360
  hasShaderTransitions: compiled.hasShaderTransitions,
15290
- isPngSequence
15361
+ isPngSequence,
15362
+ captureImageFormat: captureOptions.format ?? "jpeg",
15363
+ chromaSubsampling: job.config.chromaSubsampling ?? "420"
15291
15364
  });
15292
15365
  const encoderHdr = hasHdrContent ? effectiveHdr : void 0;
15293
15366
  const presetFormat = outputFormat === "webm" || outputFormat === "mov" ? outputFormat : "mp4";
@@ -15295,7 +15368,8 @@ async function executeRenderPipeline(input) {
15295
15368
  job.config.quality,
15296
15369
  presetFormat,
15297
15370
  encoderHdr,
15298
- job.config.proresProfile
15371
+ job.config.proresProfile,
15372
+ job.config.chromaSubsampling
15299
15373
  );
15300
15374
  if (job.config.crf != null && job.config.videoBitrate) {
15301
15375
  log.warn(
@@ -15377,7 +15451,7 @@ async function executeRenderPipeline(input) {
15377
15451
  onProgress
15378
15452
  });
15379
15453
  },
15380
- { stall: frameStallRule(job, totalFrames) }
15454
+ { stall: frameStallRule(job, totalFrames, perfStages.browserProbeMs) }
15381
15455
  );
15382
15456
  lastBrowserConsole = hdrRes.lastBrowserConsole;
15383
15457
  layeredCaptureWarnings.push(...hdrRes.warnings);
@@ -15829,7 +15903,7 @@ async function executeRenderPipeline(input) {
15829
15903
  interleaveFrames: overlap !== null,
15830
15904
  openAttempt
15831
15905
  }),
15832
- { stall: frameStallRule(job, totalFrames) }
15906
+ { stall: frameStallRule(job, totalFrames, perfStages.browserProbeMs) }
15833
15907
  );
15834
15908
  let captureRes;
15835
15909
  try {
@@ -16392,7 +16466,7 @@ import {
16392
16466
  createReferenceBackgroundRecorder as createReferenceBackgroundRecorder2
16393
16467
  } from "@hyperframes/engine";
16394
16468
  import { audioFailureDiagnostics as audioFailureDiagnostics3 } from "@hyperframes/engine";
16395
- import { extname as extname4, isAbsolute as isAbsolute4, join as join34, relative as relative4, sep as sep4 } from "node:path";
16469
+ import { extname as extname4, isAbsolute as isAbsolute4, join as join35, relative as relative4, sep as sep4 } from "node:path";
16396
16470
  import {
16397
16471
  fpsToNumber as fpsToNumber9,
16398
16472
  HF_COLOR_GRADING_ATTR as HF_COLOR_GRADING_ATTR2
@@ -16418,11 +16492,15 @@ import {
16418
16492
  // src/services/distributed/chunkFrames.ts
16419
16493
  import {
16420
16494
  compositionRequiresWebGpu as compositionRequiresWebGpu3,
16421
- createVideoFrameInjector as createVideoFrameInjector3
16495
+ createVideoFrameInjector as createVideoFrameInjector3,
16496
+ mediaIdPathSegment as mediaIdPathSegment3
16422
16497
  } from "@hyperframes/engine";
16423
16498
 
16424
16499
  // src/services/distributed/shared.ts
16425
16500
  import { execFile as execFileCallback } from "node:child_process";
16501
+ import { dirname as dirname15, join as join34 } from "node:path";
16502
+ import { existsSync as existsSync25, readFileSync as readFileSync11 } from "node:fs";
16503
+ import { fileURLToPath as fileURLToPath6 } from "node:url";
16426
16504
  import { promisify as promisify2 } from "node:util";
16427
16505
  import {
16428
16506
  getFfmpegBinary,
@@ -16430,6 +16508,30 @@ import {
16430
16508
  } from "@hyperframes/engine";
16431
16509
  var PLAN_AUDIO_RELATIVE_PATH = MIXED_AUDIO_FILENAME3;
16432
16510
  var execFile = promisify2(execFileCallback);
16511
+ var cachedProducerVersion = null;
16512
+ function readProducerVersion() {
16513
+ if (cachedProducerVersion !== null) return cachedProducerVersion;
16514
+ const startDir = dirname15(fileURLToPath6(import.meta.url));
16515
+ let current = startDir;
16516
+ for (let i = 0; i < 10; i++) {
16517
+ const candidate = join34(current, "package.json");
16518
+ if (existsSync25(candidate)) {
16519
+ try {
16520
+ const pkg = JSON.parse(readFileSync11(candidate, "utf-8"));
16521
+ if (pkg.name === "@hyperframes/producer" && typeof pkg.version === "string") {
16522
+ cachedProducerVersion = pkg.version;
16523
+ return pkg.version;
16524
+ }
16525
+ } catch {
16526
+ }
16527
+ }
16528
+ const parent = dirname15(current);
16529
+ if (parent === current) break;
16530
+ current = parent;
16531
+ }
16532
+ cachedProducerVersion = "0.0.0-unknown";
16533
+ return cachedProducerVersion;
16534
+ }
16433
16535
 
16434
16536
  // src/services/distributed/chunkWeights.ts
16435
16537
  import { resolveFrameFormat } from "@hyperframes/engine";
@@ -16510,9 +16612,9 @@ var PLAN_ROOT_CATEGORY = {
16510
16612
  var PLAN_DIR_SIZE_LIMIT_BYTES = 2 * 1024 * 1024 * 1024;
16511
16613
  var FREEZE_OWNED_PLAN_FILES = [
16512
16614
  "plan.json",
16513
- join34("meta", "composition.json"),
16514
- join34("meta", "encoder.json"),
16515
- join34("meta", "chunks.json")
16615
+ join35("meta", "composition.json"),
16616
+ join35("meta", "encoder.json"),
16617
+ join35("meta", "chunks.json")
16516
16618
  ];
16517
16619
 
16518
16620
  // src/services/distributed/renderConfigValidation.ts
@@ -16672,6 +16774,7 @@ function assertRequestOptionScalars(options) {
16672
16774
  assertOptionalEnum(options, "proresProfile", PRORES_PROFILE_NAMES2);
16673
16775
  assertOptionalEnum(options, "strictness", ["strict", "best-effort"]);
16674
16776
  assertOptionalEnum(options, "hdrMode", ["auto", "force-hdr", "force-sdr"]);
16777
+ assertOptionalEnum(options, "chromaSubsampling", ["420", "444"]);
16675
16778
  assertOptionalEnum(options, "pageMotionBlur", ["off"]);
16676
16779
  if (options.videoFrameFormat !== void 0 && !isVideoFrameFormat2(options.videoFrameFormat)) {
16677
16780
  throw new Error("Render request videoFrameFormat is invalid");
@@ -16832,7 +16935,15 @@ function parseRenderOptions(body) {
16832
16935
  const format = parseServerFormat(body.format);
16833
16936
  const outputDynamicRange = parseServerOutputDynamicRange(body.outputDynamicRange) ?? fromRenderHdrMode(parseLegacyServerHdrMode(body.hdrMode));
16834
16937
  const encoder = parseEncoderOptions(body, format ?? "mp4");
16835
- const { crf, videoBitrate, videoFrameFormat, keyframeIntervalSeconds, maxBitrate, bufferSize } = encoder.ok ? encoder.options : {};
16938
+ const {
16939
+ crf,
16940
+ videoBitrate,
16941
+ videoFrameFormat,
16942
+ keyframeIntervalSeconds,
16943
+ maxBitrate,
16944
+ bufferSize,
16945
+ chromaSubsampling
16946
+ } = encoder.ok ? encoder.options : {};
16836
16947
  const { variables, outputResolution, outputResolutionAspectAgnostic } = parseRenderOverrides(body);
16837
16948
  return {
16838
16949
  outputPath,
@@ -16845,6 +16956,7 @@ function parseRenderOptions(body) {
16845
16956
  keyframeIntervalSeconds,
16846
16957
  maxBitrate,
16847
16958
  bufferSize,
16959
+ chromaSubsampling,
16848
16960
  useGpu,
16849
16961
  debug,
16850
16962
  forceScreenshot,
@@ -16884,6 +16996,7 @@ function buildRenderJobConfig(input, outputPath, log) {
16884
16996
  keyframeIntervalSeconds: input.keyframeIntervalSeconds,
16885
16997
  maxBitrate: input.maxBitrate,
16886
16998
  bufferSize: input.bufferSize,
16999
+ chromaSubsampling: input.chromaSubsampling,
16887
17000
  useGpu: input.useGpu,
16888
17001
  debug: input.debug,
16889
17002
  strictness: input.strictness,
@@ -16901,16 +17014,29 @@ function buildRenderJobConfig(input, outputPath, log) {
16901
17014
  function resolvePreparedRenderOutput(prepared, rendersDir, log) {
16902
17015
  const { input, cleanupProjectDir } = prepared;
16903
17016
  const absoluteOutputPath = resolveOutputPath(input.projectDir, input.outputPath, rendersDir, log);
16904
- const outputDir = dirname15(absoluteOutputPath);
16905
- if (!existsSync25(outputDir)) mkdirSync13(outputDir, { recursive: true });
17017
+ const outputDir = dirname16(absoluteOutputPath);
17018
+ if (!existsSync26(outputDir)) mkdirSync13(outputDir, { recursive: true });
16906
17019
  return { input, cleanupProjectDir, absoluteOutputPath };
16907
17020
  }
17021
+ function prepareRenderJob(prepared, rendersDir, log) {
17022
+ try {
17023
+ const output = resolvePreparedRenderOutput(prepared, rendersDir, log);
17024
+ const job = createRenderJob(buildRenderJobConfig(output.input, output.absoluteOutputPath, log));
17025
+ return { ...output, job };
17026
+ } catch (error) {
17027
+ cleanupTempDir(prepared.cleanupProjectDir, log);
17028
+ return { error: error instanceof Error ? error.message : String(error) };
17029
+ }
17030
+ }
16908
17031
  function validateRenderOverrides(body) {
16909
17032
  const encoder = parseEncoderOptions(body, parseServerFormat(body.format) ?? "mp4");
16910
17033
  if (!encoder.ok) return encoder.error;
16911
17034
  if (body.maxRenderMs !== void 0 && (typeof body.maxRenderMs !== "number" || !Number.isInteger(body.maxRenderMs) || body.maxRenderMs < 0)) {
16912
17035
  return "maxRenderMs must be a non-negative integer number of milliseconds";
16913
17036
  }
17037
+ if (typeof body.workers === "number" && (!Number.isInteger(body.workers) || body.workers < 1)) {
17038
+ return "workers must be a positive integer";
17039
+ }
16914
17040
  if (body.variables !== void 0 && !isPlainObject2(body.variables)) {
16915
17041
  return 'variables must be a JSON object keyed by variable id (e.g. {"title":"Hello"})';
16916
17042
  }
@@ -16925,6 +17051,9 @@ function validateRenderOverrides(body) {
16925
17051
  if (outputDynamicRange !== void 0 && legacyHdrMode !== void 0 && outputDynamicRange !== fromRenderHdrMode(legacyHdrMode)) {
16926
17052
  return "outputDynamicRange and legacy hdrMode must describe the same output policy";
16927
17053
  }
17054
+ if (body.chromaSubsampling === "444" && outputDynamicRange === "hdr") {
17055
+ return 'chromaSubsampling "444" is SDR only, not outputDynamicRange "hdr"';
17056
+ }
16928
17057
  return validateOutputResolutionOverride(body);
16929
17058
  }
16930
17059
  function validateOutputResolutionOverride(body) {
@@ -16943,11 +17072,11 @@ function prepareProjectDirectory(projectDir, options) {
16943
17072
  const candidate = nonEmptyString(projectDir);
16944
17073
  if (!candidate) return null;
16945
17074
  const absProjectDir = resolve10(candidate);
16946
- if (!existsSync25(absProjectDir) || !statSync11(absProjectDir).isDirectory()) {
17075
+ if (!existsSync26(absProjectDir) || !statSync11(absProjectDir).isDirectory()) {
16947
17076
  return { error: `Project directory not found: ${absProjectDir}` };
16948
17077
  }
16949
17078
  const entry = options.entryFile || "index.html";
16950
- if (!existsSync25(resolve10(absProjectDir, entry))) {
17079
+ if (!existsSync26(resolve10(absProjectDir, entry))) {
16951
17080
  return { error: `Entry file "${entry}" not found in project directory: ${absProjectDir}` };
16952
17081
  }
16953
17082
  return { prepared: { input: { projectDir: absProjectDir, ...options } } };
@@ -16968,8 +17097,8 @@ async function resolveInlineRenderHtml(body) {
16968
17097
  }
16969
17098
  function materializeInlineProject(html, options) {
16970
17099
  const tempRoot = process.env.PRODUCER_TMP_PROJECT_DIR || tmpdir3();
16971
- const tempProjectDir = mkdtempSync(join35(tempRoot, "producer-project-"));
16972
- writeFileSync8(join35(tempProjectDir, "index.html"), html, "utf-8");
17100
+ const tempProjectDir = mkdtempSync(join36(tempRoot, "producer-project-"));
17101
+ writeFileSync8(join36(tempProjectDir, "index.html"), html, "utf-8");
16973
17102
  return {
16974
17103
  prepared: {
16975
17104
  input: { projectDir: tempProjectDir, ...options },
@@ -17039,7 +17168,7 @@ function cleanupTempDir(dir, log) {
17039
17168
  }
17040
17169
  }
17041
17170
  function outputFileSize(path) {
17042
- return existsSync25(path) ? statSync11(path).size : 0;
17171
+ return existsSync26(path) ? statSync11(path).size : 0;
17043
17172
  }
17044
17173
  function createBlockingProgressReporter(log, requestId) {
17045
17174
  let lastLoggedPct = -10;
@@ -17188,11 +17317,11 @@ function createRenderHandlers(options = {}) {
17188
17317
  if ("error" in preparedResult) {
17189
17318
  return c.json({ success: false, requestId, error: preparedResult.error }, 400);
17190
17319
  }
17191
- const { input, cleanupProjectDir, absoluteOutputPath } = resolvePreparedRenderOutput(
17192
- preparedResult.prepared,
17193
- rendersDir,
17194
- log
17195
- );
17320
+ const preparedJob = prepareRenderJob(preparedResult.prepared, rendersDir, log);
17321
+ if ("error" in preparedJob) {
17322
+ return c.json({ success: false, requestId, error: preparedJob.error }, 400);
17323
+ }
17324
+ const { job, input, cleanupProjectDir, absoluteOutputPath } = preparedJob;
17196
17325
  const release = await renderSemaphore.acquire();
17197
17326
  log.info("render started", {
17198
17327
  requestId,
@@ -17200,7 +17329,6 @@ function createRenderHandlers(options = {}) {
17200
17329
  fps: input.fps,
17201
17330
  quality: input.quality
17202
17331
  });
17203
- const job = createRenderJob(buildRenderJobConfig(input, absoluteOutputPath, log));
17204
17332
  try {
17205
17333
  await executeRenderJob(
17206
17334
  job,
@@ -17268,13 +17396,20 @@ function createRenderHandlers(options = {}) {
17268
17396
  const t0 = Date.now();
17269
17397
  const prepared = await prepareSseRenderRequest(c, stream, requestId);
17270
17398
  if (!prepared) return;
17271
- const { input, cleanupProjectDir, absoluteOutputPath } = resolvePreparedRenderOutput(
17272
- prepared,
17273
- rendersDir,
17274
- log
17275
- );
17399
+ const preparedJob = prepareRenderJob(prepared, rendersDir, log);
17400
+ if ("error" in preparedJob) {
17401
+ await stream.writeSSE({
17402
+ data: JSON.stringify({
17403
+ type: "error",
17404
+ requestId,
17405
+ error: preparedJob.error,
17406
+ stage: "validation"
17407
+ })
17408
+ });
17409
+ return;
17410
+ }
17411
+ const { job, input, cleanupProjectDir, absoluteOutputPath } = preparedJob;
17276
17412
  log.info("render-stream started", { requestId, projectDir: input.projectDir });
17277
- const job = createRenderJob(buildRenderJobConfig(input, absoluteOutputPath, log));
17278
17413
  const abortController = new AbortController();
17279
17414
  const onRequestAbort = () => abortController.abort(new RenderCancelledError("request_aborted"));
17280
17415
  c.req.raw.signal.addEventListener("abort", onRequestAbort, { once: true });
@@ -17318,7 +17453,8 @@ function createRenderHandlers(options = {}) {
17318
17453
  videoDurationSeconds: job.duration ?? null,
17319
17454
  outcome: job.outcome ?? "completed",
17320
17455
  warnings: job.warnings,
17321
- perf: job.perfSummary ?? null
17456
+ perf: job.perfSummary ?? null,
17457
+ producerVersion: readProducerVersion()
17322
17458
  })
17323
17459
  });
17324
17460
  } catch (error) {
@@ -17343,7 +17479,7 @@ function createRenderHandlers(options = {}) {
17343
17479
  if (!artifact) {
17344
17480
  return c.json({ success: false, error: "Output artifact not found or expired" }, 404);
17345
17481
  }
17346
- if (!existsSync25(artifact.path)) {
17482
+ if (!existsSync26(artifact.path)) {
17347
17483
  store.delete(token);
17348
17484
  return c.json({ success: false, error: "Output artifact file missing" }, 404);
17349
17485
  }
@@ -17363,9 +17499,26 @@ function createRenderHandlers(options = {}) {
17363
17499
  });
17364
17500
  return { render, renderStream, lint, health, outputs, queue };
17365
17501
  }
17502
+ function isCrossOriginBrowserRequest(c) {
17503
+ const fetchSite = c.req.header("sec-fetch-site");
17504
+ if (fetchSite) return fetchSite !== "same-origin" && fetchSite !== "none";
17505
+ const origin = c.req.header("origin");
17506
+ if (!origin) return false;
17507
+ try {
17508
+ return new URL(origin).host !== c.req.header("host");
17509
+ } catch {
17510
+ return true;
17511
+ }
17512
+ }
17366
17513
  function createProducerApp(options = {}) {
17367
17514
  const app = new Hono2();
17368
17515
  const handlers = createRenderHandlers(options);
17516
+ app.post("*", async (c, next) => {
17517
+ if (isCrossOriginBrowserRequest(c)) {
17518
+ return c.json({ success: false, error: "Cross-origin requests are not allowed" }, 403);
17519
+ }
17520
+ await next();
17521
+ });
17369
17522
  app.get("/health", handlers.health);
17370
17523
  app.post("/render", handlers.render);
17371
17524
  app.post("/render/stream", handlers.renderStream);
@@ -44,6 +44,7 @@ export interface RenderRequestOptions {
44
44
  bufferSize?: string;
45
45
  videoFrameFormat?: VideoFrameFormat;
46
46
  hdrMode?: RenderConfig["hdrMode"];
47
+ chromaSubsampling?: RenderConfig["chromaSubsampling"];
47
48
  pageMotionBlur?: RenderConfig["pageMotionBlur"];
48
49
  variables?: Record<string, unknown>;
49
50
  outputResolution?: CanvasResolution;
package/dist/server.d.ts CHANGED
@@ -52,6 +52,7 @@ interface RenderInput {
52
52
  keyframeIntervalSeconds?: number;
53
53
  maxBitrate?: string;
54
54
  bufferSize?: string;
55
+ chromaSubsampling?: RenderConfig["chromaSubsampling"];
55
56
  useGpu: boolean;
56
57
  debug: boolean;
57
58
  forceScreenshot?: true;
@@ -11,7 +11,7 @@
11
11
  /**
12
12
  * The files a site upload ships, as `/`-separated paths under `projectDir`. Symlinks are followed
13
13
  * (root included), top-level {@link PLAN_PROJECT_DIR_SKIP_SEGMENTS} are left out as the plan stage
14
- * does, and a dangling symlink throws.
14
+ * does, env files are left out at every depth, and a dangling symlink throws.
15
15
  */
16
16
  export declare function listSiteFiles(projectDir: string): string[];
17
17
  /**
@@ -1,13 +1,14 @@
1
- import type { EngineConfig, MotionBlurOptions } from "@hyperframes/engine";
1
+ import type { ChromaSubsampling, EngineConfig, MotionBlurOptions } from "@hyperframes/engine";
2
2
  /**
3
3
  * The format a render captures its frames in.
4
4
  *
5
- * Two independent reasons force PNG, and conflating them is how the encoder ends up
5
+ * Three independent reasons force PNG, and conflating them is how the encoder ends up
6
6
  * hunting for `frame_%06d.jpg` against files written as `.png`:
7
7
  *
8
8
  * - the output container keeps alpha, which JPEG cannot carry;
9
9
  * - motion blur is on, because the sub-frame samples are averaged pixel by pixel and
10
- * JPEG samples would be averaged after a lossy quantization.
10
+ * JPEG samples would be averaged after a lossy quantization;
11
+ * - 4:4:4 output, because Chrome's JPEG capture is already 4:2:0.
11
12
  *
12
13
  * Every consumer of "is this render PNG" reads the resolved capture format rather than
13
14
  * re-deriving it from one of the reasons.
@@ -15,9 +16,19 @@ import type { EngineConfig, MotionBlurOptions } from "@hyperframes/engine";
15
16
  export declare function resolveCaptureImageFormat(input: {
16
17
  needsAlpha: boolean;
17
18
  motionBlur: MotionBlurOptions | undefined;
19
+ chromaSubsampling?: ChromaSubsampling;
18
20
  }): "jpeg" | "png";
19
21
  /**
20
22
  * Below 100, Chrome's JPEG turns graded colour and grain into 8x8 chroma blotches that survive
21
23
  * the final encode. Draft keeps the smaller, faster frames.
22
24
  */
23
25
  export declare function resolveCaptureJpegQuality(quality: EngineConfig["quality"]): number;
26
+ /**
27
+ * The capture fields every session of a render shares. The probe session is reused for
28
+ * capture, so the probe and the main capture options both spread this.
29
+ */
30
+ export declare function resolveCaptureSurface(input: Parameters<typeof resolveCaptureImageFormat>[0], quality: EngineConfig["quality"]): {
31
+ format: "jpeg" | "png";
32
+ quality: number | undefined;
33
+ transparent: boolean;
34
+ };
@@ -0,0 +1,18 @@
1
+ /** Fail-fast gates for `chromaSubsampling: "444"`: refuse what would ship 4:2:0 colour. */
2
+ import type { ChromaSubsampling } from "@hyperframes/engine";
3
+ export interface ChromaSubsamplingRenderConfig {
4
+ chromaSubsampling?: ChromaSubsampling;
5
+ format?: string;
6
+ hdrMode?: "auto" | "force-hdr" | "force-sdr";
7
+ useGpu?: boolean;
8
+ }
9
+ /**
10
+ * Reject the config combinations 4:4:4 cannot honor. No-op unless "444" is requested,
11
+ * so this runs unconditionally at the top of `executeRenderJob`.
12
+ */
13
+ export declare function validateChromaSubsamplingConfig(config: ChromaSubsamplingRenderConfig): void;
14
+ /**
15
+ * Reject 4:4:4 once auto HDR detection has found HDR sources, before any capture
16
+ * runs. `validateChromaSubsamplingConfig` cannot see this: it depends on probing.
17
+ */
18
+ export declare function assertChromaSubsamplingSdr(config: Pick<ChromaSubsamplingRenderConfig, "chromaSubsampling">, hasHdrContent: boolean): void;
@@ -10,7 +10,7 @@
10
10
  * backwards compatibility with existing test files and external callers.
11
11
  */
12
12
  import { type CanvasResolution } from "@hyperframes/core";
13
- import type { AudioElement, ExtractedFrames, ImageElement, ParallelProgress, VideoElement } from "@hyperframes/engine";
13
+ import { type AudioElement, type ExtractedFrames, type ImageElement, type ParallelProgress, type VideoElement } from "@hyperframes/engine";
14
14
  import type { CompiledComposition } from "../htmlCompiler.js";
15
15
  import { type ProducerLogger } from "../../logger.js";
16
16
  import type { ProgressCallback, RenderJob, RenderStageProgress, RenderStatus } from "../renderOrchestrator.js";