The next-generation file converter. Open source, fully local* and free forever.
feat: add basic midi / soundfont conversion
JovannMC16158babfec2
diff --git a/bun.lock b/bun.lockindex 7f17434..527e5a6 100644--- a/bun.lock+++ b/bun.lock@@ -38,6 +38,7 @@"qoa-format": "^1.0.1","riff-file": "^1.0.3","sanitize-html": "^2.18.0",+ "spessasynth_core": "^4.3.22","svelte-stripe": "^2.0.0","vert-wasm": "^0.0.2","wasm-feature-detect": "^1.9.0",@@ -847,6 +848,10 @@"source-map-js": ["[email protected]", "", {}, "sha512-KGj/8Y43x35aZVDtt+J4mK1hoLGHULMYfSkODJNQjNDC3oW1PqPoxMwo0pLUsWM/UEGzON/NxeHywEfNXNP3Vw=="],+ "spessasynth_core": ["[email protected]", "", { "dependencies": { "stb-vorbis": "latest" } }, "sha512-qP6NkcZLmTLIs9fCUh2IhZRkd3Junwu8ppD4K0l/0R+Lo4P48d4Rbe8YQ8RlEYyRKFz8HcPM75sXYVQLAb7k4A=="],++ "stb-vorbis": ["[email protected]", "", {}, "sha512-CyvjJEGROIdnuZknwFvdOfMIO1ssUxO2OawsXCR3IlbJ8z2IMBjDe8FDxFJqBfLgf1ZOdqvoHAYx3Xk8q9rbbg=="],+"strtok3": ["[email protected]", "", { "dependencies": { "@tokenizer/token": "^0.3.0" } }, "sha512-MeSp4vHXiZRXM9K0rSWqTvXMU+YzmGICc5+briMVK+RY8qQ1GRTffFYVpK6cSgV/ueImFIEh3uCJJD3xBh1TaQ=="],"sucrase": ["[email protected]", "", { "dependencies": { "@jridgewell/gen-mapping": "^0.3.2", "commander": "^4.0.0", "lines-and-columns": "^1.1.6", "mz": "^2.7.0", "pirates": "^4.0.1", "tinyglobby": "^0.2.11", "ts-interface-checker": "^0.1.9" }, "bin": { "sucrase": "bin/sucrase", "sucrase-node": "bin/sucrase-node" } }, "sha512-DhuTmvZWux4H1UOnWMB3sk0sbaCVOoQZjv8u1rDoTV0HTdGem9hkAZtl4JZy8P2z4Bg0nT+YMeOFyVr4zcG5Tw=="],diff --git a/messages/en.json b/messages/en.jsonindex 71bd668..7cf1f46 100644--- a/messages/en.json+++ b/messages/en.json@@ -525,6 +525,7 @@"vips": "Error in libvips worker, image conversion may not work as expected.","vectorizer": "Error in vectorizer worker, image vectorization may not work as expected.","ffmpeg": "Error loading FFmpeg, some features may not work as expected.",+ "spessasynth": "Error in the MIDI / SoundFont converter, some features may not work as expected.","pandoc": "Error loading Pandoc worker, document conversion may not work as expected.","mediabunny": {"init": "Error loading Mediabunny, video conversion may not work as expected.",diff --git a/package.json b/package.jsonindex f47413f..3a1d264 100644--- a/package.json+++ b/package.json@@ -79,6 +79,7 @@"qoa-format": "^1.0.1","riff-file": "^1.0.3","sanitize-html": "^2.18.0",+ "spessasynth_core": "^4.3.22","svelte-stripe": "^2.0.0","vert-wasm": "^0.0.2","wasm-feature-detect": "^1.9.0",diff --git a/src/lib/converters/index.ts b/src/lib/converters/index.tsindex f696f9c..644e72c 100644--- a/src/lib/converters/index.ts+++ b/src/lib/converters/index.ts@@ -5,6 +5,7 @@ import { FFmpegConverter } from "./ffmpeg/ffmpeg.svelte";import { MagickConverter } from "./magick/magick.svelte";import { MediabunnyConverter } from "./mediabunny/mediabunny.svelte";import { PandocConverter } from "./pandoc/pandoc.svelte";+import { SpessaSynthConverter } from "./spessasynth/spessasynth.svelte";import { VectorizerConverter } from "./vectorizer/vectorizer.svelte";import { VertdConverter } from "./vertd/vertd.svelte";import { VipsConverter } from "./vips/vips.svelte";@@ -16,6 +17,8 @@ const getConverters = (): Converter[] => {new VipsConverter(),new VectorizerConverter(),new FFmpegConverter(),+ new SpessaSynthConverter("midi"),+ new SpessaSynthConverter("soundfont"),new PandocConverter(),new MediabunnyConverter(),];@@ -29,7 +32,7 @@ export const converters = getConverters();export const converterCategories = {image: ["libvips", "imagemagick", "vectorizer"],video: ["mediabunny", "vertd"],- audio: ["ffmpeg"],+ audio: ["ffmpeg", "spessasynth-midi", "spessasynth-soundfont"],doc: ["pandoc"],};@@ -58,11 +61,17 @@ export const categories: Categories = {doc: { formats: [""], canConvertTo: [] },};-categories.audio.formats =- converters- .find((c) => converterCategories.audio.includes(c.name))- ?.supportedFormats.filter((f) => f.toSupported && f.isNative)- .map((f) => f.name) || [];+categories.audio.formats = [+ ...new Set(+ converters+ .filter((c) => converterCategories.audio.includes(c.name))+ .flatMap((c) =>+ c.supportedFormats+ .filter((f) => f.toSupported && f.isNative)+ .map((f) => f.name),+ ),+ ),+];categories.video.formats = [...new Set(convertersdiff --git a/src/lib/converters/spessasynth/spessasynth.svelte.ts b/src/lib/converters/spessasynth/spessasynth.svelte.tsnew file mode 100644index 0000000..fa19242--- /dev/null+++ b/src/lib/converters/spessasynth/spessasynth.svelte.ts@@ -0,0 +1,166 @@+import { m } from "#lib/paraglide/messages";+import { VertFile, type WorkerMessage } from "#lib/types";+import { ToastManager } from "#lib/util/toast.svelte";+import SpessaSynthWorker from "#lib/workers/spessasynth?worker&url";+import { browser } from "$app/env";+import { SvelteMap } from "svelte/reactivity";+import { Converter, FormatInfo, formatDuration } from "../converter.svelte";++// can't convert between MIDI and SoundFonts ofc, so they are "separate converters" but both use the same worker+export type SpessaSynthKind = "midi" | "soundfont";++const MIDI_FORMATS = [+ new FormatInfo("mid", true, true),+ new FormatInfo("midi", true, true),+ new FormatInfo("rmi", true, true), // can only encode when a sound bank is embedded+ new FormatInfo("kar", true, true), // karaoke midi, read as midi+ new FormatInfo("xmf", true, false),+ new FormatInfo("mxmf", true, false),+];++const SOUNDFONT_FORMATS = [+ new FormatInfo("sf2", true, true),+ new FormatInfo("sf3", true, true),+ new FormatInfo("sfogg", true, true),+ new FormatInfo("dls", true, true),+];++export class SpessaSynthConverter extends Converter {+ public name: string;+ public ready = $state(false);+ public supportedFormats: FormatInfo[];++ private activeConversions = new SvelteMap<string, Worker>();++ constructor(kind: SpessaSynthKind) {+ super();+ this.name =+ kind === "midi" ? "spessasynth-midi" : "spessasynth-soundfont";+ this.supportedFormats =+ kind === "midi" ? MIDI_FORMATS : SOUNDFONT_FORMATS;+ if (!browser) return;+ this.log(`created converter`);+ }++ protected async download(): Promise<void> {+ const worker = new Worker(SpessaSynthWorker, { type: "module" });+ try {+ await this.waitForMessage(worker, "ready", 10000);+ this.ready = true;+ this.status = "ready";+ this.log(`spessasynth worker initialised`);+ } catch (err) {+ this.error(`failed to initialise spessasynth worker: ${err}`);+ ToastManager.add({+ type: "error",+ message: m["workers.errors.spessasynth"](),+ });+ throw err;+ } finally {+ worker.terminate();+ }+ }++ public async convert(+ input: VertFile,+ to: string,+ // eslint-disable-next-line @typescript-eslint/no-unused-vars+ _settings: Record<string, unknown>,+ ): Promise<VertFile> {+ await this.init();++ this.trackConversion(input);+ this.log(`converting ${input.name} (${input.id}) to ${to}`);+ const startedAt = performance.now();++ const worker = new Worker(SpessaSynthWorker, { type: "module" });+ this.activeConversions.set(input.id, worker);++ try {+ await this.waitForMessage(worker, "ready", 10000);++ const convertMsg: WorkerMessage = {+ type: "convert",+ id: input.id,+ input: {+ file: input.file,+ name: input.name,+ from: input.from,+ to,+ },+ to,+ conversionSettings: "{}",+ };+ worker.postMessage(convertMsg);++ const res = await this.waitForMessage(worker);+ if (res.type === "finished") {+ this.log(+ `converted ${input.name} (${input.id}) to ${to} in ${formatDuration(performance.now() - startedAt)}`,+ );+ const outputName =+ input.name.split(".").slice(0, -1).join(".") + to;+ return new VertFile(+ new File([res.output as unknown as BlobPart], outputName),+ to,+ );+ }++ if (res.type === "error") throw new Error(res.error);++ throw new Error("Unknown message type");+ } catch (err) {+ this.error(`conversion failed for ${input.name}: ${err}`);+ ToastManager.add({+ type: "error",+ message: m["workers.errors.spessasynth"](),+ });+ throw err;+ } finally {+ this.clearTrackedConversion(input);+ this.activeConversions.delete(input.id);+ worker.terminate();+ }+ }++ public async cancel(input: VertFile): Promise<void> {+ 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);+ }++ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ private waitForMessage(worker: Worker, type?: string, timeout = 0): Promise<any> {+ return new Promise((resolve, reject) => {+ let timer: ReturnType<typeof setTimeout> | undefined;+ const onMessage = (e: MessageEvent) => {+ if (!type || e.data.type === type) {+ cleanup();+ resolve(e.data);+ } else if (e.data.type === "error") {+ cleanup();+ reject(new Error(e.data.error));+ }+ };+ const onError = (e: ErrorEvent) => {+ cleanup();+ reject(new Error(`Worker error: ${e.message}`));+ };+ const cleanup = () => {+ worker.removeEventListener("message", onMessage);+ worker.removeEventListener("error", onError);+ if (timer) clearTimeout(timer);+ };++ worker.addEventListener("message", onMessage);+ worker.addEventListener("error", onError);+ if (timeout)+ timer = setTimeout(() => {+ cleanup();+ reject(new Error(`Worker timeout after ${timeout}ms`));+ }, timeout);+ });+ }+}diff --git a/src/lib/store/index.svelte.ts b/src/lib/store/index.svelte.tsindex e9cf2c8..194a3bc 100644--- a/src/lib/store/index.svelte.ts+++ b/src/lib/store/index.svelte.ts@@ -168,11 +168,15 @@ class Files {private _addThumbnail = async (file: VertFile) => {this.thumbnailQueue.add(async () => {+ // for now only ffmpeg are "real" audio files that music-metadata can readconst isAudio = converters- .find((c) => converterCategories.audio.includes(c.name))- ?.supportedFormats.filter((f) => f.isNative)- .map((f) => f.name)- ?.includes(file.from.toLowerCase());+ .filter((c) => c.name === "ffmpeg")+ .flatMap((c) =>+ c.supportedFormats+ .filter((f) => f.isNative)+ .map((f) => f.name),+ )+ .includes(file.from.toLowerCase());const isVideo = converters.find((c) => converterCategories.video.includes(c.name))?.supportedFormats.filter((f) => f.isNative)@@ -509,9 +513,13 @@ class Files {const category = Object.keys(categories).find((name) =>categories[name].formats.includes(format),);- const to = category- ? categories[category].formats.find((f) => f !== format)- : converter.formatStrings().find((f) => f !== format);+ // first format (in category order) the file can actually convert to+ const candidates = category+ ? categories[category].formats+ : converter.formatStrings();+ const to = candidates.find(+ (f) => f !== format && input.hasAvailableConverter(format, f),+ );if (!to) {log(["files"], `no output format found for ${file.name}`);return;diff --git a/src/lib/types/file.svelte.ts b/src/lib/types/file.svelte.tsindex 8e74587..e061031 100644--- a/src/lib/types/file.svelte.ts+++ b/src/lib/types/file.svelte.ts@@ -336,6 +336,7 @@ export class VertFile {mpg: "mpeg",mpe: "mpeg",mpv: "mpeg",+ midi: "mid",};const fileExtension = this.originalFrom.slice(1);const isPngContainer =diff --git a/src/lib/util/debug.svelte.ts b/src/lib/util/debug.svelte.tsindex 3ba0143..ef31c07 100644--- a/src/lib/util/debug.svelte.ts+++ b/src/lib/util/debug.svelte.ts@@ -15,6 +15,7 @@ import {BookTextIcon,FilmIcon,ImageIcon,+ MusicIcon,RefreshCwIcon,ServerIcon,ShapesIcon,@@ -60,6 +61,16 @@ export const CONVERTER_META: Record<icon: AudioLinesIcon,accent: "bg-accent-purple",},+ "spessasynth-midi": {+ category: "audio",+ icon: MusicIcon,+ accent: "bg-accent-purple",+ },+ "spessasynth-soundfont": {+ category: "audio",+ icon: MusicIcon,+ accent: "bg-accent-purple",+ },pandoc: {category: "doc",icon: BookTextIcon,diff --git a/src/lib/workers/spessasynth.ts b/src/lib/workers/spessasynth.tsnew file mode 100644index 0000000..592d402--- /dev/null+++ b/src/lib/workers/spessasynth.ts@@ -0,0 +1,157 @@+import type { WorkerMessage } from "#lib/types";+import ffmpegWasmURL from "@ffmpeg/core/wasm?url";+import ffmpegCoreURL from "@ffmpeg/core?url";+import { FFmpeg } from "@ffmpeg/ffmpeg";+import {+ BasicMIDI,+ BasicSoundBank,+ SoundBankLoader,+ SpessaLog,+} from "spessasynth_core";++SpessaLog.setLogLevel(false, false, false);++self.postMessage({ type: "ready", id: "0" });++const coreURL = new URL(ffmpegCoreURL, import.meta.url).href;+const wasmURL = new URL(ffmpegWasmURL, import.meta.url).href;++const isMIDI = (ext: string) => [".mid", ".midi", ".rmi", ".kar"].includes(ext);+const isBank = (ext: string) =>+ [".sf2", ".sf3", ".sfogg", ".dls"].includes(ext);++const ensureDecoder = async () => {+ try {+ await BasicSoundBank.isSF3DecoderReady;+ } catch (err) {+ console.warn(`[spessasynth] SF3 decoder failed to initialise: ${err}`);+ }+};++// ffmpeg instance purely for encoding vorbis (for sf3/sfogg)+let vorbisEncoderReady: Promise<FFmpeg> | null = null;++const initVorbisEncoder = (): Promise<FFmpeg> => {+ vorbisEncoderReady ??= (async () => {+ const ffmpeg = new FFmpeg();+ await ffmpeg.load({ coreURL, wasmURL });+ return ffmpeg;+ })();+ return vorbisEncoderReady;+};++// spessasynth_core doesn't ship an encoder for vorbis, so use ffmpeg's libvorbis encoder to compress the samples before writing an sf3/sfogg+const encodeVorbis = async (+ audioData: Float32Array,+ sampleRate: number,+): Promise<Uint8Array> => {+ const ffmpeg = await initVorbisEncoder();+ const inName = "sample.f32le";+ const outName = "sample.ogg";+ try {+ const pcm = new Uint8Array(+ audioData.buffer,+ audioData.byteOffset,+ audioData.byteLength,+ ).slice();+ await ffmpeg.writeFile(inName, pcm);+ await ffmpeg.exec([+ "-f",+ "f32le",+ "-ar",+ String(sampleRate),+ "-ac",+ "1",+ "-i",+ inName,+ "-c:a",+ "libvorbis",+ "-f",+ "ogg",+ outName,+ ]);+ const data = (await ffmpeg.readFile(outName)) as Uint8Array;+ return new Uint8Array(data);+ } finally {+ await ffmpeg.deleteFile(inName).catch(() => {});+ await ffmpeg.deleteFile(outName).catch(() => {});+ }+};++const handleMessage = async (+ message: WorkerMessage,+): Promise<Partial<WorkerMessage>> => {+ if (message.type !== "convert")+ return { type: "error", error: "Unknown message type" };++ const from = message.input.from;+ const to = message.to.startsWith(".") ? message.to : `.${message.to}`;+ const buffer = await message.input.file.arrayBuffer();++ try {+ await ensureDecoder();++ let output: Uint8Array;+ if (isBank(from) && isBank(to)) {+ output = new Uint8Array(await convertBank(buffer, from, to));+ } else if (isMIDI(from) && isMIDI(to)) {+ output = new Uint8Array(+ convertMIDI(buffer, to, message.input.name),+ );+ } else {+ throw new Error(`Unsupported conversion: ${from} -> ${to}`);+ }++ if (!output.length)+ throw new Error("Conversion produced an empty file");+ return { type: "finished", output };+ } catch (err) {+ return { type: "error", error: (err as Error).message };+ }+};++const convertBank = async (+ buffer: ArrayBuffer,+ from: string,+ to: string,+): Promise<ArrayBuffer> => {+ const bank = SoundBankLoader.fromArrayBuffer(buffer);+ if (to === ".dls") return bank.writeDLS();+ if (to === ".sf3" || to === ".sfogg") {+ await bank.setSampleFormat({+ format: "compressed",+ compressionFunction: encodeVorbis,+ });+ return bank.writeSF2();+ }+ // compressed banks must be decompressed before writing an uncompressed format (sf2/dls)+ if (from === ".sf3" || from === ".sfogg")+ await bank.setSampleFormat({ format: "pcm" });+ return bank.writeSF2();+};++// TODO: allow uploading soundfonts to convert from MIDI to audio files+const convertMIDI = (+ buffer: ArrayBuffer,+ to: string,+ name: string,+): ArrayBuffer => {+ const midi = BasicMIDI.fromArrayBuffer(buffer, name);++ if (to === ".rmi") {+ if (!midi.embeddedSoundBank)+ throw new Error(+ ".rmi files can only be created from MIDI files that contain an embedded sound bank.",+ );+ const bank = SoundBankLoader.fromArrayBuffer(midi.embeddedSoundBank);+ return midi.writeRMIDI(midi.embeddedSoundBank, { soundBank: bank });+ }++ // .mid / .midi / .kar all save as a standard MIDI file+ return midi.writeMIDI();+};++self.onmessage = async (e: MessageEvent<WorkerMessage>) => {+ const res = await handleMessage(e.data);+ if (res) self.postMessage({ ...res, id: e.data.id });+};diff --git a/src/routes/convert/+page.svelte b/src/routes/convert/+page.svelteindex d91843d..6632bb0 100644--- a/src/routes/convert/+page.svelte+++ b/src/routes/convert/+page.svelte@@ -204,13 +204,18 @@}}- // or use first available format (or if default format is same as input)+ // or use the first format the file can actually convert toif (!targetFormat) {- const firstDiff = categories[category]?.formats.find(- (f) => f !== file.from,- );+ const formats = categories[category]?.formats ?? [];targetFormat =- firstDiff || categories[category]?.formats[0] || "";+ formats.find(+ (f) =>+ f !== file.from &&+ file.hasAvailableConverter(file.from, f),+ ) ??+ formats.find((f) => f !== file.from) ??+ formats[0] ??+ "";}file.to = targetFormat;