The next-generation file converter. Open source, fully local* and free forever.
fix: converter cancellation during init fixes, zips using multiple converters, broken input/output formats
JovannMC9663f8a2ea70
diff --git a/src/lib/converters/converter.svelte.ts b/src/lib/converters/converter.svelte.tsindex dc4f074..c99233d 100644--- a/src/lib/converters/converter.svelte.ts+++ b/src/lib/converters/converter.svelte.ts@@ -7,6 +7,7 @@ import type {SettingCategories,} from "#lib/types/conversion-settings";import { error, log } from "#lib/util/logger.svelte";+import { SvelteSet } from "svelte/reactivity";import { canonicalCodecName, codecLabel } from "./codec-labels";export type WorkerStatus =@@ -68,6 +69,8 @@ export class Converter {private activeInput?: VertFile;private initPromise: Promise<void> | null = null;+ protected readonly cancelledBeforeStart = new SvelteSet<string>();+protected log: (...msg: unknown[]) => void = (...msg) =>log(["converters", this.name], ...msg);protected error: (...msg: unknown[]) => void = (...msg) =>@@ -244,6 +247,22 @@ export class Converter {}}+ // used for checking if a conversion was cancelled before it started (e.g. during init)+ protected throwIfCancelled(input: VertFile) {+ if (this.cancelledBeforeStart.has(input.id)) {+ this.cancelledBeforeStart.delete(input.id);+ throw new Error("Conversion cancelled");+ }+ }++ protected isCancelled(input: VertFile) {+ return this.cancelledBeforeStart.has(input.id);+ }++ protected clearCancel(input: VertFile) {+ this.cancelledBeforeStart.delete(input.id);+ }+/*** Convert a file to a different format.* @param input The input file.@@ -260,10 +279,13 @@ export class Converter {/*** Cancel the active conversion of a file.+ * Subclasses should call `super.clearCancel(input)` after handling their own+ * resources, so cancels during initialization are never lost.* @param input The input file.*/public async cancel(input: VertFile): Promise<void> {- throw new Error("Not implemented");+ this.log(`cancelling conversion for file ${input.name} (${input.id})`);+ this.cancelledBeforeStart.add(input.id);}public async valid(): Promise<boolean> {diff --git a/src/lib/converters/ffmpeg/audio/ffmpeg.audio.svelte.ts b/src/lib/converters/ffmpeg/audio/ffmpeg.audio.svelte.tsindex fcf229f..3c7725b 100644--- a/src/lib/converters/ffmpeg/audio/ffmpeg.audio.svelte.ts+++ b/src/lib/converters/ffmpeg/audio/ffmpeg.audio.svelte.ts@@ -192,11 +192,11 @@ export class FFmpegConverter extends BaseFFmpegConverter {await this.ensureCore();+ this.throwIfCancelled(input);+let conversionError: string | null = null;const ffmpeg = await this.setupFFmpeg(input);- this.activeConversions.set(input.id, ffmpeg);-// listen for errors during conversionconst errorListener = (l: { message: string }) => {const msg = l.message;@@ -294,6 +294,7 @@ export class FFmpegConverter extends BaseFFmpegConverter {}} finally {this.clearTrackedConversion(input);+ this.clearCancel(input);ffmpeg.off("log", errorListener);ffmpeg.off("log", logListener);this.activeConversions.delete(input.id);diff --git a/src/lib/converters/ffmpeg/ffmpeg.base.svelte.ts b/src/lib/converters/ffmpeg/ffmpeg.base.svelte.tsindex c7710e3..37020d7 100644--- a/src/lib/converters/ffmpeg/ffmpeg.base.svelte.ts+++ b/src/lib/converters/ffmpeg/ffmpeg.base.svelte.ts@@ -36,6 +36,8 @@ export abstract class BaseFFmpegConverter extends Converter {protected activeConversions = new SvelteMap<string, FFmpeg>();+ private cancelLoad = new SvelteMap<string, () => void>();+public getVariantLabel(): string | null {const variant = EngineVariants.instance.ffmpegActive;return variant === "mt"@@ -130,21 +132,41 @@ export abstract class BaseFFmpegConverter extends Converter {input.progress = progress.progress * 100;});- await ffmpeg.load(this.loadConfig());+ this.activeConversions.set(input.id, ffmpeg);++ let abortLoad!: () => void;+ const aborted = new Promise<never>((_, reject) => {+ abortLoad = () => reject(new Error("Conversion cancelled"));+ });+ this.cancelLoad.set(input.id, abortLoad);++ try {+ await Promise.race([ffmpeg.load(this.loadConfig()), aborted]);+ if (this.isCancelled(input))+ throw new Error("Conversion cancelled");+ } catch (err) {+ // don't leave a half-loaded instance registered+ if (this.activeConversions.get(input.id) === ffmpeg) {+ // we throw before the caller's try/finally, so clear the marker here+ this.activeConversions.delete(input.id);+ }+ this.clearCancel(input);+ ffmpeg.terminate();+ throw err;+ } finally {+ this.cancelLoad.delete(input.id);+ }return ffmpeg;}public async cancel(input: VertFile): Promise<void> {- const ffmpeg = this.activeConversions.get(input.id);- if (!ffmpeg) {- this.error(- `no active conversion found for file ${input.name} (${input.id})`,- );- return;- }+ await super.cancel(input);- this.log(`cancelling conversion for file ${input.name} (${input.id})`);+ this.cancelLoad.get(input.id)?.();++ const ffmpeg = this.activeConversions.get(input.id);+ if (!ffmpeg) return;ffmpeg.terminate();this.activeConversions.delete(input.id);diff --git a/src/lib/converters/ffmpeg/video/ffmpeg.video.svelte.ts b/src/lib/converters/ffmpeg/video/ffmpeg.video.svelte.tsindex b8b67b5..ce28cc6 100644--- a/src/lib/converters/ffmpeg/video/ffmpeg.video.svelte.ts+++ b/src/lib/converters/ffmpeg/video/ffmpeg.video.svelte.ts@@ -246,9 +246,10 @@ export class FFmpegVideoConverter extends BaseFFmpegConverter {await this.ensureCore();+ this.throwIfCancelled(input);+let conversionError: string | null = null;const ffmpeg = await this.setupFFmpeg(input);- this.activeConversions.set(input.id, ffmpeg);const errorListener = (l: { message: string }) => {const msg = l.message;@@ -315,6 +316,7 @@ export class FFmpegVideoConverter extends BaseFFmpegConverter {return new VertFile(new File([outBuf], outputFileName), to);} finally {this.clearTrackedConversion(input);+ this.clearCancel(input);ffmpeg.off("log", errorListener);ffmpeg.off("log", logListener);this.activeConversions.delete(input.id);diff --git a/src/lib/converters/index.ts b/src/lib/converters/index.tsindex f0afdf8..8ffff71 100644--- a/src/lib/converters/index.ts+++ b/src/lib/converters/index.ts@@ -99,15 +99,14 @@ categories.doc.formats =.map((f) => f.name) || [];export const byNative = (format: string) => {- return (a: Converter, b: Converter) => {- const aFormat = a.supportedFormats.find((f) => f.name === format);- const bFormat = b.supportedFormats.find((f) => f.name === format);-- if (aFormat && bFormat) {- return aFormat.isNative ? -1 : 1;- }- return 0;+ // rank native support first, then non-native, then unsupported.+ const rank = (converter: Converter) => {+ const info = converter.supportedFormats.find((f) => f.name === format);+ if (!info) return 2;+ return info.isNative ? 0 : 1;};++ return (a: Converter, b: Converter) => rank(a) - rank(b);};export function categoryStatus(category: ConverterCategory): WorkerStatus {diff --git a/src/lib/converters/magick/magick.svelte.ts b/src/lib/converters/magick/magick.svelte.tsindex 63919c7..d777da9 100644--- a/src/lib/converters/magick/magick.svelte.ts+++ b/src/lib/converters/magick/magick.svelte.ts@@ -323,6 +323,8 @@ export class MagickConverter extends Converter {if (EngineVariants.instance.magickActive !== this.loadedVariant)await this.download();+ this.throwIfCancelled(input);+this.trackConversion(input);this.log(`converting ${input.name} (${input.id}) to ${to}`);const startedAt = performance.now();@@ -410,21 +412,17 @@ export class MagickConverter extends Converter {cancellation.abort();this.workerCancellation.delete(worker);this.clearTrackedConversion(input);+ this.clearCancel(input);this.activeConversions.delete(input.id);worker.terminate();}}public async cancel(input: VertFile): Promise<void> {- const worker = this.activeConversions.get(input.id);- if (!worker) {- this.error(- `no active conversion found for file ${input.name} (${input.id})`,- );- return;- }+ await super.cancel(input);- this.log(`cancelling conversion for file ${input.name} (${input.id})`);+ const worker = this.activeConversions.get(input.id);+ if (!worker) return;this.workerCancellation.get(worker)?.abort();worker.terminate();diff --git a/src/lib/converters/mediabunny/mediabunny.svelte.ts b/src/lib/converters/mediabunny/mediabunny.svelte.tsindex 3506569..9ba0b68 100644--- a/src/lib/converters/mediabunny/mediabunny.svelte.ts+++ b/src/lib/converters/mediabunny/mediabunny.svelte.ts@@ -357,6 +357,8 @@ export class MediabunnyConverter extends Converter {const originalName = file.file.name.split(".").slice(0, -1).join(".");const outputFilename = `${originalName}.${toFormat}`;+ this.throwIfCancelled(file);+let streamTargetContext: Awaited<ReturnType<typeof this.createStreamingTarget>> = null;@@ -402,6 +404,7 @@ export class MediabunnyConverter extends Converter {});this.activeConversions.set(file.id, conversion);+ this.throwIfCancelled(file);const mobile = get(isMobile);const deviceMemory = (@@ -487,6 +490,7 @@ export class MediabunnyConverter extends Converter {return new VertFile(f, toFormat);} finally {this.clearTrackedConversion(file);+ this.clearCancel(file);if (slowConversionTimer) clearTimeout(slowConversionTimer);this.activeConversions.delete(file.id);try {@@ -535,15 +539,10 @@ export class MediabunnyConverter extends Converter {}public async cancel(input: VertFile): Promise<void> {- const conversion = this.activeConversions.get(input.id);- if (!conversion) {- this.error(- `no active conversion found for file ${input.name} (${input.id})`,- );- return;- }+ await super.cancel(input);- this.log(`cancelling conversion for file ${input.name} (${input.id})`);+ const conversion = this.activeConversions.get(input.id);+ if (!conversion) return;await conversion.cancel();}diff --git a/src/lib/converters/pandoc/pandoc.svelte.ts b/src/lib/converters/pandoc/pandoc.svelte.tsindex 02dddab..bb959b6 100644--- a/src/lib/converters/pandoc/pandoc.svelte.ts+++ b/src/lib/converters/pandoc/pandoc.svelte.ts@@ -42,6 +42,8 @@ export class PandocConverter extends Converter {public async convert(file: VertFile, to: string): Promise<VertFile> {await this.init();+ this.throwIfCancelled(file);+this.trackConversion(file);this.log(`converting ${file.name} (${file.id}) to ${to}`);const startedAt = performance.now();@@ -121,21 +123,17 @@ export class PandocConverter extends Converter {cancellation.abort();this.workerCancellation.delete(worker);this.clearTrackedConversion(file);+ this.clearCancel(file);this.activeConversions.delete(file.id);worker.terminate();}}public async cancel(input: VertFile): Promise<void> {- const worker = this.activeConversions.get(input.id);- if (!worker) {- this.error(- `no active conversion found for file ${input.name} (${input.id})`,- );- return;- }+ await super.cancel(input);- this.log(`cancelling conversion for file ${input.name} (${input.id})`);+ const worker = this.activeConversions.get(input.id);+ if (!worker) return;this.workerCancellation.get(worker)?.abort();worker.terminate();@@ -148,8 +146,8 @@ export class PandocConverter extends Converter {new FormatInfo("md", true, true),new FormatInfo("html", true, true),new FormatInfo("rtf", true, false),- new FormatInfo("csv", true, true),- new FormatInfo("tsv", true, true),+ new FormatInfo("csv", true, false),+ new FormatInfo("tsv", true, false),new FormatInfo("json", true, true), // must be a pandoc-converted jsonnew FormatInfo("rst", true, true),new FormatInfo("epub", true, true),diff --git a/src/lib/converters/spessasynth/spessasynth.svelte.ts b/src/lib/converters/spessasynth/spessasynth.svelte.tsindex f355048..468ed07 100644--- a/src/lib/converters/spessasynth/spessasynth.svelte.ts+++ b/src/lib/converters/spessasynth/spessasynth.svelte.ts@@ -69,6 +69,8 @@ export class SpessaSynthConverter extends Converter {): Promise<VertFile> {await this.init();+ this.throwIfCancelled(input);+this.trackConversion(input);this.log(`converting ${input.name} (${input.id}) to ${to}`);const startedAt = performance.now();@@ -118,15 +120,17 @@ export class SpessaSynthConverter extends Converter {throw err;} finally {this.clearTrackedConversion(input);+ this.clearCancel(input);this.activeConversions.delete(input.id);worker.terminate();}}public async cancel(input: VertFile): Promise<void> {+ await super.cancel(input);+const worker = this.activeConversions.get(input.id);if (!worker) return;- this.log(`cancelling conversion for file ${input.name} (${input.id})`);worker.terminate();this.activeConversions.delete(input.id);}diff --git a/src/lib/converters/vectorizer/vectorizer.svelte.ts b/src/lib/converters/vectorizer/vectorizer.svelte.tsindex 368c925..0ab9eed 100644--- a/src/lib/converters/vectorizer/vectorizer.svelte.ts+++ b/src/lib/converters/vectorizer/vectorizer.svelte.ts@@ -18,6 +18,8 @@ export class VectorizerConverter extends Converter {private activeConversions = new SvelteMap<string, Worker>();+ private workerCancellation = new SvelteMap<Worker, AbortController>();+public supportedFormats = vectorizerFormats;public readonly reportsProgress = false;@@ -42,7 +44,7 @@ export class VectorizerConverter extends Converter {protected async download(): Promise<void> {const worker = new Worker(VectorizerWorker, { type: "module" });try {- await this.waitForMessage(worker, "loaded", 60000, () => {+ await this.waitForMessage(worker, "loaded", 60000, undefined, () => {worker.postMessage({ type: "load", id: "init" });});@@ -104,6 +106,8 @@ export class VectorizerConverter extends Converter {): Promise<VertFile> {await this.init();+ this.throwIfCancelled(input);+this.trackConversion(input);this.log(`converting ${input.name} (${input.id}) to ${to}`);const startedAt = performance.now();@@ -115,10 +119,17 @@ export class VectorizerConverter extends Converter {const worker = new Worker(VectorizerWorker, { type: "module" });this.activeConversions.set(input.id, worker);+ const cancellation = new AbortController();+ this.workerCancellation.set(worker, cancellation);try {worker.postMessage({ type: "load", id: input.id });- await this.waitForMessage(worker, "loaded", 60000);+ await this.waitForMessage(+ worker,+ "loaded",+ 60000,+ cancellation.signal,+ );const convertMsg: WorkerMessage = {type: "convert",@@ -134,7 +145,12 @@ export class VectorizerConverter extends Converter {};worker.postMessage(convertMsg);- const res = await this.waitForMessage(worker);+ const res = await this.waitForMessage(+ worker,+ undefined,+ 0,+ cancellation.signal,+ );if (res.type === "finished") {this.log(`converted ${input.name} (${input.id}) to ${to} in ${formatDuration(performance.now() - startedAt)}`,@@ -149,23 +165,22 @@ export class VectorizerConverter extends Converter {throw new Error("Unknown message type");} finally {+ cancellation.abort();+ this.workerCancellation.delete(worker);this.clearTrackedConversion(input);+ this.clearCancel(input);this.activeConversions.delete(input.id);worker.terminate();}}public async cancel(input: VertFile): Promise<void> {- const worker = this.activeConversions.get(input.id);- if (!worker) {- this.error(- `no active conversion found for file ${input.name} (${input.id})`,- );- return;- }+ await super.cancel(input);- this.log(`cancelling conversion for file ${input.name} (${input.id})`);+ const worker = this.activeConversions.get(input.id);+ if (!worker) return;+ this.workerCancellation.get(worker)?.abort();worker.terminate();this.activeConversions.delete(input.id);}@@ -174,6 +189,7 @@ export class VectorizerConverter extends Converter {worker: Worker,type?: string,timeout?: number,+ signal?: AbortSignal,post?: () => void,): Promise<T> {return new Promise<T>((resolve, reject) => {@@ -195,9 +211,15 @@ export class VectorizerConverter extends Converter {reject(new Error(`Worker error: ${e.message}`));};+ const onAbort = () => {+ cleanup();+ reject(new Error("Conversion cancelled"));+ };+const cleanup = () => {worker.removeEventListener("message", onMessage);worker.removeEventListener("error", onError);+ signal?.removeEventListener("abort", onAbort);if (timeoutId) clearTimeout(timeoutId);};@@ -212,8 +234,11 @@ export class VectorizerConverter extends Converter {}, timeout): undefined;+ if (signal?.aborted) return onAbort();+worker.addEventListener("message", onMessage);worker.addEventListener("error", onError);+ signal?.addEventListener("abort", onAbort);post?.();});diff --git a/src/lib/converters/vertd/vertd.svelte.ts b/src/lib/converters/vertd/vertd.svelte.tsindex 95320b8..7d5e337 100644--- a/src/lib/converters/vertd/vertd.svelte.ts+++ b/src/lib/converters/vertd/vertd.svelte.ts@@ -673,7 +673,6 @@ export class VertdConverter extends Converter {let hash: string;if (PUB_DISABLE_FAILURE_BLOCKS === "false") {hash = await fileUpload.hash();-if (this.blocked(hash)) {this.log(`conversion blocked for file ${input.name} (${input.id})`,@@ -693,6 +692,12 @@ export class VertdConverter extends Converter {);this.activeUploads.set(input.id, uploadTask);+ // cover a cancel that arrived during url resolution / upload setup+ if (this.isCancelled(input)) {+ this.clearCancel(input);+ throw new Error("Conversion cancelled");+ }+let uploadRes: UploadResponse;try {uploadRes = await uploadTask.promise;@@ -705,8 +710,10 @@ export class VertdConverter extends Converter {`received sequence upload for ${input.name} (${input.id}) (kind: ${uploadRes.sequence.kind}, extension: ${uploadRes.sequence.extension}, entry: ${uploadRes.sequence.entry})`,);- if (this.cancelledConversions.has(input.id))+ if (this.cancelledConversions.has(input.id)) {+ this.clearCancel(input);throw new Error("Conversion cancelled");+ }return new Promise((resolve, reject) => {let settled = false;@@ -728,6 +735,7 @@ export class VertdConverter extends Converter {settled = true;clearTimeout(connectTimeout);this.cancelledConversions.delete(input.id);+ this.clearCancel(input);this.activeUploads.delete(input.id);this.activeDownloads.get(input.id)?.abort();this.activeDownloads.delete(input.id);@@ -746,6 +754,7 @@ export class VertdConverter extends Converter {settled = true;clearTimeout(connectTimeout);this.cancelledConversions.delete(input.id);+ this.clearCancel(input);this.activeUploads.delete(input.id);this.activeDownloads.delete(input.id);this.activeConversions.delete(input.id);@@ -936,6 +945,8 @@ export class VertdConverter extends Converter {}public async cancel(input: VertFile): Promise<void> {+ await super.cancel(input);+this.cancelledConversions.add(input.id);const activeUpload = this.activeUploads.get(input.id);@@ -963,8 +974,6 @@ export class VertdConverter extends Converter {return;}- this.log(`cancelling conversion for file ${input.name} (${input.id})`);-const { ws, jobId, token } = activeConversion;if (ws.readyState === WebSocket.OPEN) {diff --git a/src/lib/converters/vips/vips.svelte.ts b/src/lib/converters/vips/vips.svelte.tsindex 75a7324..d860cf7 100644--- a/src/lib/converters/vips/vips.svelte.ts+++ b/src/lib/converters/vips/vips.svelte.ts@@ -22,6 +22,8 @@ export class VipsConverter extends Converter {private activeConversions = new SvelteMap<string, Worker>();+ private workerCancellation = new SvelteMap<Worker, AbortController>();+public supportedFormats = vipsFormats;public readonly reportsProgress = false;@@ -46,7 +48,7 @@ export class VipsConverter extends Converter {protected async download(): Promise<void> {const worker = new Worker(VipsWorker, { type: "module" });try {- await this.waitForMessage(worker, "loaded", 60000, () => {+ await this.waitForMessage(worker, "loaded", 60000, undefined, () => {worker.postMessage({ type: "load", id: "init" });});@@ -143,6 +145,8 @@ export class VipsConverter extends Converter {): Promise<VertFile> {await this.init();+ this.throwIfCancelled(input);+this.trackConversion(input);this.log(`converting ${input.name} (${input.id}) to ${to}`);const startedAt = performance.now();@@ -154,10 +158,17 @@ export class VipsConverter extends Converter {const worker = new Worker(VipsWorker, { type: "module" });this.activeConversions.set(input.id, worker);+ const cancellation = new AbortController();+ this.workerCancellation.set(worker, cancellation);- try {+ try {worker.postMessage({ type: "load", id: input.id });- await this.waitForMessage(worker, "loaded", 60000);+ await this.waitForMessage(+ worker,+ "loaded",+ 60000,+ cancellation.signal,+ );const convertMsg: WorkerMessage = {type: "convert",@@ -173,7 +184,12 @@ export class VipsConverter extends Converter {};worker.postMessage(convertMsg);- const res = await this.waitForMessage(worker);+ const res = await this.waitForMessage(+ worker,+ undefined,+ 0,+ cancellation.signal,+ );if (res.type === "finished") {this.log(`converted ${input.name} (${input.id}) to ${to} in ${formatDuration(performance.now() - startedAt)}`,@@ -188,23 +204,22 @@ export class VipsConverter extends Converter {throw new Error("Unknown message type");} finally {+ cancellation.abort();+ this.workerCancellation.delete(worker);this.clearTrackedConversion(input);+ this.clearCancel(input);this.activeConversions.delete(input.id);worker.terminate();}}public async cancel(input: VertFile): Promise<void> {- const worker = this.activeConversions.get(input.id);- if (!worker) {- this.error(- `no active conversion found for file ${input.name} (${input.id})`,- );- return;- }+ await super.cancel(input);- this.log(`cancelling conversion for file ${input.name} (${input.id})`);+ const worker = this.activeConversions.get(input.id);+ if (!worker) return;+ this.workerCancellation.get(worker)?.abort();worker.terminate();this.activeConversions.delete(input.id);}@@ -213,6 +228,7 @@ export class VipsConverter extends Converter {worker: Worker,type?: string,timeout?: number,+ signal?: AbortSignal,post?: () => void,): Promise<T> {return new Promise<T>((resolve, reject) => {@@ -234,9 +250,15 @@ export class VipsConverter extends Converter {reject(new Error(`Worker error: ${e.message}`));};+ const onAbort = () => {+ cleanup();+ reject(new Error("Conversion cancelled"));+ };+const cleanup = () => {worker.removeEventListener("message", onMessage);worker.removeEventListener("error", onError);+ signal?.removeEventListener("abort", onAbort);if (timeoutId) clearTimeout(timeoutId);};@@ -249,8 +271,11 @@ export class VipsConverter extends Converter {}, timeout): undefined;+ if (signal?.aborted) return onAbort();+worker.addEventListener("message", onMessage);worker.addEventListener("error", onError);+ signal?.addEventListener("abort", onAbort);post?.();});diff --git a/src/lib/store/index.svelte.ts b/src/lib/store/index.svelte.tsindex 537f740..d713668 100644--- a/src/lib/store/index.svelte.ts+++ b/src/lib/store/index.svelte.ts@@ -334,7 +334,7 @@ class Files {continue;}- const converter = converters+ const converter = [...converters].sort(byNative(format)).find((c) => c.formatStrings().includes(format));@@ -501,7 +501,7 @@ class Files {log(["files"], `no extension found for ${file.name}`);return;}- const converter = converters+ const converter = [...converters].sort(byNative(format)).find((converter) =>converter.formatStrings().includes(format),diff --git a/src/lib/types/file.svelte.ts b/src/lib/types/file.svelte.tsindex 8f5ae37..82710f9 100644--- a/src/lib/types/file.svelte.ts+++ b/src/lib/types/file.svelte.ts@@ -324,7 +324,7 @@ export class VertFile {if (!this.fileType) return;- const forceKeep = ["mpo", "fb2"];+ const forceKeep = ["mpo", "fb2", "opml", "jats"];const aliases: Record<string, string> = {// original: aliasjpg: "jpeg",