Skip to content

armgit / VERT

Public Imported from GitHub
0

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

fix: translate codecs between converters, use canonical/friendly names for codecs

JovannMCbbc497449260
diff --git a/src/lib/components/functional/popups/SettingsModal.svelte b/src/lib/components/functional/popups/SettingsModal.svelte
index 18194f8..bde3ee0 100644
--- a/src/lib/components/functional/popups/SettingsModal.svelte
+++ b/src/lib/components/functional/popups/SettingsModal.svelte
@@ -8,10 +8,12 @@
import type { VertFile } from "#lib/types";
import { effects, files } from "#lib/store/index.svelte";
import { categoryByConverter } from "#lib/converters";
+ import { canonicalCodecName } from "#lib/converters/codec-labels";
import { log, error } from "#lib/util/logger.svelte";
import type {
ConversionSettings,
SettingCategories,
+ SettingDefinition,
} from "#lib/types/conversion-settings";
import clsx from "clsx";
import { animateHeight, duration, fade } from "#lib/util/animation";
@@ -98,6 +100,48 @@
let activeTab = $state("Converter");
let availableCategories = $state<SettingCategories>({});
+ // resolve a value against a setting's options, translating codec aliases (e.g. mediabunny's "avc" is vertd's "h264")
+ const resolveSettingValue = (
+ value: unknown,
+ setting: SettingDefinition,
+ ) => {
+ const options = setting.options ?? [];
+ if (options.some((option) => option.value === value)) return value;
+
+ const match = options.find(
+ (option) =>
+ canonicalCodecName(String(option.value)) ===
+ canonicalCodecName(String(value)),
+ );
+
+ return match?.value ?? setting.default;
+ };
+
+ // drop/translate values that the given settings don't support
+ const sanitizeSettings = (
+ current: ConversionSettings,
+ categories: SettingCategories,
+ ) => {
+ const sanitized = { ...current };
+
+ for (const setting of Object.values(categories).flat()) {
+ if (
+ setting.type !== "select" ||
+ sanitized[setting.key] === undefined
+ )
+ continue;
+
+ const resolved = resolveSettingValue(
+ sanitized[setting.key],
+ setting,
+ );
+ if (resolved === undefined) delete sanitized[setting.key];
+ else sanitized[setting.key] = resolved;
+ }
+
+ return sanitized;
+ };
+
const settingTabs = $derived.by((): SettingCategories => {
// sequences expose only Converter tab (ffmpeg/vertd)
if (targetFile?.sequenceKind) return { Converter: [] };
@@ -148,6 +192,14 @@
if (cancelled) return;
availableCategories = categories;
+ const sanitized = sanitizeSettings(settings, categories);
+ for (const key of Object.keys(settings)) {
+ if (!(key in sanitized)) delete settings[key];
+ }
+ for (const [key, value] of Object.entries(sanitized)) {
+ if (settings[key] !== value) settings[key] = value;
+ }
+
const hasConverterTab = shouldShowConverterTab(currentFile);
if (
(!hasConverterTab && activeTab === "Converter") ||
@@ -226,9 +278,9 @@
.map((setting) => setting.key),
);
const applicableSettings = Object.fromEntries(
- Object.entries(settings).filter(([key]) =>
- supportedKeys.has(key),
- ),
+ Object.entries(
+ sanitizeSettings(settings, categories),
+ ).filter(([key]) => supportedKeys.has(key)),
);
const defaultSettings = Object.fromEntries(
Object.values(categories)
@@ -239,7 +291,11 @@
// apply defaults, then existing settings, then new settings on top
targetFile.conversionSettings = {
...defaultSettings,
- ...targetFile.conversionSettings,
+ // existing settings may come from another converter (e.g. "avc")
+ ...sanitizeSettings(
+ targetFile.conversionSettings,
+ categories,
+ ),
...applicableSettings,
converter: converter.name,
};
@@ -425,14 +481,15 @@
}
: opt,
) || []}
- selected={settings[
- setting.key
- ] ??
- targetFile
- .conversionSettings[
- setting.key
- ] ??
- setting.default}
+ selected={resolveSettingValue(
+ settings[setting.key] ??
+ targetFile
+ .conversionSettings[
+ setting.key
+ ] ??
+ setting.default,
+ setting,
+ )}
style="settings"
onselect={(value) =>
handleSettingChange(
diff --git a/src/lib/converters/codec-labels.ts b/src/lib/converters/codec-labels.ts
new file mode 100644
index 0000000..1076576
--- /dev/null
+++ b/src/lib/converters/codec-labels.ts
@@ -0,0 +1,158 @@
+export interface CodecInfo {
+ name: string; // value to send to the converter, e.g. "libopus"
+ canonical: string; // codec family, e.g. "opus"
+ label: string; // friendly display name, e.g. "Opus"
+}
+
+// aliases -> canonical codec name
+const codecAliases: Record<string, string> = {
+ avc: "h264",
+ x264: "h264",
+ x264rgb: "h264",
+ openh264: "h264",
+ h265: "hevc",
+ x265: "hevc",
+ kvazaar: "hevc",
+ vpx: "vp8",
+ "vpx-vp9": "vp9",
+ webp_anim: "webp",
+ prores_ks: "prores",
+ prores_aw: "prores",
+ mp3lame: "mp3",
+ shine: "mp3",
+};
+
+// canonical codec name -> friendly label
+// only common codecs since vertd returns its own server-side labels
+const codecLabels: Record<string, string> = {
+ // video
+ h264: "H264 (AVC)",
+ hevc: "H265 (HEVC)",
+ vp8: "VP8",
+ vp9: "VP9",
+ av1: "AV1",
+ prores: "Apple ProRes",
+ mpeg4: "MPEG-4 Part 2",
+ mpeg1video: "MPEG-1",
+ mpeg2video: "MPEG-2",
+ mjpeg: "Motion JPEG",
+ dnxhd: "Avid DNxHD",
+ ffv1: "FFV1",
+ dvvideo: "DV",
+ theora: "Theora",
+ flv1: "Sorenson Spark (FLV1)",
+ wmv2: "Windows Media Video 8",
+ apng: "APNG",
+ webp: "WebP",
+ gif: "GIF",
+
+ // audio
+ aac: "AAC",
+ mp3: "MP3",
+ mp2: "MP2",
+ ac3: "AC-3 (Dolby Digital)",
+ eac3: "E-AC-3 (Dolby Digital Plus)",
+ dts: "DTS",
+ opus: "Opus",
+ vorbis: "Vorbis",
+ flac: "FLAC",
+ alac: "ALAC",
+ wmav2: "Windows Media Audio 8",
+};
+
+const pcmPattern = /^pcm[-_]([usf])(\d+)([bl]e)?$/;
+// mediabunny omits the endianness for little-endian pcm, ffmpeg is explicit
+const canonicalPcm = (match: RegExpExecArray): string => {
+ const [, type, bits, endian] = match;
+ return `pcm_${type}${bits}${endian === "be" ? "be" : "le"}`;
+};
+
+const normalize = (codec: string) =>
+ codec.toLowerCase().replace(/^lib/, "").trim();
+
+// canonical name for a codec (e.g. "avc" / "libx264" -> "h264")
+export const canonicalCodecName = (codec: string): string => {
+ const value = normalize(codec);
+
+ const pcm = pcmPattern.exec(value);
+ if (pcm) return canonicalPcm(pcm);
+
+ return codecAliases[value] ?? value;
+};
+
+// common codecs since vertd returns its own server-side labels
+const commonCodecs: Record<"video" | "audio", Set<string>> = {
+ video: new Set([
+ "h264",
+ "hevc",
+ "vp8",
+ "vp9",
+ "av1",
+ "prores",
+ "mpeg4",
+ "mpeg1video",
+ "mpeg2video",
+ "mjpeg",
+ "dnxhd",
+ "ffv1",
+ "theora",
+ "flv1",
+ "wmv2",
+ "h263",
+ "dvvideo",
+ "apng",
+ "webp",
+ "gif",
+ ]),
+ audio: new Set([
+ "aac",
+ "mp3",
+ "mp2",
+ "ac3",
+ "eac3",
+ "dts",
+ "opus",
+ "vorbis",
+ "flac",
+ "alac",
+ "pcm_s16le",
+ "pcm_s24le",
+ "pcm_s32le",
+ "pcm_f32le",
+ ]),
+};
+
+// keep only the common codecs of a type, preserving order.
+// falls back to the full list when a format only has uncommon codecs (e.g. amv)
+export const filterCommonCodecs = (
+ codecs: string[],
+ type: "video" | "audio",
+): string[] => {
+ const common = codecs.filter((codec) =>
+ commonCodecs[type].has(canonicalCodecName(codec)),
+ );
+ return common.length ? common : codecs;
+};
+
+// friendly label for a codec name (e.g. "avc" -> "H264 (AVC)")
+// falls back to the original name for unknown codecs
+export const codecLabel = (codec: string): string => {
+ const canonical = canonicalCodecName(codec);
+ return codecLabels[canonical] ?? codec;
+};
+
+export const toCodecInfo = (codec: CodecInfo | string): CodecInfo => {
+ if (typeof codec !== "string") return codec;
+
+ return {
+ name: codec,
+ canonical: canonicalCodecName(codec),
+ label: codecLabel(codec),
+ };
+};
+
+export const codecOptions = (codecs: (CodecInfo | string)[]) =>
+ codecs.map(toCodecInfo).map((codec) => ({
+ value: codec.name,
+ label: codec.label,
+ }));
diff --git a/src/lib/converters/converter.svelte.ts b/src/lib/converters/converter.svelte.ts
index 3f0869a..dc4f074 100644
--- a/src/lib/converters/converter.svelte.ts
+++ b/src/lib/converters/converter.svelte.ts
@@ -7,6 +7,7 @@ import type {
SettingCategories,
} from "#lib/types/conversion-settings";
import { error, log } from "#lib/util/logger.svelte";
+import { canonicalCodecName, codecLabel } from "./codec-labels";
export type WorkerStatus =
| "idle" // not initialized yet (nothing downloaded)
@@ -161,10 +162,62 @@ export class Converter {
to: string,
settings: ConversionSettings,
): Promise<NormalizedSettings> {
- return {
- settings: { ...settings },
- changes: [],
- };
+ const normalized = { ...settings };
+ const changes: NormalizedSettings["changes"] = [];
+
+ // only codec values need cross-converter translation, so skip the settings
+ // lookup (which may hit the network for vertd) when there are none set
+ const hasCodecValue = Object.entries(normalized).some(
+ ([key, value]) =>
+ key.toLowerCase().endsWith("codec") &&
+ value !== undefined &&
+ value !== null &&
+ value !== "auto",
+ );
+ if (!hasCodecValue) return { settings: normalized, changes };
+
+ let categories: SettingCategories = {};
+ try {
+ categories = await this.getAvailableSettings(input);
+ } catch (err) {
+ this.error(`failed to load settings for normalization: ${err}`);
+ return { settings: normalized, changes };
+ }
+
+ // translate codec values to the canonical name, finding a matching option in the new converter's settings
+ // (e.g. mediabunny's "avc" is vertd's "h264")
+ for (const setting of Object.values(categories).flat()) {
+ if (setting.type !== "select" || !setting.options?.length) continue;
+
+ const value = normalized[setting.key];
+ if (value === undefined || value === null) continue;
+ if (setting.options.some((option) => option.value === value))
+ continue;
+
+ const match = setting.options.find(
+ (option) =>
+ canonicalCodecName(String(option.value)) ===
+ canonicalCodecName(String(value)),
+ );
+ const newValue = match?.value ?? setting.default;
+
+ if (newValue === undefined) {
+ // no equivalent and no default, drop the unknown value
+ delete normalized[setting.key];
+ continue;
+ }
+ if (newValue === value) continue;
+
+ normalized[setting.key] = newValue;
+ changes.push({
+ setting: setting.key,
+ oldValue: codecLabel(String(value)),
+ newValue: codecLabel(String(newValue)),
+ file: input.name,
+ });
+ }
+
+ return { settings: normalized, changes };
}
private startTimeout() {
diff --git a/src/lib/converters/ffmpeg/video/ffmpeg.video.svelte.ts b/src/lib/converters/ffmpeg/video/ffmpeg.video.svelte.ts
index ee6d7a0..b8b67b5 100644
--- a/src/lib/converters/ffmpeg/video/ffmpeg.video.svelte.ts
+++ b/src/lib/converters/ffmpeg/video/ffmpeg.video.svelte.ts
@@ -9,6 +9,7 @@ import type {
} from "#lib/types/conversion-settings";
import { browser } from "$app/env";
import { FFmpeg } from "@ffmpeg/ffmpeg";
+import { codecOptions, filterCommonCodecs } from "../../codec-labels";
import { FormatInfo, formatDuration } from "../../converter.svelte";
import { applyPriorities } from "../../priority";
import { videoFormats } from "../../vertd/vertd.svelte";
@@ -161,10 +162,12 @@ export class FFmpegVideoConverter extends BaseFFmpegConverter {
default: "auto",
options: [
{ value: "auto", label: m["convert.settings.common.auto"]() },
- ...(support?.video ?? []).map((codec) => ({
- value: encoderFor(codec),
- label: codec,
- })),
+ ...codecOptions(
+ filterCommonCodecs(
+ (support?.video ?? []).map(encoderFor),
+ "video",
+ ),
+ ),
],
};
@@ -184,10 +187,12 @@ export class FFmpegVideoConverter extends BaseFFmpegConverter {
default: "auto",
options: [
{ value: "auto", label: m["convert.settings.common.auto"]() },
- ...(support?.audio ?? []).map((codec) => ({
- value: encoderFor(codec),
- label: codec,
- })),
+ ...codecOptions(
+ filterCommonCodecs(
+ (support?.audio ?? []).map(encoderFor),
+ "audio",
+ ),
+ ),
],
};
diff --git a/src/lib/converters/mediabunny/mediabunny.svelte.ts b/src/lib/converters/mediabunny/mediabunny.svelte.ts
index f512363..3506569 100644
--- a/src/lib/converters/mediabunny/mediabunny.svelte.ts
+++ b/src/lib/converters/mediabunny/mediabunny.svelte.ts
@@ -36,6 +36,7 @@ import {
} from "mediabunny";
import { SvelteMap } from "svelte/reactivity";
import { get } from "svelte/store";
+import { codecOptions, filterCommonCodecs } from "../codec-labels";
import { Converter, formatDuration, FormatInfo } from "../converter.svelte";
import { applyPriorities } from "../priority";
@@ -260,7 +261,10 @@ export class MediabunnyConverter extends Converter {
};
const toFormat = input.to;
- const supportedVideoCodecs = getCompatibleCodecs("video", toFormat);
+ const supportedVideoCodecs = filterCommonCodecs(
+ getCompatibleCodecs("video", toFormat),
+ "video",
+ );
const videoCodec: SettingDefinition = {
key: "videoCodec",
label: m["convert.settings.video.codec.video"](),
@@ -268,14 +272,14 @@ export class MediabunnyConverter extends Converter {
default: "auto",
options: [
{ value: "auto", label: m["convert.settings.common.auto"]() },
- ...supportedVideoCodecs.map((codec) => ({
- value: codec,
- label: codec,
- })),
+ ...codecOptions(supportedVideoCodecs),
],
};
- const supportedAudioCodecs = getCompatibleCodecs("audio", toFormat);
+ const supportedAudioCodecs = filterCommonCodecs(
+ getCompatibleCodecs("audio", toFormat),
+ "audio",
+ );
const audioCodec: SettingDefinition = {
key: "audioCodec",
label: m["convert.settings.video.codec.audio"](),
@@ -283,10 +287,7 @@ export class MediabunnyConverter extends Converter {
default: "auto",
options: [
{ value: "auto", label: m["convert.settings.common.auto"]() },
- ...supportedAudioCodecs.map((codec) => ({
- value: codec,
- label: codec,
- })),
+ ...codecOptions(supportedAudioCodecs),
],
};
diff --git a/src/lib/converters/vertd/vertd.svelte.ts b/src/lib/converters/vertd/vertd.svelte.ts
index 6adabd6..95320b8 100644
--- a/src/lib/converters/vertd/vertd.svelte.ts
+++ b/src/lib/converters/vertd/vertd.svelte.ts
@@ -15,6 +15,7 @@ import { formatError } from "#lib/util/error";
import { ToastManager } from "#lib/util/toast.svelte";
import { PUB_DISABLE_FAILURE_BLOCKS } from "$app/env/public";
import { SvelteMap, SvelteSet } from "svelte/reactivity";
+import { type CodecInfo, codecOptions, toCodecInfo } from "../codec-labels";
import { Converter, FormatInfo, formatDuration } from "../converter.svelte";
import { applyPriorities } from "../priority";
@@ -41,18 +42,36 @@ interface RouteRequestMap {
}
interface CodecsResponse {
- videoCodecs: string[];
- audioCodecs: string[];
+ videoCodecs: CodecInfo[];
+ audioCodecs: CodecInfo[];
}
+type CodecsRouteResponse = {
+ format?: string;
+ videoCodecs?: (CodecInfo | string)[];
+ audioCodecs?: (CodecInfo | string)[];
+ codec?: string;
+ formats?: string[];
+};
+
interface RouteResponseMap {
"/api/upload": UploadResponse;
"/api/version": string;
"/api/size_limit": number | null;
"/api/keep": void;
- "/api/codecs": string[]; // get list of all codecs supported by vertd server
- [key: `/api/codecs/${string}`]: unknown; // list of codecs for this format
- [key: `/api/codecs/support/${string}`]: unknown; // list of formats supporting this codec -- i dont know how this works in ts, i have to put both as unknown since this and /api/codecs are different types (CodecsResponse & string[]) and TS errors
+ // get list of all codecs supported by vertd server
+ "/api/codecs": {
+ video: CodecInfo[];
+ audio: CodecInfo[];
+ all: CodecInfo[];
+ };
+ // list of codecs for this format
+ [key: `/api/codecs/${string}`]: CodecsRouteResponse;
+ // list of formats supporting this codec
+ [key: `/api/codecs/support/${string}`]: {
+ codec: string;
+ formats: string[];
+ };
[key: `/api/confirm/${string}/${string}`]: void; // confirm download - job id, token
}
@@ -474,11 +493,15 @@ export class VertdConverter extends Converter {
baseUrl,
);
+ const nextCodecs: CodecsResponse = {
+ videoCodecs: (codecsJson.videoCodecs || []).map(toCodecInfo),
+ audioCodecs: (codecsJson.audioCodecs || []).map(toCodecInfo),
+ };
const previousCodecs = JSON.stringify(this.codecs);
- const newCodecs = JSON.stringify(codecsJson);
+ const newCodecs = JSON.stringify(nextCodecs);
if (previousCodecs !== newCodecs) {
- this.codecs = codecsJson as CodecsResponse;
+ this.codecs = nextCodecs;
this.log(`updated codecs from vertd: ${newCodecs}`);
}
} catch (e) {
@@ -528,10 +551,7 @@ export class VertdConverter extends Converter {
default: "auto",
options: [
{ value: "auto", label: m["convert.settings.common.auto"]() },
- ...(this.codecs.videoCodecs || []).map((codec) => ({
- value: codec,
- label: codec,
- })),
+ ...codecOptions(this.codecs.videoCodecs),
],
};
@@ -555,10 +575,7 @@ export class VertdConverter extends Converter {
default: "auto",
options: [
{ value: "auto", label: m["convert.settings.common.auto"]() },
- ...(this.codecs.audioCodecs || []).map((codec) => ({
- value: codec,
- label: codec,
- })),
+ ...codecOptions(this.codecs.audioCodecs),
],
};
diff --git a/src/lib/types/file.svelte.ts b/src/lib/types/file.svelte.ts
index 80d800c..8f5ae37 100644
--- a/src/lib/types/file.svelte.ts
+++ b/src/lib/types/file.svelte.ts
@@ -492,6 +492,8 @@ export class VertFile {
["file", "settings"],
`changed setting "${change.setting}" from "${change.oldValue}" to "${change.newValue}" for file ${change.file}`,
);
+ this.conversionSettings[change.setting] =
+ normalizedSettings.settings[change.setting];
ToastManager.add({
type: "warning",
message: m["workers.warnings.settings_change"]({
diff --git a/src/routes/about/+page.svelte b/src/routes/about/+page.svelte
index 0fba98f..9156988 100644
--- a/src/routes/about/+page.svelte
+++ b/src/routes/about/+page.svelte
@@ -15,15 +15,6 @@
} from "#lib/util/consts";
import { m } from "#lib/paraglide/messages";
import { ToastManager } from "#lib/util/toast.svelte";
- // import { dev } from "$app/environment";
- // import { page } from "$app/state";
-
- /* interface Donator {
- name: string;
- amount?: string | number;
- avatar: string;
- } */
-
interface Contributor {
name: string;
github: string;
@@ -31,8 +22,6 @@
role?: string;
}
- // const donors: Donator[] = [];
-
const mainContribs: Contributor[] = [
{
name: "nullptr",