sensus 0.5.0

CLI for sensus: simulate sensory perception (color blindness, low vision, hearing loss) on images
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
//! sensus CLI — simulate sensory perception on images.
//!
//! 画像/音声を読み、選択したフィルタを適用して出力する。エラーは stderr に通知し
//! 非ゼロ終了する(成功 0 / 失敗 1)。core の `Filter` は全バリアント実装済みで、
//! 未実装フィルタ経路(旧 exit-2)は持たない。

use std::path::{Path, PathBuf};
use std::process::ExitCode;

use clap::{Parser, ValueEnum};
use sensus_core::{
    pipeline::{FilterStep, Pipeline},
    stereo::{read_xmp_depth, split_mpo, stereo_to_depth},
    vision::{depth_aware_blur, DepthBlurKind},
    AudioPipeline, Error as CoreError, Filter as CoreFilter, HearingFilter,
};
use thiserror::Error;

mod audio;

/// depth フィルタ(myopia-depth / hyperopia-depth / depth-of-field)の `--strength 1.0`
/// に対応する最大ぼけ半径(min(W,H) 比)。
///
/// この値は非深度の近視ディスクブラー(`vision::myopia` の `MYOPIA_MAX_RADIUS_RATIO`)と
/// 同じ 0.023 で、Smith–Helmholtz の `0.5 × pupil_diameter × |D|` から導かれる「近視最大相当」。
/// `depth_aware_blur` は各画素のぼけ半径を `depth との差 × この比 × min(W,H)` で算出するため、
/// `--strength 1.0` がこの比=**全効果**になる(縮小ではなく、これが上限)。
const DEPTH_BLUR_MAX_RADIUS_RATIO: f32 = 0.023;

#[derive(Debug, Clone, Copy, ValueEnum)]
enum Filter {
    // Phase 1: 色覚特性 (Issue #2)
    Protanopia,
    Deuteranopia,
    Tritanopia,
    Achromatopsia,
    // Phase 1+: 四色型色覚 (Issue #3)
    Tetrachromacy,
    // Phase 2: 焦点・屈折 (Issue #4)
    Myopia,
    Hyperopia,
    Astigmatism,
    Presbyopia,
    // Phase 3: 視野異常 (Issue #5)
    Glaucoma,
    MacularDegeneration,
    Hemianopia,
    TunnelVision,
    // Phase 3: 光・透明度 (Issue #6)
    Cataract,
    Floaters,
    Photophobia,
    NightBlindness,
    // Phase 4: 平衡・めまい視覚 (Issue #9)
    Vertigo,
    BppvRotation,
    VestibularNeuritis,
    // Phase 4: 眼振・複視・スターバースト (Issue #29)
    Diplopia,
    Nystagmus,
    Starbursts,
    // Phase 4: 眼精疲労・ドライアイ (Issue #36)
    EyeStrain,
    DryEye,
    // Phase N: 変視症・コントラスト感度低下・ディテールロス・閃輝暗点 (Issue #55-#59)
    Metamorphopsia,
    ContrastSensitivity,
    DetailLoss,
    Teichopsia,
    FlickeringStars,
    // Phase N: 深度マップ対応距離依存ぼけ (Issue #19)
    MyopiaDepth,
    HyperopiaDepth,
    DepthOfField,
}

impl Filter {
    fn is_depth_filter(self) -> bool {
        matches!(
            self,
            Filter::MyopiaDepth | Filter::HyperopiaDepth | Filter::DepthOfField
        )
    }

    fn depth_kind(self) -> Option<DepthBlurKind> {
        match self {
            Filter::MyopiaDepth => Some(DepthBlurKind::Myopia),
            Filter::HyperopiaDepth => Some(DepthBlurKind::Hyperopia),
            Filter::DepthOfField => Some(DepthBlurKind::DepthOfField),
            _ => None,
        }
    }

    /// Map the CLI-facing enum (clap derive) to the core enum, pulling
    /// filter-specific parameters from the parsed `cli` flags.
    ///
    /// すべてのフィルタ固有パラメータは core `Filter` の payload に詰める。
    /// pipeline / apply はこの payload だけを読むため、CLI フラグが無視されることはない。
    fn to_core(self, cli: &Cli) -> CoreFilter {
        match self {
            Filter::Protanopia => CoreFilter::Protanopia,
            Filter::Deuteranopia => CoreFilter::Deuteranopia,
            Filter::Tritanopia => CoreFilter::Tritanopia,
            Filter::Achromatopsia => CoreFilter::Achromatopsia,
            Filter::Tetrachromacy => CoreFilter::Tetrachromacy,
            Filter::Myopia => CoreFilter::Myopia,
            Filter::Hyperopia => CoreFilter::Hyperopia,
            Filter::Astigmatism => CoreFilter::Astigmatism { axis_deg: cli.axis },
            Filter::Presbyopia => CoreFilter::Presbyopia,
            Filter::Glaucoma => CoreFilter::Glaucoma {
                mode: sensus_core::vision::GlaucomaMode::Vignette,
            },
            Filter::MacularDegeneration => CoreFilter::MacularDegeneration,
            Filter::Hemianopia => CoreFilter::Hemianopia { side: cli.side },
            Filter::TunnelVision => CoreFilter::TunnelVision,
            Filter::Cataract => CoreFilter::Cataract { seed: cli.seed },
            Filter::Floaters => CoreFilter::Floaters {
                seed: cli.seed,
                density: cli.density,
                size: cli.size,
                gaze_x: cli.gaze_x,
                gaze_y: cli.gaze_y,
            },
            Filter::Photophobia => CoreFilter::Photophobia,
            Filter::NightBlindness => CoreFilter::NightBlindness,
            Filter::Vertigo => CoreFilter::Vertigo,
            Filter::BppvRotation => CoreFilter::BppvRotation,
            Filter::VestibularNeuritis => CoreFilter::VestibularNeuritis,
            Filter::Diplopia => CoreFilter::Diplopia {
                offset_x: cli.offset_x,
                offset_y: cli.offset_y,
                ghost_strength: cli.ghost_strength,
            },
            Filter::Nystagmus => CoreFilter::Nystagmus {
                amplitude: cli.amplitude,
                direction_deg: cli.direction_deg,
            },
            Filter::Starbursts => CoreFilter::Starbursts {
                num_rays: cli.num_rays,
                ray_length_ratio: cli.ray_length,
                threshold: cli.threshold,
                dispersion: cli.dispersion,
            },
            Filter::EyeStrain => CoreFilter::EyeStrain,
            Filter::DryEye => CoreFilter::DryEye,
            Filter::Metamorphopsia => CoreFilter::Metamorphopsia {
                freq: cli.meta_freq,
                seed: cli.meta_seed,
            },
            Filter::ContrastSensitivity => CoreFilter::ContrastSensitivity,
            Filter::DetailLoss => CoreFilter::DetailLoss {
                cell_size: cli.cell_size,
            },
            Filter::Teichopsia => CoreFilter::Teichopsia,
            Filter::FlickeringStars => CoreFilter::FlickeringStars { seed: cli.seed },
            Filter::MyopiaDepth | Filter::HyperopiaDepth | Filter::DepthOfField => {
                // depth フィルタは pipeline を通さないため、ここには来ない
                unreachable!("depth filters must be handled separately")
            }
        }
    }
}

/// CLI-facing hearing filter enum (clap derive). Maps to core [`HearingFilter`].
/// `--audio` モードで `--hearing` に指定する(#105)。
//
// `HearingLoss` は疾患名(難聴)であって enum 名の重複ではないため allow する。
#[allow(clippy::enum_variant_names)]
#[derive(Debug, Clone, Copy, ValueEnum)]
enum Hearing {
    /// 難聴(高音域カット)
    HearingLoss,
    /// 突発性難聴(--freq の帯域を削る)
    SuddenHearingLoss,
    /// 騒音性難聴(4 kHz 付近の損失)
    NoiseInducedHearingLoss,
    /// 耳鳴り(--freq の正弦波を常時ミックス)
    Tinnitus,
    /// 音響過敏(全体を異常増幅)
    Hyperacusis,
    /// ミソフォニア(--freq 中心のトリガー帯域だけ過剰増幅 + 歪み)
    Misophonia,
    /// 変音(金属的な歪み)
    Paracusis,
    /// 音楽音痴(音程差を識別しにくくする)
    Amusia,
    /// ジスメロディア(不快・歪んだ音)
    Dysmelodia,
    /// 音程シフト(--semitones 半音)
    PitchShift,
    /// ダイプラクシス(左右耳で異なる音程)
    Diplacusis,
    /// APD(聴覚情報処理障害)
    AuditoryProcessingDisorder,
    /// メニエール病の聴覚側(低音域難聴 + 低い唸る耳鳴り)
    Meniere,
    /// 迷路炎の聴覚側(高音域感音難聴 + 高音の耳鳴り)
    Labyrinthitis,
}

impl Hearing {
    /// Map the CLI-facing enum to the core enum, pulling parameters from `cli`.
    fn to_core(self, cli: &Cli) -> HearingFilter {
        match self {
            Hearing::HearingLoss => HearingFilter::HearingLoss,
            Hearing::SuddenHearingLoss => HearingFilter::SuddenHearingLoss { freq_hz: cli.freq },
            Hearing::NoiseInducedHearingLoss => HearingFilter::NoiseInducedHearingLoss,
            Hearing::Tinnitus => HearingFilter::Tinnitus { freq_hz: cli.freq },
            Hearing::Hyperacusis => HearingFilter::Hyperacusis,
            Hearing::Misophonia => HearingFilter::Misophonia { freq_hz: cli.freq },
            Hearing::Paracusis => HearingFilter::Paracusis,
            Hearing::Amusia => HearingFilter::Amusia,
            Hearing::Dysmelodia => HearingFilter::Dysmelodia,
            Hearing::PitchShift => HearingFilter::PitchShift {
                semitones: cli.semitones,
            },
            Hearing::Diplacusis => HearingFilter::Diplacusis,
            Hearing::AuditoryProcessingDisorder => HearingFilter::AuditoryProcessingDisorder,
            Hearing::Meniere => HearingFilter::Meniere,
            Hearing::Labyrinthitis => HearingFilter::Labyrinthitis,
        }
    }
}

/// sensus — simulate sensory perception on images.
#[derive(Debug, Parser)]
#[command(name = "sensus", version, about, long_about = None)]
struct Cli {
    /// Input image path (PNG / JPEG / WebP, etc.). Not required when --mpo is used.
    #[arg(short, long)]
    input: Option<PathBuf>,

    /// 出力ファイルパス(--pipe 時は不要)
    #[arg(short, long, required_unless_present = "pipe")]
    output: Option<PathBuf>,

    /// Filter(s) to apply. Specify multiple times to chain filters.
    #[arg(short, long, value_enum, num_args = 1..)]
    filter: Vec<Filter>,

    /// Filter strength in 0.0..=1.0 (0.0 = original, 1.0 = full effect).
    #[arg(short, long, default_value_t = 1.0, value_parser = parse_strength)]
    strength: f32,

    /// Astigmatism axis in degrees (0.0..=180.0). Only used with
    /// `--filter astigmatism`. Default `90.0` (with-the-rule astigmatism:
    /// vertical sharp, horizontal blurred).
    #[arg(long, default_value_t = 90.0, value_parser = parse_axis)]
    axis: f32,

    /// Random seed for stochastic filters (cataract, floaters). Default: 0.
    #[arg(long, default_value = "0")]
    seed: u64,

    /// Floater density in 0.0..=1.0. Only used with --filter floaters.
    #[arg(long, default_value = "0.5")]
    density: f32,

    /// Gaze X position in 0.0..=1.0 (0=left, 1=right). Only used with --filter floaters.
    #[arg(long, default_value = "0.5")]
    gaze_x: f32,

    /// Gaze Y position in 0.0..=1.0 (0=top, 1=bottom). Only used with --filter floaters.
    #[arg(long, default_value = "0.5")]
    gaze_y: f32,

    /// Floater size multiplier (0.1..=5.0). 1.0 = default blob radius / thread width.
    /// Only used with --filter floaters.
    #[arg(long, default_value = "1.0", value_parser = parse_floater_size)]
    size: f32,

    /// Hemianopia side: 0.0 = left field lost, 1.0 = right field lost.
    /// Only used with --filter hemianopia.
    #[arg(long, default_value = "0.0")]
    side: f32,

    /// Depth map image path (PNG / JPEG / etc.). Only used with depth blur filters.
    #[arg(long)]
    depth: Option<PathBuf>,

    /// MPO stereo image path. Automatically generates a depth map and applies depth blur.
    /// Requires a depth blur filter (--filter myopia-depth / hyperopia-depth / depth-of-field).
    #[arg(long)]
    mpo: Option<PathBuf>,

    /// Android portrait-mode JPEG path. Extracts XMP depth map and applies depth blur.
    /// Requires a depth blur filter (--filter myopia-depth / hyperopia-depth / depth-of-field).
    /// --input is not required when --portrait is used.
    #[arg(long, conflicts_with = "mpo")]
    portrait: Option<PathBuf>,

    /// Focus depth in 0.0..=1.0 (bright=near, dark=far). Only used with depth blur filters.
    #[arg(long, default_value = "0.5", value_parser = parse_focus)]
    focus: f32,

    /// Diplopia horizontal offset in min(W,H) ratio (-1.0..=1.0). Default: 0.02
    #[arg(long, default_value = "0.02", value_parser = parse_signed_ratio)]
    offset_x: f32,

    /// Diplopia vertical offset in min(W,H) ratio (-1.0..=1.0). Default: 0.01
    #[arg(long, default_value = "0.01", value_parser = parse_signed_ratio)]
    offset_y: f32,

    /// Diplopia ghost image strength (0.0..=1.0). Default: 0.7
    #[arg(long, default_value = "0.7", value_parser = parse_ratio)]
    ghost_strength: f32,

    /// Nystagmus amplitude in min(W,H) ratio. Default: 0.03
    #[arg(long, default_value = "0.03", value_parser = parse_ratio)]
    amplitude: f32,

    /// Nystagmus direction in degrees (0=horizontal, 90=vertical). Default: 0.0
    #[arg(long, default_value = "0.0", value_parser = parse_direction_deg)]
    direction_deg: f32,

    /// Starbursts number of rays. Default: 6
    #[arg(long, default_value = "6")]
    num_rays: u32,

    /// Starbursts ray length in min(W,H) ratio. Default: 0.1
    #[arg(long, default_value = "0.1", value_parser = parse_ratio)]
    ray_length: f32,

    /// Starbursts brightness threshold (0.0..=1.0). Default: 0.8
    #[arg(long, default_value = "0.8", value_parser = parse_ratio)]
    threshold: f32,

    /// Starbursts chromatic dispersion (0.0..=1.0). 0.0 = white rays, 1.0 = full rainbow.
    /// Only used with --filter starbursts. Default: 0.0
    #[arg(long, default_value = "0.0", value_parser = parse_ratio)]
    dispersion: f32,

    /// Detail-loss tile size in pixels (>= 1; 1 = no effect). Only used with --filter detail-loss.
    /// Default: 8
    #[arg(long, default_value = "8")]
    cell_size: u32,

    /// Metamorphopsia distortion spatial frequency. Only used with --filter metamorphopsia.
    /// Default: 4.0
    #[arg(long, default_value = "4.0", value_parser = parse_meta_freq)]
    meta_freq: f32,

    /// Metamorphopsia distortion-field seed. Only used with --filter metamorphopsia. Default: 0
    #[arg(long, default_value = "0")]
    meta_seed: u64,

    /// Read JPEG frames from stdin and write filtered JPEG frames to stdout (ffmpeg pipe mode).
    /// Cannot be combined with --input.
    #[arg(long, conflicts_with = "input")]
    pipe: bool,

    /// Input audio path (WAV). Routes to hearing-filter mode; requires --hearing and --output.
    /// Cannot be combined with image filters (--filter) or --pipe.
    #[arg(long, conflicts_with_all = ["input", "pipe", "mpo", "portrait"])]
    audio: Option<PathBuf>,

    /// Hearing filter(s) to apply to --audio. Specify multiple times to chain.
    #[arg(long, value_enum, num_args = 1..)]
    hearing: Vec<Hearing>,

    /// Frequency (Hz) for --hearing tinnitus / sudden-hearing-loss / misophonia. Default: 4000.
    #[arg(long, default_value_t = 4000.0, value_parser = parse_freq)]
    freq: f32,

    /// Semitones for --hearing pitch-shift (negative = lower, positive = higher). Default: 0.0
    #[arg(long, default_value_t = 0.0, value_parser = parse_semitones)]
    semitones: f32,
}

/// Parse the `--strength` argument and reject values outside `0.0..=1.0`
/// or NaN early, before any I/O. core 側の clamp は防御的に残してある。
fn parse_strength(s: &str) -> Result<f32, String> {
    let v: f32 = s
        .parse()
        .map_err(|e: std::num::ParseFloatError| e.to_string())?;
    if v.is_nan() || !(0.0..=1.0).contains(&v) {
        return Err(format!("strength must be in 0.0..=1.0, got {v}"));
    }
    Ok(v)
}

/// Parse a ratio argument in `0.0..=1.0` (ghost-strength, amplitude, ray-length, threshold 等).
fn parse_ratio(s: &str) -> Result<f32, String> {
    let v: f32 = s
        .parse()
        .map_err(|e: std::num::ParseFloatError| e.to_string())?;
    if v.is_nan() || !(0.0..=1.0).contains(&v) {
        return Err(format!("value must be in 0.0..=1.0, got {v}"));
    }
    Ok(v)
}

/// Parse a signed offset ratio in `-1.0..=1.0` (offset-x, offset-y).
fn parse_signed_ratio(s: &str) -> Result<f32, String> {
    let v: f32 = s
        .parse()
        .map_err(|e: std::num::ParseFloatError| e.to_string())?;
    if v.is_nan() || !(-1.0..=1.0).contains(&v) {
        return Err(format!("value must be in -1.0..=1.0, got {v}"));
    }
    Ok(v)
}

/// Parse `--size` (floater size multiplier) in `0.1..=5.0`.
/// core 側も同じ範囲に clamp するが (#110)、誤入力を早期に弾く。
fn parse_floater_size(s: &str) -> Result<f32, String> {
    let v: f32 = s
        .parse()
        .map_err(|e: std::num::ParseFloatError| e.to_string())?;
    if !v.is_finite() || !(0.1..=5.0).contains(&v) {
        return Err(format!("size must be in 0.1..=5.0, got {v}"));
    }
    Ok(v)
}

/// Parse `--meta-freq` (metamorphopsia spatial frequency). 有限かつ正の値。
fn parse_meta_freq(s: &str) -> Result<f32, String> {
    let v: f32 = s
        .parse()
        .map_err(|e: std::num::ParseFloatError| e.to_string())?;
    if !v.is_finite() || v <= 0.0 {
        return Err(format!("meta-freq must be finite and > 0.0, got {v}"));
    }
    Ok(v)
}

/// Parse the `--focus` argument and reject values outside `0.0..=1.0` or NaN.
fn parse_focus(s: &str) -> Result<f32, String> {
    let v: f32 = s
        .parse()
        .map_err(|e: std::num::ParseFloatError| e.to_string())?;
    if v.is_nan() || !(0.0..=1.0).contains(&v) {
        return Err(format!("focus must be in 0.0..=1.0, got {v}"));
    }
    Ok(v)
}

/// Parse the `--axis` argument (astigmatism cylinder axis in degrees) and
/// reject values outside `0.0..=180.0` or NaN early. 軸の周期は 180° なので
/// それより広い範囲は意味的に冗長 (誤入力の可能性が高い) として弾く。
fn parse_axis(s: &str) -> Result<f32, String> {
    let v: f32 = s
        .parse()
        .map_err(|e: std::num::ParseFloatError| e.to_string())?;
    if v.is_nan() || !(0.0..=180.0).contains(&v) {
        return Err(format!("axis must be in 0.0..=180.0 degrees, got {v}"));
    }
    Ok(v)
}

/// Parse `--freq` (Hz) for hearing filters. 正の有限値 0 < f <= 20000 のみ許容する。
fn parse_freq(s: &str) -> Result<f32, String> {
    let v: f32 = s
        .parse()
        .map_err(|e: std::num::ParseFloatError| e.to_string())?;
    if !v.is_finite() || v <= 0.0 || v > 20000.0 {
        return Err(format!(
            "freq must be in 0.0 (exclusive)..=20000.0 Hz, got {v}"
        ));
    }
    Ok(v)
}

/// Parse `--semitones` for pitch-shift. 有限値かつ ±48 半音(±4 オクターブ)以内。
fn parse_semitones(s: &str) -> Result<f32, String> {
    let v: f32 = s
        .parse()
        .map_err(|e: std::num::ParseFloatError| e.to_string())?;
    if !v.is_finite() || !(-48.0..=48.0).contains(&v) {
        return Err(format!(
            "semitones must be finite and in -48.0..=48.0, got {v}"
        ));
    }
    Ok(v)
}

/// Parse `--direction-deg` (nystagmus) in 0.0..=360.0.
fn parse_direction_deg(s: &str) -> Result<f32, String> {
    let v: f32 = s
        .parse()
        .map_err(|e: std::num::ParseFloatError| e.to_string())?;
    if v.is_nan() || !(0.0..=360.0).contains(&v) {
        return Err(format!("direction-deg must be in 0.0..=360.0, got {v}"));
    }
    Ok(v)
}

/// CLI-internal error type. Keeps the `main` ↔ `run` boundary explicit so
/// integration tests can drive `run` directly without poking `process::exit`.
#[derive(Debug, Error)]
enum RunError {
    #[error("sensus: failed to open input {path:?}: {source}")]
    InputOpen {
        path: PathBuf,
        #[source]
        source: image::ImageError,
    },

    #[error("sensus: failed to save output {path:?}: {source}")]
    OutputSave {
        path: PathBuf,
        #[source]
        source: image::ImageError,
    },

    /// A pipeline step failed at runtime.
    #[error("{0}")]
    Pipeline(String),

    #[error("sensus: failed to read MPO file {path:?}: {source}")]
    MpoRead {
        path: PathBuf,
        #[source]
        source: std::io::Error,
    },

    #[error("{0}")]
    MpoError(String),

    #[error("sensus: failed to read portrait file {path:?}: {source}")]
    PortraitRead {
        path: PathBuf,
        #[source]
        source: std::io::Error,
    },

    #[error("{0}")]
    PortraitError(String),

    /// --input が未指定で --mpo / --portrait も指定されていない
    #[error("{0}")]
    InputRequired(String),

    /// --audio モードのバリデーション失敗 / WAV 読み書き失敗
    #[error("{0}")]
    AudioError(String),

    #[error("sensus: I/O error: {0}")]
    Io(#[from] std::io::Error),
}

fn main() -> ExitCode {
    let cli = Cli::parse();
    match run(cli) {
        Ok(()) => ExitCode::SUCCESS,
        Err(RunError::Pipeline(msg)) => {
            eprintln!("{msg}");
            ExitCode::FAILURE
        }
        Err(RunError::MpoError(msg)) => {
            eprintln!("{msg}");
            ExitCode::FAILURE
        }
        Err(RunError::PortraitError(msg)) => {
            eprintln!("{msg}");
            ExitCode::FAILURE
        }
        Err(err @ RunError::MpoRead { .. }) => {
            eprintln!("{err}");
            ExitCode::FAILURE
        }
        Err(err @ RunError::PortraitRead { .. }) => {
            eprintln!("{err}");
            ExitCode::FAILURE
        }
        Err(RunError::InputRequired(msg)) => {
            eprintln!("{msg}");
            ExitCode::FAILURE
        }
        Err(RunError::AudioError(msg)) => {
            eprintln!("{msg}");
            ExitCode::FAILURE
        }
        Err(err) => {
            eprintln!("{err}");
            ExitCode::FAILURE
        }
    }
}

/// 単一フィルタ指定時に、そのフィルタが使わないパラメータフラグが
/// 明示的に変更されていれば警告する(best-effort な UX 補助。挙動には影響しない)。
fn warn_unused_flags(cli: &Cli, core_filter: CoreFilter) {
    if !matches!(core_filter, CoreFilter::Astigmatism { .. }) && cli.axis != 90.0 {
        eprintln!(
            "sensus: warning: --axis is only used with --filter astigmatism (ignored for {core_filter:?})"
        );
    }
    let uses_seed = matches!(
        core_filter,
        CoreFilter::Cataract { .. }
            | CoreFilter::Floaters { .. }
            | CoreFilter::FlickeringStars { .. }
    );
    if !uses_seed && cli.seed != 0 {
        eprintln!(
            "sensus: warning: --seed is only used with --filter cataract / floaters / flickering-stars (ignored for {core_filter:?})"
        );
    }
    let uses_floater_params = matches!(core_filter, CoreFilter::Floaters { .. });
    if !uses_floater_params
        && (cli.density != 0.5 || cli.gaze_x != 0.5 || cli.gaze_y != 0.5 || cli.size != 1.0)
    {
        eprintln!(
            "sensus: warning: --density/--gaze-x/--gaze-y/--size are only used with --filter floaters (ignored for {core_filter:?})"
        );
    }
    if !matches!(core_filter, CoreFilter::Hemianopia { .. }) && cli.side != 0.0 {
        eprintln!(
            "sensus: warning: --side is only used with --filter hemianopia (ignored for {core_filter:?})"
        );
    }
}

fn run(cli: Cli) -> Result<(), RunError> {
    // --audio モード: WAV を読み、聴覚フィルタチェーンを適用して WAV に書き出す
    if let Some(audio_path) = cli.audio.clone() {
        return run_audio(&cli, &audio_path);
    }

    // --pipe モード: stdin から JPEG フレームを読み stdout に出力する
    if cli.pipe {
        return run_pipe(&cli);
    }

    // --mpo が指定されている場合のバリデーションと処理
    if let Some(mpo_path) = cli.mpo.clone() {
        // depth フィルタは 1 つだけ必須(#108: 非 depth フィルタは合成可能)
        let kinds = depth_kinds(&cli);
        if kinds.len() != 1 {
            return Err(RunError::MpoError(if kinds.is_empty() {
                "sensus: --mpo requires a depth blur filter (myopia-depth, hyperopia-depth, depth-of-field)".to_string()
            } else {
                "sensus: --mpo accepts at most one depth blur filter".to_string()
            }));
        }
        let kind = kinds[0];
        // --depth との同時指定は不可
        if cli.depth.is_some() {
            return Err(RunError::MpoError(
                "sensus: --mpo and --depth cannot be used together".to_string(),
            ));
        }

        let bytes = std::fs::read(&mpo_path).map_err(|source| RunError::MpoRead {
            path: mpo_path.clone(),
            source,
        })?;
        let (left, right) =
            split_mpo(&bytes).map_err(|e| RunError::MpoError(format!("sensus: {e}")))?;
        let depth_img = stereo_to_depth(&left, &right)
            .map_err(|e| RunError::MpoError(format!("sensus: {e}")))?;
        // #108: depth 以外のフィルタを左目画像に先に適用してから depth blur
        let base = apply_non_depth_filters(left, &cli)?;
        let out = depth_aware_blur(
            base,
            &depth_img,
            cli.focus,
            cli.strength * DEPTH_BLUR_MAX_RADIUS_RATIO,
            kind,
        )
        .map_err(|e| RunError::Pipeline(format!("sensus: {e}")))?;
        let out_path = cli.output.as_ref().unwrap();
        return out.save(out_path).map_err(|source| RunError::OutputSave {
            path: out_path.clone(),
            source,
        });
    }

    // --portrait: Android XMP Depth
    if let Some(portrait_path) = cli.portrait.clone() {
        // depth フィルタは 1 つだけ必須(#108: 非 depth フィルタは合成可能)
        let kinds = depth_kinds(&cli);
        if kinds.len() != 1 {
            return Err(RunError::PortraitError(if kinds.is_empty() {
                "sensus: --portrait requires a depth blur filter (myopia-depth, hyperopia-depth, depth-of-field)".to_string()
            } else {
                "sensus: --portrait accepts at most one depth blur filter".to_string()
            }));
        }
        let kind = kinds[0];
        if cli.depth.is_some() {
            return Err(RunError::PortraitError(
                "sensus: --portrait and --depth cannot be used together".to_string(),
            ));
        }

        let portrait_bytes =
            std::fs::read(&portrait_path).map_err(|source| RunError::PortraitRead {
                path: portrait_path.clone(),
                source,
            })?;
        let depth_map = read_xmp_depth(&portrait_bytes)
            .map_err(|e| RunError::PortraitError(format!("sensus: {e}")))?;

        let source_img = if let Some(ref inp) = cli.input {
            image::open(inp).map_err(|source| RunError::InputOpen {
                path: inp.clone(),
                source,
            })?
        } else {
            image::load_from_memory(&portrait_bytes).map_err(|source| RunError::InputOpen {
                path: portrait_path.clone(),
                source,
            })?
        };

        // #108: depth 以外のフィルタを先に適用してから depth blur
        let base = apply_non_depth_filters(source_img, &cli)?;
        let out = depth_aware_blur(
            base,
            &depth_map,
            cli.focus,
            cli.strength * DEPTH_BLUR_MAX_RADIUS_RATIO,
            kind,
        )
        .map_err(|e| RunError::PortraitError(format!("sensus: {e}")))?;
        let out_path = cli.output.as_ref().unwrap();
        return out.save(out_path).map_err(|source| RunError::OutputSave {
            path: out_path.clone(),
            source,
        });
    }

    // --mpo なし・--portrait なし → --input が必須
    let input_path = cli.input.clone().ok_or_else(|| {
        RunError::InputRequired(
            "sensus: --input is required when --mpo and --portrait are not specified".to_string(),
        )
    })?;

    let img = image::open(&input_path).map_err(|source| RunError::InputOpen {
        path: input_path.clone(),
        source,
    })?;

    // depth フィルタが含まれる場合(#108: 非 depth フィルタを先に合成してから depth blur)
    if cli.filter.iter().any(|f| f.is_depth_filter()) {
        let kinds = depth_kinds(&cli);
        if kinds.len() != 1 {
            return Err(RunError::Pipeline(
                "sensus: exactly one depth blur filter is allowed (myopia-depth / hyperopia-depth / depth-of-field)".to_string(),
            ));
        }
        let kind = kinds[0];

        let depth_path = cli.depth.as_ref().ok_or_else(|| {
            RunError::Pipeline(
                "sensus: --depth <PATH> is required for depth blur filters".to_string(),
            )
        })?;
        let depth_img = image::open(depth_path).map_err(|source| RunError::InputOpen {
            path: depth_path.clone(),
            source,
        })?;
        // #108: depth 以外のフィルタを先に適用してから depth blur で合成
        let base = apply_non_depth_filters(img, &cli)?;
        let out = depth_aware_blur(
            base,
            &depth_img,
            cli.focus,
            cli.strength * DEPTH_BLUR_MAX_RADIUS_RATIO,
            kind,
        )
        .map_err(|e| RunError::Pipeline(format!("sensus: {e}")))?;
        let out_path = cli.output.as_ref().unwrap();
        return out.save(out_path).map_err(|source| RunError::OutputSave {
            path: out_path.clone(),
            source,
        });
    }

    // Build pipeline from --filter list (must not be empty; clap enforces num_args=1..)
    let mut pipeline = Pipeline::new();
    for f in &cli.filter {
        let core_filter = f.to_core(&cli);
        pipeline = pipeline.push(FilterStep::new(core_filter, cli.strength));
    }
    if cli.filter.len() == 1 {
        warn_unused_flags(&cli, cli.filter[0].to_core(&cli));
    }

    let result = pipeline.apply(img);

    match result {
        Ok(out) => {
            let out_path = cli.output.as_ref().unwrap();
            out.save(out_path).map_err(|source| RunError::OutputSave {
                path: out_path.clone(),
                source,
            })?;
            Ok(())
        }
        Err(CoreError::Image(err)) => Err(RunError::InputOpen {
            path: input_path.clone(),
            source: err,
        }),
        Err(e) => Err(RunError::Pipeline(format!("sensus: {e}"))),
    }
}

/// --audio モード: WAV を読み、`--hearing` の聴覚フィルタを [`AudioPipeline`] で
/// 順番に適用し、WAV に書き出す。
fn run_audio(cli: &Cli, audio_path: &Path) -> Result<(), RunError> {
    if cli.hearing.is_empty() {
        return Err(RunError::AudioError(
            "sensus: --audio requires at least one --hearing filter".to_string(),
        ));
    }
    if !cli.filter.is_empty() {
        return Err(RunError::AudioError(
            "sensus: --audio (hearing) cannot be combined with --filter (image filters)"
                .to_string(),
        ));
    }
    let out_path = cli.output.as_ref().ok_or_else(|| {
        RunError::AudioError("sensus: --output <PATH> is required with --audio".to_string())
    })?;

    let (buf, spec) = audio::read_wav(audio_path).map_err(RunError::AudioError)?;

    let mut pipeline = AudioPipeline::new();
    for h in &cli.hearing {
        pipeline = pipeline.push(h.to_core(cli), cli.strength);
    }
    let out = pipeline
        .apply(&buf)
        .map_err(|e| RunError::AudioError(format!("sensus: {e}")))?;

    audio::write_wav(out_path, &out, spec).map_err(RunError::AudioError)
}

/// 画像にフィルタパイプラインを適用する(--pipe モードと通常モードの共通処理)。
///
/// # 通常モードとの差分
/// 通常モードの `run()` では pipeline 構築後に warning 出力(--axis / --seed 等の
/// 使われていないフラグに対する注意喚起)を行うが、--pipe モードでは省略している。
/// これはフレームごとに同じ warning が大量に出力されることを防ぐためである。
fn apply_filters_to_image(
    img: image::DynamicImage,
    cli: &Cli,
) -> Result<image::DynamicImage, RunError> {
    let mut pipeline = Pipeline::new();
    for f in &cli.filter {
        let core_filter = f.to_core(cli);
        pipeline = pipeline.push(FilterStep::new(core_filter, cli.strength));
    }
    pipeline
        .apply(img)
        .map_err(|e| RunError::Pipeline(format!("sensus: {e}")))
}

/// cli.filter 中の depth フィルタの kind 一覧(#108)。
fn depth_kinds(cli: &Cli) -> Vec<DepthBlurKind> {
    cli.filter.iter().filter_map(|f| f.depth_kind()).collect()
}

/// depth **以外**のフィルタを Pipeline で `img` に適用する(#108 の合成用)。
///
/// depth フィルタは深度マップという第2入力が必要で Pipeline に載らないため、CLI 側で
/// 「非 depth フィルタを先に適用 → その結果に depth_aware_blur」と合成する。非 depth
/// フィルタが無ければ `img` をそのまま返す。
fn apply_non_depth_filters(
    img: image::DynamicImage,
    cli: &Cli,
) -> Result<image::DynamicImage, RunError> {
    // 非 depth フィルタだけで Pipeline を組む。空なら Pipeline::apply は恒等。
    let mut pipeline = Pipeline::new();
    for f in cli.filter.iter().filter(|f| !f.is_depth_filter()) {
        let core_filter = f.to_core(cli);
        pipeline = pipeline.push(FilterStep::new(core_filter, cli.strength));
    }
    pipeline
        .apply(img)
        .map_err(|e| RunError::Pipeline(format!("sensus: {e}")))
}

fn run_pipe(args: &Cli) -> Result<(), RunError> {
    use std::io::{Read, Write};
    let stdin = std::io::stdin();
    let stdout = std::io::stdout();
    let mut reader = stdin.lock();
    let mut writer = stdout.lock();

    let mut buf = Vec::new();
    reader.read_to_end(&mut buf)?;

    // FFD8 から FFD9 までを 1 フレームとして切り出す
    let frames = split_jpeg_frames(&buf);
    for frame_data in frames {
        let img = image::load_from_memory(frame_data).map_err(|source| RunError::InputOpen {
            path: std::path::PathBuf::from("<stdin>"),
            source,
        })?;
        let out = apply_filters_to_image(img, args)?;
        // JPEG エンコードして stdout に書く
        let mut jpeg_buf = Vec::new();
        out.write_to(
            &mut std::io::Cursor::new(&mut jpeg_buf),
            image::ImageFormat::Jpeg,
        )
        .map_err(|source| RunError::OutputSave {
            path: std::path::PathBuf::from("<stdout>"),
            source,
        })?;
        writer.write_all(&jpeg_buf)?;
    }
    Ok(())
}

fn split_jpeg_frames(data: &[u8]) -> Vec<&[u8]> {
    let mut frames = Vec::new();
    let mut i = 0;
    while i + 1 < data.len() {
        // フレーム開始: SOI (FFD8)
        if data[i] != 0xFF || data[i + 1] != 0xD8 {
            i += 1;
            continue;
        }
        let frame_start = i;
        i += 2; // SOI を消費
                // マーカーを走査して EOI (FFD9) を探す
        'frame: loop {
            // 0xFF を探す
            while i < data.len() && data[i] != 0xFF {
                i += 1;
            }
            if i + 1 >= data.len() {
                break 'frame;
            }
            let marker = data[i + 1];
            match marker {
                0xD9 => {
                    // EOI: フレーム終端
                    frames.push(&data[frame_start..=i + 1]);
                    i += 2;
                    break 'frame;
                }
                0xD8 => {
                    // 別の SOI は不正(スキップ)
                    i += 2;
                }
                0x00 | 0xFF => {
                    // スタッフドバイト or padding、スキップ
                    i += 1;
                }
                0xD0..=0xD7 | 0x01 => {
                    // RST0-7, TEM: length フィールドなし
                    i += 2;
                }
                _ => {
                    // 通常マーカー: 2バイト length フィールドあり
                    if i + 3 >= data.len() {
                        break 'frame;
                    }
                    let len = u16::from_be_bytes([data[i + 2], data[i + 3]]) as usize;
                    i += 2 + len; // マーカー2バイト + length (length 自身の2バイトを含む)
                }
            }
        }
    }
    frames
}