π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
node 1
Manav Rathiadf1379b9e9d
diff --git a/desktop/src/main/ipc.ts b/desktop/src/main/ipc.tsindex b74b19ec6c..74f7821dcf 100644--- a/desktop/src/main/ipc.ts+++ b/desktop/src/main/ipc.ts@@ -13,7 +13,6 @@ import type { BrowserWindow } from "electron";import { ipcMain } from "electron/main";import type {CollectionMapping,- FFmpegCommand,FolderWatch,PendingUploads,UtilityProcessType,@@ -32,7 +31,6 @@ import {openLogDirectory,selectDirectory,} from "./services/dir";-import { ffmpegExec } from "./services/ffmpeg";import {fsExists,fsFindFiles,@@ -188,16 +186,6 @@ export const attachIPCHandlers = () => {) => generateImageThumbnail(dataOrPathOrZipItem, maxDimension, maxSize),);- ipcMain.handle(- "ffmpegExec",- (- _,- command: FFmpegCommand,- dataOrPathOrZipItem: Uint8Array | string | ZipItem,- outputFileExtension: string,- ) => ffmpegExec(command, dataOrPathOrZipItem, outputFileExtension),- );-// - UploadipcMain.handle("listZipItems", (_, zipPath: string) =>diff --git a/desktop/src/main/services/ffmpeg.ts b/desktop/src/main/services/ffmpeg-worker.tssimilarity index 96%rename from desktop/src/main/services/ffmpeg.tsrename to desktop/src/main/services/ffmpeg-worker.tsindex b5587b6ba1..ab9f6910be 100644--- a/desktop/src/main/services/ffmpeg.ts+++ b/desktop/src/main/services/ffmpeg-worker.ts@@ -1,9 +1,17 @@+/**+ * @file ffmpeg invocations. This code runs in a utility process.+ */++// See [Note: Using Electron APIs in UtilityProcess] about what we can and+// cannot import.+import { expose } from "comlink";import pathToFfmpeg from "ffmpeg-static";import { randomBytes } from "node:crypto";import fs from "node:fs/promises";import path, { basename } from "node:path";import type { FFmpegCommand, ZipItem } from "../../types/ipc";-import log from "../log";+import log from "../log-worker";+import { messagePortMainEndpoint } from "../utils/comlink";import { execAsync } from "../utils/electron";import {deleteTempFileIgnoringErrors,@@ -16,6 +24,21 @@ const ffmpegPathPlaceholder = "FFMPEG";const inputPathPlaceholder = "INPUT";const outputPathPlaceholder = "OUTPUT";+log.debugString("Started ffmpeg utility process");++process.parentPort.once("message", (e) => {+ // Expose an instance of `ElectronFFmpegWorker & ElectronFFmpegWorkerNode`+ // on the port we got from our parent.+ expose(+ {+ ffmpegExec,+ ffmpegConvertToMP4,+ ffmpegGenerateHLSPlaylistAndSegments,+ },+ messagePortMainEndpoint(e.ports[0]!),+ );+});+/*** Run a FFmpeg command*@@ -43,7 +66,7 @@ const outputPathPlaceholder = "OUTPUT";** But I'm not sure if our code is supposed to be able to use it, and how.*/-export const ffmpegExec = async (+const ffmpegExec = async (command: FFmpegCommand,dataOrPathOrZipItem: Uint8Array | string | ZipItem,outputFileExtension: string,@@ -63,7 +86,9 @@ export const ffmpegExec = async (resolvedCommand = command;} else {const isHDR = await isHDRVideo(inputFilePath);- log.debug(() => [basename(inputFilePath), { isHDR }]);+ log.debugString(+ `${basename(inputFilePath)} ${JSON.stringify({ isHDR })}`,+ );resolvedCommand = isHDR ? command.hdr : command.default;}@@ -123,7 +148,7 @@ const ffmpegBinaryPath = () => {* @param outputFilePath The path to a file on the user's local file system where* we should write the converted MP4 video.*/-export const ffmpegConvertToMP4 = async (+const ffmpegConvertToMP4 = async (inputFilePath: string,outputFilePath: string,): Promise<void> => {@@ -179,14 +204,16 @@ export interface FFmpegGenerateHLSPlaylistAndSegmentsResult {* If the video is such that it doesn't require stream generation, then this* function returns `undefined`.*/-export const ffmpegGenerateHLSPlaylistAndSegments = async (+const ffmpegGenerateHLSPlaylistAndSegments = async (inputFilePath: string,outputPathPrefix: string,): Promise<FFmpegGenerateHLSPlaylistAndSegmentsResult | undefined> => {const { isH264, isBT709, bitrate } =await detectVideoCharacteristics(inputFilePath);- log.debug(() => [basename(inputFilePath), { isH264, isBT709, bitrate }]);+ log.debugString(+ `${basename(inputFilePath)} ${JSON.stringify({ isH264, isBT709, bitrate })}`,+ );// If the video is smaller than 10 MB, and already H.264 (the codec we are// going to use for the conversion), then a streaming variant is not muchdiff --git a/desktop/src/main/services/workers.ts b/desktop/src/main/services/workers.tsindex cb6923bc62..c9977f4ed1 100644--- a/desktop/src/main/services/workers.ts+++ b/desktop/src/main/services/workers.ts@@ -12,12 +12,22 @@ import { app, utilityProcess } from "electron/main";import path from "node:path";import type { UtilityProcessType } from "../../types/ipc";import log, { processUtilityProcessLogMessage } from "../log";+import type { FFmpegGenerateHLSPlaylistAndSegmentsResult } from "./ffmpeg-worker";/** The active ML utility process, if any. */-let _child: UtilityProcess | undefined;+let _childML: UtilityProcess | undefined;++/** The active ffmpeg utility process, if any. */+let _childFFmpeg: UtilityProcess | undefined;/**- * Create a new ML utility process, terminating the older ones (if any).+ * Create a new utility process of the given {@link type}, terminating the older+ * ones (if any).+ *+ * The following note explains the reasoning why utility processes were used for+ * the first workload (ML) that was handled this way. Similar reasoning applies+ * to subsequent workloads (ffmpeg) that have been offloaded to utility+ * processes to avoid stutter in the UI.** [Note: ML IPC]*@@ -77,18 +87,20 @@ export const triggerCreateUtilityProcess = (window: BrowserWindow,) => {switch (type) {- // eslint-disable-next-line @typescript-eslint/no-unnecessary-conditioncase "ml":triggerCreateMLUtilityProcess(window);break;+ case "ffmpeg":+ triggerCreateFFmpegUtilityProcess(window);+ break;}};export const triggerCreateMLUtilityProcess = (window: BrowserWindow) => {- if (_child) {+ if (_childML) {log.debug(() => "Terminating previous ML utility process");- _child.kill();- _child = undefined;+ _childML.kill();+ _childML = undefined;}const { port1, port2 } = new MessageChannelMain();@@ -99,9 +111,9 @@ export const triggerCreateMLUtilityProcess = (window: BrowserWindow) => {window.webContents.postMessage("utilityProcessPort/ml", undefined, [port2]);- handleMessagesFromUtilityProcess(child);+ handleMessagesFromMLUtilityProcess(child);- _child = child;+ _childML = child;};/**@@ -127,7 +139,7 @@ export const triggerCreateMLUtilityProcess = (window: BrowserWindow) => {* - When we need to communicate from the utility process to the main process,* we use the `parentPort` in the utility process.*/-const handleMessagesFromUtilityProcess = (child: UtilityProcess) => {+const handleMessagesFromMLUtilityProcess = (child: UtilityProcess) => {child.on("message", (m: unknown) => {if (processUtilityProcessLogMessage("[ml-worker]", m)) {return;@@ -135,3 +147,68 @@ const handleMessagesFromUtilityProcess = (child: UtilityProcess) => {log.info("Ignoring unknown message from ML utility process", m);});};++export const triggerCreateFFmpegUtilityProcess = (window: BrowserWindow) => {+ if (_childFFmpeg) {+ log.debug(() => "Terminating previous ffmpeg utility process");+ _childFFmpeg.kill();+ _childFFmpeg = undefined;+ }++ const { port1, port2 } = new MessageChannelMain();++ const child = utilityProcess.fork(path.join(__dirname, "ffmpeg-worker.js"));+ // TODO+ const userDataPath = app.getPath("userData");+ child.postMessage({ userDataPath }, [port1]);++ window.webContents.postMessage("utilityProcessPort/ffmpeg", undefined, [+ port2,+ ]);++ handleMessagesFromFFmpegUtilityProcess(child);++ _childFFmpeg = child;+};++const handleMessagesFromFFmpegUtilityProcess = (child: UtilityProcess) => {+ child.on("message", (m: unknown) => {+ if (processUtilityProcessLogMessage("[ffmpeg-worker]", m)) {+ return;+ }+ log.info("Ignoring unknown message from ffmpeg utility process", m);+ });+};++/**+ * The port exposed by _childFFmpeg (i.e., by the utility process running+ * `ffmpeg-worker.ts`) provides an interface that conforms to+ * {@link ElectronFFmpegWorker} (meant for use by the web layer), and in+ * addition provides other "private" function meant for use by (the node layer).+ *+ * This interface lists the functions exposed for use by the node layer.+ */+export interface ElectronFFmpegWorkerNode {+ ffmpegConvertToMP4: (+ inputFilePath: string,+ outputFilePath: string,+ ) => Promise<void>;++ ffmpegGenerateHLSPlaylistAndSegments: (+ inputFilePath: string,+ outputPathPrefix: string,+ ) => Promise<FFmpegGenerateHLSPlaylistAndSegmentsResult | undefined>;+}++/**+ * Return a handle to the already running ffmpeg utility process.+ *+ * This assumes that the web layer has already initiated the utility process by+ * invoking `triggerCreateUtilityProcess("ffmpeg")`, otherwise this function+ * will throw.+ */+export const electronFFmpegWorkerNodeIfRunning = () => {+ const child = _childFFmpeg;+ if (!child) throw new Error("ffmpeg utility process has not been started");+ return child as unknown as ElectronFFmpegWorkerNode;+};diff --git a/desktop/src/main/stream.ts b/desktop/src/main/stream.tsindex 01d591042f..04332b5894 100644--- a/desktop/src/main/stream.ts+++ b/desktop/src/main/stream.ts@@ -8,11 +8,8 @@ import fs from "node:fs/promises";import { Readable, Writable } from "node:stream";import { pathToFileURL } from "node:url";import log from "./log";-import {- ffmpegConvertToMP4,- ffmpegGenerateHLSPlaylistAndSegments,- type FFmpegGenerateHLSPlaylistAndSegmentsResult,-} from "./services/ffmpeg";+import { type FFmpegGenerateHLSPlaylistAndSegmentsResult } from "./services/ffmpeg-worker";+import { electronFFmpegWorkerNodeIfRunning } from "./services/workers";import { markClosableZip, openZip } from "./services/zip";import { wait } from "./utils/common";import { writeStream } from "./utils/stream";@@ -238,8 +235,9 @@ const handleConvertToMP4Write = async (request: Request) => {await writeStream(inputTempFilePath, request.body!);const outputTempFilePath = await makeTempFilePath("mp4");+ const worker = electronFFmpegWorkerNodeIfRunning();try {- await ffmpegConvertToMP4(inputTempFilePath, outputTempFilePath);+ await worker.ffmpegConvertToMP4(inputTempFilePath, outputTempFilePath);} catch (e) {log.error("Conversion to MP4 failed", e);await deleteTempFileIgnoringErrors(outputTempFilePath);@@ -311,6 +309,8 @@ const handleGenerateHLSWrite = async (}}+ const worker = electronFFmpegWorkerNodeIfRunning();+const {path: inputFilePath,isFileTemporary: isInputFileTemporary,@@ -322,7 +322,7 @@ const handleGenerateHLSWrite = async (try {await writeToTemporaryInputFile();- result = await ffmpegGenerateHLSPlaylistAndSegments(+ result = await worker.ffmpegGenerateHLSPlaylistAndSegments(inputFilePath,outputFilePathPrefix,);diff --git a/desktop/src/types/ipc.ts b/desktop/src/types/ipc.tsindex db1d009f8b..23f57af554 100644--- a/desktop/src/types/ipc.ts+++ b/desktop/src/types/ipc.ts@@ -5,7 +5,7 @@* See [Note: types.ts <-> preload.ts <-> ipc.ts]*/-export type UtilityProcessType = "ml";+export type UtilityProcessType = "ml" | "ffmpeg";export interface AppUpdate {autoUpdatable: boolean;diff --git a/web/packages/gallery/services/ffmpeg/index.ts b/web/packages/gallery/services/ffmpeg/index.tsindex d2f6af4756..8833249555 100644--- a/web/packages/gallery/services/ffmpeg/index.ts+++ b/web/packages/gallery/services/ffmpeg/index.ts@@ -30,7 +30,7 @@ let _electronFFmpegWorker: Promise<ElectronFFmpegWorker> | undefined;* Handle to the on-demand lazily created utility process in the Node.js layer* that exposes an {@link ElectronFFmpegWorker} interface.*/-const electronFFmpegWorker = () =>+export const getElectronFFmpegWorker = () =>(_electronFFmpegWorker ??= createElectronFFmpegWorker());const createElectronFFmpegWorker = () =>@@ -94,7 +94,7 @@ const _generateVideoThumbnail = async (export const generateVideoThumbnailNative = async (fsUploadItem: FileSystemUploadItem,) =>- electronFFmpegWorker().then((electronFW) =>+ getElectronFFmpegWorker().then((electronFW) =>_generateVideoThumbnail((seekTime: number) =>electronFW.ffmpegExec(makeGenThumbnailCommand(seekTime),@@ -162,7 +162,7 @@ export const extractVideoMetadata = async (uploadItem instanceof File? await ffmpegExecWeb(command, uploadItem, "txt"): await (- await electronFFmpegWorker()+ await getElectronFFmpegWorker()).ffmpegExec(command, toDataOrPathOrZipEntry(uploadItem), "txt"),);};@@ -312,7 +312,8 @@ export const convertToMP4 = async (blob: Blob): Promise<Blob | Uint8Array> => {};const convertToMP4Native = async (electron: Electron, blob: Blob) => {- const token = await initiateConvertToMP4(electron, blob);+ const electronFFmpegWorker = await getElectronFFmpegWorker();+ const token = await initiateConvertToMP4(electronFFmpegWorker, blob);const mp4Blob = await readVideoStream(electron, token).then((res) =>res.blob(),);diff --git a/web/packages/gallery/services/video.ts b/web/packages/gallery/services/video.tsindex 8dd553aeed..1a12ba63c5 100644--- a/web/packages/gallery/services/video.ts+++ b/web/packages/gallery/services/video.ts@@ -23,6 +23,7 @@ import {videoStreamDone,} from "../utils/native-stream";import { downloadManager } from "./download";+import { getElectronFFmpegWorker } from "./ffmpeg";import {fetchFileData,fetchFilePreviewData,@@ -553,6 +554,7 @@ const processQueueItem = async ({timestampedUploadItem,}: VideoProcessingQueueItem) => {const electron = ensureElectron();+ const electronFFmpegWorker = await getElectronFFmpegWorker();log.debug(() => ["gen-hls", { file, timestampedUploadItem }]);@@ -585,7 +587,7 @@ const processQueueItem = async ({log.info(`Generate HLS for ${fileLogID(file)} | start`);const res = await initiateGenerateHLS(- electron,+ electronFFmpegWorker,sourceVideo!,objectUploadURL,);diff --git a/web/packages/gallery/utils/native-stream.ts b/web/packages/gallery/utils/native-stream.tsindex 43e4523224..f2eff42107 100644--- a/web/packages/gallery/utils/native-stream.ts+++ b/web/packages/gallery/utils/native-stream.ts@@ -6,7 +6,12 @@* See: [Note: IPC streams].*/-import type { Electron, ElectronMLWorker, ZipItem } from "ente-base/types/ipc";+import type {+ Electron,+ ElectronFFmpegWorker,+ ElectronMLWorker,+ ZipItem,+} from "ente-base/types/ipc";import { z } from "zod";import type { FileSystemUploadItem } from "../services/upload";@@ -124,8 +129,9 @@ export const writeStream = async (** This is a variant of {@link writeStream} tailored for the conversion to MP4.*- * @param _ An {@link Electron} instance, witness to the fact that we're running- * in the context of the desktop app. It is otherwise not used.+ * @param _ An {@link ElectronFFmpegWorker} instance, witness to the fact that+ * we're running in the context of the desktop app, and that an ffmpeg utility+ * process has been initialized. It is otherwise not used.** @param video A {@link Blob} containing the video to convert.*@@ -136,7 +142,7 @@ export const writeStream = async (* See: [Note: Convert to MP4].*/export const initiateConvertToMP4 = async (- _: Electron,+ _: ElectronFFmpegWorker,video: Blob,): Promise<string> => {const url = "stream://video?op=convert-to-mp4";@@ -172,14 +178,16 @@ export type GenerateHLSResult = z.infer<typeof GenerateHLSResult>;* is similar to {@link initiateConvertToMP4}, but also supports streaming* {@link FileSystemUploadItem}s and {@link ReadableStream}s.*- * @param _ An {@link Electron} instance, witness to the fact that we're running- * in the context of the desktop app. It is otherwise not used.+ * @param _ An {@link ElectronFFmpegWorker} instance, witness to the fact that+ * we're running in the context of the desktop app, and that an ffmpeg utility+ * process has been initialized. It is otherwise not used.** @param video The video to convert.** - If we're called during the upload process, then this will be set to the- * {@link FileSystemUploadItem} that was uploaded. This way, we can directly use- * the on-disk file instead of needing to download the original from remote.+ * {@link FileSystemUploadItem} that was uploaded. This way, we can directly+ * use the on-disk file instead of needing to download the original from+ * remote.** - Otherwise it should be a {@link ReadableStream} of the video contents.*@@ -197,7 +205,7 @@ export type GenerateHLSResult = z.infer<typeof GenerateHLSResult>;* See: [Note: Preview variant of videos].*/export const initiateGenerateHLS = async (- _: Electron,+ _: ElectronFFmpegWorker,video: FileSystemUploadItem | ReadableStream,objectUploadURL: string,): Promise<GenerateHLSResult | undefined> => {