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 ADR 0025 switches. Zero mode has no FIR, so
340/// the engine skips `lf_align` 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    pieces
350}
351
352pub fn sub_filter_warnings(settings: &CalibrationSettings, roles: &[String]) -> Vec<SubWarning> {
353    roles
354        .iter()
355        .filter_map(|role| {
356            let entry = settings
357                .subs_manual
358                .iter()
359                .find(|(r, _)| r == role)
360                .map(|(_, e)| e)?;
361            (entry.hp_hz != 0.0 && entry.lp_hz != 0.0 && entry.lp_hz < 2.0 * entry.hp_hz).then(
362                || SubWarning::NarrowBand {
363                    role: role.clone(),
364                    hp_hz: entry.hp_hz,
365                    lp_hz: entry.lp_hz,
366                },
367            )
368        })
369        .collect()
370}
371
372pub fn sub_gain_warnings(design: &Design) -> Vec<SubWarning> {
373    design
374        .chain
375        .subs
376        .iter()
377        .filter(|sub| sub.gain_db > SUB_GAIN_WARN_DB)
378        .map(|sub| SubWarning::HighGain {
379            role: sub.role.clone(),
380            gain_db: sub.gain_db,
381        })
382        .collect()
383}
384
385fn item(
386    design: &Design,
387    title: String,
388    notes: String,
389    spectrum: &[secs_engine::C],
390    axis: ExportAxis,
391) -> MeasurementInput {
392    let (samples, t0) = design.replay.export_ir(design, spectrum, axis);
393    MeasurementInput {
394        title,
395        notes,
396        sample_rate_hz: SR,
397        samples,
398        start_time_s: t0,
399        spl_offset_db: None,
400        source_info: None,
401        computed: false,
402    }
403}
404
405fn stage_items_with_mimo(
406    run: &ExportRun<'_>,
407    mimo: MimoExport<'_>,
408    label: Option<&str>,
409) -> Result<Vec<MeasurementInput>, ExportError> {
410    let view = run.design.replay.export_view(run.design)?;
411    let position = run.design.replay.config().main_position;
412    let subs: Vec<_> = run
413        .design
414        .replay
415        .config()
416        .subs
417        .iter()
418        .filter_map(|role| view.spectra.get(position, role))
419        .collect();
420    let label = label.map_or_else(|| run.settings.label(), str::to_owned);
421    let mut items = Vec::new();
422    for (index, main) in run.design.chain.mains.iter().enumerate() {
423        let seq = index + 1;
424        let raw = view
425            .spectra
426            .get(position, &main.role)
427            .ok_or_else(|| ExportError::MissingResponse(main.role.clone()))?;
428        let stages = stage_responses(run.design, &main.role, &view.spectra, position)
429            .ok_or_else(|| ExportError::MissingResponse(main.role.clone()))?;
430        let prefix = format!("SECS 보정 설계 · {label} · 청취 위치 {position} · 계산값 — ");
431        items.push(item(
432            run.design,
433            format!("{seq:02}_{}_1 보정 전 메인", main.role),
434            format!("{prefix}메인 스피커 원 응답(2 s 창, 필터 없음)"),
435            raw,
436            ExportAxis::Measurement,
437        ));
438        if !subs.is_empty() {
439            let mut sum = vec![secs_engine::C::new(0.0, 0.0); raw.len()];
440            for spectrum in &subs {
441                for (out, value) in sum.iter_mut().zip(spectrum.iter()) {
442                    *out += value;
443                }
444            }
445            let tail = if view.has_sub_filters {
446                "서브 원 응답의 단순 합(정렬 없음 — 서브 고정 출력 필터만)"
447            } else {
448                "서브 원 응답의 단순 합(정렬 없음·필터 없음)"
449            };
450            items.push(item(
451                run.design,
452                format!("{seq:02}_{}_1 보정 전 서브", main.role),
453                format!("{prefix}{tail}"),
454                &sum,
455                ExportAxis::Measurement,
456            ));
457        }
458        add_xo_items(run, &mut items, seq, main.role.as_str(), &prefix, &stages);
459        let mut correction_pieces = lf_correction_pieces(run.settings);
460        if let Some(piece) = rc_bands_piece(&run.settings.rc_bands) {
461            correction_pieces.insert(0, piece);
462        }
463        let correction_pieces = if correction_pieces.is_empty() {
464            String::new()
465        } else {
466            format!(" · {}", correction_pieces.join(" · "))
467        };
468        items.push(item(
469            run.design,
470            format!("{seq:02}_{}_3 합 후 보정", main.role),
471            format!(
472                "{prefix}2차: 탑+서브 합에 입력 보정({}) · 전체 지연 {} ms(시작 시각에서 뺌) · RC 상한 {} Hz{correction_pieces}",
473                chain_text(run),
474                format_fixed(run.design.chain.latency_ms, 1, false),
475                format_fixed(run.design.rc_hi, 0, false)
476            ),
477            &stages.output,
478            ExportAxis::Corrected,
479        ));
480        if let MimoExport::Responses(mimo) = mimo {
481            let supports: Vec<_> = mimo
482                .paths
483                .paths
484                .iter()
485                .filter(|path| path.input == main.role)
486                .collect();
487            if !supports.is_empty() {
488                let response = mimo
489                    .applied
490                    .iter()
491                    .find(|(role, _)| role == &main.role)
492                    .map(|(_, response)| response.as_slice())
493                    .ok_or_else(|| ExportError::MissingResponse(main.role.clone()))?;
494                let description = supports
495                    .iter()
496                    .map(|path| match &path.filter {
497                        secs_types::chain::MimoFilter::Fir { taps_48k } => {
498                            format!("{} FIR {}탭", path.support, grouped(taps_48k.len()))
499                        }
500                        secs_types::chain::MimoFilter::FirLowRate { .. } => {
501                            format!(
502                                "{} FIR {}탭",
503                                path.support,
504                                grouped(path.filter.fir_len_48k())
505                            )
506                        }
507                        secs_types::chain::MimoFilter::Iir {
508                            gain_db,
509                            delay_ms,
510                            polarity,
511                            peq,
512                            allpass,
513                        } => format!(
514                            "{} {} dB {} ms {} PEQ {} AP {}",
515                            path.support,
516                            format_fixed(*gain_db, 1, false),
517                            format_fixed(*delay_ms, 1, false),
518                            if *polarity > 0 { "+" } else { "-" },
519                            peq.len(),
520                            allpass.len()
521                        ),
522                    })
523                    .collect::<Vec<_>>()
524                    .join("; ");
525                items.push(item(
526                    run.design,
527                    format!("{seq:02}_{}_4 MIMO 적용({})", main.role, mimo.kind.name()),
528                    format!(
529                        "{prefix}MIMO {} 서포트 {}개(Fsiso {} Hz{}) — {description}",
530                        mimo.kind.name(),
531                        supports.len(),
532                        format_g(mimo.fsiso, false),
533                        mimo.cap_text
534                    ),
535                    response,
536                    ExportAxis::Corrected,
537                ));
538            }
539        }
540    }
541    Ok(items)
542}
543
544fn add_xo_items(
545    run: &ExportRun<'_>,
546    items: &mut Vec<MeasurementInput>,
547    seq: usize,
548    role: &str,
549    prefix: &str,
550    stages: &StageResponses,
551) {
552    let Some(xo) = run
553        .design
554        .chain
555        .mains
556        .iter()
557        .find(|m| m.role == role)
558        .and_then(|m| m.xo_hz)
559        .filter(|v| *v != 0.0)
560    else {
561        return;
562    };
563    items.push(item(
564        run.design,
565        format!("{seq:02}_{role}_2 XO 타겟 메인"),
566        format!(
567            "{prefix}1차: 게인·딜레이·출력 PEQ(음향 XO 타겟)·전기 HP {} Hz",
568            format_g(xo, false)
569        ),
570        &stages.top_xo,
571        ExportAxis::Measurement,
572    ));
573    if let Some(sub) = &stages.sub_xo {
574        items.push(item(
575            run.design,
576            format!("{seq:02}_{role}_2 XO 타겟 서브"),
577            format!(
578                "{prefix}1차: BA(게인·지연·극성)·서브 버스 PEQ·전기 LP — {}",
579                sub_values_text(run)
580            ),
581            sub,
582            ExportAxis::Measurement,
583        ));
584    }
585}
586
587pub fn stage_items(run: &ExportRun<'_>, label: Option<&str>) -> Vec<MeasurementInput> {
588    stage_items_with_mimo(run, MimoExport::None, label).expect("validated engine export inputs")
589}
590
591pub fn stage_items_mimo(
592    run: &ExportRun<'_>,
593    mimo: &MimoResponses,
594    label: Option<&str>,
595) -> Result<Vec<MeasurementInput>, ExportError> {
596    stage_items_with_mimo(run, MimoExport::Responses(mimo), label)
597}
598
599fn before_after_items_with_mimo(
600    run: &ExportRun<'_>,
601    mimo: MimoExport<'_>,
602    sources: Option<&Sources>,
603    originals: Option<&[Original]>,
604) -> Result<Vec<MeasurementInput>, ExportError> {
605    let view = run.design.replay.export_view(run.design)?;
606    let position = run.design.replay.config().main_position;
607    let label = run.settings.label();
608    let source_env = sources.and_then(|sources| sources.get(&position));
609    let mut items = Vec::new();
610    let mut seq = 0;
611    for main in &run.design.chain.mains {
612        seq += 1;
613        if let Some(measured) = run.design.replay.measurements().get(position, &main.role) {
614            items.push(measured_item(
615                seq,
616                &main.role,
617                position,
618                measured,
619                "",
620                source_env.and_then(|sources| sources.get(&main.role)),
621                originals,
622            ));
623        }
624        let final_response = stage_responses(run.design, &main.role, &view.spectra, position)
625            .ok_or_else(|| ExportError::MissingResponse(main.role.clone()))?
626            .output;
627        let fir = if main.fir.len() > 1 {
628            format!("FIR {}탭", grouped(main.fir.len()))
629        } else {
630            "FIR 없음".into()
631        };
632        let mut notes = format!(
633            "SECS 보정 설계 · {label} · 청취 위치 {position} · 계산값 — 채널 보정(PEQ {}개 · {fir}) + 서브 합, 전체 지연 {} ms(시작 시각에서 뺌) · {}",
634            main.input_peq.len(),
635            format_fixed(run.design.chain.latency_ms, 1, false),
636            rc_pieces(run).join(" · ")
637        );
638        if !run.design.chain.subs.is_empty() && main.xo_hz.is_some_and(|v| v != 0.0) {
639            notes.push_str(" · 서브: ");
640            notes.push_str(&sub_values_text(run));
641        }
642        let mut corrected = item(
643            run.design,
644            format!("{seq:02}_{}_2 보정 후 {label}", main.role),
645            notes,
646            &final_response,
647            ExportAxis::Corrected,
648        );
649        corrected.source_info = source_env
650            .and_then(|sources| sources.get(&main.role))
651            .cloned();
652        corrected.computed = true;
653        if originals.is_some() {
654            clear_curves(&mut corrected);
655        }
656        items.push(corrected);
657        if let MimoExport::Responses(mimo) = mimo {
658            let support_count = mimo
659                .paths
660                .paths
661                .iter()
662                .filter(|path| path.input == main.role)
663                .count();
664            if support_count != 0 {
665                let response = mimo
666                    .applied
667                    .iter()
668                    .find(|(role, _)| role == &main.role)
669                    .map(|(_, response)| response.as_slice())
670                    .ok_or_else(|| ExportError::MissingResponse(main.role.clone()))?;
671                let mut corrected = item(
672                    run.design,
673                    format!(
674                        "{seq:02}_{}_3 보정 후 + MIMO({})",
675                        main.role,
676                        mimo.kind.name()
677                    ),
678                    format!(
679                        "SECS 보정 설계 · {label} · 청취 위치 {position} · 계산값 — MIMO {} 서포트 {support_count}개 (Fsiso {} Hz{})",
680                        mimo.kind.name(),
681                        format_g(mimo.fsiso, false),
682                        mimo.cap_text
683                    ),
684                    response,
685                    ExportAxis::Corrected,
686                );
687                if originals.is_some() {
688                    corrected.computed = true;
689                    clear_curves(&mut corrected);
690                }
691                items.push(corrected);
692            }
693        }
694    }
695    for sub in &run.design.chain.subs {
696        if let Some(measured) = run.design.replay.measurements().get(position, &sub.role) {
697            seq += 1;
698            items.push(measured_item(
699                seq,
700                &sub.role,
701                position,
702                measured,
703                &format!(" · DSP 값: {}", sub_value_text(sub)),
704                source_env.and_then(|sources| sources.get(&sub.role)),
705                originals,
706            ));
707        }
708    }
709    if let Some(originals) = originals {
710        items.extend(
711            originals
712                .iter()
713                .filter(|original| original.position != position)
714                .map(|original| original.item.clone()),
715        );
716    }
717    Ok(items)
718}
719
720fn measured_item(
721    seq: usize,
722    role: &str,
723    position: u32,
724    measured: &secs_engine::Measurement,
725    note: &str,
726    source_info: Option<&SourceInfo>,
727    originals: Option<&[Original]>,
728) -> MeasurementInput {
729    let mut item = MeasurementInput {
730        title: format!("{seq:02}_{role}_1 보정 전(원 측정)"),
731        notes: format!("SECS · 청취 위치 {position} · 원 측정 그대로(필터 없음){note}"),
732        sample_rate_hz: measured.sample_rate,
733        samples: (0..measured.samples.len())
734            .map(|index| f64::from(measured.samples.at(index) as f32))
735            .collect(),
736        start_time_s: measured.t0,
737        spl_offset_db: None,
738        source_info: source_info.cloned(),
739        computed: false,
740    };
741    let Some(originals) = originals else {
742        return item;
743    };
744    if let Some(original) = originals
745        .iter()
746        .find(|original| original.position == position && original.role == role)
747    {
748        let title = item.title;
749        let notes = item.notes;
750        item = original.item.clone();
751        item.title = title;
752        item.notes = notes;
753        item.computed = false;
754    } else {
755        clear_curves(&mut item);
756    }
757    item
758}
759
760fn clear_curves(item: &mut MeasurementInput) {
761    if let Some(source_info) = &mut item.source_info {
762        source_info.cal.clear();
763    }
764}
765
766pub fn before_after_items(run: &ExportRun<'_>, sources: Option<&Sources>) -> Vec<MeasurementInput> {
767    before_after_items_with_mimo(run, MimoExport::None, sources, None)
768        .expect("validated engine export inputs")
769}
770
771pub fn before_after_items_mimo(
772    run: &ExportRun<'_>,
773    mimo: &MimoResponses,
774    sources: Option<&Sources>,
775) -> Result<Vec<MeasurementInput>, ExportError> {
776    before_after_items_with_mimo(run, MimoExport::Responses(mimo), sources, None)
777}
778
779/// Returns the REW mdat file name for the selected contents.
780pub fn rew_mdat_filename(scope: MdatScope, label: &str) -> String {
781    match scope {
782        MdatScope::All => format!("SECS 원 측정+보정 결과 {label}.mdat"),
783        MdatScope::Measurements => "SECS 원 측정.mdat".into(),
784        MdatScope::Results => format!("SECS 보정 결과 {label}.mdat"),
785    }
786}
787
788/// Builds the REW mdat items for the selected contents.
789pub fn rew_mdat_items(
790    run: Option<&ExportRun<'_>>,
791    scope: MdatScope,
792    originals: &[Original],
793    mimo: Option<&MimoResponses>,
794    sources: Option<&Sources>,
795) -> Result<Vec<MeasurementInput>, ExportError> {
796    if scope == MdatScope::Measurements {
797        if originals.is_empty() {
798            return Err(ExportError::NoMeasurements);
799        }
800        return Ok(originals
801            .iter()
802            .map(|original| original.item.clone())
803            .collect());
804    }
805    let run = run.ok_or(ExportError::NoResult)?;
806    let mut items = before_after_items_with_mimo(
807        run,
808        mimo.map_or(MimoExport::None, MimoExport::Responses),
809        sources,
810        Some(originals),
811    )?;
812    if scope == MdatScope::Results {
813        items.retain(|item| item.computed);
814    }
815    Ok(items)
816}
817
818/// `spl_offset_db` is the project's median REW SPL offset
819/// (`secs_project::project_spl_offset`).
820pub fn export_mdat(
821    run: &ExportRun<'_>,
822    folder: &Path,
823    spl_offset_db: Option<f64>,
824    now_ms: i64,
825) -> Result<PathBuf, ExportError> {
826    export_mdat_with_mimo(run, folder, None, spl_offset_db, now_ms)
827}
828
829fn export_mdat_with_mimo(
830    run: &ExportRun<'_>,
831    folder: &Path,
832    mimo: Option<&MimoResponses>,
833    spl_offset_db: Option<f64>,
834    now_ms: i64,
835) -> Result<PathBuf, ExportError> {
836    export_mdat_with_mimo_using(run, folder, mimo, spl_offset_db, now_ms, &mut || {
837        random_uuid().map_err(|error| ExportError::Random(error.to_string()))
838    })
839}
840
841/// Writes the staged mdat using an injected UUID source.
842pub fn export_mdat_with_mimo_using(
843    run: &ExportRun<'_>,
844    folder: &Path,
845    mimo: Option<&MimoResponses>,
846    spl_offset_db: Option<f64>,
847    now_ms: i64,
848    uuid: &mut dyn FnMut() -> Result<u128, ExportError>,
849) -> Result<PathBuf, ExportError> {
850    let label = run.settings.label();
851    let items = stage_items_with_mimo(
852        run,
853        mimo.map_or(MimoExport::None, MimoExport::Responses),
854        Some(&label),
855    )?;
856    export_items_using(
857        folder,
858        &format!("SECS 보정 설계 {label}.mdat"),
859        &items,
860        spl_offset_db,
861        now_ms,
862        uuid,
863    )
864}
865
866pub fn export_before_after_mdat(
867    run: &ExportRun<'_>,
868    folder: &Path,
869    sources: Option<&Sources>,
870    spl_offset_db: Option<f64>,
871    now_ms: i64,
872) -> Result<PathBuf, ExportError> {
873    export_before_after_mdat_with_mimo(run, folder, None, sources, spl_offset_db, now_ms)
874}
875
876fn export_before_after_mdat_with_mimo(
877    run: &ExportRun<'_>,
878    folder: &Path,
879    mimo: Option<&MimoResponses>,
880    sources: Option<&Sources>,
881    spl_offset_db: Option<f64>,
882    now_ms: i64,
883) -> Result<PathBuf, ExportError> {
884    export_before_after_mdat_with_mimo_using(
885        run,
886        folder,
887        mimo,
888        sources,
889        spl_offset_db,
890        now_ms,
891        &mut || random_uuid().map_err(|error| ExportError::Random(error.to_string())),
892    )
893}
894
895/// Writes the before/after mdat using an injected UUID source.
896pub fn export_before_after_mdat_with_mimo_using(
897    run: &ExportRun<'_>,
898    folder: &Path,
899    mimo: Option<&MimoResponses>,
900    sources: Option<&Sources>,
901    spl_offset_db: Option<f64>,
902    now_ms: i64,
903    uuid: &mut dyn FnMut() -> Result<u128, ExportError>,
904) -> Result<PathBuf, ExportError> {
905    let label = run.settings.label();
906    let items = before_after_items_with_mimo(
907        run,
908        mimo.map_or(MimoExport::None, MimoExport::Responses),
909        sources,
910        None,
911    )?;
912    export_items_using(
913        folder,
914        &format!("SECS 보정 전후 {label}.mdat"),
915        &items,
916        spl_offset_db,
917        now_ms,
918        uuid,
919    )
920}
921
922/// Writes the selected measurements and correction results to one REW mdat.
923#[allow(clippy::too_many_arguments)] // Signature keeps the existing injected-writer API shape.
924pub fn export_rew_mdat_using(
925    run: Option<&ExportRun<'_>>,
926    scope: MdatScope,
927    originals: &[Original],
928    folder: &Path,
929    mimo: Option<&MimoResponses>,
930    sources: Option<&Sources>,
931    spl_offset_db: Option<f64>,
932    now_ms: i64,
933    uuid: &mut dyn FnMut() -> Result<u128, ExportError>,
934) -> Result<PathBuf, ExportError> {
935    let items = rew_mdat_items(run, scope, originals, mimo, sources)?;
936    let label = run.map(|run| run.settings.label()).unwrap_or_default();
937    export_items_using(
938        folder,
939        &rew_mdat_filename(scope, &label),
940        &items,
941        spl_offset_db,
942        now_ms,
943        uuid,
944    )
945}
946
947fn export_items_using(
948    folder: &Path,
949    filename: &str,
950    items: &[MeasurementInput],
951    spl_offset_db: Option<f64>,
952    now_ms: i64,
953    uuid: &mut dyn FnMut() -> Result<u128, ExportError>,
954) -> Result<PathBuf, ExportError> {
955    let uuids = (0..items.len())
956        .map(|_| uuid())
957        .collect::<Result<Vec<_>, _>>()?;
958    let mut uuids = uuids.into_iter();
959    let bytes = secs_mdat::build(items, TEMPLATE, spl_offset_db, now_ms, &mut || {
960        uuids
961            .next()
962            .expect("one pre-generated UUID per validated measurement")
963    })?;
964    fs::create_dir_all(folder)?;
965    let destination = folder.join(filename);
966    atomic_replace(&destination, &bytes)?;
967    Ok(destination)
968}
969
970fn random_uuid() -> Result<u128, getrandom::Error> {
971    let mut bytes = [0_u8; 16];
972    getrandom::fill(&mut bytes)?;
973    let mut value = u128::from_be_bytes(bytes);
974    value &= !(0xf_u128 << 76);
975    value |= 4_u128 << 76;
976    value &= !(0x3_u128 << 62);
977    value |= 0x2_u128 << 62;
978    Ok(value)
979}
980
981fn atomic_replace(destination: &Path, bytes: &[u8]) -> Result<(), std::io::Error> {
982    secs_types::fs::write_atomic_bytes(destination, bytes)
983}
984
985#[cfg(test)]
986mod tests {
987    use super::*;
988    use std::sync::atomic::{AtomicU64, Ordering};
989
990    static TEMP_COUNTER: AtomicU64 = AtomicU64::new(0);
991
992    #[test]
993    fn rc_pieces_from_values_preserves_live_and_legacy_wording() {
994        assert_eq!(
995            rc_pieces_from_values(300.0, true, None, None, false),
996            ["RC 상한 300 Hz (기본값)", "자동: 룸 볼륨 없음"]
997        );
998        assert_eq!(
999            rc_pieces_from_values(300.0, true, None, None, true),
1000            ["RC 상한 300 Hz (자동)", "자동: 룸 볼륨 없음"]
1001        );
1002        assert_eq!(
1003            rc_pieces_from_values(300.0, false, None, Some(80.0), true),
1004            ["RC 상한 300 Hz (수동)"]
1005        );
1006        assert_eq!(
1007            rc_pieces_from_values(300.0, true, Some(420.0), Some(80.0), false),
1008            [
1009                "RC 상한 300 Hz (슈뢰더 420 Hz)",
1010                "자동: 룸 볼륨 80 m³",
1011                "자동 상한 최대 300 Hz",
1012            ]
1013        );
1014        assert_eq!(
1015            rc_pieces_from_values_with_bands(
1016                300.0,
1017                false,
1018                None,
1019                None,
1020                false,
1021                &[
1022                    RcBand {
1023                        lo_hz: 1_000.0,
1024                        hi_hz: 2_000.0,
1025                    },
1026                    RcBand {
1027                        lo_hz: 15_000.0,
1028                        hi_hz: 20_000.0,
1029                    },
1030                ],
1031            ),
1032            [
1033                "RC 상한 300 Hz (수동)",
1034                "RC 추가 구간 1000–2000, 15000–20000 Hz"
1035            ]
1036        );
1037        let settings = CalibrationSettings {
1038            lf_align: true,
1039            mode_decay: true,
1040            ..Default::default()
1041        };
1042        assert_eq!(
1043            lf_correction_pieces(&settings),
1044            ["저음 도착 맞춤", "방 울림 줄임"]
1045        );
1046        let zero = CalibrationSettings {
1047            mode: Mode::Zero,
1048            ..settings
1049        };
1050        assert_eq!(lf_correction_pieces(&zero), ["방 울림 줄임"]);
1051    }
1052
1053    #[test]
1054    fn atomic_replace_overwrites_and_cleans_temporary_file() {
1055        let root = std::env::temp_dir().join(format!(
1056            "secs-export-atomic-{}-{}",
1057            std::process::id(),
1058            TEMP_COUNTER.fetch_add(1, Ordering::Relaxed)
1059        ));
1060        fs::create_dir(&root).unwrap();
1061        let destination = root.join("SECS 보정 설계 표준 모드.mdat");
1062        fs::write(&destination, b"old").unwrap();
1063
1064        atomic_replace(&destination, b"new").unwrap();
1065
1066        assert_eq!(fs::read(&destination).unwrap(), b"new");
1067        assert_eq!(fs::read_dir(&root).unwrap().count(), 1);
1068        fs::remove_dir_all(root).unwrap();
1069    }
1070
1071    #[test]
1072    fn atomic_replace_cleans_temporary_file_after_rename_failure() {
1073        let root = std::env::temp_dir().join(format!(
1074            "secs-export-atomic-failure-{}-{}",
1075            std::process::id(),
1076            TEMP_COUNTER.fetch_add(1, Ordering::Relaxed)
1077        ));
1078        fs::create_dir(&root).unwrap();
1079        let destination = root.join("occupied");
1080        fs::create_dir(&destination).unwrap();
1081
1082        assert!(atomic_replace(&destination, b"new").is_err());
1083
1084        assert!(destination.is_dir());
1085        assert_eq!(fs::read_dir(&root).unwrap().count(), 1);
1086        fs::remove_dir_all(root).unwrap();
1087    }
1088
1089    #[test]
1090    fn random_uuid_has_v4_variant() {
1091        let uuid = random_uuid().unwrap();
1092        assert_eq!((uuid >> 76) & 0xf, 4);
1093        assert_eq!((uuid >> 62) & 0x3, 2);
1094    }
1095
1096    #[test]
1097    fn warning_edges() {
1098        let mut settings = CalibrationSettings::default();
1099        let entry = secs_types::calibration::SubEntry {
1100            hp_hz: 30.0,
1101            lp_hz: 50.0,
1102            ..secs_types::calibration::SubEntry::default()
1103        };
1104        settings.subs_manual.push(("SW1".into(), entry));
1105        assert_eq!(
1106            sub_filter_warnings(&settings, &["SW1".into()]),
1107            vec![SubWarning::NarrowBand {
1108                role: "SW1".into(),
1109                hp_hz: 30.0,
1110                lp_hz: 50.0,
1111            }]
1112        );
1113    }
1114}