Skip to main content

framefinery_api/
settings.rs

1/// Value shape accepted by a declared encoder or global setting.
2#[derive(Debug, Clone, Copy, PartialEq, Eq)]
3pub enum SettingValue {
4    /// Boolean setting, accepting common CLI spellings such as `true`, `1`, or `on`.
5    Boolean,
6    /// String setting constrained to one of the listed choices.
7    Choice(&'static [&'static str]),
8    /// Integer setting constrained to an inclusive range.
9    IntegerRange {
10        /// Minimum accepted value.
11        min: u16,
12        /// Maximum accepted value.
13        max: u16,
14    },
15    /// Signed integer setting constrained to an inclusive range.
16    SignedIntegerRange {
17        /// Minimum accepted value.
18        min: i32,
19        /// Maximum accepted value.
20        max: i32,
21    },
22}
23
24/// One accepted syntax form for a setting.
25#[derive(Debug, Clone, Copy)]
26pub struct SettingSpecForm {
27    /// User-facing syntax, such as `qp=<1..255>`.
28    pub syntax: &'static str,
29    /// Short explanation of the form.
30    pub summary: &'static str,
31}
32
33/// One example setting string for help and generated documentation.
34#[derive(Debug, Clone, Copy)]
35pub struct SettingSpecExample {
36    /// Complete setting spec string.
37    pub spec: &'static str,
38    /// Short explanation of the example.
39    pub summary: &'static str,
40}
41
42/// Documentation manifest for one setting's accepted spec strings.
43#[derive(Debug, Clone, Copy)]
44pub struct SettingSpecManifest {
45    /// Supported syntax forms.
46    pub forms: &'static [SettingSpecForm],
47    /// Example specs.
48    pub examples: &'static [SettingSpecExample],
49    /// Additional behavior notes.
50    pub notes: &'static [&'static str],
51}
52
53/// Manifest entry for one global or codec-specific setting.
54#[derive(Debug, Clone, Copy)]
55pub struct SettingManifest {
56    /// Stable setting name used in `--set name=value` and API setting specs.
57    pub name: &'static str,
58    /// Value shape accepted by this setting.
59    pub value: SettingValue,
60    /// Effective default value rendered by frontends, when the setting has a public default.
61    pub default_value: Option<&'static str>,
62    /// Help/spec manifest for this setting.
63    pub spec: &'static SettingSpecManifest,
64    /// Short user-facing summary.
65    pub summary: &'static str,
66}
67
68impl SettingValue {
69    /// Return whether `value` can be parsed by this declared setting shape.
70    pub fn accepts(self, value: &str) -> bool {
71        match self {
72            SettingValue::Boolean => matches!(
73                value,
74                "true" | "false" | "1" | "0" | "yes" | "no" | "on" | "off"
75            ),
76            SettingValue::Choice(values) => values.contains(&value),
77            SettingValue::IntegerRange { min, max } => value
78                .parse::<u16>()
79                .is_ok_and(|parsed| (min..=max).contains(&parsed)),
80            SettingValue::SignedIntegerRange { min, max } => value
81                .parse::<i32>()
82                .is_ok_and(|parsed| (min..=max).contains(&parsed)),
83        }
84    }
85}
86
87/// Return the name portion of a `name` or `name=value` setting spec.
88pub fn setting_name(spec: &str) -> &str {
89    spec.split_once('=').map_or(spec, |(name, _)| name)
90}
91
92/// Return the value portion of a `name=value` setting spec, if present.
93pub fn setting_value(spec: &str) -> Option<&str> {
94    spec.split_once('=').map(|(_, value)| value)
95}
96
97/// Parse a boolean setting from CLI-style setting specs.
98///
99/// Missing settings return `Ok(false)`. Bare matching settings imply `true`.
100pub fn boolean_setting_enabled(
101    settings: &[String],
102    name: &str,
103) -> std::result::Result<bool, String> {
104    for spec in settings {
105        if setting_name(spec) != name {
106            continue;
107        }
108        let value = setting_value(spec).unwrap_or("true");
109        match value {
110            "true" | "1" | "yes" | "on" => return Ok(true),
111            "false" | "0" | "no" | "off" => return Ok(false),
112            _ => return Err(format!("{name} expects true or false, got '{value}'")),
113        }
114    }
115    Ok(false)
116}
117
118/// Parse a one-byte integer setting from CLI-style setting specs.
119///
120/// Returns `Ok(None)` when the setting is absent.
121pub fn u8_setting(settings: &[String], name: &str) -> std::result::Result<Option<u8>, String> {
122    for spec in settings {
123        if setting_name(spec) != name {
124            continue;
125        }
126        let value = setting_value(spec).unwrap_or("true");
127        let parsed = value
128            .parse::<u16>()
129            .map_err(|_| format!("{name} expects an integer from 1 through 255, got '{value}'"))?;
130        if parsed == 0 || parsed > u16::from(u8::MAX) {
131            return Err(format!(
132                "{name} expects an integer from 1 through 255, got '{value}'"
133            ));
134        }
135        return Ok(Some(parsed as u8));
136    }
137    Ok(None)
138}
139
140/// Parse a signed integer setting from CLI-style setting specs.
141///
142/// Returns `Ok(None)` when the setting is absent.
143pub fn i32_setting(settings: &[String], name: &str) -> std::result::Result<Option<i32>, String> {
144    for spec in settings {
145        if setting_name(spec) != name {
146            continue;
147        }
148        let value = setting_value(spec).unwrap_or("true");
149        let parsed = value
150            .parse::<i32>()
151            .map_err(|_| format!("{name} expects a signed integer, got '{value}'"))?;
152        return Ok(Some(parsed));
153    }
154    Ok(None)
155}
156
157/// Render a short label for the accepted values of `setting`.
158pub fn setting_values_label(setting: SettingManifest) -> String {
159    match setting.value {
160        SettingValue::Boolean => "true|false".to_string(),
161        SettingValue::Choice(values) => values.join("|"),
162        SettingValue::IntegerRange { min, max } => format!("{min}..{max}"),
163        SettingValue::SignedIntegerRange { min, max } => format!("{min}..{max}"),
164    }
165}
166
167const LOSSLESS_SPEC_FORMS: &[SettingSpecForm] = &[
168    SettingSpecForm {
169        syntax: "lossless",
170        summary: "enable lossless coding",
171    },
172    SettingSpecForm {
173        syntax: "lossless=<bool>",
174        summary: "explicitly enable or disable lossless coding",
175    },
176];
177
178const LOSSLESS_SPEC_EXAMPLES: &[SettingSpecExample] = &[
179    SettingSpecExample {
180        spec: "lossless",
181        summary: "request lossless output",
182    },
183    SettingSpecExample {
184        spec: "lossless=false",
185        summary: "explicitly leave lossy coding enabled",
186    },
187];
188
189const LOSSLESS_SPEC_NOTES: &[&str] = &[
190    "bare boolean settings imply true",
191    "mutually exclusive with codec quantization settings",
192];
193
194/// Spec manifest for the global `lossless` setting.
195pub const LOSSLESS_SETTING_SPEC: SettingSpecManifest = SettingSpecManifest {
196    forms: LOSSLESS_SPEC_FORMS,
197    examples: LOSSLESS_SPEC_EXAMPLES,
198    notes: LOSSLESS_SPEC_NOTES,
199};
200
201/// Global setting that requests lossless coding when the selected codec supports it.
202pub const LOSSLESS_SETTING: SettingManifest = SettingManifest {
203    name: "lossless",
204    value: SettingValue::Boolean,
205    default_value: Some("false"),
206    spec: &LOSSLESS_SETTING_SPEC,
207    summary: "request lossless coding when supported",
208};
209
210/// Global settings that are available independently of selected codecs.
211pub const GLOBAL_SETTINGS: &[SettingManifest] = &[LOSSLESS_SETTING];