Files
frigate/web/src/components/config-form/theme/widgets/FfmpegArgsWidget.tsx
T

581 lines
17 KiB
TypeScript
Raw Normal View History

2026-02-27 09:55:36 -06:00
import type { WidgetProps } from "@rjsf/utils";
import useSWR from "swr";
import { useCallback, useEffect, useMemo, useState } from "react";
2026-02-27 09:55:36 -06:00
import { useTranslation } from "react-i18next";
import get from "lodash/get";
import isEqual from "lodash/isEqual";
2026-02-27 09:55:36 -06:00
import { Input } from "@/components/ui/input";
import { ConfigFormContext } from "@/types/configForm";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group";
type FfmpegPresetResponse = {
hwaccel_args: string[];
input_args: string[];
output_args: {
record: string[];
detect: string[];
};
};
type FfmpegArgsMode =
"preset" | "manual" | "inherit" | "none" | "auto" | "disabled";
// RJSF remounts the widget when the value flips between a string and a list,
// so the user's mode choice lives outside the component. It applies only
// while the value is still the one it was made for, so a save or undo that
// changes the value hands the mode back to detection.
const chosenModes = new Map<string, { mode: FfmpegArgsMode; value: unknown }>();
const chosenModeClears = new Map<string, ReturnType<typeof setTimeout>>();
2026-02-27 09:55:36 -06:00
type PresetField =
| "hwaccel_args"
| "input_args"
| "output_args.record"
| "output_args.record_sub"
2026-02-27 09:55:36 -06:00
| "output_args.detect";
const getPresetOptions = (
data: FfmpegPresetResponse | undefined,
field: PresetField | undefined,
): string[] => {
if (!data || !field) {
return [];
}
if (field === "hwaccel_args") {
return data.hwaccel_args;
}
if (field === "input_args") {
return data.input_args;
}
if (field.startsWith("output_args.")) {
const key =
field === "output_args.record_sub"
? "record"
: (field.split(".")[1] as "record" | "detect");
2026-02-27 09:55:36 -06:00
return data.output_args?.[key] ?? [];
}
return [];
};
const resolveMode = (
value: unknown,
presets: string[],
defaultMode: FfmpegArgsMode,
allowInherit: boolean,
hwaccelModes: boolean,
2026-02-27 09:55:36 -06:00
): FfmpegArgsMode => {
if (value === null || value === undefined) {
if (allowInherit) return "inherit";
return hwaccelModes ? "auto" : "none";
2026-02-27 09:55:36 -06:00
}
if (allowInherit && Array.isArray(value) && value.length === 0) {
return "inherit";
}
if (hwaccelModes) {
// An empty string is how auto-detection reports no hardware, and the
// backend runs no hwaccel for it either way.
if (value === "" || (Array.isArray(value) && value.length === 0)) {
return "disabled";
}
if (value === "auto") return "auto";
}
2026-02-27 09:55:36 -06:00
if (Array.isArray(value)) {
return "manual";
}
if (typeof value === "string") {
if (presets.length === 0) {
return defaultMode;
}
return presets.includes(value) ? "preset" : "manual";
}
return defaultMode;
};
const normalizeManualText = (value: unknown): string => {
if (Array.isArray(value)) {
return value.join(" ");
}
if (typeof value === "string") {
return value;
}
return "";
};
export function FfmpegArgsWidget(props: WidgetProps) {
const formContext = props.registry?.formContext as
ConfigFormContext | undefined;
2026-02-27 09:55:36 -06:00
const i18nNamespace = formContext?.i18nNamespace as string | undefined;
const isCameraLevel = formContext?.level === "camera";
const effectiveNamespace = isCameraLevel ? "config/cameras" : i18nNamespace;
const { t, i18n } = useTranslation([
effectiveNamespace || i18nNamespace || "common",
i18nNamespace || "common",
"views/settings",
]);
const {
value,
onChange,
disabled,
readonly,
options,
placeholder,
schema,
id,
} = props;
const presetField = options?.ffmpegPresetField as PresetField | undefined;
2026-07-14 09:42:26 -05:00
// Path to this field within its config section. This is usually the same as
// the preset field, but the two diverge when the field sits below the
// section root: record.export.hwaccel_args uses the hwaccel_args preset list
// while living at export.hwaccel_args inside the record section.
const globalFieldPath =
(options?.ffmpegGlobalFieldPath as string | undefined) ?? presetField;
// Camera-config path the backend falls back to when this camera field is
// unset, used alongside the global value to detect inheritance.
const cameraFallbackPath = options?.cameraFallbackPath as string | undefined;
2026-02-27 09:55:36 -06:00
const allowInherit = options?.allowInherit === true;
const unsetLabelKey = options?.unsetLabelKey as string | undefined;
2026-02-27 09:55:36 -06:00
const hideDescription = options?.hideDescription === true;
const useSplitLayout = options?.splitLayout !== false;
// Detect camera-level top-level fields (not inside inputs array).
// These should show "Use global setting" instead of "None".
const isInputScoped = id.includes("_inputs_");
const showUseGlobalSetting = isCameraLevel && !isInputScoped && !allowInherit;
// Hardware acceleration offers Auto and Disabled in place of None. Auto
// sends the literal "auto" because the form holds the resolved value, so a
// delete could target a key that is absent from the YAML.
const hwaccelModes = presetField === "hwaccel_args" && !allowInherit;
// Extract the global value for this specific field to detect inheritance
const globalFieldValue = useMemo(() => {
2026-07-14 09:42:26 -05:00
if (
!showUseGlobalSetting ||
!formContext?.globalValue ||
!globalFieldPath
) {
return undefined;
}
2026-07-14 09:42:26 -05:00
return get(
formContext.globalValue as Record<string, unknown>,
globalFieldPath,
);
}, [showUseGlobalSetting, formContext?.globalValue, globalFieldPath]);
2026-02-27 09:55:36 -06:00
const { data } = useSWR<FfmpegPresetResponse>("ffmpeg/presets");
const presetOptions = useMemo(
() => getPresetOptions(data, presetField),
[data, presetField],
);
const canUsePresets = presetOptions.length > 0;
const defaultMode: FfmpegArgsMode = canUsePresets ? "preset" : "manual";
const cameraFallbackValue = useMemo(
() =>
cameraFallbackPath && formContext?.fullCameraConfig
? get(formContext.fullCameraConfig, cameraFallbackPath)
: undefined,
[cameraFallbackPath, formContext?.fullCameraConfig],
);
// A camera value equal to what it would resolve to when unset counts as
// inherited (i.e. the camera does not override it).
const isInherited = useCallback(
(candidate: unknown) => {
if (!showUseGlobalSetting) return false;
if (candidate === undefined || candidate === null) return true;
return [globalFieldValue, cameraFallbackValue].some(
(inherited) =>
inherited !== undefined &&
inherited !== null &&
isEqual(candidate, inherited),
);
},
[showUseGlobalSetting, globalFieldValue, cameraFallbackValue],
);
const isInheritedFromGlobal = isInherited(value);
// globalFieldPath points at the camera-level field, not an input's own
// value, so input-scoped fields have no saved value to fall back to.
const savedValue =
!isInputScoped && globalFieldPath && formContext?.baselineFormData
? get(formContext.baselineFormData, globalFieldPath)
: undefined;
const detectedMode = useMemo(() => {
if (showUseGlobalSetting && isInheritedFromGlobal) {
return "inherit" as FfmpegArgsMode;
}
// A pending "" is a cleared Manual box. It means Disabled only when it
// is the saved value.
if (hwaccelModes && value === "" && !isEqual(savedValue, "")) {
return "manual" as FfmpegArgsMode;
}
return resolveMode(
value,
presetOptions,
defaultMode,
allowInherit,
hwaccelModes,
);
}, [
showUseGlobalSetting,
isInheritedFromGlobal,
value,
presetOptions,
defaultMode,
allowInherit,
hwaccelModes,
savedValue,
]);
2026-02-27 09:55:36 -06:00
const modeKey = [
formContext?.level,
formContext?.cameraName,
formContext?.sectionPath,
formContext?.isProfile,
id,
].join(":");
2026-02-27 09:55:36 -06:00
// An empty manual box is no change, so the form falls back to the saved
// value while Manual stays chosen.
const chosenMode = useCallback(
(current: unknown) => {
const chosen = chosenModes.get(modeKey);
if (!chosen) return undefined;
const emptyManual = chosen.mode === "manual" && chosen.value === "";
// RJSF hands an unset list-valued field back as []
const unsetList =
chosen.value === undefined &&
Array.isArray(current) &&
current.length === 0;
return isEqual(chosen.value, current) ||
unsetList ||
(emptyManual &&
savedValue !== undefined &&
isEqual(current, savedValue))
? chosen.mode
: undefined;
},
[modeKey, savedValue],
);
// A remount mounts the replacement before the timer fires, so only leaving
// the page clears the choice.
2026-02-27 09:55:36 -06:00
useEffect(() => {
clearTimeout(chosenModeClears.get(modeKey));
return () => {
chosenModeClears.set(
modeKey,
setTimeout(() => chosenModes.delete(modeKey)),
);
};
}, [modeKey]);
const [mode, setMode] = useState<FfmpegArgsMode>(
() => chosenMode(value) ?? detectedMode,
);
useEffect(() => {
const chosen = chosenMode(value);
if (chosen) {
setMode(chosen);
return;
}
2026-02-27 09:55:36 -06:00
if (!canUsePresets && detectedMode === "preset") {
setMode("manual");
return;
}
setMode(detectedMode);
}, [canUsePresets, chosenMode, detectedMode, value]);
const choose = useCallback(
(nextMode: FfmpegArgsMode, nextValue: unknown) => {
chosenModes.set(modeKey, { mode: nextMode, value: nextValue });
setMode(nextMode);
onChange(nextValue);
},
[modeKey, onChange],
);
2026-02-27 09:55:36 -06:00
const handleModeChange = useCallback(
(nextMode: FfmpegArgsMode) => {
// Restoring an inherited saved value leaves the form clean. Sending
// undefined would delete a key that may be absent from the YAML.
2026-02-27 09:55:36 -06:00
if (nextMode === "inherit") {
choose(nextMode, isInherited(savedValue) ? savedValue : undefined);
2026-02-27 09:55:36 -06:00
return;
}
if (nextMode === "none") {
choose(nextMode, undefined);
return;
}
if (nextMode === "auto") {
choose(nextMode, "auto");
return;
}
if (nextMode === "disabled") {
choose(nextMode, []);
return;
}
2026-02-27 09:55:36 -06:00
if (nextMode === "preset") {
const currentValue = typeof value === "string" ? value : undefined;
const presetValue =
currentValue && presetOptions.includes(currentValue)
? currentValue
: presetOptions[0];
if (presetValue) {
choose(nextMode, presetValue);
} else {
setMode(nextMode);
2026-02-27 09:55:36 -06:00
}
return;
}
// Start from the saved manual args, if any, so a switch back to Manual
// shows them instead of an empty box.
if (mode === "preset" || mode === "auto" || mode === "disabled") {
const savedIsManual =
resolveMode(
savedValue,
presetOptions,
defaultMode,
allowInherit,
hwaccelModes,
) === "manual";
choose(nextMode, savedIsManual ? savedValue : "");
2026-02-27 09:55:36 -06:00
return;
}
choose(nextMode, normalizeManualText(value));
2026-02-27 09:55:36 -06:00
},
[
allowInherit,
choose,
defaultMode,
hwaccelModes,
isInherited,
mode,
presetOptions,
savedValue,
value,
],
2026-02-27 09:55:36 -06:00
);
const handlePresetChange = useCallback(
(preset: string) => choose("preset", preset),
[choose],
2026-02-27 09:55:36 -06:00
);
const handleManualChange = useCallback(
(event: React.ChangeEvent<HTMLInputElement>) =>
choose("manual", event.target.value),
[choose],
2026-02-27 09:55:36 -06:00
);
const manualValue =
chosenMode(value) === "manual" && chosenModes.get(modeKey)?.value === ""
? ""
: normalizeManualText(value);
2026-02-27 09:55:36 -06:00
const presetValue =
typeof value === "string" && presetOptions.includes(value) ? value : "";
const fallbackDescriptionKey = useMemo(() => {
if (!presetField) {
return undefined;
}
const prefix = isInputScoped ? "ffmpeg.inputs" : "ffmpeg";
if (presetField === "hwaccel_args") {
return `${prefix}.hwaccel_args.description`;
}
if (presetField === "input_args") {
return `${prefix}.input_args.description`;
}
if (presetField === "output_args.record") {
return isInputScoped
? "ffmpeg.inputs.output_args.record.description"
: "ffmpeg.output_args.record.description";
}
if (presetField === "output_args.record_sub") {
return isInputScoped
? "ffmpeg.inputs.output_args.record_sub.description"
: "ffmpeg.output_args.record_sub.description";
}
2026-02-27 09:55:36 -06:00
if (presetField === "output_args.detect") {
return isInputScoped
? "ffmpeg.inputs.output_args.detect.description"
: "ffmpeg.output_args.detect.description";
}
return undefined;
}, [isInputScoped, presetField]);
2026-02-27 09:55:36 -06:00
const translatedDescription =
fallbackDescriptionKey &&
effectiveNamespace &&
i18n.exists(fallbackDescriptionKey, { ns: effectiveNamespace })
? t(fallbackDescriptionKey, { ns: effectiveNamespace })
: "";
const fieldDescription =
typeof schema.description === "string" && schema.description.length > 0
? schema.description
: translatedDescription;
const unsetMode: FfmpegArgsMode =
showUseGlobalSetting || allowInherit
? "inherit"
: hwaccelModes
? "auto"
: "none";
const unsetLabel = showUseGlobalSetting
? t("configForm.ffmpegArgs.useGlobalSetting", { ns: "views/settings" })
: allowInherit
? t(unsetLabelKey ?? "configForm.ffmpegArgs.inherit", {
ns: "views/settings",
})
: hwaccelModes
? t(unsetLabelKey ?? "configForm.ffmpegArgs.auto", {
ns: "views/settings",
})
: t(unsetLabelKey ?? "configForm.ffmpegArgs.none", {
ns: "views/settings",
});
const renderOption = (
optionMode: FfmpegArgsMode,
label: string,
optionDisabled = false,
) => (
<div className="flex items-center space-x-2">
<RadioGroupItem
value={optionMode}
id={`${id}-${optionMode}`}
disabled={disabled || readonly || optionDisabled}
className={
mode === optionMode
? "bg-selected from-selected/50 to-selected/90 text-selected"
: "bg-secondary from-secondary/50 to-secondary/90 text-secondary"
}
/>
<label htmlFor={`${id}-${optionMode}`} className="cursor-pointer text-sm">
{label}
</label>
</div>
);
2026-02-27 09:55:36 -06:00
return (
<div className="space-y-2">
<RadioGroup
value={mode}
onValueChange={(next) => handleModeChange(next as FfmpegArgsMode)}
className="gap-3"
>
{renderOption(unsetMode, unsetLabel)}
{hwaccelModes &&
renderOption(
"disabled",
t("configForm.ffmpegArgs.disabled", { ns: "views/settings" }),
)}
{renderOption(
"preset",
t("configForm.ffmpegArgs.preset", { ns: "views/settings" }),
!canUsePresets,
)}
{renderOption(
"manual",
t("configForm.ffmpegArgs.manual", { ns: "views/settings" }),
)}
2026-02-27 09:55:36 -06:00
</RadioGroup>
{mode === "auto" && !unsetLabelKey ? (
<p className="text-xs text-muted-foreground">
{t("configForm.ffmpegArgs.autoDescription", {
ns: "views/settings",
})}
</p>
) : mode === "auto" ||
mode === "inherit" ||
mode === "none" ||
mode === "disabled" ? null : mode === "preset" && canUsePresets ? (
2026-02-27 09:55:36 -06:00
<Select
value={presetValue}
onValueChange={handlePresetChange}
disabled={disabled || readonly}
>
<SelectTrigger id={id} className="w-full md:max-w-md">
<SelectValue
placeholder={
placeholder ||
schema.title ||
t("configForm.ffmpegArgs.selectPreset", {
ns: "views/settings",
})
}
/>
</SelectTrigger>
<SelectContent>
{presetOptions.map((preset) => (
<SelectItem key={preset} value={preset}>
2026-03-23 08:37:40 -06:00
{t(`configForm.ffmpegArgs.presetLabels.${preset}`, {
ns: "views/settings",
defaultValue: preset,
})}
2026-02-27 09:55:36 -06:00
</SelectItem>
))}
</SelectContent>
</Select>
) : (
<Input
id={id}
value={manualValue}
onChange={handleManualChange}
disabled={disabled || readonly}
placeholder={
placeholder ||
t("configForm.ffmpegArgs.manualPlaceholder", {
ns: "views/settings",
})
}
/>
)}
{!hideDescription && !useSplitLayout && fieldDescription ? (
<p className="text-xs text-muted-foreground">{fieldDescription}</p>
) : null}
</div>
);
}