diff --git a/packages/studio-server/src/helpers/mediaMetadata.test.ts b/packages/studio-server/src/helpers/mediaMetadata.test.ts index bc651131e6..fcc45a8274 100644 --- a/packages/studio-server/src/helpers/mediaMetadata.test.ts +++ b/packages/studio-server/src/helpers/mediaMetadata.test.ts @@ -138,6 +138,32 @@ describe("probeMediaMetadata", () => { expect(audioFile).not.toHaveProperty("hasAudio"); }); + it("reads how long the picture and the sound it plays last, apart from longer tracks it leaves out", async () => { + const probe = (streams: object[]) => + probeMediaMetadata("/tmp/clip.mkv", () => ({ + status: 0, + stdout: JSON.stringify({ streams, format: { duration: "50.0" } }), + stderr: "", + })); + const mp4 = await probe([ + { codec_type: "video", codec_name: "h264", duration: "47.000000" }, + { codec_type: "audio", codec_name: "aac", duration: "47.021333" }, + { codec_type: "audio", codec_name: "aac", duration: "50.000000" }, + { codec_type: "subtitle", codec_name: "mov_text", duration: "50.000000" }, + ]); + expect(mp4).toMatchObject({ durationSeconds: 50, keptStreamsSeconds: 47.021333 }); + const mkv = await probe([ + { codec_type: "video", codec_name: "vp9", tags: { DURATION: "00:00:47.000000000" } }, + { codec_type: "subtitle", codec_name: "ass", tags: { DURATION: "00:00:50.000000000" } }, + ]); + expect(mkv.keptStreamsSeconds).toBe(47); + const unknown = await probe([ + { codec_type: "video", codec_name: "h264" }, + { codec_type: "audio", codec_name: "aac", duration: "47.0" }, + ]); + expect(unknown).not.toHaveProperty("keptStreamsSeconds"); + }); + it("reads a flac file as audio", async () => { const flac = await probeMediaMetadata("/tmp/music.flac", () => ({ status: 0, diff --git a/packages/studio-server/src/helpers/mediaMetadata.ts b/packages/studio-server/src/helpers/mediaMetadata.ts index 3fab79fbdd..532bbdbb6e 100644 --- a/packages/studio-server/src/helpers/mediaMetadata.ts +++ b/packages/studio-server/src/helpers/mediaMetadata.ts @@ -30,7 +30,7 @@ export interface FfprobeRunResult { export type FfprobeRunner = ( command: string, args: string[], - options?: { timeout?: number; maxBuffer?: number }, + options?: { timeout?: number; maxBuffer?: number; signal?: AbortSignal }, ) => FfprobeRunResult | Promise; /** Default runner: genuinely async (`execFile`), unlike the previous @@ -41,7 +41,12 @@ const execFileRunner: FfprobeRunner = (command, args, options) => execFile( command, args, - { timeout: options?.timeout, maxBuffer: options?.maxBuffer, windowsHide: true }, + { + timeout: options?.timeout, + maxBuffer: options?.maxBuffer, + signal: options?.signal, + windowsHide: true, + }, (error, stdout, stderr) => { if (error && error.code === "ENOENT") { resolvePromise({ status: null, stdout: "", stderr: "", error }); @@ -85,6 +90,7 @@ export interface MediaMetadata { /** Video stream carries alpha (pix_fmt or the VP8/VP9 alpha_mode tag). */ hasAlpha?: boolean; durationSeconds?: number; + keptStreamsSeconds?: number; source?: PreviewSourceFacts; /** Every stream as `type:codec[flags]`, for a failure report. */ streams?: string[]; @@ -93,6 +99,7 @@ export interface MediaMetadata { interface FfprobeStream { codec_type?: string; + duration?: string; codec_name?: string; profile?: string; pix_fmt?: string; @@ -274,6 +281,14 @@ type ProbeOutput = { format?: { duration?: string; bit_rate?: string }; }; +function streamSeconds(stream: FfprobeStream): number | undefined { + const tagged = /^(\d+):(\d+):([\d.]+)$/.exec(stream.tags?.DURATION ?? ""); + const seconds = tagged + ? Number(tagged[1]) * 3600 + Number(tagged[2]) * 60 + Number(tagged[3]) + : Number(stream.duration); + return Number.isFinite(seconds) && seconds > 0 ? seconds : undefined; +} + function audioOf(streams: FfprobeStream[]): Pick { const audioStream = decodableAudioStream(streams); return audioStream === null ? { hasAudio: false } : { hasAudio: true, audioStream }; @@ -294,6 +309,13 @@ function metadataFromProbe(kind: MediaMetadata["kind"], parsed: ProbeOutput): Me metadata.hasAlpha = stream !== undefined && videoStreamHasAlpha(stream); const duration = Number(parsed.format?.duration); if (Number.isFinite(duration) && duration > 0) metadata.durationSeconds = duration; + const keptAudio = (parsed.streams ?? []).filter((item) => item.codec_type === "audio")[ + metadata.audioStream ?? -1 + ]; + const longestKept = Math.max( + ...[stream, keptAudio].flatMap((item) => (item ? [streamSeconds(item) ?? NaN] : [])), + ); + if (Number.isFinite(longestKept)) metadata.keptStreamsSeconds = longestKept; metadata.source = sourceFactsOf(stream, parsed.format?.bit_rate); } return metadata; @@ -348,6 +370,7 @@ export async function probeAudioTrack( export async function probeMediaMetadata( filePath: string, runner: FfprobeRunner = execFileRunner, + signal?: AbortSignal, ): Promise { const kind = inferKindFromPath(filePath); if (kind === "audio" || kind === "unknown") { @@ -372,14 +395,14 @@ export async function probeMediaMetadata( "-v", "error", "-show_entries", - "stream=codec_type,codec_name,profile,pix_fmt,color_space,color_transfer,color_primaries,bits_per_raw_sample,width,height,bit_rate,r_frame_rate,avg_frame_rate:stream_disposition:stream_tags=alpha_mode:format=duration,bit_rate", + "stream=codec_type,codec_name,profile,pix_fmt,color_space,color_transfer,color_primaries,bits_per_raw_sample,width,height,bit_rate,r_frame_rate,avg_frame_rate,duration:stream_disposition:stream_tags=alpha_mode,DURATION:format=duration,bit_rate", "-of", "json", ...mediaInputArgs(filePath), "--", filePath, ], - { timeout: 15_000, maxBuffer: 1024 * 1024 }, + { timeout: 15_000, maxBuffer: 1024 * 1024, signal }, ); if (result.error?.code === "ENOENT") { diff --git a/packages/studio-server/src/helpers/proxyTranscoder.test.ts b/packages/studio-server/src/helpers/proxyTranscoder.test.ts index c82f834aa6..538deef37a 100644 --- a/packages/studio-server/src/helpers/proxyTranscoder.test.ts +++ b/packages/studio-server/src/helpers/proxyTranscoder.test.ts @@ -297,7 +297,12 @@ describe("resolveProxy on a long source", () => { ]); }); - it("refuses a join of pieces with sound that came out short, and makes its pieces again", async () => { + const isJoinedCopy = (path: string) => basename(path).startsWith(".tmp-"); + + /** A source with sound whose files last what `lengthFor` says when they are measured. */ + async function loadWithSound( + lengthFor: (path: string) => number | undefined | Promise, + ) { const { spawn, calls } = createSpawnSpy(); vi.resetModules(); vi.doMock("@hyperframes/core/preview-proof", () => ({ previewToken: () => "a".repeat(64) })); @@ -306,28 +311,41 @@ describe("resolveProxy on a long source", () => { ...(await importOriginal()), findFfBinary: () => FFMPEG_PATH, })); - let joinedSeconds = 2 * PIECE_SECONDS; - const isJoinedCopy = (path: string) => basename(path).startsWith(".tmp-"); vi.doMock("./mediaMetadata.js", () => ({ probeMediaMetadata: async (path: string) => ({ kind: "video", color: { isHdr: false, hdrTransfer: null }, - durationSeconds: isJoinedCopy(path) ? joinedSeconds : lengthOf(path, LONG_SECONDS), + durationSeconds: await lengthFor(path), audioStream: 0, }), probeFirstFrameColour: async () => ({}), })); - const { resolveProxy, getProxyCachePath, clearFailedTranscodesForTest } = - await import("./proxyTranscoder.js"); const projectDir = tmpProject(); const sourcePath = join(projectDir, "talk.mov"); writeFileSync(sourcePath, "source-bytes"); - const cacheDirectory = join(projectDir, ".transcode-cache"); + return { + ...(await import("./proxyTranscoder.js")), + calls, + projectDir, + sourcePath, + cacheDirectory: join(projectDir, ".transcode-cache"), + }; + } + + it("refuses a join of pieces with sound that came out short, and makes its pieces again", async () => { + let joinedSeconds = 2 * PIECE_SECONDS; + const { resolveProxy, getProxyCachePath, clearFailedTranscodesForTest, ...made } = + await loadWithSound((path) => + isJoinedCopy(path) ? joinedSeconds : lengthOf(path, LONG_SECONDS), + ); + const { calls, projectDir, sourcePath, cacheDirectory } = made; const short = resolveProxy(projectDir, sourcePath).catch((error: unknown) => error); await answerAll(calls); expect(calls.at(-1)!.args).not.toContain("-xerror"); - expect(String(await short)).toContain(`lasts ${(2 * PIECE_SECONDS).toFixed(1)} s of`); + expect(String(await short)).toContain( + `the joined copy lasts ${(2 * PIECE_SECONDS).toFixed(1)} s of`, + ); expect(copiesIn(cacheDirectory)).toEqual([]); clearFailedTranscodesForTest(); @@ -339,6 +357,45 @@ describe("resolveProxy on a long source", () => { expect(startsOf(calls).length - piecesBefore).toBe(piecesBefore); }); + it("refuses a join whose short piece shortens the copy it adds up to", async () => { + const lastPiece = /\.part-[^/\\]*-2\.\w+$/; + const shortBy = 14; + const { resolveProxy, calls, projectDir, sourcePath, cacheDirectory } = await loadWithSound( + (path) => { + if (lastPiece.test(path)) return LONG_SECONDS - 2 * PIECE_SECONDS - shortBy; + return isJoinedCopy(path) ? LONG_SECONDS - shortBy : lengthOf(path, LONG_SECONDS); + }, + ); + + const short = resolveProxy(projectDir, sourcePath).catch((error: unknown) => error); + await answerAll(calls); + expect(String(await short)).toContain( + `piece 3 lasts ${(LONG_SECONDS - 2 * PIECE_SECONDS - shortBy).toFixed(1)} s of`, + ); + expect(copiesIn(cacheDirectory)).toEqual([]); + }); + + it("keeps no copy when its last caller leaves while the copy is being measured", async () => { + let measure: (seconds: number) => void = () => {}; + const measuring = new Promise((resolve) => (measure = resolve)); + const { resolveProxy, getProxyCachePath, calls, projectDir, sourcePath, cacheDirectory } = + await loadWithSound((path) => + isJoinedCopy(path) ? measuring : lengthOf(path, LONG_SECONDS), + ); + const leave = new AbortController(); + + const left = resolveProxy(projectDir, sourcePath, "h264", undefined, { + signal: leave.signal, + }).catch((error: unknown) => error); + await answerAll(calls); + leave.abort(); + expect(await left).toBe(leave.signal.reason); + measure(LONG_SECONDS); + await flush(50); + expect(existsSync(getProxyCachePath(projectDir, sourcePath))).toBe(false); + expect(readdirSync(cacheDirectory).filter((name) => name.startsWith(".part-"))).toHaveLength(3); + }); + it.skipIf(process.platform === "win32")( "runs the join from the cache folder and names the list there by its bare name", async () => { diff --git a/packages/studio-server/src/helpers/proxyTranscoder.ts b/packages/studio-server/src/helpers/proxyTranscoder.ts index 106d2733c5..efe0087dbe 100644 --- a/packages/studio-server/src/helpers/proxyTranscoder.ts +++ b/packages/studio-server/src/helpers/proxyTranscoder.ts @@ -670,16 +670,24 @@ async function encodeInChunks( } finally { rmSync(listPath, { force: true }); } - let wanted = 0; - for (const piece of pieces) wanted += (await probeMediaMetadata(piece)).durationSeconds ?? NaN; - const { durationSeconds: joined } = await probeMediaMetadata(tempPath); + const measured = [...pieces, tempPath]; + const lengths = ranges.map((range) => range.lengthSeconds); + const wanted = [...lengths, lengths.reduce((sum, length) => sum + length, 0)]; + let short: string | undefined; + for (const [index, path] of measured.entries()) { + const seconds = (await probeMediaMetadata(path, undefined, signal)).durationSeconds; + signal.throwIfAborted(); + if ( + short === undefined && + !((seconds ?? NaN) >= wanted[index]! - JOIN_SHORTFALL_ALLOWED_SECONDS) + ) { + const what = path === tempPath ? "the joined copy" : `piece ${index + 1}`; + short = `${what} lasts ${seconds?.toFixed(1) ?? "an unknown time"} s of ${wanted[index]!.toFixed(1)} s`; + } + } for (const piece of pieces) if (existsSync(piece)) unlinkSync(piece); - if (joined === undefined || !(joined >= wanted - JOIN_SHORTFALL_ALLOWED_SECONDS)) { - throw new ProxyTranscodeError( - `the joined copy lasts ${joined?.toFixed(1) ?? "an unknown time"} s of its pieces' ${wanted.toFixed(1)} s; its pieces are made again next time`, - null, - "", - ); + if (short !== undefined) { + throw new ProxyTranscodeError(`${short}; its pieces are made again next time`, null, ""); } } @@ -795,7 +803,10 @@ async function runFfmpeg( ...["-map", "0:V:0"], ...(metadata.audioStream === undefined ? [] : ["-map", `0:a:${metadata.audioStream}`]), ]; - const totalSeconds = copiedSeconds(metadata.durationSeconds, limitSeconds); + const totalSeconds = copiedSeconds( + metadata.keptStreamsSeconds ?? metadata.durationSeconds, + limitSeconds, + ); // libvpx scales poorly across threads, so alpha pieces run side by side with the cores shared out. const gate = keepsAlpha ? ALPHA_PIECE_GATE : UNGATED; const vp8Threads = (pieces: number) => [ @@ -1031,6 +1042,7 @@ async function transcodeToCache( (progress) => reportProgress(job, progress), () => job.background && !job.priority, ); + job.abandoned.signal.throwIfAborted(); renameSync(tempPath, cachePath); writeCopyIndex(contentIndex, cachePath); maintainProxyCache(cacheDir);