ot-tools-io 0.7.0

A library crate for reading/writing binary data files used by the Elektron Octatrack DPS-1.
Documentation
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
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
/*
SPDX-License-Identifier: GPL-3.0-or-later
Copyright © 2024 Mike Robeson [dijksterhuis]
*/

//! Types and parsing of the attributes data for a project's sample slots.
//! Used in the [`crate::projects::ProjectFile`] type.
//!
//! NOTE: Sample slot attributes here refer to the non-'playback markers' data.
//! See [crate::markers::MarkersFile] for information on trim/loop/slice
//! settings for a project's sample slot.

/*
Example data:
[SAMPLE]\r\nTYPE=FLEX\r\nSLOT=001\r\nPATH=../AUDIO/flex.wav\r\nTRIM_BARSx100=173\r\nTSMODE=2\r\nLOOPMODE=1\r\nGAIN=48\r\nTRIGQUANTIZATION=-1\r\n[/SAMPLE]
-----

[SAMPLE]
TYPE=FLEX
SLOT=001
PATH=../AUDIO/flex.wav
TRIM_BARSx100=173
TSMODE=2
LOOPMODE=1
GAIN=48
TRIGQUANTIZATION=-1
[/SAMPLE]
*/
use crate::projects::parse_hashmap_string_value;
use crate::projects::ProjectParseError;
use crate::settings::SlotType;

use crate::settings::{InvalidValueError, LoopMode, TimeStretchMode, TrigQuantizationMode};

use itertools::Itertools;
use ot_tools_io_derive::{AsMutDerive, AsRefDerive, IsDefaultCheck};
use serde::de::{self, Deserializer, MapAccess, Visitor};
use serde::{Deserialize, Serialize};
use serde_big_array::Array;
use std::{collections::HashMap, fmt, path::PathBuf, str::FromStr};

use thiserror::Error;

#[cfg(test)]
mod test_utils {
    use crate::projects::slots::ProjectSlotsError;
    use crate::projects::slots::SlotAttributes;
    use crate::settings::LoopMode;
    use crate::settings::SlotType;
    use crate::settings::TimeStretchMode;
    use crate::settings::TrigQuantizationMode;
    use std::path::PathBuf;
    pub(crate) fn new_slot_attr_full_args() -> Result<SlotAttributes, ProjectSlotsError> {
        SlotAttributes::new(
            SlotType::Static,
            100,
            Some(PathBuf::from("../AUDIO/location.wav")),
            Some(TimeStretchMode::default()),
            Some(LoopMode::default()),
            Some(TrigQuantizationMode::default()),
            Some(48),
            Some(3360),
        )
    }
    pub(crate) fn new_slot_attr_minimal_args() -> Result<SlotAttributes, ProjectSlotsError> {
        SlotAttributes::new(SlotType::Static, 100, None, None, None, None, None, None)
    }
}

#[allow(clippy::enum_variant_names)]
#[derive(Debug, Error)]
pub enum ProjectSlotsError {
    #[error("invalid slot_id ({value}), must be in range 1 <= x <= 136")]
    SlotIdOutOfBounds { value: u8 },
    #[error("invalid tempo ({value}), must be in range 720 <= x <= 7200")]
    TempoOutOfBounds { value: u16 },
    #[error("invalid gain ({value}), must be in range 24 <= x <= 120")]
    GainOutOfBounds { value: u8 },
}

/// Default tempo for the new slots.
pub const DEFAULT_TEMPO: u16 = 2880;

/// Default gain for new slots.
pub const DEFAULT_GAIN: u8 = 48;

/// A sample slot's global playback settings -- trig quantization, bpm,
/// timestrech mode ... anything applied to the sample globally .
/// The Octatrack only stores data when an audio file has been assigned to a sample slot.
///
/// NOTE: On the naming for this -- the Octatrack manual specifically refers to
/// > SAVE SAMPLE SETTINGS will save the trim, slice and attribute settings in a
/// > separate file and link it to the sample currently being edited.
/// > -- page 87
///
/// So ... these are the Slot ATTRIBUTES which are saved to a settings file.
///
/// No `Default` trait as not possible to have a default `slot_id` value
///
/// No `Copy` trait as PathBuf used for `path` field
// todo: default
#[derive(
    Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize, AsMutDerive, AsRefDerive,
)]
pub struct SlotAttributes {
    /// Type of sample: STATIC or FLEX
    pub slot_type: SlotType,

    /// String ID Number of the slot the sample is assigned to e.g. 001, 002, 003...
    /// Maximum of 128 entries for STATIC sample slots, but can be up to 136 for flex
    /// slots as there are 8 recorders + 128 flex slots.
    pub slot_id: u8,

    /// Relative path to the file on the card from the project directory.
    ///
    /// Recording buffer flex slots by default have an empty path attribute,
    /// which basically means 'no path'. In idiomatic rust that's an option.
    pub path: Option<PathBuf>,

    /// Current `TimestrechModes` setting for the specific slot. Example: `TSMODE=2`
    /// See [TimeStretchMode].
    pub timestrech_mode: TimeStretchMode,

    /// Current `LoopMode` setting for the specific slot.
    /// See [LoopMode].
    pub loop_mode: LoopMode,

    /// Current `TrigQuantizationModes` setting for this specific slot.
    /// This is not used for recording buffer 'flex' tracks.
    /// See [TrigQuantizationMode].
    pub trig_quantization_mode: TrigQuantizationMode,

    /// Sample gain. 48 is default as per sample attributes file. maximum 96, minimum 0.
    pub gain: u8,

    /// BPM of the sample in this slot. The stored representation is the 'real' bpm (float to 2
    /// decimal places) multiplied by 24.
    /// Default value is 2880 (120 BPM).
    /// Max value is 7200 (300 BPM).
    /// Min value is 720 (30 BPM).
    pub bpm: u16,
}

#[allow(clippy::too_many_arguments)] // not my fault there's a bunch of inputs for this...
impl SlotAttributes {
    pub fn new(
        slot_type: SlotType,
        slot_id: u8,
        path: Option<PathBuf>,
        timestretch_mode: Option<TimeStretchMode>,
        loop_mode: Option<LoopMode>,
        trig_quantization_mode: Option<TrigQuantizationMode>,
        gain: Option<u8>,
        bpm: Option<u16>,
    ) -> Result<Self, ProjectSlotsError> {
        // cannot be zero, flex slots go up to 128 + 8 (136), static up to 128
        match slot_type {
            SlotType::Static => {
                if !(1..=128).contains(&slot_id) {
                    return Err(ProjectSlotsError::SlotIdOutOfBounds { value: slot_id });
                }
            }
            SlotType::Flex => {
                if !(1..=136).contains(&slot_id) {
                    return Err(ProjectSlotsError::SlotIdOutOfBounds { value: slot_id });
                }
            }
        }

        // human range multiplied by 24
        if let Some(tempo) = bpm {
            if !(720..=7200).contains(&tempo) {
                return Err(ProjectSlotsError::TempoOutOfBounds { value: tempo });
            }
        }

        // -24.0 to +24.0 with 0.2 step
        if let Some(amp) = gain {
            if !(24..=120).contains(&amp) {
                return Err(ProjectSlotsError::GainOutOfBounds { value: amp });
            }
        }

        Ok(Self {
            slot_type,
            slot_id,
            path,
            timestrech_mode: timestretch_mode.unwrap_or_default(),
            loop_mode: loop_mode.unwrap_or_default(),
            trig_quantization_mode: trig_quantization_mode.unwrap_or_default(),
            gain: gain.unwrap_or(DEFAULT_GAIN),
            bpm: bpm.unwrap_or(DEFAULT_TEMPO),
        })
    }
}

#[cfg(test)]
mod new_slot_attributes {
    use crate::projects::slots::test_utils;
    use crate::projects::slots::ProjectSlotsError;
    use crate::projects::slots::SlotAttributes;
    use crate::settings::SlotType;
    #[test]
    fn valid_all_args() -> Result<(), ProjectSlotsError> {
        test_utils::new_slot_attr_full_args()?;
        Ok(())
    }

    #[test]
    fn valid_no_args() -> Result<(), ProjectSlotsError> {
        test_utils::new_slot_attr_minimal_args()?;
        Ok(())
    }

    #[test]
    fn invalid_slot_id_too_low_static() -> Result<(), ProjectSlotsError> {
        let r = SlotAttributes::new(SlotType::Static, 0, None, None, None, None, None, None);
        assert!(r.is_err());
        Ok(())
    }

    #[test]
    fn invalid_slot_id_too_high_static() -> Result<(), ProjectSlotsError> {
        let r = SlotAttributes::new(SlotType::Static, 129, None, None, None, None, None, None);
        assert!(r.is_err());
        Ok(())
    }

    #[test]
    fn invalid_slot_id_too_high_flex() -> Result<(), ProjectSlotsError> {
        let r = SlotAttributes::new(SlotType::Flex, 137, None, None, None, None, None, None);
        assert!(r.is_err());
        Ok(())
    }

    #[test]
    fn invalid_gain_too_high() -> Result<(), ProjectSlotsError> {
        let r = SlotAttributes::new(
            SlotType::Static,
            100,
            None,
            None,
            None,
            None,
            Some(200),
            None,
        );
        assert!(r.is_err());
        Ok(())
    }

    #[test]
    fn invalid_gain_too_low() -> Result<(), ProjectSlotsError> {
        let r = SlotAttributes::new(SlotType::Static, 100, None, None, None, None, Some(1), None);
        assert!(r.is_err());
        Ok(())
    }

    #[test]
    fn invalid_tempo_too_high() -> Result<(), ProjectSlotsError> {
        let r = SlotAttributes::new(
            SlotType::Static,
            100,
            None,
            None,
            None,
            None,
            None,
            Some(8000),
        );
        assert!(r.is_err());
        Ok(())
    }

    #[test]
    fn invalid_tempo_too_low() -> Result<(), ProjectSlotsError> {
        let r = SlotAttributes::new(
            SlotType::Static,
            100,
            None,
            None,
            None,
            None,
            None,
            Some(20),
        );
        assert!(r.is_err());
        Ok(())
    }
}

fn parse_id(hmap: &HashMap<String, String>) -> Result<u8, ProjectParseError> {
    let x = parse_hashmap_string_value::<u8>(hmap, "slot", None)?;
    Ok(x)
}

fn parse_loop_mode(hmap: &HashMap<String, String>) -> Result<LoopMode, InvalidValueError> {
    let default = LoopMode::default() as u8;
    let default_str = format!["{default}"];

    let x = parse_hashmap_string_value::<u8>(hmap, "loopmode", Some(default_str.as_str()))
        .unwrap_or(default);
    LoopMode::try_from(&x)
}

fn parse_tstrech_mode(
    hmap: &HashMap<String, String>,
) -> Result<TimeStretchMode, InvalidValueError> {
    let default = TimeStretchMode::default() as u8;
    let default_str = format!["{default}"];

    let x = parse_hashmap_string_value::<u8>(hmap, "tsmode", Some(default_str.as_str()))
        .unwrap_or(default);
    TimeStretchMode::try_from(&x)
}

fn parse_trig_quantize_mode(
    hmap: &HashMap<String, String>,
) -> Result<TrigQuantizationMode, InvalidValueError> {
    let default = TrigQuantizationMode::default() as u8;
    let default_str = format!["{default}"];
    let x = parse_hashmap_string_value::<u8>(hmap, "trigquantization", Some(default_str.as_str()))
        .unwrap_or(default);
    TrigQuantizationMode::try_from(x)
}

fn parse_gain(hmap: &HashMap<String, String>) -> Result<u8, ProjectParseError> {
    // note: default slot gain is 48, except for recording buffers which are 72.
    // see:
    // - `flex_slot_default_case_switch`
    // - `test-data/blank-project/project.work`
    let x =
        parse_hashmap_string_value::<u8>(hmap, "gain", Some(format!["{DEFAULT_GAIN}"].as_str()))
            .unwrap_or(DEFAULT_GAIN);
    Ok(x)
}

fn parse_tempo(hmap: &HashMap<String, String>) -> Result<u16, ProjectParseError> {
    let x = parse_hashmap_string_value::<u16>(
        hmap,
        "bpmx24",
        Some(format!["{DEFAULT_TEMPO}"].as_str()),
    )
    .unwrap_or(DEFAULT_TEMPO);
    Ok(x)
}

fn parse_path(hmap: &HashMap<String, String>) -> Result<PathBuf, ProjectParseError> {
    let path_str = hmap.get("path").ok_or(ProjectParseError::HashMap)?;
    let path = PathBuf::from_str(path_str).map_err(|_| ProjectParseError::String)?;
    Ok(path)
}

impl TryFrom<&HashMap<String, String>> for SlotAttributes {
    type Error = ProjectParseError;
    fn try_from(value: &HashMap<String, String>) -> Result<Self, Self::Error> {
        let slot_id = parse_id(value)?;

        let sample_slot_type = value
            .get("type")
            .ok_or(ProjectParseError::HashMap)?
            .to_string();
        let slot_type = SlotType::try_from(sample_slot_type)?;

        let path = parse_path(value)?;

        let loop_mode = parse_loop_mode(value)?;
        let timestrech_mode = parse_tstrech_mode(value)?;
        let trig_quantization_mode = parse_trig_quantize_mode(value)?;
        let gain = parse_gain(value)?;
        let bpm = parse_tempo(value)?;

        let sample_struct = Self {
            slot_type,
            slot_id,
            path: if path.as_os_str() != "" {
                Some(path)
            } else {
                None
            },
            timestrech_mode,
            loop_mode,
            trig_quantization_mode,
            gain,
            bpm,
        };

        Ok(sample_struct)
    }
}

impl FromStr for SlotAttributes {
    type Err = ProjectParseError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let k_v: Vec<Vec<&str>> = s
            .strip_prefix("\r\n\r\n[SAMPLE]\r\n")
            .ok_or(ProjectParseError::HashMap)?
            .strip_suffix("\r\n")
            .ok_or(ProjectParseError::HashMap)?
            .split("\r\n")
            .map(|x: &str| x.split('=').collect_vec())
            .filter(|x: &Vec<&str>| x.len() == 2)
            .collect_vec();

        let mut hmap: HashMap<String, String> = HashMap::new();
        for key_value_pair in k_v {
            hmap.insert(
                key_value_pair[0].to_string().to_lowercase(),
                key_value_pair[1].to_string(),
            );
        }

        let sample_struct = SlotAttributes::try_from(&hmap)?;
        Ok(sample_struct)
    }
}

impl fmt::Display for SlotAttributes {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
        let mut s = "[SAMPLE]\r\n".to_string();
        s.push_str(&format!("TYPE={}", self.slot_type));
        s.push_str("\r\n");
        // NOTE: Slot ID data is always prefixed with leading zeros
        s.push_str(format!("SLOT={:0>3}", self.slot_id).as_str());
        s.push_str("\r\n");
        // NOTE: Handle recording buffers having empty paths
        if let Some(path) = &self.path {
            /*
            HACK: Remove escape characters from the path string.

            A path like `my\file.wav` ends up like `my\\\\[...loads more \ chars...]\\\file.wav`.
            The Octatrack will attempt to load the project and then a catastrophic error message pops up.
            Helpfully, it will have made changes to the `project.work` file already which means you
            have to manually fix it yourself.

            This looks like some recursive injection of escape characters during parsing of the PATH field.
            Basically ... don't use the `\` escape character in path names!
            */
            s.push_str(
                format!("PATH={path:#?}")
                    .replace('"', "") // should not have quotes on PATH fields
                    .replace("\\", "") // ^ need to remove escape chars (`\`)
                    .as_str(),
            );
        } else {
            s.push_str("PATH=");
        }
        s.push_str("\r\n");
        s.push_str(format!("BPMx24={}", self.bpm).as_str());
        s.push_str("\r\n");
        s.push_str(format!("TSMODE={}", self.timestrech_mode as u8).as_str());
        s.push_str("\r\n");
        s.push_str(format!("LOOPMODE={}", self.loop_mode as u8).as_str());
        s.push_str("\r\n");
        s.push_str(format!("GAIN={}", self.gain).as_str());
        s.push_str("\r\n");
        s.push_str(format!("TRIGQUANTIZATION={}", self.trig_quantization_mode as u8).as_str());
        s.push_str("\r\n[/SAMPLE]");
        write!(f, "{s:#}")
    }
}

#[cfg(test)]
mod test_slot_attr_display {
    use crate::projects::slots::test_utils;
    use crate::projects::slots::ProjectSlotsError;
    #[test]
    fn valid_full() -> Result<(), ProjectSlotsError> {
        test_utils::new_slot_attr_full_args()?.to_string();
        Ok(())
    }

    #[test]
    fn valid_minimal() -> Result<(), ProjectSlotsError> {
        test_utils::new_slot_attr_minimal_args()?.to_string();
        Ok(())
    }
}

// YAML/JSON Deserialization for Sample Slot
// we can get away with just defining map deserialization for YAML/JSON.
// `ToString`/`FromStr` implementations are currently used for the actual data file.
impl<'de> Deserialize<'de> for SlotAttributes {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        enum Field {
            SlotType,
            SlotId,
            Path,
            Timestretch,
            Loop,
            Quant,
            Gain,
            Bpm,
        }

        // TODO: FIELDS_MAP: Tuple array
        const FIELDS: &[&str] = &[
            "slot_type",
            "slot_id",
            "path",
            "timestrech_mode",
            "loop_mode",
            "trig_quantization_mode",
            "gain",
            "bpm",
        ];

        impl<'de> Deserialize<'de> for Field {
            fn deserialize<D>(deserializer: D) -> Result<Field, D::Error>
            where
                D: Deserializer<'de>,
            {
                struct FieldVisitor;

                impl Visitor<'_> for FieldVisitor {
                    type Value = Field;

                    fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
                        formatter.write_str(
                            FIELDS
                                .iter()
                                .map(|x| format!["`{x}`"])
                                .collect::<Vec<_>>()
                                .join(" or ")
                                .as_str(),
                        )
                    }

                    fn visit_str<E>(self, value: &str) -> Result<Field, E>
                    where
                        E: de::Error,
                    {
                        match value {
                            "slot_type" => Ok(Field::SlotType),
                            "slot_id" => Ok(Field::SlotId),
                            "path" => Ok(Field::Path),
                            "timestrech_mode" => Ok(Field::Timestretch),
                            "loop_mode" => Ok(Field::Loop),
                            "trig_quantization_mode" => Ok(Field::Quant),
                            "gain" => Ok(Field::Gain),
                            "bpm" => Ok(Field::Bpm),
                            _ => Err(de::Error::unknown_field(value, FIELDS)),
                        }
                    }
                }

                deserializer.deserialize_identifier(FieldVisitor)
            }
        }

        struct SlotAttributesVisitor;

        impl<'de> Visitor<'de> for SlotAttributesVisitor {
            type Value = SlotAttributes;

            fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
                formatter.write_str("struct SlotAttributes")
            }

            fn visit_map<V>(self, mut map: V) -> Result<SlotAttributes, V::Error>
            where
                V: MapAccess<'de>,
            {
                let mut slot_type = None;
                let mut slot_id = None;
                let mut path = None;
                let mut timestretch_mode = None;
                let mut loop_mode = None;
                let mut trig_quantization_mode = None;
                let mut gain = None;
                let mut bpm = None;

                while let Some(key) = map.next_key()? {
                    match key {
                        Field::SlotType => {
                            if slot_type.is_some() {
                                return Err(de::Error::duplicate_field("slot_type"));
                            }
                            slot_type = Some(map.next_value::<SlotType>()?);
                        }
                        Field::SlotId => {
                            if slot_id.is_some() {
                                return Err(de::Error::duplicate_field("slot_id"));
                            }
                            slot_id = Some(map.next_value::<u8>()?);
                        }
                        Field::Path => {
                            if path.is_some() {
                                return Err(de::Error::duplicate_field("path"));
                            }
                            path = Some(map.next_value::<PathBuf>()?);
                        }
                        Field::Timestretch => {
                            if timestretch_mode.is_some() {
                                return Err(de::Error::duplicate_field("timestretch_mode"));
                            }
                            timestretch_mode = Some(map.next_value::<TimeStretchMode>()?);
                        }
                        Field::Loop => {
                            if loop_mode.is_some() {
                                return Err(de::Error::duplicate_field("loop_mode"));
                            }
                            loop_mode = Some(map.next_value::<LoopMode>()?);
                        }
                        Field::Quant => {
                            if trig_quantization_mode.is_some() {
                                return Err(de::Error::duplicate_field("trig_quantization_mode"));
                            }
                            trig_quantization_mode =
                                Some(map.next_value::<TrigQuantizationMode>()?);
                        }
                        Field::Gain => {
                            if gain.is_some() {
                                return Err(de::Error::duplicate_field("gain"));
                            }
                            gain = Some(map.next_value::<u8>()?);
                        }
                        Field::Bpm => {
                            if bpm.is_some() {
                                return Err(de::Error::duplicate_field("bpm"));
                            }
                            bpm = Some(map.next_value::<u16>()?);
                        }
                    }
                }

                let slot = SlotAttributes {
                    slot_type: slot_type.ok_or_else(|| de::Error::missing_field("slot_type"))?,
                    slot_id: slot_id.ok_or_else(|| de::Error::missing_field("slot_type"))?,
                    path, // allowed to be missing to handle recording buffer empty paths
                    timestrech_mode: timestretch_mode
                        .ok_or_else(|| de::Error::missing_field("trimstretch_mode"))?,
                    loop_mode: loop_mode.ok_or_else(|| de::Error::missing_field("loop_mode"))?,
                    trig_quantization_mode: trig_quantization_mode
                        .ok_or_else(|| de::Error::missing_field("trig_quantization_mode"))?,
                    gain: gain.ok_or_else(|| de::Error::missing_field("gain"))?,
                    bpm: bpm.ok_or_else(|| de::Error::missing_field("bpm"))?,
                };

                Ok(slot)
            }
        }

        deserializer.deserialize_struct("SampleSlot", FIELDS, SlotAttributesVisitor)
    }
}

/// Container type for all sample slots.
///
/// The `project.*` data files store all sample slots together in a single 1-indexed array.
/// This tends to lead to a lot of additional yak-shaving when interacting with sample slots.
/// So this type models the octatrack's UI, displaying slots in 2x arrays: Flex and Static.
/// These individual arrays are 0-indexed (easier lookups within for loops etc), but the
/// slots themselves retain their 1-indexed slot IDs.
///
/// NOTE: This type only includes the ATTRIBUTE data for slots. Markers data is
/// stored separately in [crate::markers::MarkersFile].
///
/// NOTE: I'm aware of the dangerous naming here -- `SlotX` versus `SlotsX` ...
/// lean into the type system to stop you from using the wrong one! `SlotsX` is
/// a container, while `SlotX` is the single slot with it's data (naming things
/// is hard, okay).
///
/// To create a new [SlotsAttributes] instance, start with a mutable default
/// as it will generate the recording buffer flex slots for you!
/// ```rust
/// # use ot_tools_io::settings::SlotType;
/// # use ot_tools_io::projects::SlotsAttributes;
///
/// let mut slots = SlotsAttributes::default();
/// for i in (128..=135_usize) {
///    let s = slots.flex_slots[i].clone();
///    assert_eq!(s.unwrap().slot_type, SlotType::Flex)
/// }
/// ```
///
/// No `Copy` trait as this type uses the [`Array`] type (which does not implement `Copy`)
#[derive(
    Clone,
    Debug,
    Eq,
    Hash,
    Ord,
    PartialEq,
    PartialOrd,
    Serialize,
    AsMutDerive,
    AsRefDerive,
    IsDefaultCheck,
)]
pub struct SlotsAttributes {
    pub static_slots: Array<Option<SlotAttributes>, 128>,
    pub flex_slots: Array<Option<SlotAttributes>, 136>,
}

// YAML/JSON Deserialization for Sample Slots
// we can get away with just defining map deserialization for YAML/JSON.
// `ToString`/`FromStr` implementations are currently used for the actual data file.
impl<'de> Deserialize<'de> for SlotsAttributes {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        enum Field {
            Static,
            Flex,
        }

        impl<'de> Deserialize<'de> for Field {
            fn deserialize<D>(deserializer: D) -> Result<Field, D::Error>
            where
                D: Deserializer<'de>,
            {
                struct FieldVisitor;

                impl Visitor<'_> for FieldVisitor {
                    type Value = Field;

                    fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
                        formatter.write_str("`static_slots` or `flex_slots`")
                    }

                    fn visit_str<E>(self, value: &str) -> Result<Field, E>
                    where
                        E: de::Error,
                    {
                        match value {
                            "static_slots" => Ok(Field::Static),
                            "flex_slots" => Ok(Field::Flex),
                            _ => Err(de::Error::unknown_field(value, FIELDS)),
                        }
                    }
                }

                deserializer.deserialize_identifier(FieldVisitor)
            }
        }

        struct SampleSlotsVisitor;

        impl<'de> Visitor<'de> for SampleSlotsVisitor {
            type Value = SlotsAttributes;

            fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
                formatter.write_str("struct SampleSlots")
            }

            fn visit_unit<E>(self) -> Result<SlotsAttributes, E> {
                Ok(SlotsAttributes::default())
            }
            fn visit_map<V>(self, mut map: V) -> Result<SlotsAttributes, V::Error>
            where
                V: MapAccess<'de>,
            {
                let mut static_slots = None;
                let mut flex_slots = None;
                while let Some(key) = map.next_key()? {
                    match key {
                        Field::Static => {
                            if static_slots.is_some() {
                                return Err(de::Error::duplicate_field("static_slots"));
                            }
                            static_slots =
                                Some(map.next_value::<Array<Option<SlotAttributes>, 128>>()?);
                        }
                        Field::Flex => {
                            if flex_slots.is_some() {
                                return Err(de::Error::duplicate_field("flex_slots"));
                            }
                            flex_slots =
                                Some(map.next_value::<Array<Option<SlotAttributes>, 136>>()?);
                        }
                    }
                }
                let s_slots =
                    static_slots.ok_or_else(|| de::Error::missing_field("static_slots"))?;

                let f_slots = flex_slots.ok_or_else(|| de::Error::missing_field("flex_slots"))?;

                let slots = SlotsAttributes {
                    static_slots: s_slots,
                    flex_slots: f_slots,
                };

                Ok(slots)
            }
        }

        const FIELDS: &[&str] = &["static_slots", "flex_slots"];
        deserializer.deserialize_struct("SampleSlots", FIELDS, SampleSlotsVisitor)
    }
}

/// Helper function to create default recorder flex slots, no public
fn flex_slot_default_case_switch(i: usize) -> Option<SlotAttributes> {
    if i <= 127 {
        None
    } else {
        Some(SlotAttributes {
            slot_type: SlotType::Flex,
            // WARN: i is a 0-indexed iterable, slot IDs need to be 1-indexed!
            slot_id: i as u8 + 1,
            path: None,
            timestrech_mode: TimeStretchMode::default(),
            loop_mode: LoopMode::default(),
            trig_quantization_mode: TrigQuantizationMode::default(),
            gain: 72, // recording buffers are set to +12.0 dB, other slots are created with 0.0dB
            bpm: DEFAULT_TEMPO,
        })
    }
}

impl Default for SlotsAttributes {
    fn default() -> Self {
        Self {
            static_slots: Array(std::array::from_fn(|_| None)),
            flex_slots: Array(std::array::from_fn(flex_slot_default_case_switch)),
        }
    }
}

impl FromStr for SlotsAttributes {
    type Err = ProjectParseError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let footer_stripped = s
            .strip_suffix("\r\n\r\n############################\r\n\r\n")
            .ok_or(ProjectParseError::Footer)?;

        let data_window: Vec<&str> = footer_stripped
            .split("############################\r\n# Samples\r\n############################")
            .collect();

        let mut samples_string: Vec<&str> = data_window[1].split("[/SAMPLE]").collect();
        // last one is always a blank string.
        samples_string.pop();

        // mutate from default as we always need recording buffers populated
        let mut slots = Self::default();

        for s in &samples_string {
            // need zero indexing to insert slots into arrays
            let slot = SlotAttributes::from_str(s)?;
            let zero_indexed_id = slot.slot_id as usize - 1;
            match slot.slot_type {
                SlotType::Static => {
                    slots.static_slots[zero_indexed_id] = Some(slot);
                }
                SlotType::Flex => {
                    slots.flex_slots[zero_indexed_id] = Some(slot);
                }
            }
        }

        Ok(slots)
    }
}

impl fmt::Display for SlotsAttributes {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
        let mut string_slots: String = "".to_string();

        let slots = vec![self.static_slots.to_vec(), self.flex_slots.to_vec()];

        let slots_concat = itertools::concat(slots).into_iter().flatten();

        for slot in slots_concat {
            string_slots.push_str(&slot.to_string());
            string_slots.push_str("\r\n\r\n");
        }
        string_slots = string_slots
            .strip_suffix("\r\n\r\n")
            .ok_or(fmt::Error)?
            .to_string();
        write!(f, "{string_slots:#}")
    }
}

#[cfg(test)]
#[allow(unused_imports)]
mod test {

    #[test]
    fn parse_id_001_correct() {
        let mut hmap = std::collections::HashMap::new();
        hmap.insert("slot".to_string(), "001".to_string());

        let slot_id = crate::projects::slots::parse_id(&hmap);

        assert_eq!(1, slot_id.unwrap());
    }

    #[test]
    fn parse_id_1_correct() {
        let mut hmap = std::collections::HashMap::new();
        hmap.insert("slot".to_string(), "1".to_string());

        let slot_id = crate::projects::slots::parse_id(&hmap);

        assert_eq!(1, slot_id.unwrap());
    }

    #[test]
    fn parse_id_127_correct() {
        let mut hmap = std::collections::HashMap::new();
        hmap.insert("slot".to_string(), "127".to_string());

        let slot_id = crate::projects::slots::parse_id(&hmap);

        assert_eq!(127, slot_id.unwrap());
    }

    #[test]
    fn parse_id_099_correct() {
        let mut hmap = std::collections::HashMap::new();
        hmap.insert("slot".to_string(), "099".to_string());

        let slot_id = crate::projects::slots::parse_id(&hmap);

        assert_eq!(99, slot_id.unwrap());
    }

    #[test]
    fn parse_id_010_correct() {
        let mut hmap = std::collections::HashMap::new();
        hmap.insert("slot".to_string(), "010".to_string());

        let slot_id = crate::projects::slots::parse_id(&hmap);

        assert_eq!(10, slot_id.unwrap());
    }

    #[test]
    fn test_parse_id_err_bad_value_type_err() {
        let mut hmap = std::collections::HashMap::new();
        hmap.insert("slot".to_string(), "AAAA".to_string());
        let slot_id = crate::projects::slots::parse_id(&hmap);
        assert!(slot_id.is_err());
    }

    #[test]
    fn test_parse_tempo_correct_default() {
        let mut hmap = std::collections::HashMap::new();
        hmap.insert("bpmx24".to_string(), "2880".to_string());
        let r = crate::projects::slots::parse_tempo(&hmap);
        assert_eq!(2880_u16, r.unwrap());
    }

    #[test]
    fn test_parse_tempo_correct_min() {
        let mut hmap = std::collections::HashMap::new();
        hmap.insert("bpmx24".to_string(), "720".to_string());
        let r = crate::projects::slots::parse_tempo(&hmap);
        assert_eq!(720_u16, r.unwrap());
    }

    #[test]
    fn test_parse_tempo_correct_max() {
        let mut hmap = std::collections::HashMap::new();
        hmap.insert("bpmx24".to_string(), "7200".to_string());
        let r = crate::projects::slots::parse_tempo(&hmap);
        assert_eq!(7200_u16, r.unwrap());
    }

    #[test]
    fn test_parse_tempo_bad_value_type_default_return() {
        let mut hmap = std::collections::HashMap::new();
        hmap.insert("bpmx24".to_string(), "AAAFSFSFSSFfssafAA".to_string());
        let r = crate::projects::slots::parse_tempo(&hmap);
        assert_eq!(r.unwrap(), 2880_u16);
    }

    #[test]
    fn test_parse_gain_correct() {
        let mut hmap = std::collections::HashMap::new();
        hmap.insert("gain".to_string(), "72".to_string());
        let r = crate::projects::slots::parse_gain(&hmap);
        assert_eq!(72, r.unwrap());
    }

    #[test]
    fn test_parse_gain_bad_value_type_default_return() {
        let mut hmap = std::collections::HashMap::new();
        hmap.insert("gain".to_string(), "AAAFSFSFSSFfssafAA".to_string());
        let r = crate::projects::slots::parse_gain(&hmap);
        assert_eq!(r.unwrap(), super::DEFAULT_GAIN); // note: recording slots have a different default value
    }

    #[test]
    fn test_parse_loop_mode_correct_off() {
        let mut hmap = std::collections::HashMap::new();
        hmap.insert("loopmode".to_string(), "0".to_string());
        let r = crate::projects::slots::parse_loop_mode(&hmap);
        assert_eq!(r.unwrap(), crate::settings::LoopMode::Off);
    }

    #[test]
    fn test_parse_loop_mode_correct_normal() {
        let mut hmap = std::collections::HashMap::new();
        hmap.insert("loopmode".to_string(), "1".to_string());
        let r = crate::projects::slots::parse_loop_mode(&hmap);
        assert_eq!(r.unwrap(), crate::settings::LoopMode::Normal);
    }

    #[test]
    fn test_parse_loop_mode_correct_pingpong() {
        let mut hmap = std::collections::HashMap::new();
        hmap.insert("loopmode".to_string(), "2".to_string());
        let r = crate::projects::slots::parse_loop_mode(&hmap);
        assert_eq!(r.unwrap(), crate::settings::LoopMode::PingPong);
    }

    #[test]
    fn test_parse_loop_mode_bad_value_type_default_return() {
        let mut hmap = std::collections::HashMap::new();
        hmap.insert("loopmode".to_string(), "AAAFSFSFSSFfssafAA".to_string());
        let r = crate::projects::slots::parse_loop_mode(&hmap);
        assert_eq!(r.unwrap(), crate::settings::LoopMode::default());
    }

    #[test]
    fn test_parse_tstretch_correct_off() {
        let mut hmap = std::collections::HashMap::new();
        hmap.insert("tsmode".to_string(), "0".to_string());
        let r = crate::projects::slots::parse_tstrech_mode(&hmap);
        assert_eq!(crate::settings::TimeStretchMode::Off, r.unwrap());
    }

    #[test]
    fn test_parse_tstretch_correct_normal() {
        let mut hmap = std::collections::HashMap::new();
        hmap.insert("tsmode".to_string(), "2".to_string());
        let r = crate::projects::slots::parse_tstrech_mode(&hmap);
        assert_eq!(crate::settings::TimeStretchMode::Normal, r.unwrap());
    }

    #[test]
    fn test_parse_tstretch_correct_beat() {
        let mut hmap = std::collections::HashMap::new();
        hmap.insert("tsmode".to_string(), "3".to_string());
        let r = crate::projects::slots::parse_tstrech_mode(&hmap);
        assert_eq!(crate::settings::TimeStretchMode::Beat, r.unwrap());
    }

    #[test]
    fn test_parse_tstretch_bad_value_type_default_return() {
        let mut hmap = std::collections::HashMap::new();
        hmap.insert("tsmode".to_string(), "AAAFSFSFSSFfssafAA".to_string());
        let r = crate::projects::slots::parse_tstrech_mode(&hmap);
        assert_eq!(r.unwrap(), crate::settings::TimeStretchMode::default());
    }

    #[test]
    fn test_parse_tquantize_correct_off() {
        let mut hmap = std::collections::HashMap::new();
        hmap.insert("trigquantization".to_string(), "255".to_string());
        let r = crate::projects::slots::parse_trig_quantize_mode(&hmap);
        assert_eq!(crate::settings::TrigQuantizationMode::Direct, r.unwrap());
    }

    #[test]
    fn test_parse_tquantize_correct_direct() {
        let mut hmap = std::collections::HashMap::new();
        hmap.insert("trigquantization".to_string(), "0".to_string());
        let r = crate::projects::slots::parse_trig_quantize_mode(&hmap);
        assert_eq!(
            crate::settings::TrigQuantizationMode::PatternLength,
            r.unwrap()
        );
    }

    #[test]
    fn test_parse_tquantize_correct_onestep() {
        let mut hmap = std::collections::HashMap::new();
        hmap.insert("trigquantization".to_string(), "1".to_string());
        let r = crate::projects::slots::parse_trig_quantize_mode(&hmap);
        assert_eq!(crate::settings::TrigQuantizationMode::OneStep, r.unwrap());
    }

    #[test]
    fn test_parse_tquantize_correct_twostep() {
        let mut hmap = std::collections::HashMap::new();
        hmap.insert("trigquantization".to_string(), "2".to_string());
        let r = crate::projects::slots::parse_trig_quantize_mode(&hmap);
        assert_eq!(crate::settings::TrigQuantizationMode::TwoSteps, r.unwrap());
    }

    #[test]
    fn test_parse_tquantize_correct_threestep() {
        let mut hmap = std::collections::HashMap::new();
        hmap.insert("trigquantization".to_string(), "3".to_string());
        let r = crate::projects::slots::parse_trig_quantize_mode(&hmap);
        assert_eq!(
            crate::settings::TrigQuantizationMode::ThreeSteps,
            r.unwrap()
        );
    }

    #[test]
    fn test_parse_tquantize_correct_fourstep() {
        let mut hmap = std::collections::HashMap::new();
        hmap.insert("trigquantization".to_string(), "4".to_string());
        let r = crate::projects::slots::parse_trig_quantize_mode(&hmap);
        assert_eq!(crate::settings::TrigQuantizationMode::FourSteps, r.unwrap());
    }

    // i'm not going to test every single option. we do that already elsewhere.

    #[test]
    fn test_parse_tquantize_bad_value_type_default_return() {
        let mut hmap = std::collections::HashMap::new();
        hmap.insert(
            "trigquantization".to_string(),
            "AAAFSFSFSSFfssafAA".to_string(),
        );
        let r = crate::projects::slots::parse_trig_quantize_mode(&hmap);
        assert_eq!(r.unwrap(), crate::settings::TrigQuantizationMode::default());
    }

    use std::path::PathBuf;
    #[test]
    fn test_parse_path_good_utf8_value() {
        let test_path = "../AUDIO/some/file.wav";

        let mut hmap = std::collections::HashMap::new();
        hmap.insert("path".to_string(), test_path.to_string());
        let r = crate::projects::slots::parse_path(&hmap);
        assert_eq!(r.unwrap(), PathBuf::from(test_path));
    }

    #[test]
    fn test_parse_empty_path() {
        let test_path = "";

        let mut hmap = std::collections::HashMap::new();
        hmap.insert("path".to_string(), test_path.to_string());
        let r = crate::projects::slots::parse_path(&hmap);
        assert_eq!(r.unwrap(), PathBuf::from(test_path));
    }

    #[test]
    fn test_parse_non_utf8_path() {
        let test_path = "../AUDIO/🇯🇲something.wav";

        let mut hmap = std::collections::HashMap::new();
        hmap.insert("path".to_string(), test_path.to_string());
        let r = crate::projects::slots::parse_path(&hmap);
        assert_eq!(r.unwrap(), PathBuf::from(test_path));
    }
}