Skip to content

armgit / ente

Public Imported from GitHub
0

πŸ’š End-to-end encrypted cloud for everything.

Sketch

Manav Rathi3677d53ea9d1
diff --git a/web/packages/gallery/services/ffmpeg/index.ts b/web/packages/gallery/services/ffmpeg/index.ts
index 4a9f27595f..fd44297021 100644
--- a/web/packages/gallery/services/ffmpeg/index.ts
+++ b/web/packages/gallery/services/ffmpeg/index.ts
@@ -20,7 +20,7 @@ import {
inputPathPlaceholder,
outputPathPlaceholder,
} from "./constants";
-import { ffmpegExecWeb } from "./web";
+import { determineVideoDurationWeb, ffmpegExecWeb } from "./web";
/**
* Generate a thumbnail for the given video using a Wasm FFmpeg running in a web
diff --git a/web/packages/gallery/services/ffmpeg/web.ts b/web/packages/gallery/services/ffmpeg/web.ts
index acf2eb5dda..bbcd67beff 100644
--- a/web/packages/gallery/services/ffmpeg/web.ts
+++ b/web/packages/gallery/services/ffmpeg/web.ts
@@ -15,7 +15,7 @@ import {
let _ffmpeg: Promise<FFmpeg> | undefined;
/** Queue of in-flight requests. */
-const _ffmpegTaskQueue = new PromiseQueue<Uint8Array>();
+const _ffmpegTaskQueue = new PromiseQueue<Uint8Array | number>();
/**
* Return the shared {@link FFmpeg} instance, lazily creating and loading it if
@@ -45,7 +45,7 @@ const createFFmpeg = async () => {
*
* @param command The FFmpeg command to execute.
*
- * @param blob The input data on which to run the command, provided as a blob.
+ * @param blob The input blob on which to run the command.
*
* @param outputFileExtension The extension of the (temporary) output file which
* will be generated by the command.
@@ -66,7 +66,26 @@ export const ffmpegExecWeb = async (
// So serialize them using a promise queue.
return _ffmpegTaskQueue.add(() =>
ffmpegExec(ffmpeg, command, outputFileExtension, blob),
- );
+ ) as Promise<Uint8Array>;
+};
+
+/**
+ * Determine the duration of the given video blob.
+ *
+ * This is a specialized variant of {@link ffmpegExecWeb} that uses the same
+ * queue but internally uses ffprobe to try and determine the video's duration.
+ *
+ * @param blob The input blob on which to run the command, provided as a blob.
+ *
+ * @returns The duration of the {@link blob} (if it indeed is a video).
+ */
+export const determineVideoDurationWeb = async (
+ blob: Blob,
+): Promise<number> => {
+ const ffmpeg = await ffmpegLazy();
+ return _ffmpegTaskQueue.add(() =>
+ ffprobeExecVideoDuration(ffmpeg, blob),
+ ) as Promise<number>;
};
const ffmpegExec = async (
@@ -75,53 +94,78 @@ const ffmpegExec = async (
outputFileExtension: string,
blob: Blob,
) => {
- const mountDir = "/mount";
- const inputFileName = newID("in_");
- const inputPath = joinPath(mountDir, inputFileName);
-
const outputSuffix = outputFileExtension ? "." + outputFileExtension : "";
const outputPath = newID("out_") + outputSuffix;
- const inputFile = new File([blob], inputFileName);
-
// Exit status of the ffmpeg.exec invocation.
// `0` if no error, `!= 0` if timeout (1) or error.
let status: number | undefined;
- try {
- const startTime = Date.now();
+ return withInputMount(ffmpeg, blob, async (inputPath) => {
+ try {
+ const startTime = Date.now();
- await ffmpeg.createDir(mountDir);
- await ffmpeg.mount(FFFSType.WORKERFS, { files: [inputFile] }, mountDir);
+ let resolvedCommand: string[];
+ if (Array.isArray(command)) {
+ resolvedCommand = command;
+ } else {
+ const isHDR = await isHDRVideo(ffmpeg, inputPath);
+ resolvedCommand = isHDR ? command.hdr : command.default;
+ }
- let resolvedCommand: string[];
- if (Array.isArray(command)) {
- resolvedCommand = command;
- } else {
- const isHDR = await isHDRVideo(ffmpeg, inputPath);
- resolvedCommand = isHDR ? command.hdr : command.default;
- }
+ const cmd = substitutePlaceholders(
+ resolvedCommand,
+ inputPath,
+ outputPath,
+ );
- const cmd = substitutePlaceholders(
- resolvedCommand,
- inputPath,
- outputPath,
- );
+ status = await ffmpeg.exec(cmd);
+ if (status !== 0) {
+ log.info(
+ `[wasm] ffmpeg command failed with exit code ${status}: ${cmd.join(" ")}`,
+ );
+ throw new Error(
+ `ffmpeg command failed with exit code ${status}`,
+ );
+ }
- status = await ffmpeg.exec(cmd);
- if (status !== 0) {
- log.info(
- `[wasm] ffmpeg command failed with exit code ${status}: ${cmd.join(" ")}`,
- );
- throw new Error(`ffmpeg command failed with exit code ${status}`);
+ const result = await ffmpeg.readFile(outputPath);
+ if (typeof result == "string")
+ throw new Error("Expected binary data");
+
+ const ms = Date.now() - startTime;
+ log.debug(() => `[wasm] ffmpeg ${cmd.join(" ")} (${ms} ms)`);
+ return result;
+ } finally {
+ try {
+ await ffmpeg.deleteFile(outputPath);
+ } catch (e) {
+ // Output file might not even exist if the command did not succeed,
+ // so only log on success.
+ if (status === 0) {
+ log.error(`Failed to remove output ${outputPath}`, e);
+ }
+ }
}
+ });
+};
- const result = await ffmpeg.readFile(outputPath);
- if (typeof result == "string") throw new Error("Expected binary data");
+const withInputMount = async <T>(
+ ffmpeg: FFmpeg,
+ blob: Blob,
+ f: (inputPath: string) => Promise<T>,
+) => {
+ const mountDir = "/mount";
+ const inputFileName = newID("in_");
+ const inputPath = joinPath(mountDir, inputFileName);
- const ms = Date.now() - startTime;
- log.debug(() => `[wasm] ffmpeg ${cmd.join(" ")} (${ms} ms)`);
- return result;
+ const inputFile = new File([blob], inputFileName);
+
+ try {
+ await ffmpeg.createDir(mountDir);
+ await ffmpeg.mount(FFFSType.WORKERFS, { files: [inputFile] }, mountDir);
+
+ return await f(inputPath);
} finally {
try {
await ffmpeg.unmount(mountDir);
@@ -133,15 +177,6 @@ const ffmpegExec = async (
} catch (e) {
log.error(`Failed to delete mount directory ${mountDir}`, e);
}
- try {
- await ffmpeg.deleteFile(outputPath);
- } catch (e) {
- // Output file might not even exist if the command did not succeed,
- // so only log on success.
- if (status === 0) {
- log.error(`Failed to remove output ${outputPath}`, e);
- }
- }
}
};
@@ -258,3 +293,35 @@ const ffprobeOutput = async (
}
}
};
+
+const ffprobeExecVideoDuration = async (ffmpeg: FFmpeg, blob: Blob) =>
+ withInputMount(ffmpeg, blob, async (inputPath) => {
+ const jsonString = await ffprobeOutput(
+ ffmpeg,
+ [
+ ["-i", inputPath],
+ // Show information about streams.
+ "-show_streams",
+ // Select the first video stream. This is not necessarily
+ // correct in a multi stream file because the ffmpeg automatic
+ // mapping will use the highest resolution stream, but short of
+ // reinventing ffmpeg's resolution mechanism, it is a reasonable
+ // assumption for our current heuristic check.
+ ["-select_streams", "v:0"],
+ // Output JSON
+ ["-of", "json"],
+ ["-o", "output.json"],
+ ].flat(),
+ "output.json",
+ );
+
+ const output = IsHDRVideoFFProbeOutput.parse(JSON.parse(jsonString));
+ switch (output.streams[0]?.color_transfer) {
+ case "smpte2084":
+ case "arib-std-b67":
+ // TODO: Implement me
+ return 1;
+ default:
+ return 0;
+ }
+ });