Skip to content

armgit / ente

Public Imported from GitHub
0

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

Prune desktop service comments

Manav Rathi969acad47f54
diff --git a/desktop/src/main/services/app-update.ts b/desktop/src/main/services/app-update.ts
index 5dfd107b50..eea770e331 100644
--- a/desktop/src/main/services/app-update.ts
+++ b/desktop/src/main/services/app-update.ts
@@ -11,100 +11,19 @@ import { isDev } from "../utils/electron";
export const setupAutoUpdater = (mainWindow: BrowserWindow) => {
autoUpdater.logger = electronLog;
autoUpdater.autoDownload = false;
- // This is going to be the default at some point, right now if we don't
- // explicitly set this to true then electron-builder prints a (harmless)
- // warning when updating on Windows.
- // See: https://github.com/electron-userland/electron-builder/pull/6575
autoUpdater.disableWebInstaller = true;
- // Disable differential downloads to fix Windows NSIS update issues
- // See: https://github.com/electron-userland/electron-builder/issues/9181
+ // Differential downloads currently break some Windows NSIS updates.
+ // https://github.com/electron-userland/electron-builder/issues/9181
autoUpdater.disableDifferentialDownload = true;
- /**
- * [Note: Testing auto updates]
- *
- * By default, we skip checking for updates automatically in dev builds.
- * This is because even if installing updates would fail (at least on macOS)
- * because auto updates only work for signed builds.
- *
- * So an end to end testing for updates requires using a temporary GitHub
- * repository and signed builds therein. More on this later.
- *
- * ---------------
- *
- * [Note: Testing auto updates - Sanity checks]
- *
- * However, for partial checks of the UI flow, something like the following
- * can be used to do a test of the update process (up until the actual
- * installation itself).
- *
- * Create a `app/dev-app-update.yml` with:
- *
- * provider: generic
- * url: http://127.0.0.1:7777/
- *
- * and start a local webserver in some directory:
- *
- * python3 -m http.server 7777
- *
- * In this directory, put `latest-mac.yml` and the DMG file that this YAML
- * file refers to.
- *
- * Alternatively, `dev-app-update.yml` can point to some arbitrary GitHub
- * repository too, e.g.:
- *
- * provider: github
- * owner: ente
- * repo: test-desktop-updates
- *
- * Now we can use the "Check for updates..." menu option to trigger the
- * update flow.
- */
+ // Dev builds use dev-app-update.yml for manual checks, but never poll.
autoUpdater.forceDevUpdateConfig = isDev;
if (isDev) return;
- /**
- * [Note: Testing auto updates - End to end checks]
- *
- * Since end-to-end update testing can only be done with signed builds, the
- * easiest way is to create temporary builds in a test repository.
- *
- * Let us say we have v2.0.0 about to go out. We have builds artifacts for
- * v2.0.0 also in some draft release in our normal release repository.
- *
- * Create a new test repository, say `ente/test-desktop-updates`. In this
- * repository, create a release v2.0.0, attaching the actual build
- * artifacts. Make this release the latest.
- *
- * Now we need to create a old signed build.
- *
- * First, modify `package.json` to put in a version number older than the
- * new version number that we want to test updating to, e.g. `v1.0.0-test`.
- *
- * Then uncomment the following block of code. This tells the auto updater
- * to use `ente/test-desktop-updates` to get updates.
- *
- * With these two changes (older version and setFeedURL), create a new
- * release signed build on CI. Install this build - it will check for
- * updates in the temporary feed URL that we set, and we'll be able to check
- * the full update flow.
- */
-
- /*
- autoUpdater.setFeedURL({
- provider: "github",
- owner: "ente",
- repo: "test-desktop-updates",
- });
- */
-
const oneDay = 1 * 24 * 60 * 60 * 1000;
setInterval(() => void checkForUpdatesAndNotify(mainWindow), oneDay);
void checkForUpdatesAndNotify(mainWindow);
};
-/**
- * Check for app update check ignoring any previously saved skips / mutes.
- */
export const forceCheckForAppUpdates = (mainWindow: BrowserWindow) => {
userPreferences.delete("skipAppVersion");
userPreferences.delete("muteUpdateNotificationVersion");
@@ -112,15 +31,6 @@ export const forceCheckForAppUpdates = (mainWindow: BrowserWindow) => {
};
interface CheckForUpdatesAndNotifyOpts {
- /**
- * By default, the updater waits for 5 minutes after an update has been
- * downloaded before notifying the user. This is so as to not get in their
- * way during an app launch.
- *
- * However, when the user clicks the "Check for updates..." menu action,
- * they would prefer more immediate feedback, so this flag allows us to
- * bypass this delay.
- */
notifyImmediately?: boolean;
}
@@ -180,11 +90,6 @@ const checkForUpdatesAndNotify = async (
await autoUpdater.downloadUpdate();
};
-/**
- * Return the version of the desktop app.
- *
- * The return value is of the form `v1.2.3`.
- */
export const appVersion = () => `v${app.getVersion()}`;
export const updateAndRestart = () => {
diff --git a/desktop/src/main/services/auto-launcher.ts b/desktop/src/main/services/auto-launcher.ts
index 1ff2727068..af61b24452 100644
--- a/desktop/src/main/services/auto-launcher.ts
+++ b/desktop/src/main/services/auto-launcher.ts
@@ -2,10 +2,6 @@ import AutoLaunch from "auto-launch";
import { app } from "electron/main";
class AutoLauncher {
- /**
- * This property will be set and used on Linux and Windows. On macOS,
- * there's a separate API
- */
private autoLaunch?: AutoLaunch;
constructor() {
diff --git a/desktop/src/main/services/device-lock.ts b/desktop/src/main/services/device-lock.ts
index 599edd3f0e..7f82c25539 100644
--- a/desktop/src/main/services/device-lock.ts
+++ b/desktop/src/main/services/device-lock.ts
@@ -2,11 +2,6 @@ import { systemPreferences } from "electron/main";
import type { NativeDeviceLockCapability } from "../../types/ipc";
import log from "../log";
-/**
- * Return native device lock capability for the current platform.
- *
- * Electron currently exposes native prompt APIs only on macOS (Touch ID).
- */
export const getNativeDeviceLockCapability = (): NativeDeviceLockCapability => {
switch (process.platform) {
case "darwin":
@@ -18,9 +13,7 @@ export const getNativeDeviceLockCapability = (): NativeDeviceLockCapability => {
return {
available: false,
provider: "none",
- // `canPromptTouchID()` can become false for transient
- // runtime states (for example lockout/cancellation
- // sequences), not only for permanent hardware setup.
+ // canPromptTouchID() can be false during transient lockouts.
reason: "touchid-temporarily-unavailable",
};
} catch (e) {
@@ -44,12 +37,6 @@ export const getNativeDeviceLockCapability = (): NativeDeviceLockCapability => {
}
};
-/**
- * Prompt the user to unlock using native device authentication.
- *
- * Returns true on successful authentication. Returns false if unavailable,
- * cancelled, or failed.
- */
export const promptDeviceLock = async (reason: string) => {
if (process.platform !== "darwin") {
log.warn("Native device lock prompt is unavailable on this OS");
diff --git a/desktop/src/main/services/dir.ts b/desktop/src/main/services/dir.ts
index 4b1f748fe5..681fcc3a60 100644
--- a/desktop/src/main/services/dir.ts
+++ b/desktop/src/main/services/dir.ts
@@ -11,59 +11,16 @@ export const selectDirectory = async () => {
return dirPath ? posixPath(dirPath) : undefined;
};
-/**
- * Open the given {@link dirPath} in the system's folder viewer.
- *
- * For example, on macOS this'll open {@link dirPath} in Finder.
- */
export const openDirectory = async (dirPath: string) => {
- // We need to use `path.normalize` because `shell.openPath; does not support
- // POSIX path, it needs to be a platform specific path:
- // https://github.com/electron/electron/issues/28831#issuecomment-826370589
+ // shell.openPath requires native separators, not our POSIX IPC paths.
const res = await shell.openPath(path.normalize(dirPath));
- // `shell.openPath` resolves with a string containing the error message
- // corresponding to the failure if a failure occurred, otherwise "".
+ // Electron resolves with an error message on failure.
if (res) throw new Error(`Failed to open directory ${dirPath}: res`);
};
-/**
- * Open the app's log directory in the system's folder viewer.
- *
- * @see {@link openDirectory}
- */
export const openLogDirectory = () => openDirectory(logDirectoryPath());
-/**
- * Return the path where the logs for the app are saved.
- *
- * [Note: Electron app paths]
- *
- * There are three paths we need to be aware of usually.
- *
- * First is the "appData". We can obtain this with `app.getPath("appData")`.
- * This is per-user application data directory. This is usually the following:
- *
- * - Windows: `%APPDATA%`, e.g. `C:\Users\<username>\AppData\Local`
- * - Linux: `~/.config`
- * - macOS: `~/Library/Application Support`
- *
- * Now, if we suffix the app's name onto the appData directory, we get the
- * "userData" directory. This is the **primary** place applications are meant to
- * store user's data, e.g. various configuration files and saved state.
- *
- * Note that Chromium also stores the browser state, e.g. localStorage or disk
- * caches, in userData.
- *
- * https://www.electronjs.org/docs/latest/api/app
- *
- * [Note: App log path]
- *
- * Finally, there is the "logs" directory. This is not within "appData" but has
- * a slightly different OS specific path. Since our log file is named
- * "ente.log", it can be found at:
- *
- * - macOS: ~/Library/Logs/ente/ente.log (production)
- * - Linux: ~/.config/ente/logs/ente.log
- * - Windows: %USERPROFILE%\AppData\Roaming\ente\logs\ente.log
- */
+// macOS: ~/Library/Logs/ente/ente.log (production)
+// Linux: ~/.config/ente/logs/ente.log
+// Windows: %USERPROFILE%\AppData\Roaming\ente\logs\ente.log
const logDirectoryPath = () => app.getPath("logs");
diff --git a/desktop/src/main/services/ffmpeg-worker.ts b/desktop/src/main/services/ffmpeg-worker.ts
index 94cbd57353..b050967db3 100644
--- a/desktop/src/main/services/ffmpeg-worker.ts
+++ b/desktop/src/main/services/ffmpeg-worker.ts
@@ -1,9 +1,3 @@
-/**
- * @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 shellescape from "any-shell-escape";
import { expose } from "comlink";
import pathToFfmpeg from "ffmpeg-static";
@@ -23,17 +17,10 @@ import {
publicRequestHeaders,
} from "../utils/http";
-/* Ditto in the web app's code (used by the Wasm FFmpeg invocation). */
const ffmpegPathPlaceholder = "FFMPEG";
const inputPathPlaceholder = "INPUT";
const outputPathPlaceholder = "OUTPUT";
-/**
- * The interface of the object exposed by `ffmpeg-worker.ts` on the message port
- * pair that the main process creates to communicate with it.
- *
- * @see {@link ffmpegUtilityProcessEndpoint}.
- */
export interface FFmpegUtilityProcess {
ffmpegExec: (
command: FFmpegCommand,
@@ -62,10 +49,7 @@ log.debugString("Started ffmpeg utility process");
process.on("uncaughtException", (e, origin) => log.error(origin, e));
process.parentPort.once("message", (e) => {
- // Initialize ourselves with the data we got from our parent.
parseInitData(e.data);
- // Expose an instance of `FFmpegUtilityProcess` on the port we got from our
- // parent.
expose(
{
ffmpegExec,
@@ -75,18 +59,11 @@ process.parentPort.once("message", (e) => {
} satisfies FFmpegUtilityProcess,
messagePortMainEndpoint(e.ports[0]!),
);
- // Let the main process know we're ready.
mainProcess("ack", undefined);
});
-/**
- * We cannot access Electron's {@link app} object within a utility process, so
- * we pass the value of `app.getVersion()` during initialization, and it can be
- * subsequently retrieved from here.
- */
let _desktopAppVersion: string | undefined;
-/** Equivalent to `app.getVersion()` */
const desktopAppVersion = () => _desktopAppVersion!;
const FFmpegWorkerInitData = z.object({ appVersion: z.string() });
@@ -95,39 +72,9 @@ const parseInitData = (data: unknown) => {
_desktopAppVersion = FFmpegWorkerInitData.parse(data).appVersion;
};
-/**
- * Send a message to the main process using a barebones RPC protocol.
- */
const mainProcess = (method: string, param: unknown) =>
process.parentPort.postMessage({ method, p: param });
-/**
- * Run a FFmpeg command
- *
- * [Note: FFmpeg in Electron]
- *
- * There is a Wasm build of FFmpeg, but that is currently 10-20 times slower
- * that the native build. That is slow enough to be unusable for our purposes.
- * https://ffmpegwasm.netlify.app/docs/performance
- *
- * So the alternative is to bundle a FFmpeg executable binary with our app. e.g.
- *
- * npm install fluent-ffmpeg ffmpeg-static ffprobe-static
- *
- * (we only use ffmpeg-static, the rest are mentioned for completeness' sake).
- *
- * Interestingly, Electron already bundles an binary FFmpeg library (it comes
- * from the ffmpeg fork maintained by Chromium).
- * https://chromium.googlesource.com/chromium/third_party/ffmpeg
- * https://stackoverflow.com/questions/53963672/what-version-of-ffmpeg-is-bundled-inside-electron
- *
- * This can be found in (e.g. on macOS) at
- *
- * $ file ente.app/Contents/Frameworks/Electron\ Framework.framework/Versions/Current/Libraries/libffmpeg.dylib
- * .../libffmpeg.dylib: Mach-O 64-bit dynamically linked shared library arm64
- *
- * But I'm not sure if our code is supposed to be able to use it, and how.
- */
const ffmpegExec = async (
command: FFmpegCommand,
inputFilePath: string,
@@ -167,29 +114,12 @@ const substitutePlaceholders = (
}
});
-/**
- * Return the path to the `ffmpeg` binary.
- *
- * At runtime, the FFmpeg binary is present in a path like (macOS example):
- * `ente.app/Contents/Resources/app.asar.unpacked/node_modules/ffmpeg-static/ffmpeg`
- */
+// Packaged dependencies live outside the archive at this rewritten path.
+// https://github.com/eugeneware/ffmpeg-static/issues/16
const ffmpegBinaryPath = () => {
- // This substitution of app.asar by app.asar.unpacked is suggested by the
- // ffmpeg-static library author themselves:
- // https://github.com/eugeneware/ffmpeg-static/issues/16
return pathToFfmpeg!.replace("app.asar", "app.asar.unpacked");
};
-/**
- * A variant of {@link ffmpegExec} adapted to work with streams so that it can
- * handle the MP4 conversion of large video files.
- *
- * @param inputFilePath The path to a file on the user's local file system. This
- * is the video we want to convert.
- *
- * @param outputFilePath The path to a file on the user's local file system where
- * we should write the converted MP4 video.
- */
const ffmpegConvertToMP4 = async (
inputFilePath: string,
outputFilePath: string,
@@ -215,45 +145,6 @@ export interface FFmpegGenerateHLSPlaylistAndSegmentsResult {
videoObjectID: string;
}
-/**
- * A bespoke variant of {@link ffmpegExec} for generation of HLS playlists for
- * videos.
- *
- * Overview of the cases:
- *
- * H.264, <= 10 MB - Skip
- * H.264, <= 4000 kb/s bitrate - Don't re-encode video stream
- * !HDR, <= 2000 kb/s bitrate - Don't apply the scale+fps filter
- * HDR - Apply tonemap (zscale+tonemap+zscale)
- *
- * Example invocation:
- *
- * ffmpeg -i in.mov -vf "scale='if(lt(iw,ih),min(720,iw),-2)':'if(lt(iw,ih),-2,min(720,ih))',fps=30,zscale=transfer=linear,tonemap=tonemap=hable:desat=0,zscale=primaries=709:transfer=709:matrix=709,format=yuv420p" -c:v libx264 -c:a aac -f hls -hls_key_info_file out.m3u8.info -hls_list_size 0 -hls_flags single_file out.m3u8
- *
- * See: [Note: Preview variant of videos]
- *
- * @param inputFilePath The path to a file on the user's local file system. This
- * is the video we want to generate an streamable HLS playlist for.
- *
- * @param outputPathPrefix The path to unique, unused and temporary prefix on
- * the user's local file system. This function will write the generated HLS
- * playlist and video segments under this prefix.
- *
- * @param fileID The ID of the {@link EnteFile} whose HLS playlist we are
- * generating.
- *
- * @param fetchURL The fully resolved API URL for obtaining pre-signed S3 URLs
- * for uploading the generated video segment file.
- *
- * @param authToken A token that can be used to make API request to
- * {@link fetchURL}.
- *
- * @returns The path to the file on the user's file system containing the
- * generated HLS playlist, and other metadata about the generated video stream.
- *
- * If the video is such that it doesn't require stream generation, then this
- * function returns `undefined`.
- */
const ffmpegGenerateHLSPlaylistAndSegments = async (
inputFilePath: string,
outputPathPrefix: string,
@@ -266,217 +157,62 @@ const ffmpegGenerateHLSPlaylistAndSegments = async (
log.debugString(JSON.stringify({ isH264, isHDR, 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 much
- // use. Skip such cases.
- //
- // See also: [Note: Marking files which do not need video processing]
- //
- // ---
- //
- // [Note: HEVC/H.265 issues]
- //
- // We've observed two issues out in the wild with HEVC videos:
- //
- // 1. On Linux, HEVC video streams don't play. However, since the audio
- // stream plays, the browser tells us that the "video" itself is
- // playable, but the user sees a blank screen with only audio.
- //
- // 2. HEVC + HDR videos taken on an iPhone have a rotation (`Side data:
- // displaymatrix` in the ffmpeg output) that Chrome (and thus Electron)
- // doesn't take into account, so these play upside down.
- //
- // Not fully related to this case, but mentioning here as to why both the
- // size and codec need to be checked before skipping stream generation.
+ // Never skip HEVC: it can be audio-only on Linux, and Chromium can ignore
+ // iPhone HEVC+HDR rotation metadata.
if (isH264) {
const inputVideoSize = await fs
.stat(inputFilePath)
.then((st) => st.size);
- if (inputVideoSize <= 10 * 1024 * 1024 /* 10 MB */) {
+ if (inputVideoSize <= 10 * 1024 * 1024) {
return undefined;
}
}
- // If the video is already H.264 with a bitrate less than 4000 kbps, then we
- // do not need to reencode the video stream (by _far_ the costliest part of
- // the HLS stream generation).
+ // Re-encoding is by far the dominant cost of generating the stream.
const reencodeVideo = !(isH264 && bitrate && bitrate <= 4000 * 1000);
-
- // If the bitrate is not too high, then we don't need to rescale the video
- // when generating the video stream. This is not a performance optimization,
- // but more for avoiding making the video size smaller unnecessarily.
+ // Avoid shrinking video whose bitrate is already modest.
const rescaleVideo = !(bitrate && bitrate <= 2000 * 1000);
-
- // [Note: Tonemapping HDR to HD]
- //
- // BT.709 ("HD") is a standard that describes things like how color is
- // encoded, the range of values, and their "meaning" - i.e. how to map the
- // values in the video to the pixels on the screen.
- //
- // It is not the only such standard, there are three common examples:
- //
- // - BT.601 ("Standard-Definition" or SD)
- // - BT.709 ("High-Definition" or HD)
- // - BT.2020 ("Ultra-High-Definition" or UHD, aka HDR^).
- //
- // ^ HDR ("High-Dynamic-Range") is an addendum to BT.2020, but for the
- // discussion here we can treat it as as alias. In particular, not all
- // BT.2020 videos are HDR, the check we use instead looks for particular
- // color transfers (see the `isHDRVideo` function below).
- //
- // BT.709 is the most common amongst these for older files out stored on
- // computers, and they conform mostly to the standard (one notable exception
- // is that the BT.709 standard also recommends using the yuv422p pixel
- // format, but de facto yuv420p is used because many video players only
- // support yuv420p).
- //
- // Since BT.709 is the most widely supported standard, we use it when
- // generating the HLS playlist so to allow playback across the widest
- // possible hardware/OS/browser combinations.
- //
- // If we convert HDR to HD without naively, then the colors look washed out
- // compared to the original. To resolve this, we use a ffmpeg filterchain
- // that uses the tonemap filter.
- //
- // However applying this tonemap to videos that are already HD leads to a
- // brightness drop. So we conditionally apply this filter chain only if we
- // can heuristically detect that the video is HDR.
- //
- // See also: [Note: Alternative FFmpeg command for HDR videos].
- //
- // Reference:
- // - https://trac.ffmpeg.org/wiki/colorspace
+ // HDR needs BT.709 tonemapping; applying it to SDR reduces brightness.
const tonemap = isHDR;
- // We want the generated playlist to refer to the chunks as "output.ts".
- //
- // So we arrange things accordingly: We use the `outputPathPrefix` as our
- // working directory, and then ask ffmpeg to generate a playlist with the
- // name "output.m3u8".
- //
- // ffmpeg will automatically place the segments in a file with the same base
- // name as the playlist, but with a ".ts" extension. And since we use the
- // "single_file" option, all the segments will be placed in a file named
- // "output.ts".
-
await fs.mkdir(outputPathPrefix);
const playlistPath = path.join(outputPathPrefix, "output.m3u8");
const videoPath = path.join(outputPathPrefix, "output.ts");
- // A file into which we'll redirect ffmpeg's stderr.
- //
- // [Note: ERR_CHILD_PROCESS_STDIO_MAXBUFFER]
- //
- // For very large videos, the stderr output of ffmpeg may cause the stdio
- // max buffer size limits to be exceeded, raising the following error:
- //
- // RangeError [ERR_CHILD_PROCESS_STDIO_MAXBUFFER]: stderr maxBuffer length exceeded
- //
- // So instead of capturing the stderr normally, we redirect it to a
- // temporary file, and then read it from there to extract the video
- // dimensions.
+ // Avoid child_process's stderr buffer limit on large videos.
const stderrPath = path.join(outputPathPrefix, "stderr.txt");
- // Generate a cryptographically secure random key (16 bytes).
const keyBytes = randomBytes(16);
const keyB64 = keyBytes.toString("base64");
- // Convert it to a data: URI that will be added to the playlist.
const keyURI = `data:text/plain;base64,${keyB64}`;
- // Determine two paths - one where we will write the key itself, and where
- // we will write the "key info" that provides ffmpeg the `keyURI` and the
- // `keyPath;.
const keyPath = playlistPath + ".key";
const keyInfoPath = playlistPath + ".key-info";
- // Generate a "key info":
- //
- // - the first line specifies the key URI that is written into the playlist.
- // - the second line specifies the path to the local file system file from
- // where ffmpeg should read the key.
- //
- // [Note: ffmpeg newlines]
- //
- // Tested on Windows that ffmpeg recognizes these lines correctly. In
- // general, ffmpeg tends to expect input and write output the Unix way (\n),
- // even when we're running on Windows.
- //
- // - The ffmetadata and the HLS playlist file generated by ffmpeg uses \n
- // separators, even on Windows.
- // - The HLS key info file, expected as an input by ffmpeg, works fine when
- // \n separated even on Windows.
- //
+ // FFmpeg key-info is the playlist URI followed by the local key path.
const keyInfo = [keyURI, keyPath].join("\n");
- // Overview:
- //
- // - Video H.264 HD 720p (max) 30fps.
- // - Audio AAC 128kbps.
- // - Encrypted HLS playlist with a single file containing all the chunks.
- //
- // Reference:
- // - `man ffmpeg-all`
- // - https://trac.ffmpeg.org/wiki/Encode/H.264
- //
const command = [
ffmpegBinaryPath(),
- // Reduce the amount of output lines we have to parse.
["-hide_banner"],
- // Input file. We don't need any extra options that apply to the input file.
"-i",
inputFilePath,
- // The remaining options apply to the next output file (`playlistPath`).
reencodeVideo
? [
- // `-vf` creates a filter graph for the video stream. It is a
- // comma separated list of filters chained together, e.g.
- // `filter1=key=value:key=value.filter2=key=value`.
"-vf",
[
- // Do the rescaling to even number of pixels always if the
- // tonemapping is going to be applied subsequently,
- // otherwise the tonemapping will fail with "image
- // dimensions must be divisible by subsampling factor".
- //
- // While we add the extra condition here for completeness,
- // it won't usually matter since a non-BT.709 video is
- // likely using a new codec, and as such would've a high
- // enough bitrate to require rescaling anyways.
+ // Tonemapping requires dimensions divisible by chroma
+ // subsampling, so it also forces the even-size scale.
rescaleVideo || tonemap
? [
- // Scale smaller dimension to 720p (or keep
- // original if less than 720p). Portrait videos
- // scale width, landscape videos scale height.
- // -2 keeps aspect ratio with even pixel count.
"scale='if(lt(iw,ih),min(720,iw),-2)':'if(lt(iw,ih),-2,min(720,ih))'",
- // Convert the video to a constant 30 fps,
- // duplicating or dropping frames as necessary.
"fps=30",
]
: [],
- // Convert the colorspace if the video is HDR. Before
- // conversion, tone map colors so that they work the same
- // across the change in the dyamic range.
- //
- // 1. The tonemap filter only works linear light, so we
- // first use zscale with transfer=linear to linearize
- // the input.
- //
- // 2. Then we use the tonemap, with the hable option that
- // is best for preserving details. desat=0 turns off
- // the default desaturation.
- //
- // 3. Use zscale again to "convert to BT.709" by asking it
- // to set the all three of color primaries, transfer
- // characteristics and colorspace matrix to 709 (Note:
- // the constants specified in the tonemap filter help
- // do not include the "bt" prefix)
- //
- // See: https://ffmpeg.org/ffmpeg-filters.html#tonemap-1
- //
- // See: [Note: Tonemapping HDR to HD]
+ // tonemap requires linear input; the final zscale emits
+ // the broadly supported BT.709 color space.
tonemap
? [
"zscale=transfer=linear",
@@ -484,8 +220,6 @@ const ffmpegGenerateHLSPlaylistAndSegments = async (
"zscale=primaries=709:transfer=709:matrix=709",
]
: [],
- // Output using the well supported pixel format: 8-bit YUV
- // planar color space with 4:2:0 chroma subsampling.
"format=yuv420p",
]
.flat()
@@ -493,37 +227,13 @@ const ffmpegGenerateHLSPlaylistAndSegments = async (
]
: [],
reencodeVideo
- ? // Video codec H.264
- //
- // - `-c:v libx264` converts the video stream to the H.264 codec.
- //
- // - We use CRF 23 (default) for quality, but cap the bitrate at
- // 2000 kbps using `-maxrate` to ensure smaller bitrates are
- // preserved while preventing CRF from exceeding 2000 kbps.
- //
- // - `-bufsize` is set to 2x maxrate for smooth rate control.
- //
- // - We don't supply a preset, it'll use the default ("medium").
- ["-c:v", "libx264", "-maxrate", "2000k", "-bufsize", "4000k"]
- : // Keep the video stream unchanged
- ["-c:v", "copy"],
- // Audio codec AAC
- //
- // - `-c:a aac` converts the audio stream to use the AAC codec
- //
- // - We don't supply a bitrate, it'll use the AAC default 128k bps.
+ ? ["-c:v", "libx264", "-maxrate", "2000k", "-bufsize", "4000k"]
+ : ["-c:v", "copy"],
["-c:a", "aac"],
- // Generate a HLS playlist.
["-f", "hls"],
- // Tell ffmpeg where to find the key, and the URI for the key to write
- // into the generated playlist. Implies "-hls_enc 1".
["-hls_key_info_file", keyInfoPath],
- // Generate as many playlist entries as needed (default limit is 5).
["-hls_list_size", "0"],
- // Place all the video segments within the same .ts file (with the same
- // path as the playlist file but with a ".ts" extension).
["-hls_flags", "single_file"],
- // Output path where the playlist should be generated.
playlistPath,
].flat();
@@ -532,35 +242,24 @@ const ffmpegGenerateHLSPlaylistAndSegments = async (
let videoObjectID: string;
try {
- // Write the key and the keyInfo to their desired paths.
await Promise.all([
fs.writeFile(keyPath, keyBytes),
fs.writeFile(keyInfoPath, keyInfo, { encoding: "utf8" }),
]);
- // Tack on the redirection after constructing the command.
const commandWithRedirection = `${shellescape(command)} 2>${stderrPath}`;
- // Run the ffmpeg command to generate the HLS playlist and segments.
- //
- // Note: Depending on the size of the input file, this may take long!
await execAsyncWorker(commandWithRedirection);
- // While ffmpeg uses \n as the line separator in the generated playlist
- // file on Windows too, add an extra safety check that should fail the
- // HLS generation if this doesn't hold. See: [Note: ffmpeg newlines].
+ // FFmpeg-generated HLS uses LF even on Windows; fail if that changes.
if (process.platform == "win32") {
const playlistText = await fs.readFile(playlistPath, "utf-8");
if (playlistText.includes("\r\n"))
throw new Error("Unexpected Windows newlines in playlist");
}
- // Determine the dimensions of the generated video from the stderr
- // output produced by ffmpeg during the conversion.
dimensions = await detectVideoDimensions(stderrPath);
- // Find the size of the generated video segments by reading the size of
- // the generated .ts file.
videoSize = await fs.stat(videoPath).then((st) => st.size);
videoObjectID = await uploadVideoSegments(
@@ -580,7 +279,7 @@ const ffmpegGenerateHLSPlaylistAndSegments = async (
deletePathIgnoringErrors(keyInfoPath),
deletePathIgnoringErrors(keyPath),
deletePathIgnoringErrors(videoPath),
- // ffmpeg writes a /path/output.ts.tmp, clear it out too.
+ // FFmpeg can leave this beside the output after failures.
deletePathIgnoringErrors(videoPath + ".tmp"),
]);
}
@@ -588,13 +287,6 @@ const ffmpegGenerateHLSPlaylistAndSegments = async (
return { playlistPath, dimensions, videoSize, videoObjectID };
};
-/**
- * A variant of {@link deletePathIgnoringErrors} (which we can't directly use in
- * the utility process). It unconditionally removes the item at the provided
- * path; in particular, this will not raise any errors if there is no item at
- * the given path (as may be expected to happen when we run during catch
- * handlers).
- */
const deletePathIgnoringErrors = async (tempFilePath: string) => {
try {
await fs.rm(tempFilePath, { force: true });
@@ -603,36 +295,13 @@ const deletePathIgnoringErrors = async (tempFilePath: string) => {
}
};
-/**
- * A regex that matches the first line of the form
- *
- * Stream #0:0: Video: h264 (High 10) ([27][0][0][0] / 0x001B), yuv420p10le(tv, bt2020nc/bt2020/arib-std-b67), 1920x1080, 30 fps, 30 tbr, 90k tbn
- *
- * The part after Video: is the first capture group.
- *
- * Another example:
- *
- * Stream #0:1[0x2](und): Video: h264 (Constrained Baseline) (avc1 / 0x31637661), yuv420p(progressive), 480x270 [SAR 1:1 DAR 16:9], 539 kb/s, 29.97 fps, 29.97 tbr, 30k tbn (default)
- */
const videoStreamLineRegex = /Stream #.+: Video:(.+)\r?\n/;
-/** {@link videoStreamLineRegex}, but global. */
const videoStreamLinesRegex = /Stream #.+: Video:(.+)\r?\n/g;
-/**
- * A regex that matches "<digits> kb/s" preceded by a space. See
- * {@link videoStreamLineRegex} for the context in which it is used.
- */
const videoBitrateRegex = / ([1-9]\d*) kb\/s/;
-/**
- * A regex that matches <digits>x<digits> pair preceded by a space. See
- * {@link videoStreamLineRegex} for the context in which it is used.
- *
- * We constrain the digit sequence not to begin with 0 to exclude hexadecimal
- * representations of various constants that ffmpeg prints on this line (e.g.
- * "avc1 / 0x31637661").
- */
+// Leading nonzero digits avoid matching hexadecimal constants in stream info.
const videoDimensionsRegex = / ([1-9]\d*)x([1-9]\d*)/;
interface VideoCharacteristics {
@@ -641,44 +310,12 @@ interface VideoCharacteristics {
bitrate: number | undefined;
}
-/**
- * Heuristically determine information about the video at the given
- * {@link inputFilePath}:
- *
- * - If is encoded using H.264 codec.
- * - If it is HDR.
- * - Its bitrate.
- *
- * The defaults are tailored for the cases in which these conditions are used,
- * so that even if we get the detection wrong we'll only end up encoding videos
- * that could've possibly been skipped as an optimization.
- *
- * [Note: Parsing CLI output might break on ffmpeg updates]
- *
- * This function tries to determine the these bits of information about the
- * given video by scanning the ffmpeg info output for the video stream line, and
- * doing various string matches and regex extractions.
- *
- * Needless to say, while this works currently, this is liable to break in the
- * future. So if something stops working after updating ffmpeg, look here!
- *
- * Ideally, we'd have done this using `ffprobe`, but we don't have the ffprobe
- * binary at hand, so we make do by grepping the log output of ffmpeg.
- *
- * For reference,
- *
- * - codec and colorspace are printed by the `avcodec_string` function in the
- * ffmpeg source:
- * https://github.com/FFmpeg/FFmpeg/blob/master/libavcodec/avcodec.c
- *
- * - bitrate is printed by the `dump_stream_format` function in `dump.c`.
- */
+// We do not bundle ffprobe, so this parses ffmpeg stderr. Failed parses fall
+// back to re-encoding instead of incorrectly skipping conversion.
const detectVideoCharacteristics = async (inputFilePath: string) => {
const videoInfo = await pseudoFFProbeVideo(inputFilePath);
const videoStreamLine = videoStreamLineRegex.exec(videoInfo)?.at(1)?.trim();
- // Since the checks are heuristic, start with defaults that would cause the
- // codec conversion to happen, even if it is unnecessary.
const res: VideoCharacteristics = {
isH264: false,
isHDR: false,
@@ -688,15 +325,10 @@ const detectVideoCharacteristics = async (inputFilePath: string) => {
res.isH264 = videoStreamLine.startsWith("h264 ");
- // Same check as `isHDRVideo`.
res.isHDR =
videoStreamLine.includes("smpte2084") ||
videoStreamLine.includes("arib-std-b67");
- // The regex matches "\d kb/s", but there can be other units for the
- // bitrate. However, (a) "kb/s" is the most common for videos out in the
- // wild, and (b) even if we guess wrong it we'll just do "-v:c x264" instead
- // of "-v:c copy", so only unnecessary processing but no change in output.
const brs = videoBitrateRegex.exec(videoStreamLine)?.at(0);
if (brs) {
const br = parseInt(brs, 10);
@@ -706,43 +338,15 @@ const detectVideoCharacteristics = async (inputFilePath: string) => {
return res;
};
-/**
- * Heuristically detect the dimensions of the given video from the log output of
- * the ffmpeg invocation during the HLS playlist generation.
- *
- * This function tries to determine the width and height of the generated video
- * from the output log written by ffmpeg on its stderr during the generation
- * process, scanning it for the last video stream line, and trying to match a
- * "<digits>x<digits>" regex.
- *
- * See: [Note: Parsing CLI output might break on ffmpeg updates].
- */
const detectVideoDimensions = async (stderrPath: string) => {
- // Instead of reading the stderr directly off the child_process.exec, we
- // wrote it to a file to avoid hitting the max stdio buffer limits. Read it
- // from there.
const conversionStderr = await fs.readFile(stderrPath, "utf-8");
- // There is a nicer way to do it - by running `pseudoFFProbeVideo` on the
- // generated playlist. However, that playlist includes a data URL that
- // specifies the encryption info, and ffmpeg refuses to read that unless we
- // specify the "-allowed_extensions ALL" or something to that effect.
- //
- // Unfortunately, our current ffmpeg binary (5.x) does not support that
- // option. So we instead parse the conversion output itself.
- //
- // This is also nice, since it saves on an extra ffmpeg invocation. But we
- // now need to be careful to find the right video stream line, since the
- // conversion output includes both the input and output video stream lines.
- //
- // To match the right (output) video stream line, we use a global regex, and
- // use the last match since that'd correspond to the single video stream
- // written in the output.
+ // Conversion output lists the input stream before the output stream.
const videoStreamLine = Array.from(
conversionStderr.matchAll(videoStreamLinesRegex),
)
- .at(-1) /* Last Stream...: Video: line in the output */
- ?.at(1); /* First capture group */
+ .at(-1)
+ ?.at(1);
if (videoStreamLine) {
const [, ws, hs] = videoDimensionsRegex.exec(videoStreamLine) ?? [];
if (ws && hs) {
@@ -758,34 +362,8 @@ const detectVideoDimensions = async (stderrPath: string) => {
);
};
-/**
- * Heuristically detect if the file at given path is a HDR video.
- *
- * This is similar to {@link detectVideoCharacteristics}, and see that
- * function's documentation for all the caveats. Specifically, this function
- * uses an allow-list, and considers any file with color transfer "smpte2084" or
- * "arib-std-b67" to be HDR. Caveats:
- *
- * 1. These particular constants are not guaranteed to be correct; these are
- * from various internet posts as being used / recommended for detecting HDR.
- *
- * 2. Since we don't have ffprobe, we're not checking the color space value
- * itself but a substring of the stream line in the ffmpeg stderr output.
- *
- * This check should generally not have false positives (unless something else
- * in the log line triggers #2), but it can have false negative. This is the
- * lesser of the two evils since if we apply the tonemapping to any non-BT.709
- * file, we start getting the "code 3074: no path between colorspaces" error
- * during the JPEG or H.264 conversion.
- *
- * - See: [Note: Alternative FFmpeg command for HDR videos]
- * - See: [Note: Tonemapping HDR to HD]
- *
- * @param inputFilePath The path to a video file on the user's machine.
- *
- * @returns `true` if this file is likely a HDR video. Exceptions are treated as
- * `false` to make this function safe to invoke without breaking the happy path.
- */
+// False positives fail zscale with "code 3074: no path between colorspaces";
+// false negatives only miss tonemapping, so allow-list known HDR transfers.
const isHDRVideo = async (inputFilePath: string) => {
try {
const videoInfo = await pseudoFFProbeVideo(inputFilePath);
@@ -798,24 +376,10 @@ const isHDRVideo = async (inputFilePath: string) => {
}
};
-/**
- * Return the stderr of ffmpeg in an attempt to gain information about the video
- * at the given {@link inputFilePath}.
- *
- * We don't have the ffprobe binary at hand, which is why we need to use this
- * alternative. See: [Note: Parsing CLI output might break on ffmpeg updates]
- *
- * @returns the stderr of ffmpeg after running it on the input file. The exact
- * command we run is:
- *
- * ffmpeg -i in.mov -an -frames:v 0 -f null - 2>info.txt
- *
- * And the returned string is the contents of the `info.txt` thus produced.
- */
+// Extract stream metadata from ffmpeg stderr because ffprobe is not bundled.
const pseudoFFProbeVideo = async (inputFilePath: string) => {
const command = [
ffmpegPathPlaceholder,
- // Reduce the amount of output lines we have to parse.
["-hide_banner"],
["-i", inputPathPlaceholder],
"-an",
@@ -824,35 +388,13 @@ const pseudoFFProbeVideo = async (inputFilePath: string) => {
"-",
].flat();
- const cmd = substitutePlaceholders(command, inputFilePath, /* NA */ "");
+ const cmd = substitutePlaceholders(command, inputFilePath, "");
const { stderr } = await execAsyncWorker(cmd);
return stderr;
};
-/**
- * Upload the file at the given {@link videoFilePath} to the provided pre-signed
- * URL(s) using a HTTP PUT request.
- *
- * All HTTP requests are retried up to 4 times (1 original + 3 retries) with
- * exponential backoff.
- *
- * See: [Note: Upload HLS video segment from node side].
- *
- * @param videoFilePath The path to the file on the user's file system to
- * upload.
- *
- * @param videoSize The size in bytes of the file at {@link videoFilePath}.
- *
- * @param fileID The ID of the {@link EnteFile} whose video segment this is.
- *
- * @param fetchURL The API URL for fetching pre-signed upload URLs.
- *
- * @param authToken The user's auth token for use with {@link fetchURL}.
- *
- * @return The object ID of the uploaded file on remote storage.
- */
const uploadVideoSegments = async (
videoFilePath: string,
videoSize: number,
@@ -860,9 +402,8 @@ const uploadVideoSegments = async (
fetchURL: string,
authToken: string,
) => {
- // Self hosters might be using Cloudflare's free plan which (currently) has
- // a maximum request size of 100 MB. Keeping a bit of margin for headers,
- const partSize = 96 * 1024 * 1024; /* 96 MB */
+ // Leave headroom below Cloudflare's 100 MB limit for self-hosters.
+ const partSize = 96 * 1024 * 1024;
const partCount = Math.ceil(videoSize / partSize);
const { objectID, url, partURLs, completeURL } =
@@ -891,43 +432,12 @@ const uploadVideoSegments = async (
};
const FilePreviewDataUploadURLResponse = z.object({
- /**
- * The objectID with which this uploaded data can be referred to post upload
- * (e.g. when invoking {@link putVideoData}).
- */
objectID: z.string(),
- /**
- * A pre-signed URL that can be used to upload the file.
- *
- * This will be present only if we requested a singular object upload URL.
- */
url: z.string().nullish().transform(nullToUndefined),
- /**
- * A list of pre-signed URLs that can be used to upload parts of a multipart
- * upload of the uploaded data.
- *
- * This will be present only if we requested a multipart upload URLs for the
- * object by setting `isMultiPart` true in the request.
- */
partURLs: z.string().array().nullish().transform(nullToUndefined),
- /**
- * A pre-signed URL that can be used to finalize the multipart upload.
- *
- * This will be present only if we requested a multipart upload URLs for the
- * object by setting `isMultiPart` true in the request.
- */
completeURL: z.string().nullish().transform(nullToUndefined),
});
-/**
- * Obtain a pre-signed URL(s) that can be used to upload the "file preview data"
- * of type "vid_preview".
- *
- * This will be the file containing the encrypted video segments which the
- * "vid_preview" HLS playlist for the file would refer to.
- *
- * @param partCount If greater than 1, then we request for a multipart upload.
- */
export const getFilePreviewDataUploadURL = async (
partCount: number,
fileID: number,
@@ -962,58 +472,30 @@ const uploadVideoSegmentsSingle = (
objectUploadURL: string,
) =>
retryEnsuringHTTPOk(() =>
- // net.fetch is 40-50x slower than the native fetch for this particular
- // PUT request. This is easily reproducible - replace `fetch` with
- // `net.fetch`, then even on localhost the PUT requests start taking a
- // minute or so, while they take second(s) with node's native fetch.
+ // Electron's net.fetch is 40-50x slower for this streaming PUT.
fetch(objectUploadURL, {
method: "PUT",
- // net.fetch deduces and inserts a content-length for us, when we
- // use the node native fetch then we need to provide it explicitly.
+ // Node fetch does not infer Content-Length for streams.
headers: {
...publicRequestHeaders(desktopAppVersion()),
"Content-Length": `${videoSize}`,
},
- // See: [Note: duplex param required for stream body]
- // @ts-expect-error ^see note above
+ // @ts-expect-error Node fetch accepts duplex streaming.
duplex: "half",
- // The cast is needed because TS checks this against DOM fetch, but
- // at runtime this utility process calls Node fetch.
- // See: [Note: Node and web stream type mismatch].
+ // Node's ReadableStream type does not satisfy DOM BodyInit.
body: Readable.toWeb(
fs_.createReadStream(videoFilePath),
) as unknown as BodyInit,
}),
);
-/**
- * Retry a async operation on failure up to 4 times (1 original + 3 retries)
- * with exponential backoff.
- *
- * This is an inlined but bespoke reimplementation of `retryEnsuringHTTPOk` from
- * `web/packages/base/http.ts`
- *
- * - We don't have the rest of the scaffolding used by that function, which is
- * why it is intially inlined bespoked.
- *
- * - It handles the specific use case of uploading videos since generating the
- * HLS stream is a fairly expensive operation, so a retry to discount
- * transient network issues is called for. The number of retries and their
- * gaps are same as the "background" `retryProfile` of the web implementation.
- *
- * - Later it was discovered that net.fetch is much slower than node's native
- * fetch, so this implementation has further diverged.
- *
- * - This also moved to a utility process, where we also have a more restricted
- * ability to import electron API.
- */
const retryEnsuringHTTPOk = async (request: () => Promise<Response>) => {
const waitTimeBeforeNextTry = [10000, 30000, 120000];
while (true) {
try {
const res = await request();
- if (res.ok) /* Success. */ return res;
+ if (res.ok) return res;
throw new Error(
`Request failed: HTTP ${res.status} ${res.statusText}`,
);
@@ -1036,12 +518,8 @@ const uploadVideoSegmentsMultipart = async (
partUploadURLs: string[],
completionURL: string,
) => {
- // The part we're currently uploading.
let partNumber = 0;
- // A rolling offset into the file.
let start = 0;
- // See `createMultipartUploadRequestBody` in the web code for a more
- // expansive and documented version of this XML body construction.
const completionXML = ["<CompleteMultipartUpload>"];
for (const partUploadURL of partUploadURLs) {
partNumber += 1;
@@ -1054,15 +532,10 @@ const uploadVideoSegmentsMultipart = async (
...publicRequestHeaders(desktopAppVersion()),
"Content-Length": `${size}`,
},
- // See: [Note: duplex param required for stream body]
- // @ts-expect-error ^see note above
+ // @ts-expect-error Node fetch accepts duplex streaming.
duplex: "half",
- // The cast is needed because TS checks this against DOM fetch,
- // but at runtime this utility process calls Node fetch.
- // See: [Note: Node and web stream type mismatch].
+ // Node's ReadableStream type does not satisfy DOM BodyInit.
body: Readable.toWeb(
- // start and end are inclusive 0-indexed range of bytes to
- // read from the file.
fs_.createReadStream(videoFilePath, { start, end }),
) as unknown as BodyInit,
}),
@@ -1088,23 +561,8 @@ const uploadVideoSegmentsMultipart = async (
);
};
-/**
- * A regex that matches the first line of the form
- *
- * Duration: 00:00:03.13, start: 0.000000, bitrate: 16088 kb/s
- *
- * The part after Duration: and until the first non-digit or colon is the first
- * capture group, while after the dot is an optional second capture group.
- */
const videoDurationLineRegex = /\s\sDuration: ([0-9:]+)(.[0-9]+)?/;
-/**
- * Determine the duration of the video at the given {@link inputFilePath}.
- *
- * While the detection works for all known cases, it is still heuristic because
- * it uses ffmpeg output instead of ffprobe (which we don't have access to).
- * See: [Note: Parsing CLI output might break on ffmpeg updates].
- */
export const ffmpegDetermineVideoDuration = async (inputFilePath: string) => {
const videoInfo = await pseudoFFProbeVideo(inputFilePath);
const matches = videoDurationLineRegex.exec(videoInfo);
@@ -1113,7 +571,6 @@ export const ffmpegDetermineVideoDuration = async (inputFilePath: string) => {
throw new Error(`Cannot parse video duration '${matches?.at(0)}'`);
};
- // The HH:mm:ss.
const ints = (matches?.at(1) ?? "")
.split(":")
.map((s) => parseInt(s, 10) || 0);
@@ -1135,10 +592,9 @@ export const ffmpegDetermineVideoDuration = async (inputFilePath: string) => {
fail();
}
- // Optional subseconds.
const ss = parseFloat(`0${matches?.at(2) ?? ""}`);
- // Follow the same round up behaviour that the web side uses.
+ // Match the web implementation's rounding.
const duration = Math.ceil(h * 3600 + m * 60 + s + ss);
if (!duration) fail();
return duration;
diff --git a/desktop/src/main/services/ffmpeg.ts b/desktop/src/main/services/ffmpeg.ts
index bb7914486b..7d364377e1 100644
--- a/desktop/src/main/services/ffmpeg.ts
+++ b/desktop/src/main/services/ffmpeg.ts
@@ -1,8 +1,3 @@
-/**
- * @file A bridge to the ffmpeg utility process. This code runs in the main
- * process.
- */
-
import { wrap } from "comlink";
import fs from "node:fs/promises";
import type { FFmpegCommand, ZipItem } from "../../types/ipc";
@@ -14,19 +9,11 @@ import {
import type { FFmpegUtilityProcess } from "./ffmpeg-worker";
import { ffmpegUtilityProcessEndpoint } from "./workers";
-/**
- * Return a handle to the ffmpeg utility process, starting it if needed.
- */
export const ffmpegUtilityProcess = () =>
ffmpegUtilityProcessEndpoint().then((port) =>
wrap<FFmpegUtilityProcess>(port),
);
-/**
- * Implement the IPC "ffmpegExec" contract, writing the input and output to
- * temporary files as needed, and then forward to the {@link ffmpegExec} running
- * in the utility process.
- */
export const ffmpegExec = async (
command: FFmpegCommand,
pathOrZipItem: string | ZipItem,
@@ -64,11 +51,6 @@ export const withInputFile = async <T>(
}
};
-/**
- * Implement the IPC "ffmpegDetermineVideoDuration" contract, writing the input
- * to temporary files as needed, and then forward to the
- * {@link ffmpegDetermineVideoDuration} running in the utility process.
- */
export const ffmpegDetermineVideoDuration = async (
pathOrZipItem: string | ZipItem,
): Promise<number> =>
diff --git a/desktop/src/main/services/fs.ts b/desktop/src/main/services/fs.ts
index cba66a46d9..3c0d694c34 100644
--- a/desktop/src/main/services/fs.ts
+++ b/desktop/src/main/services/fs.ts
@@ -1,7 +1,3 @@
-/**
- * @file file system related functions exposed over the context bridge.
- */
-
import { existsSync } from "node:fs";
import fs from "node:fs/promises";
import path from "node:path";
@@ -36,15 +32,8 @@ export const fsIsDir = async (dirPath: string) => {
return stat.isDirectory();
};
+// mtimeMs can be fractional; persisted mtimes must be integral and comparable.
export const fsStatMtime = (path: string) =>
- // [Note: Integral last modified time]
- //
- // Whenever we need to find the modified time of a file, use the
- // `mtime.getTime()` instead of `mtimeMs` of the stat; this way, it is
- // guaranteed that the times are integral (we persist these values to remote
- // in some cases, and the contract is for them to be integral; mtimeMs is a
- // float with sub-millisecond precision), and that all places use the same
- // value so that they're comparable.
fs.stat(path).then((st) => st.mtime.getTime());
export const fsFindFiles = async (dirPath: string) => {
diff --git a/desktop/src/main/services/image.ts b/desktop/src/main/services/image.ts
index 102d7339e2..4d33a6fb52 100644
--- a/desktop/src/main/services/image.ts
+++ b/desktop/src/main/services/image.ts
@@ -1,5 +1,3 @@
-/** @file Image format conversions and thumbnail generation */
-
import fs from "node:fs/promises";
import path from "node:path";
import { type ZipItem } from "../../types/ipc";
@@ -53,9 +51,6 @@ const convertToJPEGCommand = (
}
};
-/**
- * Path to the vips executable bundled with our app on Linux and Windows.
- */
const vipsPath = () =>
path.join(
isDev ? "build" : process.resourcesPath,
@@ -75,7 +70,6 @@ export const generateImageThumbnail = async (
const outputFilePath = await makeTempFilePath("jpeg");
- // Construct the command first, it may throw `NotAvailable`.
let quality = 70;
let command = generateImageThumbnailCommand(
inputFilePath,
diff --git a/desktop/src/main/services/logout.ts b/desktop/src/main/services/logout.ts
index 14968ff24e..2a2ebe9ccd 100644
--- a/desktop/src/main/services/logout.ts
+++ b/desktop/src/main/services/logout.ts
@@ -6,13 +6,7 @@ import { watchReset } from "./watch";
import { terminateUtilityProcesses } from "./workers";
import { clearOpenZipCache } from "./zip";
-/**
- * Perform the native side logout sequence.
- *
- * This function is guaranteed not to throw any errors.
- *
- * See: [Note: Do not throw during logout].
- */
+// Every cleanup must run even if an earlier one fails.
export const logout = (watcher: FSWatcher) => {
const ignoreError = (label: string, e: unknown) =>
log.error(`Ignoring error during logout (${label})`, e);
diff --git a/desktop/src/main/services/ml-native.ts b/desktop/src/main/services/ml-native.ts
index a9b5747f73..d1bbcf5f32 100644
--- a/desktop/src/main/services/ml-native.ts
+++ b/desktop/src/main/services/ml-native.ts
@@ -1,42 +1,11 @@
-/**
- * @file Locations of the Rust ML addon and the ONNX Runtime library.
- *
- * This code runs in the main process; the resolved (absolute) paths are
- * passed to the ML utility process alongside the rest of its init data.
- *
- * [Note: ML with Rust]
- *
- * The ML indexing pipeline β€” image decode, preprocessing, ONNX inference,
- * postprocessing β€” is implemented by a Rust crate shared by all Ente clients
- * (rust/crates/photos). The desktop app talks to it through a Node native
- * addon (rust/bindings/napi/photos), which loads ONNX Runtime dynamically at
- * runtime from Ente's pinned custom builds (see [Note: ONNX Runtime binaries]
- * in scripts/ort.js).
- *
- * During development, `scripts/napi.js` (invoked by `npm run dev`) builds the
- * addon into the gitignored `rust-bindings/` directory, while ONNX Runtime is
- * loaded directly from the postinstall cache. When packaging, `beforeBuild.js`
- * stages both the addon and ONNX Runtime for the target architectures, and
- * electron-builder copies them into the app's resources directory.
- */
-
import path from "node:path";
import { isDev } from "../utils/electron";
-/**
- * Absolute paths needed by the ML utility process to load the Rust addon.
- */
export interface MLNativePaths {
- /** The Node native addon (.node) with the Rust ML bindings. */
addon: string;
- /** The ONNX Runtime dynamic library that the addon should load. */
onnxRuntimeLibrary: string;
}
-/**
- * The platform-arch triple that `napi build` uses when naming the built
- * addon for the current process' platform and architecture.
- */
const napiTriple = () => {
switch (`${process.platform}-${process.arch}`) {
case "darwin-arm64":
diff --git a/desktop/src/main/services/ml-worker.ts b/desktop/src/main/services/ml-worker.ts
index 8289d11263..771e20e51e 100644
--- a/desktop/src/main/services/ml-worker.ts
+++ b/desktop/src/main/services/ml-worker.ts
@@ -1,17 +1,3 @@
-/**
- * @file ML related tasks. This code runs in a utility process.
- *
- * The ML pipeline itself β€” image decode, preprocessing, ONNX inference and
- * postprocessing β€” is implemented by the Rust crate shared with the mobile
- * apps, and reaches us via a Node native addon (see [Note: ML with Rust]).
- * This file loads the addon and forwards requests that arrive from the web
- * layer over our MessagePort. The addon downloads the models through the
- * shared Rust asset store.
- */
-
-// See [Note: Using Electron APIs in UtilityProcess] about what we can and
-// cannot import.
-
import { expose } from "comlink";
import path from "node:path";
import { z } from "zod";
@@ -20,9 +6,7 @@ import { messagePortMainEndpoint } from "../utils/comlink";
import { wait } from "../utils/common";
import { fsStatMtime } from "./fs";
-// The addon is loaded at runtime from the path the main process gives us, so
-// this import is used only for its types (it resolves to the generated
-// `rust-bindings/index.d.ts`).
+// require(paths.addon) loads this module; the import supplies only its types.
import type * as MLNativeModule from "../../../rust-bindings";
import type { MLNativePaths } from "./ml-native";
@@ -31,12 +15,10 @@ log.debugString("Started ML utility process");
process.on("uncaughtException", (e, origin) => log.error(origin, e));
process.parentPort.once("message", (e) => {
- // Initialize ourselves with the data we got from our parent.
const { mlNativePaths } = parseInitData(e.data);
loadMLNative(mlNativePaths);
if (_native) void warmUpClipTextEncoder(_native);
- // Expose an instance of `ElectronMLWorker` on the port we got from our
- // parent.
+
expose(
{
fsStatMtime,
@@ -48,14 +30,8 @@ process.parentPort.once("message", (e) => {
);
});
-/**
- * We cannot access Electron's {@link app} object within a utility process, so
- * we pass the value of `app.getPath("userData")` during initialization, and it
- * can be subsequently retrieved from here.
- */
let _userDataPath: string | undefined;
-/** Equivalent to app.getPath("userData") */
const userDataPath = () => _userDataPath!;
const MLWorkerInitData = z.object({
@@ -99,20 +75,12 @@ let _native: MLNative | undefined;
let _assetStore: MLNativeModule.AssetStore | undefined;
let _nativeLoadError: string | undefined;
-/**
- * Load the Rust ML addon and point it at the ONNX Runtime library.
- *
- * A failure here (e.g. an OS version too old for the ONNX Runtime build) is
- * not fatal to the app: we remember the error, and all subsequent ML requests
- * fail with it, leaving the rest of the app functional.
- */
const loadMLNative = (paths: MLNativePaths) => {
try {
// eslint-disable-next-line @typescript-eslint/no-require-imports
const native = require(paths.addon) as MLNative;
native.initOrt(paths.onnxRuntimeLibrary);
- // Enables the guarded WebGPU path on Linux and Windows. This is a
- // no-op on macOS, where CoreML remains the preferred provider.
+ // Enables WebGPU where supported; macOS continues to use CoreML.
native.setMlExecutionConfig(true);
_assetStore = new native.AssetStore(
path.join(userDataPath(), "assets"),
@@ -125,10 +93,6 @@ const loadMLNative = (paths: MLNativePaths) => {
}
};
-/**
- * Return the loaded addon, throwing if it (or the ONNX Runtime library it
- * needs) could not be loaded on this machine.
- */
const mlNative = () => {
if (_native) return _native;
throw new CategorizedMLWorkerError(
@@ -145,10 +109,6 @@ const assetStore = () => {
);
};
-/**
- * Drain the runtime events (execution provider fallbacks, self-test failures)
- * buffered on the Rust side, writing each to our log at its severity.
- */
const logMLRuntimeEvents = (native: MLNative) => {
for (const { severity, message } of native.takeMlRuntimeEvents()) {
const s = `[ml-rt] ${message}`;
@@ -158,13 +118,6 @@ const logMLRuntimeEvents = (native: MLNative) => {
}
};
-/**
- * The models needed for the indexing tasks enabled in the given request,
- * mapped to verified on-disk paths.
- *
- * Models for tasks that are not requested are left as empty strings, which
- * the Rust side treats as "not configured".
- */
const _indexingModelPaths = new Map<
number,
Promise<MLNativeModule.ModelPaths>
@@ -190,11 +143,6 @@ const indexingModelPaths = (
return promise;
};
-/**
- * The model paths key for which the Rust runtime is currently prepared, if
- * any. Re-preparing with the same paths is skipped (the Rust side would
- * anyway no-op, this just avoids the IPC churn).
- */
let _preparedRuntimeKey: string | undefined;
const ensureMLRuntime = (
@@ -207,10 +155,6 @@ const ensureMLRuntime = (
_preparedRuntimeKey = key;
};
-/**
- * Release the (pinned) Rust ML runtime sessions. Called by the web layer when
- * indexing goes idle so that we don't hold on to the session memory.
- */
export const releaseMLRuntime = () => {
if (!_native) return;
_native.releaseMlRuntime();
@@ -218,16 +162,9 @@ export const releaseMLRuntime = () => {
logMLRuntimeEvents(_native);
};
-/**
- * The request the web layer sends us to analyze a single image. Mirrors (a
- * subset of) the addon's own request, except the image source, which we
- * convert to what the addon expects.
- */
export interface MLWorkerAnalyzeImageRequest {
fileID: number;
- /** Path to the image on the local filesystem. */
path?: string | undefined;
- /** The encoded image bytes (used when there is no local file). */
bytes?: Uint8Array | undefined;
runFaces: boolean;
runClip: boolean;
@@ -235,10 +172,6 @@ export interface MLWorkerAnalyzeImageRequest {
generateFaceCrops: boolean;
}
-/**
- * Analyze a single image with the Rust ML pipeline, downloading any needed
- * models first.
- */
export const analyzeImage = async (
req: MLWorkerAnalyzeImageRequest,
): Promise<MLWorkerAnalyzeImageResponse> => {
@@ -258,9 +191,8 @@ const analyzeImageOrThrow = async (req: MLWorkerAnalyzeImageRequest) => {
}
};
-// A corrupt on-disk model won't fix itself (models are hash-verified on
-// download), so treat it like an init failure: suspend indexing for the rest
-// of the process lifetime instead of retrying.
+// A corrupt on-disk model will fail every retry, so report an init failure that
+// suspends indexing until restart.
const categorizeAnalyzeImageError = (e: unknown): MLWorkerAnalyzeImageError => {
if (e instanceof CategorizedMLWorkerError) {
return { kind: e.kind, message: e.message };
@@ -309,7 +241,7 @@ const analyzeImageOnce = async (
});
};
-// Zero-copy view over the transferred bytes.
+// Buffer.from(bytes) would copy the image.
const uint8ArrayToBuffer = (bytes: Uint8Array) =>
Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength);
@@ -323,13 +255,6 @@ const clipTextModelPaths = () =>
throw e;
}));
-/**
- * Run a throwaway CLIP text query so that the Rust side builds and caches the
- * text encoder session before the user's first search. Mirrors the mobile
- * app's warm up (see ml_computer.dart).
- *
- * Best effort - on failure, queries build the session on demand as before.
- */
const warmUpClipTextEncoder = async (native: MLNative) => {
try {
const { modelPath, vocabPath } = await clipTextModelPaths();
@@ -345,22 +270,13 @@ const warmUpClipTextEncoder = async (native: MLNative) => {
}
};
-/**
- * Compute CLIP embeddings for a text snippet, if the model is available.
- *
- * The embedding is computed by the Rust pipeline (which also handles the
- * tokenization). If the model (or the addon itself) is not available yet, we
- * return `undefined` instead of blocking the caller on the download.
- */
export const computeCLIPTextEmbeddingIfAvailable = async (text: string) => {
if (!_native) return undefined;
const native = _native;
const pathsOrSkip = await Promise.race([
clipTextModelPaths(),
- // Wait a bit for the models to resolve the first time this code runs
- // on each app start (when they're already downloaded, resolving them
- // is quick), but don't block on a download.
+ // Allow an on-disk model to resolve without awaiting a download.
wait(50).then(() => 1 as const),
]);
diff --git a/desktop/src/main/services/store.ts b/desktop/src/main/services/store.ts
index 6e32b1923b..9adfbb490f 100644
--- a/desktop/src/main/services/store.ts
+++ b/desktop/src/main/services/store.ts
@@ -5,26 +5,14 @@ import { uploadStatusStore } from "../stores/upload-status";
import { userPreferences } from "../stores/user-preferences";
import { watchStore } from "../stores/watch";
-/**
- * Clear all stores except user preferences.
- *
- * This function is useful to reset state when the user logs out. User
- * preferences are preserved since they contain things tied to the person using
- * the app or other machine specific state not tied to the account they were
- * using inside the app.
- */
+// User preferences belong to the person or device, not the signed-in account.
export const clearStores = () => {
safeStorageStore.clear();
uploadStatusStore.clear();
watchStore.clear();
};
-/**
- * [Note: Safe storage keys]
- *
- * On macOS, `safeStorage` stores our data under a Keychain entry named
- * "<app-name> Safe Storage". In our case, "ente Safe Storage".
- */
+// macOS Keychain entry: "ente Safe Storage".
export const saveMasterKeyInSafeStorage = (masterKey: string) => {
const encryptedKeyBuffer = safeStorage.encryptString(masterKey);
const encryptedKey = Buffer.from(encryptedKeyBuffer).toString("base64");
@@ -87,11 +75,6 @@ export const appLockConfigFromSafeStorage = ():
| undefined => {
const config = appLockConfigStringFromSafeStorage();
- /*
- * if a key is not found then it will naturally return undefined, so
- * therefore if the config is not present returning undefined
- */
-
if (!config) return undefined;
return parsePersistedAppLockConfig(config);
@@ -107,27 +90,7 @@ export const lastShownChangelogVersion = (): number | undefined =>
export const setLastShownChangelogVersion = (version: number) =>
userPreferences.set("lastShownChangelogVersion", version);
-/**
- * Return true if the dock icon should be hidden when the window is closed
- * [macOS only].
- *
- * On macOS, if this function returns true then when the user closes the window
- * using the x traffic light we also hide the app's icon in the dock. The user
- * can modify their preference using the Menu bar > ente > Settings > Hide dock
- * icon checkbox.
- *
- * If the user has not set a value for this preference (i.e., the value is
- * `undefined`), we use the default `true`. This is confusing, but this way we
- * can retain the preexisting preference key instead of doing a migration.
- *
- * Value | Behaviour
- * ----------|--------------
- * undefined | default (hide)
- * false | show
- * true | hide
- *
- * On non-macOS platforms, it always returns false.
- */
+// A missing value preserves the legacy default without migrating the store.
export const shouldHideDockIcon = (): boolean =>
process.platform == "darwin" &&
userPreferences.get("hideDockIcon") !== false;
diff --git a/desktop/src/main/services/upload.ts b/desktop/src/main/services/upload.ts
index eb48b2096a..c1ccd478af 100644
--- a/desktop/src/main/services/upload.ts
+++ b/desktop/src/main/services/upload.ts
@@ -101,42 +101,7 @@ export const pendingUploads = (): PendingUploads | undefined => {
};
};
-/**
- * [Note: Missing values in electron-store]
- *
- * Suppose we were to create a store like this:
- *
- * const store = new Store({
- * schema: {
- * foo: { type: "string" },
- * bars: { type: "array", items: { type: "string" } },
- * },
- * });
- *
- * If we fetch `store.get("foo")` or `store.get("bars")`, we get `undefined`.
- * But if we try to set these back to `undefined`, say `store.set("foo",
- * someUndefValue)`, we get asked to
- *
- * TypeError: Use `delete()` to clear values
- *
- * This happens even if we do bulk object updates, e.g. with a JS object that
- * has undefined keys:
- *
- * > TypeError: Setting a value of type `undefined` for key `collectionName` is
- * > not allowed as it's not supported by JSON
- *
- * So what should the TypeScript type for "foo" be?
- *
- * If it is were to not include the possibility of `undefined`, then the type
- * would lie because `store.get("foo")` can indeed be `undefined. But if we were
- * to include the possibility of `undefined`, then trying to `store.set("foo",
- * someUndefValue)` will throw.
- *
- * The approach we take is to rely on false-y values (empty strings and empty
- * arrays) to indicate missing values, and then converting those to `undefined`
- * when reading from the store, and converting `undefined` to the corresponding
- * false-y value when writing.
- */
+// electron-store rejects undefined; empty strings and arrays encode absence.
export const setPendingUploads = ({
collectionName,
filePaths,
@@ -162,7 +127,7 @@ export const markUploadedFile = (
const existing = uploadStatusStore.get("filePaths") ?? [];
const updated = existing.filter((p) => p != path && p != associatedPath);
uploadStatusStore.set("filePaths", updated);
- // See: [Note: Integral last modified time]
+ // Persist integral mtimes for stable comparisons with remote values.
return fs.stat(path).then((st) => st.mtime.getTime());
};
diff --git a/desktop/src/main/services/watch.ts b/desktop/src/main/services/watch.ts
index 628ce88847..74fb37c6fc 100644
--- a/desktop/src/main/services/watch.ts
+++ b/desktop/src/main/services/watch.ts
@@ -6,14 +6,6 @@ import { watchStore } from "../stores/watch";
import { posixPath } from "../utils/electron";
import { fsIsDir } from "./fs";
-/**
- * Create and return a new file system watcher.
- *
- * Internally this uses the watcher from the chokidar package.
- *
- * @param mainWindow The window handle is used to notify the renderer process of
- * pertinent file system events.
- */
export const createWatcher = (mainWindow: BrowserWindow) => {
const send = (eventName: string) => (path: string) =>
mainWindow.webContents.send(eventName, ...eventData(path));
@@ -21,24 +13,11 @@ export const createWatcher = (mainWindow: BrowserWindow) => {
const folderPaths = folderWatches().map((watch) => watch.folderPath);
const watcher = chokidar.watch(folderPaths, {
- // Don't emit "add" events for matching paths when instantiating the
- // watch (we do a full disk scan on launch on our own, and also getting
- // the same events from the watcher causes duplicates).
+ // Initial events duplicate the full scan performed at launch.
ignoreInitial: true,
- // Ask the watcher to wait for a the file size to stabilize before
- // telling us about a new file. By default, it waits for 2 seconds.
awaitWriteFinish: true,
- // On macOS we start getting "EMFILE: too many open files" when watching
- // large folders. This is a known regression in Chokidar v4:
+ // Chokidar v4 exhausts file descriptors on macOS without polling.
// https://github.com/paulmillr/chokidar/issues/1385
- //
- // The recommended workaround for now is to enable usePolling. Since it
- // comes at a performance cost, we only do it where needed (macOS).
- //
- // Polling with the default interval (100ms) causes high CPU usage for
- // large folders (e.g. 10,000+ files). Increasing the interval to 5
- // seconds significantly reduces CPU while still detecting new files
- // within a reasonable time for a backup use case.
...(process.platform == "darwin"
? { usePolling: true, interval: 5000, binaryInterval: 5000 }
: {}),
@@ -73,14 +52,11 @@ export const watchGet = async (watcher: FSWatcher): Promise<FolderWatch[]> => {
const isAccessible = await fsIsDir(watch.folderPath);
result.push({ ...watch, isAccessible });
- // Update the file system watcher based on accessibility.
if (isAccessible) {
- // Add to watcher if not already being watched.
if (!watched[watch.folderPath]) {
watcher.add(watch.folderPath);
}
} else {
- // Stop watching inaccessible folders.
watcher.unwatch(watch.folderPath);
}
}
@@ -121,8 +97,6 @@ export const watchAdd = async (
watcher.add(folderPath);
- // Return watches with isAccessible set. The newly added folder is
- // accessible (we just verified it exists), and we check the others.
return await Promise.all(
watches.map(async (watch) => ({
...watch,
@@ -140,7 +114,6 @@ export const watchRemove = async (watcher: FSWatcher, folderPath: string) => {
);
setFolderWatches(filtered);
watcher.unwatch(folderPath);
- // Return watches with isAccessible set.
return await Promise.all(
filtered.map(async (watch) => ({
...watch,
@@ -177,15 +150,6 @@ export const watchUpdateIgnoredFiles = (
);
};
-/**
- * Stop watching all existing folder watches and remove any callbacks.
- *
- * This function is meant to be called when the user logs out. It stops
- * all existing folder watches and forgets about any "on*" callback
- * functions that have been registered.
- *
- * The persisted state itself gets cleared via {@link clearStores}.
- */
export const watchReset = (watcher: FSWatcher) => {
watcher.unwatch(folderWatches().map((watch) => watch.folderPath));
};
diff --git a/desktop/src/main/services/workers.ts b/desktop/src/main/services/workers.ts
index 514419f627..6005fc2008 100644
--- a/desktop/src/main/services/workers.ts
+++ b/desktop/src/main/services/workers.ts
@@ -1,8 +1,3 @@
-/**
- * @file This main process code and interface for dealing with the various
- * utility processes that we create.
- */
-
import type { Endpoint } from "comlink";
import {
MessageChannelMain,
@@ -16,93 +11,21 @@ import log, { processUtilityProcessLogMessage } from "../log";
import { messagePortMainEndpoint } from "../utils/comlink";
import { mlNativePaths } from "./ml-native";
-/**
- * Terminate any existing utility processes if they're running.
- *
- * This function is called during the logout sequence.
- */
export const terminateUtilityProcesses = () => {
terminateMLProcessIfRunning();
terminateFFmpegProcessIfRunning();
};
-/** The active ML utility process, if any. */
let _utilityProcessML: UtilityProcess | undefined;
-/** The active FFmpeg utility process, if any. */
let _utilityProcessFFmpeg: UtilityProcess | undefined;
-/**
- * A promise to a comlink {@link Endpoint} that can be used to communicate with
- * the active ffmpeg utility process (if any).
- */
let _utilityProcessFFmpegEndpoint: Promise<Endpoint> | undefined;
-/**
- * Create a new utility process of the given {@link type}, terminating the older
- * ones (if any).
- *
- * Currently the only type is "ml". 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 in a slightly different manner to
- * avoid stutter in the UI.
- *
- * [Note: ML IPC]
- *
- * The primary reason for doing ML tasks in the Node.js layer is so that we can
- * use the binary ONNX runtime, which is 10-20x faster than the Wasm one that
- * can be used directly on the web layer.
- *
- * For this to work, the main and renderer process need to communicate with each
- * other. Further, in the web layer the ML indexing runs in a web worker (so as
- * to not get in the way of the main thread). So the communication has 2 hops:
- *
- * Node.js main <-> Renderer main <-> Renderer web worker
- *
- * This naive way works, but has a problem. The Node.js main process is in the
- * code path for delivering user events to the renderer process. The ML tasks we
- * do take in the order of 100-300 ms (possibly more) for each individual
- * inference. Thus, the Node.js main process is busy for those 100-300 ms, and
- * does not forward events to the renderer, causing the UI to jitter.
- *
- * The solution for this is to spawn an Electron UtilityProcess, which we can
- * think of a regular Node.js child process. This frees up the Node.js main
- * process, and would remove the jitter.
- * https://www.electronjs.org/docs/latest/tutorial/process-model
- *
- * It would seem that this introduces another hop in our IPC
- *
- * Node.js utility process <-> Node.js main <-> ...
- *
- * but here we can use the special bit about Electron utility processes that
- * separates them from regular Node.js child processes: their support for
- * message ports. https://www.electronjs.org/docs/latest/tutorial/message-ports
- *
- * As a brief summary, a MessagePort is a web feature that allows two contexts
- * to communicate. A pair of message ports is called a message channel. The cool
- * thing about these is that we can pass these ports themselves over IPC.
- *
- * > One caveat here is that the message ports can only be passed using the
- * > `postMessage` APIs, not the usual send/invoke APIs.
- *
- * So we
- *
- * 1. In the utility process create a message channel.
- * 2. Spawn a utility process, and send one port of the pair to it.
- * 3. Send the other port of the pair to the renderer.
- *
- * The renderer will forward that port to the web worker that is coordinating
- * the ML indexing on the web layer. Thereafter, the utility process and web
- * worker can directly talk to each other!
- *
- * Node.js utility process <-> Renderer web worker
- *
- * The RPC protocol is handled using comlink on both ends. The port itself needs
- * to be relayed using `postMessage`.
- */
+// Native ML runs outside main so inference cannot block UI event delivery. A
+// transferred MessagePort connects the utility process to the renderer worker.
export const triggerCreateUtilityProcess = (
- type: UtilityProcessType,
+ _type: UtilityProcessType,
window: BrowserWindow,
) => triggerCreateMLUtilityProcess(window);
@@ -115,20 +38,8 @@ const terminateMLProcessIfRunning = () => {
}
};
-/**
- * Fork a utility process running {@link scriptName}, mirroring its stdout and
- * stderr into our log (prefixed with {@link logTag}), and logging an error if
- * it exits on its own.
- *
- * The usual log flow for utility processes (see `log-worker.ts`) requires
- * their module graph to have loaded. Without this mirroring, a crash during
- * module load (e.g. a missing native library) would be written only to the
- * inherited stderr, which is invisible in packaged apps, and the log file
- * would not contain any trace of it.
- *
- * Callers that deliberately kill the returned process should remove its
- * "exit" listeners first.
- */
+// Pipe stdio because failures before log-worker loads are otherwise invisible
+// in packaged apps.
const forkWatchedUtilityProcess = (scriptName: string, logTag: string) => {
const child = utilityProcess.fork(path.join(__dirname, scriptName), [], {
stdio: "pipe",
@@ -145,7 +56,7 @@ const forkWatchedUtilityProcess = (scriptName: string, logTag: string) => {
return child;
};
-// Electron tears down utility processes on quit; don't report those exits.
+// Electron tears these down on quit; those exits are not failures.
app.on("before-quit", () => {
_utilityProcessML?.removeAllListeners("exit");
_utilityProcessFFmpeg?.removeAllListeners("exit");
@@ -158,10 +69,9 @@ export const triggerCreateMLUtilityProcess = (window: BrowserWindow) => {
const child = forkWatchedUtilityProcess("ml-worker.js", "[ml-worker]");
const userDataPath = app.getPath("userData");
- child.postMessage(
- /* MLWorkerInitData */ { userDataPath, mlNativePaths: mlNativePaths() },
- [port1],
- );
+ child.postMessage({ userDataPath, mlNativePaths: mlNativePaths() }, [
+ port1,
+ ]);
window.webContents.postMessage("utilityProcessPort/ml", undefined, [port2]);
@@ -170,29 +80,6 @@ export const triggerCreateMLUtilityProcess = (window: BrowserWindow) => {
_utilityProcessML = child;
};
-/**
- * Handle messages posted from the utility process.
- *
- * [Note: Using Electron APIs in UtilityProcess]
- *
- * Only a small subset of the Electron APIs are available to a UtilityProcess.
- * As of writing (Jul 2024, Electron 30), only the following are available:
- *
- * - net
- * - systemPreferences
- *
- * In particular, `app` is not available.
- *
- * We structure our code so that it doesn't need anything apart from `net`.
- *
- * For the other cases,
- *
- * - Additional parameters to the utility process are passed alongwith the
- * initial message where we provide it the message port.
- *
- * - When we need to communicate from the utility process to the main process,
- * we use the `parentPort` in the utility process.
- */
const handleMessagesFromMLUtilityProcess = (child: UtilityProcess) => {
child.on("message", (m: unknown) => {
if (processUtilityProcessLogMessage("[ml-worker]", m)) {
@@ -202,32 +89,8 @@ const handleMessagesFromMLUtilityProcess = (child: UtilityProcess) => {
});
};
-/**
- * A comlink endpoint that can be used to communicate with the ffmpeg utility
- * process. If there is no ffmpeg utility process, a new one is created on
- * demand.
- *
- * See [Note: ML IPC] for a general outline of why utility processes are needed
- * (tl;dr; to avoid stutter on the UI).
- *
- * In the case of ffmpeg, the IPC flow is a bit different: the utility process
- * is not exposed to the web layer, and is internal to the node layer. The
- * reason for this difference is that we need to create temporary files etc, and
- * doing it a utility process requires access to the `app` module which are not
- * accessible (See: [Note: Using Electron APIs in UtilityProcess]).
- *
- * There could've been possible reasonable workarounds, but the architecture
- * we've adopted of three layers:
- *
- * Renderer (web) <-> Node.js main <-> Node.js ffmpeg utility process
- *
- * The temporary file creation etc is handled in the Node.js main process, and
- * paths to the files are forwarded to the ffmpeg utility process to act on.
- *
- * @returns an endpoint that can be used to communicate with the utility
- * process. The utility process is expected to expose an object that conforms to
- * the {@link ElectronFFmpegWorkerNode} interface on this endpoint.
- */
+// FFmpeg file setup stays in main because Electron's app API is unavailable in
+// utility processes.
export const ffmpegUtilityProcessEndpoint = () =>
(_utilityProcessFFmpegEndpoint ??= createFFmpegUtilityProcessEndpoint());
@@ -246,7 +109,6 @@ const createFFmpegUtilityProcessEndpoint = () => {
throw new Error("FFmpeg utility process is already running");
}
- // Promise.withResolvers is currently in the node available to us.
let resolve: ((endpoint: Endpoint) => void) | undefined;
let reject: ((e: Error) => void) | undefined;
const promise = new Promise<Endpoint>((res, rej) => {
@@ -260,11 +122,9 @@ const createFFmpegUtilityProcessEndpoint = () => {
"ffmpeg-worker.js",
"[ffmpeg-worker]",
);
- // Send a handle to the port (one end of the message channel) to the utility
- // process (alongwith any other init data). The utility process will reply
- // with an "ack" when it get it.
+
const appVersion = app.getVersion();
- child.postMessage(/* FFmpegWorkerInitData */ { appVersion }, [port1]);
+ child.postMessage({ appVersion }, [port1]);
child.on("message", (m: unknown) => {
if (m && typeof m == "object" && "method" in m) {
@@ -284,16 +144,11 @@ const createFFmpegUtilityProcessEndpoint = () => {
_utilityProcessFFmpeg = child;
- // Recover from crashes: reject the endpoint promise if it is still
- // pending, and clear the cached values so that the next FFmpeg operation
- // spawns a new utility process.
child.on("exit", () => {
reject?.(new Error("The FFmpeg utility process exited"));
_utilityProcessFFmpeg = undefined;
_utilityProcessFFmpegEndpoint = undefined;
});
- // Resolve with the other end of the message channel (once we get an "ack"
- // from the utility process).
return promise;
};
diff --git a/desktop/src/main/services/zip.ts b/desktop/src/main/services/zip.ts
index 17a7205bce..bcf4cc8c04 100644
--- a/desktop/src/main/services/zip.ts
+++ b/desktop/src/main/services/zip.ts
@@ -1,12 +1,11 @@
import { LRUCache } from "lru-cache";
import StreamZip from "node-stream-zip";
-/** The cache. */
const _cache = new LRUCache<string, StreamZip.StreamZipAsync>({
max: 50,
disposeAfter: (zip, zipPath) => {
if (_refCount.has(zipPath)) {
- // Add it back again.
+ // Eviction must not close handles still in use.
_cache.set(zipPath, zip);
} else {
void zip.close();
@@ -14,29 +13,9 @@ const _cache = new LRUCache<string, StreamZip.StreamZipAsync>({
},
});
-/** Reference count. */
const _refCount = new Map<string, number>();
-/**
- * Cached `StreamZip.async`s
- *
- * This function uses an LRU cache to cache handles to zip files indexed by
- * their path.
- *
- * To clear the cache (which is a good idea to avoid having open file handles
- * lying around), use {@link clearOpenZipCache}.
- *
- * Why was this needed
- * -------------------
- *
- * Caching the StreamZip file handles _significantly_ (hours => seconds)
- * improves the performance of the metadata parsing step during import of large
- * Google Takeout zips.
- *
- * In ad-hoc tests, it seems that beyond a certain zip size (few GBs), reopening
- * the handle to a stream zip overshadows the time taken to read the individual
- * JSONs.
- */
+// Reopening multi-GB Takeout archives per entry turns seconds into hours.
export const openZip = (zipPath: string) => {
let result = _cache.get(zipPath);
if (!result) {
@@ -47,12 +26,6 @@ export const openZip = (zipPath: string) => {
return result;
};
-/**
- * Indicate to our cache that an item we opened earlier using {@link openZip}
- * can now be safely closed.
- *
- * @param zipPath The key that was used for opening this zip.
- */
export const markClosableZip = (zipPath: string) => {
const rc = _refCount.get(zipPath);
if (!rc) throw new Error(`Double close for ${zipPath}`);
@@ -60,9 +33,6 @@ export const markClosableZip = (zipPath: string) => {
else _refCount.set(zipPath, rc - 1);
};
-/**
- * Clear any entries previously cached by {@link openZip}.
- */
export const clearOpenZipCache = () => {
if (_refCount.size > 0) {
const kvs = JSON.stringify([..._refCount.entries()]);