The next-generation file converter. Open source, fully local* and free forever.
feat: ffmpeg.wasm for local video conversions
JovannMCca7fc889bd70
diff --git a/messages/en.json b/messages/en.jsonindex 7cf1f46..348a5c8 100644--- a/messages/en.json+++ b/messages/en.json@@ -182,6 +182,16 @@"fast": "Lower quality (faster)","ultra_fast": "Lowest quality (fastest)"},+ "local_speed": {+ "title": "Conversion speed",+ "description": "This controls the encoder preset for the local FFmpeg converter. Local video conversion is very slow - higher quality settings can take a long time. This is overridden if you manually set a video bitrate.",+ "very_slow": "Highest quality (very slow)",+ "slower": "Higher quality (slower)",+ "slow": "High quality (slow)",+ "medium": "Medium quality (average)",+ "fast": "Lower quality (faster)",+ "ultra_fast": "Lowest quality (fastest)"+ },"fps": {"label": "Frame rate (FPS)","placeholder": "e.g. 24, 30, 60"@@ -535,6 +545,8 @@"no_audio": "No audio stream found.","invalid_rate": "Invalid sample rate specified: {rate}Hz","invalid_channels": "Invalid audio channel count: {channels}",+ "ffmpeg_video_unsupported": "Encoding to {to} is not supported by the local FFmpeg converter.",+ "ffmpeg_video_no_audio_encoder": "No audio encoder is available for {to} in the local FFmpeg converter.","file_too_large": "This file exceeds the {limit}GB browser / device limit. Try Firefox or Safari to convert this large file, which typically have higher limits."},"warnings": {diff --git a/src/lib/components/functional/popups/SettingsModal.svelte b/src/lib/components/functional/popups/SettingsModal.svelteindex c7ee17c..18194f8 100644--- a/src/lib/components/functional/popups/SettingsModal.svelte+++ b/src/lib/components/functional/popups/SettingsModal.svelte@@ -52,11 +52,12 @@(converter) => !vertFile.unavailableConverters[converter.name],);- // image sequences can be converted locally (ffmpeg) or on the server (vertd)+ // image sequences can be converted locally (local ffmpeg) or on the server (vertd)if (vertFile.sequenceKind)return availableConverters.filter((converter) =>- converter.name === "ffmpeg" || converter.name === "vertd",+ converter.name === "ffmpeg-video" ||+ converter.name === "vertd",);const supportedConverters = vertFile.findConverters(diff --git a/src/lib/converters/ffmpeg/ffmpeg.svelte.ts b/src/lib/converters/ffmpeg/audio/ffmpeg.audio.svelte.tssimilarity index 67%rename from src/lib/converters/ffmpeg/ffmpeg.svelte.tsrename to src/lib/converters/ffmpeg/audio/ffmpeg.audio.svelte.tsindex 8034fd8..fcf229f 100644--- a/src/lib/converters/ffmpeg/ffmpeg.svelte.ts+++ b/src/lib/converters/ffmpeg/audio/ffmpeg.audio.svelte.ts@@ -7,48 +7,20 @@ import type {SettingCategories,SettingDefinition,} from "#lib/types/conversion-settings";-import { ToastManager } from "#lib/util/toast.svelte";import { browser } from "$app/env";-import ffmpegMtWasmURL from "@ffmpeg/core-mt/wasm?url";-import ffmpegMtWorkerRaw from "@ffmpeg/core-mt/worker?raw";-import ffmpegMtCoreURL from "@ffmpeg/core-mt?url";-import ffmpegWasmURL from "@ffmpeg/core/wasm?url";-import ffmpegCoreURL from "@ffmpeg/core?url";import { FFmpeg } from "@ffmpeg/ffmpeg";-import { SvelteMap } from "svelte/reactivity";-import { Converter, FormatInfo, formatDuration } from "../converter.svelte";-import { EngineVariants, type FFmpegVariant } from "../engine-variants.svelte";-import { applyPriorities } from "../priority";-import { videoFormats } from "../vertd/vertd.svelte";-import { buildImageSequenceCommand } from "./ffmpeg.animated";-import { getCodecs, toArgs } from "./ffmpeg.codecs";-import { avWithArt, avWithBg, extractAlbumArt } from "./utils/ffmpeg";--const coreURL = new URL(ffmpegCoreURL, import.meta.url).href;-const wasmURL = new URL(ffmpegWasmURL, import.meta.url).href;-const mtCoreURL = new URL(ffmpegMtCoreURL, import.meta.url).href;-const mtWasmURL = new URL(ffmpegMtWasmURL, import.meta.url).href;--// The pthread worker ffmpeg-core-mt spawns is a *classic* worker, but the ESM-// worker file only runs as a module and Vite injects an import into it in dev,-// so serve it as a blob of the raw source instead (works in dev and prod).-// ..whatever the ai said above. i didn't know how to fix this but it works so uuuuh, sorry -maya-let mtWorkerURL: string | undefined;-const getMtWorkerURL = (): string =>- (mtWorkerURL ??= URL.createObjectURL(- new Blob([ffmpegMtWorkerRaw], { type: "text/javascript" }),- ));+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 { avWithArt, avWithBg, extractAlbumArt } from "../utils/ffmpeg";// TODO: differentiate in UI? (not native formats)-export class FFmpegConverter extends Converter {+export class FFmpegConverter extends BaseFFmpegConverter {public name = "ffmpeg";public ready = $state(false);- private loadedVariant: "mt" | "st" | null = null;- private requestedVariant: "mt" | "st" | null = null;-- private activeConversions = new SvelteMap<string, FFmpeg>();-// non supported audio to video formatsprivate cantConvert: string[] = ["ogx", "y4m", "ivf"]; // y4m/ivf are uncompressed/raw video containers without audio@@ -93,91 +65,12 @@ export class FFmpegConverter extends Converter {),]);- public readonly reportsProgress = true;-constructor() {super();if (!browser) return;this.log(`created converter`);}- public getVariantLabel(): string | null {- const variant = EngineVariants.instance.ffmpegActive;- return variant === "mt"- ? m["convert.settings.engines.ffmpeg_mt"]()- : m["convert.settings.engines.ffmpeg_st"]();- }-- public getVariantOptions() {- return [- { value: "auto", label: m["convert.settings.engines.auto"]() },- {- value: "mt",- label: m["convert.settings.engines.ffmpeg_mt"](),- },- {- value: "st",- label: m["convert.settings.engines.ffmpeg_st"](),- },- ];- }-- public getVariantValue(): string {- return EngineVariants.instance.ffmpeg;- }-- public setVariant(value: string): void {- EngineVariants.instance.setFfmpeg(value as FFmpegVariant);- }-- 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 instance- if (!browser) return;- this.resolveThreads();-- try {- await this.probeCore();- this.status = "ready";- return Promise.resolve();- } catch (err) {- if (this.loadedVariant === "mt") {- this.log(- `multi-threaded ffmpeg core failed to load, falling back to single-threaded: ${err}`,- );- ToastManager.add({- type: "info",- message: m["workers.info.ffmpeg_mt_unavailable"](),- });- this.loadedVariant = "st";- try {- await this.probeCore();- this.status = "ready";- return Promise.resolve();- } catch (fallbackErr) {- this.error(- `single-threaded ffmpeg core failed too: ${fallbackErr}`,- );- }- }-- ToastManager.add({- type: "error",- message: m["workers.errors.ffmpeg"](),- });- throw err;- }- }-- // load (and immediately discard) a worker to validate and/or cache- private async probeCore(): Promise<void> {- const ffmpeg = new FFmpeg();- try {- await ffmpeg.load(this.loadConfig());- } finally {- ffmpeg.terminate();- }- }-public async getAvailableSettings(): Promise<SettingCategories> {// audio - bitrate, sample rate, channels, normalize, trim silenceconst bitrate: SettingDefinition = {@@ -297,10 +190,7 @@ export class FFmpegConverter extends Converter {const isAlac = to === ".alac";if (isAlac) to = ".m4a";- await this.init();-- if (EngineVariants.instance.ffmpegActive !== this.requestedVariant)- await this.download();+ await this.ensureCore();let conversionError: string | null = null;const ffmpeg = await this.setupFFmpeg(input);@@ -411,61 +301,6 @@ export class FFmpegConverter extends Converter {}}- 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;- }-- this.log(`cancelling conversion for file ${input.name} (${input.id})`);-- ffmpeg.terminate();- this.activeConversions.delete(input.id);- }-- private async setupFFmpeg(input: VertFile): Promise<FFmpeg> {- const ffmpeg = new FFmpeg();-- ffmpeg.on("progress", (progress) => {- input.progress = progress.progress * 100;- });-- await ffmpeg.load(this.loadConfig());-- return ffmpeg;- }-- private resolveThreads(): void {- const variants = EngineVariants.instance;-- if (variants.ffmpeg === "mt" && !variants.ffmpegMtSupported) {- this.log(- "multi-threaded ffmpeg requested but the page is not cross-origin isolated, using single-threaded",- );- ToastManager.add({- type: "info",- message: m["workers.info.ffmpeg_mt_unavailable"](),- });- }-- this.loadedVariant = variants.ffmpegActive;- this.requestedVariant = this.loadedVariant;- this.log(`using ${this.loadedVariant} ffmpeg core`);- }-- private loadConfig() {- return this.loadedVariant === "mt"- ? {- coreURL: mtCoreURL,- wasmURL: mtWasmURL,- workerURL: getMtWorkerURL(),- }- : { coreURL, wasmURL };- }-private async buildConversionCommand(ffmpeg: FFmpeg,input: VertFile,@@ -476,60 +311,11 @@ export class FFmpegConverter extends Converter {const inputFormat = input.from.slice(1);const outputFormat = to.slice(1);const m4a = isAlac || to === ".m4a";- const isImageSequence = input.isZip() && settings.imageSequence;const userBitrate = settings.bitrate;const userSampleRate = settings.sampleRate;const keepMetadata = settings.metadata;- // image sequences -> animated image // video- if (isImageSequence) {- this.log(- `converting image sequence ${input.name} (${input.id}) to ${to}`,- );-- const { extractZip } = await import("#lib/util/file");- const entries = (await extractZip(input.file)).sort((a, b) =>- a.filename.localeCompare(b.filename, undefined, {- numeric: true,- sensitivity: "base",- }),- );-- if (!entries.length)- throw new Error("No images found in zip archive");-- const imageFiles: Array<{ name: string }> = [];-- for (const [index, entry] of entries.entries()) {- const fileName =- entry.filename.split("/").pop() ?? entry.filename;- const ext = fileName.split(".").pop()?.toLowerCase();- if (!ext) continue;-- const paddedName = `img${String(index + 1).padStart(5, "0")}.${ext}`;- await ffmpeg.writeFile(paddedName, entry.data);- imageFiles.push({ name: paddedName });- }-- if (!imageFiles.length)- throw new Error("No images found in zip archive");-- const listContent = imageFiles- .map(- (image) =>- `file '${image.name}'\nduration ${1 / (settings.imageSequenceFPS || 15)}`,- )- .join("\n");- await ffmpeg.writeFile(- "frames.txt",- `${listContent}\nfile '${imageFiles[imageFiles.length - 1].name}'\n`,- );- this.log(`wrote ${imageFiles.length} images to ffmpeg virtual fs`);-- return buildImageSequenceCommand(outputFormat, settings, isAlac);- }-// else normal single file conversionlet audioBitrateArgs: string[] = [];@@ -656,13 +442,6 @@ export class FFmpegConverter extends Converter {}}-// const handleSpecialInput = async (-// ffmpeg: FFmpeg,-// input: VertFile,-// ): Promise<VertFile | null> => {-//-// }-const parseChannels = (value: ConversionSettings[string]): number | null => {const text = String(value ?? "").trim();if (!text || text === "auto") return null;diff --git a/src/lib/converters/ffmpeg/ffmpeg.base.svelte.ts b/src/lib/converters/ffmpeg/ffmpeg.base.svelte.tsnew file mode 100644index 0000000..c7710e3--- /dev/null+++ b/src/lib/converters/ffmpeg/ffmpeg.base.svelte.ts@@ -0,0 +1,180 @@+import { m } from "#lib/paraglide/messages";+import type { VertFile } from "#lib/types";+import { ToastManager } from "#lib/util/toast.svelte";+import { browser } from "$app/env";+import ffmpegMtWasmURL from "@ffmpeg/core-mt/wasm?url";+import ffmpegMtWorkerRaw from "@ffmpeg/core-mt/worker?raw";+import ffmpegMtCoreURL from "@ffmpeg/core-mt?url";+import ffmpegWasmURL from "@ffmpeg/core/wasm?url";+import ffmpegCoreURL from "@ffmpeg/core?url";+import { FFmpeg } from "@ffmpeg/ffmpeg";+import { SvelteMap } from "svelte/reactivity";+import { Converter } from "../converter.svelte";+import { EngineVariants, type FFmpegVariant } from "../engine-variants.svelte";++const coreURL = new URL(ffmpegCoreURL, import.meta.url).href;+const wasmURL = new URL(ffmpegWasmURL, import.meta.url).href;+const mtCoreURL = new URL(ffmpegMtCoreURL, import.meta.url).href;+const mtWasmURL = new URL(ffmpegMtWasmURL, import.meta.url).href;++// The pthread worker ffmpeg-core-mt spawns is a *classic* worker, but the ESM+// worker file only runs as a module and Vite injects an import into it in dev,+// so serve it as a blob of the raw source instead (works in dev and prod).+// ..whatever the ai said above. i didn't know how to fix this but it works so uuuuh, sorry -maya+let mtWorkerURL: string | undefined;+const getMtWorkerURL = (): string =>+ (mtWorkerURL ??= URL.createObjectURL(+ new Blob([ffmpegMtWorkerRaw], { type: "text/javascript" }),+ ));++export abstract class BaseFFmpegConverter extends Converter {+ public abstract name: string;+ public reportsProgress = true;++ protected loadedVariant: "mt" | "st" | null = null;+ protected requestedVariant: "mt" | "st" | null = null;++ protected activeConversions = new SvelteMap<string, FFmpeg>();++ public getVariantLabel(): string | null {+ const variant = EngineVariants.instance.ffmpegActive;+ return variant === "mt"+ ? m["convert.settings.engines.ffmpeg_mt"]()+ : m["convert.settings.engines.ffmpeg_st"]();+ }++ public getVariantOptions() {+ return [+ { value: "auto", label: m["convert.settings.engines.auto"]() },+ {+ value: "mt",+ label: m["convert.settings.engines.ffmpeg_mt"](),+ },+ {+ value: "st",+ label: m["convert.settings.engines.ffmpeg_st"](),+ },+ ];+ }++ public getVariantValue(): string {+ return EngineVariants.instance.ffmpeg;+ }++ public setVariant(value: string): void {+ EngineVariants.instance.setFfmpeg(value as FFmpegVariant);+ }++ 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 instance+ if (!browser) return;+ this.resolveThreads();++ try {+ await this.probeCore();+ this.status = "ready";+ return Promise.resolve();+ } catch (err) {+ if (this.loadedVariant === "mt") {+ this.log(+ `multi-threaded ffmpeg core failed to load, falling back to single-threaded: ${err}`,+ );+ ToastManager.add({+ type: "info",+ message: m["workers.info.ffmpeg_mt_unavailable"](),+ });+ this.loadedVariant = "st";+ try {+ await this.probeCore();+ this.status = "ready";+ return Promise.resolve();+ } catch (fallbackErr) {+ this.error(+ `single-threaded ffmpeg core failed too: ${fallbackErr}`,+ );+ }+ }++ ToastManager.add({+ type: "error",+ message: m["workers.errors.ffmpeg"](),+ });+ throw err;+ }+ }++ // load (and immediately discard) a worker to validate and/or cache+ protected async probeCore(): Promise<void> {+ const ffmpeg = new FFmpeg();+ try {+ await ffmpeg.load(this.loadConfig());+ } finally {+ ffmpeg.terminate();+ }+ }++ /**+ * Ensure the core is loaded and matches the currently selected engine+ * variant, re-downloading if the user switched variants since last time.+ */+ protected async ensureCore(): Promise<void> {+ await this.init();+ if (EngineVariants.instance.ffmpegActive !== this.requestedVariant)+ await this.download();+ }++ protected async setupFFmpeg(input: VertFile): Promise<FFmpeg> {+ const ffmpeg = new FFmpeg();++ ffmpeg.on("progress", (progress) => {+ input.progress = progress.progress * 100;+ });++ await ffmpeg.load(this.loadConfig());++ 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;+ }++ this.log(`cancelling conversion for file ${input.name} (${input.id})`);++ ffmpeg.terminate();+ this.activeConversions.delete(input.id);+ }++ protected resolveThreads(): void {+ const variants = EngineVariants.instance;++ if (variants.ffmpeg === "mt" && !variants.ffmpegMtSupported) {+ this.log(+ "multi-threaded ffmpeg requested but the page is not cross-origin isolated, using single-threaded",+ );+ ToastManager.add({+ type: "info",+ message: m["workers.info.ffmpeg_mt_unavailable"](),+ });+ }++ this.loadedVariant = variants.ffmpegActive;+ this.requestedVariant = this.loadedVariant;+ this.log(`using ${this.loadedVariant} ffmpeg core`);+ }++ protected loadConfig() {+ return this.loadedVariant === "mt"+ ? {+ coreURL: mtCoreURL,+ wasmURL: mtWasmURL,+ workerURL: getMtWorkerURL(),+ }+ : { coreURL, wasmURL };+ }+}diff --git a/src/lib/converters/ffmpeg/ffmpeg.animated.ts b/src/lib/converters/ffmpeg/video/ffmpeg.animated.tssimilarity index 97%rename from src/lib/converters/ffmpeg/ffmpeg.animated.tsrename to src/lib/converters/ffmpeg/video/ffmpeg.animated.tsindex 3b2098e..9c9c59c 100644--- a/src/lib/converters/ffmpeg/ffmpeg.animated.ts+++ b/src/lib/converters/ffmpeg/video/ffmpeg.animated.ts@@ -3,7 +3,7 @@ import {toArgs,} from "#lib/converters/ffmpeg/ffmpeg.codecs";import type { ConversionSettings } from "#lib/types/conversion-settings";-import { videoFormats } from "../vertd/vertd.svelte";+import { videoFormats } from "../../vertd/vertd.svelte";export function buildImageSequenceCommand(outputFormat: string,diff --git a/src/lib/converters/ffmpeg/video/ffmpeg.video.codecs.ts b/src/lib/converters/ffmpeg/video/ffmpeg.video.codecs.tsnew file mode 100644index 0000000..791bab5--- /dev/null+++ b/src/lib/converters/ffmpeg/video/ffmpeg.video.codecs.ts@@ -0,0 +1,463 @@+export interface FormatCodecSupport {+ video: string[];+ audio: string[];+}++// converter/codecs.rs `codec_support_for`+// prettier-ignore+export const FORMAT_CODECS: Record<string, FormatCodecSupport> = {+ mp4: {+ video: ["h264", "hevc", "mpeg4", "vp9", "mpeg2video", "mpeg1video"],+ audio: ["aac", "mp3", "ac3", "eac3", "alac", "flac", "libopus"],+ },+ webm: {+ video: ["vp9", "vp8"],+ audio: ["libopus", "libvorbis"],+ },+ avi: {+ video: ["mpeg4", "msmpeg4v3", "msmpeg4v2", "h264", "mjpeg", "dvvideo", "huffyuv"],+ audio: ["mp3", "ac3", "pcm_s16le", "pcm_s24le"],+ },+ mkv: {+ video: ["h264", "hevc", "vp9", "vp8", "mpeg2video", "mpeg4", "prores", "dnxhd", "ffv1", "huffyuv", "mjpeg", "mpeg1video"],+ audio: ["aac", "mp3", "ac3", "eac3", "libopus", "libvorbis", "flac", "alac", "wavpack", "tta", "pcm_s16le", "pcm_s24le", "pcm_s32le", "pcm_f32le", "pcm_s16be", "pcm_s24be", "pcm_s32be", "pcm_mulaw", "pcm_alaw", "pcm_u8"],+ },+ mov: {+ video: ["h264", "hevc", "prores", "dnxhd", "mpeg4", "mjpeg", "ffv1"],+ audio: ["aac", "alac", "mp3", "flac", "pcm_s16le", "pcm_s24le", "pcm_s32le", "pcm_f32le", "pcm_s16be", "pcm_s24be", "pcm_mulaw", "pcm_alaw", "pcm_u8"],+ },+ m2ts: {+ video: ["h264", "mpeg2video"],+ audio: ["ac3", "eac3", "pcm_s16le"],+ },+ mts: {+ video: ["h264", "mpeg2video", "hevc"],+ audio: ["ac3", "aac", "mp2", "mp3", "eac3"],+ },+ ts: {+ video: ["h264", "hevc", "mpeg2video", "mpeg1video"],+ audio: ["aac", "ac3", "mp2", "mp3", "eac3"],+ },+ mpeg: {+ video: ["mpeg2video", "mpeg1video"],+ audio: ["ac3", "mp2", "mp3"],+ },+ mpg: {+ video: ["mpeg2video", "mpeg1video"],+ audio: ["ac3", "mp2", "mp3"],+ },+ flv: {+ video: ["h264", "flv1", "h263"],+ audio: ["aac", "mp3", "nellymoser", "speex", "adpcm_swf"],+ },+ f4v: {+ video: ["h264"],+ audio: ["aac", "mp3"],+ },+ vob: {+ video: ["mpeg2video", "mpeg1video"],+ audio: ["ac3", "mp2", "pcm_s16le"],+ },+ m4v: {+ video: ["h264", "mpeg4"],+ audio: ["aac", "ac3", "alac", "flac"],+ },+ "3gp": {+ video: ["h264", "mpeg4", "h263"],+ audio: ["aac"],+ },+ "3g2": {+ video: ["h264", "mpeg4", "h263"],+ audio: ["aac"],+ },+ mxf: {+ video: ["prores", "dnxhd", "h264", "mpeg2video", "mjpeg"],+ audio: ["pcm_s24le", "pcm_s16le", "pcm_s32le"],+ },+ gxf: {+ video: ["mpeg2video", "dvvideo", "mjpeg", "mpeg1video"],+ audio: ["pcm_s16le", "pcm_s24le", "ac3"],+ },+ ogv: {+ video: ["theora", "vp8"],+ audio: ["libvorbis", "libopus", "flac", "speex"],+ },+ ogx: {+ video: ["theora", "vp8"],+ audio: ["libvorbis", "libopus", "flac", "speex"],+ },+ swf: {+ video: ["flv1", "flashsv", "mjpeg"],+ audio: ["mp3"],+ },+ amv: {+ video: ["amv"],+ audio: ["adpcm_ima_amv"],+ },+ asf: {+ video: ["wmv2", "wmv1", "msmpeg4v3"],+ audio: ["wmav2", "wmav1", "mp3"],+ },+ wmv: {+ video: ["wmv2", "wmv1"],+ audio: ["wmav2"],+ },+ nut: {+ video: ["h264", "mpeg4", "vp9", "vp8", "ffv1", "mjpeg", "huffyuv", "h263", "prores", "mpeg2video", "h261", "svq1", "ljpeg", "snow"],+ audio: ["aac", "mp3", "ac3", "eac3", "libopus", "libvorbis", "flac", "alac", "wavpack", "pcm_s16le", "pcm_s24le", "pcm_s32le", "pcm_f32le", "pcm_s16be", "pcm_s24be", "pcm_s32be", "pcm_mulaw", "pcm_alaw", "pcm_u8"],+ },+ h264: {+ video: ["h264"],+ audio: [],+ },+ divx: {+ video: ["mpeg4", "h264", "hevc"],+ audio: ["mp3", "ac3", "aac", "pcm_s16le"],+ },+ gif: {+ video: ["gif"],+ audio: [],+ },+ apng: {+ video: ["apng"],+ audio: [],+ },+ webp: {+ video: ["webp"],+ audio: [],+ },+};++const normalize = (format: string) => format.replace(/^\./, "").toLowerCase();++// converter/codecs.rs `codec_support_for`+export const codecSupportFor = (format: string): FormatCodecSupport | null =>+ FORMAT_CODECS[normalize(format)] ?? null;++// converter/codecs.rs `canonical_codec`+export const canonicalCodec = (codec: string): string => {+ const value = codec.toLowerCase();+ switch (value) {+ case "libx264":+ case "libx264rgb":+ case "libopenh264":+ return "h264";+ case "libx265":+ case "libkvazaar":+ return "hevc";+ case "libxvid":+ return "mpeg4";+ case "libvpx":+ return "vp8";+ case "libvpx-vp9":+ return "vp9";+ case "libwebp":+ case "libwebp_anim":+ return "webp";+ case "prores_ks":+ case "prores_aw":+ return "prores";+ case "libmp3lame":+ case "libshine":+ return "mp3";+ case "libopus":+ return "opus";+ case "libvorbis":+ return "vorbis";+ case "libspeex":+ return "speex";+ default:+ return value.startsWith("lib") ? value.slice(3) : value;+ }+};++// converter/codecs.rs `support_video_codec` / `support_audio_codec`+export const supportsCodec = (codecs: string[], encoder: string): boolean =>+ codecs.some((codec) => canonicalCodec(codec) === canonicalCodec(encoder));++// converter/format.rs `preferred_video_encoder` (codec pick)+export const preferredVideoCodec = (format: string): string | null =>+ codecSupportFor(format)?.video[0] ?? null;++// converter/format.rs `preferred_audio_encoder`+export const preferredAudioEncoder = (format: string): string | null => {+ const codec = codecSupportFor(format)?.audio[0];+ return codec ? encoderFor(codec) : null;+};++// converter/format.rs `default_encoder_for_codec`+export const encoderFor = (codec: string): string => {+ switch (codec.toLowerCase()) {+ case "h264":+ return "libx264";+ case "hevc":+ return "libx265";+ case "vp8":+ return "libvpx";+ case "vp9":+ return "libvpx-vp9";+ case "theora":+ return "libtheora";+ case "prores":+ return "prores_ks";+ case "webp":+ return "libwebp";+ case "flv1":+ return "flv";+ case "mp3":+ return "libmp3lame";+ case "vorbis":+ return "libvorbis";+ case "opus":+ return "libopus";+ case "speex":+ return "libspeex";+ default:+ return codec;+ }+};++// converter/speed.rs `ConversionSpeed::to_args` — encoder preset table+// (0 = fastest, 5 = slowest)+const encoderPreset = (+ encoder: string,+ level: number,+): [string, string] | null => {+ switch (encoder) {+ case "libx264":+ case "libx265":+ return [+ "-preset",+ ["ultrafast", "fast", "medium", "slow", "slower", "veryslow"][+ level+ ],+ ];+ case "libvpx":+ case "libvpx-vp9":+ return ["-cpu-used", ["8", "6", "4", "2", "1", "0"][level]];+ default:+ return null;+ }+};++// converter/speed.rs `ConversionSpeed::to_args`+export const speedArgs = (+ level: number,+ encoder: string,+ toFormat: string,+ bitrate: number,+): string[] => {+ if (encoder === "copy") return [];++ const args: string[] = [];+ const preset = encoderPreset(encoder, level);+ if (preset) args.push(...preset);++ if (normalize(toFormat) === "webp" && encoder === "libwebp")+ args.push("-lossless", level >= 3 ? "1" : "0");++ if (normalize(toFormat) !== "gif") args.push("-b:v", String(bitrate));++ return args;+};++// converter/job.rs `Job::bitrate`+// resolution-based default bitrate, capped by probe+export const targetBitrate = (+ width: number,+ height: number,+ probedBitrate: number | null,+): number => {+ const fallback = (() => {+ if (width >= 3840 || height >= 2160) return 30_000_000;+ if (width >= 2560 || height >= 1440) return 14_000_000;+ if (width >= 1920 || height >= 1080) return 7_000_000;+ if (width >= 1280 || height >= 720) return 4_000_000;+ return 1_500_000;+ })();++ if (probedBitrate && probedBitrate > 0)+ return Math.min(probedBitrate, fallback);+ return fallback;+};++// constraints stuff (port of vertd's `converter/constraint.rs`)++export type Constraint<T> =+ { kind: "cap"; value: T } | { kind: "exact"; value: T };++export interface FormatConstraint {+ videoBitrate?: Constraint<number>;+ resolution?: Constraint<[number, number]>;+ fps?: Constraint<number>;+ audioBitrate?: Constraint<number>;+ audioSampleRate?: Constraint<number>;+ audioChannels?: Constraint<number>;+ dynamicAudioBlockSize?: boolean;+}++const cap = <T>(value: T): Constraint<T> => ({ kind: "cap", value });+const exact = <T>(value: T): Constraint<T> => ({ kind: "exact", value });++// converter/constraint.rs `FormatConstraint::for_format`+// prettier-ignore+export const constraintFor = (format: string): FormatConstraint | null => {+ switch (normalize(format)) {+ case "amv":+ return {+ videoBitrate: cap(384_000),+ resolution: cap([320, 240]),+ fps: exact(30),+ audioBitrate: cap(32_000),+ audioSampleRate: exact(22_050),+ audioChannels: exact(1),+ dynamicAudioBlockSize: true,+ };+ case "3gp":+ case "3g2":+ return {+ videoBitrate: cap(512_000),+ resolution: cap([320, 240]),+ fps: exact(30),+ audioBitrate: cap(16_000),+ audioSampleRate: exact(22_050),+ audioChannels: exact(2),+ };+ case "swf":+ return {+ videoBitrate: cap(800_000),+ resolution: cap([640, 480]),+ fps: exact(30),+ audioBitrate: cap(128_000),+ audioSampleRate: exact(22_050),+ };+ case "asf":+ case "wmv":+ return {+ videoBitrate: cap(1_500_000),+ resolution: cap([640, 480]),+ fps: exact(30),+ audioBitrate: cap(128_000),+ audioSampleRate: exact(44_100),+ audioChannels: exact(2),+ };+ case "mpeg":+ case "mpg":+ case "vob":+ return {+ videoBitrate: cap(2_000_000),+ resolution: cap([720, 576]),+ fps: exact(30),+ audioBitrate: cap(192_000),+ audioSampleRate: exact(48_000),+ };+ case "mxf":+ return {+ audioSampleRate: exact(48_000),+ };+ case "gxf":+ return {+ resolution: exact([720, 576]),+ audioSampleRate: exact(48_000),+ audioChannels: exact(1),+ };+ default:+ return null;+ }+};++export interface AppliedConstraint {+ bitrate: number;+ fps: number;+ requiresVideoEncoding: boolean;+ requiresAudioEncoding: boolean;+ args: string[];+ extraArgs: string[];+}++// converter/constraint.rs `FormatConstraint::apply`+export const applyConstraint = (+ constraint: FormatConstraint | null,+ bitrate: number,+ fps: number,+ resolution: [number, number],+ autoVideoBitrate: boolean,+ autoFps: boolean,+ autoResolution: boolean,+ autoAudioBitrate: boolean,+ autoSampleRate: boolean,+): AppliedConstraint => {+ const applied: AppliedConstraint = {+ bitrate,+ fps,+ requiresVideoEncoding: false,+ requiresAudioEncoding: false,+ args: [],+ extraArgs: [],+ };+ if (!constraint) return applied;++ if (autoVideoBitrate && constraint.videoBitrate) {+ const { kind, value } = constraint.videoBitrate;+ if (+ (kind === "cap" && bitrate > value) ||+ (kind === "exact" && bitrate !== value)+ ) {+ applied.bitrate = value;+ applied.requiresVideoEncoding = true;+ }+ }++ if (autoFps && constraint.fps) {+ const { kind, value } = constraint.fps;+ if ((kind === "cap" && fps > value) || kind === "exact") {+ applied.fps = value;+ applied.args.push("-r", String(value));+ applied.requiresVideoEncoding = true;+ }+ }++ if (autoResolution && constraint.resolution) {+ const { kind, value } = constraint.resolution;+ const [w, h] = value;+ if (kind === "cap") {+ if (!(resolution[0] <= w && resolution[1] <= h)) {+ applied.args.push(+ "-vf",+ `scale='min(${w},iw)':'min(${h},ih)':force_original_aspect_ratio=decrease:force_divisible_by=2`,+ );+ applied.requiresVideoEncoding = true;+ }+ } else if (!(resolution[0] === w && resolution[1] === h)) {+ applied.args.push("-vf", `scale=${w}:${h}`);+ applied.requiresVideoEncoding = true;+ }+ }++ if (autoAudioBitrate && constraint.audioBitrate)+ applied.args.push("-b:a", String(constraint.audioBitrate.value));++ if (autoSampleRate && constraint.audioSampleRate)+ applied.args.push("-ar", String(constraint.audioSampleRate.value));++ if (constraint.audioChannels) {+ applied.args.push("-ac", String(constraint.audioChannels.value));+ applied.requiresAudioEncoding = true;+ }++ if (constraint.dynamicAudioBlockSize) {+ const effectiveFps = Math.max(1, applied.fps);+ const effectiveSampleRate = constraint.audioSampleRate?.value ?? 22_050;+ const blockSize = Math.max(+ 1,+ Math.floor(+ (effectiveSampleRate + Math.floor(effectiveFps / 2)) /+ effectiveFps,+ ),+ );+ applied.args.push("-block_size", String(blockSize));+ applied.requiresAudioEncoding = true;+ }++ return applied;+};diff --git a/src/lib/converters/ffmpeg/video/ffmpeg.video.probe.ts b/src/lib/converters/ffmpeg/video/ffmpeg.video.probe.tsnew file mode 100644index 0000000..45da379--- /dev/null+++ b/src/lib/converters/ffmpeg/video/ffmpeg.video.probe.ts@@ -0,0 +1,151 @@+// ffprobe helpers, ported from `converter/job.rs++import type { FFmpeg } from "@ffmpeg/ffmpeg";++export interface VideoStreamProbe {+ index: number;+ codec_name: string;+ width: number;+ height: number;+ pix_fmt: string;+ r_frame_rate: string;+ bit_rate?: string;+ disposition?: { attached_pic?: number };+}++export interface AudioStreamProbe {+ index: number;+ codec_name: string;+}++export interface VideoMetadata {+ streams: VideoStreamProbe[];+ durationSecs: number | null;+}++interface StreamsResponse<T> {+ streams?: T[];+ format?: { duration?: string };+}++// `-show_entries` list used by `Job::video_metadata` in converter/job.rs+const VIDEO_ENTRIES =+ "stream=index,codec_name,width,height,pix_fmt,r_frame_rate,bit_rate:stream_disposition=attached_pic:format=duration";++// converter/job.rs `parse_fps`+// parse fps which could be "30", "29.97" or "30000/1001"+export const parseFps = (value: string): number | null => {+ const trimmed = value.trim();+ if (!trimmed) return null;++ const [numerator, denominator] = trimmed.split("/");+ const num = Number(numerator);+ if (!Number.isFinite(num)) return null;++ if (denominator === undefined) return Math.round(num);++ const den = Number(denominator);+ if (!Number.isFinite(den) || den === 0) return null;+ return Math.round(num / den);+};++// converter/job.rs `run_ffprobe` + `validate_ffprobe_output`+const readJson = async <T>(+ ffmpeg: FFmpeg,+ inputArgs: string[],+ entries: string,+ selectStream: "v" | "a",+ path: string,+ probeFile: string,+): Promise<StreamsResponse<T> | null> => {+ const args = [+ "-v",+ "error",+ ...inputArgs,+ "-select_streams",+ selectStream,+ "-show_entries",+ entries,+ "-of",+ "json",+ path,+ "-o",+ probeFile,+ ];++ try {+ // ffprobe in ffmpeg-wasm always returns -1 even on success, so rely on the JSON output instead of the return code+ await ffmpeg.ffprobe(args);++ const raw = (await ffmpeg.readFile(probeFile, "utf8")) as string;+ if (!raw.trim()) return null;+ return JSON.parse(raw) as StreamsResponse<T>;+ } catch {+ return null;+ } finally {+ await ffmpeg.deleteFile(probeFile).catch(() => {});+ }+};++// converter/job.rs `Job::video_metadata`+export const probeVideo = async (+ ffmpeg: FFmpeg,+ path: string,+ inputArgs: string[] = [],+): Promise<VideoMetadata> => {+ const probe = await readJson<VideoStreamProbe>(+ ffmpeg,+ inputArgs,+ VIDEO_ENTRIES,+ "v",+ path,+ "probe-v.json",+ );++ const durationSecs = probe?.format?.duration+ ? (() => {+ const parsed = Number(probe.format?.duration);+ return Number.isFinite(parsed) && parsed > 0 ? parsed : null;+ })()+ : null;++ return { streams: probe?.streams ?? [], durationSecs };+};++// converter/job.rs `Job::audio_streams_probe`+export const probeAudioStreams = async (+ ffmpeg: FFmpeg,+ path: string,+ inputArgs: string[] = [],+): Promise<AudioStreamProbe[]> => {+ const probe = await readJson<AudioStreamProbe>(+ ffmpeg,+ inputArgs,+ "stream=index,codec_name",+ "a",+ path,+ "probe-a.json",+ );+ return probe?.streams ?? [];+};++// converter/job.rs `VideoProbe::is_attached_picture`+export const isAttachedPicture = (stream: VideoStreamProbe): boolean =>+ (stream.disposition?.attached_pic ?? 0) !== 0;++// converter/job.rs `primary_video_stream`+// first non-attached-picture video stream, falling back to the first stream+export const primaryVideoStream = (+ streams: VideoStreamProbe[],+): VideoStreamProbe | null =>+ streams.find((stream) => !isAttachedPicture(stream)) ?? streams[0] ?? null;++// converter/job.rs `video_stream_indices`+// all mapped video streams except attached pictures, falling back to the first+export const videoStreamIndices = (streams: VideoStreamProbe[]): number[] => {+ const indices = streams+ .filter((stream) => !isAttachedPicture(stream))+ .map((stream) => stream.index);+ if (indices.length) return indices;+ return [streams[0]?.index ?? 0];+};diff --git a/src/lib/converters/ffmpeg/video/ffmpeg.video.svelte.ts b/src/lib/converters/ffmpeg/video/ffmpeg.video.svelte.tsnew file mode 100644index 0000000..ee6d7a0--- /dev/null+++ b/src/lib/converters/ffmpeg/video/ffmpeg.video.svelte.ts@@ -0,0 +1,696 @@+import type { ConversionSpeed } from "#lib/converters/vertd/vertd.svelte";+import { m } from "#lib/paraglide/messages";+import { Settings } from "#lib/sections/settings/index.svelte";+import { VertFile } from "#lib/types";+import type {+ ConversionSettings,+ 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 { animatedImageFormats } from "../ffmpeg.codecs";+import { buildImageSequenceCommand } from "./ffmpeg.animated";+import {+ applyConstraint,+ codecSupportFor,+ constraintFor,+ encoderFor,+ preferredAudioEncoder,+ preferredVideoCodec,+ speedArgs,+ supportsCodec,+ targetBitrate,+} from "./ffmpeg.video.codecs";+import {+ parseFps,+ primaryVideoStream,+ probeAudioStreams,+ probeVideo,+ videoStreamIndices,+} from "./ffmpeg.video.probe";++const normalize = (format: string) => format.replace(/^\./, "").toLowerCase();++// format.rs `ConverterFormat::supports_single_video_stream`+// containers that can only carry a single video stream+const singleVideoStreamFormats = ["gif", "amv", "swf", "h264", "webp", "apng"];++// format.rs (inside) `to_args`+// formats that can't be encoded in to+const cantEncode = ["rm", "rmvb"];++// format.rs `ConverterFormat::input_format_args`+// input args for specific source formats+const inputFormatArgs = (format: string): string[] =>+ ["mts", "ts", "flv", "nut"].includes(format) ? ["-fflags", "+genpts"] : [];++// format.rs `ConverterFormat::output_format_args`+// output args for specific target formats+const outputFormatArgs = (format: string): string[] => {+ switch (format) {+ case "ogx":+ return ["-f", "ogg"];+ case "divx":+ return ["-f", "avi"];+ case "mxf":+ return ["-timecode", "00:00:00:00", "-g", "128"];+ default:+ return [];+ }+};++const SPEED_ORDER: ConversionSpeed[] = [+ "verySlow",+ "slower",+ "slow",+ "medium",+ "fast",+ "ultraFast",+];++const speedRangeToLevel = (value: number) => 5 - value;+const speedToRange = (speed: ConversionSpeed) =>+ Math.max(0, SPEED_ORDER.indexOf(speed));++const isAuto = (value: unknown): boolean =>+ value === undefined || value === null || value === "" || value === "auto";++const customValue = (value: unknown): string | null =>+ isAuto(value) ? null : String(value);++export class FFmpegVideoConverter extends BaseFFmpegConverter {+ public name = "ffmpeg-video";+ public ready = $state(false);++ public supportedFormats = applyPriorities(+ "ffmpeg-video",+ videoFormats.map(+ (f) => new FormatInfo(f, true, !cantEncode.includes(f), true),+ ),+ );++ constructor() {+ super();+ if (!browser) return;+ this.log(`created converter`);+ }++ public async getAvailableSettings(+ input: VertFile,+ ): Promise<SettingCategories> {+ const toFormat = normalize(input.to);+ const support = codecSupportFor(toFormat);++ const speedOptions = [+ m["convert.settings.video.local_speed.very_slow"](),+ m["convert.settings.video.local_speed.slower"](),+ m["convert.settings.video.local_speed.slow"](),+ m["convert.settings.video.local_speed.medium"](),+ m["convert.settings.video.local_speed.fast"](),+ m["convert.settings.video.local_speed.ultra_fast"](),+ ];++ const speed: SettingDefinition = {+ key: "ffmpegVideoSpeed",+ label: m["convert.settings.video.local_speed.title"](),+ description: m["convert.settings.video.local_speed.description"](),+ type: "range",+ min: 0,+ max: speedOptions.length - 1,+ step: 1,+ default: speedToRange(Settings.instance.settings.ffmpegVideoSpeed),+ options: speedOptions.map((label, value) => ({ value, label })),+ forceFullWidth: true,+ };++ const fps: SettingDefinition = {+ key: "fps",+ label: m["convert.settings.video.fps.label"](),+ type: "text",+ default: "",+ placeholder: m["convert.settings.video.fps.placeholder"](),+ };++ const resolution: SettingDefinition = {+ key: "resolution",+ label: m["convert.settings.video.resolution.label"](),+ type: "text",+ default: "",+ placeholder: m["convert.settings.video.resolution.placeholder"](),+ };++ const metadata: SettingDefinition = {+ key: "metadata",+ label: m["convert.settings.common.metadata"](),+ type: "boolean",+ default: Settings.instance.settings.metadata,+ };++ if (animatedImageFormats.includes(toFormat))+ return { Video: [speed, fps, resolution], General: [metadata] };++ const videoCodec: SettingDefinition = {+ key: "videoCodec",+ label: m["convert.settings.video.codec.video"](),+ type: "select",+ default: "auto",+ options: [+ { value: "auto", label: m["convert.settings.common.auto"]() },+ ...(support?.video ?? []).map((codec) => ({+ value: encoderFor(codec),+ label: codec,+ })),+ ],+ };++ const videoBitrate: SettingDefinition = {+ key: "videoBitrate",+ label: m["convert.settings.video.bitrate.video"](),+ type: "text",+ default: "",+ placeholder:+ m["convert.settings.video.bitrate.video_placeholder"](),+ };++ const audioCodec: SettingDefinition = {+ key: "audioCodec",+ label: m["convert.settings.video.codec.audio"](),+ type: "select",+ default: "auto",+ options: [+ { value: "auto", label: m["convert.settings.common.auto"]() },+ ...(support?.audio ?? []).map((codec) => ({+ value: encoderFor(codec),+ label: codec,+ })),+ ],+ };++ const audioBitrate: SettingDefinition = {+ key: "audioBitrate",+ label: m["convert.settings.video.bitrate.audio"](),+ type: "text",+ default: "",+ placeholder:+ m["convert.settings.video.bitrate.audio_placeholder"](),+ };++ const audioChannels: SettingDefinition = {+ key: "audioChannels",+ label: m["convert.settings.video.audioChannels.label"](),+ type: "text",+ default: "",+ placeholder:+ m["convert.settings.video.audioChannels.placeholder"](),+ };++ const sampleRate: SettingDefinition = {+ key: "sampleRate",+ label: m["convert.settings.audio.sample_rate.label"](),+ type: "text",+ default: "",+ placeholder: m["convert.settings.audio.sample_rate.placeholder"](),+ };++ return {+ Video: [speed, videoCodec, videoBitrate, fps, resolution],+ Audio: [audioCodec, audioBitrate, audioChannels, sampleRate],+ General: [metadata],+ };+ }++ 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+ ? { ...settings }+ : { ...(await this.getDefaultSettings(input)), ...settings };++ await this.ensureCore();++ 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;+ if (+ msg.includes("Error initializing output stream") ||+ msg.includes("Error while opening encoder") ||+ msg.includes("Error while opening decoder") ||+ msg.includes("Conversion failed!") ||+ (msg.includes("Error") && msg.includes("stream"))+ ) {+ if (!conversionError) conversionError = msg;+ }+ };+ ffmpeg.on("log", errorListener);++ const logListener = (l: { message: string }) => this.log(l.message);+ ffmpeg.on("log", logListener);++ try {+ const isImageSequence =+ input.isZip() && settings.imageSequence === true;++ let command: string[];+ if (isImageSequence) {+ command = await this.buildImageSequenceCommand(+ ffmpeg,+ input,+ to,+ conversionSettings,+ );+ } else {+ const buf = new Uint8Array(await input.file.arrayBuffer());+ // keep the extension so ffmpeg/ffprobe can detect the container+ await ffmpeg.writeFile(input.name, buf);+ this.log(+ `wrote ${input.name} (${input.id}) to ffmpeg virtual fs`,+ );+ command = await this.buildVideoCommand(+ ffmpeg,+ input,+ to,+ conversionSettings,+ );+ }++ 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;+ 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);+ ffmpeg.off("log", errorListener);+ ffmpeg.off("log", logListener);+ this.activeConversions.delete(input.id);+ ffmpeg.terminate();+ }+ }++ // converter/format.rs `Conversion::to_args` (minus GPU paths)+ private async buildVideoCommand(+ ffmpeg: FFmpeg,+ input: VertFile,+ to: string,+ settings: ConversionSettings,+ ): Promise<string[]> {+ const from = normalize(input.from);+ const toFormat = normalize(to);+ const fromSupport = codecSupportFor(from);+ const toSupport = codecSupportFor(toFormat);+ const keepMetadata = settings.metadata;++ const metadataArgs = keepMetadata+ ? ["-map_metadata", "0", "-map_chapters", "0"]+ : ["-map_metadata", "-1", "-map_chapters", "-1"];++ const [video, audioStreams] = await Promise.all([+ probeVideo(ffmpeg, input.name),+ probeAudioStreams(ffmpeg, input.name),+ ]);+ const primary = primaryVideoStream(video.streams);+ if (!primary)+ this.log(+ `ffprobe returned no video metadata for ${input.name} (${input.id}), falling back to defaults`,+ );+ const pixFmt = primary?.pix_fmt ?? "";+ const inputCodec = (primary?.codec_name ?? "").toLowerCase();+ const hasUsableAudio = audioStreams.length > 0;+ const probedBitrate = primary?.bit_rate+ ? Number(primary.bit_rate) || null+ : null;+ const fps = Math.min(parseFps(primary?.r_frame_rate ?? "") ?? 30, 24);+ const width = primary?.width ?? 0;+ const height = primary?.height ?? 0;++ const autoVideoBitrate = isAuto(settings.videoBitrate);+ const autoFps = isAuto(settings.fps);+ const autoResolution = isAuto(settings.resolution);+ const autoAudioBitrate = isAuto(settings.audioBitrate);+ const autoSampleRate = isAuto(settings.sampleRate);+ const autoVideoCodec = isAuto(settings.videoCodec);+ const autoAudioCodec = isAuto(settings.audioCodec);++ const effectiveBitrate = targetBitrate(width, height, probedBitrate);+ const constraint = constraintFor(toFormat);+ const applied = applyConstraint(+ constraint,+ effectiveBitrate,+ fps,+ [width, height],+ autoVideoBitrate,+ autoFps,+ autoResolution,+ autoAudioBitrate,+ autoSampleRate,+ );++ const hasAlpha =+ /^(yuva|gbrap|ya|rgba|bgra)/.test(pixFmt) ||+ ["argb", "abgr", "ayuv", "vuya"].includes(pixFmt);+ const flattenAlpha =+ hasAlpha && !animatedImageFormats.includes(toFormat);++ const supportsRemux =+ !!fromSupport && !!toSupport && toFormat !== "gif";+ const requiresVideoEncoding =+ !autoVideoCodec ||+ !autoVideoBitrate ||+ !autoFps ||+ !autoResolution ||+ applied.requiresVideoEncoding;+ const requiresAudioEncoding =+ !autoAudioCodec ||+ !autoAudioBitrate ||+ !autoSampleRate ||+ !!customValue(settings.audioChannels) ||+ applied.requiresAudioEncoding;++ const canRemuxVideo =+ supportsRemux &&+ !requiresVideoEncoding &&+ !flattenAlpha &&+ supportsCodec(fromSupport!.video, inputCodec) &&+ supportsCodec(toSupport!.video, inputCodec);++ const result: string[] = [];++ if (canRemuxVideo) {+ // format.rs `Conversion::remux_args`+ this.log(+ `remuxing ${input.from} to ${to} for ${input.name} (${input.id})`,+ );+ result.push("-map", "0:v:0");+ if (["mts", "ts"].includes(toFormat))+ result.push("-avoid_negative_ts", "make_zero");+ result.push("-c:v", "copy", "-strict", "experimental");+ } else {+ // format.rs `to_args`+ switch (toFormat) {+ case "gif": {+ const gifWidth = width || 320;+ result.push(+ "-filter_complex",+ `[0:v:0]fps=${applied.fps},scale=${gifWidth}:-1:flags=lanczos,split[s0][s1];[s0]palettegen=max_colors=64[p];[s1][p]paletteuse=dither=bayer[gif]`,+ "-map",+ "[gif]",+ "-loop",+ "0",+ "-strict",+ "experimental",+ );+ break;+ }+ case "swf":+ result.push("-f", "swf", "-strict", "experimental");+ break;+ case "amv":+ if (!hasUsableAudio) {+ result.push(+ "-f",+ "lavfi",+ "-i",+ "anullsrc=channel_layout=mono:sample_rate=22050",+ "-map",+ "0:v:0",+ "-map",+ "1:a:0",+ "-shortest",+ "-strict",+ "experimental",+ );+ } else {+ result.push(+ "-map",+ "0:v:0",+ "-map",+ "0:a:0",+ "-strict",+ "experimental",+ );+ }+ break;+ case "rm":+ case "rmvb":+ throw new Error(+ m["workers.errors.ffmpeg_video_unsupported"]({+ to: `.${toFormat}`,+ }),+ );+ default:+ result.push("-strict", "experimental");+ }++ // map every video stream (excluding cover art), the exclusions only support a single video stream+ if (!["gif", "amv"].includes(toFormat)) {+ let indices = videoStreamIndices(video.streams);+ if (singleVideoStreamFormats.includes(toFormat))+ indices = indices.slice(0, 1);+ for (const index of indices) result.push("-map", `0:${index}`);+ }++ // auto video codec+ if (autoVideoCodec) {+ const preferred = preferredVideoCodec(toFormat);+ if (preferred)+ insertCodecArg(result, "-c:v", encoderFor(preferred));+ }+ }++ // custom fps+ const fpsValue = customValue(settings.fps);+ if (fpsValue && Number.isFinite(Number(fpsValue)))+ result.push("-r", String(Math.trunc(Number(fpsValue))));++ // custom resolution (gif is handled by the palette filter)+ const resolutionValue = customValue(settings.resolution);+ if (resolutionValue && toFormat !== "gif") {+ const [w, h] = resolutionValue.split("x");+ if (Number(w) > 0 && Number(h) > 0)+ appendVideoFilter(result, `scale=${w}:${h}`);+ }++ // custom audio settings+ const audioBitrateValue = customValue(settings.audioBitrate);+ if (audioBitrateValue) result.push("-b:a", `${audioBitrateValue}k`);+ const audioChannelsValue = customValue(settings.audioChannels);+ if (audioChannelsValue) result.push("-ac", audioChannelsValue);++ // custom video/audio codecs+ const videoCodecValue = customValue(settings.videoCodec);+ if (videoCodecValue) insertCodecArg(result, "-c:v", videoCodecValue);+ const audioCodecValue = customValue(settings.audioCodec);+ if (audioCodecValue) insertCodecArg(result, "-c:a", audioCodecValue);++ // custom sample rate+ const sampleRateValue = customValue(settings.sampleRate);+ if (sampleRateValue) result.push("-ar", sampleRateValue);++ // container constraint args+ appendConstraintArgs(result, applied.args);++ if (!canRemuxVideo) {+ // resolve the final video encoder & apply speed presets+ const videoEncoder = lastCodecValue(result, "-c:v") ?? "";+ const userVideoBitrate = customValue(settings.videoBitrate);+ const videoBitrate = userVideoBitrate+ ? Number(userVideoBitrate) * 1000+ : applied.bitrate;++ const level = speedRangeToLevel(+ Number(settings.ffmpegVideoSpeed ?? 2),+ );+ result.push(+ ...speedArgs(level, videoEncoder, toFormat, videoBitrate),+ );+ }++ // audio streams+ const supportsAudio = !!toSupport && toSupport.audio.length > 0;+ if (!supportsAudio) {+ result.push("-an");+ } else {+ const audioCodec =+ customValue(settings.audioCodec) ??+ preferredAudioEncoder(toFormat) ??+ "";+ for (const [outputIndex, stream] of audioStreams.entries()) {+ // amv/swf only allow a single audio stream+ if (["amv", "swf"].includes(toFormat) && outputIndex > 0) break;+ if (toFormat !== "amv")+ result.push("-map", `0:${stream.index}`);++ const copy =+ !requiresAudioEncoding &&+ supportsCodec(toSupport.audio, stream.codec_name);+ const encoder = copy ? "copy" : audioCodec;+ if (!encoder)+ throw new Error(+ m["workers.errors.ffmpeg_video_no_audio_encoder"]({+ to: `.${toFormat}`,+ }),+ );+ result.push(`-c:a:${outputIndex}`, encoder);++ // webm + opus needs to be stereo+ if (+ !copy &&+ toFormat === "webm" &&+ ["opus", "libopus"].includes(encoder) &&+ isAuto(settings.audioChannels)+ )+ result.push(`-ac:a:${outputIndex}`, "2");+ }++ // amv requires an audio track+ if (toFormat === "amv" && !hasUsableAudio)+ result.push("-c:a:0", audioCodec);+ }++ // flatten alpha onto black for non-alpha containers+ if (flattenAlpha)+ appendVideoFilter(+ result,+ "format=rgba,geq=r='r(X,Y)*alpha(X,Y)/255':g='g(X,Y)*alpha(X,Y)/255':b='b(X,Y)*alpha(X,Y)/255':a=255,format=yuv420p",+ );++ this.log(+ `conversion plan for ${input.name} (${input.id}): remux=${canRemuxVideo}, keepMetadata=${keepMetadata}, hasUsableAudio=${hasUsableAudio}`,+ );++ return [+ "-y",+ "-hide_banner",+ ...inputFormatArgs(from),+ "-i",+ input.name,+ ...result,+ ...metadataArgs,+ ...outputFormatArgs(toFormat),+ "output" + to,+ ];+ }++ private async buildImageSequenceCommand(+ ffmpeg: FFmpeg,+ input: VertFile,+ to: string,+ settings: ConversionSettings,+ ): Promise<string[]> {+ const toFormat = normalize(to);+ this.log(+ `converting image sequence ${input.name} (${input.id}) to ${to}`,+ );++ const { extractZip } = await import("#lib/util/file");+ const entries = (await extractZip(input.file)).sort((a, b) =>+ a.filename.localeCompare(b.filename, undefined, {+ numeric: true,+ sensitivity: "base",+ }),+ );++ if (!entries.length) throw new Error("No images found in zip archive");++ const imageFiles: Array<{ name: string }> = [];+ for (const [index, entry] of entries.entries()) {+ const fileName = entry.filename.split("/").pop() ?? entry.filename;+ const ext = fileName.split(".").pop()?.toLowerCase();+ if (!ext) continue;++ const paddedName = `img${String(index + 1).padStart(5, "0")}.${ext}`;+ await ffmpeg.writeFile(paddedName, entry.data);+ imageFiles.push({ name: paddedName });+ }++ if (!imageFiles.length)+ throw new Error("No images found in zip archive");++ const listContent = imageFiles+ .map(+ (image) =>+ `file '${image.name}'\nduration ${1 / (settings.imageSequenceFPS || 15)}`,+ )+ .join("\n");+ await ffmpeg.writeFile(+ "frames.txt",+ `${listContent}\nfile '${imageFiles[imageFiles.length - 1].name}'\n`,+ );+ this.log(`wrote ${imageFiles.length} images to ffmpeg virtual fs`);++ return [+ "-y",+ "-hide_banner",+ ...buildImageSequenceCommand(toFormat, settings, false),+ ];+ }+}++// converter/format.rs `Conversion::insert_codec_arg`+const insertCodecArg = (args: string[], flag: string, codec: string): void => {+ const index = args.indexOf(flag);+ if (index === -1) {+ args.push(flag, codec);+ return;+ }+ args[index + 1] = codec;+};++// converter/format.rs `Conversion::last_codec_value`+const lastCodecValue = (args: string[], flag: string): string | null => {+ for (let i = args.length - 2; i >= 0; i--)+ if (args[i] === flag) return args[i + 1];+ return null;+};++// converter/format.rs `Conversion::append_video_filter`+const appendVideoFilter = (args: string[], filter: string): void => {+ const index = args.indexOf("-vf");+ if (index !== -1) {+ args[index + 1] = `${args[index + 1]},${filter}`;+ return;+ }+ args.push("-vf", filter);+};++// converter/format.rs `Conversion::append_constraint_args`+const appendConstraintArgs = (args: string[], constraints: string[]): void => {+ for (let i = 0; i < constraints.length; i++) {+ const arg = constraints[i];+ if (arg === "-vf") {+ appendVideoFilter(args, constraints[++i]);+ continue;+ }+ args.push(arg);+ }+};diff --git a/src/lib/converters/index.ts b/src/lib/converters/index.tsindex 644e72c..f0afdf8 100644--- a/src/lib/converters/index.ts+++ b/src/lib/converters/index.ts@@ -1,7 +1,8 @@import type { Categories } from "#lib/types";import { DISABLE_ALL_EXTERNAL_REQUESTS } from "#lib/util/consts";import type { Converter, WorkerStatus } from "./converter.svelte";-import { FFmpegConverter } from "./ffmpeg/ffmpeg.svelte";+import { FFmpegConverter } from "./ffmpeg/audio/ffmpeg.audio.svelte";+import { FFmpegVideoConverter } from "./ffmpeg/video/ffmpeg.video.svelte";import { MagickConverter } from "./magick/magick.svelte";import { MediabunnyConverter } from "./mediabunny/mediabunny.svelte";import { PandocConverter } from "./pandoc/pandoc.svelte";@@ -21,6 +22,7 @@ const getConverters = (): Converter[] => {new SpessaSynthConverter("soundfont"),new PandocConverter(),new MediabunnyConverter(),+ new FFmpegVideoConverter(),];if (!DISABLE_ALL_EXTERNAL_REQUESTS) converters.push(new VertdConverter());@@ -31,7 +33,7 @@ const getConverters = (): Converter[] => {export const converters = getConverters();export const converterCategories = {image: ["libvips", "imagemagick", "vectorizer"],- video: ["mediabunny", "vertd"],+ video: ["mediabunny", "vertd", "ffmpeg-video"],audio: ["ffmpeg", "spessasynth-midi", "spessasynth-soundfont"],doc: ["pandoc"],};diff --git a/src/lib/converters/priority.ts b/src/lib/converters/priority.tsindex 9e10549..c88c358 100644--- a/src/lib/converters/priority.ts+++ b/src/lib/converters/priority.ts@@ -25,21 +25,42 @@ export const FORMAT_ENGINES: Record<string, string[]> = {pnm: ["libvips", "imagemagick"],// formats that are both image and video (animated formats) — image engines first, then video- webp: ["libvips", "imagemagick", "vertd"],- gif: ["libvips", "imagemagick", "vertd"],+ webp: ["libvips", "imagemagick", "vertd", "ffmpeg-video"],+ gif: ["libvips", "imagemagick", "vertd", "ffmpeg-video"],+ apng: ["vertd", "ffmpeg-video"],- // video - local supported- mp4: ["mediabunny", "vertd"],- m4v: ["mediabunny", "vertd"],- mkv: ["mediabunny", "vertd"],- webm: ["mediabunny", "vertd"],- mov: ["mediabunny", "vertd"],- f4v: ["mediabunny", "vertd"],- "3gp": ["mediabunny", "vertd"],- "3g2": ["mediabunny", "vertd"],- mts: ["mediabunny", "vertd"],- m2ts: ["mediabunny", "vertd"],- ts: ["mediabunny", "vertd"],+ // video - local supported (ffmpeg-wasm is slow, even with multithreading, so it's last)+ mp4: ["mediabunny", "vertd", "ffmpeg-video"],+ m4v: ["mediabunny", "vertd", "ffmpeg-video"],+ mkv: ["mediabunny", "vertd", "ffmpeg-video"],+ webm: ["mediabunny", "vertd", "ffmpeg-video"],+ mov: ["mediabunny", "vertd", "ffmpeg-video"],+ f4v: ["mediabunny", "vertd", "ffmpeg-video"],+ "3gp": ["mediabunny", "vertd", "ffmpeg-video"],+ "3g2": ["mediabunny", "vertd", "ffmpeg-video"],+ mts: ["mediabunny", "vertd", "ffmpeg-video"],+ m2ts: ["mediabunny", "vertd", "ffmpeg-video"],+ ts: ["mediabunny", "vertd", "ffmpeg-video"],++ // video+ avi: ["vertd", "ffmpeg-video"],+ wmv: ["vertd", "ffmpeg-video"],+ mpg: ["vertd", "ffmpeg-video"],+ mpeg: ["vertd", "ffmpeg-video"],+ flv: ["vertd", "ffmpeg-video"],+ vob: ["vertd", "ffmpeg-video"],+ mxf: ["vertd", "ffmpeg-video"],+ ogv: ["vertd", "ffmpeg-video"],+ ogx: ["vertd", "ffmpeg-video"],+ gxf: ["vertd", "ffmpeg-video"],+ h264: ["vertd", "ffmpeg-video"],+ divx: ["vertd", "ffmpeg-video"],+ swf: ["vertd", "ffmpeg-video"],+ amv: ["vertd", "ffmpeg-video"],+ asf: ["vertd", "ffmpeg-video"],+ nut: ["vertd", "ffmpeg-video"],+ ivf: ["vertd", "ffmpeg-video"],+ y4m: ["vertd", "ffmpeg-video"],};export function priorityFor(converter: string, format: string): number {diff --git a/src/lib/converters/spessasynth/spessasynth.svelte.ts b/src/lib/converters/spessasynth/spessasynth.svelte.tsindex 88d134b..f355048 100644--- a/src/lib/converters/spessasynth/spessasynth.svelte.ts+++ b/src/lib/converters/spessasynth/spessasynth.svelte.ts@@ -135,7 +135,7 @@ export class SpessaSynthConverter extends Converter {worker: Worker,type?: string,timeout = 0,- // eslint-disable-next-line @typescript-eslint/no-explicit-any+ // eslint-disable-next-line @typescript-eslint/no-explicit-any): Promise<any> {return new Promise((resolve, reject) => {let timer: ReturnType<typeof setTimeout> | undefined;diff --git a/src/lib/sections/settings/index.svelte.ts b/src/lib/sections/settings/index.svelte.tsindex 4aa6f1d..1551569 100644--- a/src/lib/sections/settings/index.svelte.ts+++ b/src/lib/sections/settings/index.svelte.ts@@ -24,10 +24,11 @@ export interface ISettings {metadata: boolean;plausible: boolean;vertdURL: string;- vertdSpeed: ConversionSpeed; // videos+ vertdSpeed: ConversionSpeed; // videos (vertd)vertdBlockedHashes: Map<string, Date[]>; // hashes of files blocked from vertd conversionvertdCustomHeaders: string; // custom headers to send to the vertd servermagickQuality: number; // images+ ffmpegVideoSpeed: ConversionSpeed; // videos (local ffmpeg.wasm)}export class Settings {@@ -49,6 +50,7 @@ export class Settings {vertdBlockedHashes: new SvelteMap<string, Date[]>(),vertdCustomHeaders: "",magickQuality: 90,+ ffmpegVideoSpeed: "medium",});public save() {diff --git a/src/lib/store/index.svelte.ts b/src/lib/store/index.svelte.tsindex 194a3bc..a8a6327 100644--- a/src/lib/store/index.svelte.ts+++ b/src/lib/store/index.svelte.ts@@ -103,7 +103,7 @@ class Files {const sequenceMode = file.conversionSettings.imageSequence === true;const candidates = sequenceMode? converters.filter(- (c) => c.name === "ffmpeg" || c.name === "vertd",+ (c) => c.name === "ffmpeg-video" || c.name === "vertd",): converters;@@ -113,8 +113,9 @@ class Files {if (current && candidates.some((c) => c.name === current)) return;const fallback = sequenceMode- ? !file.isLarge() && candidates.some((c) => c.name === "ffmpeg")- ? "ffmpeg"+ ? !file.isLarge() &&+ candidates.some((c) => c.name === "ffmpeg-video")+ ? "ffmpeg-video": (candidates.find((c) => c.name === "vertd")?.name ??candidates[0]?.name): ([...candidates].sort(@@ -359,7 +360,7 @@ class Files {? vf.conversionSettings.imageSequence? converters.filter((c) =>- c.name === "ffmpeg" ||+ c.name === "ffmpeg-video" ||c.name === "vertd",): converters@@ -374,12 +375,12 @@ class Files {vf.sequenceKind === "frameSequence" &&vf.conversionSettings.imageSequence) {- // sequence mode prefers ffmpeg, then falls back to vertd+ // sequence mode prefers local ffmpeg, then falls back to vertdconst has = (name: string) =>vf.converters.some((c) => c.name === name);defaultConverter =- !vf.isLarge() && has("ffmpeg")- ? "ffmpeg"+ !vf.isLarge() && has("ffmpeg-video")+ ? "ffmpeg-video": has("vertd")? "vertd": vf.converters[0].name;diff --git a/src/lib/types/file.svelte.ts b/src/lib/types/file.svelte.tsindex e061031..fd274d5 100644--- a/src/lib/types/file.svelte.ts+++ b/src/lib/types/file.svelte.ts@@ -261,7 +261,7 @@ export class VertFile {return this.converters.filter((c) => {if (this.unavailableConverters[c.name] || !c.isAvailable())return false;- return c.name === "ffmpeg" || c.name === "vertd";+ return c.name === "ffmpeg-video" || c.name === "vertd";});}@@ -413,18 +413,18 @@ export class VertFile {);const candidates = this.converters.filter((c) =>- (c.name === "ffmpeg" || c.name === "vertd") &&+ (c.name === "ffmpeg-video" || c.name === "vertd") &&!this.unavailableConverters[c.name] &&c.isAvailable() &&supported(c),);- // dash + large files go to the server, everything else prefers ffmpeg+ // dash + large files go to the server, everything else prefers local ffmpegconst preference = isDash? ["vertd"]: this.isLarge()- ? ["vertd", "ffmpeg"]- : ["ffmpeg", "vertd"];+ ? ["vertd", "ffmpeg-video"]+ : ["ffmpeg-video", "vertd"];const chosen = this.conversionSettings.converter;const order =chosen && candidates.some((c) => c.name === chosen)diff --git a/src/lib/util/debug.svelte.ts b/src/lib/util/debug.svelte.tsindex ef31c07..c7c07fe 100644--- a/src/lib/util/debug.svelte.ts+++ b/src/lib/util/debug.svelte.ts@@ -81,6 +81,11 @@ export const CONVERTER_META: Record<icon: FilmIcon,accent: "bg-accent-red",},+ "ffmpeg-video": {+ category: "video",+ icon: FilmIcon,+ accent: "bg-accent-purple",+ },vertd: {category: "video",icon: ServerIcon,