The next-generation file converter. Open source, fully local* and free forever.
feat: defer downloading converters till file added
JovannMCaa79c1230da3
diff --git a/messages/en.json b/messages/en.jsonindex 08d659b..7791a86 100644--- a/messages/en.json+++ b/messages/en.json@@ -33,7 +33,7 @@"ready": "ready","partially_ready": "partially ready","not_ready": "not ready",- "not_initialized": "not initialized",+ "not_initialized": "not initialized yet","downloading": "downloading...","initializing": "initializing...","unknown": "unknown status"@@ -207,7 +207,8 @@"document_file": "Document file","image_file": "Image file","convert_file": "Convert this file",- "download_file": "Download this file"+ "download_file": "Download this file",+ "converter_initializing": "The converter is being downloaded and initialized. The converters will be cached in your browser for future conversions."},"errors": {"cant_convert": "We can't convert this file.",@@ -220,7 +221,7 @@},"unsupported_format": "Only image, video, audio, and document files are supported","format_output_only": "This format can currently only be used as output (converted to), not as input.",- "worker_downloading": "The {type} converter is currently being initialized, please wait a few moments.",+ "worker_downloading": "The {type} converter is currently being downloaded and/or initialized, please wait a few moments.","worker_error": "The {type} converter had an error during initialization, please try again later.","worker_timeout": "The {type} converter is taking longer than expected to initialize, please wait a few more moments or refresh the page.","audio": "audio",@@ -410,8 +411,9 @@"title": "Converters","formats": "Formats","statuses": {- "not_ready": "Not ready",+ "idle": "Not initialized","downloading": "Downloading",+ "initializing": "Initializing","ready": "Ready","partially_ready": "Partially ready","error": "Error"diff --git a/src/lib/converters/converter.svelte.ts b/src/lib/converters/converter.svelte.tsindex 5d7e2ff..22a8c65 100644--- a/src/lib/converters/converter.svelte.ts+++ b/src/lib/converters/converter.svelte.ts@@ -1,5 +1,6 @@/* eslint-disable @typescript-eslint/no-explicit-any *//* eslint-disable @typescript-eslint/no-unused-vars */+import { error, log } from "#lib/util/logger.svelte";import type { VertFile } from "#lib/types";import type {ConversionSettings,@@ -8,7 +9,12 @@ import type {} from "#lib/types/conversion-settings";export type WorkerStatus =- "not-ready" | "downloading" | "ready" | "partially-ready" | "error";+ | "idle" // not initialized yet (nothing downloaded)+ | "downloading" // fetching the converter's assets (wasm/js)+ | "initializing" // initialize converter after downloading+ | "ready"+ | "partially-ready"+ | "error"; // actual failure during initializationexport class FormatInfo {public name: string;@@ -44,21 +50,69 @@ export class Converter {*/public supportedFormats: FormatInfo[] = [];- public status: WorkerStatus = $state("not-ready");+ public status: WorkerStatus = $state("idle");public readonly reportsProgress: boolean = false;private timeoutId?: ReturnType<typeof setTimeout>;private activeInput?: VertFile;+ private initPromise: Promise<void> | null = null;- constructor(public readonly timeout: number = 10) {- this.startTimeout();- }+ protected log: (...msg: unknown[]) => void = (...msg) =>+ log(["converters", this.name], ...msg);+ protected error: (...msg: unknown[]) => void = (...msg) =>+ error(["converters", this.name], ...msg);++ constructor(public readonly timeout: number = 10) {}++ /**+ * Downloads any assets (WASM/JS) the converter needs.+ */+ protected async download(): Promise<void> {}/**- * Downloads (if necessary) and initializes the converter.+ * Initializes the converter after downloading its assets.*/- public async init(): Promise<void> {- this.status = "ready";+ protected async setup(): Promise<void> {}++ public init(): Promise<void> {+ // allow a another attempt if the previous one failed+ if (this.status === "error") this.initPromise = null;+ return (this.initPromise ??= this.runInit());+ }++ private async runInit(): Promise<void> {+ if (this.status === "ready" || this.status === "partially-ready")+ return;++ const hasDownload = this.download !== Converter.prototype.download;+ const hasSetup = this.setup !== Converter.prototype.setup;++ // nothing to do unless a subclass implements one of the hooks+ if (!hasDownload && !hasSetup) {+ this.status = "ready";+ return;+ }++ this.log(`initializing (was ${this.status})`);+ this.startTimeout();+ try {+ if (hasDownload) {+ this.status = "downloading";+ await this.download();+ }+ if (hasSetup) {+ this.status = "initializing";+ await this.setup();+ }+ // if the hooks didn't set a terminal status, assume it succeeded+ if (this.status === "downloading" || this.status === "initializing")+ this.status = "ready";+ } catch (err) {+ this.error(`initialization failed: ${err}`);+ this.status = "error";+ } finally {+ this.clearTimeout();+ }}/**@@ -101,10 +155,11 @@ export class Converter {}private startTimeout() {+ this.clearTimeout();this.timeoutId = setTimeout(() => {- if (this.status === "ready") return;- this.status = "not-ready";- if (this.activeInput) void this.cancel(this.activeInput);+ if (this.status !== "downloading" && this.status !== "initializing")+ return;+ this.log(`initialization is taking longer than ${this.timeout}s`);}, this.timeout * 1000);}@@ -149,6 +204,18 @@ export class Converter {return true;}+ /**+ * This is to indicate whether the converter is usable at all.+ * It will be true if its still downloading / initializing - it shouldn't block the user from starting a conversion+ * unless it does actually fail to initialize+ */+ public isAvailable(): boolean {+ return this.status !== "error";+ }++ /**+ * Whether this converter is initialized and usable right now+ */public isReady(): boolean {return this.status === "ready" || this.status === "partially-ready";}diff --git a/src/lib/converters/ffmpeg/ffmpeg.svelte.ts b/src/lib/converters/ffmpeg/ffmpeg.svelte.tsindex 0bf7555..7b473d9 100644--- a/src/lib/converters/ffmpeg/ffmpeg.svelte.ts+++ b/src/lib/converters/ffmpeg/ffmpeg.svelte.ts@@ -2,7 +2,6 @@ import { VertFile } from "#lib/types";import { Converter, FormatInfo } from "../converter.svelte";import { FFmpeg } from "@ffmpeg/ffmpeg";import { browser } from "$app/env";-import { error, log } from "#lib/util/logger.svelte";import { SvelteMap } from "svelte/reactivity";import { m } from "#lib/paraglide/messages";import { Settings } from "#lib/sections/settings/index.svelte";@@ -74,39 +73,28 @@ export class FFmpegConverter extends Converter {public readonly reportsProgress = true;- // eslint-disable-next-line @typescript-eslint/no-explicit-any- private log: (...msg: any[]) => void = () => {};- // eslint-disable-next-line @typescript-eslint/no-explicit-any- private error: (...msg: any[]) => void = () => {};-constructor() {super();if (!browser) return;- this.log = (msg) => log(["converters", this.name], msg);- this.error = (msg) => error(["converters", this.name], msg);this.log(`created converter`);}- public async init(): Promise<void> {+ protected async download(): Promise<void> {// this is just to cache the wasm and js for when we actually use it. we're not using this ffmpeg instanceif (!browser) return;this.ffmpeg = new FFmpeg();try {- this.status = "downloading";-await this.ffmpeg.load({ coreURL, wasmURL });- this.status = "ready";this.ffmpeg.terminate();- this.log("preloaded ffmpeg assets and released the cache instance");+ this.status = "ready";} catch (err) {- this.error(`Error loading ffmpeg: ${err}`);- this.status = "error";this.ffmpeg.terminate();ToastManager.add({type: "error",message: m["workers.errors.ffmpeg"](),});+ throw err;}}@@ -227,6 +215,8 @@ export class FFmpegConverter extends Converter {const isAlac = to === ".alac";if (isAlac) to = ".m4a";+ await this.init();+let conversionError: string | null = null;const ffmpeg = await this.setupFFmpeg(input);diff --git a/src/lib/converters/magick/magick.svelte.ts b/src/lib/converters/magick/magick.svelte.tsindex 123df52..5b07625 100644--- a/src/lib/converters/magick/magick.svelte.ts+++ b/src/lib/converters/magick/magick.svelte.ts@@ -1,5 +1,4 @@import { browser } from "$app/env";-import { error, log } from "#lib/util/logger.svelte";import { m } from "#lib/paraglide/messages";import { VertFile, type WorkerMessage } from "#lib/types";import MagickWorker from "#lib/workers/magick?worker&url";@@ -91,23 +90,14 @@ export class MagickConverter extends Converter {public readonly reportsProgress = false;- // eslint-disable-next-line @typescript-eslint/no-explicit-any- private log: (...msg: any[]) => void = () => {};- // eslint-disable-next-line @typescript-eslint/no-explicit-any- private error: (...msg: any[]) => void = () => {};-constructor() {super();- this.log = (msg) => log(["converters", this.name], msg);- this.error = (msg) => error(["converters", this.name], msg);this.log(`created converter`);if (!browser) return;- this.initializeWasm();}- private async initializeWasm() {+ protected async download(): Promise<void> {try {- this.status = "downloading";const response = await fetch(magickWasm);if (!response.ok) {throw new Error(@@ -116,15 +106,12 @@ export class MagickConverter extends Converter {}this.wasm = await response.arrayBuffer();- this.status = "ready";} catch (err) {- this.status = "error";- this.error(`Failed to load ImageMagick WASM: ${err}`);-ToastManager.add({type: "error",message: m["workers.errors.magick"](),});+ throw err;}}@@ -250,6 +237,8 @@ export class MagickConverter extends Converter {// eslint-disable-next-line @typescript-eslint/no-explicit-any...args: any[]): Promise<VertFile> {+ await this.init();+this.trackConversion(input);this.log(`converting ${input.name} to ${to}`);diff --git a/src/lib/converters/mediabunny/mediabunny.svelte.ts b/src/lib/converters/mediabunny/mediabunny.svelte.tsindex 71e3689..b62e7cc 100644--- a/src/lib/converters/mediabunny/mediabunny.svelte.ts+++ b/src/lib/converters/mediabunny/mediabunny.svelte.ts@@ -25,8 +25,7 @@ import { registerMp3Encoder } from "@mediabunny/mp3-encoder";import { registerFlacEncoder } from "@mediabunny/flac-encoder";import { registerProresDecoder } from "@mediabunny/prores";import { SvelteMap } from "svelte/reactivity";-import { Converter, FormatInfo, type WorkerStatus } from "../converter.svelte";-import { error, log } from "#lib/util/logger.svelte";+import { Converter, FormatInfo } from "../converter.svelte";import { m } from "#lib/paraglide/messages";import type {SettingDefinition,@@ -133,7 +132,6 @@ const buildAudioConfig = (export class MediabunnyConverter extends Converter {public name = "mediabunny";- public status: WorkerStatus = $state("ready");public reportsProgress: boolean = true;private activeConversions = new SvelteMap<string, Conversion>();@@ -156,27 +154,17 @@ export class MediabunnyConverter extends Converter {...this.formats.map((f) => new FormatInfo(f, true, true, true, 2)),];- // eslint-disable-next-line @typescript-eslint/no-explicit-any- private log: (...msg: any[]) => void = () => {};- // eslint-disable-next-line @typescript-eslint/no-explicit-any- private error: (...msg: any[]) => void = () => {};-constructor() {super();if (!browser) return;+ }- this.log = (msg) => log(["converters", this.name], msg);- this.error = (msg) => error(["converters", this.name], msg);-+ protected async setup(): Promise<void> {// additional mediabunny coders// currently the official ones -- maybe add our own in the future- void this.initializeCodecs()- .then(() => this.checkStatus())- .catch((err) => {- this.error(`Failed to initialize Mediabunny codecs: ${err}`);- this.status = "error";- });+ await this.initializeCodecs();+ await this.checkStatus();}private async checkStatus() {@@ -357,6 +345,8 @@ export class MediabunnyConverter extends Converter {to: string,settings: ConversionSettings,): Promise<VertFile> {+ await this.init();+this.trackConversion(file);const toFormat = to.startsWith(".") ? to.slice(1) : to;const originalName = file.file.name.split(".").slice(0, -1).join(".");diff --git a/src/lib/converters/pandoc/pandoc.svelte.ts b/src/lib/converters/pandoc/pandoc.svelte.tsindex 485f333..fde15ed 100644--- a/src/lib/converters/pandoc/pandoc.svelte.ts+++ b/src/lib/converters/pandoc/pandoc.svelte.ts@@ -2,7 +2,6 @@ import { VertFile, type WorkerMessage } from "#lib/types";import { Converter, FormatInfo } from "../converter.svelte";import { browser } from "$app/env";import PandocWorker from "#lib/workers/pandoc?worker&url";-import { error, log } from "#lib/util/logger.svelte";import { ToastManager } from "#lib/util/toast.svelte";import { SvelteMap } from "svelte/reactivity";import { m } from "#lib/paraglide/messages";@@ -14,36 +13,30 @@ export class PandocConverter extends Converter {private activeConversions = new SvelteMap<string, Worker>();- // eslint-disable-next-line @typescript-eslint/no-explicit-any- private log: (...msg: any[]) => void = () => {};- // eslint-disable-next-line @typescript-eslint/no-explicit-any- private error: (...msg: any[]) => void = () => {};-constructor() {super();- this.log = (msg) => log(["converters", this.name], msg);- this.error = (msg) => error(["converters", this.name], msg);if (!browser) return;- (async () => {- try {- this.status = "downloading";- this.wasm = await fetch("/pandoc.wasm").then((r) =>- r.arrayBuffer(),- );-- this.status = "ready";- } catch (err) {- this.status = "error";- this.error(`Failed to load Pandoc worker: ${err}`);- ToastManager.add({- type: "error",- message: m["workers.errors.pandoc"](),- });- }- })();+ }++ protected async download(): Promise<void> {+ if (!browser) return;+ try {+ this.wasm = await fetch("/pandoc.wasm").then((r) =>+ r.arrayBuffer(),+ );+ } catch (err) {+ this.error(`Failed to load Pandoc WASM: ${err}`);+ ToastManager.add({+ type: "error",+ message: m["workers.errors.pandoc"](),+ });+ throw err;+ }}public async convert(file: VertFile, to: string): Promise<VertFile> {+ await this.init();+this.trackConversion(file);const worker = new Worker(PandocWorker, {type: "module",diff --git a/src/lib/converters/vertd/vertd.svelte.ts b/src/lib/converters/vertd/vertd.svelte.tsindex d634a52..a1c6dec 100644--- a/src/lib/converters/vertd/vertd.svelte.ts+++ b/src/lib/converters/vertd/vertd.svelte.ts@@ -1,5 +1,4 @@import VertdErrorComponent from "#lib/components/functional/popups/VertdError.svelte";-import { error, log } from "#lib/util/logger.svelte";import { m } from "#lib/paraglide/messages";import { Settings } from "#lib/sections/settings/index.svelte";import { SvelteMap, SvelteSet } from "svelte/reactivity";@@ -372,17 +371,10 @@ export class VertdConverter extends Converter {...cantDecode.map((f) => new FormatInfo(f, false, true, true, 0)),];- // eslint-disable-next-line @typescript-eslint/no-explicit-any- private log: (...msg: any[]) => void = () => {};- // eslint-disable-next-line @typescript-eslint/no-explicit-any- private error: (...msg: any[]) => void = () => {};-private codecs: CodecsResponse = { videoCodecs: [], audioCodecs: [] };constructor() {super();- this.log = (msg) => log(["converters", this.name], msg);- this.error = (msg) => error(["converters", this.name], msg);this.log("created converter");this.log("not rly sure how to implement this :P");this.status = "ready";@@ -925,8 +917,7 @@ export class VertdConverter extends Converter {return;}- log(- ["converters", this.name],+ this.log(`cancelling conversion for file ${input.name}`,);diff --git a/src/lib/store/index.svelte.ts b/src/lib/store/index.svelte.tsindex a190c5a..6071326 100644--- a/src/lib/store/index.svelte.ts+++ b/src/lib/store/index.svelte.ts@@ -58,6 +58,12 @@ class Files {);}+ // preload first required converter when added to list+ private preloadConverters(file: VertFile): void {+ const [preferred] = this.getRequiredConverters(file);+ void preferred?.init();+ }+public requiredConverters = $derived(Array.from(new Set(@@ -279,6 +285,7 @@ class Files {this.files.push(vf);this._addThumbnail(vf);+ this.preloadConverters(vf);// set converter// TODO: this is weird, we rely on conversionSettings for the right converter but zip archives obv dont have settings to change@@ -340,6 +347,7 @@ class Files {if (file instanceof VertFile) {this.files.push(file);this._addThumbnail(file);+ this.preloadConverters(file);} else {// regular filesconst format = input.from;@@ -372,6 +380,7 @@ class Files {vf.to = to;this.files.push(vf);this._addThumbnail(vf);+ this.preloadConverters(vf);const convName = converter.name;if (diff --git a/src/lib/types/file.svelte.ts b/src/lib/types/file.svelte.tsindex 3cac2d0..1c0e8d5 100644--- a/src/lib/types/file.svelte.ts+++ b/src/lib/types/file.svelte.ts@@ -204,7 +204,7 @@ export class VertFile {.filter((converter) => {if (unavailableConverters[converter.name] ||- !converter.isReady()+ !converter.isAvailable())return false;if (@@ -255,7 +255,7 @@ export class VertFile {return this.converters.some((converter) => {if (this.unavailableConverters[converter.name] ||- !converter.isReady()+ !converter.isAvailable())return false;diff --git a/src/lib/util/debug.svelte.ts b/src/lib/util/debug.svelte.tsindex 0a6142a..ec18519 100644--- a/src/lib/util/debug.svelte.ts+++ b/src/lib/util/debug.svelte.ts@@ -67,8 +67,9 @@ export const CONVERTER_META: Record<};export const STATUS_CLASSES: Record<string, string> = {- "not-ready": "bg-button text-muted",+ idle: "bg-button text-muted",downloading: "bg-accent-blue text-black",+ initializing: "bg-accent-blue text-black",ready: "bg-accent-green text-black","partially-ready": "bg-accent-purple text-black",error: "bg-accent-red text-black",@@ -76,8 +77,9 @@ export const STATUS_CLASSES: Record<string, string> = {export function getStatusLabels(): Record<string, string> {return {- "not-ready": m["settings.debug.converters.statuses.not_ready"](),+ idle: m["settings.debug.converters.statuses.idle"](),downloading: m["settings.debug.converters.statuses.downloading"](),+ initializing: m["settings.debug.converters.statuses.initializing"](),ready: m["settings.debug.converters.statuses.ready"](),"partially-ready":m["settings.debug.converters.statuses.partially_ready"](),diff --git a/src/routes/+page.svelte b/src/routes/+page.svelteindex 8782087..3c6818e 100644--- a/src/routes/+page.svelte+++ b/src/routes/+page.svelte@@ -45,7 +45,7 @@title: m["upload.cards.images"](),status:converters.find((c) => c.name === "imagemagick")?.status ||- "not-ready",+ "idle",},Audio: {formats: getSupportedFormats("ffmpeg"),@@ -53,7 +53,7 @@title: m["upload.cards.audio"](),status:converters.find((c) => c.name === "ffmpeg")?.status ||- "not-ready",+ "idle",},Documents: {formats: getSupportedFormats("pandoc"),@@ -61,7 +61,7 @@title: m["upload.cards.documents"](),status:converters.find((c) => c.name === "pandoc")?.status ||- "not-ready",+ "idle",},};@@ -75,17 +75,16 @@.filter((f) => f !== "none").join(", ");- const mediabunnyStatus = converters.find(+ const mediabunnyAvailable = converters.find((c) => c.name === "mediabunny",- )?.status;+ )?.isAvailable();const vertdReady = $vertdLoaded === true;- const mediabunnyReady = mediabunnyStatus === "ready";const videoStatus =- vertdReady && mediabunnyReady+ vertdReady && mediabunnyAvailable? "ready"- : vertdReady || mediabunnyReady+ : vertdReady || mediabunnyAvailable? "partially-ready"- : "not-ready";+ : "error";output.Video = {formats,@@ -120,12 +119,16 @@switch (status) {case "downloading":return m["upload.cards.status.downloading"]();+ case "initializing":+ return m["upload.cards.status.initializing"]();case "partially-ready":return m["upload.cards.status.partially_ready"]();case "ready":return m["upload.cards.status.ready"]();+ case "idle":+ return m["upload.cards.status.not_initialized"]();default:- // "not-ready", "error" and other statuses (somehow)+ // "error" and other statuses (somehow)return m["upload.cards.status.not_ready"]();}};diff --git a/src/routes/convert/+page.svelte b/src/routes/convert/+page.svelteindex c3bdbc7..3012379 100644--- a/src/routes/convert/+page.svelte+++ b/src/routes/convert/+page.svelte@@ -94,7 +94,7 @@if (selectedConverter) return selectedConverter;}- // prefer a usable converter over a not-ready one+ // prefer a usable (loaded) converter over one that still has to initializeconst readyConverter = availableConverters.find((c) => c.status === "ready" || c.status === "partially-ready",);@@ -210,6 +210,10 @@{@const isAudio = converterCategories.audio.includes(name)}{@const isVideo = converterCategories.video.includes(name)}{@const isDocument = converterCategories.doc.includes(name)}+ {@const isInitializing =+ currentConverter?.status === "idle" ||+ currentConverter?.status === "downloading" ||+ currentConverter?.status === "initializing"}<Panel class="p-5 flex flex-col min-w-0 gap-4 relative"><div class="flex-shrink-0 h-8 w-full flex items-center gap-2">{#if !converters.length}@@ -267,6 +271,23 @@</h2>{/if}</div>+ <div+ class="flex-shrink-0 flex items-center justify-center overflow-visible transition-transform duration-300 {isInitializing+ ? 'w-8 opacity-100'+ : 'w-0 opacity-0'}"+ >+ {#if isInitializing}+ <Tooltip+ text={m["convert.tooltips.converter_initializing"]()}+ position="bottom"+ >+ <DownloadIcon+ size="20"+ class="animate-bounce text-muted"+ />+ </Tooltip>+ {/if}+ </div><buttonclass="flex-shrink-0 w-8 rounded-full hover:bg-panel-alt h-full flex items-center justify-center"onclick={() => files.remove(file)}@@ -327,25 +348,6 @@})}</p></div>- {:else if currentConverter.status === "downloading"}- <div- class="h-full flex flex-col text-center justify-center text-failure"- >- <p class="font-body font-bold">- {m["convert.errors.cant_convert"]()}- </p>- <p class="font-normal">- {m["convert.errors.worker_downloading"]({- type: isAudio- ? m["convert.errors.audio"]()- : isVideo- ? m["convert.errors.video"]()- : isDocument- ? m["convert.errors.doc"]()- : m["convert.errors.image"](),- })}- </p>- </div>{:else if currentConverter.status === "error"}<divclass="h-full flex flex-col text-center justify-center text-failure"@@ -365,25 +367,6 @@})}</p></div>- {:else if currentConverter.status === "not-ready"}- <div- class="h-full flex flex-col text-center justify-center text-failure"- >- <p class="font-body font-bold">- {m["convert.errors.cant_convert"]()}- </p>- <p class="font-normal">- {m["convert.errors.worker_timeout"]({- type: isAudio- ? m["convert.errors.audio"]()- : isVideo- ? m["convert.errors.video"]()- : isDocument- ? m["convert.errors.doc"]()- : m["convert.errors.image"](),- })}- </p>- </div>{:else}<div class="flex flex-row justify-between"><div