Skip to content

armgit / VERT

Public Imported from GitHub
0

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

14.8 KB
Raw Blame
import { m } from "#lib/paraglide/messages";
import { Settings } from "#lib/sections/settings/index.svelte";
import { VertFile } from "#lib/types";
import type {
	ConversionSettings,
	NormalizedSettings,
	SettingCategories,
	SettingDefinition,
} from "#lib/types/conversion-settings";
import { browser } from "$app/env";
import { FFmpeg } from "@ffmpeg/ffmpeg";
import { FormatInfo, formatDuration } from "../../converter.svelte";
import { applyPriorities } from "../../priority";
import { videoFormats } from "../../vertd/vertd.svelte";
import { BaseFFmpegConverter } from "../ffmpeg.base.svelte";
import { getCodecs, toArgs } from "../ffmpeg.codecs";
import {
	getDecodableAudioCodecs,
	pickUsableAudioStreams,
} from "../ffmpeg.decoders";
import { avWithArt, avWithBg, extractAlbumArt } from "../utils/ffmpeg";
import { probeAudioStreams } from "../video/ffmpeg.video.probe";

// TODO: differentiate in UI? (not native formats)
export class FFmpegConverter extends BaseFFmpegConverter {
	public name = "ffmpeg";
	public ready = $state(false);

	// non supported audio to video formats
	private cantConvert: string[] = ["ogx", "y4m", "ivf"]; // y4m/ivf are uncompressed/raw video containers without audio

	public supportedFormats = applyPriorities("ffmpeg", [
		new FormatInfo("mp3", true, true),
		new FormatInfo("wav", true, true),
		new FormatInfo("flac", true, true),
		new FormatInfo("ogg", true, true),
		new FormatInfo("mogg", true, false),
		new FormatInfo("oga", true, true),
		new FormatInfo("opus", true, true),
		new FormatInfo("aac", true, true),
		new FormatInfo("alac", true, true), // outputted as m4a
		new FormatInfo("m4a", true, true), // can be alac
		new FormatInfo("caf", true, false), // can be alac
		new FormatInfo("qoa", true, true),
		new FormatInfo("wma", true, true),
		new FormatInfo("ac3", true, true),
		new FormatInfo("aiff", true, true),
		new FormatInfo("aifc", true, true),
		new FormatInfo("aif", true, true),
		new FormatInfo("mp1", true, false),
		new FormatInfo("mp2", true, true),
		new FormatInfo("mpc", true, false), // unknown if it works, can't find sample file but ffmpeg should support i think?
		//new FormatInfo("raw", true, false), // usually pcm
		new FormatInfo("dsd", true, false), // dsd
		new FormatInfo("dsf", true, false), // dsd
		new FormatInfo("dff", true, false), // dsd
		new FormatInfo("mqa", true, false),
		new FormatInfo("au", true, true),
		new FormatInfo("m4b", true, true),
		new FormatInfo("voc", true, true),
		new FormatInfo("tta", true, true),
		new FormatInfo("amr", true, false), // only decode in ffmpeg-wasm
		new FormatInfo("ape", true, false),
		...videoFormats.map(
			//  exclude cantConvert from audio to video
			(f: string) => {
				const isCantConvert = this.cantConvert.includes(f);
				return new FormatInfo(f, true, !isCantConvert, false);
			},
		),
	]);

	constructor() {
		super();
		if (!browser) return;
		this.log(`created converter`);
	}

	public async getAvailableSettings(): Promise<SettingCategories> {
		// audio - bitrate, sample rate, channels, normalize, trim silence
		const bitrate: SettingDefinition = {
			key: "bitrate",
			label: m["convert.settings.audio.bitrate.label"](),
			type: "text",
			placeholder: m["convert.settings.audio.bitrate.placeholder"](),
		};

		const sampleRate: SettingDefinition = {
			key: "sampleRate",
			label: m["convert.settings.audio.sample_rate.label"](),
			type: "text",
			placeholder: m["convert.settings.audio.sample_rate.placeholder"](),
		};

		const channels: SettingDefinition = {
			key: "channels",
			label: m["convert.settings.audio.channels.label"](),
			type: "text",
			default: "2",
			placeholder: m["convert.settings.audio.channels.placeholder"](),
		};

		/*
		 *	common
		 */
		const metadata: SettingDefinition = {
			key: "metadata",
			label: m["convert.settings.common.metadata"](),
			type: "boolean",
			default: Settings.instance.settings.metadata,
		};

		// resize, crop, rotate - prob want a ui

		return {
			Audio: [bitrate, sampleRate, channels],
			General: [metadata],
		};
	}

	public async getDefaultSettings(): Promise<ConversionSettings> {
		const defaults: ConversionSettings = {};
		const categories = await this.getAvailableSettings();
		Object.values(categories)
			.flat()
			.forEach((setting) => {
				defaults[setting.key] = setting.default;
			});
		return defaults;
	}

	public async normalizeSettings(
		input: VertFile,
		to: string,
		settings: ConversionSettings,
	): Promise<NormalizedSettings> {
		const normalized = { ...settings };
		const changes: NormalizedSettings["changes"] = [];

		const change = (setting: string, newValue: string | number) => {
			const oldValue = normalized[setting];
			if (oldValue === newValue) return;

			normalized[setting] = newValue;
			changes.push({
				setting,
				oldValue,
				newValue,
				file: input.name,
			});
		};

		if (to === ".opus") {
			// work around browser stereo+libopus wasm crash
			// no idea why its broken like this in the browser only lol
			if (Number(normalized.channels) >= 2) change("channels", "1");

			const bitrate = Number(normalized.bitrate);
			if (Number.isFinite(bitrate) && bitrate > 256)
				change("bitrate", "256");
		} else if (to === ".amv") {
			change("sampleRate", "22050");
			change("channels", "1");
			change("bitrate", "32");
		} else if (to === ".mpg" || to === ".mpeg" || to === ".vob") {
			const bitrate = Number(normalized.bitrate);
			if (Number.isFinite(bitrate) && bitrate > 0)
				change("bitrate", Math.pow(2, Math.round(Math.log2(bitrate))));
		} else if (to === ".gxf") {
			change("sampleRate", "48000");
			change("channels", "1");
		}

		return { settings: normalized, changes };
	}

	public async convert(
		input: VertFile,
		to: string,
		settings: ConversionSettings,
	): Promise<VertFile> {
		this.trackConversion(input);
		if (!to.startsWith(".")) to = `.${to}`;
		this.log(`converting ${input.name} (${input.id}) to ${to}`);
		const startedAt = performance.now();

		const conversionSettings =
			Object.keys(settings).length > 4 // TODO: find better way to do this lmfao, rn we are just assuming all settings are present if there's at least 5 keys but ts bad
				? { ...settings }
				: {
						...(await this.getDefaultSettings()),
						...settings,
					}; // use defaults if not provided

		const isAlac = to === ".alac";
		if (isAlac) to = ".m4a";

		await this.ensureCore();

		this.throwIfCancelled(input);

		let conversionError: string | null = null;
		const ffmpeg = await this.setupFFmpeg(input);

		// listen for errors during conversion
		const errorListener = (l: { message: string }) => {
			const msg = l.message;
			if (
				msg.includes("Specified sample rate") &&
				msg.includes("is not supported")
			) {
				const rate = conversionSettings.sampleRate;
				conversionError = m["workers.errors.invalid_rate"]({
					rate,
				});
			} else if (msg.includes("matches no streams")) {
				conversionError = m["workers.errors.no_audio"]();
			} else if (
				msg.includes("Error initializing output stream") ||
				msg.includes("Error while opening encoder") ||
				msg.includes("Error while opening decoder") ||
				(msg.includes("Error") && msg.includes("stream")) ||
				msg.includes("Conversion failed!")
			) {
				// other general errors
				if (!conversionError) conversionError = msg;
			}
		};

		ffmpeg.on("log", errorListener);

		const logListener = (l: { message: string }) => {
			this.log(l.message);
		};

		ffmpeg.on("log", logListener);

		try {
			let buf = new Uint8Array(await input.file.arrayBuffer());

			if (input.from === ".qoa") {
				const { decodeQoa, encodeWav } =
					await import("#lib/util/parse/qoa");
				const decoded = decodeQoa(buf);
				buf = new Uint8Array(
					encodeWav(
						decoded.pcm,
						decoded.sampleRate,
						decoded.channels,
						true,
					),
				);
			}

			await ffmpeg.writeFile("input", buf);
			this.log(`wrote ${input.name} (${input.id}) to ffmpeg virtual fs`);

			const specialHandled = await handleSpecialOutput(
				ffmpeg,
				input,
				to,
				conversionSettings,
				() => conversionError,
			);
			if (specialHandled) {
				return specialHandled;
			} else {
				const command = await this.buildConversionCommand(
					ffmpeg,
					input,
					to,
					conversionSettings,
					isAlac,
				);
				this.log(`FFmpeg command: ${command.join(" ")}`);
				await ffmpeg.exec(command);
				this.log("executed ffmpeg command");

				if (conversionError) throw new Error(conversionError);

				const output = (await ffmpeg.readFile(
					"output" + to,
				)) as unknown as Uint8Array;

				if (!output || output.length === 0)
					throw new Error("empty file returned");

				const outputFileName =
					input.name.split(".").slice(0, -1).join(".") + to;
				this.log(
					`read ${outputFileName} (${input.id}) from ffmpeg virtual fs`,
				);

				const outBuf = new Uint8Array(output).buffer.slice(0);
				this.log(
					`converted ${input.name} (${input.id}) to ${to} in ${formatDuration(performance.now() - startedAt)}`,
				);
				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);
			ffmpeg.terminate();
		}
	}

	private async buildConversionCommand(
		ffmpeg: FFmpeg,
		input: VertFile,
		to: string,
		settings: ConversionSettings,
		isAlac: boolean = false,
	): Promise<string[]> {
		const inputFormat = input.from.slice(1);
		const outputFormat = to.slice(1);
		const m4a = isAlac || to === ".m4a";

		const userBitrate = settings.bitrate;
		const userSampleRate = settings.sampleRate;
		const keepMetadata = settings.metadata;

		// else normal single file conversion

		let audioBitrateArgs: string[] = [];
		let sampleRateArgs: string[] = [];
		let channelsArgs: string[] = [];
		let metadataArgs: string[] = [];
		const extraArgs: string[] = [];
		if (to === ".amv") {
			// amv requires mono audio, 32kbps, and 22050 sample rate
			// block size is 22050 (sample rate) / fps. max is 8192, so we have to force a higher fps
			const amvFps = 3;
			extraArgs.push(
				"-r",
				String(amvFps),
				"-block_size",
				String(Math.floor(22050 / amvFps)),
			);
		}

		this.log(`keep metadata: ${keepMetadata}`);
		if (!keepMetadata) {
			metadataArgs = [
				"-map_metadata", // remove metadata
				"-1",
				"-map_chapters", // remove chapters
				"-1",
			];
		}

		if (userBitrate) {
			audioBitrateArgs = ["-b:a", `${userBitrate}k`];
			this.log(`using user setting for audio bitrate: ${userBitrate}`);
		}

		// sample rate setting
		if (userSampleRate) {
			sampleRateArgs = ["-ar", String(userSampleRate)];
			this.log(`using user setting for sample rate: ${userSampleRate}Hz`);
		}

		// channels setting
		const channels = parseChannels(settings.channels);
		if (channels !== null) {
			channelsArgs = ["-ac", String(channels)];
			this.log(`using user setting for audio channels: ${channels}`);
		}

		// video to audio
		if (videoFormats.includes(inputFormat)) {
			this.log(
				`Converting video ${input.from} to audio ${to} (${input.name} ${input.id})`,
			);
			const usable = pickUsableAudioStreams(
				await probeAudioStreams(ffmpeg, "input"),
				getDecodableAudioCodecs(),
			);
			if (!usable.length) throw new Error(m["workers.errors.no_audio"]());
			this.log(`extracting audio stream #${usable[0].index}`);
			return [
				"-i",
				"input",
				"-map",
				`0:${usable[0].index}`,
				...metadataArgs,
				...audioBitrateArgs,
				...sampleRateArgs,
				...channelsArgs,
				...extraArgs,
				"output" + to,
			];
		}

		// audio to video
		if (videoFormats.includes(outputFormat)) {
			this.log(
				`Converting audio ${input.from} to video ${to} (${input.name} ${input.id})`,
			);

			const hasAlbumArt = keepMetadata
				? await extractAlbumArt(ffmpeg)
				: false;
			const codecArgs = toArgs(to, isAlac);

			if (hasAlbumArt) {
				this.log("Using album art as video background");
				return avWithArt(
					to,
					codecArgs,
					metadataArgs,
					audioBitrateArgs,
					sampleRateArgs,
					channelsArgs,
					extraArgs,
				);
			} else {
				this.log("Using solid color background");
				return avWithBg(
					to,
					toArgs(to, isAlac),
					metadataArgs,
					audioBitrateArgs,
					sampleRateArgs,
					channelsArgs,
					extraArgs,
				);
			}
		}

		// audio to audio
		this.log(
			`Converting audio ${input.from} to audio ${to} (${input.name} ${input.id})`,
		);
		const { audio: audioCodec } = getCodecs(to, isAlac);
		if (m4a && keepMetadata) extraArgs.push("-c:v", "copy"); // for album art

		return [
			"-i",
			"input",
			"-c:a",
			audioCodec,
			...metadataArgs,
			...audioBitrateArgs,
			...sampleRateArgs,
			...channelsArgs,
			...extraArgs,
			"-strict",
			"experimental",
			"output" + to,
		];
	}
}

const parseChannels = (value: ConversionSettings[string]): number | null => {
	const text = String(value ?? "").trim();
	if (!text || text === "auto") return null;
	const channels = Number(text);
	if (!Number.isSafeInteger(channels) || channels <= 0)
		throw new Error(
			m["workers.errors.invalid_channels"]({ channels: text }),
		);
	return channels;
};

const handleSpecialOutput = async (
	ffmpeg: FFmpeg,
	input: VertFile,
	to: string,
	conversionSettings: ConversionSettings,
	getConversionError: () => string | null,
): Promise<VertFile | null> => {
	if (to === ".qoa") {
		const sampleRate =
			conversionSettings.sampleRate &&
			conversionSettings.sampleRate !== "auto"
				? (conversionSettings.sampleRate as number)
				: 48000;

		const channels = parseChannels(conversionSettings.channels) ?? 2;
		if (channels > 255)
			throw new Error(
				m["workers.errors.invalid_channels"]({
					channels: String(channels),
				}),
			);

		const usable = pickUsableAudioStreams(
			await probeAudioStreams(ffmpeg, "input"),
			getDecodableAudioCodecs(),
		);
		if (!usable.length) throw new Error(m["workers.errors.no_audio"]());

		const pcmArgs = [
			"-i",
			"input",
			"-map",
			`0:${usable[0].index}`,
			"-f",
			"f32le",
			"-ar",
			String(sampleRate),
			"-ac",
			String(channels),
			"-c:a",
			"pcm_f32le",
			"output.raw",
		];
		const exitCode = await ffmpeg.exec(pcmArgs);

		const conversionError = getConversionError();
		if (conversionError) throw new Error(conversionError);
		if (exitCode !== 0)
			throw new Error(
				`FFmpeg QOA PCM conversion failed with exit code ${exitCode}`,
			);

		const pcmRaw = (await ffmpeg.readFile(
			"output.raw",
		)) as unknown as Uint8Array;
		if (!pcmRaw || pcmRaw.length === 0)
			throw new Error("FFmpeg QOA conversion returned empty PCM audio");
		const { encodeQoa } = await import("#lib/util/parse/qoa");
		const qoaBytes = encodeQoa(
			new Uint8Array(pcmRaw),
			sampleRate,
			channels,
		);
		const outputFileName =
			input.name.split(".").slice(0, -1).join(".") + ".qoa";
		return new VertFile(
			new File([new Uint8Array(qoaBytes)], outputFileName),
			".qoa",
		);
	}
	// if (whatever other formats need special parsing)

	return null;
};