import type { WidgetProps } from "@rjsf/utils"; import useSWR from "swr"; import { useCallback, useEffect, useMemo, useState } from "react"; import { useTranslation } from "react-i18next"; import get from "lodash/get"; import isEqual from "lodash/isEqual"; 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(); const chosenModeClears = new Map>(); type PresetField = | "hwaccel_args" | "input_args" | "output_args.record" | "output_args.record_sub" | "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"); return data.output_args?.[key] ?? []; } return []; }; const resolveMode = ( value: unknown, presets: string[], defaultMode: FfmpegArgsMode, allowInherit: boolean, hwaccelModes: boolean, ): FfmpegArgsMode => { if (value === null || value === undefined) { if (allowInherit) return "inherit"; return hwaccelModes ? "auto" : "none"; } 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"; } 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; 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; // 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; const allowInherit = options?.allowInherit === true; const unsetLabelKey = options?.unsetLabelKey as string | undefined; 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(() => { if ( !showUseGlobalSetting || !formContext?.globalValue || !globalFieldPath ) { return undefined; } return get( formContext.globalValue as Record, globalFieldPath, ); }, [showUseGlobalSetting, formContext?.globalValue, globalFieldPath]); const { data } = useSWR("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, ]); const modeKey = [ formContext?.level, formContext?.cameraName, formContext?.sectionPath, formContext?.isProfile, id, ].join(":"); // 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. useEffect(() => { clearTimeout(chosenModeClears.get(modeKey)); return () => { chosenModeClears.set( modeKey, setTimeout(() => chosenModes.delete(modeKey)), ); }; }, [modeKey]); const [mode, setMode] = useState( () => chosenMode(value) ?? detectedMode, ); useEffect(() => { const chosen = chosenMode(value); if (chosen) { setMode(chosen); return; } 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], ); 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. if (nextMode === "inherit") { choose(nextMode, isInherited(savedValue) ? savedValue : undefined); return; } if (nextMode === "none") { choose(nextMode, undefined); return; } if (nextMode === "auto") { choose(nextMode, "auto"); return; } if (nextMode === "disabled") { choose(nextMode, []); return; } 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); } 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 : ""); return; } choose(nextMode, normalizeManualText(value)); }, [ allowInherit, choose, defaultMode, hwaccelModes, isInherited, mode, presetOptions, savedValue, value, ], ); const handlePresetChange = useCallback( (preset: string) => choose("preset", preset), [choose], ); const handleManualChange = useCallback( (event: React.ChangeEvent) => choose("manual", event.target.value), [choose], ); const manualValue = chosenMode(value) === "manual" && chosenModes.get(modeKey)?.value === "" ? "" : normalizeManualText(value); 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"; } if (presetField === "output_args.detect") { return isInputScoped ? "ffmpeg.inputs.output_args.detect.description" : "ffmpeg.output_args.detect.description"; } return undefined; }, [isInputScoped, presetField]); 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, ) => (
); return (
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" }), )} {mode === "auto" && !unsetLabelKey ? (

{t("configForm.ffmpegArgs.autoDescription", { ns: "views/settings", })}

) : mode === "auto" || mode === "inherit" || mode === "none" || mode === "disabled" ? null : mode === "preset" && canUsePresets ? ( ) : ( )} {!hideDescription && !useSplitLayout && fieldDescription ? (

{fieldDescription}

) : null}
); }