@hyperframes/studio-server 0.8.142 → 0.8.144
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.
- package/dist/{chunk-DSVQ2U7J.js → chunk-32IH7WBY.js} +36 -14
- package/dist/chunk-32IH7WBY.js.map +1 -0
- package/dist/{chunk-QP7LKFU2.js → chunk-AZBGTB3N.js} +98 -30
- package/dist/chunk-AZBGTB3N.js.map +1 -0
- package/dist/{chunk-74JVVCWL.js → chunk-RN33UALN.js} +16 -18
- package/dist/chunk-RN33UALN.js.map +1 -0
- package/dist/{chunk-5VCIZYUE.js → chunk-VE2AOX4K.js} +3 -3
- package/dist/helpers/loudness.js +4 -1
- package/dist/helpers/mediaCodecMap.js +1 -1
- package/dist/helpers/mediaProxyPreview.d.ts +1 -1
- package/dist/helpers/mediaProxyPreview.js +3 -3
- package/dist/helpers/proxyTranscoder.d.ts +12 -12
- package/dist/helpers/proxyTranscoder.js +2 -2
- package/dist/index.d.ts +3 -2
- package/dist/index.js +247 -50
- package/dist/index.js.map +1 -1
- package/dist/{mediaProxyPreview-CJ4lbPcF.d.ts → mediaProxyPreview-ozy7FkMP.d.ts} +1 -0
- package/package.json +3 -3
- package/dist/chunk-74JVVCWL.js.map +0 -1
- package/dist/chunk-DSVQ2U7J.js.map +0 -1
- package/dist/chunk-QP7LKFU2.js.map +0 -1
- /package/dist/{chunk-5VCIZYUE.js.map → chunk-VE2AOX4K.js.map} +0 -0
|
@@ -1,3 +1,7 @@
|
|
|
1
|
+
import {
|
|
2
|
+
resolveWithinProject
|
|
3
|
+
} from "./chunk-DTKK7TKL.js";
|
|
4
|
+
|
|
1
5
|
// src/helpers/loudness.ts
|
|
2
6
|
import { execFile } from "child_process";
|
|
3
7
|
import { isAbsolute, relative, resolve } from "path";
|
|
@@ -5,6 +9,25 @@ import { promisify } from "util";
|
|
|
5
9
|
import { isAudibleVideoElement } from "@hyperframes/core/audible-video";
|
|
6
10
|
import { formatAudioGain, MAX_AUDIO_GAIN_DB } from "@hyperframes/core/audio-gain";
|
|
7
11
|
import { findFfBinary } from "@hyperframes/parsers/ff-binaries";
|
|
12
|
+
import { readMediaOffsetSeconds } from "@hyperframes/parsers/media-duration";
|
|
13
|
+
|
|
14
|
+
// src/helpers/requestSubPath.ts
|
|
15
|
+
import { existsSync } from "fs";
|
|
16
|
+
import { decodedUrlPath, decodeWellFormedEscapes } from "@hyperframes/parsers/asset-paths";
|
|
17
|
+
import { decodeWellFormedEscapes as decodeWellFormedEscapes2 } from "@hyperframes/parsers/asset-paths";
|
|
18
|
+
function requestSubPath(url, route) {
|
|
19
|
+
const routeSegments = route.split("/");
|
|
20
|
+
const segments = new URL(url).pathname.split("/");
|
|
21
|
+
const start = segments.indexOf(routeSegments[0] ?? "");
|
|
22
|
+
return decodeWellFormedEscapes(segments.slice(start + routeSegments.length).join("/"));
|
|
23
|
+
}
|
|
24
|
+
function requestedProjectPath(projectDir, field) {
|
|
25
|
+
const trimmed = field.trim().replace(/^[.]\//, "");
|
|
26
|
+
const named = resolveWithinProject(projectDir, trimmed);
|
|
27
|
+
return named && existsSync(named) ? trimmed : decodedUrlPath(trimmed);
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
// src/helpers/loudness.ts
|
|
8
31
|
var execFileAsync = promisify(execFile);
|
|
9
32
|
var FFMPEG_TIMEOUT_MS = 12e4;
|
|
10
33
|
function authoredNumber(raw, fallback, attribute, id, strictlyPositive = false) {
|
|
@@ -149,6 +172,13 @@ function requiredAudioIdentity(attributes) {
|
|
|
149
172
|
if (!src) throw new Error(`Audio #${id} has no src`);
|
|
150
173
|
return { id, src };
|
|
151
174
|
}
|
|
175
|
+
function authoredMediaStart(attributes, id) {
|
|
176
|
+
return readMediaOffsetSeconds((name) => {
|
|
177
|
+
const raw = attributes.get(name)?.value;
|
|
178
|
+
if (name === "data-media-start") authoredNumber(raw, 0, name, id);
|
|
179
|
+
return raw;
|
|
180
|
+
});
|
|
181
|
+
}
|
|
152
182
|
function hasBareAttribute(html, range, name) {
|
|
153
183
|
const unquoted = html.slice(range.start, range.end).replace(/"[^"]*"|'[^']*'/g, '""');
|
|
154
184
|
return new RegExp(`\\s${name}(?=[\\s/>=])`, "i").test(unquoted);
|
|
@@ -173,12 +203,7 @@ function mediaTagFromRange(html, range) {
|
|
|
173
203
|
id,
|
|
174
204
|
src,
|
|
175
205
|
volume: authoredNumber(volumeAttribute?.value, 1, "data-volume", id),
|
|
176
|
-
mediaStart:
|
|
177
|
-
attributes.get("data-media-start")?.value,
|
|
178
|
-
0,
|
|
179
|
-
"data-media-start",
|
|
180
|
-
id
|
|
181
|
-
),
|
|
206
|
+
mediaStart: authoredMediaStart(attributes, id),
|
|
182
207
|
duration: authoredDuration(attributes, id),
|
|
183
208
|
playbackRate: authoredNumber(
|
|
184
209
|
attributes.get("data-playback-rate")?.value,
|
|
@@ -205,13 +230,7 @@ function audioTags(html) {
|
|
|
205
230
|
return tags;
|
|
206
231
|
}
|
|
207
232
|
function resolveLocalAudioPath(projectDir, src) {
|
|
208
|
-
const
|
|
209
|
-
let decoded = "";
|
|
210
|
-
try {
|
|
211
|
-
decoded = decodeURIComponent(withoutSuffix);
|
|
212
|
-
} catch {
|
|
213
|
-
throw new Error(`Audio source must be a local project file: ${src}`);
|
|
214
|
-
}
|
|
233
|
+
const decoded = requestedProjectPath(projectDir, src);
|
|
215
234
|
if (!decoded || isAbsolute(decoded) || /^(?:[a-z][a-z\d+.-]*:|\/\/)/i.test(decoded)) {
|
|
216
235
|
throw new Error(`Audio source must be a local project file: ${src}`);
|
|
217
236
|
}
|
|
@@ -346,6 +365,9 @@ function absoluteLoudnessPlan(track, targetLufs = DEFAULT_TARGET_LUFS) {
|
|
|
346
365
|
}
|
|
347
366
|
|
|
348
367
|
export {
|
|
368
|
+
requestSubPath,
|
|
369
|
+
requestedProjectPath,
|
|
370
|
+
decodeWellFormedEscapes2 as decodeWellFormedEscapes,
|
|
349
371
|
audioTags,
|
|
350
372
|
resolveLocalAudioPath,
|
|
351
373
|
parseEbur128Summary,
|
|
@@ -359,4 +381,4 @@ export {
|
|
|
359
381
|
NORMALIZE_TRUE_PEAK_CEILING_DBFS,
|
|
360
382
|
absoluteLoudnessPlan
|
|
361
383
|
};
|
|
362
|
-
//# sourceMappingURL=chunk-
|
|
384
|
+
//# sourceMappingURL=chunk-32IH7WBY.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/helpers/loudness.ts","../src/helpers/requestSubPath.ts"],"sourcesContent":["import { execFile } from \"node:child_process\";\nimport { isAbsolute, relative, resolve } from \"node:path\";\nimport { promisify } from \"node:util\";\nimport { isAudibleVideoElement } from \"@hyperframes/core/audible-video\";\nimport { formatAudioGain, MAX_AUDIO_GAIN_DB } from \"@hyperframes/core/audio-gain\";\nimport { findFfBinary } from \"@hyperframes/parsers/ff-binaries\";\nimport { readMediaOffsetSeconds } from \"@hyperframes/parsers/media-duration\";\nimport { requestedProjectPath } from \"./requestSubPath.js\";\n\nconst execFileAsync = promisify(execFile);\n\nconst FFMPEG_TIMEOUT_MS = 120_000;\n\ninterface AttributeSpan {\n value: string;\n valueStart: number;\n valueEnd: number;\n}\n\ninterface TagRange {\n start: number;\n end: number;\n}\n\ntype MediaTagName = \"audio\" | \"video\";\n\ninterface MediaTagRange extends TagRange {\n name: MediaTagName;\n}\n\ninterface ParsedStartTag extends TagRange {\n closing: boolean;\n name: string;\n}\n\ninterface ScanResult {\n cursor: number;\n mediaRange: MediaTagRange | null;\n}\n\nexport interface AudioTag {\n tag: MediaTagName;\n id: string;\n src: string;\n volume: number;\n mediaStart: number;\n duration: number | null;\n playbackRate: number;\n start: number;\n end: number;\n volumeAttribute: AttributeSpan | null;\n}\n\nexport interface LoudnessMeasurement {\n integratedLufs: number;\n truePeakDbfs: number;\n}\n\nexport interface NormalizationTrack extends LoudnessMeasurement {\n id: string;\n volume: number;\n}\n\nexport interface AudioNormalizationPlan {\n referenceId: string;\n targetId: string;\n referenceLufs: number;\n targetLufs: number;\n previousVolume: number;\n volume: number;\n gainDb: number;\n changeDb: number;\n projectedLufs: number;\n projectedTruePeakDbfs: number;\n}\n\nfunction authoredNumber(\n raw: string | undefined,\n fallback: number,\n attribute: string,\n id: string,\n strictlyPositive = false,\n): number {\n if (raw === undefined) return fallback;\n const value = Number(raw);\n if (!Number.isFinite(value) || (strictlyPositive ? value <= 0 : value < 0)) {\n throw new Error(`Audio #${id} has an invalid ${attribute}: ${raw}`);\n }\n return value;\n}\n\nfunction attributeFromMatch(\n match: RegExpMatchArray,\n absoluteOffset: number,\n): [string, AttributeSpan] | null {\n if (match.index === undefined) return null;\n const name = match[1]?.toLowerCase();\n const value = matchedAttributeValue(match);\n if (!name || value === undefined) return null;\n\n const whole = match[0];\n const localValueStart = attributeValueStart(whole);\n const valueStart = absoluteOffset + match.index + localValueStart;\n return [name, { value, valueStart, valueEnd: valueStart + value.length }];\n}\n\nfunction matchedAttributeValue(match: RegExpMatchArray): string | undefined {\n return match[2] ?? match[3] ?? match[4];\n}\n\nfunction attributeValueStart(attribute: string): number {\n let cursor = attribute.indexOf(\"=\") + 1;\n while (/\\s/.test(attribute[cursor] ?? \"\")) cursor += 1;\n const quote = attribute[cursor];\n return quote === '\"' || quote === \"'\" ? cursor + 1 : cursor;\n}\n\nfunction attributesInTag(html: string, from: number, to: number): Map<string, AttributeSpan> {\n const tag = html.slice(from, to);\n const nameEnd = tag.search(/\\s|\\/?\\s*>/);\n const attributes = new Map<string, AttributeSpan>();\n if (nameEnd < 0) return attributes;\n\n const pattern = /([^\\s=/>]+)\\s*=\\s*(?:\"([^\"]*)\"|'([^']*)'|([^\\s\"'=<>`]+))/g;\n for (const match of tag.slice(nameEnd).matchAll(pattern)) {\n const attribute = attributeFromMatch(match, from + nameEnd);\n if (attribute) attributes.set(...attribute);\n }\n return attributes;\n}\n\nfunction startTagEnd(html: string, start: number): number {\n let quote = \"\";\n let end = start + 1;\n for (; end < html.length; end += 1) {\n const char = html[end];\n if (quote) {\n if (char === quote) quote = \"\";\n } else if (char === '\"' || char === \"'\") {\n quote = char;\n } else if (char === \">\") {\n return end + 1;\n }\n }\n throw new Error(\"Unterminated HTML start tag\");\n}\n\nfunction commentEnd(html: string, start: number): number {\n const end = html.indexOf(\"-->\", start + 4);\n if (end < 0) throw new Error(\"Unterminated HTML comment\");\n return end + 3;\n}\n\nconst isSpaceAt = (html: string, index: number) => /\\s/.test(html.charAt(index));\nconst isWordAt = (html: string, index: number) => /\\w/.test(html.charAt(index));\n\nfunction skipSpaces(html: string, index: number): number {\n let cursor = index;\n while (cursor < html.length && isSpaceAt(html, cursor)) cursor++;\n return cursor;\n}\n\nfunction parsedStartTag(html: string, start: number): ParsedStartTag | null {\n let cursor = skipSpaces(html, start + 1);\n const closing = html.charAt(cursor) === \"/\";\n if (closing) cursor = skipSpaces(html, cursor + 1);\n const nameStart = cursor;\n if (!/[a-z]/i.test(html.charAt(cursor))) return null;\n while (/[a-z\\d:-]/i.test(html.charAt(cursor + 1))) cursor++;\n let nameEnd = cursor + 1;\n while (nameEnd > nameStart && isWordAt(html, nameEnd - 1) === isWordAt(html, nameEnd)) nameEnd--;\n if (nameEnd === nameStart) return null;\n return {\n start,\n end: startTagEnd(html, start),\n closing,\n name: html.slice(nameStart, nameEnd).toLowerCase(),\n };\n}\n\nfunction rawTextElementEnd(html: string, lower: string, tag: ParsedStartTag): number | null {\n if (tag.closing || (tag.name !== \"script\" && tag.name !== \"style\")) return null;\n const closeStart = lower.indexOf(`</${tag.name}`, tag.end);\n if (closeStart < 0) throw new Error(`Unterminated <${tag.name}> element`);\n return startTagEnd(html, closeStart);\n}\n\nfunction scanMarkup(html: string, lower: string, start: number): ScanResult {\n if (html.startsWith(\"<!--\", start)) {\n return { cursor: commentEnd(html, start), mediaRange: null };\n }\n const tag = parsedStartTag(html, start);\n if (!tag) {\n const marker = html[start + 1];\n const cursor = marker === \"!\" || marker === \"?\" ? startTagEnd(html, start) : start + 1;\n return { cursor, mediaRange: null };\n }\n const rawTextEnd = rawTextElementEnd(html, lower, tag);\n if (rawTextEnd !== null) return { cursor: rawTextEnd, mediaRange: null };\n return { cursor: tag.end, mediaRange: mediaRangeOf(tag) };\n}\n\nfunction mediaRangeOf(tag: ParsedStartTag): MediaTagRange | null {\n if (tag.closing) return null;\n if (tag.name === \"audio\" || tag.name === \"video\") {\n return { start: tag.start, end: tag.end, name: tag.name };\n }\n return null;\n}\n\nfunction mediaTagRanges(html: string): MediaTagRange[] {\n const lower = html.toLowerCase();\n const ranges: MediaTagRange[] = [];\n let cursor = 0;\n while (cursor < html.length) {\n const start = html.indexOf(\"<\", cursor);\n if (start < 0) break;\n const scanned = scanMarkup(html, lower, start);\n if (scanned.mediaRange) ranges.push(scanned.mediaRange);\n cursor = scanned.cursor;\n }\n return ranges;\n}\n\nfunction trimmedAttribute(attributes: Map<string, AttributeSpan>, name: string): string {\n return attributes.get(name)?.value.trim() ?? \"\";\n}\n\n/**\n * How much of the source the composition actually plays.\n *\n * `data-duration` is the explicit trim; absent, `data-end` still bounds the\n * clip's timeline window, and the parser, the runtime and the render mixer all\n * honour it. Measuring the whole file for a `data-end`-trimmed clip reads a\n * loudness the composition never plays — and `--write` then \"corrects\" an\n * already-matched clip by tens of dB.\n */\nfunction authoredDuration(attributes: Map<string, AttributeSpan>, id: string): number | null {\n const raw = attributes.get(\"data-duration\")?.value;\n if (raw !== undefined) return authoredNumber(raw, 0, \"data-duration\", id, true);\n\n const rawEnd = attributes.get(\"data-end\")?.value;\n if (rawEnd === undefined) return null;\n const end = authoredNumber(rawEnd, 0, \"data-end\", id, true);\n const start = authoredNumber(attributes.get(\"data-start\")?.value, 0, \"data-start\", id);\n return end > start ? end - start : null;\n}\n\nfunction requiredAudioIdentity(attributes: Map<string, AttributeSpan>) {\n const id = trimmedAttribute(attributes, \"id\");\n const src = trimmedAttribute(attributes, \"src\");\n if (!id) throw new Error(\"Every normalized <audio> element needs an id\");\n if (!src) throw new Error(`Audio #${id} has no src`);\n return { id, src };\n}\n\nfunction authoredMediaStart(attributes: Map<string, AttributeSpan>, id: string): number {\n return readMediaOffsetSeconds((name) => {\n const raw = attributes.get(name)?.value;\n if (name === \"data-media-start\") authoredNumber(raw, 0, name, id);\n return raw;\n });\n}\n\n/** Boolean attributes carry no `=`, so the value map cannot see them. */\nfunction hasBareAttribute(html: string, range: TagRange, name: string): boolean {\n const unquoted = html.slice(range.start, range.end).replace(/\"[^\"]*\"|'[^']*'/g, '\"\"');\n return new RegExp(`\\\\s${name}(?=[\\\\s/>=])`, \"i\").test(unquoted);\n}\n\nfunction isAudibleVideoTag(\n html: string,\n range: TagRange,\n attributes: Map<string, AttributeSpan>,\n): boolean {\n return isAudibleVideoElement({\n tagName: \"video\",\n hasAttribute: (name) => attributes.has(name) || hasBareAttribute(html, range, name),\n getAttribute: (name) => attributes.get(name)?.value ?? null,\n });\n}\n\n/**\n * A video joins the scan only when it carries sound and can be addressed.\n * Silent footage, and a video no command could name, are skipped rather than\n * failing a run that is about some other clip.\n */\nfunction inScopeVideo(\n html: string,\n range: TagRange,\n attributes: Map<string, AttributeSpan>,\n): boolean {\n return (\n isAudibleVideoTag(html, range, attributes) &&\n trimmedAttribute(attributes, \"id\") !== \"\" &&\n trimmedAttribute(attributes, \"src\") !== \"\"\n );\n}\n\nfunction mediaTagFromRange(html: string, range: MediaTagRange): AudioTag | null {\n const attributes = attributesInTag(html, range.start, range.end);\n if (range.name === \"video\" && !inScopeVideo(html, range, attributes)) return null;\n const { id, src } = requiredAudioIdentity(attributes);\n const volumeAttribute = attributes.get(\"data-volume\") ?? null;\n return {\n tag: range.name,\n id,\n src,\n volume: authoredNumber(volumeAttribute?.value, 1, \"data-volume\", id),\n mediaStart: authoredMediaStart(attributes, id),\n duration: authoredDuration(attributes, id),\n playbackRate: authoredNumber(\n attributes.get(\"data-playback-rate\")?.value,\n 1,\n \"data-playback-rate\",\n id,\n true,\n ),\n start: range.start,\n end: range.end,\n volumeAttribute,\n };\n}\n\n/** Read the authored clips with sound — `<audio>` and audible `<video>` — without reserializing. */\nexport function audioTags(html: string): AudioTag[] {\n const seen = new Set<string>();\n const tags: AudioTag[] = [];\n for (const range of mediaTagRanges(html)) {\n const tag = mediaTagFromRange(html, range);\n if (!tag) continue;\n if (seen.has(tag.id)) throw new Error(`Duplicate audio id \"${tag.id}\"`);\n seen.add(tag.id);\n tags.push(tag);\n }\n return tags;\n}\n\n/** Resolve only a file contained by the project. Remote and traversal sources are not measured. */\nexport function resolveLocalAudioPath(projectDir: string, src: string): string {\n const decoded = requestedProjectPath(projectDir, src);\n if (!decoded || isAbsolute(decoded) || /^(?:[a-z][a-z\\d+.-]*:|\\/\\/)/i.test(decoded)) {\n throw new Error(`Audio source must be a local project file: ${src}`);\n }\n const root = resolve(projectDir);\n const file = resolve(root, decoded);\n const rel = relative(root, file);\n if (!rel || rel === \"..\" || rel.startsWith(`..${process.platform === \"win32\" ? \"\\\\\" : \"/\"}`)) {\n throw new Error(`Audio source must be a local project file: ${src}`);\n }\n return file;\n}\n\n/** Parse FFmpeg's final EBU R128 summary, not its per-window log lines. */\nexport function parseEbur128Summary(stderr: string): LoudnessMeasurement {\n const summaryAt = stderr.lastIndexOf(\"Summary:\");\n const summary = summaryAt >= 0 ? stderr.slice(summaryAt) : \"\";\n const integrated = summary.match(/\\bI:\\s*(-?\\d+(?:\\.\\d+)?)\\s+LUFS\\b/);\n const peak = summary.match(/\\bPeak:\\s*(-?\\d+(?:\\.\\d+)?)\\s+dBFS\\b/);\n const integratedLufs = Number(integrated?.[1]);\n const truePeakDbfs = Number(peak?.[1]);\n if (!Number.isFinite(integratedLufs)) {\n throw new Error(\"FFmpeg did not report integrated loudness for this audio stream\");\n }\n if (!Number.isFinite(truePeakDbfs)) {\n throw new Error(\"FFmpeg did not report true peak for this audio stream\");\n }\n return { integratedLufs, truePeakDbfs };\n}\n\nexport function gainDb(volume: number): number {\n return volume > 0 ? 20 * Math.log10(volume) : Number.NEGATIVE_INFINITY;\n}\n\n/** Calculate the target's absolute authored gain while keeping the reference unchanged. */\nexport function audioNormalizationPlan(\n referenceTrack: NormalizationTrack,\n targetTrack: NormalizationTrack,\n): AudioNormalizationPlan {\n if (!(referenceTrack.volume > 0) || !(targetTrack.volume > 0)) {\n throw new Error(\"Muted audio cannot be used for loudness matching\");\n }\n const referenceLufs = referenceTrack.integratedLufs + gainDb(referenceTrack.volume);\n const targetLufs = targetTrack.integratedLufs + gainDb(targetTrack.volume);\n const wantedGainDb = referenceLufs - targetTrack.integratedLufs;\n if (wantedGainDb > MAX_AUDIO_GAIN_DB + 1e-9) {\n throw new Error(\n `Matching #${targetTrack.id} needs ${wantedGainDb.toFixed(1)} dB, beyond the +${MAX_AUDIO_GAIN_DB} dB authoring ceiling. ` +\n `A gap this large belongs in the source file, not the mixer — mixer gain raises the noise floor with the signal. ` +\n `Normalize ${targetTrack.id}'s asset offline (e.g. ffmpeg loudnorm), or lower #${referenceTrack.id} instead.`,\n );\n }\n const volume = 10 ** (wantedGainDb / 20);\n const projectedTruePeakDbfs = targetTrack.truePeakDbfs + wantedGainDb;\n if (projectedTruePeakDbfs > 0) {\n throw new Error(\n `Matching #${targetTrack.id} would clip at +${projectedTruePeakDbfs.toFixed(1)} dBFS; limit or preprocess the source first`,\n );\n }\n return {\n referenceId: referenceTrack.id,\n targetId: targetTrack.id,\n referenceLufs,\n targetLufs,\n previousVolume: targetTrack.volume,\n volume,\n gainDb: wantedGainDb,\n changeDb: wantedGainDb - gainDb(targetTrack.volume),\n projectedLufs: targetTrack.integratedLufs + wantedGainDb,\n projectedTruePeakDbfs,\n };\n}\n\n/** Patch one authored attribute in place so scripts/styles/comments remain byte-stable. */\nexport function updateAudioVolume(html: string, id: string, volume: number): string {\n const tag = audioTags(html).find((candidate) => candidate.id === id);\n if (!tag) throw new Error(`Audio #${id} was not found`);\n const value = formatAudioGain(volume);\n if (tag.volumeAttribute) {\n return (\n html.slice(0, tag.volumeAttribute.valueStart) +\n value +\n html.slice(tag.volumeAttribute.valueEnd)\n );\n }\n\n let insertion = tag.end - 1;\n let tail = insertion - 1;\n while (tail >= tag.start && /\\s/.test(html[tail] ?? \"\")) tail -= 1;\n if (html[tail] === \"/\") {\n insertion = tail;\n while (insertion > tag.start && /\\s/.test(html[insertion - 1] ?? \"\")) insertion -= 1;\n } else {\n while (insertion > tag.start && /\\s/.test(html[insertion - 1] ?? \"\")) insertion -= 1;\n }\n return html.slice(0, insertion) + ` data-volume=\"${value}\"` + html.slice(insertion);\n}\n\n/**\n * FFmpeg arguments that measure exactly the window the composition plays.\n *\n * `-ss` / `-t` go BEFORE `-i`, as INPUT options. After `-i` they bound the\n * output, and with `-f null` there is no real output to bound: ffmpeg keeps\n * feeding the filter graph past the limit, so ebur128 integrates audio the clip\n * never plays. Measured on a 12 s file whose first 4 s — the played window — is\n * -61.8 LUFS: output-side `-t 4` reported -33.8 LUFS, input-side reports -61.8,\n * the same as physically cutting the file first.\n */\nexport function loudnessMeasureArgs(file: string, tag: MeasuredWindow): string[] {\n const args = [\"-hide_banner\", \"-nostats\"];\n if (tag.mediaStart > 0) args.push(\"-ss\", String(tag.mediaStart));\n const sourceSpan = tag.duration === null ? null : tag.duration * (tag.playbackRate ?? 1);\n if (sourceSpan !== null && sourceSpan > 0) args.push(\"-t\", String(sourceSpan));\n args.push(\"-i\", file, \"-map\", \"0:a:0\", \"-vn\", \"-af\", \"ebur128=peak=true\", \"-f\", \"null\", \"-\");\n return args;\n}\n\nexport type MeasuredWindow = Pick<AudioTag, \"mediaStart\" | \"duration\"> &\n Partial<Pick<AudioTag, \"playbackRate\">>;\n\nexport async function measureAudio(\n ffmpegPath: string,\n file: string,\n tag: MeasuredWindow,\n): Promise<LoudnessMeasurement> {\n const result = await execFileAsync(ffmpegPath, loudnessMeasureArgs(file, tag), {\n encoding: \"utf8\",\n maxBuffer: 16 * 1024 * 1024,\n timeout: FFMPEG_TIMEOUT_MS,\n windowsHide: true,\n });\n return parseEbur128Summary(result.stderr);\n}\n\nexport function requiredFfmpeg(): string {\n const ffmpegPath = findFfBinary(\"ffmpeg\", { configuredMustExist: true });\n if (!ffmpegPath) throw new Error(\"FFmpeg is required to measure integrated loudness\");\n return ffmpegPath;\n}\n\nexport const DEFAULT_TARGET_LUFS = -16;\nexport const NORMALIZE_TRUE_PEAK_CEILING_DBFS = -1.5;\n/** EBU R128's absolute gate: a window this quiet has no integrated loudness to match. */\nconst SILENCE_LUFS = -70;\n\nexport type LoudnessLimit = \"gain-ceiling\" | \"true-peak\";\n\nexport interface AbsoluteLoudnessPlan {\n targetId: string;\n targetLufs: number;\n sourceLufs: number;\n previousVolume: number;\n volume: number;\n gainDb: number;\n changeDb: number;\n projectedLufs: number;\n projectedTruePeakDbfs: number;\n limitedBy: LoudnessLimit | null;\n}\n\n/**\n * The authored gain that brings one clip's played window to an absolute\n * loudness. Unlike reference matching it never refuses: past the +12 dB\n * authoring ceiling or the true-peak ceiling it applies the most that fits and\n * names which limit stopped it.\n */\nexport function absoluteLoudnessPlan(\n track: NormalizationTrack,\n targetLufs: number = DEFAULT_TARGET_LUFS,\n): AbsoluteLoudnessPlan {\n if (track.integratedLufs <= SILENCE_LUFS) {\n throw new Error(`#${track.id} is silent in the played window; there is nothing to normalize`);\n }\n const wantedGainDb = targetLufs - track.integratedLufs;\n const peakRoomDb = NORMALIZE_TRUE_PEAK_CEILING_DBFS - track.truePeakDbfs;\n const limits: Array<[LoudnessLimit | null, number]> = [\n [null, wantedGainDb],\n [\"gain-ceiling\", MAX_AUDIO_GAIN_DB],\n [\"true-peak\", peakRoomDb],\n ];\n const [limitedBy, appliedGainDb] = limits.reduce((lowest, candidate) =>\n candidate[1] < lowest[1] - 1e-9 ? candidate : lowest,\n );\n const previousGainDb = track.volume > 0 ? gainDb(track.volume) : 0;\n return {\n targetId: track.id,\n targetLufs,\n sourceLufs: track.integratedLufs,\n previousVolume: track.volume,\n volume: 10 ** (appliedGainDb / 20),\n gainDb: appliedGainDb,\n changeDb: appliedGainDb - previousGainDb,\n projectedLufs: track.integratedLufs + appliedGainDb,\n projectedTruePeakDbfs: track.truePeakDbfs + appliedGainDb,\n limitedBy,\n };\n}\n","import { existsSync } from \"node:fs\";\nimport { decodedUrlPath, decodeWellFormedEscapes } from \"@hyperframes/parsers/asset-paths\";\nimport { resolveWithinProject } from \"./safePath.js\";\nexport { decodeWellFormedEscapes } from \"@hyperframes/parsers/asset-paths\";\n\n// The decoded path after `route` (\"projects/:id/preview\", \"composition\"), cut by segment from the raw URL:\n// Hono's c.req.path leaves %40 %25 %23 %26 %3F encoded, so cutting a decoded prefix out of it misses.\nexport function requestSubPath(url: string, route: string): string {\n const routeSegments = route.split(\"/\");\n const segments = new URL(url).pathname.split(\"/\");\n const start = segments.indexOf(routeSegments[0] ?? \"\");\n return decodeWellFormedEscapes(segments.slice(start + routeSegments.length).join(\"/\"));\n}\n\n// A project file a request names: the literal name when that file exists, otherwise the field read as a URL.\nexport function requestedProjectPath(projectDir: string, field: string): string {\n const trimmed = field.trim().replace(/^[.]\\//, \"\");\n const named = resolveWithinProject(projectDir, trimmed);\n return named && existsSync(named) ? trimmed : decodedUrlPath(trimmed);\n}\n"],"mappings":";;;;;AAAA,SAAS,gBAAgB;AACzB,SAAS,YAAY,UAAU,eAAe;AAC9C,SAAS,iBAAiB;AAC1B,SAAS,6BAA6B;AACtC,SAAS,iBAAiB,yBAAyB;AACnD,SAAS,oBAAoB;AAC7B,SAAS,8BAA8B;;;ACNvC,SAAS,kBAAkB;AAC3B,SAAS,gBAAgB,+BAA+B;AAExD,SAAS,2BAAAA,gCAA+B;AAIjC,SAAS,eAAe,KAAa,OAAuB;AACjE,QAAM,gBAAgB,MAAM,MAAM,GAAG;AACrC,QAAM,WAAW,IAAI,IAAI,GAAG,EAAE,SAAS,MAAM,GAAG;AAChD,QAAM,QAAQ,SAAS,QAAQ,cAAc,CAAC,KAAK,EAAE;AACrD,SAAO,wBAAwB,SAAS,MAAM,QAAQ,cAAc,MAAM,EAAE,KAAK,GAAG,CAAC;AACvF;AAGO,SAAS,qB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AgB;AAAA,IAC/B,QAAQ;AAAA,IACR,UAAU,gBAAgB;AAAA,IAC1B,eAAe,MAAM,iBAAiB;AAAA,IACtC,uBAAuB,MAAM,eAAe;AAAA,IAC5C;AAAA,EACF;AACF;","names":["decodeWellFormedEscapes"]}
|
|
@@ -2,7 +2,7 @@ import {
|
|
|
2
2
|
PROXY_VARIANT_CONFIG,
|
|
3
3
|
probeFirstFrameColour,
|
|
4
4
|
probeMediaMetadata
|
|
5
|
-
} from "./chunk-
|
|
5
|
+
} from "./chunk-RN33UALN.js";
|
|
6
6
|
import {
|
|
7
7
|
mkdirWithinProject,
|
|
8
8
|
realProjectRoot,
|
|
@@ -235,31 +235,67 @@ function getProxyCachePath(projectDir, absoluteSourcePath, variant = "h264") {
|
|
|
235
235
|
variant
|
|
236
236
|
);
|
|
237
237
|
}
|
|
238
|
+
var ProxyDroppedError = class extends ProxyTranscodeError {
|
|
239
|
+
constructor() {
|
|
240
|
+
super("media proxy copy dropped: every caller left before it started", null, "");
|
|
241
|
+
this.name = "ProxyDroppedError";
|
|
242
|
+
}
|
|
243
|
+
};
|
|
238
244
|
var activeTranscodes = 0;
|
|
239
245
|
var waitQueue = [];
|
|
240
|
-
function
|
|
246
|
+
function enqueue(job) {
|
|
247
|
+
const firstNormal = job.priority ? waitQueue.findIndex((queued) => !queued.priority) : -1;
|
|
248
|
+
if (firstNormal === -1) waitQueue.push(job);
|
|
249
|
+
else waitQueue.splice(firstNormal, 0, job);
|
|
250
|
+
}
|
|
251
|
+
function dequeue(job) {
|
|
252
|
+
const index = waitQueue.indexOf(job);
|
|
253
|
+
if (index !== -1) waitQueue.splice(index, 1);
|
|
254
|
+
}
|
|
255
|
+
function acquireSlot(job) {
|
|
256
|
+
if (activeTranscodes < MAX_CONCURRENT_TRANSCODES) {
|
|
257
|
+
activeTranscodes++;
|
|
258
|
+
return Promise.resolve();
|
|
259
|
+
}
|
|
241
260
|
return new Promise((resolveSlot, reject) => {
|
|
242
|
-
|
|
243
|
-
|
|
261
|
+
job.queued = {
|
|
262
|
+
start: () => {
|
|
263
|
+
job.queued = void 0;
|
|
244
264
|
activeTranscodes++;
|
|
245
265
|
resolveSlot();
|
|
246
|
-
}
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
266
|
+
},
|
|
267
|
+
drop: () => {
|
|
268
|
+
job.queued = void 0;
|
|
269
|
+
dequeue(job);
|
|
270
|
+
forget(job);
|
|
271
|
+
reject(new ProxyDroppedError());
|
|
252
272
|
}
|
|
253
273
|
};
|
|
254
|
-
|
|
274
|
+
enqueue(job);
|
|
255
275
|
});
|
|
256
276
|
}
|
|
277
|
+
function queueIsFull() {
|
|
278
|
+
return activeTranscodes >= MAX_CONCURRENT_TRANSCODES && waitQueue.length >= MAX_QUEUED_TRANSCODES;
|
|
279
|
+
}
|
|
257
280
|
function releaseSlot() {
|
|
258
281
|
activeTranscodes--;
|
|
259
|
-
|
|
260
|
-
|
|
282
|
+
waitQueue.shift()?.queued?.start();
|
|
283
|
+
}
|
|
284
|
+
function prioritize(job) {
|
|
285
|
+
if (job.priority) return;
|
|
286
|
+
job.priority = true;
|
|
287
|
+
if (!job.queued) return;
|
|
288
|
+
dequeue(job);
|
|
289
|
+
enqueue(job);
|
|
290
|
+
}
|
|
291
|
+
function leave(job) {
|
|
292
|
+
job.callers--;
|
|
293
|
+
if (job.callers === 0) job.queued?.drop();
|
|
261
294
|
}
|
|
262
295
|
var inFlight = /* @__PURE__ */ new Map();
|
|
296
|
+
function forget(job) {
|
|
297
|
+
if (inFlight.get(job.cachePath)?.job === job) inFlight.delete(job.cachePath);
|
|
298
|
+
}
|
|
263
299
|
function maintainProxyCache(cacheDir) {
|
|
264
300
|
try {
|
|
265
301
|
cleanupProxyCache(cacheDir, { protectedPaths: new Set(inFlight.keys()) });
|
|
@@ -421,8 +457,8 @@ async function runFfmpeg(sourcePath, outputPath, variant, box) {
|
|
|
421
457
|
});
|
|
422
458
|
});
|
|
423
459
|
}
|
|
424
|
-
async function transcodeToCache(projectDir, absoluteSourcePath, cachePath, variant, box) {
|
|
425
|
-
await acquireSlot();
|
|
460
|
+
async function transcodeToCache(job, projectDir, absoluteSourcePath, cachePath, variant, box) {
|
|
461
|
+
await acquireSlot(job);
|
|
426
462
|
try {
|
|
427
463
|
if (existsSync2(cachePath)) return cachePath;
|
|
428
464
|
const cacheDir = dirname(cachePath);
|
|
@@ -440,14 +476,15 @@ async function transcodeToCache(projectDir, absoluteSourcePath, cachePath, varia
|
|
|
440
476
|
releaseSlot();
|
|
441
477
|
}
|
|
442
478
|
}
|
|
443
|
-
var
|
|
479
|
+
var proxyActivity = 0;
|
|
444
480
|
function proxyActivityMark(projectDir) {
|
|
445
|
-
if (!existsSync2(projectDir)) return String(
|
|
481
|
+
if (!existsSync2(projectDir)) return String(proxyActivity);
|
|
446
482
|
const cacheDir = join2(realpath(projectDir), CACHE_DIR_NAME) + sep;
|
|
447
483
|
for (const cachePath of inFlight.keys()) if (cachePath.startsWith(cacheDir)) return null;
|
|
448
|
-
return String(
|
|
484
|
+
return String(proxyActivity);
|
|
449
485
|
}
|
|
450
|
-
async function resolveProxy(projectDir, absoluteSourcePath, variant = "h264", box) {
|
|
486
|
+
async function resolveProxy(projectDir, absoluteSourcePath, variant = "h264", box, options = {}) {
|
|
487
|
+
options.signal?.throwIfAborted();
|
|
451
488
|
const source = canonicalizeProxySource(projectDir, absoluteSourcePath);
|
|
452
489
|
const cachePath = getCanonicalProxyCachePath(source, variant, box);
|
|
453
490
|
if (existsSync2(cachePath)) {
|
|
@@ -460,17 +497,48 @@ async function resolveProxy(projectDir, absoluteSourcePath, variant = "h264", bo
|
|
|
460
497
|
if (rememberedFailure.expiresAt > Date.now()) throw rememberedFailure.error;
|
|
461
498
|
failedTranscodes.delete(cachePath);
|
|
462
499
|
}
|
|
463
|
-
|
|
464
|
-
if (
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
500
|
+
let entry = inFlight.get(cachePath);
|
|
501
|
+
if (!entry) {
|
|
502
|
+
if (!options.priority && queueIsFull()) {
|
|
503
|
+
proxyActivity += 1;
|
|
504
|
+
throw new ProxyCapacityError();
|
|
505
|
+
}
|
|
506
|
+
const job = {
|
|
507
|
+
cachePath,
|
|
508
|
+
priority: options.priority === true,
|
|
509
|
+
callers: 0
|
|
510
|
+
};
|
|
511
|
+
const promise = transcodeToCache(
|
|
512
|
+
job,
|
|
513
|
+
source.projectDir,
|
|
514
|
+
source.sourcePath,
|
|
515
|
+
cachePath,
|
|
516
|
+
variant,
|
|
517
|
+
box
|
|
518
|
+
).catch((err) => {
|
|
519
|
+
if (!(err instanceof ProxyDroppedError)) rememberFailure(cachePath, err);
|
|
520
|
+
throw err;
|
|
521
|
+
}).finally(() => {
|
|
522
|
+
forget(job);
|
|
523
|
+
proxyActivity += 1;
|
|
524
|
+
});
|
|
525
|
+
entry = { promise, job };
|
|
526
|
+
inFlight.set(cachePath, entry);
|
|
527
|
+
}
|
|
528
|
+
if (options.priority) prioritize(entry.job);
|
|
529
|
+
return joinJob(entry.promise, entry.job, options.signal);
|
|
530
|
+
}
|
|
531
|
+
function joinJob(promise, job, signal) {
|
|
532
|
+
job.callers++;
|
|
533
|
+
if (!signal) return promise;
|
|
534
|
+
return new Promise((resolveJoin, rejectJoin) => {
|
|
535
|
+
const onAbort = () => {
|
|
536
|
+
leave(job);
|
|
537
|
+
rejectJoin(signal.reason);
|
|
538
|
+
};
|
|
539
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
540
|
+
promise.finally(() => signal.removeEventListener("abort", onAbort)).then(resolveJoin, rejectJoin);
|
|
471
541
|
});
|
|
472
|
-
inFlight.set(cachePath, promise);
|
|
473
|
-
return promise;
|
|
474
542
|
}
|
|
475
543
|
|
|
476
544
|
export {
|
|
@@ -491,4 +559,4 @@ export {
|
|
|
491
559
|
proxyActivityMark,
|
|
492
560
|
resolveProxy
|
|
493
561
|
};
|
|
494
|
-
//# sourceMappingURL=chunk-
|
|
562
|
+
//# sourceMappingURL=chunk-AZBGTB3N.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/helpers/proxyTranscoder.ts","../src/helpers/proxyCache.ts"],"sourcesContent":["import { spawn } from \"node:child_process\";\nimport { createHash, randomUUID } from \"node:crypto\";\nimport { existsSync, renameSync, statSync, unlinkSync, utimesSync } from \"node:fs\";\nimport { basename, dirname, isAbsolute, join, relative, resolve, sep } from \"node:path\";\nimport {\n formatPreviewProxyBox,\n hdrToSdrToneMapFilter,\n type PreviewProxyBox,\n} from \"@hyperframes/core\";\nimport { findFfBinary } from \"@hyperframes/parsers/ff-binaries\";\nimport { probeFirstFrameColour, probeMediaMetadata } from \"./mediaMetadata.js\";\nimport { cleanupProxyCache } from \"./proxyCache.js\";\nimport { PROXY_VARIANT_CONFIG, type ProxyVariant } from \"./mediaCodecMap.js\";\nimport { mkdirWithinProject, realpath, realProjectRoot } from \"./safePath.js\";\n\n/**\n * Transcodes browser-hostile local video sources (HEVC, ProRes, ...) into a\n * cached, seekable authoring proxy. Consumed by the preview/play/static\n * project routes (U3/U4) to serve a `?hf-proxy=` request; never used on\n * the render path (render always sees the original file).\n *\n * A started ffmpeg child is never killed for one caller: every caller of a cache\n * key shares it (in-flight dedupe below). A caller's `signal` only detaches that\n * caller, and drops the copy while it is still queued with no caller left.\n */\n\nexport const PROXY_PARAMS_VERSION = \"v5\";\n\nexport const CACHE_DIR_NAME = \".transcode-cache\";\n\nfunction boundedEnvInteger(name: string, fallback: number, min: number, max: number): number {\n const raw = process.env[name]?.trim();\n if (!raw) return fallback;\n const parsed = Number(raw);\n return Number.isSafeInteger(parsed) && parsed >= min && parsed <= max ? parsed : fallback;\n}\n\n// ffmpeg is internally multithreaded, so two concurrent proxy encodes already\n// saturate a typical laptop. Operators of shared/large machines may tune the\n// bounded values without patching the package; invalid values fail safe.\nconst MAX_CONCURRENT_TRANSCODES = boundedEnvInteger(\"HYPERFRAMES_PROXY_MAX_CONCURRENCY\", 2, 1, 16);\nconst MAX_QUEUED_TRANSCODES = boundedEnvInteger(\"HYPERFRAMES_PROXY_MAX_QUEUE\", 8, 0, 256);\n\nconst STDERR_TAIL_MAX_CHARS = 4000;\nexport const TRANSCODE_TIMEOUT_MS = 15 * 60 * 1000;\nconst FAILURE_CACHE_TTL_MS = 60 * 1000;\nexport const PROXY_PENDING_RETRY_AFTER_SECONDS = 2;\nconst ENVIRONMENT_FAILURE_TTL_MS = 5 * PROXY_PENDING_RETRY_AFTER_SECONDS * 1000;\nconst MAX_FAILURE_CACHE_ENTRIES = 128;\nexport const DEFAULT_PROXY_WAIT_TIMEOUT_MS = 2 * 60 * 1000;\n\nexport class ProxyTranscodeError extends Error {\n readonly exitCode: number | null;\n readonly stderrTail: string;\n\n constructor(message: string, exitCode: number | null, stderrTail: string) {\n super(message);\n this.name = \"ProxyTranscodeError\";\n this.exitCode = exitCode;\n this.stderrTail = stderrTail;\n }\n}\n\n/** \"ffmpeg isn't installed\" — an environment condition, not a per-source\n * failure, so the negative cache below keeps it only briefly\n * (installing ffmpeg mid-session must recover without a server restart). */\nclass FfmpegUnavailableError extends ProxyTranscodeError {\n constructor() {\n super(\"ffmpeg binary not found\", null, \"\");\n }\n}\n\nexport class FfmpegMissingFilterError extends ProxyTranscodeError {\n constructor() {\n super(\n \"HDR proxying requires ffmpeg zscale/tonemap filters (libzimg); install an ffmpeg build with libzimg support\",\n null,\n \"\",\n );\n this.name = \"FfmpegMissingFilterError\";\n }\n}\n\nexport class ProxyCapacityError extends ProxyTranscodeError {\n constructor() {\n super(\"media proxy queue is full; retry shortly\", null, \"\");\n this.name = \"ProxyCapacityError\";\n }\n}\n\nexport class ProxySourceOutsideProjectError extends ProxyTranscodeError {\n constructor() {\n super(\"media proxy source must be addressed through the project\", null, \"\");\n this.name = \"ProxySourceOutsideProjectError\";\n }\n}\n\nexport class ProxyWaitTimeoutError extends ProxyTranscodeError {\n constructor(timeoutMs: number) {\n super(`media proxy did not become ready within ${timeoutMs}ms`, null, \"\");\n this.name = \"ProxyWaitTimeoutError\";\n }\n}\n\n/** Bounds one caller's wait without cancelling the shared in-flight ffmpeg\n * job. Other preview/publish callers still receive the completed cache entry. */\nexport async function waitForProxy<T>(\n promise: Promise<T>,\n timeoutMs = DEFAULT_PROXY_WAIT_TIMEOUT_MS,\n): Promise<T> {\n let timer: NodeJS.Timeout | undefined;\n try {\n return await Promise.race([\n promise,\n new Promise<never>((_resolve, reject) => {\n timer = setTimeout(() => reject(new ProxyWaitTimeoutError(timeoutMs)), timeoutMs);\n timer.unref();\n }),\n ]);\n } finally {\n if (timer) clearTimeout(timer);\n }\n}\n\n/**\n * Cache key inputs per the plan: project-relative source path (portable across\n * checkouts), canonical source identity (so retargeted external symlinks do\n * not reuse a proxy), mtime and file size (mtime alone can collide on\n * same-second re-exports on coarse-timestamp filesystems; size catches nearly\n * all such cases at zero cost), and a params version token so changing the\n * ffmpeg recipe below invalidates every cached proxy cleanly.\n */\ntype CanonicalProxySource = {\n projectDir: string;\n sourcePath: string;\n relativePath: string;\n cacheIdentity: string;\n};\n\nfunction canonicalizeProxySource(\n projectDir: string,\n absoluteSourcePath: string,\n): CanonicalProxySource {\n const requestedProjectDir = resolve(projectDir);\n const requestedSourcePath = resolve(absoluteSourcePath);\n const requestedRelativePath = relative(requestedProjectDir, requestedSourcePath);\n if (\n requestedRelativePath === \"..\" ||\n requestedRelativePath.startsWith(`..${sep}`) ||\n isAbsolute(requestedRelativePath)\n ) {\n throw new ProxySourceOutsideProjectError();\n }\n\n const canonicalProjectDir = realProjectRoot(projectDir);\n const canonicalSourcePath = realpath(absoluteSourcePath);\n const canonicalRelativePath = relative(canonicalProjectDir, canonicalSourcePath);\n const sourceIsInsideCanonicalProject =\n canonicalRelativePath !== \"..\" &&\n !canonicalRelativePath.startsWith(`..${sep}`) &&\n !isAbsolute(canonicalRelativePath);\n return {\n projectDir: canonicalProjectDir,\n sourcePath: canonicalSourcePath,\n relativePath: requestedRelativePath.normalize(\"NFC\"),\n // An external target needs a stable identity in addition to its project-local\n // symlink path, otherwise retargeting the link can reuse an unrelated proxy.\n cacheIdentity: (sourceIsInsideCanonicalProject\n ? canonicalRelativePath\n : canonicalSourcePath\n ).normalize(\"NFC\"),\n };\n}\n\nfunction buildProxyCacheKey(\n source: CanonicalProxySource,\n variant: ProxyVariant,\n box: PreviewProxyBox | undefined,\n): string {\n const stat = statSync(source.sourcePath);\n const size = box ? `\\0${formatPreviewProxyBox(box)}` : \"\";\n return createHash(\"sha256\")\n .update(\n `${source.relativePath}\\0${source.cacheIdentity}\\0${stat.mtimeMs}\\0${stat.size}\\0${PROXY_PARAMS_VERSION}\\0${variant}${size}`,\n )\n .digest(\"hex\");\n}\n\nfunction getCanonicalProxyCachePath(\n source: CanonicalProxySource,\n variant: ProxyVariant,\n box?: PreviewProxyBox,\n): string {\n const key = buildProxyCacheKey(source, variant, box);\n return join(\n source.projectDir,\n CACHE_DIR_NAME,\n `${key}${PROXY_VARIANT_CONFIG[variant].extension}`,\n );\n}\n\n/**\n * Computes the absolute path a proxy for this source would live at, without\n * transcoding anything. Route handlers use this to check cache state (e.g.\n * for ETag/If-None-Match) before deciding whether to await a transcode.\n */\nexport function getProxyCachePath(\n projectDir: string,\n absoluteSourcePath: string,\n variant: ProxyVariant = \"h264\",\n): string {\n return getCanonicalProxyCachePath(\n canonicalizeProxySource(projectDir, absoluteSourcePath),\n variant,\n );\n}\n\n// --- global concurrency limiter -------------------------------------------\n// ponytail: a counter + one wait queue is the whole semaphore. Priority copies\n// queue ahead of the rest and are never refused for a full queue, so a few\n// priority asks (the copy a viewer is waiting on) can exceed the cap.\n\n/** One copy per cache key, shared by every caller asking for it. */\ninterface ProxyJob {\n cachePath: string;\n priority: boolean;\n /** Callers still waiting; one without a signal never leaves, so its copy is always made. */\n callers: number;\n /** Set while the job waits for a slot. */\n queued?: { start: () => void; drop: () => void };\n}\n\nclass ProxyDroppedError extends ProxyTranscodeError {\n constructor() {\n super(\"media proxy copy dropped: every caller left before it started\", null, \"\");\n this.name = \"ProxyDroppedError\";\n }\n}\n\nlet activeTranscodes = 0;\nconst waitQueue: ProxyJob[] = [];\n\nfunction enqueue(job: ProxyJob): void {\n const firstNormal = job.priority ? waitQueue.findIndex((queued) => !queued.priority) : -1;\n if (firstNormal === -1) waitQueue.push(job);\n else waitQueue.splice(firstNormal, 0, job);\n}\n\nfunction dequeue(job: ProxyJob): void {\n const index = waitQueue.indexOf(job);\n if (index !== -1) waitQueue.splice(index, 1);\n}\n\nfunction acquireSlot(job: ProxyJob): Promise<void> {\n if (activeTranscodes < MAX_CONCURRENT_TRANSCODES) {\n activeTranscodes++;\n return Promise.resolve();\n }\n return new Promise((resolveSlot, reject) => {\n job.queued = {\n start: () => {\n job.queued = undefined;\n activeTranscodes++;\n resolveSlot();\n },\n drop: () => {\n job.queued = undefined;\n dequeue(job);\n forget(job);\n reject(new ProxyDroppedError());\n },\n };\n enqueue(job);\n });\n}\n\nfunction queueIsFull(): boolean {\n return activeTranscodes >= MAX_CONCURRENT_TRANSCODES && waitQueue.length >= MAX_QUEUED_TRANSCODES;\n}\n\nfunction releaseSlot(): void {\n activeTranscodes--;\n waitQueue.shift()?.queued?.start();\n}\n\nfunction prioritize(job: ProxyJob): void {\n if (job.priority) return;\n job.priority = true;\n if (!job.queued) return;\n dequeue(job);\n enqueue(job);\n}\n\nfunction leave(job: ProxyJob): void {\n job.callers--;\n if (job.callers === 0) job.queued?.drop();\n}\n\n// --- per-key in-flight dedupe ----------------------------------------------\n\nconst inFlight = new Map<string, { promise: Promise<string>; job: ProxyJob }>();\n\nfunction forget(job: ProxyJob): void {\n if (inFlight.get(job.cachePath)?.job === job) inFlight.delete(job.cachePath);\n}\n\nfunction maintainProxyCache(cacheDir: string): void {\n try {\n cleanupProxyCache(cacheDir, { protectedPaths: new Set(inFlight.keys()) });\n } catch (error) {\n // Cache maintenance must never turn a playable preview into an error.\n console.warn(\n `[media-proxy] cache cleanup failed: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n}\n\nfunction markCacheEntryUsed(cachePath: string): void {\n try {\n const now = new Date();\n utimesSync(cachePath, now, now);\n } catch {\n // A concurrent cleanup may have removed a stale entry after existsSync;\n // the normal miss path below will recreate it on the next request.\n }\n}\n\n// --- negative cache ---------------------------------------------------------\n// A source that failed to transcode fails again identically until the file\n// changes (the cache key embeds mtime+size, so a re-export invalidates this\n// naturally). Remembering the failure per key means repeated `?hf-proxy=`\n// requests for a broken asset rethrow instantly instead of respawning ffmpeg\n// on every retry the browser makes.\ninterface RememberedFailure {\n error: unknown;\n expiresAt: number;\n}\n\nconst failedTranscodes = new Map<string, RememberedFailure>();\n\nlet hdrFilterCheck: { ffmpegPath: string; promise: Promise<void> } | undefined;\n\nfunction ensureHdrFilters(ffmpegPath: string): Promise<void> {\n if (hdrFilterCheck?.ffmpegPath === ffmpegPath) return hdrFilterCheck.promise;\n const promise = new Promise<void>((resolveCheck, rejectCheck) => {\n const proc = spawn(ffmpegPath, [\"-hide_banner\", \"-filters\"], {\n stdio: [\"ignore\", \"pipe\", \"pipe\"],\n windowsHide: true,\n });\n let stdout = \"\";\n proc.stdout?.on(\"data\", (chunk: Buffer) => {\n stdout += chunk.toString();\n });\n proc.on(\"error\", () => rejectCheck(new FfmpegMissingFilterError()));\n proc.on(\"close\", (code) => {\n if (code !== 0 || !/\\bzscale\\b/.test(stdout) || !/\\btonemap\\b/.test(stdout)) {\n rejectCheck(new FfmpegMissingFilterError());\n } else {\n resolveCheck();\n }\n });\n });\n hdrFilterCheck = { ffmpegPath, promise };\n return promise;\n}\n\nfunction rememberFailure(cachePath: string, error: unknown): void {\n const ttlMs =\n error instanceof FfmpegUnavailableError || error instanceof FfmpegMissingFilterError\n ? ENVIRONMENT_FAILURE_TTL_MS\n : FAILURE_CACHE_TTL_MS;\n failedTranscodes.delete(cachePath);\n failedTranscodes.set(cachePath, { error, expiresAt: Date.now() + ttlMs });\n while (failedTranscodes.size > MAX_FAILURE_CACHE_ENTRIES) {\n const oldest = failedTranscodes.keys().next().value;\n if (oldest === undefined) break;\n failedTranscodes.delete(oldest);\n }\n}\n\n/** Test hook: forget remembered transcode failures (module state persists\n * across tests that don't reload the module). */\nexport function clearFailedTranscodesForTest(): void {\n failedTranscodes.clear();\n}\n\n/** Even dimensions; with a box, the source shrinks until its tighter side fills the box, never grows. */\nfunction proxyScaleFilter(box?: PreviewProxyBox): string {\n if (!box) return \"scale=trunc(iw/2)*2:trunc(ih/2)*2\";\n const factor = `min(1\\\\,max(${box.width}/iw\\\\,${box.height}/ih))`;\n const side = (d: string) => `min(trunc(${d}/2)*2\\\\,ceil(${d}*${factor}/2)*2)`;\n return `scale=${side(\"iw\")}:${side(\"ih\")}`;\n}\n\nasync function runFfmpeg(\n sourcePath: string,\n outputPath: string,\n variant: ProxyVariant,\n box: PreviewProxyBox | undefined,\n): Promise<void> {\n const metadata = await probeMediaMetadata(sourcePath);\n const ffmpegPath = findFfBinary(\"ffmpeg\", { configuredMustExist: true });\n if (!ffmpegPath) {\n throw new FfmpegUnavailableError();\n }\n const keepsAlpha = variant === \"vp8\";\n const { hdrTransfer } = metadata.color;\n const toneMap = (hdrTransfer === \"pq\" || hdrTransfer === \"hlg\") && !keepsAlpha;\n if (toneMap) await ensureHdrFilters(ffmpegPath);\n const firstFrame = toneMap ? await probeFirstFrameColour(sourcePath) : {};\n const evenScale = proxyScaleFilter(box);\n const pixelFormat = keepsAlpha ? \"yuva420p\" : \"yuv420p\";\n // The tone map ends in RGB; older ffmpeg (seen on 5.1) converts it with BT.601 unless the matrix is named.\n const videoFilter = toneMap\n ? [\n hdrToSdrToneMapFilter(metadata.color, firstFrame),\n `${evenScale}:out_color_matrix=bt709:out_range=tv`,\n `format=${pixelFormat}`,\n ].join(\",\")\n : [evenScale, `format=${pixelFormat}`].join(\",\");\n\n return new Promise((resolvePromise, reject) => {\n const commonArgs = [\"-y\", \"-i\", sourcePath, \"-vf\", videoFilter];\n const h264Args = [\n \"-c:v\",\n \"libx264\",\n \"-profile:v\",\n \"high\",\n \"-pix_fmt\",\n \"yuv420p\",\n \"-colorspace\",\n \"bt709\",\n \"-color_primaries\",\n \"bt709\",\n \"-color_trc\",\n \"bt709\",\n \"-crf\",\n \"18\",\n \"-preset\",\n \"veryfast\",\n \"-c:a\",\n \"aac\",\n \"-movflags\",\n \"+faststart\",\n ];\n const vp8Args = [\n \"-c:v\",\n \"libvpx\",\n \"-b:v\",\n \"0\",\n \"-crf\",\n \"23\",\n \"-deadline\",\n \"good\",\n \"-pix_fmt\",\n \"yuva420p\",\n \"-colorspace\",\n \"bt709\",\n \"-color_primaries\",\n \"bt709\",\n \"-color_trc\",\n \"bt709\",\n \"-cpu-used\",\n \"4\",\n \"-auto-alt-ref\",\n \"0\",\n \"-metadata:s:v:0\",\n \"alpha_mode=1\",\n \"-ac\",\n \"2\",\n \"-c:a\",\n \"libopus\",\n ];\n const args = [...commonArgs, ...(variant === \"vp8\" ? vp8Args : h264Args), outputPath];\n\n // Hard ceiling so a hung ffmpeg can never permanently occupy one of the\n // global transcode slots: the child is killed and the slot released via\n // the caller's finally. Generous because long assets transcode at\n // roughly real time; a healthy encode of any authoring asset fits.\n const proc = spawn(ffmpegPath, args, {\n stdio: [\"ignore\", \"ignore\", \"pipe\"],\n timeout: TRANSCODE_TIMEOUT_MS,\n killSignal: \"SIGKILL\",\n windowsHide: true,\n });\n let stderrTail = \"\";\n proc.stderr?.on(\"data\", (chunk: Buffer) => {\n stderrTail = (stderrTail + chunk.toString()).slice(-STDERR_TAIL_MAX_CHARS);\n });\n proc.on(\"error\", (err) => {\n reject(new ProxyTranscodeError(`failed to spawn ffmpeg: ${err.message}`, null, stderrTail));\n });\n proc.on(\"close\", (code, signal) => {\n if (code === 0) {\n resolvePromise();\n } else if (signal) {\n reject(\n new ProxyTranscodeError(\n `ffmpeg killed by ${signal} (timeout ${TRANSCODE_TIMEOUT_MS}ms or external kill)`,\n null,\n stderrTail,\n ),\n );\n } else {\n reject(new ProxyTranscodeError(`ffmpeg exited with code ${code}`, code, stderrTail));\n }\n });\n });\n}\n\nasync function transcodeToCache(\n job: ProxyJob,\n projectDir: string,\n absoluteSourcePath: string,\n cachePath: string,\n variant: ProxyVariant,\n box: PreviewProxyBox | undefined,\n): Promise<string> {\n await acquireSlot(job);\n try {\n // Another caller may have finished (or a pre-warm beat us) while queued.\n if (existsSync(cachePath)) return cachePath;\n\n const cacheDir = dirname(cachePath);\n mkdirWithinProject(projectDir, cacheDir);\n const tempPath = join(cacheDir, `.tmp-${randomUUID()}-${basename(cachePath)}`);\n try {\n await runFfmpeg(absoluteSourcePath, tempPath, variant, box);\n renameSync(tempPath, cachePath);\n maintainProxyCache(cacheDir);\n return cachePath;\n } finally {\n // No partial files: if anything above threw, remove whatever ffmpeg\n // may have partially written under the temp name.\n if (existsSync(tempPath)) unlinkSync(tempPath);\n }\n } finally {\n releaseSlot();\n }\n}\n\nlet proxyActivity = 0;\n\n/** Null while this project has a copy in progress; otherwise a mark that moves when any copy finishes or is refused. */\nexport function proxyActivityMark(projectDir: string): string | null {\n if (!existsSync(projectDir)) return String(proxyActivity);\n const cacheDir = join(realpath(projectDir), CACHE_DIR_NAME) + sep;\n for (const cachePath of inFlight.keys()) if (cachePath.startsWith(cacheDir)) return null;\n return String(proxyActivity);\n}\n\n/**\n * Resolves the cached proxy variant for `absoluteSourcePath`, transcoding it at\n * most once per cache key. Concurrent calls for the same key (including a\n * pre-warm call racing an element-triggered one) share one ffmpeg child and\n * one promise; calls for different keys queue through the global concurrency\n * limiter above. Throws `ProxyTranscodeError` on failure (missing ffmpeg or a\n * nonzero exit) — callers (route handlers) decide how to surface that (502).\n * A `box` makes a smaller preview-only copy with its own cache entry; without\n * one the copy keeps the source size (CLI play, static servers, publish).\n * `priority` moves the copy ahead of every normal queued copy; a `signal`\n * lets this caller leave (see the detachment note at the top of this file).\n */\nexport async function resolveProxy(\n projectDir: string,\n absoluteSourcePath: string,\n variant: ProxyVariant = \"h264\",\n box?: PreviewProxyBox,\n options: ResolveProxyOptions = {},\n): Promise<string> {\n options.signal?.throwIfAborted();\n const source = canonicalizeProxySource(projectDir, absoluteSourcePath);\n const cachePath = getCanonicalProxyCachePath(source, variant, box);\n if (existsSync(cachePath)) {\n markCacheEntryUsed(cachePath);\n maintainProxyCache(dirname(cachePath));\n return cachePath;\n }\n\n const rememberedFailure = failedTranscodes.get(cachePath);\n if (rememberedFailure) {\n if (rememberedFailure.expiresAt > Date.now()) throw rememberedFailure.error;\n failedTranscodes.delete(cachePath);\n }\n\n let entry = inFlight.get(cachePath);\n if (!entry) {\n if (!options.priority && queueIsFull()) {\n proxyActivity += 1;\n throw new ProxyCapacityError();\n }\n const job: ProxyJob = {\n cachePath,\n priority: options.priority === true,\n callers: 0,\n };\n const promise = transcodeToCache(\n job,\n source.projectDir,\n source.sourcePath,\n cachePath,\n variant,\n box,\n )\n .catch((err: unknown) => {\n if (!(err instanceof ProxyDroppedError)) rememberFailure(cachePath, err);\n throw err;\n })\n .finally(() => {\n forget(job);\n proxyActivity += 1;\n });\n entry = { promise, job };\n inFlight.set(cachePath, entry);\n }\n if (options.priority) prioritize(entry.job);\n return joinJob(entry.promise, entry.job, options.signal);\n}\n\nexport interface ResolveProxyOptions {\n priority?: boolean;\n signal?: AbortSignal;\n}\n\nfunction joinJob(promise: Promise<string>, job: ProxyJob, signal?: AbortSignal): Promise<string> {\n job.callers++;\n if (!signal) return promise;\n return new Promise((resolveJoin, rejectJoin) => {\n const onAbort = (): void => {\n leave(job);\n rejectJoin(signal.reason);\n };\n signal.addEventListener(\"abort\", onAbort, { once: true });\n promise\n .finally(() => signal.removeEventListener(\"abort\", onAbort))\n .then(resolveJoin, rejectJoin);\n });\n}\n","import { existsSync, readdirSync, statSync, unlinkSync } from \"node:fs\";\nimport { extname, join } from \"node:path\";\nimport { PROXY_VARIANT_CONFIG } from \"./mediaCodecMap.js\";\n\nconst DEFAULT_MAX_BYTES = 10 * 1024 * 1024 * 1024;\nconst DEFAULT_STALE_TEMP_MS = 60 * 60 * 1000;\nconst DEFAULT_MIN_SWEEP_INTERVAL_MS = 5 * 60 * 1000;\nconst PROXY_EXTENSIONS: ReadonlySet<string> = new Set(\n Object.values(PROXY_VARIANT_CONFIG).map(({ extension }) => extension),\n);\nconst TRANSCODER_PROXY_NAME = /^[0-9a-f]{64}\\.\\w+$/;\nconst TRANSCODER_TEMP_NAME = /^\\.tmp-[0-9a-f-]{36}-[0-9a-f]{64}\\.\\w+$/;\n\nexport interface ProxyCacheCleanupOptions {\n maxBytes?: number;\n maxIdleMs?: number;\n staleTempMs?: number;\n minSweepIntervalMs?: number;\n protectedPaths?: ReadonlySet<string>;\n now?: number;\n dryRun?: boolean;\n}\n\nexport interface ProxyCacheCleanupResult {\n removed: string[];\n bytesBefore: number;\n bytesAfter: number;\n skipped: boolean;\n}\n\ninterface CacheEntry {\n path: string;\n size: number;\n modifiedAt: number;\n protected: boolean;\n}\n\nconst lastSweepAt = new Map<string, number>();\n\nfunction positiveEnvNumber(name: string, fallback: number): number {\n const parsed = Number(process.env[name]);\n return Number.isFinite(parsed) && parsed > 0 ? parsed : fallback;\n}\n\nfunction proxyCacheCleanupDefaults(): Required<\n Pick<ProxyCacheCleanupOptions, \"maxBytes\" | \"maxIdleMs\" | \"staleTempMs\" | \"minSweepIntervalMs\">\n> {\n return {\n maxBytes: positiveEnvNumber(\"HYPERFRAMES_PROXY_CACHE_MAX_BYTES\", DEFAULT_MAX_BYTES),\n maxIdleMs: positiveEnvNumber(\"HYPERFRAMES_PROXY_CACHE_MAX_IDLE_DAYS\", 30) * 24 * 60 * 60 * 1000,\n staleTempMs: positiveEnvNumber(\"HYPERFRAMES_PROXY_CACHE_STALE_TEMP_MS\", DEFAULT_STALE_TEMP_MS),\n minSweepIntervalMs: positiveEnvNumber(\n \"HYPERFRAMES_PROXY_CACHE_SWEEP_INTERVAL_MS\",\n DEFAULT_MIN_SWEEP_INTERVAL_MS,\n ),\n };\n}\n\nfunction shouldSkipSweep(cacheDir: string, now: number, minSweepIntervalMs: number): boolean {\n const previousSweep = lastSweepAt.get(cacheDir);\n if (previousSweep !== undefined && now - previousSweep < minSweepIntervalMs) return true;\n lastSweepAt.set(cacheDir, now);\n return false;\n}\n\nfunction readCacheInventory(\n cacheDir: string,\n protectedPaths: ReadonlySet<string>,\n now: number,\n staleTempMs: number,\n): { entries: CacheEntry[]; staleTemps: CacheEntry[] } {\n const entries: CacheEntry[] = [];\n const staleTemps: CacheEntry[] = [];\n for (const dirent of readdirSync(cacheDir, { withFileTypes: true })) {\n if (!dirent.isFile()) continue;\n const path = join(cacheDir, dirent.name);\n const stat = statSync(path);\n const entry = {\n path,\n size: stat.size,\n modifiedAt: stat.mtimeMs,\n protected: protectedPaths.has(path),\n };\n if (TRANSCODER_TEMP_NAME.test(dirent.name)) {\n if (now - stat.mtimeMs >= staleTempMs) staleTemps.push(entry);\n } else if (\n TRANSCODER_PROXY_NAME.test(dirent.name) &&\n PROXY_EXTENSIONS.has(extname(dirent.name))\n ) {\n entries.push(entry);\n }\n }\n const oldestFirst = (a: CacheEntry, b: CacheEntry): number =>\n a.modifiedAt - b.modifiedAt || a.path.localeCompare(b.path);\n entries.sort(oldestFirst);\n staleTemps.sort(oldestFirst);\n return { entries, staleTemps };\n}\n\nfunction evictCacheEntries(\n entries: CacheEntry[],\n staleTemps: CacheEntry[],\n now: number,\n maxIdleMs: number,\n maxBytes: number,\n dryRun: boolean,\n): Omit<ProxyCacheCleanupResult, \"skipped\"> {\n const bytesBefore = entries.reduce((total, entry) => total + entry.size, 0);\n let bytesAfter = bytesBefore;\n const removed: string[] = [];\n const remove = (entry: CacheEntry, countsTowardBudget: boolean): void => {\n if (!dryRun) unlinkSync(entry.path);\n removed.push(entry.path);\n if (countsTowardBudget) bytesAfter -= entry.size;\n };\n\n for (const entry of staleTemps) remove(entry, false);\n const kept: CacheEntry[] = [];\n for (const entry of entries) {\n if (!entry.protected && now - entry.modifiedAt >= maxIdleMs) remove(entry, true);\n else kept.push(entry);\n }\n for (const entry of kept) {\n if (bytesAfter <= maxBytes) break;\n if (!entry.protected && existsSync(entry.path)) remove(entry, true);\n }\n return { removed, bytesBefore, bytesAfter };\n}\n\n/**\n * Opportunistically bounds a project's transparent-proxy cache. Cleanup is\n * synchronous because callers already perform filesystem bookkeeping on the\n * preview request path, but rate limiting keeps the directory scan off the\n * hot path. Errors intentionally bubble so callers can warn without turning\n * a cache-maintenance failure into a preview failure.\n */\nexport function cleanupProxyCache(\n cacheDir: string,\n options: ProxyCacheCleanupOptions = {},\n): ProxyCacheCleanupResult {\n const defaults = proxyCacheCleanupDefaults();\n const now = options.now ?? Date.now();\n const minSweepIntervalMs = options.minSweepIntervalMs ?? defaults.minSweepIntervalMs;\n if (shouldSkipSweep(cacheDir, now, minSweepIntervalMs)) {\n return { removed: [], bytesBefore: 0, bytesAfter: 0, skipped: true };\n }\n if (!existsSync(cacheDir)) {\n return { removed: [], bytesBefore: 0, bytesAfter: 0, skipped: false };\n }\n\n const maxBytes = options.maxBytes ?? defaults.maxBytes;\n const maxIdleMs = options.maxIdleMs ?? defaults.maxIdleMs;\n const staleTempMs = options.staleTempMs ?? defaults.staleTempMs;\n const protectedPaths = options.protectedPaths ?? new Set<string>();\n const { entries, staleTemps } = readCacheInventory(cacheDir, protectedPaths, now, staleTempMs);\n return {\n ...evictCacheEntries(entries, staleTemps, now, maxIdleMs, maxBytes, options.dryRun ?? false),\n skipped: false,\n };\n}\n"],"mappings":";;;;;;;;;;;;AAAA,SAAS,aAAa;AACtB,SAAS,YAAY,kBAAkB;AACvC,SAAS,cAAAA,aAAY,YAAY,YAAAC,WAAU,cAAAC,aAAY,kBAAkB;AACzE,SAAS,UAAU,SAAS,YAAY,QAAAC,OAAM,UAAU,SAAS,WAAW;AAC5E;AAAA,EACE;AAAA,EACA;AAAA,OAEK;AACP,SAAS,oBAAoB;;;ACT7B,SAAS,YAAY,aAAa,UAAU,kBAAkB;AAC9D,SAAS,SAAS,YAAY;AAG9B,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B,YAAM,GAAG;AACT,iBAAW,OAAO,MAAM;AAAA,IAC1B;AACA,WAAO,iBAAiB,SAAS,SAAS,EAAE,MAAM,KAAK,CAAC;AACxD,YACG,QAAQ,MAAM,OAAO,oBAAoB,SAAS,OAAO,CAAC,EAC1D,KAAK,aAAa,UAAU;AAAA,EACjC,CAAC;AACH;","names":["existsSync","statSync","unlinkSync","join","statSync","join","existsSync","unlinkSync"]}
|
|
@@ -3,15 +3,15 @@ import {
|
|
|
3
3
|
} from "./chunk-DTKK7TKL.js";
|
|
4
4
|
|
|
5
5
|
// src/helpers/mediaCodecMap.ts
|
|
6
|
-
import {
|
|
7
|
-
import {
|
|
6
|
+
import { scanHtmlOpeningTags, decodeAuthoredAttribute } from "@hyperframes/parsers";
|
|
7
|
+
import { statSync } from "fs";
|
|
8
|
+
import { sep } from "path";
|
|
8
9
|
import { rewriteAssetPath } from "@hyperframes/parsers/asset-paths";
|
|
9
10
|
import {
|
|
10
11
|
cleanAssetUrl,
|
|
11
12
|
isRemoteOrInlineUrl,
|
|
12
13
|
isUnresolvedAssetPlaceholder,
|
|
13
|
-
|
|
14
|
-
resolveLocalAssetCandidates
|
|
14
|
+
resolveExistingLocalAsset as resolveAsset
|
|
15
15
|
} from "@hyperframes/parsers/asset-resolution";
|
|
16
16
|
|
|
17
17
|
// src/helpers/mediaMetadata.ts
|
|
@@ -272,24 +272,22 @@ async function probeAssetCodec(filePath, runner, cache = defaultProbeCache) {
|
|
|
272
272
|
rememberProbeResult(cache, filePath, { target, mtimeMs: stat.mtimeMs, size: stat.size, facts });
|
|
273
273
|
return facts;
|
|
274
274
|
}
|
|
275
|
-
var VIDEO_SRC_RE = /<video\b[^>]*\bsrc\s*=\s*["']([^"']+)["'][^>]*>/gi;
|
|
276
275
|
function resolveExistingLocalAsset(projectDir, url) {
|
|
277
|
-
const
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
return { resolvedPath, rootRelativePathname: `/${rootRelative}` };
|
|
276
|
+
const asset = resolveAsset(projectDir, url);
|
|
277
|
+
if (!asset) return null;
|
|
278
|
+
return {
|
|
279
|
+
resolvedPath: asset.resolved,
|
|
280
|
+
rootRelativePathname: `/${asset.rootRelativePath.split(sep).join("/")}`
|
|
281
|
+
};
|
|
284
282
|
}
|
|
285
283
|
function collectLocalVideoAssets(projectDir, htmlSources) {
|
|
286
284
|
const candidates = /* @__PURE__ */ new Map();
|
|
287
285
|
for (const { html, compSrcPath } of htmlSources) {
|
|
288
|
-
const
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
const rawSrc =
|
|
286
|
+
for (const tag of scanHtmlOpeningTags(html)) {
|
|
287
|
+
if (tag.name !== "video" || !tag.closed) continue;
|
|
288
|
+
const attribute = tag.attributes.find((attr) => attr.name === "src");
|
|
289
|
+
if (attribute?.kind !== "value") continue;
|
|
290
|
+
const rawSrc = decodeAuthoredAttribute(attribute.value);
|
|
293
291
|
if (isUnresolvedAssetPlaceholder(rawSrc)) continue;
|
|
294
292
|
const src = cleanAssetUrl(rawSrc);
|
|
295
293
|
if (!src || isRemoteOrInlineUrl(src)) continue;
|
|
@@ -346,4 +344,4 @@ export {
|
|
|
346
344
|
probeAssetCodec,
|
|
347
345
|
scanProjectMediaCodecMap
|
|
348
346
|
};
|
|
349
|
-
//# sourceMappingURL=chunk-
|
|
347
|
+
//# sourceMappingURL=chunk-RN33UALN.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/helpers/mediaCodecMap.ts","../src/helpers/mediaMetadata.ts"],"sourcesContent":["import { scanHtmlOpeningTags, decodeAuthoredAttribute } from \"@hyperframes/parsers\";\nimport { statSync } from \"node:fs\";\nimport { realpath } from \"./safePath.js\";\nimport { sep } from \"node:path\";\nimport { rewriteAssetPath } from \"@hyperframes/parsers/asset-paths\";\nimport {\n cleanAssetUrl,\n isRemoteOrInlineUrl,\n isUnresolvedAssetPlaceholder,\n resolveExistingLocalAsset as resolveAsset,\n} from \"@hyperframes/parsers/asset-resolution\";\nimport { pixelFormatHasAlpha, probeMediaMetadata, type FfprobeRunner } from \"./mediaMetadata.js\";\n\n/**\n * One reusable answer to \"what codec is this asset, and is it browser-hostile?\",\n * built on top of `mediaMetadata.ts`'s ffprobe-backed prober so studio-server\n * probes each asset once instead of running a second prober.\n */\n\nexport interface AssetCodecFacts {\n codecName: string;\n browserHostile: boolean;\n /** Coarse `canPlayType()` input; `null` when not applicable (safe codec) or\n * when no representative mime exists (ProRes: browsers never decode it, so\n * the runtime always proxies rather than probing `canPlayType`). */\n representativeMime: string | null;\n /** Source carries an alpha channel (ffprobe pix_fmt). Alpha sources use a\n * VP8/WebM proxy so their transparency is preserved across Chromium builds. */\n hasAlpha: boolean;\n}\n\n/** Server-root-relative URL pathname -> that asset's codec facts. */\nexport type MediaCodecMap = Record<string, AssetCodecFacts>;\n\nexport interface BrowserHostileCodec {\n /** Coarse `canPlayType()` input; `null` when no representative mime exists\n * (ProRes: browsers never decode it, so the runtime always proxies rather\n * than probing `canPlayType`). */\n representativeMime: string | null;\n /**\n * Whether the server may transcode before any browser asks. True only where\n * no cross-platform decode exists, so some client is sure to need the\n * substitute; false where the first `?hf-proxy=` request can do it lazily.\n */\n prewarm: boolean;\n}\n\n/**\n * Browser-hostile codec table v1. One exported constant so extending it is a\n * one-line change. `ffprobe` cannot emit exact RFC 6381 codec strings, so\n * these `representativeMime` values are deliberately coarse (a false\n * positive costs one proxy transcode, never correctness; a false negative is\n * rescued by the runtime's reactive zero-videoWidth swap).\n */\nexport const BROWSER_HOSTILE_CODECS: Record<string, BrowserHostileCodec> = {\n // HEVC decode is platform-bound, not absent: macOS Chrome answers\n // canPlayType with \"probably\" and keeps the source, while Chrome on\n // Windows/Linux and Firefox everywhere need the substitute.\n hevc: { representativeMime: 'video/mp4; codecs=\"hvc1.1.6.L120.B0\"', prewarm: true },\n prores: { representativeMime: null, prewarm: true },\n // Every mainstream engine decodes AV1 and VP9, so canPlayType keeps the\n // original and only the rare browser that cannot pays for a transcode.\n av1: { representativeMime: 'video/mp4; codecs=\"av01.0.08M.08\"', prewarm: false },\n vp9: { representativeMime: 'video/webm; codecs=\"vp09.00.10.08\"', prewarm: false },\n};\n\n/** `Object.hasOwn` rather than a bare index: a codec named `constructor` or\n * `toString` would otherwise resolve against `Object.prototype`. */\nfunction hostileCodecEntry(codecName: string): BrowserHostileCodec | undefined {\n return Object.hasOwn(BROWSER_HOSTILE_CODECS, codecName)\n ? BROWSER_HOSTILE_CODECS[codecName]\n : undefined;\n}\n\n/** The pre-warm gate: true only for codecs with no cross-platform browser\n * decode, so some client will ask. See `BrowserHostileCodec.prewarm`. */\nexport function shouldPrewarmProxy(facts: AssetCodecFacts): boolean {\n return hostileCodecEntry(facts.codecName)?.prewarm === true;\n}\n\n// Per process, and deliberately in one unit — a call to `resolveProxy` — so\n// the pair reads as a ratio. Summarised at exit on stderr, in the same\n// `[hyperframes:<area>] {json}` shape as `writeUrlDownloadTelemetry`.\nconst proxyDemand = { prewarmsRequested: 0, proxyRequests: 0 };\n\n/** Snapshot of this process's pre-warm demand counters. */\nexport function mediaProxyDemand(): { prewarmsRequested: number; proxyRequests: number } {\n return { ...proxyDemand };\n}\n\nfunction writeDemandLine(event: \"prewarm_requested\" | \"summary\"): void {\n try {\n process.stderr.write(\n `[hyperframes:media-proxy] ${JSON.stringify({ event, ...proxyDemand })}\\n`,\n );\n } catch {\n // Observability must never change proxy correctness.\n }\n}\n\n/** Mirrors `isGpuProbeDebugEnabled` in packages/engine/src/utils/gpuEncoder.ts. */\nfunction isMediaProxyDebugEnabled(): boolean {\n const value = process.env.HYPERFRAMES_DEBUG_MEDIA_PROXY;\n return value === \"1\" || value === \"true\";\n}\n\n// Registered on the first pre-warm rather than at import, so a process that\n// never pre-warms adds no handler and prints nothing. Sync-only, mirroring the\n// `process.on(\"exit\")` shutdown hooks in packages/cli/src/cli.ts:331 and\n// packages/cli/src/commands/preview.ts:1329.\nlet summaryHookInstalled = false;\n\n/**\n * One proxy asked for before any browser wanted it. \"Requested\", not\n * \"started\": a warm cache makes `resolveProxy` a no-op and this counter cannot\n * see that, so it is an upper bound on transcodes, not a measure of CPU. The\n * number it does answer exactly is the one that decides policy — a nonzero\n * count beside `proxyRequests: 0` means nothing ever redeemed the pre-warm.\n *\n * The per-asset line is debug-only: a composition with fifty hostile clips\n * would otherwise print fifty JSON lines into a clack-formatted terminal on\n * every re-render. The exit summary carries the same numbers unconditionally.\n */\nexport function recordProxyPrewarm(): void {\n proxyDemand.prewarmsRequested++;\n if (!summaryHookInstalled) {\n summaryHookInstalled = true;\n process.once(\"exit\", () => writeDemandLine(\"summary\"));\n }\n if (isMediaProxyDebugEnabled()) writeDemandLine(\"prewarm_requested\");\n}\n\n/** One proxy resolved for a browser that asked, counted on the path that calls\n * `resolveProxy` so it shares a unit with `prewarmsRequested`. A 304 does not\n * count; an unconditional Range refill still does, so read it as zero versus\n * nonzero. Never logged per event, only in the exit summary. */\nexport function recordProxyRequest(): void {\n proxyDemand.proxyRequests++;\n}\n\nexport type ProxyVariant = \"h264\" | \"vp8\";\nexport type ProxyVariantRequest = ProxyVariant | \"auto\";\n\nexport const PROXY_VARIANT_CONFIG: Record<\n ProxyVariant,\n { extension: \".mp4\" | \".webm\"; contentType: \"video/mp4\" | \"video/webm\" }\n> = {\n h264: { extension: \".mp4\", contentType: \"video/mp4\" },\n vp8: { extension: \".webm\", contentType: \"video/webm\" },\n};\n\nexport function isProxyVariant(value: string): value is ProxyVariant {\n return Object.hasOwn(PROXY_VARIANT_CONFIG, value);\n}\n\nexport function isProxyVariantRequest(value: string): value is ProxyVariantRequest {\n return value === \"auto\" || isProxyVariant(value);\n}\n\nexport function proxyVariantFor(facts: AssetCodecFacts): ProxyVariant {\n return facts.hasAlpha ? \"vp8\" : \"h264\";\n}\n\nexport function resolveProxyVariantRequest(\n request: ProxyVariantRequest,\n facts: AssetCodecFacts,\n): ProxyVariant | null {\n const expected = proxyVariantFor(facts);\n return request === \"auto\" || request === expected ? expected : null;\n}\n\nexport type MediaProxyIneligibilityReason = \"browser_safe_codec\" | \"unknown_codec\";\n\nexport type MediaProxyEligibility =\n | { eligible: true }\n | { eligible: false; reason: MediaProxyIneligibilityReason };\n\n/** Single policy gate shared by proactive scans and on-demand proxy routes. */\nexport function decideMediaProxyEligibility(facts: AssetCodecFacts | null): MediaProxyEligibility {\n if (!facts) return { eligible: false, reason: \"unknown_codec\" };\n if (!facts.browserHostile) return { eligible: false, reason: \"browser_safe_codec\" };\n return { eligible: true };\n}\n\nfunction codecFactsFor(codecName: string, hasAlpha: boolean): AssetCodecFacts {\n const hostile = hostileCodecEntry(codecName);\n return {\n codecName,\n browserHostile: hostile !== undefined,\n representativeMime: hostile?.representativeMime ?? null,\n hasAlpha,\n };\n}\n\n/** `undefined` when ffprobe itself failed: no answer about the file, so nothing to cache. */\nasync function probeCodecFacts(\n filePath: string,\n runner?: FfprobeRunner,\n): Promise<AssetCodecFacts | null | undefined> {\n const metadata = runner\n ? await probeMediaMetadata(filePath, runner)\n : await probeMediaMetadata(filePath);\n if (metadata.probeError) return undefined;\n if (metadata.kind !== \"video\") return null;\n const codecName = metadata.color.codecName;\n if (!codecName) return null;\n return codecFactsFor(codecName, pixelFormatHasAlpha(metadata.color.pixelFormat));\n}\n\ninterface CachedAssetProbe {\n /** The file a symlinked path pointed at, so retargeting the link is a miss. */\n target: string;\n mtimeMs: number;\n size: number;\n facts: AssetCodecFacts | null;\n}\n\n/** Per (path, mtime) probe cache. Construct one per project/server lifetime\n * and reuse it across scans; a fresh instance defeats the caching benefit. */\nexport type MediaCodecProbeCache = Map<string, CachedAssetProbe>;\n\nexport function createMediaCodecProbeCache(): MediaCodecProbeCache {\n return new Map();\n}\n\n// Shared by every route and scan in this process that does not pass its own cache.\nconst defaultProbeCache: MediaCodecProbeCache = new Map();\nconst MAX_PROBE_CACHE_ENTRIES = 512;\n\nfunction rememberProbeResult(\n cache: MediaCodecProbeCache,\n filePath: string,\n result: CachedAssetProbe,\n): void {\n if (!cache.has(filePath) && cache.size >= MAX_PROBE_CACHE_ENTRIES) {\n const oldest = cache.keys().next().value;\n if (oldest) cache.delete(oldest);\n }\n // Refresh insertion order so frequently used assets remain resident.\n cache.delete(filePath);\n cache.set(filePath, result);\n}\n\n/**\n * Codec facts for one video, cached per path until its target, mtime or size changes; a hit skips\n * `runner`. Never throws: no video stream or a failed probe gives `null`, and a failed probe is not cached.\n */\nexport async function probeAssetCodec(\n filePath: string,\n runner?: FfprobeRunner,\n cache: MediaCodecProbeCache = defaultProbeCache,\n): Promise<AssetCodecFacts | null> {\n let stat: ReturnType<typeof statSync>;\n let target: string;\n try {\n stat = statSync(filePath);\n target = realpath(filePath);\n } catch {\n return null;\n }\n const cached = cache.get(filePath);\n if (\n cached &&\n cached.target === target &&\n cached.mtimeMs === stat.mtimeMs &&\n cached.size === stat.size\n ) {\n rememberProbeResult(cache, filePath, cached);\n return cached.facts;\n }\n const facts = await probeCodecFacts(filePath, runner);\n if (facts === undefined) return null;\n rememberProbeResult(cache, filePath, { target, mtimeMs: stat.mtimeMs, size: stat.size, facts });\n return facts;\n}\n\n/** Structurally compatible with `packages/lint/src/hevcPreviewLint.ts`'s\n * (unexported) `HtmlSourceLike`. */\nexport interface HtmlSourceLike {\n html: string;\n compSrcPath?: string;\n}\n\n/**\n * Resolve a `<video src>` reference to an existing local file.\n *\n * `rootRelativePathname` is the map key format PINNED by this plan's Key\n * Technical Decisions: project-root-relative URL pathname, percent-decoded,\n * query-string-stripped, forward-slash separated, leading-slash prefixed\n * (e.g. \"/assets/videos/clip.mp4\"). This must match what the runtime derives\n * via `new URL(el.currentSrc || el.src, document.baseURI).pathname`, because\n * server-side scanning resolves filesystem paths while the DOM sees served\n * URLs — a documented prior source of this exact class of bug.\n */\nfunction resolveExistingLocalAsset(\n projectDir: string,\n url: string,\n): { resolvedPath: string; rootRelativePathname: string } | null {\n const asset = resolveAsset(projectDir, url);\n if (!asset) return null;\n return {\n resolvedPath: asset.resolved,\n rootRelativePathname: `/${asset.rootRelativePath.split(sep).join(\"/\")}`,\n };\n}\n\n/**\n * Collects local `<video src>` references, resolved to their absolute path\n * and deduped by that path, keyed by the pinned root-relative URL pathname.\n */\n// fallow-ignore-next-line complexity\nfunction collectLocalVideoAssets(\n projectDir: string,\n htmlSources: HtmlSourceLike[],\n): Map<string, string> {\n const candidates = new Map<string, string>();\n\n for (const { html, compSrcPath } of htmlSources) {\n for (const tag of scanHtmlOpeningTags(html)) {\n if (tag.name !== \"video\" || !tag.closed) continue;\n const attribute = tag.attributes.find((attr) => attr.name === \"src\");\n if (attribute?.kind !== \"value\") continue;\n const rawSrc = decodeAuthoredAttribute(attribute.value);\n // Placeholder check runs on the RAW value: cleanAssetUrl() splits on ?/# and would chop inside a ${...} token.\n if (isUnresolvedAssetPlaceholder(rawSrc)) continue;\n const src = cleanAssetUrl(rawSrc);\n if (!src || isRemoteOrInlineUrl(src)) continue;\n const rootRelativeSrc = compSrcPath ? rewriteAssetPath(compSrcPath, src) : src;\n const resolved = resolveExistingLocalAsset(projectDir, rootRelativeSrc);\n if (!resolved) continue;\n candidates.set(resolved.resolvedPath, resolved.rootRelativePathname);\n }\n }\n\n return candidates;\n}\n\n// Bounds concurrent ffprobe child processes for projects referencing many\n// videos, mirroring `PROBE_CONCURRENCY` in `hevcPreviewLint.ts`.\nconst PROBE_CONCURRENCY = 8;\n\nexport interface ScanProjectMediaCodecMapOptions {\n /** Persisted across calls by the caller for the mtime-cache benefit;\n * defaults to a shared module-level cache when omitted. */\n cache?: MediaCodecProbeCache;\n runner?: FfprobeRunner;\n}\n\n/**\n * Scans a project's composition HTML for local `<video src>` references and\n * returns the injection map: root-relative URL pathname -> codec facts.\n * Best-effort throughout — a video whose codec can't be determined (missing\n * ffprobe, probe error, no video stream) is simply omitted, never thrown.\n */\nexport async function scanProjectMediaCodecMap(\n projectDir: string,\n htmlSources: HtmlSourceLike[],\n options: ScanProjectMediaCodecMapOptions = {},\n): Promise<MediaCodecMap> {\n const candidates = collectLocalVideoAssets(projectDir, htmlSources);\n if (candidates.size === 0) return {};\n\n const cache = options.cache ?? defaultProbeCache;\n const entries = [...candidates.entries()]; // [resolvedPath, rootRelativePathname]\n const facts = new Array<AssetCodecFacts | null>(entries.length).fill(null);\n let nextIndex = 0;\n const workerCount = Math.min(PROBE_CONCURRENCY, entries.length);\n await Promise.all(\n Array.from({ length: workerCount }, async () => {\n while (nextIndex < entries.length) {\n const index = nextIndex++;\n const entry = entries[index];\n if (!entry) break;\n facts[index] = await probeAssetCodec(entry[0], options.runner, cache);\n }\n }),\n );\n\n const map: MediaCodecMap = {};\n entries.forEach(([, pathname], index) => {\n const entryFacts = facts[index];\n if (entryFacts?.browserHostile) map[pathname] = entryFacts;\n });\n return map;\n}\n","import { execFile } from \"node:child_process\";\nimport { extname } from \"node:path\";\nimport {\n firstFrameColourArgs,\n parseFirstFrameColour,\n type ToneMapSourceColour,\n} from \"@hyperframes/core\";\nimport { findFfBinary } from \"@hyperframes/parsers/ff-binaries\";\n\nexport interface FfprobeRunResult {\n status: number | null;\n stdout: string | Buffer;\n stderr: string | Buffer;\n /** Spawn-level failure (covers both `NodeJS.ErrnoException` and\n * `ExecFileException`); only `code === \"ENOENT\"` is ever inspected. */\n error?: { code?: string | number | null | undefined };\n}\n\n/** Injectable ffprobe runner. May be synchronous (tests) or async (the\n * default `execFile`-based runner below), so cold scans can run many probes\n * concurrently off the event loop. */\nexport type FfprobeRunner = (\n command: string,\n args: string[],\n options?: { timeout?: number; maxBuffer?: number },\n) => FfprobeRunResult | Promise<FfprobeRunResult>;\n\n/** Default runner: genuinely async (`execFile`), unlike the previous\n * `spawnSync`-based one — a pool of concurrent probes actually parallelizes\n * (mirrors `execFileAsync` in packages/lint/src/hevcPreviewLint.ts). */\nconst execFileRunner: FfprobeRunner = (command, args, options) =>\n new Promise<FfprobeRunResult>((resolvePromise) => {\n execFile(\n command,\n args,\n { timeout: options?.timeout, maxBuffer: options?.maxBuffer, windowsHide: true },\n (error, stdout, stderr) => {\n if (error && error.code === \"ENOENT\") {\n resolvePromise({ status: null, stdout: \"\", stderr: \"\", error });\n return;\n }\n if (error) {\n // Nonzero exit / timeout / kill: report a nonzero status; callers\n // only distinguish \"ok\" (0) from \"failed\" from \"ENOENT\".\n const status = typeof error.code === \"number\" ? error.code : 1;\n resolvePromise({ status, stdout: stdout ?? \"\", stderr: stderr ?? \"\" });\n return;\n }\n resolvePromise({ status: 0, stdout: stdout ?? \"\", stderr: stderr ?? \"\" });\n },\n );\n });\n\nexport type MediaDynamicRange = \"hdr\" | \"sdr\" | \"unknown\";\nexport type MediaHdrTransfer = \"pq\" | \"hlg\" | \"unknown\";\n\nexport interface MediaColorMetadata {\n dynamicRange: MediaDynamicRange;\n hdrTransfer: MediaHdrTransfer | null;\n label: string;\n isHdr: boolean;\n codecName?: string;\n profile?: string;\n pixelFormat?: string;\n colorSpace?: string;\n colorTransfer?: string;\n colorPrimaries?: string;\n bitsPerRawSample?: string;\n}\n\nexport interface MediaMetadata {\n kind: \"video\" | \"image\" | \"audio\" | \"unknown\";\n color: MediaColorMetadata;\n /** Video audio stream, when probed. Absent means the drop path stays muted. */\n hasAudio?: boolean;\n probeError?: string;\n}\n\ninterface FfprobeStream {\n codec_type?: string;\n codec_name?: string;\n profile?: string;\n pix_fmt?: string;\n color_space?: string;\n color_transfer?: string;\n color_primaries?: string;\n bits_per_raw_sample?: string;\n disposition?: { attached_pic?: number };\n}\n\nconst VIDEO_EXT = new Set([\n \".mp4\",\n \".mov\",\n \".webm\",\n \".mkv\",\n \".avi\",\n \".m4v\",\n \".mxf\",\n \".mts\",\n \".m2ts\",\n \".ts\",\n]);\nconst IMAGE_EXT = new Set([\".jpg\", \".jpeg\", \".png\", \".webp\", \".avif\"]);\nconst AUDIO_EXT = new Set([\".mp3\", \".wav\", \".ogg\", \".m4a\", \".aac\", \".flac\"]);\n\nfunction lower(value: string | undefined): string {\n return value?.toLowerCase() ?? \"\";\n}\n\nfunction inferKindFromPath(path: string): MediaMetadata[\"kind\"] {\n const ext = extname(path).toLowerCase();\n if (VIDEO_EXT.has(ext)) return \"video\";\n if (IMAGE_EXT.has(ext)) return \"image\";\n if (AUDIO_EXT.has(ext)) return \"audio\";\n return \"unknown\";\n}\n\nfunction colorLabel(input: {\n isHdr: boolean;\n hdrTransfer: MediaHdrTransfer | null;\n colorPrimaries: string;\n colorSpace: string;\n colorTransfer: string;\n}): string {\n if (input.isHdr) {\n if (input.hdrTransfer === \"pq\") return \"HDR PQ\";\n if (input.hdrTransfer === \"hlg\") return \"HDR HLG\";\n return \"HDR\";\n }\n if (\n input.colorPrimaries.includes(\"bt709\") ||\n input.colorSpace.includes(\"bt709\") ||\n input.colorTransfer.includes(\"bt709\")\n ) {\n return \"SDR Rec.709\";\n }\n return \"SDR/unknown\";\n}\n\n// Conservative alpha-bearing pix_fmt list: yuva* (yuva420p, yuva444p10le...),\n// rgba/argb/bgra/abgr (packed RGB+alpha), gbrap* (planar GBR+alpha, ProRes\n// 4444 decodes to these), ya* (gray+alpha). Prefix match keeps bit-depth /\n// endianness suffixes covered.\nconst ALPHA_PIX_FMT_RE = /^(?:yuva|rgba|argb|bgra|abgr|gbrap|ya)/;\n\n/** True when an ffprobe `pix_fmt` carries an alpha component. */\nexport function pixelFormatHasAlpha(pixFmt: string | undefined): boolean {\n return pixFmt !== undefined && ALPHA_PIX_FMT_RE.test(pixFmt.toLowerCase());\n}\n\nexport function classifyMediaColor(stream: FfprobeStream | null | undefined): MediaColorMetadata {\n const colorPrimaries = lower(stream?.color_primaries);\n const colorSpace = lower(stream?.color_space);\n const colorTransfer = lower(stream?.color_transfer);\n const isHdr =\n colorPrimaries.includes(\"bt2020\") ||\n colorSpace.includes(\"bt2020\") ||\n colorTransfer === \"smpte2084\" ||\n colorTransfer === \"arib-std-b67\";\n const hdrTransfer: MediaHdrTransfer | null = isHdr\n ? colorTransfer === \"smpte2084\"\n ? \"pq\"\n : colorTransfer === \"arib-std-b67\"\n ? \"hlg\"\n : \"unknown\"\n : null;\n\n return {\n dynamicRange: stream ? (isHdr ? \"hdr\" : \"sdr\") : \"unknown\",\n hdrTransfer,\n label: stream\n ? colorLabel({ isHdr, hdrTransfer, colorPrimaries, colorSpace, colorTransfer })\n : \"Unknown\",\n isHdr,\n codecName: stream?.codec_name,\n profile: stream?.profile,\n pixelFormat: stream?.pix_fmt,\n colorSpace: stream?.color_space,\n colorTransfer: stream?.color_transfer,\n colorPrimaries: stream?.color_primaries,\n bitsPerRawSample: stream?.bits_per_raw_sample,\n };\n}\n\n/** The first shown frame's colour tags, which zscale reads per frame. Empty when unread. */\nexport async function probeFirstFrameColour(\n filePath: string,\n runner: FfprobeRunner = execFileRunner,\n): Promise<ToneMapSourceColour> {\n const ffmpegPath =\n findFfBinary(\"ffmpeg\", { configuredMustExist: true }) ??\n (runner === execFileRunner ? undefined : \"ffmpeg\");\n if (!ffmpegPath) return {};\n const result = await runner(ffmpegPath, firstFrameColourArgs(filePath), {\n timeout: 15_000,\n maxBuffer: 1024 * 1024,\n });\n return result.status === 0 ? parseFirstFrameColour(String(result.stderr)) : {};\n}\n\nexport async function probeMediaMetadata(\n filePath: string,\n runner: FfprobeRunner = execFileRunner,\n): Promise<MediaMetadata> {\n const kind = inferKindFromPath(filePath);\n if (kind === \"audio\" || kind === \"unknown\") {\n return { kind, color: classifyMediaColor(null) };\n }\n\n // The default runner degrades a missing ffprobe to \"unavailable\" without\n // spawning; injected runners own execution and receive the normal command.\n const ffprobePath =\n findFfBinary(\"ffprobe\", { configuredMustExist: true }) ??\n (runner === execFileRunner ? undefined : \"ffprobe\");\n if (!ffprobePath) {\n return { kind, color: classifyMediaColor(null), probeError: \"ffprobe unavailable\" };\n }\n\n const result = await runner(\n ffprobePath,\n [\n \"-v\",\n \"error\",\n \"-show_entries\",\n \"stream=codec_type,codec_name,profile,pix_fmt,color_space,color_transfer,color_primaries,bits_per_raw_sample:stream_disposition=attached_pic\",\n \"-of\",\n \"json\",\n \"--\",\n filePath,\n ],\n { timeout: 15_000, maxBuffer: 1024 * 1024 },\n );\n\n if (result.error?.code === \"ENOENT\") {\n return { kind, color: classifyMediaColor(null), probeError: \"ffprobe unavailable\" };\n }\n if (result.status !== 0) {\n return { kind, color: classifyMediaColor(null), probeError: \"ffprobe failed\" };\n }\n\n try {\n const parsed = JSON.parse(String(result.stdout || \"{}\")) as { streams?: FfprobeStream[] };\n const stream = parsed.streams?.find((item) => {\n if (kind === \"image\") return item.codec_type === \"video\";\n return item.codec_type === kind && item.disposition?.attached_pic !== 1;\n });\n const metadata: MediaMetadata = { kind, color: classifyMediaColor(stream) };\n if (kind === \"video\") {\n metadata.hasAudio = (parsed.streams ?? []).some((item) => item.codec_type === \"audio\");\n }\n return metadata;\n } catch {\n return { kind, color: classifyMediaColor(null), probeError: \"ffprobe returned invalid json\" };\n }\n}\n"],"mappings":";;;;;AAAA,SAAS,qBAAqB,+BAA+B;AAC7D,SAAS,gBAAgB;AAEzB,SAAS,WAAW;AACpB,SAAS,wBAAwB;AACjC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA,6BAA6B;AAAA,OACxB;;;ACVP,SAAS,gBAAgB;AACzB,SAAS,eAAe;AACxB;AAAA,EACE;AAAA,EACA;AAAA,OAEK;AACP,SAAS,oBAAoB;AAuB7B,IAAM,iBAAgC,CAAC,SAAS,MAAM,YACpD,IAAI,QAA0B,CAAC,mBAAmB;AAChD;AAAA,IACE;AAAA,IACA;AAAA,IACA,EAAE,SAAS,SAAS,SAAS,WAAW,SAAS,WAAW,aAAa,KAAK;AAAA,IAC9E,CAAC,OAAO,QAAQ,WAAW;AACzB,UAAI,SAAS,MAAM,SAAS,UAAU;AACpC,uBAAe,EAAE,QAAQ,MAAM,QAAQ,IAAI,QAAQ,IAAI,MAAM,CAAC;AAC9D;AAAA,MACF;AACA,UAAI,OAAO;AAGT,cAAM,SAAS,OAAO,MAAM,SAAS,WAAW,MAAM,OAAO;AAC7D,uBAAe,EAAE,QAAQ,Q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-
} from "./chunk-
|
|
11
|
+
} from "./chunk-RN33UALN.js";
|
|
12
12
|
|
|
13
13
|
// src/helpers/mediaProxyPreview.ts
|
|
14
14
|
import { resolve } from "path";
|
|
@@ -64,4 +64,4 @@ export {
|
|
|
64
64
|
injectMediaCodecMapIntoHtml,
|
|
65
65
|
injectMediaCodecMap
|
|
66
66
|
};
|
|
67
|
-
//# sourceMappingURL=chunk-
|
|
67
|
+
//# sourceMappingURL=chunk-VE2AOX4K.js.map
|
package/dist/helpers/loudness.js
CHANGED
|
@@ -11,7 +11,10 @@ import {
|
|
|
11
11
|
requiredFfmpeg,
|
|
12
12
|
resolveLocalAudioPath,
|
|
13
13
|
updateAudioVolume
|
|
14
|
-
} from "../chunk-
|
|
14
|
+
} from "../chunk-32IH7WBY.js";
|
|
15
|
+
import "../chunk-DTKK7TKL.js";
|
|
16
|
+
import "../chunk-6XMC64FJ.js";
|
|
17
|
+
import "../chunk-4ETS2LXI.js";
|
|
15
18
|
export {
|
|
16
19
|
DEFAULT_TARGET_LUFS,
|
|
17
20
|
NORMALIZE_TRUE_PEAK_CEILING_DBFS,
|