diff --git a/packages/studio-server/src/helpers/proxyTranscoder.test.ts b/packages/studio-server/src/helpers/proxyTranscoder.test.ts index 7b69b215c2..d6cfba38bd 100644 --- a/packages/studio-server/src/helpers/proxyTranscoder.test.ts +++ b/packages/studio-server/src/helpers/proxyTranscoder.test.ts @@ -272,7 +272,8 @@ describe("resolveProxy on a long source", () => { await answerAll(calls); await result; const joinArgs = calls.at(-1)!.args; - expect(joinArgs.slice(1, 13)).toEqual([ + expect(joinArgs.slice(1, 14)).toEqual([ + "-xerror", "-protocol_whitelist", "file", "-f", @@ -288,6 +289,47 @@ 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 { spawn, calls } = createSpawnSpy(); + vi.resetModules(); + vi.doMock("@hyperframes/core/preview-proof", () => ({ previewToken: () => "a".repeat(64) })); + vi.doMock("node:child_process", () => ({ spawn, default: { spawn } })); + vi.doMock("@hyperframes/parsers/ff-binaries", async (importOriginal) => ({ + ...(await importOriginal()), + findFfBinary: () => FFMPEG_PATH, + })); + let joinedSeconds = 2 * PIECE_SECONDS; + vi.doMock("./mediaMetadata.js", () => ({ + probeMediaMetadata: async (path: string) => ({ + kind: "video", + color: { isHdr: false, hdrTransfer: null }, + durationSeconds: path.includes(".transcode-cache") ? joinedSeconds : LONG_SECONDS, + 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"); + + 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(copiesIn(cacheDirectory)).toEqual([]); + + clearFailedTranscodesForTest(); + joinedSeconds = LONG_SECONDS; + const piecesBefore = startsOf(calls).length; + const whole = resolveProxy(projectDir, sourcePath); + await answerAll(calls); + expect(await whole).toBe(getProxyCachePath(projectDir, sourcePath)); + expect(startsOf(calls).length - piecesBefore).toBe(piecesBefore); + }); + it.skipIf(process.platform === "win32")( "runs the join from the cache folder and names the list there by its bare name", async () => { @@ -380,16 +422,18 @@ describe("resolveProxy on a long source", () => { ]); const proxyPath = await resolveProxy(projectDir, sourcePath); - const streams = execFileSync( - findFfBinary("ffprobe")!, - [ - ...["-v", "error", "-show_entries", "stream=codec_type:format=duration"], - ...["-of", "csv=p=0", "--", proxyPath], - ], - { encoding: "utf8" }, - ).split("\n"); - expect(streams).toEqual(expect.arrayContaining(["video", "audio"])); - expect(Number(streams.find((line) => /^[\d.]+$/.test(line)))).toBeCloseTo(LONG_SECONDS, 0); + const probed = JSON.parse( + execFileSync( + findFfBinary("ffprobe")!, + [ + ...["-v", "error", "-show_entries", "stream=codec_type:format=duration"], + ...["-of", "json", "--", proxyPath], + ], + { encoding: "utf8" }, + ), + ) as { streams: Array<{ codec_type: string }>; format: { duration: string } }; + expect(probed.streams.map((stream) => stream.codec_type).sort()).toEqual(["audio", "video"]); + expect(Number(probed.format.duration)).toBeCloseTo(LONG_SECONDS, 0); }, 60_000, ); diff --git a/packages/studio-server/src/helpers/proxyTranscoder.ts b/packages/studio-server/src/helpers/proxyTranscoder.ts index 243c50508c..67ccd13dbe 100644 --- a/packages/studio-server/src/helpers/proxyTranscoder.ts +++ b/packages/studio-server/src/helpers/proxyTranscoder.ts @@ -670,9 +670,20 @@ async function encodeInChunks( } finally { rmSync(listPath, { force: true }); } + const wanted = ranges.reduce((sum, range) => sum + range.lengthSeconds, 0); + const { durationSeconds: joined } = await probeMediaMetadata(tempPath); 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 ${wanted.toFixed(1)} s; its pieces are made again next time`, + null, + "", + ); + } } +const JOIN_SHORTFALL_ALLOWED_SECONDS = 1; + const KEYFRAME_EVERY_SECOND_ARGS = ["-force_key_frames", "expr:gte(t,n_forced*1)"]; // Fixed recipe; changing either array means bumping PROXY_PARAMS_VERSION. const H264_ARGS = [ @@ -833,7 +844,12 @@ async function runFfmpeg( const cwd = JOIN_FROM_CACHE_FOLDER ? dirname(listPath) : undefined; return spawnFfmpeg( ffmpegPath, - concatArgs(cwd ? basename(listPath) : listPath, target, variant), + concatArgs( + cwd ? basename(listPath) : listPath, + target, + variant, + metadata.audioStream !== undefined, + ), CONCAT_TIMEOUT_MS, signal, undefined, @@ -850,12 +866,15 @@ async function runFfmpeg( } } -const LET_FFMPEG_MOVE_SOUND_TIMESTAMPS_AT_SEAMS = { exitOnError: false }; - -function concatArgs(listPath: string, target: string, variant: ProxyVariant): string[] { +function concatArgs( + listPath: string, + target: string, + variant: ProxyVariant, + piecesHaveSound: boolean, +): string[] { return [ "-y", - ...concatListInputArgs(listPath, LET_FFMPEG_MOVE_SOUND_TIMESTAMPS_AT_SEAMS), + ...concatListInputArgs(listPath, { exitOnError: !piecesHaveSound }), "-c", "copy", ...(variant === "h264" ? ["-movflags", "+faststart"] : []),