Skip to main content

secs_types/
ipc.rs

1//! IPC between the screen and the service.
2//!
3//! The screen sends a [`Request`] as `{"method": "...", "params": {...}}` and
4//! always receives an envelope: `{"ok": true, "data": Response}` or
5//! `{"ok": false, "error": IpcError}`. The service never throws across this
6//! seam. Long jobs report progress through the event sink supplied with the call.
7//!
8//! Errors carry a code and parameters, not prose: the screen turns them into
9//! a sentence in the current language and keeps `detail` (the raw text) for
10//! the details view and the log.
11
12use std::collections::BTreeMap;
13
14use serde::{Deserialize, Serialize};
15use ts_rs::TS;
16
17use crate::calibration::{CalibrationSettings, Mode};
18use crate::compute::{ComputePreference, ComputeReport, ComputeStatus};
19pub use crate::settings_edit::CalibrationSettingsEditParams;
20
21/// A call from the screen.
22///
23/// The method names come from the variant names in one place: serde and
24/// strum both rename them to snake_case, and `method_names_match_the_wire`
25/// checks that the two agree.
26#[derive(
27    Debug, Clone, PartialEq, Serialize, Deserialize, TS, strum::VariantNames, strum::IntoStaticStr,
28)]
29#[serde(tag = "method", content = "params", rename_all = "snake_case")]
30#[strum(serialize_all = "snake_case")]
31#[ts(export)]
32pub enum Request {
33    /// Version, the upstream release this build is ported from, and the
34    /// platform. The first call the screen makes.
35    Bootstrap,
36    /// The `ProjectNew` Request variant.
37    ProjectNew(ProjectNewParams),
38    /// The `ProjectOpen` Request variant.
39    ProjectOpen(ProjectPathParams),
40    /// The `ProjectSave` Request variant.
41    ProjectSave(ProjectSaveParams),
42    /// The `ProjectInfo` Request variant.
43    ProjectInfo,
44    /// The `SampleLoad` Request variant.
45    SampleLoad(SampleLoadParams),
46    /// The `Calibrate` Request variant.
47    Calibrate(CalibrateParams),
48    /// The `RecommendXo` Request variant.
49    RecommendXo,
50    /// The `Mimo` Request variant.
51    Mimo(MimoParams),
52    /// The `Results` Request variant.
53    Results,
54    /// The `Export` Request variant.
55    Export(ExportParams),
56    /// The `JobCancel` Request variant.
57    JobCancel(JobCancelParams),
58    /// The `Jobs` Request variant.
59    Jobs,
60    /// The `MeasureMethods` Request variant.
61    MeasureMethods,
62    /// The `MeasureConfigure` Request variant.
63    MeasureConfigure(MeasureConfigureParams),
64    /// Returns the measurement settings stored in the open project.
65    MeasureConfigGet,
66    /// Returns one recording-status entry per arranged position.
67    MeasurementRecords,
68    /// Returns the project's microphone calibration and attachment counts.
69    MicCalibrationGet,
70    /// Reads, validates and stores a microphone calibration file in the project.
71    MicCalibrationSet(MicCalibrationSetParams),
72    /// Removes the project's selected microphone calibration file.
73    MicCalibrationClear,
74    /// Attaches the selected file to sweep measurements that have no mic curve.
75    MicCalibrationAttach,
76    /// Returns stored per-role level and SPL values.
77    LevelsGet,
78    /// Fills only missing per-role level values with upstream defaults.
79    LevelsFillDefaults,
80    /// Stops the current 2.5-second level burst without stopping its monitor.
81    LevelStop,
82    /// The `MeasurePosition` Request variant.
83    MeasurePosition(MeasurePositionParams),
84    /// The `PositionClear` Request variant.
85    PositionClear(PositionClearParams),
86    /// The `Undo` Request variant.
87    Undo(UndoParams),
88    /// The `RewLaunch` Request variant.
89    RewLaunch,
90    /// The `MdatScan` Request variant.
91    MdatScan(MdatScanParams),
92    /// The `MdatImport` Request variant.
93    MdatImport(MdatImportParams),
94    /// Returns the editable speaker configuration.
95    ConfigGet,
96    /// Replaces the speaker configuration with a built-in preset.
97    ConfigApplyPreset(ConfigPresetParams),
98    /// Changes the number of configured subwoofers.
99    ConfigSetSubCount(ConfigSubCountParams),
100    /// Changes one speaker or one of its bands.
101    ConfigSetSpeaker(ConfigSetSpeakerParams),
102    /// Adds the first unused upstream speaker role.
103    ConfigAddSpeaker,
104    /// Removes one configured speaker.
105    ConfigRemoveSpeaker(ConfigIndexParams),
106    /// Renumbers outputs in configuration order.
107    ConfigRenumber,
108    /// Returns structured configuration validation notices.
109    ConfigValidate,
110    /// Writes the upstream patch-sheet CSV.
111    PatchSheetCsv(PathParams),
112    /// Returns the editable DSP profile.
113    DspGet,
114    /// Applies a DSP preset or manual fields.
115    DspSet(DspSetParams),
116    /// Returns measurement arrangement and timing options.
117    LayoutGet,
118    /// Changes measurement arrangement or timing options.
119    LayoutSet(LayoutSetParams),
120    /// Returns the current per-position and total estimate.
121    PositionEstimate,
122    /// Returns the target curve and presets.
123    TargetGet,
124    /// Replaces target control points.
125    TargetSetPoints(TargetPointsParams),
126    /// Applies a built-in target preset.
127    TargetApplyPreset(TargetPresetParams),
128    /// Saves the target curve as upstream JSON.
129    TargetSave(PathParams),
130    /// Loads the target curve from upstream JSON.
131    TargetLoad(PathParams),
132    /// Returns calibration settings stored in the project.
133    CalibrationSettingsGet,
134    /// Stores calibration settings in the project.
135    CalibrationSettingsSet(CalibrationSettingsParams),
136    /// Applies one upstream calibration-screen edit and stores the settings.
137    CalibrationSettingsEdit(CalibrationSettingsEditParams),
138    /// Filter warnings from current settings (gain warnings require a run).
139    SubWarnings,
140    /// Optional REW facts read through the injected transport.
141    RewInfo,
142    /// Changes REW's audio driver and returns refreshed REW facts.
143    RewDriverSet(RewDriverSetParams),
144    /// Returns numeric capabilities for one calibration mode.
145    ModeSpec(ModeSpecParams),
146    /// Returns application-local settings.
147    AppSettingsGet,
148    /// Stores application-local settings.
149    AppSettingsSet(AppSettingsParams),
150    /// Reads CamillaDSP and Equalizer APO application state.
151    ApplyStatus,
152    /// Exports and applies the current design to CamillaDSP.
153    ApplyCamilla(ApplyCamillaParams),
154    /// Exports and applies the current design to Equalizer APO.
155    ApplyEqapo,
156    /// Removes SECS 2R's managed Equalizer APO include.
157    RevertEqapo,
158    /// Validates and stores application settings for both apply targets.
159    ApplySettingsSet(ApplySettings),
160    /// Installs the Windows managed host service with an elevation prompt.
161    HostInstall,
162    /// Stops and removes the Windows managed host service with an elevation prompt.
163    HostUninstall,
164    /// Clears every target persisted by the managed host service.
165    HostStopManaging,
166    /// Reports the application update state and the one-time "updated" notice.
167    UpdateStatus,
168    /// Checks for a newer release now, whatever the stored policy.
169    UpdateCheck,
170    /// Downloads the newer release found by the last check.
171    UpdateDownload,
172    /// Installs the downloaded release and starts the new version.
173    UpdateRestart,
174    /// Marks the one-time "updated" notice as shown.
175    UpdateNoticeDismiss,
176    /// Opens one release's page in the system browser.
177    UpdateOpenRelease(UpdateOpenReleaseParams),
178    /// Reports the opt-in local API server and token.
179    LocalApiStatus,
180    /// Replaces the local API bearer token and restarts its server when needed.
181    LocalApiTokenRegenerate,
182    /// Available compute devices and the effective application preference.
183    ComputeStatus,
184    /// Opens the official GPU runtime installation guide for this platform.
185    OpenGpuHelp,
186    /// Smoothed, normalized measurement curves and their shared frequency grid.
187    MeasurementCurves(MeasurementCurvesParams),
188    /// Ready-to-draw calibration curves and axis limits for one result tab.
189    ResultCurves(ResultCurvesParams),
190    /// Numeric metrics, filter counts, BA rows and coded result notices.
191    ResultLines,
192    /// Copies the last BA output alignment into the manual sub settings.
193    SubTakeValues,
194    /// Opens a project-file picker through the application host.
195    DialogOpenProject,
196    /// Opens a project save-file picker through the application host.
197    DialogSaveProject(DialogSuggestedParams),
198    /// Opens an mdat-file picker through the application host.
199    DialogPickMdat,
200    /// Opens a folder picker through the application host.
201    DialogPickFolder(DialogPickFolderParams),
202    /// Opens a typed save-file picker through the application host.
203    DialogSaveFile(DialogSaveFileParams),
204    /// Opens a typed file picker through the application host.
205    DialogOpenFile(DialogOpenFileParams),
206    /// Opens a folder in the operating-system file manager.
207    OpenFolder(OpenFolderParams),
208    /// Starts the live input level monitor.
209    LevelMonitorStart(LevelMonitorStartParams),
210    /// Stops the live input level monitor.
211    LevelMonitorStop,
212    /// Plays a role's level-check signal for 2.5 seconds.
213    LevelPlay(LevelPlayParams),
214    /// Starts watching measurement-method status.
215    StatusWatchStart,
216    /// Stops watching measurement-method status.
217    StatusWatchStop,
218    /// Returns the stored or derived export base folder.
219    ExportFolderGet,
220    /// Stores the export base folder in the open project.
221    ExportFolderSet(ExportFolderSetParams),
222}
223
224impl Request {
225    /// Every method name, as it appears on the wire, derived from the
226    /// variants. `secs-policy` checks that each one is registered in
227    /// `features.toml` as `ipc.<method>`.
228    pub const METHODS: &'static [&'static str] = <Self as strum::VariantNames>::VARIANTS;
229
230    /// The wire name of this request's method.
231    pub fn method(&self) -> &'static str {
232        self.into()
233    }
234}
235
236/// The successful result of a [`Request`], tagged with the same method name.
237#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
238#[serde(tag = "method", content = "data", rename_all = "snake_case")]
239#[ts(export)]
240pub enum Response {
241    /// The `Bootstrap` Response variant.
242    Bootstrap(BootstrapInfo),
243    /// The `ProjectNew` Response variant.
244    ProjectNew(ProjectInfo),
245    /// The `ProjectOpen` Response variant.
246    ProjectOpen(ProjectInfo),
247    /// The `ProjectSave` Response variant.
248    ProjectSave(ProjectInfo),
249    /// The `ProjectInfo` Response variant.
250    ProjectInfo(ProjectInfo),
251    /// The `SampleLoad` Response variant.
252    SampleLoad(JobStarted),
253    /// The `Calibrate` Response variant.
254    Calibrate(JobStarted),
255    /// The `RecommendXo` Response variant.
256    RecommendXo(JobStarted),
257    /// The `Mimo` Response variant.
258    Mimo(JobStarted),
259    /// The `Results` Response variant.
260    Results(ResultsSummary),
261    /// The `Export` Response variant.
262    Export(JobStarted),
263    /// The `JobCancel` Response variant.
264    JobCancel(JobSnapshot),
265    /// The `Jobs` Response variant.
266    Jobs(Vec<JobSnapshot>),
267    /// The `MeasureMethods` Response variant.
268    MeasureMethods(MeasureMethodsResult),
269    /// The `MeasureConfigure` Response variant.
270    MeasureConfigure(MeasureConfigResult),
271    /// Measurement settings stored in the open project.
272    MeasureConfigGet(MeasureConfigResult),
273    /// Recording status for every arranged position.
274    MeasurementRecords(MeasurementRecordsResult),
275    /// Selected microphone calibration and attachment counts.
276    MicCalibrationGet(MicCalibrationStatus),
277    /// Selected microphone calibration after storing a file.
278    MicCalibrationSet(MicCalibrationStatus),
279    /// Empty microphone calibration status after clearing the selection.
280    MicCalibrationClear(MicCalibrationStatus),
281    /// Microphone calibration status after attaching it to eligible sweeps.
282    MicCalibrationAttach(MicCalibrationStatus),
283    /// Stored per-role level and SPL values.
284    LevelsGet(LevelsResult),
285    /// Stored values after filling missing level defaults.
286    LevelsFillDefaults(LevelsResult),
287    /// Confirms that the current level burst was stopped.
288    LevelStop(()),
289    /// The `MeasurePosition` Response variant.
290    MeasurePosition(JobStarted),
291    /// The `PositionClear` Response variant.
292    PositionClear(UndoResult),
293    /// The `Undo` Response variant.
294    Undo(ProjectInfo),
295    /// The `RewLaunch` Response variant.
296    RewLaunch(RewStatusResult),
297    /// The `MdatScan` Response variant.
298    MdatScan(MdatScanResult),
299    /// The `MdatImport` Response variant.
300    MdatImport(JobStarted),
301    /// The `ConfigGet` Response variant.
302    ConfigGet(ConfigResult),
303    /// The `ConfigApplyPreset` Response variant.
304    ConfigApplyPreset(ConfigMutationResult),
305    /// The `ConfigSetSubCount` Response variant.
306    ConfigSetSubCount(ConfigMutationResult),
307    /// The `ConfigSetSpeaker` Response variant.
308    ConfigSetSpeaker(ConfigResult),
309    /// The `ConfigAddSpeaker` Response variant.
310    ConfigAddSpeaker(ConfigResult),
311    /// The `ConfigRemoveSpeaker` Response variant.
312    ConfigRemoveSpeaker(ConfigResult),
313    /// The `ConfigRenumber` Response variant.
314    ConfigRenumber(ConfigResult),
315    /// The `ConfigValidate` Response variant.
316    ConfigValidate(Vec<Notice>),
317    /// The `PatchSheetCsv` Response variant.
318    PatchSheetCsv(PathResult),
319    /// The `DspGet` Response variant.
320    DspGet(DspResult),
321    /// The `DspSet` Response variant.
322    DspSet(DspResult),
323    /// The `LayoutGet` Response variant.
324    LayoutGet(LayoutResult),
325    /// The `LayoutSet` Response variant.
326    LayoutSet(LayoutMutationResult),
327    /// The `PositionEstimate` Response variant.
328    PositionEstimate(PositionEstimateResult),
329    /// The `TargetGet` Response variant.
330    TargetGet(TargetResult),
331    /// The `TargetSetPoints` Response variant.
332    TargetSetPoints(TargetResult),
333    /// The `TargetApplyPreset` Response variant.
334    TargetApplyPreset(TargetResult),
335    /// The `TargetSave` Response variant.
336    TargetSave(PathResult),
337    /// The `TargetLoad` Response variant.
338    TargetLoad(TargetResult),
339    /// The `CalibrationSettingsGet` Response variant.
340    CalibrationSettingsGet(CalibrationSettings),
341    /// The `CalibrationSettingsSet` Response variant.
342    CalibrationSettingsSet(CalibrationSettings),
343    /// Settings after one edit.
344    CalibrationSettingsEdit(CalibrationSettings),
345    /// Current settings-only filter warnings.
346    SubWarnings(Vec<Notice>),
347    /// Current REW facts; unavailable fields are null.
348    RewInfo(RewInfoResult),
349    /// Current REW facts after changing its driver.
350    RewDriverSet(RewInfoResult),
351    /// The `ModeSpec` Response variant.
352    ModeSpec(ModeSpecResult),
353    /// The `AppSettingsGet` Response variant.
354    AppSettingsGet(AppSettings),
355    /// The `AppSettingsSet` Response variant.
356    AppSettingsSet(AppSettings),
357    /// Current state of both application targets.
358    ApplyStatus(ApplyStatus),
359    /// The CamillaDSP application job.
360    ApplyCamilla(JobStarted),
361    /// The Equalizer APO application job.
362    ApplyEqapo(JobStarted),
363    /// Confirms removal of the managed Equalizer APO include.
364    RevertEqapo(()),
365    /// Stored application settings for both targets.
366    ApplySettingsSet(ApplySettings),
367    /// Confirms that the Windows managed host service installer was started.
368    HostInstall(()),
369    /// Confirms that the Windows managed host service uninstaller was started.
370    HostUninstall(()),
371    /// Confirms that every managed target was cleared.
372    HostStopManaging(()),
373    /// Application update state.
374    UpdateStatus(UpdateStatus),
375    /// Update state after the check finished.
376    UpdateCheck(UpdateStatus),
377    /// Update state once the download started.
378    UpdateDownload(UpdateStatus),
379    /// Confirms that installing and restarting started.
380    UpdateRestart(()),
381    /// Update state without the notice.
382    UpdateNoticeDismiss(UpdateStatus),
383    /// Confirms that the release page was handed to the system browser.
384    UpdateOpenRelease(()),
385    /// Current local API server and token state.
386    LocalApiStatus(LocalApiStatus),
387    /// Local API state after replacing its bearer token.
388    LocalApiTokenRegenerate(LocalApiStatus),
389    /// Device capability and automatic-selection result.
390    ComputeStatus(ComputeStatus),
391    /// GPU installation documentation opened by the application host.
392    OpenGpuHelp(()),
393    /// Measurement curves on the common display grid.
394    MeasurementCurves(MeasurementCurvesResult),
395    /// Calibration tab curves, ranges and staleness.
396    ResultCurves(ResultCurvesResult),
397    /// Numeric summary lines and BA table.
398    ResultLines(ResultLinesResult),
399    /// Stored settings after taking the last sub alignment.
400    SubTakeValues(CalibrationSettings),
401    /// The chosen project path, or null when cancelled.
402    DialogOpenProject(Option<String>),
403    /// The chosen project destination, or null when cancelled.
404    DialogSaveProject(Option<String>),
405    /// The chosen mdat path, or null when cancelled.
406    DialogPickMdat(Option<String>),
407    /// The chosen folder, or null when cancelled.
408    DialogPickFolder(Option<String>),
409    /// The chosen save destination, or null when cancelled.
410    DialogSaveFile(Option<String>),
411    /// The chosen source path, or null when cancelled.
412    DialogOpenFile(Option<String>),
413    /// Confirms that the folder-open request reached the host.
414    OpenFolder(()),
415    /// The live level-monitor job.
416    LevelMonitorStart(JobStarted),
417    /// The stopped live level-monitor job, when one was running.
418    LevelMonitorStop(Option<JobSnapshot>),
419    /// Confirms that role playback was accepted.
420    LevelPlay(()),
421    /// The measurement-status watch job.
422    StatusWatchStart(JobStarted),
423    /// The stopped status-watch job, when one was running.
424    StatusWatchStop(Option<JobSnapshot>),
425    /// The current export base folder.
426    ExportFolderGet(ExportFolderResult),
427    /// The stored export base folder.
428    ExportFolderSet(ExportFolderResult),
429}
430
431/// Optional measurement selection; an absent selection includes every recorded pair.
432#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS, Default)]
433#[ts(export)]
434pub struct MeasurementCurvesParams {
435    /// Position numbers to include.
436    #[ts(type = "number[] | null")]
437    pub positions: Option<Vec<i64>>,
438    /// Speaker roles to include.
439    pub roles: Option<Vec<String>>,
440}
441/// A smoothed measurement curve shifted by the result's shared reference.
442#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
443#[ts(export)]
444pub struct MeasurementCurve {
445    /// Speaker role.
446    pub role: String,
447    /// Measurement position.
448    #[ts(type = "number")]
449    pub position: i64,
450    /// Configuration kind: main, sub or top.
451    pub kind: String,
452    /// Levels in dB on the shared grid.
453    pub values: Vec<f64>,
454}
455/// Display limits; both endpoints are data values, not logarithms.
456#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
457#[ts(export)]
458pub struct CurveAxes {
459    /// Frequency bounds in Hz.
460    pub frequency_hz: [f64; 2],
461    /// Level or delay bounds.
462    pub value: [f64; 2],
463    /// Vertical unit: db or ms.
464    pub unit: String,
465}
466/// Frequency band used to set zero dB on the measurement graph.
467#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, TS)]
468#[serde(rename_all = "snake_case")]
469#[ts(export)]
470pub enum CurveReferenceBand {
471    /// 200–2000 Hz mean of a main speaker.
472    Mid,
473    /// 40–120 Hz mean of a subwoofer.
474    Sub,
475}
476/// The stored measurement that sets zero dB for every displayed curve.
477#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)]
478#[ts(export)]
479pub struct CurveReference {
480    /// Configured speaker role.
481    pub role: String,
482    /// Measurement position.
483    #[ts(type = "number")]
484    pub position: i64,
485    /// Frequency band used for the mean.
486    pub band: CurveReferenceBand,
487}
488/// Measurement graph data.
489#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
490#[ts(export)]
491pub struct MeasurementCurvesResult {
492    /// Shared 280-point logarithmic frequency grid in Hz.
493    pub grid: Vec<f64>,
494    /// One curve per recorded role and position.
495    pub curves: Vec<MeasurementCurve>,
496    /// Stored curve and band that set zero dB, or absent when nothing is measured.
497    pub reference: Option<CurveReference>,
498    /// Upstream default axis bounds.
499    pub axes: CurveAxes,
500}
501/// The calibration graph to display.
502#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, TS)]
503#[serde(rename_all = "snake_case")]
504#[ts(export)]
505pub enum ResultTab {
506    /// Sound pressure level relative to the target reference.
507    Spl,
508    /// Group delay in milliseconds.
509    Gd,
510    /// Crossover preview.
511    Xo,
512    /// Bass alignment.
513    Ba,
514}
515/// Selection for one ready-to-draw result graph.
516#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
517#[ts(export)]
518pub struct ResultCurvesParams {
519    /// Graph tab.
520    pub tab: ResultTab,
521    /// Selected main role; absent selects the first available channel.
522    pub channel: Option<String>,
523    /// Crossover group; absent selects the selected channel's group.
524    pub group: Option<String>,
525    /// Dragged crossover in Hz; absent uses the configured value.
526    pub xo_hz: Option<f64>,
527    /// Apply input correction to the XO preview; defaults to true.
528    pub corrected: Option<bool>,
529}
530/// One named series on a result graph.
531#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
532#[ts(export)]
533pub struct ResultCurve {
534    /// Series identity: before, after, target, mimo, main, sub, sum_before or sum_after.
535    pub kind: String,
536    /// Speaker role for per-sub curves, otherwise absent.
537    pub role: Option<String>,
538    /// Values on the response's shared grid.
539    pub values: Vec<f64>,
540}
541/// A result graph whose calculations are entirely owned by the service.
542#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
543#[ts(export)]
544pub struct ResultCurvesResult {
545    /// Requested tab.
546    pub tab: ResultTab,
547    /// Shared frequency grid in Hz.
548    pub grid: Vec<f64>,
549    /// Ordered drawable series.
550    pub curves: Vec<ResultCurve>,
551    /// Upstream default axis bounds.
552    pub axes: CurveAxes,
553    /// Whether the retained result no longer matches current inputs.
554    pub stale: bool,
555    /// Whether the graph comes from a dedicated subs-only result.
556    pub subs_only: bool,
557    /// RC lower and upper bounds, with an unknown auto upper bound represented as null.
558    pub rc_band_hz: Option<(f64, Option<f64>)>,
559    /// Extra correction bands (ADR 0024), `(lo, hi)` in Hz, sorted; the
560    /// graph shades outside `rc_band_hz` and these together. Empty when
561    /// there are none or the tab shows no RC band.
562    #[serde(default)]
563    pub rc_bands_hz: Vec<(f64, f64)>,
564    /// Selected crossover frequency for the draggable line.
565    pub xo_hz: Option<f64>,
566}
567/// Values behind one channel's metrics and filters lines.
568#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
569#[ts(export)]
570pub struct ChannelResultLine {
571    /// Main role.
572    pub role: String,
573    /// Before and after percentage within one dB, 20–200 Hz.
574    pub within_1db_pct: [f64; 2],
575    /// Before and after group-delay spread, 20–100 Hz, in ms.
576    pub gd_spread_ms: [f64; 2],
577    /// Number of input PEQs.
578    pub peq_count: usize,
579    /// FIR taps, absent when no FIR is used.
580    pub fir_taps: Option<usize>,
581    /// Crossover frequency, absent without bass management.
582    pub xo_hz: Option<f64>,
583    /// Fresh, enabled MIMO support path count, absent when not shown.
584    pub mimo_support_count: Option<usize>,
585}
586/// One sub's output alignment and fixed filters.
587#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
588#[ts(export)]
589pub struct SubResultRow {
590    /// Sub role.
591    pub role: String,
592    /// Alignment mode code.
593    pub mode: String,
594    /// Output gain in dB.
595    pub gain_db: f64,
596    /// Output delay in ms.
597    pub delay_ms: f64,
598    /// Output polarity, plus or minus one.
599    pub polarity: i8,
600    /// Ordered all-pass frequency and Q pairs.
601    pub allpass: Vec<(f64, f64)>,
602    /// High-pass frequency and filter type.
603    pub high_pass: (f64, String),
604    /// Low-pass frequency and filter type.
605    pub low_pass: (f64, String),
606    /// Fixed and generated peaking filters as frequency, Q and gain.
607    pub peq: Vec<(f64, f64, f64)>,
608}
609/// A typed BA layout summary.
610#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
611#[ts(export)]
612pub struct SubLayoutLine {
613    /// Bundle name.
614    pub bundle: String,
615    /// Layout code, dba or multi.
616    pub kind: String,
617    /// All members.
618    pub members: Vec<String>,
619    /// Front row roles.
620    pub front: Vec<String>,
621    /// Rear row roles.
622    pub rear: Vec<String>,
623    /// Rear delay in ms.
624    pub rear_ms: f64,
625    /// Automatic rear delay in ms, when available.
626    pub auto_ms: Option<f64>,
627    /// Manual rear trim in ms.
628    pub trim_ms: f64,
629    /// Shared peaking filters.
630    pub peq: Vec<(f64, f64, f64)>,
631}
632/// BA metrics and table, independent of the selected main channel.
633#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
634#[ts(export)]
635pub struct SubResultLines {
636    /// Whether this BA result is stale.
637    pub stale: bool,
638    /// Whether a dedicated subs-only run supplies these values.
639    pub subs_only: bool,
640    /// Metric band in Hz.
641    pub band_hz: [f64; 2],
642    /// Before and after flatness in dB.
643    pub flatness_db: [f64; 2],
644    /// Before and after across-seat spread, absent for a single seat.
645    pub seat_spread_db: Option<[f64; 2]>,
646    /// Number of complete sub positions.
647    pub positions: usize,
648    /// Output rows in configuration order.
649    pub rows: Vec<SubResultRow>,
650    /// Bundle layouts.
651    pub layouts: Vec<SubLayoutLine>,
652    /// Filter and gain warning codes and their arguments.
653    pub warnings: Vec<Notice>,
654}
655/// Numeric calibration summary lines; no localized sentences cross IPC.
656#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
657#[ts(export)]
658pub struct ResultLinesResult {
659    /// Whether the full calibration result is stale.
660    pub stale: bool,
661    /// Per-main metrics and filter counts.
662    pub channels: Vec<ChannelResultLine>,
663    /// Total delay in milliseconds, absent before calibration.
664    pub total_delay_ms: Option<f64>,
665    /// Engine notes as codes and arguments.
666    pub notes: Vec<Notice>,
667    /// RC ceiling provenance and room-volume notices.
668    pub rc: Vec<Notice>,
669    /// BA metrics, table, layouts and warnings when at least two subs are available.
670    pub ba: Option<SubResultLines>,
671}
672
673/// What the screen needs before it draws anything.
674#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)]
675#[ts(export)]
676pub struct BootstrapInfo {
677    /// Product name shown in the title bar and the about view.
678    pub app_name: String,
679    /// The SECS 2R version (the workspace version).
680    pub version: String,
681    /// True while the major version is 0: every 0.x build is a prerelease.
682    pub prerelease: bool,
683    /// The SECS 2 release this build follows.
684    pub upstream: UpstreamBase,
685    /// The operating-system platform running this build.
686    pub platform: Platform,
687}
688/// The upstream SECS 2 release a build is ported from (`UPSTREAM.toml`).
689#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)]
690#[ts(export)]
691pub struct UpstreamBase {
692    /// Upstream product name from `UPSTREAM.toml`.
693    pub name: String,
694    /// Upstream repository URL from `UPSTREAM.toml`.
695    pub repository: String,
696    /// Upstream release version from `UPSTREAM.toml`.
697    pub version: String,
698    /// Forty-character upstream Git commit from `UPSTREAM.toml`.
699    pub commit: String,
700    /// Upstream snapshot date from `UPSTREAM.toml`.
701    pub date: String,
702}
703/// The operating-system platform running the service.
704#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)]
705#[ts(export)]
706pub struct Platform {
707    /// `windows`, `macos` or `linux` (`std::env::consts::OS`).
708    pub os: String,
709    /// `x86_64` or `aarch64` (`std::env::consts::ARCH`).
710    pub arch: String,
711}
712
713/// Inputs for creating a project.
714#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)]
715#[ts(export)]
716pub struct ProjectNewParams {
717    /// Destination `.secs` file path.
718    pub path: String,
719    /// Speaker-layout preset name.
720    pub preset: String,
721    /// Number of subwoofers.
722    pub sub_count: u8,
723    /// Whether to create the fixed 7.1.4 sample-room project.
724    pub sample: bool,
725    /// Whether this is a tutorial session using the sample room. The session
726    /// cannot be saved or exported; its measurements and results live in a
727    /// temporary folder that is removed when the session ends, and `path` is
728    /// only reported back.
729    #[serde(default)]
730    pub tutorial: bool,
731}
732/// Inputs for loading embedded or synthetic sample measurements.
733#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS, Default)]
734#[ts(export)]
735pub struct SampleLoadParams {
736    /// Synthetic position count, 2 to 17 (the largest layout); absent loads
737    /// the one-position embedded room. Other counts are refused with
738    /// `measurement_input` (`field = positions`).
739    pub positions: Option<u32>,
740}
741/// A project file path.
742#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)]
743#[ts(export)]
744pub struct ProjectPathParams {
745    /// Source `.secs` file path.
746    pub path: String,
747}
748/// Inputs for saving the open project.
749#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS, Default)]
750#[ts(export)]
751pub struct ProjectSaveParams {
752    /// Optional save-as `.secs` path; absent saves in place.
753    pub path: Option<String>,
754}
755/// Screen-facing information about the open project.
756#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)]
757#[ts(export)]
758pub struct ProjectInfo {
759    /// Open `.secs` file path.
760    pub path: String,
761    /// Project display name.
762    pub name: String,
763    /// Speaker-layout preset name.
764    pub preset: String,
765    /// Number of configured subwoofers.
766    pub sub_count: usize,
767    /// Measured position numbers.
768    pub positions: Vec<i64>,
769    /// Whether the in-memory project has unsaved changes.
770    pub dirty: bool,
771    /// Whether this open project is a non-writable tutorial session.
772    pub tutorial: bool,
773    /// Warnings produced while loading legacy project entries.
774    pub migration_warnings: Vec<MigrationWarning>,
775}
776/// A project migration warning code and affected entry.
777#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)]
778#[ts(export)]
779pub struct MigrationWarning {
780    /// Stable warning code translated by the screen.
781    pub code: String,
782    /// Project entry affected by the warning.
783    pub entry: String,
784}
785
786/// Optional settings for a calibration run.
787#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS, Default)]
788#[ts(export)]
789pub struct CalibrateParams {
790    /// Settings override; absent uses the open project.
791    pub settings: Option<CalibrationSettings>,
792    /// Designs the subwoofers only (upstream [서브만 계산]); the result is
793    /// kept apart and shown by the BA tab until the next full run.
794    #[serde(default)]
795    pub subs_only: bool,
796    /// Computes MIMO after the correction in the same job. Absent on the
797    /// wire means false, so the TypeScript field is optional.
798    #[serde(default)]
799    #[ts(as = "Option<bool>", optional)]
800    pub mimo: bool,
801}
802/// Optional settings for a MIMO run.
803#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS, Default)]
804#[ts(export)]
805pub struct MimoParams {
806    /// Settings override; absent uses the open project.
807    pub settings: Option<CalibrationSettings>,
808}
809
810/// A service-assigned long-running job identifier.
811#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, TS)]
812#[serde(transparent)]
813#[ts(export)]
814pub struct JobId(#[ts(type = "number")] pub u64);
815/// The operation performed by a long-running job.
816#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, TS)]
817#[serde(rename_all = "snake_case")]
818#[ts(export)]
819pub enum JobKind {
820    /// Records all configured roles at one measurement position.
821    Measure,
822    /// Loads embedded or deterministic synthetic sample measurements.
823    SampleLoad,
824    /// Imports assigned measurements from a REW mdat file.
825    MdatImport,
826    /// Computes a calibration design from project measurements.
827    Calibrate,
828    /// Scores crossover-frequency candidates.
829    RecommendXo,
830    /// Computes MIMO support paths.
831    Mimo,
832    /// Writes one selected export bundle.
833    Export,
834    /// Exports and applies the current design to a running target.
835    Apply,
836    /// Streams microphone levels and controls level-check playback.
837    LevelMonitor,
838    /// Watches measurement-method status changes.
839    StatusWatch,
840}
841/// The current lifecycle state of a job.
842#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, TS)]
843#[serde(rename_all = "snake_case")]
844#[ts(export)]
845pub enum JobStatus {
846    /// The worker is still running and may accept cancellation.
847    Running,
848    /// Cancellation was requested and the worker has not stopped yet.
849    CancelRequested,
850    /// The worker completed and produced a result.
851    Succeeded,
852    /// The worker stopped with an error.
853    Failed,
854    /// The caller cancelled the operation.
855    Cancelled,
856}
857impl JobStatus {
858    /// Whether the job can no longer change state.
859    pub fn is_terminal(self) -> bool {
860        matches!(self, Self::Succeeded | Self::Failed | Self::Cancelled)
861    }
862}
863/// The immediate response after a job starts.
864#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
865#[ts(export)]
866pub struct JobStarted {
867    /// Identifier assigned to the job.
868    pub job: JobId,
869    /// Operation the job performs.
870    pub kind: JobKind,
871}
872/// The latest observable state of a job.
873#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
874#[ts(export)]
875pub struct JobSnapshot {
876    /// Identifier assigned to the job.
877    pub job: JobId,
878    /// Operation the job performs.
879    pub kind: JobKind,
880    /// Current lifecycle state.
881    pub status: JobStatus,
882    /// Whether a cancellation request can still prevent commit.
883    pub cancellable: bool,
884    /// Most recently reported stage progress.
885    pub progress: Option<JobProgress>,
886    /// Failure once finished unsuccessfully.
887    pub error: Option<IpcError>,
888}
889/// Progress within one named job stage.
890#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
891#[ts(export)]
892pub struct JobProgress {
893    /// Stable stage code translated by the screen.
894    pub stage: String,
895    #[ts(type = "number")]
896    /// Completed work units in this stage.
897    pub done: u64,
898    #[ts(type = "number")]
899    /// Total work units in this stage.
900    pub total: u64,
901}
902/// A pushed lifecycle event for a long-running job.
903#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
904#[serde(tag = "event", rename_all = "snake_case")]
905#[ts(export)]
906pub enum JobEvent {
907    /// Announces a newly accepted job and its operation.
908    Started { job: JobId, kind: JobKind },
909    /// Reports completed and total work units for a stable stage code.
910    Progress {
911        job: JobId,
912        stage: String,
913        #[ts(type = "number")]
914        done: u64,
915        #[ts(type = "number")]
916        total: u64,
917    },
918    /// Reports a presentation-neutral log code and template parameters.
919    Log {
920        job: JobId,
921        code: String,
922        params: BTreeMap<String, String>,
923    },
924    /// Reports a terminal status and an ephemeral operation result or error.
925    /// Calibration and MIMO carry only a marker; read `results` for their summary.
926    Finished {
927        job: JobId,
928        status: JobStatus,
929        result: Option<Box<JobResult>>,
930        error: Option<IpcError>,
931    },
932    /// Reports a live input level at the monitor cadence.
933    Meter {
934        job: JobId,
935        rms_dbfs: f64,
936        peak_dbfs: f64,
937        spl_db: Option<f64>,
938        clipping: bool,
939    },
940    /// Reports a changed measurement-method status snapshot.
941    MeasureStatus {
942        job: JobId,
943        status: MeasureMethodsResult,
944    },
945}
946/// The successful result produced by a job.
947#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
948#[serde(tag = "kind", content = "data", rename_all = "snake_case")]
949#[ts(export)]
950pub enum JobResult {
951    /// Calibration committed; fetch the current screen summary with `results`.
952    Calibration,
953    /// Crossover recommendation computed for the current project.
954    Xo(XoRecommendation),
955    /// MIMO committed; fetch the current screen summary with `results`.
956    Mimo,
957    /// Paths written by an exporter.
958    Export(ExportResult),
959    /// A design applied to CamillaDSP or Equalizer APO.
960    Apply(ApplyResult),
961    /// Project state after a completed measurement.
962    Measurement(ProjectInfo),
963    /// Project state after an mdat import.
964    MdatImport(ProjectInfo),
965    /// A long-lived monitor or watcher stopped without a payload.
966    Stopped,
967}
968/// The job to cancel.
969#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)]
970#[ts(export)]
971pub struct JobCancelParams {
972    /// Identifier of the job to cancel.
973    pub job: JobId,
974}
975
976/// The latest calibration and MIMO results.
977#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
978#[ts(export)]
979pub struct ResultsSummary {
980    /// Latest calibration result, including stale state.
981    pub calibration: Option<CalibrationSummary>,
982    /// Latest MIMO result, including stale state.
983    pub mimo: Option<MimoSummary>,
984    /// Whether the MIMO result goes into an export, and if not, why.
985    pub mimo_export: MimoExportDecision,
986}
987/// Whether the MIMO result goes into an export, and if not, why.
988#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, TS)]
989#[serde(rename_all = "snake_case")]
990#[ts(export)]
991pub enum MimoExportDecision {
992    /// The current MIMO support paths go into the export.
993    Included,
994    /// MIMO is switched off in the current settings.
995    Off,
996    /// No MIMO result has been computed or restored.
997    None,
998    /// The MIMO result does not match the current inputs or compute environment.
999    Stale,
1000    /// MIMO needs at least three measured positions.
1001    TooFewPositions,
1002    /// The current MIMO result contains no support paths.
1003    NoSupports,
1004}
1005/// A presentation-neutral note or warning code with template parameters.
1006#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)]
1007#[ts(export)]
1008pub struct Notice {
1009    /// Stable snake_case code derived from the engine note variant.
1010    pub code: String,
1011    /// String values for the screen message template.
1012    pub params: BTreeMap<String, String>,
1013}
1014
1015/// The screen-facing summary of one calibration design.
1016#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
1017#[ts(export)]
1018pub struct CalibrationSummary {
1019    /// Whether this result was restored from the project cache instead of computed in this
1020    /// session; staged and before/after mdat need a live design.
1021    #[serde(default)]
1022    pub cached: bool,
1023    /// Whether current project inputs differ from this result.
1024    pub stale: bool,
1025    /// Which input first differs: measurements, settings or target.
1026    pub stale_reason: Option<String>,
1027    /// Calibration mode used to compute this result.
1028    pub mode: Mode,
1029    /// Ultra-mode latency limit used to compute this result, in milliseconds.
1030    pub ultra_ms: f64,
1031    /// Values for the upstream verdict card.
1032    pub verdict: VerdictSummary,
1033    /// Per-channel before-and-after metrics.
1034    pub scorecard: Vec<ChannelScore>,
1035    /// Late 20–150 Hz energy before and after correction at every measured position.
1036    #[serde(default)]
1037    pub late_energy: Vec<LateEnergy>,
1038    /// Total filter latency in milliseconds.
1039    pub latency_ms: f64,
1040    /// Informational codes and values translated by the screen.
1041    pub notes: Vec<Notice>,
1042    /// Main-channel roles in design order; filter coefficients stay in Rust.
1043    pub main_roles: Vec<String>,
1044    /// Subwoofer roles in design order; filter coefficients stay in Rust.
1045    pub sub_roles: Vec<String>,
1046}
1047/// Values shown by the upstream `step_calibration.py` verdict card.
1048#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
1049#[ts(export)]
1050pub struct VerdictSummary {
1051    /// Share within ±1 dB before correction, in percent.
1052    pub within_1db_before_pct: f64,
1053    /// Share within ±1 dB after correction, in percent.
1054    pub within_1db_after_pct: f64,
1055    /// Low-band group-delay spread before correction, in milliseconds.
1056    pub low_band_time_spread_before_ms: f64,
1057    /// Low-band group-delay spread after correction, in milliseconds.
1058    pub low_band_time_spread_after_ms: f64,
1059    /// Delay added by correction, in milliseconds.
1060    pub added_delay_ms: f64,
1061    /// Across-position level spread after correction, in dB.
1062    pub position_spread_db: f64,
1063}
1064/// Before-and-after scorecard metrics for one speaker role.
1065#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
1066#[ts(export)]
1067pub struct ChannelScore {
1068    /// Internal speaker role.
1069    pub role: String,
1070    /// Metrics before correction.
1071    pub before: MetricsSummary,
1072    /// Metrics after correction.
1073    pub after: MetricsSummary,
1074}
1075/// Late 20–150 Hz energy for one main role at one measured position.
1076#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
1077#[ts(export)]
1078pub struct LateEnergy {
1079    /// Internal speaker role.
1080    pub role: String,
1081    /// Measured position number.
1082    pub position: u32,
1083    /// Late-to-early energy before correction, in dB.
1084    pub before_db: f64,
1085    /// Late-to-early energy after correction, in dB.
1086    pub after_db: f64,
1087}
1088/// The upstream `Metrics` fields for one response.
1089#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize, TS)]
1090#[ts(export)]
1091pub struct MetricsSummary {
1092    /// Reference level from upstream `Metrics.level`, in dB.
1093    pub level: f64,
1094    /// Share within ±1 dB from 20 Hz, in percent.
1095    pub in1_20: f64,
1096    /// Share within ±2 dB from 20 Hz, in percent.
1097    pub in2_20: f64,
1098    /// Share within ±1 dB from 200 Hz, in percent.
1099    pub in1_200: f64,
1100    /// Share within ±2 dB from 200 Hz, in percent.
1101    pub in2_200: f64,
1102    /// Share within ±1 dB from 2,000 Hz, in percent.
1103    pub in1_2000: f64,
1104    /// Share within ±2 dB from 2,000 Hz, in percent.
1105    pub in2_2000: f64,
1106    /// Phase rotation from upstream `Metrics.turns`, in turns.
1107    pub turns: f64,
1108    /// Group-delay spread near 20 Hz, in milliseconds.
1109    pub gd_20: f64,
1110    /// Group-delay spread near 100 Hz, in milliseconds.
1111    pub gd_100: f64,
1112    /// Group-delay spread near 500 Hz, in milliseconds.
1113    pub gd_500: f64,
1114    /// Largest absolute 1/24-octave group-delay peak, in milliseconds.
1115    pub gd24_abs: f64,
1116    /// Frequency of the largest absolute group-delay peak, in Hz.
1117    pub gd24_abs_hz: f64,
1118    /// Largest signed 1/24-octave group-delay peak, in milliseconds.
1119    pub gd24_max: f64,
1120    /// Span of 1/24-octave group delay, in milliseconds.
1121    pub gd24_span: f64,
1122    /// Group-delay spread near 30 Hz, in milliseconds.
1123    pub gd_30: f64,
1124    /// Pre-ringing level from upstream `Metrics.pre_db`, in dB.
1125    pub pre_db: f64,
1126}
1127/// The screen-facing summary of one MIMO run.
1128#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
1129#[ts(export)]
1130pub struct MimoSummary {
1131    /// Actual computation backend, retained with the result.
1132    #[serde(default)]
1133    pub compute: ComputeReport,
1134    /// Whether current calibration inputs differ from this MIMO result.
1135    pub stale: bool,
1136    /// Realization kind, `iir` or `fir`.
1137    pub kind: String,
1138    /// Upper support frequency in Hz.
1139    pub fsiso: f64,
1140    /// Number of generated support paths.
1141    pub support_count: usize,
1142    /// Total FIR-tap budget across all generated paths.
1143    pub fir_taps_total: usize,
1144    /// Informational codes and values translated by the screen.
1145    pub notes: Vec<Notice>,
1146    /// Number of distinct input roles with at least one generated support path.
1147    pub input_count: usize,
1148    /// Per-channel metrics after MIMO at the main position.
1149    #[serde(default)]
1150    pub scorecard: Vec<MimoChannelScore>,
1151    /// Late 20–150 Hz energy after MIMO at every measured position.
1152    #[serde(default)]
1153    pub late_energy: Vec<MimoLateEnergy>,
1154}
1155/// Scorecard metrics after MIMO for one main role.
1156#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
1157#[ts(export)]
1158pub struct MimoChannelScore {
1159    /// Internal speaker role.
1160    pub role: String,
1161    /// Metrics after the MIMO support contributions are added.
1162    pub after_mimo: MetricsSummary,
1163}
1164/// Late 20–150 Hz energy after MIMO for one main role and measured position.
1165#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
1166#[ts(export)]
1167pub struct MimoLateEnergy {
1168    /// Internal speaker role.
1169    pub role: String,
1170    /// Measured position number.
1171    pub position: u32,
1172    /// Late-to-early energy after MIMO, in dB.
1173    pub after_mimo_db: f64,
1174}
1175/// Crossover candidates and the best value for each group.
1176#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
1177#[ts(export)]
1178pub struct XoRecommendation {
1179    /// Best crossover frequency in Hz for each speaker group.
1180    pub best: Vec<(String, f64)>,
1181    /// Evaluated crossover frequencies in Hz.
1182    pub candidates: Vec<f64>,
1183}
1184
1185/// The supported export bundle.
1186#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, TS)]
1187#[serde(rename_all = "snake_case")]
1188#[ts(export)]
1189pub enum ExportKind {
1190    /// CamillaDSP configuration and FIR coefficient WAV files.
1191    CamillaDsp,
1192    /// REW mdat containing the upstream staged responses.
1193    StagedMdat,
1194    /// REW mdat containing the original measurements, the correction results
1195    /// or both ([`ExportParams::mdat_scope`]; upstream's before-and-after mdat).
1196    BeforeAfterMdat,
1197    /// Per-channel filter values as text plus FIR WAV files (upstream
1198    /// `calibration.export_filter_text`). Results with RC only.
1199    FilterText,
1200    /// A complete Equalizer APO configuration: `config.txt`, the filter file
1201    /// and FIR WAV files (upstream `calibration.export_eqapo`). RC, BA and
1202    /// MIMO support paths, which upstream refuses (docs/DEVIATIONS.md F12).
1203    EqualizerApo,
1204    /// One complete 48 kHz impulse response and response CSV per reachable
1205    /// input-to-output path, including RC, BA, LFE and MIMO operations.
1206    Convolution,
1207}
1208
1209/// Why a filter export cannot carry the current result (upstream
1210/// `calibration.filter_export_block`).
1211#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, TS)]
1212#[serde(rename_all = "snake_case")]
1213#[ts(export)]
1214pub enum ExportBlock {
1215    /// The result has subs (BA); filter text carries RC only.
1216    Subs,
1217    /// The result includes MIMO; filter text does not carry it.
1218    Mimo,
1219    /// The result was restored from the cache and is stale; mdat needs the measurements' spectra,
1220    /// so it must be recalibrated first.
1221    StaleCache,
1222}
1223
1224impl ExportBlock {
1225    /// The `params.reason` value of an [`ErrorCode::ExportScope`] error.
1226    pub fn name(self) -> &'static str {
1227        match self {
1228            Self::Subs => "subs",
1229            Self::Mimo => "mimo",
1230            Self::StaleCache => "stale_cache",
1231        }
1232    }
1233}
1234
1235/// Upstream `filter_export_block`: whether `kind` can carry a result with
1236/// subs (`has_subs`) and MIMO support paths (`has_mimo`). CamillaDSP, the
1237/// mdat exports, Equalizer APO and convolution carry everything; filter text
1238/// carries RC only (subs are checked first, as upstream). Upstream stops MIMO at
1239/// Equalizer APO as well; its writer already routes the support paths, and
1240/// `secs-filters/tests/eqapo_playback.rs` plays them through the engine
1241/// (DEVIATIONS F12). The screen mirrors this rule (`screens/export/types.ts`).
1242pub fn filter_export_block(
1243    kind: ExportKind,
1244    has_subs: bool,
1245    has_mimo: bool,
1246) -> Option<ExportBlock> {
1247    match kind {
1248        ExportKind::FilterText if has_subs => Some(ExportBlock::Subs),
1249        ExportKind::FilterText if has_mimo => Some(ExportBlock::Mimo),
1250        _ => None,
1251    }
1252}
1253
1254/// Whether an export format can carry the current result. Stale cached
1255/// calibration blocks mdat; filter formats retain [`filter_export_block`].
1256pub fn export_block(
1257    kind: ExportKind,
1258    has_subs: bool,
1259    has_mimo: bool,
1260    stale_cache: bool,
1261) -> Option<ExportBlock> {
1262    match kind {
1263        ExportKind::StagedMdat | ExportKind::BeforeAfterMdat if stale_cache => {
1264            Some(ExportBlock::StaleCache)
1265        }
1266        _ => filter_export_block(kind, has_subs, has_mimo),
1267    }
1268}
1269/// What the REW mdat export ([`ExportKind::BeforeAfterMdat`]) carries
1270/// (docs/DEVIATIONS.md F19). The file name says which: `원 측정` for the
1271/// measurements, `보정 결과` for the computed responses.
1272#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize, TS)]
1273#[serde(rename_all = "snake_case")]
1274#[ts(export)]
1275pub enum MdatScope {
1276    /// The main position's before-and-after responses (upstream's file) and
1277    /// the original measurements of the other positions.
1278    #[default]
1279    All,
1280    /// The original measurements of every position, as stored; needs no
1281    /// correction result.
1282    Measurements,
1283    /// The computed responses at the main position only.
1284    Results,
1285}
1286
1287/// Sample formats accepted by CamillaDSP's Wasapi backend.
1288#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, TS)]
1289#[ts(export)]
1290pub enum CamillaWasapiFormat {
1291    /// Signed 32-bit integer.
1292    #[serde(rename = "S32")]
1293    S32,
1294    /// Signed 24-bit integer.
1295    #[serde(rename = "S24")]
1296    S24,
1297    /// Signed 16-bit integer.
1298    #[serde(rename = "S16")]
1299    S16,
1300    /// 32-bit floating point.
1301    #[serde(rename = "F32")]
1302    F32,
1303}
1304
1305impl CamillaWasapiFormat {
1306    /// CamillaDSP configuration spelling.
1307    pub fn name(self) -> &'static str {
1308        match self {
1309            Self::S32 => "S32",
1310            Self::S24 => "S24",
1311            Self::S16 => "S16",
1312            Self::F32 => "F32",
1313        }
1314    }
1315}
1316
1317/// CamillaDSP capture backend. Channel counts come from the export plan.
1318#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS, Default)]
1319#[serde(tag = "type", rename_all = "snake_case")]
1320#[ts(export)]
1321pub enum CamillaCaptureDevice {
1322    /// File placeholder compatible with the existing export.
1323    #[default]
1324    File,
1325    /// Windows Audio Session API capture.
1326    Wasapi {
1327        /// Endpoint name; absent selects the system default.
1328        device: Option<String>,
1329        /// Sample representation.
1330        format: CamillaWasapiFormat,
1331        /// Request exclusive access.
1332        exclusive: bool,
1333        /// Capture a playback endpoint in shared mode.
1334        loopback: bool,
1335    },
1336    /// ASIO capture. Requires CamillaDSP's ASIO build (`camilladsp-windows-asio`).
1337    Asio {
1338        /// ASIO driver name.
1339        device: String,
1340    },
1341}
1342
1343/// CamillaDSP playback backend. Channel counts come from the export plan.
1344#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS, Default)]
1345#[serde(tag = "type", rename_all = "snake_case")]
1346#[ts(export)]
1347pub enum CamillaPlaybackDevice {
1348    /// File placeholder compatible with the existing export.
1349    #[default]
1350    File,
1351    /// Windows Audio Session API playback.
1352    Wasapi {
1353        /// Endpoint name; absent selects the system default.
1354        device: Option<String>,
1355        /// Sample representation.
1356        format: CamillaWasapiFormat,
1357        /// Request exclusive access.
1358        exclusive: bool,
1359    },
1360    /// ASIO playback. Requires CamillaDSP's ASIO build (`camilladsp-windows-asio`).
1361    Asio {
1362        /// ASIO driver name.
1363        device: String,
1364    },
1365}
1366
1367/// Capture and playback backends for a CamillaDSP export.
1368#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS, Default)]
1369#[ts(export)]
1370pub struct CamillaDevices {
1371    /// Capture backend.
1372    pub capture: CamillaCaptureDevice,
1373    /// Playback backend.
1374    pub playback: CamillaPlaybackDevice,
1375}
1376
1377/// The export bundle and destination folder.
1378#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)]
1379#[ts(export)]
1380pub struct ExportParams {
1381    /// Export bundle to write.
1382    pub kind: ExportKind,
1383    /// Destination folder path. An empty path uses the project's export folder
1384    /// and applies the upstream timestamped subfolder convention.
1385    pub folder: String,
1386    /// What the REW mdat carries; absent means [`MdatScope::All`]. Only
1387    /// [`ExportKind::BeforeAfterMdat`] takes it; other kinds refuse it.
1388    #[serde(default, skip_serializing_if = "Option::is_none")]
1389    #[ts(optional)]
1390    pub mdat_scope: Option<MdatScope>,
1391    /// Optional stable export name. Named exports replace the matching bundle.
1392    #[serde(default, skip_serializing_if = "Option::is_none")]
1393    #[ts(optional)]
1394    pub design_name: Option<String>,
1395    /// Optional CamillaDSP Windows backends. File placeholders are the default.
1396    #[serde(default, skip_serializing_if = "Option::is_none")]
1397    #[ts(optional)]
1398    pub camilla_devices: Option<CamillaDevices>,
1399    /// Additional convolution output rates. Other export kinds refuse a non-empty list.
1400    #[serde(default)]
1401    #[ts(optional = nullable)]
1402    pub extra_rates: Vec<u32>,
1403}
1404/// Files written by a completed export job.
1405#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)]
1406#[ts(export)]
1407pub struct ExportResult {
1408    /// Paths of all files written by the exporter.
1409    pub files: Vec<String>,
1410    /// Sample rate of the files in Hz. REW mdat always reports 48000.
1411    pub output_rate: u32,
1412    /// Informational notices produced while resolving the output rate.
1413    #[serde(default)]
1414    pub notes: Vec<Notice>,
1415    /// Actual export folder written by the job.
1416    pub folder: String,
1417    /// Whether the exported calibration differed from current project inputs.
1418    pub stale: bool,
1419}
1420
1421// P28 host, live-monitor, watch and export-folder types. Keep this block
1422// contiguous so the parallel M5 IPC additions merge without interleaving.
1423/// Optional suggested name for a save dialog.
1424#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS, Default)]
1425#[ts(export)]
1426pub struct DialogSuggestedParams {
1427    /// Suggested file name.
1428    pub suggested: String,
1429}
1430/// Optional starting folder for a folder picker.
1431#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS, Default)]
1432#[ts(export)]
1433pub struct DialogPickFolderParams {
1434    /// Starting folder, when known.
1435    pub start: Option<String>,
1436}
1437/// The kind of file a host save dialog accepts.
1438#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, TS)]
1439#[serde(rename_all = "snake_case")]
1440#[ts(export)]
1441pub enum SaveFileKind {
1442    /// UTF-8 patch-sheet CSV.
1443    PatchSheet,
1444    /// Target-curve JSON.
1445    Target,
1446}
1447/// Typed save-file dialog parameters.
1448#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)]
1449#[ts(export)]
1450pub struct DialogSaveFileParams {
1451    /// File type and filter.
1452    pub kind: SaveFileKind,
1453    /// Suggested file name.
1454    pub suggested: String,
1455}
1456/// The kind of file a host open dialog accepts.
1457#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, TS)]
1458#[serde(rename_all = "snake_case")]
1459#[ts(export)]
1460pub enum OpenFileKind {
1461    /// Target-curve JSON.
1462    Target,
1463    /// Microphone response calibration text (`.txt`, `.cal` or `.frd`).
1464    MicCalibration,
1465    /// CamillaDSP executable selected for managed launching.
1466    CamillaExe,
1467}
1468/// Typed open-file dialog parameters.
1469#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)]
1470#[ts(export)]
1471pub struct DialogOpenFileParams {
1472    /// File type and filter.
1473    pub kind: OpenFileKind,
1474}
1475/// Folder to reveal in the operating-system file manager.
1476#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)]
1477#[ts(export)]
1478pub struct OpenFolderParams {
1479    /// Folder path.
1480    pub path: String,
1481}
1482/// Optional role to associate with a level-monitor start.
1483#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS, Default)]
1484#[ts(export)]
1485pub struct LevelMonitorStartParams {
1486    /// Speaker role initially selected for playback.
1487    pub role: Option<String>,
1488}
1489/// Role and output level for one 2.5-second level-check burst.
1490#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
1491#[ts(export)]
1492pub struct LevelPlayParams {
1493    /// Internal speaker role.
1494    pub role: String,
1495    /// Master output level in dBFS.
1496    pub master_dbfs: f64,
1497}
1498/// Export base-folder update.
1499#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)]
1500#[ts(export)]
1501pub struct ExportFolderSetParams {
1502    /// Folder path to store in the open project.
1503    pub folder: String,
1504}
1505/// Current export base folder and whether it came from project storage.
1506#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)]
1507#[ts(export)]
1508pub struct ExportFolderResult {
1509    /// Export base folder.
1510    pub folder: String,
1511    /// True when `extra.export.folder` supplied this value.
1512    pub stored: bool,
1513}
1514
1515// Measurement request and response types.
1516/// A validated microphone calibration file selected for the open project.
1517#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
1518#[ts(export)]
1519pub struct MicCalibrationFile {
1520    /// File name as selected by the user.
1521    pub name: String,
1522    /// Full selected path; the project retains the decoded text separately.
1523    pub path: String,
1524    /// miniDSP serial number from `SERNO`, when present.
1525    pub serial: Option<String>,
1526    /// USB microphone sensitivity factor in dB.
1527    pub sens_factor_db: Option<f64>,
1528    /// Analog input gain from `AGain`, in dB.
1529    pub analog_gain_db: Option<f64>,
1530    /// Analog microphone sensitivity at 94 dB SPL, in dBFS.
1531    pub sensitivity_dbfs: Option<f64>,
1532    /// Quoted metadata lines other than the sensitivity header.
1533    pub notes: Vec<String>,
1534    /// Number of frequency-response points.
1535    pub points: u32,
1536    /// Lowest tabulated frequency in Hz.
1537    pub min_hz: f64,
1538    /// Highest tabulated frequency in Hz.
1539    pub max_hz: f64,
1540    /// Whether any response point includes phase.
1541    pub has_phase: bool,
1542}
1543/// Selected microphone calibration and recorded-measurement attachment counts.
1544#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
1545#[ts(export)]
1546pub struct MicCalibrationStatus {
1547    /// The project's selected file, or absent when none is selected.
1548    pub file: Option<MicCalibrationFile>,
1549    /// Recorded position-role pairs whose sidecar attaches a `meterCal` curve.
1550    pub attached: u32,
1551    /// Sweep measurements without a `meterCal` curve that can receive the file.
1552    pub attachable: u32,
1553}
1554/// A microphone calibration file selected by full path.
1555#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)]
1556#[ts(export)]
1557pub struct MicCalibrationSetParams {
1558    /// Full path selected by the user.
1559    pub path: String,
1560}
1561
1562/// Measurement methods available on this host.
1563#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS, Default)]
1564#[ts(export)]
1565pub struct MeasureMethodsResult {
1566    /// Stable identifiers for available measurement methods.
1567    pub methods: Vec<String>,
1568    /// Native endpoints with their channel counts.
1569    pub native_devices: Vec<MeasureDevice>,
1570    /// Native enumeration failure, without hiding the other methods.
1571    pub native_error: Option<IpcError>,
1572    /// REW process, API, and license status.
1573    pub rew: RewStatusResult,
1574    /// Positions present in the unmodified sample room.
1575    pub mock_positions: Vec<i64>,
1576    /// Roles present in the unmodified sample room.
1577    pub mock_roles: Vec<String>,
1578}
1579/// An enumerated native audio endpoint.
1580#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)]
1581#[ts(export)]
1582pub struct MeasureDevice {
1583    /// Backend endpoint identifier.
1584    pub id: String,
1585    /// Backend endpoint display name.
1586    pub name: String,
1587    /// Maximum number of input channels.
1588    pub input_channels: usize,
1589    /// Maximum number of output channels.
1590    pub output_channels: usize,
1591}
1592/// Measurement method and device settings.
1593#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS, Default)]
1594#[ts(export)]
1595pub struct MeasureConfigureParams {
1596    /// Measurement method identifier.
1597    pub method: String,
1598    /// Optional input device identifier.
1599    pub input_device: Option<String>,
1600    /// Optional output device identifier.
1601    pub output_device: Option<String>,
1602    /// Optional one-based input channel number.
1603    pub input_channel: Option<u16>,
1604    /// One-based output channels in measurement-plan role order; empty preserves wiring.
1605    #[serde(default)]
1606    pub output_channels: Vec<u16>,
1607    /// Optional sweep length in samples.
1608    pub sweep_length: Option<usize>,
1609    /// Optional sweep repetition count; allowed values are 1, 2, 4 and 8.
1610    pub repetitions: Option<u8>,
1611    /// Optional sweep level in dBFS.
1612    pub sweep_level_dbfs: Option<f64>,
1613    /// Optional timing-reference mode.
1614    pub timing: Option<String>,
1615    /// Optional one-based loopback input channel.
1616    pub loopback_input_channel: Option<u16>,
1617    /// Optional acoustic timing-reference output channel.
1618    pub timing_ref_output: Option<u16>,
1619    /// Optional share preference: auto, exclusive, or shared.
1620    pub share_mode: Option<String>,
1621}
1622/// The active measurement settings.
1623#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS, Default)]
1624#[ts(export)]
1625pub struct MeasureConfigResult {
1626    /// Active measurement method identifier.
1627    pub method: String,
1628    /// Active sweep level in dBFS.
1629    pub sweep_level_dbfs: Option<f64>,
1630    /// Active input endpoint identifier; empty selects the default.
1631    pub input_device: String,
1632    /// Active output endpoint identifier; empty selects the default.
1633    pub output_device: String,
1634    /// One-based microphone input channel.
1635    pub input_channel: u16,
1636    /// Roles in the same order as output_channels.
1637    pub roles: Vec<String>,
1638    /// One-based output channels in measurement-plan role order.
1639    pub output_channels: Vec<u16>,
1640    /// Sweep length in samples.
1641    pub sweep_length: usize,
1642    /// Active repetition count after timing-reference normalization.
1643    pub repetitions: u8,
1644    /// Sweep sample rate in Hz.
1645    pub sample_rate: u32,
1646    /// Supported sweep lengths in samples.
1647    pub sweep_lengths: Vec<usize>,
1648    /// Timing-reference mode.
1649    pub timing: String,
1650    /// Optional one-based loopback input channel.
1651    pub loopback_input_channel: Option<u16>,
1652    /// Optional acoustic timing-reference output channel.
1653    pub timing_ref_output: Option<u16>,
1654    /// Share preference: auto, exclusive, or shared.
1655    pub share_mode: String,
1656}
1657/// Recording status and upstream source values for one arranged position.
1658#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)]
1659#[ts(export)]
1660pub struct PositionRecord {
1661    /// One-based arranged position number.
1662    #[ts(type = "number")]
1663    pub position: i64,
1664    /// Whether every planned role is recorded at this position.
1665    pub done: bool,
1666    /// Planned roles that have a recording at this position.
1667    pub roles: Vec<String>,
1668    /// Source file/value by recorded role; native and REW sweeps use `measured`.
1669    pub sources: BTreeMap<String, String>,
1670}
1671/// Recording status for the complete measurement arrangement.
1672#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)]
1673#[ts(export)]
1674pub struct MeasurementRecordsResult {
1675    /// One entry per arranged position.
1676    pub records: Vec<PositionRecord>,
1677}
1678/// Stored level-check readings, keyed by measurement role (upstream `extra['levels']`).
1679#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
1680#[ts(export)]
1681pub struct LevelsResult {
1682    /// Measured input level in dBFS by role: the meter reading while that channel played.
1683    pub levels: BTreeMap<String, f64>,
1684    /// Measured sound-pressure level in dB SPL by role.
1685    pub spl: BTreeMap<String, f64>,
1686}
1687/// The measurement position to record.
1688#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)]
1689#[ts(export)]
1690pub struct MeasurePositionParams {
1691    /// One-based measurement position number.
1692    pub position: i64,
1693}
1694/// The measurement position to clear.
1695#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)]
1696#[ts(export)]
1697pub struct PositionClearParams {
1698    /// One-based measurement position number.
1699    pub position: i64,
1700}
1701/// A service-issued undo token.
1702#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)]
1703#[ts(export)]
1704pub struct UndoParams {
1705    /// Opaque service-issued undo token.
1706    pub token: String,
1707}
1708/// An undo token and the project state it restores.
1709#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)]
1710#[ts(export)]
1711pub struct UndoResult {
1712    /// Opaque token for the inverse action.
1713    pub token: String,
1714    /// Project state after the action.
1715    pub project: ProjectInfo,
1716}
1717/// Whether REW is running, reachable, and licensed as Pro.
1718#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS, Default)]
1719#[ts(export)]
1720pub struct RewStatusResult {
1721    /// Whether an REW process is running.
1722    pub running: bool,
1723    /// Whether the REW API responds.
1724    pub reachable: bool,
1725    /// Observed automatic-sweep license state: unknown until success or rejection.
1726    pub pro: Option<bool>,
1727}
1728/// A requested REW audio driver.
1729#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)]
1730#[ts(export)]
1731pub struct RewDriverSetParams {
1732    /// Driver name as REW reports it (`ASIO` or `Java`).
1733    pub driver: String,
1734}
1735/// Facts from REW, distinct from project-stored measurement preferences.
1736#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS, Default)]
1737#[ts(export)]
1738pub struct RewInfoResult {
1739    pub executable_path: Option<String>,
1740    pub running: bool,
1741    pub reachable: bool,
1742    pub version: Option<String>,
1743    /// REW's current audio driver, or null when it could not be read.
1744    pub driver: Option<String>,
1745    /// Observed automatic-sweep license state: unknown until success or rejection.
1746    pub pro: Option<bool>,
1747    /// REW's current input device, read from its own audio preferences.
1748    pub input_device: Option<String>,
1749    /// REW's current output device, read from its own audio preferences.
1750    pub output_device: Option<String>,
1751    /// REW's current input channel name.
1752    pub input: Option<String>,
1753    pub blocking: Option<bool>,
1754    /// Empty means no file loaded; null means unknown or per-input calibration.
1755    pub input_calibration_file: Option<String>,
1756    pub input_devices: Option<Vec<RewDeviceInfo>>,
1757    pub output_devices: Option<Vec<RewDeviceInfo>>,
1758    pub input_channel_names: Option<Vec<String>>,
1759    pub sample_rate: Option<f64>,
1760    pub sweep: Option<RewSweepInfo>,
1761    pub level_dbfs: Option<f64>,
1762}
1763
1764#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)]
1765#[ts(export)]
1766pub struct RewDeviceInfo {
1767    pub id: String,
1768    pub name: String,
1769    pub channels: usize,
1770}
1771
1772#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
1773#[ts(export)]
1774pub struct RewSweepInfo {
1775    pub start_hz: Option<f64>,
1776    pub end_hz: Option<f64>,
1777    pub length: Option<String>,
1778}
1779
1780/// The REW mdat file to scan.
1781#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)]
1782#[ts(export)]
1783pub struct MdatScanParams {
1784    /// Source `.mdat` file path.
1785    pub path: String,
1786}
1787/// Measurements, suggested assignments, and problem codes found in an mdat file.
1788#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS, Default)]
1789#[ts(export)]
1790pub struct MdatScanResult {
1791    /// Measurements in file order, including assignment guesses.
1792    pub measurements: Vec<MdatScanMeasurement>,
1793    /// Suggested measurement-to-role assignments.
1794    pub suggestions: Vec<MdatAssignment>,
1795    /// Stable problem codes and template parameters.
1796    pub problems: Vec<Notice>,
1797}
1798/// One scanned measurement with an unambiguous row identifier.
1799#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)]
1800#[ts(export)]
1801pub struct MdatScanMeasurement {
1802    /// Zero-based row index, also usable when titles repeat.
1803    pub index: usize,
1804    /// Original measurement title.
1805    pub title: String,
1806    /// Suggested internal role, or no assignment.
1807    pub role: Option<String>,
1808    /// Guessed one-based measurement position.
1809    pub position: i64,
1810    /// Whether the title explicitly names a position, including position 1.
1811    pub position_tagged: bool,
1812    /// Low-band classifier result, absent when no IR is available.
1813    pub looks_like_sub: Option<bool>,
1814}
1815/// An mdat measurement assigned to a speaker role.
1816#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)]
1817#[ts(export)]
1818pub struct MdatAssignment {
1819    /// Measurement title from the mdat file.
1820    pub measurement: String,
1821    /// Internal speaker role.
1822    pub role: String,
1823    /// Optional zero-based row index to disambiguate repeated titles.
1824    pub index: Option<usize>,
1825    /// Optional per-row position overriding the import destination.
1826    pub position: Option<i64>,
1827}
1828/// An mdat file, its assignments, and destination position.
1829#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)]
1830#[ts(export)]
1831pub struct MdatImportParams {
1832    /// Source `.mdat` file path.
1833    pub path: String,
1834    /// Accepted measurement-to-role assignments.
1835    pub assignments: Vec<MdatAssignment>,
1836    /// Destination measurement position number.
1837    pub position: i64,
1838}
1839
1840// Project editing request and response types.
1841/// A filesystem path used by a project editor.
1842#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)]
1843#[ts(export)]
1844pub struct PathParams {
1845    /// File system path chosen by the user.
1846    pub path: String,
1847}
1848/// A path written by an editor.
1849#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)]
1850#[ts(export)]
1851pub struct PathResult {
1852    /// File system path that was written.
1853    pub path: String,
1854}
1855/// A preset change which may need measurement-clearing confirmation.
1856#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)]
1857#[ts(export)]
1858pub struct ConfigPresetParams {
1859    /// Preset name (`2.0`, `2.1`, `2.2`, `4.0`, `4.1`, `4.2`, `5.1`, `7.1`, `7.1.4`, `9.1.6`, or `custom` for an empty layout).
1860    pub preset: String,
1861    /// Clears existing measurements; without it a project with measurements answers `confirm_required` (U5).
1862    #[serde(default)]
1863    pub confirm: bool,
1864}
1865/// A sub-count change which may need measurement-clearing confirmation.
1866#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)]
1867#[ts(export)]
1868pub struct ConfigSubCountParams {
1869    /// Number of subwoofers, 0 to 8.
1870    pub count: i64,
1871    /// Clears existing measurements; without it a project with measurements answers `confirm_required` (U5).
1872    #[serde(default)]
1873    pub confirm: bool,
1874}
1875/// One speaker index.
1876#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)]
1877#[ts(export)]
1878pub struct ConfigIndexParams {
1879    /// Speaker index in `ConfigResult.speakers`.
1880    pub index: usize,
1881}
1882/// Optional edits to one speaker or one of its bands.
1883#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)]
1884#[ts(export)]
1885pub struct ConfigSetSpeakerParams {
1886    /// Speaker index in `ConfigResult.speakers`.
1887    pub index: usize,
1888    /// New role code; a sub role forces a single SUB band (`step2_config.py:988-1002`).
1889    pub role: Option<String>,
1890    /// New size: `small` (crossover applied) or `large` (full range).
1891    pub size: Option<String>,
1892    /// Band the output and polarity edits apply to; absent means the first band.
1893    pub band_index: Option<usize>,
1894    /// New measurement output channel (1-based).
1895    pub out: Option<i64>,
1896    /// New polarity: `+` normal or `-` inverted.
1897    pub pol: Option<String>,
1898}
1899/// One configured output band.
1900#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)]
1901#[ts(export)]
1902pub struct ConfigBand {
1903    /// Band name: `FULL`, `LF`, `MF`, `HF` or `SUB`.
1904    pub band: String,
1905    /// Measurement output channel (1-based).
1906    pub out: i64,
1907    /// Polarity: `+` normal or `-` inverted.
1908    pub pol: String,
1909}
1910/// One configured speaker.
1911#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)]
1912#[ts(export)]
1913pub struct ConfigSpeaker {
1914    /// Role code (`L`, `C`, `SW1`, `Tfl`, ...).
1915    pub role: String,
1916    /// `small` (crossover applied) or `large` (full range); subs are `sub`.
1917    pub size: String,
1918    /// Bands in order; one band unless bi-amped.
1919    pub bands: Vec<ConfigBand>,
1920}
1921/// One upstream speaker group in upstream order.
1922#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)]
1923#[ts(export)]
1924pub struct ConfigGroup {
1925    /// Stable presentation group id: front, center, sub, surround, back, wide, top, height or other.
1926    pub id: String,
1927    /// Upstream group name used as the project and crossover-map key.
1928    pub key: String,
1929    /// Indices into `ConfigResult.speakers` that belong to this group.
1930    pub speaker_indices: Vec<usize>,
1931}
1932/// Values derived from the complete speaker configuration.
1933#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)]
1934#[ts(export)]
1935pub struct ConfigSummary {
1936    /// Number of speakers.
1937    pub speaker_count: usize,
1938    /// Number of measurement outputs in use.
1939    pub outputs: Vec<i64>,
1940    /// Highest output channel in use.
1941    pub max_channel: i64,
1942    /// Number of output channels used twice or more.
1943    pub duplicate_outputs: Vec<i64>,
1944    /// Number of subwoofers.
1945    pub sub_count: usize,
1946}
1947/// Screen-facing editable speaker configuration.
1948#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)]
1949#[ts(export)]
1950pub struct ConfigResult {
1951    /// Speakers in table order.
1952    pub speakers: Vec<ConfigSpeaker>,
1953    /// Preset name, or `custom` after any manual edit.
1954    pub preset: String,
1955    /// Measurement output device name (`config.device`).
1956    pub device: String,
1957    /// Table group header rows in upstream order.
1958    pub groups: Vec<ConfigGroup>,
1959    /// Counts the summary line shows.
1960    pub summary: ConfigSummary,
1961}
1962/// Configuration after a destructive edit and its optional inverse token.
1963#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)]
1964#[ts(export)]
1965pub struct ConfigMutationResult {
1966    /// The configuration after the edit.
1967    pub config: ConfigResult,
1968    /// Token for `undo` when the edit cleared measurements (U5).
1969    pub undo_token: Option<String>,
1970}
1971/// Output sample-rate selection stored with a DSP profile.
1972#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, TS)]
1973#[serde(rename_all = "snake_case")]
1974#[ts(export)]
1975pub enum OutputRateChoice {
1976    /// Resolve the rate from the default output endpoint when exporting.
1977    Auto,
1978    /// Always export at this rate in Hz.
1979    Fixed(u32),
1980}
1981
1982/// The manually editable DSP profile fields.
1983#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)]
1984#[ts(export)]
1985pub struct DspFields {
1986    /// Output sample rate.
1987    pub output_rate: OutputRateChoice,
1988    /// Whether this profile permits changing the output rate.
1989    pub output_rate_editable: bool,
1990    /// FIR taps per channel.
1991    pub fir_taps: i64,
1992    /// Total FIR taps the DSP can run across channels.
1993    pub fir_budget: i64,
1994    /// IIR (PEQ) bands per channel.
1995    pub iir_bands: i64,
1996    /// All-pass bands per channel.
1997    pub allpass_bands: i64,
1998    /// Bass-management path delays the DSP offers.
1999    pub bm_path_delays: i64,
2000}
2001/// One DSP preset in the built-in table.
2002#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)]
2003#[ts(export)]
2004pub struct DspPreset {
2005    /// Preset key (`camilla`, `tesira`, `qsys`, `minidsp`, `custom`).
2006    pub key: String,
2007    /// Device name shown in the device list.
2008    pub name: String,
2009    /// The preset's filter resources.
2010    pub fields: DspFields,
2011}
2012/// A preset selection or a complete manual edit.
2013#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS, Default)]
2014#[ts(export)]
2015pub struct DspSetParams {
2016    /// Selects a preset; absent with `fields` set means a manual edit.
2017    pub preset: Option<String>,
2018    /// Manual values; any manual edit makes the profile `custom`.
2019    pub fields: Option<DspFields>,
2020}
2021/// Editable DSP state and derived resolution values.
2022#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
2023#[ts(export)]
2024pub struct DspResult {
2025    /// Current profile key.
2026    pub profile: String,
2027    /// Current device name.
2028    pub name: String,
2029    /// Current filter resources.
2030    pub fields: DspFields,
2031    /// Every preset, for the device list.
2032    pub presets: Vec<DspPreset>,
2033    /// FIR window length the taps give, in ms (note line).
2034    pub window_ms: f64,
2035    /// Frequency resolution the taps give, in Hz (note line).
2036    pub resolution_hz: f64,
2037}
2038/// Measurement timing-reference settings stored under `extra.devices`.
2039#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)]
2040#[ts(export)]
2041pub struct LayoutTiming {
2042    /// Timing reference: `acoustic`, `loopback` or `none`.
2043    pub reference: String,
2044    /// Reference speaker role for the acoustic reference (default `R`).
2045    pub role: String,
2046    /// Reference output channel for the loopback reference (1-based).
2047    pub output: i64,
2048}
2049/// One measurement microphone point in centimetres.
2050#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
2051#[ts(export)]
2052pub struct LayoutPoint {
2053    /// Position number; 1 is the listening position.
2054    pub position: usize,
2055    /// Left-right offset from the centre seat, in cm (`layout_map.py`).
2056    pub x_cm: f64,
2057    /// Front-back offset from the centre seat, in cm (`layout_map.py`).
2058    pub y_cm: f64,
2059    /// Height step: 0 at ear height, +1 or -1 for ±20 cm.
2060    pub height: i8,
2061}
2062/// One supported measurement arrangement.
2063#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
2064#[ts(export)]
2065pub struct LayoutArrangement {
2066    /// Number of positions: 1, 9, 13 or 17.
2067    pub count: usize,
2068    /// Microphone points of this arrangement.
2069    pub points: Vec<LayoutPoint>,
2070}
2071/// Editable arrangement and measurement options.
2072#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
2073#[ts(export)]
2074pub struct LayoutResult {
2075    /// Chosen arrangement (`extra['array']`).
2076    pub count: usize,
2077    /// Start delay before each position as stored (`extra['start_delay']`):
2078    /// one of [`crate::rules::START_DELAYS`], `끄기` or `5 초` to `15 초`.
2079    pub start_delay: String,
2080    /// Timing reference and its reference speaker or output.
2081    pub timing: LayoutTiming,
2082    /// Every arrangement with its geometry, for the cards and maps.
2083    pub arrangements: Vec<LayoutArrangement>,
2084}
2085/// Optional arrangement and timing edits.
2086#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS, Default)]
2087#[ts(export)]
2088pub struct LayoutSetParams {
2089    /// New arrangement; changing it clears measurements (U5).
2090    pub count: Option<usize>,
2091    /// New start delay, one of [`crate::rules::START_DELAYS`]; any other
2092    /// value answers `invalid_request` (field `start_delay`).
2093    pub start_delay: Option<String>,
2094    /// New timing reference.
2095    pub timing: Option<LayoutTiming>,
2096    /// Clears existing measurements; without it a project with measurements answers `confirm_required` (U5).
2097    #[serde(default)]
2098    pub confirm: bool,
2099}
2100/// Arrangement after editing and its optional inverse token.
2101#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
2102#[ts(export)]
2103pub struct LayoutMutationResult {
2104    /// The arrangement and options after the edit.
2105    pub layout: LayoutResult,
2106    /// Token for `undo` when the edit cleared measurements (U5).
2107    pub undo_token: Option<String>,
2108}
2109/// Position-duration estimate from upstream step 4 semantics.
2110#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
2111#[ts(export)]
2112pub struct PositionEstimateResult {
2113    /// Number of positions in the arrangement.
2114    pub positions: usize,
2115    /// Estimated time per position, in seconds (`step4_layout.position_seconds`).
2116    pub per_position_seconds: f64,
2117    /// Estimated time for every position, without moving the microphone, in seconds.
2118    pub total_seconds: f64,
2119}
2120/// Target control points.
2121#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
2122#[ts(export)]
2123pub struct TargetPointsParams {
2124    /// Target points as (Hz, dB); clamped to 10–24000 Hz and ±30 dB, at least two.
2125    pub points: Vec<(f64, f64)>,
2126}
2127/// One built-in target preset selection.
2128#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)]
2129#[ts(export)]
2130pub struct TargetPresetParams {
2131    /// Target preset: `flat`, `harman` or `cinema`.
2132    pub preset: String,
2133}
2134/// Target curve, selected preset, and built-in preset table.
2135#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
2136#[ts(export)]
2137pub struct TargetResult {
2138    /// Target points as (Hz, dB).
2139    pub points: Vec<(f64, f64)>,
2140    /// Preset name, or absent when the points were edited (custom).
2141    pub preset: Option<String>,
2142    /// Preset names the target menu offers.
2143    pub presets: Vec<(String, Vec<(f64, f64)>)>,
2144}
2145/// Complete calibration settings replacement.
2146#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
2147#[ts(export)]
2148pub struct CalibrationSettingsParams {
2149    /// The complete calibration settings to store.
2150    pub settings: CalibrationSettings,
2151}
2152/// Mode whose numeric specification should be returned.
2153#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
2154#[ts(export)]
2155pub struct ModeSpecParams {
2156    /// Correction mode: `zero`, `mixed`, `linear` or `ultra`.
2157    pub mode: Mode,
2158    /// Latency limit for the ultra mode, in ms.
2159    pub ultra_ms: Option<f64>,
2160    /// Whether MIMO support paths use FIR instead of IIR.
2161    #[serde(default, skip_serializing_if = "Option::is_none")]
2162    #[ts(optional)]
2163    pub mimo_fir: Option<bool>,
2164}
2165/// Presentation-neutral values underlying the upstream mode specification line.
2166#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
2167#[ts(export)]
2168pub struct ModeSpecResult {
2169    /// Room-correction filters: `iir` (IIR only) or `iir_fir` (IIR plus FIR).
2170    pub rc_filter: String,
2171    /// FIR taps the mode uses (0 without FIR).
2172    pub fir_taps: usize,
2173    /// PEQ bands per channel, when the mode uses IIR.
2174    pub peq_bands: Option<usize>,
2175    /// MIMO support filter kind (`fir` when requested, otherwise `iir`).
2176    pub mimo_filter: String,
2177    /// Delay the FIR may add ahead of the main arrival (`lift_ms`), in ms.
2178    pub lift_ms: f64,
2179    /// Octave fraction of the excess-phase smoothing (6, or 24 in linear and ultra modes).
2180    pub phase_frac: f64,
2181    /// Upper latency bound of the mode, in ms.
2182    pub max_latency_ms: f64,
2183}
2184/// Application theme preference.
2185#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, TS, Default)]
2186#[serde(rename_all = "snake_case")]
2187#[ts(export)]
2188pub enum AppTheme {
2189    /// Follow the operating-system preference.
2190    #[default]
2191    System,
2192    /// Always use the light theme.
2193    Light,
2194    /// Always use the dark theme.
2195    Dark,
2196}
2197/// The skin set the screen draws with (docs/skins, ADR 0010).
2198#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, TS, Default)]
2199#[serde(rename_all = "snake_case")]
2200#[ts(export)]
2201pub enum AppSkin {
2202    /// The instrument skin: the default tokens.
2203    #[default]
2204    Default,
2205    /// Hardware Rack: a 19-inch rack faceplate.
2206    Rack,
2207    /// Signal Matrix: a routing board of cells on a grid.
2208    Matrix,
2209}
2210/// The logo on the rail and the window (docs/DEVIATIONS.md U12). The
2211/// installed program's own icon is always `Expert`.
2212#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, TS, Default)]
2213#[serde(rename_all = "snake_case")]
2214#[ts(export)]
2215pub enum AppIcon {
2216    /// "전문가 모드": upstream's confirmed logo (`logo_b8.svg`).
2217    #[default]
2218    Expert,
2219    /// "킹반인 모드": SECS 2R's own logo (`apps/secs2r/icons/logo/civilian.svg`),
2220    /// a measured response and its correction on the target.
2221    Civilian,
2222}
2223/// Opt-in loopback API settings.
2224#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, TS)]
2225#[ts(export)]
2226pub struct LocalApiSettings {
2227    /// Whether the app starts the local API server.
2228    pub enabled: bool,
2229    /// Loopback TCP port; zero asks the operating system for a free port.
2230    pub port: u16,
2231}
2232impl Default for LocalApiSettings {
2233    fn default() -> Self {
2234        Self {
2235            enabled: false,
2236            port: crate::local_api::DEFAULT_PORT,
2237        }
2238    }
2239}
2240
2241/// How far SECS 2R controls one application target.
2242#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize, TS)]
2243#[serde(rename_all = "snake_case")]
2244#[ts(export)]
2245pub enum ApplyLevel {
2246    /// Only write ordinary export files.
2247    #[default]
2248    Files,
2249    /// Apply on explicit request while the app is running.
2250    Apply,
2251    /// Keep the applied design active through the managed service.
2252    Manage,
2253}
2254
2255/// CamillaDSP application settings.
2256#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)]
2257#[ts(export)]
2258pub struct CamillaApply {
2259    /// Selected control level.
2260    pub level: ApplyLevel,
2261    /// Plain websocket address in `host:port` form.
2262    pub address: String,
2263    /// CamillaDSP executable selected by the user for managed operation.
2264    #[serde(default, skip_serializing_if = "Option::is_none")]
2265    #[ts(optional)]
2266    pub exe_path: Option<String>,
2267}
2268impl Default for CamillaApply {
2269    fn default() -> Self {
2270        Self {
2271            level: ApplyLevel::Files,
2272            address: "127.0.0.1:1234".into(),
2273            exe_path: None,
2274        }
2275    }
2276}
2277
2278/// Equalizer APO application settings.
2279#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, TS)]
2280#[ts(export)]
2281pub struct EqApoApply {
2282    /// Selected control level.
2283    pub level: ApplyLevel,
2284}
2285
2286/// Settings for applying designs to external processors.
2287#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, TS)]
2288#[ts(export)]
2289pub struct ApplySettings {
2290    /// CamillaDSP settings.
2291    pub camilla: CamillaApply,
2292    /// Equalizer APO settings.
2293    pub eqapo: EqApoApply,
2294}
2295
2296/// Optional device choices for a CamillaDSP application export.
2297#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, TS)]
2298#[ts(export)]
2299pub struct ApplyCamillaParams {
2300    /// Capture and playback choices; absent keeps file placeholders.
2301    #[serde(default, skip_serializing_if = "Option::is_none")]
2302    #[ts(optional)]
2303    pub camilla_devices: Option<CamillaDevices>,
2304}
2305
2306/// Equalizer APO edition detected from its installed path.
2307#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, TS)]
2308#[serde(rename_all = "snake_case")]
2309#[ts(export)]
2310pub enum EqApoVariant {
2311    /// The SourceForge Equalizer APO release.
2312    Official,
2313    /// EqualizerAPO-XT.
2314    Xt,
2315    /// An installation whose path does not identify either edition.
2316    Unknown,
2317}
2318
2319/// Equalizer APO installation values supplied by the operating-system adapter.
2320#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
2321pub struct EqApoInstall {
2322    /// Equalizer APO configuration directory.
2323    pub config_path: String,
2324    /// Equalizer APO installation directory.
2325    pub install_path: String,
2326    /// Detected edition.
2327    pub variant: EqApoVariant,
2328}
2329
2330/// State of SECS 2R's managed lines in Equalizer APO's `config.txt`.
2331#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, TS)]
2332#[serde(rename_all = "snake_case")]
2333#[ts(export)]
2334pub enum IncludeState {
2335    /// No managed marker exists.
2336    Absent,
2337    /// The marker and include line form one intact pair.
2338    Present,
2339    /// A marker exists without exactly one intact include pair.
2340    Damaged,
2341}
2342
2343/// One CamillaDSP process kept running by the host service.
2344#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)]
2345#[ts(export)]
2346pub struct ManagedCamilla {
2347    pub exe_path: String,
2348    pub config_path: String,
2349    pub port: u16,
2350    pub design_id: String,
2351}
2352
2353/// One Equalizer APO include kept intact by the host service.
2354#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)]
2355#[ts(export)]
2356pub struct ManagedEqApo {
2357    pub config_path: String,
2358    pub design_id: String,
2359}
2360
2361/// Targets persisted by the host service.
2362#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, TS)]
2363#[ts(export)]
2364pub struct HostManaged {
2365    #[serde(default, skip_serializing_if = "Option::is_none")]
2366    #[ts(optional)]
2367    pub camilla: Option<ManagedCamilla>,
2368    #[serde(default, skip_serializing_if = "Option::is_none")]
2369    #[ts(optional)]
2370    pub eqapo: Option<ManagedEqApo>,
2371    /// Interactive session that selected these targets.
2372    #[serde(default, skip_serializing_if = "Option::is_none")]
2373    #[ts(skip)]
2374    pub owner_session_id: Option<u32>,
2375    /// Stable SID bytes of that session's user token.
2376    #[serde(default, skip_serializing_if = "Option::is_none")]
2377    #[ts(skip)]
2378    pub owner_user_sid: Option<String>,
2379}
2380
2381/// A request sent over the local managed-host pipe.
2382#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)]
2383#[serde(tag = "method", content = "params", rename_all = "snake_case")]
2384#[ts(export)]
2385pub enum HostRequest {
2386    Status,
2387    SetManaged(HostManaged),
2388    StopManaging,
2389    Log {
2390        lines: u32,
2391    },
2392    /// Replaces the service with the signed `secs2r-host.exe` next to
2393    /// `secs2r-host.json` in `from_dir` (ADR 0020).
2394    UpdateSelf {
2395        from_dir: String,
2396    },
2397}
2398
2399/// One JSON Lines entry from the managed host log.
2400#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)]
2401#[ts(export)]
2402pub struct HostLogLine {
2403    /// UTC timestamp in RFC 3339 form.
2404    pub timestamp: String,
2405    /// Stable machine-readable event name.
2406    pub event: String,
2407    /// Event-specific string values such as a PID, path, or reason.
2408    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
2409    pub fields: BTreeMap<String, String>,
2410}
2411
2412/// Why a managed CamillaDSP process is not simply running.
2413#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)]
2414#[serde(tag = "kind", rename_all = "snake_case")]
2415#[ts(export)]
2416pub enum ManagedProcessState {
2417    Running,
2418    BackingOff { until: String },
2419    GivenUp { reason: String },
2420    Stopped,
2421    NoSession,
2422    OtherUser,
2423}
2424
2425/// Current CamillaDSP supervision state.
2426#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)]
2427#[ts(export)]
2428pub struct ManagedProcess {
2429    pub state: ManagedProcessState,
2430    #[ts(type = "number | null")]
2431    pub pid: Option<u32>,
2432    pub restarts_in_window: u32,
2433}
2434
2435impl Default for ManagedProcess {
2436    fn default() -> Self {
2437        Self {
2438            state: ManagedProcessState::Stopped,
2439            pid: None,
2440            restarts_in_window: 0,
2441        }
2442    }
2443}
2444
2445/// Status returned by the managed host service.
2446#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)]
2447#[ts(export)]
2448pub struct HostStatus {
2449    pub version: String,
2450    pub managed: HostManaged,
2451    pub camilla: ManagedProcess,
2452    pub eqapo_include: IncludeState,
2453    pub last_repair: Option<String>,
2454}
2455
2456/// One response returned over the local managed-host pipe.
2457#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)]
2458#[serde(tag = "kind", content = "data", rename_all = "snake_case")]
2459#[ts(export)]
2460pub enum HostResponse {
2461    Status(Box<HostStatus>),
2462    Ok,
2463    Log(Vec<HostLogLine>),
2464    Error(IpcError),
2465}
2466
2467/// Windows service state visible to the app before a pipe call.
2468#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize, TS)]
2469#[serde(rename_all = "snake_case")]
2470#[ts(export)]
2471pub enum ServiceState {
2472    #[default]
2473    NotInstalled,
2474    Stopped,
2475    Running,
2476    Unreachable,
2477}
2478
2479/// How the running CamillaDSP configuration compares with the current result.
2480#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)]
2481#[serde(tag = "kind", rename_all = "snake_case")]
2482#[ts(export)]
2483pub enum DesignMatch {
2484    /// The title and embedded identity match the current design.
2485    This { design_id: String },
2486    /// CamillaDSP runs another titled configuration.
2487    Other { title: String },
2488    /// There is not enough information to identify the running design.
2489    Unknown,
2490}
2491
2492/// CamillaDSP status mirrored from the platform-neutral application client.
2493#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
2494#[ts(export)]
2495pub struct CamillaStatus {
2496    pub version: String,
2497    pub state: String,
2498    pub stop_reason: Option<String>,
2499    pub title: Option<String>,
2500    pub description: Option<String>,
2501    pub config_path: Option<String>,
2502    pub capture_rate: Option<u32>,
2503    #[ts(type = "number | null")]
2504    pub clipped_samples: Option<u64>,
2505    pub processing_load_pct: Option<f64>,
2506    pub playback_peak_db: Option<Vec<f64>>,
2507}
2508
2509/// Reachability and running design reported by CamillaDSP.
2510#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
2511#[ts(export)]
2512pub struct CamillaApplyStatus {
2513    pub reachable: bool,
2514    pub error: Option<IpcError>,
2515    pub status: Option<CamillaStatus>,
2516    pub design: DesignMatch,
2517}
2518
2519/// Installed and applied state of Equalizer APO.
2520#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)]
2521#[ts(export)]
2522pub struct EqApoApplyStatus {
2523    pub installed: bool,
2524    pub variant: EqApoVariant,
2525    pub config_path: Option<String>,
2526    pub include: IncludeState,
2527    pub applied_design_id: Option<String>,
2528}
2529
2530/// Current state of both application targets.
2531#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
2532#[ts(export)]
2533pub struct ApplyStatus {
2534    pub camilla: CamillaApplyStatus,
2535    pub eqapo: EqApoApplyStatus,
2536    /// Windows managed-host service state.
2537    #[serde(default)]
2538    pub host: ServiceState,
2539    /// Detailed host state when the service is running and reachable.
2540    #[serde(default, skip_serializing_if = "Option::is_none")]
2541    #[ts(optional)]
2542    pub host_status: Option<Box<HostStatus>>,
2543    /// Design ID of the current result, absent without one; the screen
2544    /// compares Equalizer APO's `applied_design_id` with it.
2545    #[serde(default)]
2546    pub current_design_id: Option<String>,
2547}
2548
2549/// Result of applying an exported design.
2550#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)]
2551#[serde(tag = "kind", rename_all = "snake_case")]
2552#[ts(export)]
2553pub enum ApplyOutcome {
2554    /// The target accepted the design.
2555    Applied,
2556    /// No CamillaDSP was running; the managed host will start it with the design.
2557    HandedOver,
2558    /// CamillaDSP rejected reload and the previous path was restored.
2559    RolledBack { error: IpcError },
2560}
2561
2562/// Completed application job result.
2563#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)]
2564#[ts(export)]
2565pub struct ApplyResult {
2566    pub outcome: ApplyOutcome,
2567    pub design_id: String,
2568    pub folder: String,
2569    pub stale: bool,
2570}
2571
2572/// Application-local settings, independent of an open project.
2573#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)]
2574#[ts(export)]
2575pub struct AppSettings {
2576    /// Application-local compute preference; never stored in an upstream project.
2577    #[serde(default)]
2578    pub compute: ComputePreference,
2579    /// Screen language: `ko` or `en`.
2580    pub language: String,
2581    /// Application theme preference.
2582    #[serde(default)]
2583    pub theme: AppTheme,
2584    /// Logo on the rail and the window.
2585    #[serde(default)]
2586    pub icon: AppIcon,
2587    /// Skin set the screen draws with.
2588    #[serde(default)]
2589    pub skin: AppSkin,
2590    /// Opt-in loopback API server.
2591    #[serde(default)]
2592    pub local_api: LocalApiSettings,
2593    /// Applying designs to CamillaDSP and Equalizer APO.
2594    #[serde(default)]
2595    pub apply: ApplySettings,
2596    /// When to look for and install new releases.
2597    #[serde(default)]
2598    pub updates: UpdatePolicy,
2599    /// Recently opened project paths, newest first (at most 10).
2600    pub recent_projects: Vec<String>,
2601    /// Last window size in logical pixels.
2602    pub last_window_size: Option<(u32, u32)>,
2603}
2604impl Default for AppSettings {
2605    fn default() -> Self {
2606        Self {
2607            language: "ko".into(),
2608            compute: ComputePreference::Auto,
2609            theme: AppTheme::System,
2610            icon: AppIcon::Expert,
2611            skin: AppSkin::Default,
2612            local_api: LocalApiSettings::default(),
2613            apply: ApplySettings::default(),
2614            updates: UpdatePolicy::Auto,
2615            recent_projects: Vec::new(),
2616            last_window_size: None,
2617        }
2618    }
2619}
2620/// Complete application-local settings replacement.
2621#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)]
2622#[ts(export)]
2623pub struct AppSettingsParams {
2624    /// The complete app settings to store.
2625    pub settings: AppSettings,
2626}
2627
2628/// When SECS 2R looks for and installs new releases (ADR 0020).
2629#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize, TS)]
2630#[serde(rename_all = "snake_case")]
2631#[ts(export)]
2632pub enum UpdatePolicy {
2633    /// Check, download in the background and install when the app closes.
2634    #[default]
2635    Auto,
2636    /// Check and report a newer release; download only on request.
2637    Notify,
2638    /// Never contact the release server.
2639    Off,
2640}
2641
2642/// When a downloaded release is installed.
2643#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, TS)]
2644#[serde(rename_all = "snake_case")]
2645#[ts(export)]
2646pub enum UpdateInstall {
2647    /// When the app closes, or at once with a restart.
2648    OnExit,
2649    /// Only when the user asks (a package that needs an administrator password).
2650    OnRequest,
2651}
2652
2653/// Where the application update stands.
2654#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)]
2655#[serde(tag = "kind", rename_all = "snake_case")]
2656#[ts(export)]
2657pub enum UpdatePhase {
2658    /// The policy is `off`, or this build has no updater.
2659    Off,
2660    /// No check has finished since the app started.
2661    Idle,
2662    /// A check is running.
2663    Checking,
2664    /// The last check found no newer release.
2665    UpToDate,
2666    /// A newer release waits for a download request (policy `notify`).
2667    Available { version: String },
2668    /// A newer release is being downloaded.
2669    Downloading {
2670        version: String,
2671        #[ts(type = "number")]
2672        received: u64,
2673        #[ts(type = "number | null")]
2674        total: Option<u64>,
2675    },
2676    /// A newer release is downloaded and verified.
2677    Ready {
2678        version: String,
2679        install: UpdateInstall,
2680    },
2681    /// The installer is starting; the app closes next.
2682    Installing { version: String },
2683    /// A newer release exists, but this portable copy is replaced by hand.
2684    Portable { version: String, url: String },
2685    /// The last check, download or install failed.
2686    Failed { reason: String },
2687}
2688
2689/// Shown once when the app starts a newer version than it ran last time.
2690#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)]
2691#[ts(export)]
2692pub struct UpdateNotice {
2693    /// Version that downloaded the update.
2694    pub from: String,
2695    /// Version now running.
2696    pub to: String,
2697    /// The release's CHANGELOG section (Markdown).
2698    pub notes: String,
2699    /// Releases between `from` and `to` were skipped; their notes are only on
2700    /// the release page.
2701    pub skipped: bool,
2702    /// The release page of `to`.
2703    pub release_url: String,
2704}
2705
2706/// The release whose page [`Request::UpdateOpenRelease`] opens.
2707#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)]
2708#[ts(export)]
2709pub struct UpdateOpenReleaseParams {
2710    /// A release version such as `0.36.0`, without the `v` of its tag.
2711    pub version: String,
2712}
2713
2714/// Application update state for the screen.
2715#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)]
2716#[ts(export)]
2717pub struct UpdateStatus {
2718    /// Version now running.
2719    pub current: String,
2720    /// Stored policy.
2721    pub policy: UpdatePolicy,
2722    pub phase: UpdatePhase,
2723    /// When the last check finished, RFC 3339 UTC.
2724    pub checked_at: Option<String>,
2725    /// The one-time "updated" notice, until dismissed.
2726    pub notice: Option<UpdateNotice>,
2727}
2728
2729/// A downloaded release waiting for its first start: `update.json` in the
2730/// app's config folder, written by the app or the host shell and read by the
2731/// app on its next start. Not sent over IPC.
2732#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
2733pub struct PendingUpdate {
2734    /// Version that downloaded the update.
2735    pub from: String,
2736    /// Version that will run after the install.
2737    pub to: String,
2738    /// The release's CHANGELOG section (Markdown).
2739    pub notes: String,
2740    /// The release before `to`, from the update manifest's `previous` field.
2741    #[serde(default, skip_serializing_if = "Option::is_none")]
2742    pub previous: Option<String>,
2743}
2744
2745/// App-facing state of the opt-in local API server.
2746#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)]
2747#[ts(export)]
2748pub struct LocalApiStatus {
2749    /// Configured enabled state.
2750    pub enabled: bool,
2751    /// Configured port, or the selected free port while running with port zero.
2752    pub port: u16,
2753    /// Whether a listener is currently running.
2754    pub running: bool,
2755    /// Most recent startup failure, when present.
2756    pub error: Option<String>,
2757    /// Loopback base URL.
2758    pub url: String,
2759    /// Current bearer token.
2760    pub token: String,
2761    /// Full token-file path.
2762    pub token_path: String,
2763}
2764
2765/// Why a call failed. The screen maps each code to a written message with the
2766/// cause and the next action.
2767#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, TS)]
2768#[serde(rename_all = "snake_case")]
2769#[ts(export)]
2770pub enum ErrorCode {
2771    /// The request did not parse or named an unknown method.
2772    InvalidRequest,
2773    /// A bug: the service failed in a way it does not expect.
2774    Internal,
2775    /// The method is registered but not connected yet.
2776    NotImplemented,
2777    /// The method opens a window or program and is unavailable to local API clients.
2778    UiOnly,
2779    /// The selected operation or control level is unavailable on this host.
2780    Unsupported,
2781    /// A target file could not be changed because access was denied.
2782    PermissionDenied,
2783    /// CamillaDSP or Equalizer APO refused or failed an application request.
2784    ApplyFailed,
2785    /// The call requires an open project.
2786    ProjectNotOpen,
2787    /// Opening, reading, or writing project data failed.
2788    ProjectIo,
2789    /// Another job in the same group is running.
2790    JobBusy,
2791    /// The named job does not exist.
2792    JobNotFound,
2793    /// The caller cancelled the operation.
2794    Cancelled,
2795    /// Project measurements or settings are not valid engine inputs.
2796    EngineInput,
2797    /// Explicit GPU execution was requested but no usable GPU backend is available.
2798    ComputeUnavailable,
2799    /// The requested exporter failed.
2800    ExportFailed,
2801    /// The chosen export cannot carry the result (upstream
2802    /// `filter_export_block`); `params.reason` is an [`ExportBlock`] name.
2803    ExportScope,
2804    /// Cached results no longer match project inputs.
2805    StaleInputs,
2806    /// The audio backend or selected endpoint is unavailable.
2807    DeviceUnavailable,
2808    /// Recording completed but was discarded because it had a gap or corrupt samples.
2809    RecordingFailed,
2810    /// The backend refused a pinned audio share mode.
2811    ShareModeRefused,
2812    /// The REW API cannot be reached.
2813    RewUnreachable,
2814    /// REW requires a Pro license for this operation.
2815    RewProRequired,
2816    /// REW returned an HTTP or schema failure.
2817    RewFailed,
2818    /// A measurement setting or plan field is invalid.
2819    MeasurementInput,
2820    /// Tutorial sessions cannot save or export project data.
2821    TutorialBlocked,
2822    /// A destructive edit needs explicit confirmation while measurements exist.
2823    ConfirmRequired,
2824}
2825/// A coded IPC failure with template parameters and diagnostic detail.
2826#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)]
2827#[ts(export)]
2828pub struct IpcError {
2829    /// Stable error code translated by the screen.
2830    pub code: ErrorCode,
2831    /// Values for the message template of `code` (file names, counts, ...).
2832    pub params: BTreeMap<String, String>,
2833    /// Whether trying the same call again can succeed.
2834    pub retryable: bool,
2835    /// The raw error text, for the details view and the log only.
2836    pub detail: String,
2837}
2838impl IpcError {
2839    /// Creates a non-retryable error without template parameters.
2840    pub fn new(code: ErrorCode, detail: impl Into<String>) -> Self {
2841        Self {
2842            code,
2843            params: BTreeMap::new(),
2844            retryable: false,
2845            detail: detail.into(),
2846        }
2847    }
2848    /// Adds one screen message-template parameter.
2849    pub fn with_param(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
2850        self.params.insert(key.into(), value.into());
2851        self
2852    }
2853}
2854
2855/// The reply to every call: `{"ok": true, "data": ...}` or
2856/// `{"ok": false, "error": ...}`.
2857///
2858/// The TypeScript side declares the same union in `src/ipc/client.ts`
2859/// (`Envelope`); `envelope_wire_shape` below pins the JSON both sides rely on.
2860#[derive(Debug, Clone, PartialEq)]
2861pub enum Envelope {
2862    /// The `Ok` Envelope variant.
2863    Ok(Box<Response>),
2864    /// The `Err` Envelope variant.
2865    Err(IpcError),
2866}
2867impl Serialize for Envelope {
2868    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
2869        use serde::ser::SerializeStruct;
2870        let mut state = serializer.serialize_struct("Envelope", 2)?;
2871        match self {
2872            Self::Ok(data) => {
2873                state.serialize_field("ok", &true)?;
2874                state.serialize_field("data", data)?;
2875            }
2876            Self::Err(error) => {
2877                state.serialize_field("ok", &false)?;
2878                state.serialize_field("error", error)?;
2879            }
2880        }
2881        state.end()
2882    }
2883}
2884
2885#[cfg(test)]
2886mod tests {
2887    use super::*;
2888
2889    /// One value of every variant. A new variant fails to compile here until
2890    /// it gets an example, which `method_names_match_the_wire` then checks.
2891    fn examples() -> Vec<Request> {
2892        vec![
2893            Request::Bootstrap,
2894            Request::ProjectNew(ProjectNewParams {
2895                path: "x.secs".into(),
2896                preset: "2.1".into(),
2897                sub_count: 1,
2898                sample: false,
2899                tutorial: false,
2900            }),
2901            Request::ProjectOpen(ProjectPathParams {
2902                path: "x.secs".into(),
2903            }),
2904            Request::ProjectSave(ProjectSaveParams::default()),
2905            Request::ProjectInfo,
2906            Request::SampleLoad(SampleLoadParams::default()),
2907            Request::Calibrate(CalibrateParams::default()),
2908            Request::RecommendXo,
2909            Request::Mimo(MimoParams::default()),
2910            Request::Results,
2911            Request::Export(ExportParams {
2912                kind: ExportKind::CamillaDsp,
2913                folder: ".".into(),
2914                mdat_scope: None,
2915                design_name: None,
2916                camilla_devices: None,
2917                extra_rates: Vec::new(),
2918            }),
2919            Request::JobCancel(JobCancelParams { job: JobId(1) }),
2920            Request::Jobs,
2921            Request::MeasureMethods,
2922            Request::MeasureConfigure(MeasureConfigureParams::default()),
2923            Request::MeasureConfigGet,
2924            Request::MeasurementRecords,
2925            Request::MicCalibrationGet,
2926            Request::MicCalibrationSet(MicCalibrationSetParams {
2927                path: "mic.txt".into(),
2928            }),
2929            Request::MicCalibrationClear,
2930            Request::MicCalibrationAttach,
2931            Request::LevelsGet,
2932            Request::LevelsFillDefaults,
2933            Request::LevelStop,
2934            Request::MeasurePosition(MeasurePositionParams { position: 1 }),
2935            Request::PositionClear(PositionClearParams { position: 1 }),
2936            Request::Undo(UndoParams { token: "x".into() }),
2937            Request::RewLaunch,
2938            Request::MdatScan(MdatScanParams {
2939                path: "x.mdat".into(),
2940            }),
2941            Request::MdatImport(MdatImportParams {
2942                path: "x.mdat".into(),
2943                assignments: vec![],
2944                position: 1,
2945            }),
2946            Request::ConfigGet,
2947            Request::ConfigApplyPreset(ConfigPresetParams {
2948                preset: "2.1".into(),
2949                confirm: false,
2950            }),
2951            Request::ConfigSetSubCount(ConfigSubCountParams {
2952                count: 2,
2953                confirm: false,
2954            }),
2955            Request::ConfigSetSpeaker(ConfigSetSpeakerParams {
2956                index: 0,
2957                role: Some("L".into()),
2958                size: None,
2959                band_index: Some(0),
2960                out: Some(1),
2961                pol: Some("+".into()),
2962            }),
2963            Request::ConfigAddSpeaker,
2964            Request::ConfigRemoveSpeaker(ConfigIndexParams { index: 0 }),
2965            Request::ConfigRenumber,
2966            Request::ConfigValidate,
2967            Request::PatchSheetCsv(PathParams {
2968                path: "patch.csv".into(),
2969            }),
2970            Request::DspGet,
2971            Request::DspSet(DspSetParams {
2972                preset: Some("tesira".into()),
2973                fields: None,
2974            }),
2975            Request::LayoutGet,
2976            Request::LayoutSet(LayoutSetParams {
2977                count: Some(9),
2978                ..Default::default()
2979            }),
2980            Request::PositionEstimate,
2981            Request::TargetGet,
2982            Request::TargetSetPoints(TargetPointsParams {
2983                points: vec![(20.0, 0.0), (20_000.0, 0.0)],
2984            }),
2985            Request::TargetApplyPreset(TargetPresetParams {
2986                preset: "flat".into(),
2987            }),
2988            Request::TargetSave(PathParams {
2989                path: "target.json".into(),
2990            }),
2991            Request::TargetLoad(PathParams {
2992                path: "target.json".into(),
2993            }),
2994            Request::CalibrationSettingsGet,
2995            Request::CalibrationSettingsEdit(CalibrationSettingsEditParams {
2996                edit: crate::settings_edit::SettingEdit::MimoOn { on: true },
2997            }),
2998            Request::SubWarnings,
2999            Request::RewInfo,
3000            Request::RewDriverSet(RewDriverSetParams {
3001                driver: "ASIO".into(),
3002            }),
3003            Request::CalibrationSettingsSet(CalibrationSettingsParams {
3004                settings: CalibrationSettings::default(),
3005            }),
3006            Request::ModeSpec(ModeSpecParams {
3007                mode: Mode::Mixed,
3008                ultra_ms: None,
3009                mimo_fir: None,
3010            }),
3011            Request::AppSettingsGet,
3012            Request::AppSettingsSet(AppSettingsParams {
3013                settings: AppSettings::default(),
3014            }),
3015            Request::ApplyStatus,
3016            Request::ApplyCamilla(ApplyCamillaParams::default()),
3017            Request::ApplyEqapo,
3018            Request::RevertEqapo,
3019            Request::ApplySettingsSet(ApplySettings::default()),
3020            Request::HostInstall,
3021            Request::HostUninstall,
3022            Request::HostStopManaging,
3023            Request::UpdateStatus,
3024            Request::UpdateCheck,
3025            Request::UpdateDownload,
3026            Request::UpdateRestart,
3027            Request::UpdateNoticeDismiss,
3028            Request::UpdateOpenRelease(UpdateOpenReleaseParams {
3029                version: "0.36.0".into(),
3030            }),
3031            Request::LocalApiStatus,
3032            Request::LocalApiTokenRegenerate,
3033            Request::ComputeStatus,
3034            Request::OpenGpuHelp,
3035            Request::MeasurementCurves(MeasurementCurvesParams::default()),
3036            Request::ResultCurves(ResultCurvesParams {
3037                tab: ResultTab::Spl,
3038                channel: None,
3039                group: None,
3040                xo_hz: None,
3041                corrected: None,
3042            }),
3043            Request::ResultLines,
3044            Request::SubTakeValues,
3045            Request::DialogOpenProject,
3046            Request::DialogSaveProject(DialogSuggestedParams {
3047                suggested: "x.secs".into(),
3048            }),
3049            Request::DialogPickMdat,
3050            Request::DialogPickFolder(DialogPickFolderParams { start: None }),
3051            Request::DialogSaveFile(DialogSaveFileParams {
3052                kind: SaveFileKind::PatchSheet,
3053                suggested: "x.csv".into(),
3054            }),
3055            Request::DialogOpenFile(DialogOpenFileParams {
3056                kind: OpenFileKind::Target,
3057            }),
3058            Request::OpenFolder(OpenFolderParams { path: ".".into() }),
3059            Request::LevelMonitorStart(LevelMonitorStartParams::default()),
3060            Request::LevelMonitorStop,
3061            Request::LevelPlay(LevelPlayParams {
3062                role: "L".into(),
3063                master_dbfs: -20.0,
3064            }),
3065            Request::StatusWatchStart,
3066            Request::StatusWatchStop,
3067            Request::ExportFolderGet,
3068            Request::ExportFolderSet(ExportFolderSetParams { folder: ".".into() }),
3069        ]
3070    }
3071    #[test]
3072    fn method_names_match_the_wire() {
3073        let examples = examples();
3074        assert_eq!(examples.len(), Request::METHODS.len());
3075        for request in examples {
3076            let wire = serde_json::to_value(&request).unwrap();
3077            assert_eq!(wire["method"], request.method());
3078        }
3079    }
3080    #[test]
3081    fn every_method_name_is_listed_and_parses() {
3082        for request in examples() {
3083            let wire = serde_json::to_value(&request).unwrap();
3084            let parsed: Request = serde_json::from_value(wire).unwrap();
3085            assert_eq!(parsed.method(), request.method());
3086        }
3087    }
3088    #[test]
3089    fn old_app_settings_without_local_api_use_the_disabled_default() {
3090        let settings: AppSettings = serde_json::from_str(
3091            r#"{"language":"ko","recent_projects":[],"last_window_size":null}"#,
3092        )
3093        .unwrap();
3094        assert_eq!(settings.local_api, LocalApiSettings::default());
3095        assert!(!settings.local_api.enabled);
3096        assert_eq!(settings.local_api.port, crate::local_api::DEFAULT_PORT);
3097    }
3098
3099    #[test]
3100    fn calibrate_mimo_defaults_false_on_the_wire() {
3101        let old: CalibrateParams =
3102            serde_json::from_str(r#"{"settings":null,"subs_only":false}"#).unwrap();
3103        assert!(!old.mimo);
3104        assert_eq!(CalibrateParams::default(), old);
3105        let wire = serde_json::to_value(CalibrateParams {
3106            mimo: true,
3107            ..Default::default()
3108        })
3109        .unwrap();
3110        assert_eq!(wire["mimo"], true);
3111    }
3112
3113    #[test]
3114    fn mdat_scope_is_optional_on_the_wire() {
3115        let old: ExportParams =
3116            serde_json::from_str(r#"{"kind":"before_after_mdat","folder":""}"#).unwrap();
3117        assert_eq!(old.mdat_scope, None);
3118        assert!(old.extra_rates.is_empty());
3119        assert_eq!(old.mdat_scope.unwrap_or_default(), MdatScope::All);
3120        let wire = serde_json::to_value(&old).unwrap();
3121        assert!(wire.get("mdat_scope").is_none());
3122        let scoped = ExportParams {
3123            mdat_scope: Some(MdatScope::Measurements),
3124            design_name: None,
3125            camilla_devices: None,
3126            ..old
3127        };
3128        let wire = serde_json::to_value(&scoped).unwrap();
3129        assert_eq!(wire["mdat_scope"], "measurements");
3130        assert_eq!(
3131            serde_json::from_value::<ExportParams>(wire).unwrap(),
3132            scoped
3133        );
3134    }
3135    #[test]
3136    fn envelope_wire_shape() {
3137        let ok = Envelope::Ok(Box::new(Response::Bootstrap(BootstrapInfo {
3138            app_name: "SECS 2R".into(),
3139            version: "0.0.1".into(),
3140            prerelease: true,
3141            upstream: UpstreamBase {
3142                name: "SECS".into(),
3143                repository: "https://example.invalid/secs".into(),
3144                version: "Beta".into(),
3145                commit: "0".repeat(40),
3146                date: "2026-10-12".into(),
3147            },
3148            platform: Platform {
3149                os: "linux".into(),
3150                arch: "x86_64".into(),
3151            },
3152        })));
3153        let value = serde_json::to_value(ok).unwrap();
3154        assert_eq!(value["ok"], true);
3155        assert_eq!(value["data"]["method"], "bootstrap");
3156        let value = serde_json::to_value(Envelope::Err(IpcError::new(
3157            ErrorCode::InvalidRequest,
3158            "bad",
3159        )))
3160        .unwrap();
3161        assert_eq!(value["ok"], false);
3162        assert_eq!(value["error"]["code"], "invalid_request");
3163    }
3164
3165    #[test]
3166    fn compute_completion_events_are_payload_free_markers() {
3167        for (result, kind) in [
3168            (JobResult::Calibration, "calibration"),
3169            (JobResult::Mimo, "mimo"),
3170        ] {
3171            let event = JobEvent::Finished {
3172                job: JobId(1),
3173                status: JobStatus::Succeeded,
3174                result: Some(Box::new(result)),
3175                error: None,
3176            };
3177            let wire = serde_json::to_vec(&event).unwrap();
3178            let value: serde_json::Value = serde_json::from_slice(&wire).unwrap();
3179            assert_eq!(value["result"], serde_json::json!({ "kind": kind }));
3180            assert!(wire.len() < 128, "completion must not carry a design");
3181            assert_eq!(serde_json::from_slice::<JobEvent>(&wire).unwrap(), event);
3182        }
3183    }
3184
3185    #[test]
3186    fn job_snapshot_is_metadata_without_a_result_payload() {
3187        let snapshot = JobSnapshot {
3188            job: JobId(42),
3189            kind: JobKind::Mimo,
3190            status: JobStatus::Succeeded,
3191            cancellable: false,
3192            progress: None,
3193            error: None,
3194        };
3195        let wire = serde_json::to_value(&snapshot).unwrap();
3196        assert!(wire.get("result").is_none());
3197        assert_eq!(
3198            serde_json::from_value::<JobSnapshot>(wire).unwrap(),
3199            snapshot
3200        );
3201    }
3202
3203    #[test]
3204    fn filter_export_scope_follows_upstream_but_eqapo_carries_mimo_f12() {
3205        use ExportKind::*;
3206        for kind in [
3207            CamillaDsp,
3208            StagedMdat,
3209            BeforeAfterMdat,
3210            EqualizerApo,
3211            Convolution,
3212        ] {
3213            for (subs, mimo) in [(false, false), (true, false), (false, true), (true, true)] {
3214                assert_eq!(filter_export_block(kind, subs, mimo), None, "{kind:?}");
3215            }
3216        }
3217        assert_eq!(filter_export_block(FilterText, false, false), None);
3218        assert_eq!(
3219            export_block(StagedMdat, false, false, true),
3220            Some(ExportBlock::StaleCache)
3221        );
3222        assert_eq!(
3223            export_block(BeforeAfterMdat, true, true, true),
3224            Some(ExportBlock::StaleCache)
3225        );
3226        assert_eq!(export_block(CamillaDsp, true, true, true), None);
3227        assert_eq!(
3228            filter_export_block(FilterText, true, false),
3229            Some(ExportBlock::Subs)
3230        );
3231        assert_eq!(
3232            filter_export_block(FilterText, true, true),
3233            Some(ExportBlock::Subs)
3234        );
3235        assert_eq!(
3236            filter_export_block(FilterText, false, true),
3237            Some(ExportBlock::Mimo)
3238        );
3239        assert_eq!(serde_json::to_value(FilterText).unwrap(), "filter_text");
3240        assert_eq!(serde_json::to_value(EqualizerApo).unwrap(), "equalizer_apo");
3241        assert_eq!(serde_json::to_value(Convolution).unwrap(), "convolution");
3242        assert_eq!(
3243            serde_json::to_value(ExportBlock::Subs).unwrap(),
3244            ExportBlock::Subs.name()
3245        );
3246        assert_eq!(
3247            serde_json::to_value(ExportBlock::Mimo).unwrap(),
3248            ExportBlock::Mimo.name()
3249        );
3250        assert_eq!(
3251            serde_json::to_value(ErrorCode::ExportScope).unwrap(),
3252            "export_scope"
3253        );
3254    }
3255}