Skip to content

armgit / VERT

Public Imported from GitHub
0

The next-generation file converter. Open source, fully local* and free forever.

fix: properly clean up mediabunny OPFS files

JovannMCa242f96f01a6
diff --git a/src/lib/components/functional/ConversionPanel.svelte b/src/lib/components/functional/ConversionPanel.svelte
index 8b283b1..21100d8 100644
--- a/src/lib/components/functional/ConversionPanel.svelte
+++ b/src/lib/components/functional/ConversionPanel.svelte
@@ -76,7 +76,7 @@
? ''
: '!scale-100'} flex gap-3 max-md:w-full"
disabled={files.files.length === 0}
- onclick={() => (files.files = [])}
+ onclick={() => files.removeAll()}
>
<Trash2Icon size="24" />
<p>{m["convert.panel.remove_all"]()}</p>
@@ -91,7 +91,7 @@
? ''
: '!scale-100'} flex gap-3 max-md:w-full"
disabled={files.files.length === 0}
- onclick={() => (files.files = [])}
+ onclick={() => files.removeAll()}
>
<Trash2Icon size="24" />
</button>
diff --git a/src/lib/components/functional/FormatDropdown.svelte b/src/lib/components/functional/FormatDropdown.svelte
index 8777b3a..3b6a877 100644
--- a/src/lib/components/functional/FormatDropdown.svelte
+++ b/src/lib/components/functional/FormatDropdown.svelte
@@ -448,7 +448,7 @@
})
.filter(Boolean);
- files.files = files.files.filter((f) => f !== file);
+ await files.remove(file);
newFiles.forEach((f) => files.add(f));
};
diff --git a/src/lib/converters/mediabunny/mediabunny.svelte.ts b/src/lib/converters/mediabunny/mediabunny.svelte.ts
index 8e2ed52..05137d0 100644
--- a/src/lib/converters/mediabunny/mediabunny.svelte.ts
+++ b/src/lib/converters/mediabunny/mediabunny.svelte.ts
@@ -170,7 +170,6 @@ export class MediabunnyConverter extends Converter {
public reportsProgress: boolean = true;
private activeConversions = new Map<string, Conversion>();
- private pendingOutputCleanups = new Map<string, () => Promise<void>>();
private formats: string[] = [
"mp4",
@@ -396,139 +395,155 @@ export class MediabunnyConverter extends Converter {
const originalName = file.file.name.split(".").slice(0, -1).join(".");
const outputFilename = `${originalName}.${toFormat}`;
- const input = new Input({
- formats: [MP4, QTFF, MATROSKA, WEBM, MPEG_TS],
- source: new BlobSource(file.file),
- });
-
- const streamTargetContext =
- await this.createStreamingTarget(outputFilename);
- if (streamTargetContext) {
- this.log(`using OPFS stream target for ${file.name}`);
- this.pendingOutputCleanups.set(
- file.id,
- streamTargetContext.cleanup,
- );
- }
-
- const target = streamTargetContext?.target ?? new BufferTarget();
-
- const output = new Output({
- format: this.format(to),
- target,
- });
-
- const conversionSettings =
- Object.keys(settings).length > 4
- ? settings
- : Object.assign(settings, await this.getDefaultSettings(file)); // use defaults if not provided
-
- const videoConfig = buildVideoConfig(conversionSettings);
- const audioConfig = buildAudioConfig(conversionSettings);
-
- const conversion = await Conversion.init({
- input,
- output,
- video: videoConfig,
- audio: audioConfig,
- ...(conversionSettings.metadata === "false" ? { tags: {} } : {}),
- });
-
- this.activeConversions.set(file.id, conversion);
-
- const mobile = get(isMobile);
- const deviceMemory = (
- navigator as Navigator & { deviceMemory?: number }
- ).deviceMemory;
- const hardwareConcurrency = navigator.hardwareConcurrency || 3; // if we can't detect it, just fall back to something that will definitely warn
- const likelySlowDevice =
- (mobile && hardwareConcurrency <= 4) ||
- hardwareConcurrency <= 4 ||
- (deviceMemory !== undefined && deviceMemory <= 4);
- if (likelySlowDevice) void file.slowConversionOffer("device");
- this.log(`hardwareConcurrency: ${hardwareConcurrency}`);
- this.log(`deviceMemory: ${deviceMemory}`);
- this.log(`mobile: ${mobile}`);
-
- const slowConversionTimer: ReturnType<typeof setTimeout> = setTimeout(
- () => {
- void file.slowConversionOffer("timeout");
- },
- 60 * 1000,
- );
+ let streamTargetContext: Awaited<
+ ReturnType<typeof this.createStreamingTarget>
+ > = null;
+ let input: Input | undefined;
+ let output: Output | undefined;
+ let slowConversionTimer: ReturnType<typeof setTimeout> | undefined;
+ let retained = false;
+ try {
+ input = new Input({
+ formats: [MP4, QTFF, MATROSKA, WEBM, MPEG_TS],
+ source: new BlobSource(file.file),
+ });
+ streamTargetContext =
+ await this.createStreamingTarget(outputFilename);
+ if (streamTargetContext) {
+ this.log(`using OPFS stream target for ${file.name}`);
+ }
- this.log(`videoConfig: ${JSON.stringify(videoConfig)}`);
- this.log(`audioConfig: ${JSON.stringify(audioConfig)}`);
+ const target = streamTargetContext?.target ?? new BufferTarget();
- // log any discarded tracks & its reasons
- const discardedTracks = conversion.discardedTracks;
- if (discardedTracks.length > 0) {
- const discardedTrackCount = discardedTracks.length;
- const discardedTrackList = discardedTracks.map(
- (discarded, index) =>
- `${index + 1}. ${discarded.track.type} (${discarded.track.getCodec()}) - ${discarded.reason}`,
- );
+ output = new Output({
+ format: this.format(to),
+ target,
+ });
- const isValid = conversion.isValid;
- const logMethod = isValid ? this.error : this.log;
- logMethod(
- `${discardedTrackCount} discarded track(s) for ${file.name}:\n${discardedTrackList.join("\n")}`,
- );
- ToastManager.add({
- type: isValid ? "warning" : "error", // warning if output created, error if nothing / conversion was completely invalid
- message: m["workers.errors.mediabunny.discarded"]({
- count: discardedTrackCount,
- file: file.name,
- }),
- durations: {
- stay: 10000,
- },
+ const conversionSettings =
+ Object.keys(settings).length > 4
+ ? settings
+ : Object.assign(
+ settings,
+ await this.getDefaultSettings(file),
+ ); // use defaults if not provided
+
+ const videoConfig = buildVideoConfig(conversionSettings);
+ const audioConfig = buildAudioConfig(conversionSettings);
+
+ const conversion = await Conversion.init({
+ input,
+ output,
+ video: videoConfig,
+ audio: audioConfig,
+ ...(conversionSettings.metadata === "false"
+ ? { tags: {} }
+ : {}),
});
- if (!isValid) {
- this.activeConversions.delete(file.id);
- throw new Error(
- `Mediabunny cannot produce an output for ${file.name} due to unsupported tracks/codecs.`,
+ this.activeConversions.set(file.id, conversion);
+
+ const mobile = get(isMobile);
+ const deviceMemory = (
+ navigator as Navigator & { deviceMemory?: number }
+ ).deviceMemory;
+ const hardwareConcurrency = navigator.hardwareConcurrency || 3; // if we can't detect it, just fall back to something that will definitely warn
+ const likelySlowDevice =
+ (mobile && hardwareConcurrency <= 4) ||
+ hardwareConcurrency <= 4 ||
+ (deviceMemory !== undefined && deviceMemory <= 4);
+ if (likelySlowDevice) void file.slowConversionOffer("device");
+ this.log(`hardwareConcurrency: ${hardwareConcurrency}`);
+ this.log(`deviceMemory: ${deviceMemory}`);
+ this.log(`mobile: ${mobile}`);
+
+ slowConversionTimer = setTimeout(() => {
+ void file.slowConversionOffer("timeout");
+ }, 60 * 1000);
+
+ this.log(`videoConfig: ${JSON.stringify(videoConfig)}`);
+ this.log(`audioConfig: ${JSON.stringify(audioConfig)}`);
+
+ // log any discarded tracks & its reasons
+ const discardedTracks = conversion.discardedTracks;
+ if (discardedTracks.length > 0) {
+ const discardedTrackCount = discardedTracks.length;
+ const discardedTrackList = discardedTracks.map(
+ (discarded, index) =>
+ `${index + 1}. ${discarded.track.type} (${discarded.track.getCodec()}) - ${discarded.reason}`,
+ );
+
+ const isValid = conversion.isValid;
+ const logMethod = isValid ? this.error : this.log;
+ logMethod(
+ `${discardedTrackCount} discarded track(s) for ${file.name}:\n${discardedTrackList.join("\n")}`,
);
+ ToastManager.add({
+ type: isValid ? "warning" : "error", // warning if output created, error if nothing / conversion was completely invalid
+ message: m["workers.errors.mediabunny.discarded"]({
+ count: discardedTrackCount,
+ file: file.name,
+ }),
+ durations: {
+ stay: 10000,
+ },
+ });
+
+ if (!isValid) {
+ throw new Error(
+ `Mediabunny cannot produce an output for ${file.name} due to unsupported tracks/codecs.`,
+ );
+ }
}
- }
- conversion.onProgress = (progress) => {
- file.progress = progress * 100;
- };
+ conversion.onProgress = (progress) => {
+ file.progress = progress * 100;
+ };
- try {
await conversion.execute();
- } catch (err) {
- const cleanup = this.pendingOutputCleanups.get(file.id);
- if (cleanup) {
- await cleanup();
- this.pendingOutputCleanups.delete(file.id);
+
+ if (streamTargetContext) {
+ const streamedFile = await streamTargetContext.getFile();
+ const result = new VertFile(streamedFile, toFormat);
+ result.setPostDownload(streamTargetContext.cleanup);
+ retained = true;
+ return result;
+ }
+
+ if (!(target instanceof BufferTarget) || !target.buffer) {
+ throw new Error(
+ "Mediabunny conversion failed: no output buffer",
+ );
}
- throw err;
+
+ const f = new File([target.buffer], `${originalName}.${toFormat}`, {
+ type: "application/octet-stream",
+ });
+
+ return new VertFile(f, toFormat);
} finally {
this.clearTrackedConversion(file);
if (slowConversionTimer) clearTimeout(slowConversionTimer);
this.activeConversions.delete(file.id);
+ try {
+ if (output && output.state !== "finalized")
+ await output.cancel();
+ } catch (err) {
+ this.error(`Failed to cancel Mediabunny output: ${err}`);
+ }
+ try {
+ input?.dispose();
+ } catch (err) {
+ this.error(`Failed to dispose Mediabunny input: ${err}`);
+ }
+ if (!retained && streamTargetContext) {
+ try {
+ await streamTargetContext.cleanup();
+ } catch (err) {
+ this.error(`Failed to clean up OPFS output: ${err}`);
+ }
+ }
}
-
- if (streamTargetContext) {
- const streamedFile = await streamTargetContext.getFile();
- const result = new VertFile(streamedFile, toFormat);
- result.setPostDownload(streamTargetContext.cleanup);
- this.pendingOutputCleanups.delete(file.id);
- return result;
- }
-
- if (!(target instanceof BufferTarget) || !target.buffer) {
- throw new Error("Mediabunny conversion failed: no output buffer");
- }
-
- const f = new File([target.buffer], `${originalName}.${toFormat}`, {
- type: "application/octet-stream",
- });
-
- return new VertFile(f, toFormat);
}
private format(ext: string) {
@@ -564,14 +579,7 @@ export class MediabunnyConverter extends Converter {
this.log(`cancelling conversion for file ${input.name}`);
- conversion.cancel();
- this.activeConversions.delete(input.id);
-
- const cleanup = this.pendingOutputCleanups.get(input.id);
- if (cleanup) {
- await cleanup();
- this.pendingOutputCleanups.delete(input.id);
- }
+ await conversion.cancel();
}
private async createStreamingTarget(filename: string): Promise<{
@@ -579,6 +587,7 @@ export class MediabunnyConverter extends Converter {
getFile: () => Promise<File>;
cleanup: () => Promise<void>;
} | null> {
+ let cleanup: (() => Promise<void>) | undefined;
try {
const storage = navigator.storage as StorageManager & {
getDirectory?: () => Promise<FileSystemDirectoryHandle>;
@@ -594,17 +603,41 @@ export class MediabunnyConverter extends Converter {
create: true,
});
- const fileStream = await fileHandle.createWritable();
+ // eslint-disable-next-line prefer-const
+ let fileStream: FileSystemWritableFileStream | undefined;
+ let closed = false;
+ cleanup = async () => {
+ try {
+ if (fileStream && !closed) {
+ await fileStream.abort();
+ closed = true;
+ }
+ await tempDir.removeEntry(tempName);
+ } catch (err) {
+ if (
+ err instanceof DOMException &&
+ err.name === "NotFoundError"
+ )
+ return;
+ this.error(
+ `Failed to remove OPFS entry ${tempName}: ${err}`,
+ );
+ throw err;
+ }
+ };
+ fileStream = await fileHandle.createWritable();
const writable = new WritableStream({
- write: (chunk) => fileStream.write(chunk),
- close: () => fileStream.close(),
- abort: (reason) => fileStream.abort(reason),
+ write: (chunk) => fileStream!.write(chunk),
+ close: async () => {
+ await fileStream!.close();
+ closed = true;
+ },
+ abort: async (reason) => {
+ await fileStream!.abort(reason);
+ closed = true;
+ },
});
- const cleanup = async () => {
- await tempDir.removeEntry(tempName).catch(() => {});
- };
-
return {
target: new StreamTarget(writable, {
chunked: true,
@@ -614,6 +647,7 @@ export class MediabunnyConverter extends Converter {
cleanup,
};
} catch (err) {
+ if (cleanup) await cleanup();
this.error(
`failed to initialize OPFS stream target, falling back to BufferTarget: ${err}`,
);
diff --git a/src/lib/store/index.svelte.ts b/src/lib/store/index.svelte.ts
index daad8e0..f273f0a 100644
--- a/src/lib/store/index.svelte.ts
+++ b/src/lib/store/index.svelte.ts
@@ -23,6 +23,16 @@ import { vertdFetch } from "$lib/converters/vertd/vertd.svelte";
class Files {
public files = $state<VertFile[]>([]);
+ public async remove(file: VertFile): Promise<void> {
+ this.files = this.files.filter((entry) => entry !== file);
+ await file.dispose();
+ await file.cancel();
+ }
+
+ public async removeAll(): Promise<void> {
+ await Promise.all([...this.files].map((file) => this.remove(file)));
+ }
+
private getRequiredConverters(file: VertFile): Converter[] {
if (file.isZip()) return file.converters;
diff --git a/src/lib/types/file.svelte.ts b/src/lib/types/file.svelte.ts
index f7dc397..6b30920 100644
--- a/src/lib/types/file.svelte.ts
+++ b/src/lib/types/file.svelte.ts
@@ -125,6 +125,8 @@ export class VertFile {
private attemptedConverters = new Set<string>();
private retryingFallback = false;
private postDownload: (() => Promise<void>) | null = null;
+ private disposal: Promise<void> | null = null;
+ private disposed = false;
private activeConverterName: string | null = null;
private fileTypeMismatchShown = false;
private fileTypeCheck: Promise<void> | null = null;
@@ -157,19 +159,28 @@ export class VertFile {
}
public setPostDownload(cleanup: (() => Promise<void>) | null) {
+ // Legacy name: cleanup runs on disposal, not download; OPFS backs repeated reads.
this.postDownload = cleanup;
}
- private async runPostDownload() {
- if (!this.postDownload) return;
-
- try {
- await this.postDownload();
- } catch (err) {
- log(["file", "cleanup"], `post-download function failed: ${err}`);
- } finally {
- this.postDownload = null;
- }
+ public dispose(): Promise<void> {
+ this.disposed = true;
+ return (this.disposal ??= (async () => {
+ await this.result?.dispose();
+ this.result = null;
+ try {
+ await this.postDownload?.();
+ this.postDownload = null;
+ } catch (err) {
+ log(
+ ["file", "cleanup"],
+ `resource cleanup failed for ${this.name}: ${err}`,
+ );
+ } finally {
+ if (this.blobUrl) URL.revokeObjectURL(this.blobUrl);
+ this.blobUrl = undefined;
+ }
+ })());
}
public getAvailableSettings(
@@ -356,12 +367,11 @@ export class VertFile {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
public async convert(...args: any[]) {
+ if (this.disposed) return;
if (!this.retryingFallback) this.attemptedConverters.clear();
this.cancelled = false;
let res: VertFile | undefined;
try {
- await this.runPostDownload();
-
log(
["file", "convert"],
`Starting conversion for ${this.file.name} from ${this.from} to ${this.to}`,
@@ -451,6 +461,7 @@ export class VertFile {
log(["file", "convert"], `using converter: ${converter.name}`);
+ await this.result?.dispose();
this.result = null;
this.progress = 0;
this.processing = true;
@@ -469,6 +480,10 @@ export class VertFile {
normalizedSettings.settings,
...args,
);
+ if (this.disposed || this.cancelled) {
+ await res.dispose();
+ return;
+ }
this.result = res;
if (this.fallbackToastId !== null) {
ToastManager.remove(this.fallbackToastId);
@@ -479,6 +494,7 @@ export class VertFile {
this.slowConversionToastId = null;
}
} catch (err) {
+ if (this.disposed) return;
if (!this.cancelled) this.toastErr(err);
const compatibleConverters = this.findConverters([
@@ -540,6 +556,7 @@ export class VertFile {
});
}
+ await this.result?.dispose();
this.result = null;
} finally {
this.processing = false;
@@ -570,6 +587,7 @@ export class VertFile {
const totalFiles = entries.length;
const fileProgress: number[] = new Array(totalFiles).fill(0);
const convertedFiles: File[] = [];
+ const convertedResults: VertFile[] = [];
const failedFiles: string[] = [];
const progressFiles = new Map<number, VertFile>();
const progressInterval = setInterval(() => {
@@ -618,6 +636,7 @@ export class VertFile {
settings,
);
+ convertedResults.push(converted);
convertedFiles[index] = converted.file;
fileProgress[index] = 100;
updateProgress();
@@ -632,6 +651,7 @@ export class VertFile {
settings,
);
+ convertedResults.push(converted);
convertedFiles[index] = converted.file;
fileProgress[index] = 100;
@@ -657,48 +677,50 @@ export class VertFile {
}),
),
);
+ // return zip of converted files
+ if (this.cancelled) throw new Error("Conversion cancelled");
+ const outputFiles = convertedFiles.filter(Boolean);
+ const failures = failedFiles.filter(Boolean);
+ let reportName = "failed-files.txt";
+ if (failures.length) {
+ for (
+ let suffix = 1;
+ outputFiles.some((file) => file.name === reportName);
+ suffix++
+ )
+ reportName = `failed-files-${suffix}.txt`;
+ outputFiles.push(
+ new File(
+ [
+ `Failed conversions (${failures.length}):\n\n${failures.join("\n")}\n`,
+ ],
+ reportName,
+ { type: "text/plain" },
+ ),
+ );
+ }
+ const resultArray = await createZip(outputFiles);
+ const outputFilename = this.file.name.replace(/\.[^/.]+$/, ".zip");
+ const resultFile = new File(
+ [new Uint8Array(resultArray)],
+ outputFilename,
+ );
+ if (failures.length)
+ ToastManager.add({
+ type: "warning",
+ message: m["convert.archive_file.conversion_failed"]({
+ filename: outputFilename,
+ count: failures.length,
+ reportName,
+ }),
+ });
+ return new VertFile(resultFile, ".zip");
} finally {
clearInterval(progressInterval);
- }
-
- // return zip of converted files
- if (this.cancelled) throw new Error("Conversion cancelled");
- const outputFiles = convertedFiles.filter(Boolean);
- const failures = failedFiles.filter(Boolean);
- let reportName = "failed-files.txt";
- if (failures.length) {
- for (
- let suffix = 1;
- outputFiles.some((file) => file.name === reportName);
- suffix++
- )
- reportName = `failed-files-${suffix}.txt`;
- outputFiles.push(
- new File(
- [
- `Failed conversions (${failures.length}):\n\n${failures.join("\n")}\n`,
- ],
- reportName,
- { type: "text/plain" },
- ),
+ await Promise.all(
+ convertedResults.map((result) => result.dispose()),
);
}
- const resultArray = await createZip(outputFiles);
- const outputFilename = this.file.name.replace(/\.[^/.]+$/, ".zip");
- const resultFile = new File(
- [new Uint8Array(resultArray)],
- outputFilename,
- );
- if (failures.length)
- ToastManager.add({
- type: "warning",
- message: m["convert.archive_file.conversion_failed"]({
- filename: outputFilename,
- count: failures.length,
- reportName,
- }),
- });
- return new VertFile(resultFile, ".zip");
}
public slowConversionOffer(reason: "device" | "timeout") {
diff --git a/src/lib/util/animation.ts b/src/lib/util/animation.ts
index 27773dc..e5b64d1 100644
--- a/src/lib/util/animation.ts
+++ b/src/lib/util/animation.ts
@@ -41,6 +41,7 @@ export function animateHeight(
let frame = 0;
let releaseTimer = 0;
let settledHeight: number | undefined;
+ // eslint-disable-next-line prefer-const
let resizeObserver: ResizeObserver | undefined;
let mutationObserver: MutationObserver | undefined;
@@ -114,6 +115,7 @@ export function animateHeight(
};
resizeObserver = new ResizeObserver(updateHeight);
+ // eslint-disable-next-line prefer-const
mutationObserver = new MutationObserver(updateHeight);
mutationObserver.observe(node, { childList: true });
updateHeight();
diff --git a/src/routes/convert/+page.svelte b/src/routes/convert/+page.svelte
index 7f4fe80..3c81f2d 100644
--- a/src/routes/convert/+page.svelte
+++ b/src/routes/convert/+page.svelte
@@ -204,7 +204,7 @@
});
</script>
-{#snippet fileItem(file: VertFile, index: number)}
+{#snippet fileItem(file: VertFile)}
{@const currentConverter = getCurrentConverter(file)}
{@const name = currentConverter?.name || "unknown"}
{@const isAudio = converterCategories.audio.includes(name)}
@@ -269,10 +269,7 @@
</div>
<button
class="flex-shrink-0 w-8 rounded-full hover:bg-panel-alt h-full flex items-center justify-center"
- onclick={async () => {
- await file.cancel();
- files.files = files.files.filter((_, i) => i !== index);
- }}
+ onclick={() => files.remove(file)}
>
<XIcon size="24" class="text-muted" />
</button>
@@ -497,7 +494,7 @@
class="w-full h-full col-start-1 row-start-1 md:col-start-2"
/>
{/if}
- {@render fileItem(file, i)}
+ {@render fileItem(file)}
{#if files.files.length < 2}
<Uploader class="w-full h-full" />
{/if}