Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 13 additions & 3 deletions packages/cli/src/audio/analysis/decode.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { execFile } from "node:child_process";
import { promisify } from "node:util";
import { findFfBinary, mediaInputArgs } from "@hyperframes/parsers/ff-binaries";
import { resolve } from "node:path";
import { ffmpegCwd, findFfBinary, mediaInputArgs } from "@hyperframes/parsers/ff-binaries";
import { assertLiteralMediaInput } from "@hyperframes/parsers/literal-media-input";
import {
decodableAudioStream,
Expand All @@ -10,6 +11,8 @@ import {
import type { AudioSignal } from "@hyperframes/core/audio-analysis";

const run = promisify(execFile);
const absoluteLocal = (file: string): string =>
/^(?:[a-z][a-z0-9+.-]+:|subfile,)/i.test(file) ? file : resolve(file);

export interface AudioStreamInfo {
audioStream: number;
Expand All @@ -36,6 +39,7 @@ export async function probeAudio(
file: string,
inputArgs: readonly string[] = [],
): Promise<AudioStreamInfo | null> {
file = absoluteLocal(file);
const ffprobe = requiredBinary("ffprobe");
const { stdout } = await run(
ffprobe,
Expand All @@ -52,7 +56,7 @@ export async function probeAudio(
"--",
file,
],
{ maxBuffer: 8 * 1024 * 1024, windowsHide: true },
{ maxBuffer: 8 * 1024 * 1024, windowsHide: true, cwd: ffmpegCwd() },
);
const parsed = JSON.parse(stdout) as {
streams?: (FfprobePcmFields & { duration?: string })[];
Expand Down Expand Up @@ -95,6 +99,7 @@ export async function decodeAudio(
probed?: AudioStreamInfo,
format: DecodeFormat = {},
): Promise<Decoded | null> {
file = absoluteLocal(file);
const inputArgs = format.inputArgs ?? [];
const probedInfo = probed ?? (await probeAudio(file, inputArgs));
if (!probedInfo) return null;
Expand Down Expand Up @@ -128,7 +133,12 @@ export async function decodeAudio(
"pcm_f32le",
"-",
],
{ encoding: "buffer", maxBuffer: 2 * 1024 * 1024 * 1024, windowsHide: true },
{
encoding: "buffer",
maxBuffer: 2 * 1024 * 1024 * 1024,
windowsHide: true,
cwd: ffmpegCwd(),
},
);
const bytes = stdout.byteLength - (stdout.byteLength % 4);
const interleaved = new Float32Array(
Expand Down
3 changes: 2 additions & 1 deletion packages/cli/src/capture/captureCompositionFrame.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { oneProcessOverPipe, resolveRestrictPageNetwork } from "@hyperframes/engine";
import { ffmpegCwd } from "@hyperframes/parsers/ff-binaries";
import { SEEK_SETTLES_BEFORE_PROTOCOL_TIMEOUT_MS } from "./captureTimeout.js";
import {
rethrowAfterBrowserCleanup,
Expand Down Expand Up @@ -881,7 +882,7 @@ export async function runFfmpegOnce(
timeoutMs: number,
): Promise<FfmpegRunResult> {
return await new Promise((resolvePromise) => {
const ff = spawn(ffmpegPath, args, { windowsHide: true });
const ff = spawn(ffmpegPath, args, { windowsHide: true, cwd: ffmpegCwd() });
let stderr = "";
let timedOut = false;
const timer = setTimeout(() => {
Expand Down
21 changes: 12 additions & 9 deletions packages/cli/src/commands/render.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import type { ReferenceBackgroundResult } from "@hyperframes/producer";
import { fromEmptyFolder } from "@hyperframes/parsers/ff-binaries";
import { captureArtifactRevision } from "../utils/artifactCapture.js";
import { recordRenderSuccess, registerRenderOutput } from "@hyperframes/studio-server/history";
import { resolveGsapVendorDir } from "../server/gsapVendor.js";
Expand Down Expand Up @@ -1428,15 +1429,17 @@ async function renderRange(input: {
logger: input.logger,
abortSignal: input.signal,
});
const spanResult = await producer.renderSpan(
input.projectDir,
config,
input.range,
input.outputPath,
{
allowOutsideProjectAssets: input.allowOutsideProjectAssets,
includeOutsideScripts: input.includeOutsideScripts,
},
const spanResult = await fromEmptyFolder(() =>
producer.renderSpan(
resolve(input.projectDir),
config,
input.range,
resolve(input.outputPath),
{
allowOutsideProjectAssets: input.allowOutsideProjectAssets,
includeOutsideScripts: input.includeOutsideScripts,
},
),
);
framesEncoded = spanResult.framesEncoded;
reference = producer.referenceBackgroundResult(spanResult[producer.REFERENCE_BACKGROUND_FIELD]);
Expand Down
26 changes: 22 additions & 4 deletions packages/cli/src/commands/snapshot.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import {
isHdrColorSpace,
sdrCanvasColourFilters,
} from "@hyperframes/engine";
import { mediaInputArgs } from "@hyperframes/parsers/ff-binaries";
import { ffmpegCwd, fromEmptyFolder, mediaInputArgs } from "@hyperframes/parsers/ff-binaries";
import { projectFolder } from "../utils/projectRecords.js";
import { screenshotOnceMore } from "../utils/screenshotOnceMore.js";
import { parseTimeoutMs } from "../utils/timeoutArg.js";
Expand Down Expand Up @@ -503,7 +503,11 @@ export async function probeContainingSourceFrameSeek(
...["-select_streams", "v:0", "-read_intervals", readIntervals],
...["-show_entries", entries, "-of", "json", "--", videoPath],
],
{ timeoutMs: FFMPEG_EXTRACT_TIMEOUT_MS, maxBufferBytes: 32 * 1024 * 1024 },
{
timeoutMs: FFMPEG_EXTRACT_TIMEOUT_MS,
maxBufferBytes: 32 * 1024 * 1024,
cwd: ffmpegCwd(),
},
);
const parsed: unknown = JSON.parse(stdout);
return typeof parsed === "object" && parsed !== null
Expand Down Expand Up @@ -634,7 +638,11 @@ async function probeSeekLanding(
...["-ss", String(seek), "-i", videoPath],
...["-map", "0:v:0", "-c", "copy", "-frames:v", "1", "-f", "framecrc", "-"],
],
{ timeoutMs: FFMPEG_EXTRACT_TIMEOUT_MS, maxBufferBytes: 1024 * 1024 },
{
timeoutMs: FFMPEG_EXTRACT_TIMEOUT_MS,
maxBufferBytes: 1024 * 1024,
cwd: ffmpegCwd(),
},
);
const base = /^#tb 0: (\d+)\/(\d+)/m.exec(stdout);
const row = /^0,\s*-?\d+,\s*(-?\d+),/m.exec(stdout);
Expand Down Expand Up @@ -986,7 +994,17 @@ export function serveCapturePage(projectDir: string, html: string, proxy: boolea
* Render key frames from a composition as PNG screenshots.
* The agent can Read these to verify its output visually.
*/
export async function captureSnapshots(
export function captureSnapshots(
projectDir: string,
opts: Parameters<typeof captureSnapshotsFrom>[1],
): Promise<CapturedSnapshots> {
const against = opts.against && resolve(opts.against);
return fromEmptyFolder(() =>
captureSnapshotsFrom(resolve(projectDir), { ...opts, ...(against ? { against } : {}) }),
);
}

async function captureSnapshotsFrom(
projectDir: string,
opts: {
frames?: number;
Expand Down
4 changes: 2 additions & 2 deletions packages/cli/src/commands/snapshotHeldVideos.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { parseHTML } from "@hyperframes/parsers/linkedom";
import { MEDIA_RENDER_ID_ATTR, naturalVideoSize, streamRotation } from "@hyperframes/core";
import { isPrivateFileUnder, isStudioPrivatePath } from "@hyperframes/core/safe-path";
import { isNotMediaPayload, type CaptureVideoMetadataHint } from "@hyperframes/engine";
import { mediaInputArgs } from "@hyperframes/parsers/ff-binaries";
import { ffmpegCwd, mediaInputArgs } from "@hyperframes/parsers/ff-binaries";
import { findFFprobe } from "../browser/ffmpeg.js";
import { runCancellableProcess } from "../utils/cancellableProcess.js";

Expand Down Expand Up @@ -118,7 +118,7 @@ export function probeHeldVideo(
"--",
path,
],
{ timeoutMs: PROBE_TIMEOUT_MS, maxBufferBytes: 1024 * 1024 },
{ timeoutMs: PROBE_TIMEOUT_MS, maxBufferBytes: 1024 * 1024, cwd: ffmpegCwd() },
);
return parseProbe(JSON.parse(stdout) as ProbeJson);
} catch {
Expand Down
3 changes: 2 additions & 1 deletion packages/cli/src/measure/face.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import {
ffmpegBin,
frameAt,
guardedLimitReason,
guardedCwd,
round,
runFfmpeg,
sumOf,
Expand Down Expand Up @@ -59,7 +60,7 @@ function decode(info: VideoInfo, args: string[]): Buffer {
const formats = mediaInputArgs(ffmpegBin(), info.path, { playlists: info.guarded });
if (!info.guarded) return runFfmpeg([...formats, ...args]);
try {
return runFfmpeg([...formats, ...args], undefined, undefined, GUARDED_RUN_MS);
return runFfmpeg([...formats, ...args], undefined, guardedCwd(info), GUARDED_RUN_MS);
} catch (err) {
const stopped = guardedLimitReason(err);
throw stopped ? new Error(`ffmpeg cannot read ${info.path}: ${stopped}`) : err;
Expand Down
32 changes: 18 additions & 14 deletions packages/cli/src/measure/hands.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import { tmpdir } from "node:os";
import { join } from "node:path";
import type { HTTPRequest, Page } from "puppeteer-core";
import { trustedCacheRoot } from "@hyperframes/core/cache-dir";
import { ffmpegInput, Fix, round, runFfmpeg, type VideoInfo } from "./media.js";
import { ffmpegInput, Fix, guardedCwd, round, runFfmpeg, type VideoInfo } from "./media.js";
import { ensurePinnedFiles, type PinnedFile } from "./pinnedFiles.js";

const VERSION = "1.0.0";
Expand Down Expand Up @@ -150,19 +150,23 @@ export function handFrames(
fps: number,
dir: string,
): string[] {
runFfmpeg([
"-y",
"-ss",
start.toFixed(3),
...ffmpegInput(info.path, { playlists: info.guarded }),
"-t",
(end - start).toFixed(3),
"-vf",
`fps=${fps}:round=near,scale=${WIDTH}:-2`,
"-q:v",
"3",
join(dir, "t%05d.jpg"),
]);
runFfmpeg(
[
"-y",
"-ss",
start.toFixed(3),
...ffmpegInput(info.path, { playlists: info.guarded }),
"-t",
(end - start).toFixed(3),
"-vf",
`fps=${fps}:round=near,scale=${WIDTH}:-2`,
"-q:v",
"3",
join(dir, "t%05d.jpg"),
],
undefined,
guardedCwd(info),
);
return readdirSync(dir)
.filter((name) => FRAME_NAME.test(name))
.sort();
Expand Down
8 changes: 6 additions & 2 deletions packages/cli/src/measure/media.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { closeSync, existsSync, mkdirSync, openSync, readSync, rmSync } from "no
import { basename, dirname, join, resolve } from "node:path";
import { createStagingDir } from "@hyperframes/core/atomic-file";
import { renameWithRetry } from "@hyperframes/core/rename-retry";
import { mediaInputArgs } from "@hyperframes/parsers/ff-binaries";
import { ffmpegWorkingDir, mediaInputArgs } from "@hyperframes/parsers/ff-binaries";
import { assertLiteralMediaOutput } from "@hyperframes/parsers/literal-media-input";
import { findFFmpeg, findFFprobe, getFFmpegInstallHint } from "../browser/ffmpeg.js";
import { recordFolder } from "../utils/projectRecords.js";
Expand Down Expand Up @@ -67,6 +67,9 @@ export function runFfmpeg(args: string[], input?: Buffer, cwd?: string, timeout?
});
}

export const guardedCwd = (info: VideoInfo): string | undefined =>
info.guarded ? ffmpegWorkingDir() : undefined;

export function ffmpegInput(path: string, { playlists = false } = {}): string[] {
return [...mediaInputArgs(ffmpegBin(), path, { playlists }), "-i", path];
}
Expand Down Expand Up @@ -217,6 +220,7 @@ function startsWithMp4Header(path: string): boolean {
/** Size (as displayed, rotation applied), clock and sound of a video; `guarded` for a file a composition names. */
// fallow-ignore-next-line complexity
export function probeVideo(path: string, { guarded = false } = {}): VideoInfo {
if (guarded) path = resolve(path);
if (!existsSync(path)) throw new Fix(`no file at ${path}`, missingFileFix(path));
const bin = ffprobeBin();
const formats = mediaInputArgs(bin, path, { playlists: guarded });
Expand All @@ -230,7 +234,7 @@ export function probeVideo(path: string, { guarded = false } = {}): VideoInfo {
maxBuffer: MAX_BUFFER,
windowsHide: true,
stdio: ["ignore", "pipe", "pipe"],
...(guarded ? { timeout: GUARDED_RUN_MS } : {}),
...(guarded ? { timeout: GUARDED_RUN_MS, cwd: ffmpegWorkingDir() } : {}),
},
).toString(),
);
Expand Down
27 changes: 16 additions & 11 deletions packages/cli/src/measure/sync.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import {
pearson,
readClip,
round,
guardedCwd,
runFfmpeg,
videoClip,
type Roi,
Expand All @@ -17,18 +18,22 @@ const RATE = 16000;

/** Mono samples of the window at RATE Hz. */
function samples(info: VideoInfo, start: number, seconds: number): Float32Array {
const raw = runFfmpeg([
...[
"-ss",
String(start),
...ffmpegInput(info.path, { playlists: info.guarded }),
"-t",
String(seconds),
"-vn",
const raw = runFfmpeg(
[
...[
"-ss",
String(start),
...ffmpegInput(info.path, { playlists: info.guarded }),
"-t",
String(seconds),
"-vn",
],
...["-af", "aresample=async=1:first_pts=0"],
...["-ac", "1", "-ar", String(RATE), "-f", "f32le", "-"],
],
...["-af", "aresample=async=1:first_pts=0"],
...["-ac", "1", "-ar", String(RATE), "-f", "f32le", "-"],
]);
undefined,
guardedCwd(info),
);
return new Float32Array(raw.buffer.slice(raw.byteOffset, raw.byteOffset + (raw.byteLength & ~3)));
}

Expand Down
11 changes: 10 additions & 1 deletion packages/cli/src/timeline/describeProject.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { readFileSync, realpathSync, statSync } from "node:fs";
import { fromEmptyFolder } from "@hyperframes/parsers/ff-binaries";
import { basename, dirname, isAbsolute, relative, resolve, sep } from "node:path";
import {
HF_AUDIO_AUTOMATION_ATTR,
Expand Down Expand Up @@ -488,10 +489,18 @@ function projectFps(source: string): number {
}

/** Needs a global DOMParser (`ensureDOMParser`). Reads `index.html` and one level of sub-compositions. */
export async function describeProject(
export function describeProject(
indexPath: string,
measure: MeasureMedia = measureWithFfprobe,
sourceOverrides: ReadonlyMap<string, string> = new Map(),
): Promise<ProjectTimeline> {
return fromEmptyFolder(() => describeProjectAt(resolve(indexPath), measure, sourceOverrides));
}

async function describeProjectAt(
indexPath: string,
measure: MeasureMedia,
sourceOverrides: ReadonlyMap<string, string>,
): Promise<ProjectTimeline> {
const projectDir = dirname(indexPath);
const source = sourceOverrides.get(basename(indexPath)) ?? readFileSync(indexPath, "utf-8");
Expand Down
10 changes: 9 additions & 1 deletion packages/cli/src/utils/checkPipeline.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ import { writeFileSync } from "node:fs";
import { readFile } from "node:fs/promises";
import type { PrelaunchedBrowser } from "../capture/captureCompositionFrame.js";
import { join, relative } from "node:path";
import { fromEmptyFolder } from "@hyperframes/parsers/ff-binaries";
import { trackCheckReport, trackCommandFailure } from "../telemetry/events.js";
import { trackLintRun } from "../telemetry/lintRun.js";
import { getRunId } from "../telemetry/runId.js";
Expand Down Expand Up @@ -2487,7 +2488,14 @@ async function captureFindingCrops(
}

/** HDR promotion before the browser starts; audio findings later, overlapping the browser pass. */
async function inspectProjectMedia(
function inspectProjectMedia(
project: ProjectDir,
dependencies: CheckDependencies,
): Promise<{ hdr: CheckReport["hdr"]; audio: Promise<CheckFinding[]> }> {
return fromEmptyFolder(() => inspectProjectMediaIn(project, dependencies));
}

async function inspectProjectMediaIn(
project: ProjectDir,
dependencies: CheckDependencies,
): Promise<{ hdr: CheckReport["hdr"]; audio: Promise<CheckFinding[]> }> {
Expand Down
11 changes: 7 additions & 4 deletions packages/cli/src/utils/projectMedia.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ import {
type AudioElement,
type VideoElement,
} from "@hyperframes/engine";
import { resolve } from "node:path";
import { fromEmptyFolder } from "@hyperframes/parsers/ff-binaries";
import { loadProducer } from "./producer.js";

/** The render's own media list for a project: what it extracts, probes and mixes. */
Expand Down Expand Up @@ -54,10 +56,11 @@ const PROBE: HeardProbe = {

/** Every clip the render mixes, read as the render reads them (scenes inlined, on the film's clock), each ended where
* its media runs out if sooner, and left out if it starts past that; a ramped rate or a loop keeps its end. */
export async function heardClips(
projectDir: string,
probe: HeardProbe = PROBE,
): Promise<HeardClip[]> {
export function heardClips(projectDir: string, probe: HeardProbe = PROBE): Promise<HeardClip[]> {
return fromEmptyFolder(() => heardClipsIn(resolve(projectDir), probe));
}

async function heardClipsIn(projectDir: string, probe: HeardProbe): Promise<HeardClip[]> {
const { audios } = await collectProjectMedia(projectDir);
const lengths = new Map<string, Promise<number | null>>();
const length = (src: string): Promise<number | null> => {
Expand Down
Loading
Loading