Skip to main content

secs_export/
lib.rs

1#![forbid(unsafe_code)]
2#![deny(unsafe_op_in_unsafe_fn)]
3//! SECS 2's user-visible REW `.mdat` exports.
4
5use std::{
6    collections::BTreeMap,
7    fs,
8    path::{Path, PathBuf},
9};
10
11use secs_camilla::pyfmt::{format_fixed, format_g};
12use secs_engine::{
13    Design, EngineError, ExportAxis, StageResponses, input::LayoutKind, stage_responses,
14};
15use secs_mdat::{MdatError, MeasurementInput, SourceInfo, TEMPLATE};
16use secs_types::{
17    calibration::{CalibrationSettings, Mode, RcBand},
18    chain::{MimoPaths, SubChannel},
19};
20
21pub use secs_types::ipc::MdatScope;
22
23const SR: u32 = 48_000;
24const SUB_GAIN_WARN_DB: f64 = 12.0;
25
26pub type Sources = BTreeMap<u32, BTreeMap<String, SourceInfo>>;
27
28/// Inputs already computed by the correction engine.
29#[derive(Debug)]
30pub struct ExportRun<'a> {
31    pub design: &'a Design,
32    pub settings: &'a CalibrationSettings,
33}
34
35/// One stored measurement, as the project's side mdat writes it.
36#[derive(Clone, Debug)]
37pub struct Original {
38    pub position: u32,
39    pub role: String,
40    pub item: MeasurementInput,
41}
42
43/// MIMO support-filter realization used in exported labels.
44#[derive(Debug, Clone, Copy, PartialEq, Eq)]
45pub enum MimoKind {
46    Iir,
47    Fir,
48}
49
50impl MimoKind {
51    fn name(self) -> &'static str {
52        match self {
53            Self::Iir => "IIR",
54            Self::Fir => "FIR",
55        }
56    }
57}
58
59/// MIMO paths and already-applied design-grid responses.
60#[derive(Debug)]
61pub struct MimoResponses {
62    pub kind: MimoKind,
63    pub fsiso: f64,
64    pub cap_text: String,
65    pub paths: MimoPaths,
66    pub applied: Vec<(String, Vec<secs_engine::C>)>,
67}
68
69/// Typed future seam for M3 MIMO stage responses.
70#[derive(Debug, Clone, Copy)]
71enum MimoExport<'a> {
72    None,
73    Responses(&'a MimoResponses),
74}
75
76#[derive(Debug, Clone, PartialEq)]
77pub enum SubWarning {
78    NarrowBand {
79        role: String,
80        hp_hz: f64,
81        lp_hz: f64,
82    },
83    HighGain {
84        role: String,
85        gain_db: f64,
86    },
87}
88
89#[derive(Debug, thiserror::Error)]
90pub enum ExportError {
91    #[error(transparent)]
92    Engine(#[from] EngineError),
93    #[error(transparent)]
94    Mdat(#[from] MdatError),
95    #[error(transparent)]
96    Io(#[from] std::io::Error),
97    #[error("operating-system randomness failed: {0}")]
98    Random(String),
99    #[error("there are no stored measurements to export")]
100    NoMeasurements,
101    #[error("calibration must run before export")]
102    NoResult,
103    #[error("missing export response for {0}")]
104    MissingResponse(String),
105}
106
107fn chain_text(run: &ExportRun<'_>) -> String {
108    let peq = run.design.replay.config().peq_bands.unwrap_or(16);
109    // The fitted budget; mode_decay puts its cuts beside it (ADR 0025), so
110    // the per-channel count printed later can be larger.
111    let peq = if run.design.replay.config().mode_decay {
112        format!("{peq} + 울림 컷")
113    } else {
114        peq.to_string()
115    };
116    if run.design.replay.config().taps > 0 {
117        format!(
118            "PEQ {peq} + FIR {}",
119            grouped(run.design.replay.config().taps)
120        )
121    } else {
122        format!("PEQ {peq}")
123    }
124}
125
126fn grouped(value: usize) -> String {
127    let digits = value.to_string();
128    let mut out = String::new();
129    for (index, ch) in digits.chars().enumerate() {
130        if index > 0 && (digits.len() - index).is_multiple_of(3) {
131            out.push(',');
132        }
133        out.push(ch);
134    }
135    out
136}
137
138fn sub_mode_text(mode: &str) -> String {
139    if mode == "fixed" {
140        "고정".into()
141    } else if let Some(rest) = mode.strip_prefix("bundle:") {
142        let mut parts = rest.split(':');
143        let bundle = parts.next().unwrap_or_default();
144        let place = match parts.next() {
145            Some("dba-front") => " DBA 앞",
146            Some("dba-rear") => " DBA 뒤",
147            Some("multi") => " 멀티",
148            _ => "",
149        };
150        format!("Group {bundle}{place}")
151    } else {
152        "자동".into()
153    }
154}
155
156fn band_type_text(name: &str) -> String {
157    let split = name.len().min(2);
158    format!("{} {}", &name[..split], &name[split..])
159}
160
161fn sub_filter_text(sub: &SubChannel) -> String {
162    let mut parts = Vec::new();
163    if sub.hp_hz != 0.0 {
164        parts.push(format!(
165            "HP {} Hz {}",
166            format_g(sub.hp_hz, false),
167            band_type_text(sub.hp_type.name())
168        ));
169    }
170    if sub.lp_hz != 0.0 {
171        parts.push(format!(
172            "LP {} Hz {}",
173            format_g(sub.lp_hz, false),
174            band_type_text(sub.lp_type.name())
175        ));
176    }
177    parts.extend(sub.peq.iter().map(|&(hz, q, gain)| {
178        format!(
179            "PEQ {} Hz Q {} {} dB",
180            format_fixed(hz, 0, false),
181            format_fixed(q, 2, false),
182            format_fixed(gain, 1, true)
183        )
184    }));
185    parts.join(" ")
186}
187
188fn sub_value_text(sub: &SubChannel) -> String {
189    let mut out = format!(
190        "{} {} {} dB {} ms {}",
191        sub.role,
192        sub_mode_text(&sub.mode),
193        format_fixed(sub.gain_db, 2, true),
194        format_fixed(sub.delay_ms, 2, false),
195        if sub.polarity > 0 { "정상" } else { "반전" }
196    );
197    for &(hz, q) in &sub.allpass {
198        out.push_str(&format!(
199            " AP {} Hz Q {}",
200            format_fixed(hz, 0, false),
201            format_fixed(q, 2, false)
202        ));
203    }
204    let filters = sub_filter_text(sub);
205    if !filters.is_empty() {
206        out.push(' ');
207        out.push_str(&filters);
208    }
209    out
210}
211
212pub fn layout_lines(run: &ExportRun<'_>) -> Vec<String> {
213    let Some(subs) = &run.design.subs else {
214        return Vec::new();
215    };
216    let mut layouts: Vec<_> = subs.layout_info.iter().collect();
217    layouts.sort_by(|a, b| a.0.cmp(&b.0));
218    layouts
219        .into_iter()
220        .map(|(name, info)| match info.kind {
221            LayoutKind::Dba => format!(
222                "Group {name} DBA: 앞 {}, 뒤 {} 반전 +{} ms(자동 {} 보정 {}), 같은 필터 PEQ {}",
223                info.front.join("·"),
224                info.rear.join("·"),
225                format_fixed(info.rear_ms, 2, false),
226                format_fixed(info.auto_ms.unwrap_or(0.0), 2, false),
227                format_fixed(info.trim_ms, 2, true),
228                info.peq.len()
229            ),
230            LayoutKind::Multi => format!(
231                "Group {name} 멀티서브: {}, 같은 필터 PEQ {}",
232                info.members.join("·"),
233                info.peq.len()
234            ),
235        })
236        .collect()
237}
238
239pub fn sub_values_text(run: &ExportRun<'_>) -> String {
240    layout_lines(run)
241        .into_iter()
242        .chain(run.design.chain.subs.iter().map(sub_value_text))
243        .collect::<Vec<_>>()
244        .join(" · ")
245}
246
247pub fn rc_pieces(run: &ExportRun<'_>) -> Vec<String> {
248    let mut pieces = rc_pieces_from_values_with_bands(
249        run.design.rc_hi,
250        run.design.rc_auto,
251        run.design.schroeder_hz,
252        run.settings.room_volume_m3,
253        false,
254        &run.settings.rc_bands,
255    );
256    pieces.extend(lf_correction_pieces(run.settings));
257    pieces
258}
259
260/// Builds the upstream RC note fragments from cached scalar values.
261pub fn rc_pieces_from_values(
262    rc_hi: f64,
263    rc_auto: bool,
264    schroeder_hz: Option<f64>,
265    room_volume_m3: Option<f64>,
266    legacy_fallback: bool,
267) -> Vec<String> {
268    rc_pieces_from_values_with_bands(
269        rc_hi,
270        rc_auto,
271        schroeder_hz,
272        room_volume_m3,
273        legacy_fallback,
274        &[],
275    )
276}
277
278pub fn rc_pieces_from_values_with_bands(
279    rc_hi: f64,
280    rc_auto: bool,
281    schroeder_hz: Option<f64>,
282    room_volume_m3: Option<f64>,
283    legacy_fallback: bool,
284    rc_bands: &[RcBand],
285) -> Vec<String> {
286    let hz = format_fixed(rc_hi, 0, false);
287    let head = if rc_auto {
288        if let Some(schroeder) = schroeder_hz {
289            format!(
290                "RC 상한 {hz} Hz (슈뢰더 {} Hz)",
291                format_fixed(schroeder, 0, false)
292            )
293        } else if legacy_fallback {
294            format!("RC 상한 {hz} Hz (자동)")
295        } else {
296            format!("RC 상한 {hz} Hz (기본값)")
297        }
298    } else {
299        format!("RC 상한 {hz} Hz (수동)")
300    };
301    let mut out = vec![head];
302    if rc_auto {
303        match room_volume_m3.filter(|v| *v != 0.0) {
304            Some(volume) => {
305                out.push(format!(
306                    "자동: 룸 볼륨 {} m³",
307                    format_fixed(volume, 0, false)
308                ));
309                if schroeder_hz.is_some_and(|v| v > rc_hi + 0.5) {
310                    out.push(format!("자동 상한 최대 {hz} Hz"));
311                }
312            }
313            None => out.push("자동: 룸 볼륨 없음".into()),
314        }
315    }
316    if let Some(piece) = rc_bands_piece(rc_bands) {
317        out.push(piece);
318    }
319    out
320}
321
322fn rc_bands_piece(rc_bands: &[RcBand]) -> Option<String> {
323    (!rc_bands.is_empty()).then(|| {
324        format!(
325            "RC 추가 구간 {} Hz",
326            rc_bands
327                .iter()
328                .map(|band| format!(
329                    "{}–{}",
330                    format_fixed(band.lo_hz, 0, false),
331                    format_fixed(band.hi_hz, 0, false)
332                ))
333                .collect::<Vec<_>>()
334                .join(", ")
335        )
336    })
337}
338
339/// Export-text pieces for the optional LF and HF corrections. Zero mode has
340/// no FIR, so the engine skips `lf_align` and `hf_phase` there and the text does too.
341pub fn lf_correction_pieces(settings: &CalibrationSettings) -> Vec<String> {
342    let mut pieces = Vec::new();
343    if settings.lf_align && settings.mode != Mode::Zero {
344        pieces.push("저음 도착 맞춤".into());
345    }
346    if settings.mode_decay {
347        pieces.push("방 울림 줄임".into());
348    }
349    if settings.hf_phase && settings.mode != Mode::Zero {
350        pieces.push("고역 위상 맞춤".into());
351    }
352    pieces
353}
354
355pub fn sub_filter_warnings(settings: &CalibrationSettings, roles: &[String]) -> Vec<SubWarning> {
356    roles
357        .iter()
358        .filter_map(|role| {
359            let entry = settings
360                .subs_manual
361                .iter()
362                .find(|(r, _)| r == role)
363                .map(|(_, e)| e)?;
364            (entry.hp_hz != 0.0 && entry.lp_hz != 0.0 && entry.lp_hz < 2.0 * entry.hp_hz).then(
365                || SubWarning::NarrowBand {
366                    role: role.clone(),
367                    hp_hz: entry.hp_hz,
368                    lp_hz: entry.lp_hz,
369                },
370            )
371        })
372        .collect()
373}
374
375pub fn sub_gain_warnings(design: &Design) -> Vec<SubWarning> {
376    design
377        .chain
378        .subs
379        .iter()
380        .filter(|sub| sub.gain_db > SUB_GAIN_WARN_DB)
381        .map(|sub| SubWarning::HighGain {
382            role: sub.role.clone(),
383            gain_db: sub.gain_db,
384        })
385        .collect()
386}
387
388fn item(
389    design: &Design,
390    title: String,
391    notes: String,
392    spectrum: &[secs_engine::C],
393    axis: ExportAxis,
394) -> MeasurementInput {
395    let (samples, t0) = design.replay.export_ir(design, spectrum, axis);
396    MeasurementInput {
397        title,
398        notes,
399        sample_rate_hz: SR,
400        samples,
401        start_time_s: t0,
402        spl_offset_db: None,
403        source_info: None,
404        computed: false,
405    }
406}
407
408fn stage_items_with_mimo(
409    run: &ExportRun<'_>,
410    mimo: MimoExport<'_>,
411    label: Option<&str>,
412) -> Result<Vec<MeasurementInput>, ExportError> {
413    let view = run.design.replay.export_view(run.design)?;
414    let position = run.design.replay.config().main_position;
415    let subs: Vec<_> = run
416        .design
417        .replay
418        .config()
419        .subs
420        .iter()
421        .filter_map(|role| view.spectra.get(position, role))
422        .collect();
423    let label = label.map_or_else(|| run.settings.label(), str::to_owned);
424    let mut items = Vec::new();
425    for (index, main) in run.design.chain.mains.iter().enumerate() {
426        let seq = index + 1;
427        let raw = view
428            .spectra
429            .get(position, &main.role)
430            .ok_or_else(|| ExportError::MissingResponse(main.role.clone()))?;
431        let stages = stage_responses(run.design, &main.role, &view.spectra, position)
432            .ok_or_else(|| ExportError::MissingResponse(main.role.clone()))?;
433        let prefix = format!("SECS 보정 설계 · {label} · 청취 위치 {position} · 계산값 — ");
434        items.push(item(
435            run.design,
436            format!("{seq:02}_{}_1 보정 전 메인", main.role),
437            format!("{prefix}메인 스피커 원 응답(2 s 창, 필터 없음)"),
438            raw,
439            ExportAxis::Measurement,
440        ));
441        if !subs.is_empty() {
442            let mut sum = vec![secs_engine::C::new(0.0, 0.0); raw.len()];
443            for spectrum in &subs {
444                for (out, value) in sum.iter_mut().zip(spectrum.iter()) {
445                    *out += value;
446                }
447            }
448            let tail = if view.has_sub_filters {
449                "서브 원 응답의 단순 합(정렬 없음 — 서브 고정 출력 필터만)"
450            } else {
451                "서브 원 응답의 단순 합(정렬 없음·필터 없음)"
452            };
453            items.push(item(
454                run.design,
455                format!("{seq:02}_{}_1 보정 전 서브", main.role),
456                format!("{prefix}{tail}"),
457                &sum,
458                ExportAxis::Measurement,
459            ));
460        }
461        add_xo_items(run, &mut items, seq, main.role.as_str(), &prefix, &stages);
462        let mut correction_pieces = lf_correction_pieces(run.settings);
463        if let Some(piece) = rc_bands_piece(&run.settings.rc_bands) {
464            correction_pieces.insert(0, piece);
465        }
466        let correction_pieces = if correction_pieces.is_empty() {
467            String::new()
468        } else {
469            format!(" · {}", correction_pieces.join(" · "))
470        };
471        items.push(item(
472            run.design,
473            format!("{seq:02}_{}_3 합 후 보정", main.role),
474            format!(
475                "{prefix}2차: 탑+서브 합에 입력 보정({}) · 전체 지연 {} ms(시작 시각에서 뺌) · RC 상한 {} Hz{correction_pieces}",
476                chain_text(run),
477                format_fixed(run.design.chain.latency_ms, 1, false),
478                format_fixed(run.design.rc_hi, 0, false)
479            ),
480            &stages.output,
481            ExportAxis::Corrected,
482        ));
483        if let MimoExport::Responses(mimo) = mimo {
484            let supports: Vec<_> = mimo
485                .paths
486                .paths
487                .iter()
488                .filter(|path| path.input == main.role)
489                .collect();
490            if !supports.is_empty() {
491                let response = mimo
492                    .applied
493                    .iter()
494                    .find(|(role, _)| role == &main.role)
495                    .map(|(_, response)| response.as_slice())
496                    .ok_or_else(|| ExportError::MissingResponse(main.role.clone()))?;
497                let description = supports
498                    .iter()
499                    .map(|path| match &path.filter {
500                        secs_types::chain::MimoFilter::Fir { taps_48k } => {
501                            format!("{} FIR {}탭", path.support, grouped(taps_48k.len()))
502                        }
503                        secs_types::chain::MimoFilter::FirLowRate { .. } => {
504                            format!(
505                                "{} FIR {}탭",
506                                path.support,
507                                grouped(path.filter.fir_len_48k())
508                            )
509                        }
510                        secs_types::chain::MimoFilter::Iir {
511                            gain_db,
512                            delay_ms,
513                            polarity,
514                            peq,
515                            allpass,
516                        } => format!(
517                            "{} {} dB {} ms {} PEQ {} AP {}",
518                            path.support,
519                            format_fixed(*gain_db, 1, false),
520                            format_fixed(*delay_ms, 1, false),
521                            if *polarity > 0 { "+" } else { "-" },
522                            peq.len(),
523                            allpass.len()
524                        ),
525                    })
526                    .collect::<Vec<_>>()
527                    .join("; ");
528                items.push(item(
529                    run.design,
530                    format!("{seq:02}_{}_4 MIMO 적용({})", main.role, mimo.kind.name()),
531                    format!(
532                        "{prefix}MIMO {} 서포트 {}개(Fsiso {} Hz{}) — {description}",
533                        mimo.kind.name(),
534                        supports.len(),
535                        format_g(mimo.fsiso, false),
536                        mimo.cap_text
537                    ),
538                    response,
539                    ExportAxis::Corrected,
540                ));
541            }
542        }
543    }
544    Ok(items)
545}
546
547fn add_xo_items(
548    run: &ExportRun<'_>,
549    items: &mut Vec<MeasurementInput>,
550    seq: usize,
551    role: &str,
552    prefix: &str,
553    stages: &StageResponses,
554) {
555    let Some(xo) = run
556        .design
557        .chain
558        .mains
559        .iter()
560        .find(|m| m.role == role)
561        .and_then(|m| m.xo_hz)
562        .filter(|v| *v != 0.0)
563    else {
564        return;
565    };
566    items.push(item(
567        run.design,
568        format!("{seq:02}_{role}_2 XO 타겟 메인"),
569        format!(
570            "{prefix}1차: 게인·딜레이·출력 PEQ(음향 XO 타겟)·전기 HP {} Hz",
571            format_g(xo, false)
572        ),
573        &stages.top_xo,
574        ExportAxis::Measurement,
575    ));
576    if let Some(sub) = &stages.sub_xo {
577        items.push(item(
578            run.design,
579            format!("{seq:02}_{role}_2 XO 타겟 서브"),
580            format!(
581                "{prefix}1차: BA(게인·지연·극성)·서브 버스 PEQ·전기 LP — {}",
582                sub_values_text(run)
583            ),
584            sub,
585            ExportAxis::Measurement,
586        ));
587    }
588}
589
590pub fn stage_items(run: &ExportRun<'_>, label: Option<&str>) -> Vec<MeasurementInput> {
591    stage_items_with_mimo(run, MimoExport::None, label).expect("validated engine export inputs")
592}
593
594pub fn stage_items_mimo(
595    run: &ExportRun<'_>,
596    mimo: &MimoResponses,
597    label: Option<&str>,
598) -> Result<Vec<MeasurementInput>, ExportError> {
599    stage_items_with_mimo(run, MimoExport::Responses(mimo), label)
600}
601
602fn before_after_items_with_mimo(
603    run: &ExportRun<'_>,
604    mimo: MimoExport<'_>,
605    sources: Option<&Sources>,
606    originals: Option<&[Original]>,
607) -> Result<Vec<MeasurementInput>, ExportError> {
608    let view = run.design.replay.export_view(run.design)?;
609    let position = run.design.replay.config().main_position;
610    let label = run.settings.label();
611    let source_env = sources.and_then(|sources| sources.get(&position));
612    let mut items = Vec::new();
613    let mut seq = 0;
614    for main in &run.design.chain.mains {
615        seq += 1;
616        if let Some(measured) = run.design.replay.measurements().get(position, &main.role) {
617            items.push(measured_item(
618                seq,
619                &main.role,
620                position,
621                measured,
622                "",
623                source_env.and_then(|sources| sources.get(&main.role)),
624                originals,
625            ));
626        }
627        let final_response = stage_responses(run.design, &main.role, &view.spectra, position)
628            .ok_or_else(|| ExportError::MissingResponse(main.role.clone()))?
629            .output;
630        let fir = if main.fir.len() > 1 {
631            format!("FIR {}탭", grouped(main.fir.len()))
632        } else {
633            "FIR 없음".into()
634        };
635        let mut notes = format!(
636            "SECS 보정 설계 · {label} · 청취 위치 {position} · 계산값 — 채널 보정(PEQ {}개 · {fir}) + 서브 합, 전체 지연 {} ms(시작 시각에서 뺌) · {}",
637            main.input_peq.len(),
638            format_fixed(run.design.chain.latency_ms, 1, false),
639            rc_pieces(run).join(" · ")
640        );
641        if !run.design.chain.subs.is_empty() && main.xo_hz.is_some_and(|v| v != 0.0) {
642            notes.push_str(" · 서브: ");
643            notes.push_str(&sub_values_text(run));
644        }
645        let mut corrected = item(
646            run.design,
647            format!("{seq:02}_{}_2 보정 후 {label}", main.role),
648            notes,
649            &final_response,
650            ExportAxis::Corrected,
651        );
652        corrected.source_info = source_env
653            .and_then(|sources| sources.get(&main.role))
654            .cloned();
655        corrected.computed = true;
656        if originals.is_some() {
657            clear_curves(&mut corrected);
658        }
659        items.push(corrected);
660        if let MimoExport::Responses(mimo) = mimo {
661            let support_count = mimo
662                .paths
663                .paths
664                .iter()
665                .filter(|path| path.input == main.role)
666                .count();
667            if support_count != 0 {
668                let response = mimo
669                    .applied
670                    .iter()
671                    .find(|(role, _)| role == &main.role)
672                    .map(|(_, response)| response.as_slice())
673                    .ok_or_else(|| ExportError::MissingResponse(main.role.clone()))?;
674                let mut corrected = item(
675                    run.design,
676                    format!(
677                        "{seq:02}_{}_3 보정 후 + MIMO({})",
678                        main.role,
679                        mimo.kind.name()
680                    ),
681                    format!(
682                        "SECS 보정 설계 · {label} · 청취 위치 {position} · 계산값 — MIMO {} 서포트 {support_count}개 (Fsiso {} Hz{})",
683                        mimo.kind.name(),
684                        format_g(mimo.fsiso, false),
685                        mimo.cap_text
686                    ),
687                    response,
688                    ExportAxis::Corrected,
689                );
690                if originals.is_some() {
691                    corrected.computed = true;
692                    clear_curves(&mut corrected);
693                }
694                items.push(corrected);
695            }
696        }
697    }
698    for sub in &run.design.chain.subs {
699        if let Some(measured) = run.design.replay.measurements().get(position, &sub.role) {
700            seq += 1;
701            items.push(measured_item(
702                seq,
703                &sub.role,
704                position,
705                measured,
706                &format!(" · DSP 값: {}", sub_value_text(sub)),
707                source_env.and_then(|sources| sources.get(&sub.role)),
708                originals,
709            ));
710        }
711    }
712    if let Some(originals) = originals {
713        items.extend(
714            originals
715                .iter()
716                .filter(|original| original.position != position)
717                .map(|original| original.item.clone()),
718        );
719    }
720    Ok(items)
721}
722
723fn measured_item(
724    seq: usize,
725    role: &str,
726    position: u32,
727    measured: &secs_engine::Measurement,
728    note: &str,
729    source_info: Option<&SourceInfo>,
730    originals: Option<&[Original]>,
731) -> MeasurementInput {
732    let mut item = MeasurementInput {
733        title: format!("{seq:02}_{role}_1 보정 전(원 측정)"),
734        notes: format!("SECS · 청취 위치 {position} · 원 측정 그대로(필터 없음){note}"),
735        sample_rate_hz: measured.sample_rate,
736        samples: (0..measured.samples.len())
737            .map(|index| f64::from(measured.samples.at(index) as f32))
738            .collect(),
739        start_time_s: measured.t0,
740        spl_offset_db: None,
741        source_info: source_info.cloned(),
742        computed: false,
743    };
744    let Some(originals) = originals else {
745        return item;
746    };
747    if let Some(original) = originals
748        .iter()
749        .find(|original| original.position == position && original.role == role)
750    {
751        let title = item.title;
752        let notes = item.notes;
753        item = original.item.clone();
754        item.title = title;
755        item.notes = notes;
756        item.computed = false;
757    } else {
758        clear_curves(&mut item);
759    }
760    item
761}
762
763fn clear_curves(item: &mut MeasurementInput) {
764    if let Some(source_info) = &mut item.source_info {
765        source_info.cal.clear();
766    }
767}
768
769pub fn before_after_items(run: &ExportRun<'_>, sources: Option<&Sources>) -> Vec<MeasurementInput> {
770    before_after_items_with_mimo(run, MimoExport::None, sources, None)
771        .expect("validated engine export inputs")
772}
773
774pub fn before_after_items_mimo(
775    run: &ExportRun<'_>,
776    mimo: &MimoResponses,
777    sources: Option<&Sources>,
778) -> Result<Vec<MeasurementInput>, ExportError> {
779    before_after_items_with_mimo(run, MimoExport::Responses(mimo), sources, None)
780}
781
782/// Returns the REW mdat file name for the selected contents.
783pub fn rew_mdat_filename(scope: MdatScope, label: &str) -> String {
784    match scope {
785        MdatScope::All => format!("SECS 원 측정+보정 결과 {label}.mdat"),
786        MdatScope::Measurements => "SECS 원 측정.mdat".into(),
787        MdatScope::Results => format!("SECS 보정 결과 {label}.mdat"),
788    }
789}
790
791/// Builds the REW mdat items for the selected contents.
792pub fn rew_mdat_items(
793    run: Option<&ExportRun<'_>>,
794    scope: MdatScope,
795    originals: &[Original],
796    mimo: Option<&MimoResponses>,
797    sources: Option<&Sources>,
798) -> Result<Vec<MeasurementInput>, ExportError> {
799    if scope == MdatScope::Measurements {
800        if originals.is_empty() {
801            return Err(ExportError::NoMeasurements);
802        }
803        return Ok(originals
804            .iter()
805            .map(|original| original.item.clone())
806            .collect());
807    }
808    let run = run.ok_or(ExportError::NoResult)?;
809    let mut items = before_after_items_with_mimo(
810        run,
811        mimo.map_or(MimoExport::None, MimoExport::Responses),
812        sources,
813        Some(originals),
814    )?;
815    if scope == MdatScope::Results {
816        items.retain(|item| item.computed);
817    }
818    Ok(items)
819}
820
821/// `spl_offset_db` is the project's median REW SPL offset
822/// (`secs_project::project_spl_offset`).
823pub fn export_mdat(
824    run: &ExportRun<'_>,
825    folder: &Path,
826    spl_offset_db: Option<f64>,
827    now_ms: i64,
828) -> Result<PathBuf, ExportError> {
829    export_mdat_with_mimo(run, folder, None, spl_offset_db, now_ms)
830}
831
832fn export_mdat_with_mimo(
833    run: &ExportRun<'_>,
834    folder: &Path,
835    mimo: Option<&MimoResponses>,
836    spl_offset_db: Option<f64>,
837    now_ms: i64,
838) -> Result<PathBuf, ExportError> {
839    export_mdat_with_mimo_using(run, folder, mimo, spl_offset_db, now_ms, &mut || {
840        random_uuid().map_err(|error| ExportError::Random(error.to_string()))
841    })
842}
843
844/// Writes the staged mdat using an injected UUID source.
845pub fn export_mdat_with_mimo_using(
846    run: &ExportRun<'_>,
847    folder: &Path,
848    mimo: Option<&MimoResponses>,
849    spl_offset_db: Option<f64>,
850    now_ms: i64,
851    uuid: &mut dyn FnMut() -> Result<u128, ExportError>,
852) -> Result<PathBuf, ExportError> {
853    let label = run.settings.label();
854    let items = stage_items_with_mimo(
855        run,
856        mimo.map_or(MimoExport::None, MimoExport::Responses),
857        Some(&label),
858    )?;
859    export_items_using(
860        folder,
861        &format!("SECS 보정 설계 {label}.mdat"),
862        &items,
863        spl_offset_db,
864        now_ms,
865        uuid,
866    )
867}
868
869pub fn export_before_after_mdat(
870    run: &ExportRun<'_>,
871    folder: &Path,
872    sources: Option<&Sources>,
873    spl_offset_db: Option<f64>,
874    now_ms: i64,
875) -> Result<PathBuf, ExportError> {
876    export_before_after_mdat_with_mimo(run, folder, None, sources, spl_offset_db, now_ms)
877}
878
879fn export_before_after_mdat_with_mimo(
880    run: &ExportRun<'_>,
881    folder: &Path,
882    mimo: Option<&MimoResponses>,
883    sources: Option<&Sources>,
884    spl_offset_db: Option<f64>,
885    now_ms: i64,
886) -> Result<PathBuf, ExportError> {
887    export_before_after_mdat_with_mimo_using(
888        run,
889        folder,
890        mimo,
891        sources,
892        spl_offset_db,
893        now_ms,
894        &mut || random_uuid().map_err(|error| ExportError::Random(error.to_string())),
895    )
896}
897
898/// Writes the before/after mdat using an injected UUID source.
899pub fn export_before_after_mdat_with_mimo_using(
900    run: &ExportRun<'_>,
901    folder: &Path,
902    mimo: Option<&MimoResponses>,
903    sources: Option<&Sources>,
904    spl_offset_db: Option<f64>,
905    now_ms: i64,
906    uuid: &mut dyn FnMut() -> Result<u128, ExportError>,
907) -> Result<PathBuf, ExportError> {
908    let label = run.settings.label();
909    let items = before_after_items_with_mimo(
910        run,
911        mimo.map_or(MimoExport::None, MimoExport::Responses),
912        sources,
913        None,
914    )?;
915    export_items_using(
916        folder,
917        &format!("SECS 보정 전후 {label}.mdat"),
918        &items,
919        spl_offset_db,
920        now_ms,
921        uuid,
922    )
923}
924
925/// Writes the selected measurements and correction results to one REW mdat.
926#[allow(clippy::too_many_arguments)] // Signature keeps the existing injected-writer API shape.
927pub fn export_rew_mdat_using(
928    run: Option<&ExportRun<'_>>,
929    scope: MdatScope,
930    originals: &[Original],
931    folder: &Path,
932    mimo: Option<&MimoResponses>,
933    sources: Option<&Sources>,
934    spl_offset_db: Option<f64>,
935    now_ms: i64,
936    uuid: &mut dyn FnMut() -> Result<u128, ExportError>,
937) -> Result<PathBuf, ExportError> {
938    let items = rew_mdat_items(run, scope, originals, mimo, sources)?;
939    let label = run.map(|run| run.settings.label()).unwrap_or_default();
940    export_items_using(
941        folder,
942        &rew_mdat_filename(scope, &label),
943        &items,
944        spl_offset_db,
945        now_ms,
946        uuid,
947    )
948}
949
950fn export_items_using(
951    folder: &Path,
952    filename: &str,
953    items: &[MeasurementInput],
954    spl_offset_db: Option<f64>,
955    now_ms: i64,
956    uuid: &mut dyn FnMut() -> Result<u128, ExportError>,
957) -> Result<PathBuf, ExportError> {
958    let uuids = (0..items.len())
959        .map(|_| uuid())
960        .collect::<Result<Vec<_>, _>>()?;
961    let mut uuids = uuids.into_iter();
962    let bytes = secs_mdat::build(items, TEMPLATE, spl_offset_db, now_ms, &mut || {
963        uuids
964            .next()
965            .expect("one pre-generated UUID per validated measurement")
966    })?;
967    fs::create_dir_all(folder)?;
968    let destination = folder.join(filename);
969    atomic_replace(&destination, &bytes)?;
970    Ok(destination)
971}
972
973fn random_uuid() -> Result<u128, getrandom::Error> {
974    let mut bytes = [0_u8; 16];
975    getrandom::fill(&mut bytes)?;
976    let mut value = u128::from_be_bytes(bytes);
977    value &= !(0xf_u128 << 76);
978    value |= 4_u128 << 76;
979    value &= !(0x3_u128 << 62);
980    value |= 0x2_u128 << 62;
981    Ok(value)
982}
983
984fn atomic_replace(destination: &Path, bytes: &[u8]) -> Result<(), std::io::Error> {
985    secs_types::fs::write_atomic_bytes(destination, bytes)
986}
987
988#[cfg(test)]
989mod tests {
990    use super::*;
991    use std::sync::atomic::{AtomicU64, Ordering};
992
993    static TEMP_COUNTER: AtomicU64 = AtomicU64::new(0);
994
995    #[test]
996    fn rc_pieces_from_values_preserves_live_and_legacy_wording() {
997        assert_eq!(
998            rc_pieces_from_values(300.0, true, None, None, false),
999            ["RC 상한 300 Hz (기본값)", "자동: 룸 볼륨 없음"]
1000        );
1001        assert_eq!(
1002            rc_pieces_from_values(300.0, true, None, None, true),
1003            ["RC 상한 300 Hz (자동)", "자동: 룸 볼륨 없음"]
1004        );
1005        assert_eq!(
1006            rc_pieces_from_values(300.0, false, None, Some(80.0), true),
1007            ["RC 상한 300 Hz (수동)"]
1008        );
1009        assert_eq!(
1010            rc_pieces_from_values(300.0, true, Some(420.0), Some(80.0), false),
1011            [
1012                "RC 상한 300 Hz (슈뢰더 420 Hz)",
1013                "자동: 룸 볼륨 80 m³",
1014                "자동 상한 최대 300 Hz",
1015            ]
1016        );
1017        assert_eq!(
1018            rc_pieces_from_values_with_bands(
1019                300.0,
1020                false,
1021                None,
1022                None,
1023                false,
1024                &[
1025                    RcBand {
1026                        lo_hz: 1_000.0,
1027                        hi_hz: 2_000.0,
1028                    },
1029                    RcBand {
1030                        lo_hz: 15_000.0,
1031                        hi_hz: 20_000.0,
1032                    },
1033                ],
1034            ),
1035            [
1036                "RC 상한 300 Hz (수동)",
1037                "RC 추가 구간 1000–2000, 15000–20000 Hz"
1038            ]
1039        );
1040        let settings = CalibrationSettings {
1041            lf_align: true,
1042            mode_decay: true,
1043            hf_phase: true,
1044            ..Default::default()
1045        };
1046        assert_eq!(
1047            lf_correction_pieces(&settings),
1048            ["저음 도착 맞춤", "방 울림 줄임", "고역 위상 맞춤"]
1049        );
1050        let zero = CalibrationSettings {
1051            mode: Mode::Zero,
1052            ..settings
1053        };
1054        assert_eq!(lf_correction_pieces(&zero), ["방 울림 줄임"]);
1055    }
1056
1057    #[test]
1058    fn atomic_replace_overwrites_and_cleans_temporary_file() {
1059        let root = std::env::temp_dir().join(format!(
1060            "secs-export-atomic-{}-{}",
1061            std::process::id(),
1062            TEMP_COUNTER.fetch_add(1, Ordering::Relaxed)
1063        ));
1064        fs::create_dir(&root).unwrap();
1065        let destination = root.join("SECS 보정 설계 표준 모드.mdat");
1066        fs::write(&destination, b"old").unwrap();
1067
1068        atomic_replace(&destination, b"new").unwrap();
1069
1070        assert_eq!(fs::read(&destination).unwrap(), b"new");
1071        assert_eq!(fs::read_dir(&root).unwrap().count(), 1);
1072        fs::remove_dir_all(root).unwrap();
1073    }
1074
1075    #[test]
1076    fn atomic_replace_cleans_temporary_file_after_rename_failure() {
1077        let root = std::env::temp_dir().join(format!(
1078            "secs-export-atomic-failure-{}-{}",
1079            std::process::id(),
1080            TEMP_COUNTER.fetch_add(1, Ordering::Relaxed)
1081        ));
1082        fs::create_dir(&root).unwrap();
1083        let destination = root.join("occupied");
1084        fs::create_dir(&destination).unwrap();
1085
1086        assert!(atomic_replace(&destination, b"new").is_err());
1087
1088        assert!(destination.is_dir());
1089        assert_eq!(fs::read_dir(&root).unwrap().count(), 1);
1090        fs::remove_dir_all(root).unwrap();
1091    }
1092
1093    #[test]
1094    fn random_uuid_has_v4_variant() {
1095        let uuid = random_uuid().unwrap();
1096        assert_eq!((uuid >> 76) & 0xf, 4);
1097        assert_eq!((uuid >> 62) & 0x3, 2);
1098    }
1099
1100    #[test]
1101    fn warning_edges() {
1102        let mut settings = CalibrationSettings::default();
1103        let entry = secs_types::calibration::SubEntry {
1104            hp_hz: 30.0,
1105            lp_hz: 50.0,
1106            ..secs_types::calibration::SubEntry::default()
1107        };
1108        settings.subs_manual.push(("SW1".into(), entry));
1109        assert_eq!(
1110            sub_filter_warnings(&settings, &["SW1".into()]),
1111            vec![SubWarning::NarrowBand {
1112                role: "SW1".into(),
1113                hp_hz: 30.0,
1114                lp_hz: 50.0,
1115            }]
1116        );
1117    }
1118}