ot-tools-io 0.6.1

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
/*
SPDX-License-Identifier: GPL-3.0-or-later
Copyright © 2024 Mike Robeson [dijksterhuis]
*/

//! Types and ser/de of `*.ot` binary data files.

use crate::markers::SlotMarkers;
use crate::projects::SlotAttributes;
use crate::settings::{LoopMode, TimeStretchMode, TrigQuantizationMode};
use crate::slices::{Slice, Slices};
use crate::traits::SwapBytes;
use crate::{
    HasChecksumField, HasFileVersionField, HasHeaderField, OctatrackFileIO, OtToolsIoError,
};
use ot_tools_io_derive::IntegrityChecks;
use serde::{Deserialize, Serialize};
use serde_big_array::BigArray;
use thiserror::Error;

#[cfg(test)]
mod test_utils {
    use super::{
        LoopConfig, LoopMode, SampleSettingsError, SampleSettingsFile, Slice, Slices,
        TimeStretchMode, TrigQuantizationMode, TrimConfig, DEFAULT_GAIN, DEFAULT_TEMPO,
        SAMPLES_FILE_VERSION, SAMPLES_HEADER,
    };

    pub(crate) fn create_mock_new(
        tempo: Option<u32>,
        gain: Option<u16>,
    ) -> Result<SampleSettingsFile, SampleSettingsError> {
        let trim_config = TrimConfig {
            start: 0,
            end: 0,
            length: 0,
        };

        let loop_config = LoopConfig {
            start: 0,
            length: 0,
            mode: LoopMode::default(),
        };

        let default_slice = Slice {
            trim_start: 0,
            trim_end: 0,
            loop_start: 0xFFFFFFFF,
        };

        let slices: [Slice; 64] = [default_slice; 64];

        let slice_conf = Slices { slices, count: 0 };

        SampleSettingsFile::new(
            &tempo.unwrap_or(DEFAULT_TEMPO),
            &TimeStretchMode::Off,
            &TrigQuantizationMode::PatternLength,
            &gain.unwrap_or(DEFAULT_GAIN),
            &trim_config,
            &loop_config,
            &slice_conf,
        )
    }

    pub(crate) fn mock_0_slice() -> SampleSettingsFile {
        SampleSettingsFile {
            header: SAMPLES_HEADER,
            datatype_version: SAMPLES_FILE_VERSION,
            unknown: 1,
            tempo: 2281,
            trim_len: 800,
            loop_len: 800,
            stretch: 2,
            loop_mode: 0,
            gain: 48,
            quantization: 255,
            trim_start: 0,
            trim_end: 890839,
            loop_start: 0,
            slices: Slices::default().slices,
            slices_len: 0,
            checksum: 998,
        }
    }
}

#[derive(Debug, Error)]
pub enum SampleSettingsError {
    #[error("invalid gain, must be u16 in range 0 <= x <= 96: {value}")]
    GainOutOfBounds { value: u32 },
    #[error("invalid tempo value, must be u32 in range 720 <= x <= 7200: {value}")]
    TempoOutOfBounds { value: u32 },
}

// in `hexdump -C` format:
// ```
// FORM....DPS1SMPA
// ......
// ```
/// Standard header bytes in a sample settings file
pub const SAMPLES_HEADER: [u8; 21] = [
    0x46, 0x4F, 0x52, 0x4D, 0x00, 0x00, 0x00, 0x00, 0x44, 0x50, 0x53, 0x31, 0x53, 0x4D, 0x50, 0x41,
    0x00, 0x00, 0x00, 0x00, 0x00,
];

/// Current/supported datatype version for a sample settings file
pub const SAMPLES_FILE_VERSION: u8 = 2;

pub const DEFAULT_TEMPO: u32 = 2880;
pub const DEFAULT_GAIN: u16 = 48;

/// Struct to create a valid Octatrack `.ot` file a.k.a. a sample settings file.
/// General metadata for the sample's configuration on the OT
/// and the slice array with pointer positions for the sliced WAV.
///
/// 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 ... this is the SETTINGS file.
#[derive(Serialize, Deserialize, PartialEq, Debug, Clone, Hash, IntegrityChecks)]
pub struct SampleSettingsFile {
    /// Header
    pub header: [u8; 21],

    /// Datatype's version ID//
    pub datatype_version: u8,

    /// Unknown data -- can sometimes be 1, usually 0.
    pub unknown: u8,

    /// Tempo is always the machine UI's BPM multiplied by 24
    pub tempo: u32,

    /// Number of bars for the sample trim length marker.
    /// By default, trim length should be equal to trim end,
    /// and probably loop length too for drum hit sample chains.
    pub trim_len: u32,

    /// Number of bars for the sample loop length marker.
    /// By default, loop length should be equal to trim length for sample chains.
    pub loop_len: u32,

    /// Default time-stretch algorithm applied to the sample.
    /// See the [`TimeStretchMode`] enum for suitable choices.
    pub stretch: u32,

    /// Default loop mode applied to the sample.
    /// See the [`LoopMode`] enum for suitable choices.
    pub loop_mode: u32,

    /// Gain of the sample.
    /// -24.0 db <= x <= +24 db range in the machine's UI, with increments of 0.5 db changes.
    /// 0 <= x <= 96 range in binary data file.
    pub gain: u16,

    /// Default trig quantization mode applied to the sample.
    /// See the [`TrigQuantizationMode`] enum for suitable choices.
    pub quantization: u8,

    /// Where the trim start marker is placed for the sample, measured in bars.
    /// Default is 0 (start of sample).
    pub trim_start: u32,

    /// Where the trim end marker is placed for the sample.
    /// When the sample is being played in normal mode (i.e. not using slices),
    /// the Octatrack will not play samples past this point.
    /// By default, trim length should be equal to trim end,
    /// and probably loop length too for drum hit sample chains.
    pub trim_end: u32,

    /// Start position for any loops. Default should be the same as trim start.
    /// Measured in bars.
    /// A note from the Octatrack manual on loop point/start behaviour:
    /// > If a loop point is set, the sample will play from the start point to the
    /// > end point, then loop from the loop point to the end point
    pub loop_start: u32,

    /// 64 length array containing `Slice`s.
    /// See the `Slice` struct for more details.
    /// Any empty slice positions should have zero-valued struct fields.
    #[serde(with = "BigArray")]
    pub slices: [Slice; 64],

    /// Number of usable `Slice`s in this sample.
    /// Used by the Octatrack to ignore zero-valued `Slice`s in the `slices` array when loading the sample.
    pub slices_len: u32,

    /// Checksum value for the struct.
    /// This must be calculated **after** the struct is created on little-endian systems
    /// (requires byte swapping all struct fields to get the correct checksum value).
    pub checksum: u16,
}

impl SampleSettingsFile {
    /// Create a new `SampleSettingsFile`
    ///
    /// Values like `tempo` and `gain` need to be normalized to relevant OT
    /// bounds before using this method.
    /// ```rust
    /// # use std::array::from_fn;
    /// # use ot_tools_io::samples::{SampleSettingsFile, TrimConfig, LoopConfig};
    /// # use ot_tools_io::settings::{
    /// #    TrigQuantizationMode,
    /// #    LoopMode,
    /// #    TimeStretchMode,
    /// # };
    /// # use ot_tools_io::slices::{Slices, Slice};
    /// # let slice_arr: [Slice; 64] = from_fn(|_| Slice::default());
    /// # let slices: Slices = Slices { slices: slice_arr, count: 0 };
    /// let x = SampleSettingsFile::new(
    ///     &2880,
    ///     // ...
    ///     # &TimeStretchMode::default(),
    ///     # &TrigQuantizationMode::default(),
    ///     &48,
    ///     // ...
    ///     # &TrimConfig { start: 0, end: 100, length: 25 },
    ///     # &LoopConfig { start: 0, length: 100, mode: LoopMode::Off },
    ///     # &slices,
    /// ).unwrap();
    /// assert_eq!(x.tempo, 2880);
    /// assert_eq!(x.gain, 48);
    /// ```
    pub fn new(
        tempo: &u32,
        stretch: &TimeStretchMode,
        quantization: &TrigQuantizationMode,
        gain: &u16,
        trim_config: &TrimConfig,
        loop_config: &LoopConfig,
        slices: &Slices,
    ) -> Result<Self, SampleSettingsError> {
        #[allow(clippy::manual_range_contains)]
        if tempo < &720 || tempo > &7200 {
            return Err(SampleSettingsError::TempoOutOfBounds { value: *tempo });
        }

        #[allow(clippy::manual_range_contains)]
        if gain < &0 || gain > &96 {
            return Err(SampleSettingsError::GainOutOfBounds {
                value: *gain as u32,
            });
        }

        Ok(Self {
            header: SAMPLES_HEADER,
            datatype_version: SAMPLES_FILE_VERSION,
            unknown: 0,
            gain: *gain,
            stretch: (*stretch).into(),
            tempo: *tempo,
            quantization: (*quantization).into(),
            trim_start: trim_config.start,
            trim_end: trim_config.end,
            trim_len: trim_config.length, // bin lengths are multiplied by 100?
            loop_start: loop_config.start,
            loop_len: loop_config.length, // bin lengths are multiplied by 100?
            loop_mode: loop_config.mode.into(),
            slices: slices.slices,
            slices_len: slices.count,
            checksum: 0,
        })
    }
}

#[cfg(test)]
mod new {
    use super::test_utils::create_mock_new;
    use crate::OtToolsIoError;
    #[test]
    fn invalid_oob_temp() -> Result<(), OtToolsIoError> {
        assert_eq!(
            create_mock_new(Some(7201), None).unwrap_err().to_string(),
            "invalid tempo value, must be u32 in range 720 <= x <= 7200: 7201".to_string(),
        );
        Ok(())
    }

    #[test]
    fn invalid_oob_gain() -> Result<(), OtToolsIoError> {
        assert_eq!(
            create_mock_new(None, Some(97)).unwrap_err().to_string(),
            "invalid gain, must be u16 in range 0 <= x <= 96: 97".to_string(),
        );
        Ok(())
    }
}

impl SwapBytes for SampleSettingsFile {
    fn swap_bytes(self) -> Self {
        let mut bswapped_slices: [Slice; 64] = self.slices;

        for (i, slice) in self.slices.iter().enumerate() {
            bswapped_slices[i] = slice.swap_bytes();
        }

        Self {
            header: SAMPLES_HEADER,
            datatype_version: SAMPLES_FILE_VERSION,
            unknown: self.unknown,
            tempo: self.tempo.swap_bytes(),
            trim_len: self.trim_len.swap_bytes(),
            loop_len: self.loop_len.swap_bytes(),
            stretch: self.stretch.swap_bytes(),
            loop_mode: self.loop_mode.swap_bytes(),
            gain: self.gain.swap_bytes(),
            quantization: self.quantization.swap_bytes(),
            trim_start: self.trim_start.swap_bytes(),
            trim_end: self.trim_end.swap_bytes(),
            loop_start: self.loop_start.swap_bytes(),
            slices: bswapped_slices,
            slices_len: self.slices_len.swap_bytes(),
            checksum: self.checksum.swap_bytes(),
        }
    }
}

impl OctatrackFileIO for SampleSettingsFile {
    /// Encodes struct data to binary representation, after some pre-processing.
    ///
    /// Before serializing, will:
    /// 1. modify tempo and gain values to machine ranges
    /// 2. swaps bytes of values (when current system is little-endian)
    /// 3. generate checksum value
    fn encode(&self) -> Result<Vec<u8>, OtToolsIoError> {
        let mut chkd = self.clone();
        chkd.checksum = self.calculate_checksum()?;

        let encoded = if cfg!(target_endian = "little") {
            bincode::serialize(&chkd.swap_bytes())?
        } else {
            bincode::serialize(&chkd)?
        };
        Ok(encoded)
    }

    /// Decode raw bytes of a `.ot` data file into a new struct,
    /// swap byte values if system is little-endian then do some minor
    /// post-processing to get user-friendly settings values.
    fn decode(bytes: &[u8]) -> Result<Self, OtToolsIoError> {
        let decoded: Self = bincode::deserialize(bytes)?;
        let mut bswapd = decoded.clone();

        // swapping bytes is one required when running on little-endian systems
        if cfg!(target_endian = "little") {
            bswapd = decoded.swap_bytes();
        }

        Ok(bswapd)
    }
}

#[cfg(test)]
mod decode {
    use crate::read_bin_file;
    use crate::samples::test_utils::mock_0_slice;
    use crate::test_utils::get_samples_dirpath;
    use crate::{OctatrackFileIO, OtToolsIoError, SampleSettingsFile};
    #[test]
    fn valid() -> Result<(), OtToolsIoError> {
        let path = get_samples_dirpath().join("checksum").join("0slices.ot");
        let bytes = read_bin_file(&path)?;
        let s = SampleSettingsFile::decode(&bytes)?;
        assert_eq!(s, mock_0_slice());
        Ok(())
    }
}

#[cfg(test)]
mod encode {
    use crate::read_bin_file;
    use crate::samples::test_utils::mock_0_slice;
    use crate::test_utils::get_samples_dirpath;
    use crate::{OctatrackFileIO, OtToolsIoError};
    #[test]
    fn valid() -> Result<(), OtToolsIoError> {
        let path = get_samples_dirpath().join("checksum").join("0slices.ot");
        let bytes = read_bin_file(&path)?;
        let b = mock_0_slice().encode()?;
        assert_eq!(b, bytes);
        Ok(())
    }
}

impl HasChecksumField for SampleSettingsFile {
    // tests for this are in the main tests directory -- `samples_settings_files.rs`
    fn calculate_checksum(&self) -> Result<u16, OtToolsIoError> {
        let bytes = bincode::serialize(&self)?;

        // skip header and checksum byte values
        let checksum_bytes = &bytes[16..bytes.len() - 2];

        let chk: u32 = checksum_bytes
            .iter()
            .map(|x| *x as u32)
            .sum::<u32>()
            .rem_euclid(u16::MAX as u32 + 1);

        Ok(chk as u16)
    }

    fn check_checksum(&self) -> Result<bool, OtToolsIoError> {
        Ok(self.checksum == self.calculate_checksum()?)
    }
}

#[cfg(test)]
mod checksum_field {
    use super::test_utils::create_mock_new;
    use crate::{HasChecksumField, OtToolsIoError};
    #[test]
    fn valid() -> Result<(), OtToolsIoError> {
        let mut x = create_mock_new(None, None)?;
        x.checksum = x.calculate_checksum()?;
        assert!(x.check_checksum()?);
        Ok(())
    }

    #[test]
    fn invalid() -> Result<(), OtToolsIoError> {
        let mut x = create_mock_new(None, None)?;
        x.checksum = x.calculate_checksum()?;
        x.checksum = 0;
        assert!(!x.check_checksum()?);
        Ok(())
    }

    mod files {
        use crate::test_utils::get_samples_dirpath;
        use crate::{HasChecksumField, OctatrackFileIO, OtToolsIoError, SampleSettingsFile};

        fn helper(test_name: String) -> Result<(u16, u16), OtToolsIoError> {
            let mut src_path = get_samples_dirpath().join("checksum").join(&test_name);
            src_path.set_extension("ot");

            let valid = SampleSettingsFile::from_data_file(&src_path)?;
            let mut x = valid.clone();
            x.checksum = 0;

            Ok((x.calculate_checksum()?, valid.checksum))
        }

        #[test]
        fn zero_slices_trig_quant_one_step() -> Result<(), OtToolsIoError> {
            let (test, valid) = helper("0slices-tq1step".to_string())?;
            assert_eq!(test, valid);
            Ok(())
        }

        #[test]
        fn zero_slices() -> Result<(), OtToolsIoError> {
            let (test, valid) = helper("0slices".to_string())?;
            assert_eq!(test, valid);
            Ok(())
        }

        #[test]
        fn one_slice() -> Result<(), OtToolsIoError> {
            let (test, valid) = helper("1slices".to_string())?;
            assert_eq!(test, valid);
            Ok(())
        }

        #[test]
        fn two_slices() -> Result<(), OtToolsIoError> {
            let (test, valid) = helper("2slices".to_string())?;
            assert_eq!(test, valid);
            Ok(())
        }

        #[test]
        fn four_slices() -> Result<(), OtToolsIoError> {
            let (test, valid) = helper("4slices".to_string())?;
            assert_eq!(test, valid);
            Ok(())
        }

        #[test]
        fn eight_slices() -> Result<(), OtToolsIoError> {
            let (test, valid) = helper("8slices".to_string())?;
            assert_eq!(test, valid);
            Ok(())
        }

        #[test]
        fn sixteen_slices() -> Result<(), OtToolsIoError> {
            let (test, valid) = helper("16slices".to_string())?;
            assert_eq!(test, valid);
            Ok(())
        }

        #[test]
        fn thirty_two_slices() -> Result<(), OtToolsIoError> {
            let (test, valid) = helper("32slices".to_string())?;
            assert_eq!(test, valid);
            Ok(())
        }

        #[test]
        fn forty_eight_slices() -> Result<(), OtToolsIoError> {
            let (test, valid) = helper("48slices".to_string())?;
            assert_eq!(test, valid);
            Ok(())
        }

        #[test]
        fn sixty_two_slices() -> Result<(), OtToolsIoError> {
            let (test, valid) = helper("62slices".to_string())?;
            assert_eq!(test, valid);
            Ok(())
        }

        #[test]
        fn sixty_three_slices() -> Result<(), OtToolsIoError> {
            let (test, valid) = helper("63slices".to_string())?;
            assert_eq!(test, valid);
            Ok(())
        }

        #[test]
        fn sixty_four_slices_correct() -> Result<(), OtToolsIoError> {
            let (test, valid) = helper("64slices".to_string())?;
            assert_eq!(test, valid);
            Ok(())
        }
    }
}

impl HasHeaderField for SampleSettingsFile {
    fn check_header(&self) -> Result<bool, OtToolsIoError> {
        Ok(self.header == SAMPLES_HEADER)
    }
}

#[cfg(test)]
mod header_field {
    use super::test_utils::create_mock_new;
    use crate::{HasHeaderField, OtToolsIoError};
    #[test]
    fn valid() -> Result<(), OtToolsIoError> {
        assert!(create_mock_new(None, None)?.check_header()?);
        Ok(())
    }

    #[test]
    fn invalid() -> Result<(), OtToolsIoError> {
        let mut mutated = create_mock_new(None, None)?;
        mutated.header[0] = 0x00;
        mutated.header[20] = 111;
        assert!(!mutated.check_header()?);
        Ok(())
    }
}

impl HasFileVersionField for SampleSettingsFile {
    fn check_file_version(&self) -> Result<bool, OtToolsIoError> {
        Ok(self.datatype_version == SAMPLES_FILE_VERSION)
    }
}

#[cfg(test)]
mod file_version_field {
    use super::test_utils::create_mock_new;
    use crate::{HasFileVersionField, OtToolsIoError};
    #[test]
    fn valid() -> Result<(), OtToolsIoError> {
        assert!(create_mock_new(None, None)?.check_file_version()?);
        Ok(())
    }

    #[test]
    fn invalid() -> Result<(), OtToolsIoError> {
        let mut mutated = create_mock_new(None, None)?;
        mutated.datatype_version = 0;
        assert!(!mutated.check_file_version()?);
        Ok(())
    }
}

/// Helper function to avoid infinite recursion for the `From<(&SlotAttributes, &SlotMarkers)>` trait
/// implementation for `SampleSettingsFile`
// this
pub(crate) fn from_slot_tuple(attrs: SlotAttributes, markers: SlotMarkers) -> SampleSettingsFile {
    SampleSettingsFile {
        header: SAMPLES_HEADER,
        datatype_version: SAMPLES_FILE_VERSION,
        unknown: 0,
        tempo: attrs.bpm as u32,
        // TODO: bar len -- markers.trim_end - markers.trim_offset
        trim_len: 0,
        // TODO: bar len -- markers.trim_end - markers.loop_point
        loop_len: 0,
        stretch: attrs.timestrech_mode.into(),
        loop_mode: attrs.loop_mode.into(),
        gain: attrs.gain as u16,
        quantization: attrs.trig_quantization_mode.into(),
        trim_start: markers.trim_offset,
        trim_end: markers.trim_end,
        loop_start: markers.loop_point,
        slices: markers.slices,
        slices_len: markers.slice_count,
        checksum: 0,
    }
}

impl From<(SlotAttributes, SlotMarkers)> for SampleSettingsFile {
    fn from(value: (SlotAttributes, SlotMarkers)) -> Self {
        let (attrs, markers) = value;
        from_slot_tuple(attrs, markers)
    }
}

impl From<(&SlotAttributes, &SlotMarkers)> for SampleSettingsFile {
    fn from(value: (&SlotAttributes, &SlotMarkers)) -> Self {
        let (attrs, markers) = value;
        from_slot_tuple(attrs.clone(), markers.clone())
    }
}

#[cfg(test)]
mod sample_settings_from {
    use crate::projects::SlotsAttributes;
    use crate::samples::from_slot_tuple;
    use crate::MarkersFile;
    use crate::OtToolsIoError;
    use crate::SampleSettingsFile;
    #[test]
    fn from_slot_tuple_valid() -> Result<(), OtToolsIoError> {
        let slots = SlotsAttributes::default();
        let slot = slots
            .flex_slots
            .iter()
            .find(|x| x.is_some())
            .unwrap()
            .clone();
        let markers = MarkersFile::default().flex_slots[0].clone();
        from_slot_tuple(slot.unwrap(), markers);
        Ok(())
    }

    #[test]
    fn from_owned_valid() -> Result<(), OtToolsIoError> {
        let slots = SlotsAttributes::default();
        let slot = slots
            .flex_slots
            .iter()
            .find(|x| x.is_some())
            .unwrap()
            .clone();
        let markers = MarkersFile::default().flex_slots[0].clone();
        let _ = SampleSettingsFile::from((slot.unwrap(), markers));
        Ok(())
    }

    #[test]
    fn from_borrowed_valid() -> Result<(), OtToolsIoError> {
        let slots = SlotsAttributes::default();
        let slot = slots
            .flex_slots
            .iter()
            .find(|x| x.is_some())
            .unwrap()
            .clone();
        let markers = MarkersFile::default().flex_slots[0].clone();
        let _ = SampleSettingsFile::from((&slot.unwrap(), &markers));
        Ok(())
    }
}

/// A helper struct for the OT Sample's Trim settings

#[derive(PartialEq, Debug, Clone, Copy)]
pub struct TrimConfig {
    /// Start of full audio sample (n samples)
    pub start: u32,
    /// End of full audio sample (n samples)
    pub end: u32,
    /// Length of audio sample to play before stopping/looping playback
    /// NOTE: This is measured in number of bars.
    pub length: u32,
}

impl From<SampleSettingsFile> for TrimConfig {
    fn from(decoded: SampleSettingsFile) -> Self {
        Self {
            start: decoded.trim_start,
            end: decoded.trim_end,
            length: decoded.trim_len,
        }
    }
}

impl From<&SampleSettingsFile> for TrimConfig {
    fn from(decoded: &SampleSettingsFile) -> Self {
        Self::from(decoded.clone())
    }
}

impl From<SlotMarkers> for TrimConfig {
    fn from(value: SlotMarkers) -> Self {
        Self {
            start: value.trim_offset,
            end: value.trim_end,
            length: value.trim_end - value.trim_offset,
        }
    }
}

impl From<&SlotMarkers> for TrimConfig {
    fn from(value: &SlotMarkers) -> Self {
        Self::from(value.clone())
    }
}

#[cfg(test)]
mod trim_config_from {
    mod sample_settings {
        use crate::samples::test_utils::create_mock_new;
        use crate::samples::TrimConfig;
        use crate::OtToolsIoError;
        #[test]
        fn owned() -> Result<(), OtToolsIoError> {
            let s = create_mock_new(None, None)?;
            assert_eq!(
                TrimConfig::from(s),
                TrimConfig {
                    start: 0,
                    end: 0,
                    length: 0,
                }
            );
            Ok(())
        }
        #[test]
        fn borrowed() -> Result<(), OtToolsIoError> {
            let s = create_mock_new(None, None)?;
            assert_eq!(
                TrimConfig::from(&s),
                TrimConfig {
                    start: 0,
                    end: 0,
                    length: 0,
                }
            );
            Ok(())
        }
    }

    mod slot_markers {
        use crate::samples::TrimConfig;
        use crate::MarkersFile;
        use crate::OtToolsIoError;
        #[test]
        fn owned() -> Result<(), OtToolsIoError> {
            let markers = MarkersFile::default().flex_slots[0].clone();
            assert_eq!(
                TrimConfig::from(markers),
                TrimConfig {
                    start: 0,
                    end: 0,
                    length: 0,
                }
            );
            Ok(())
        }
        #[test]
        fn borrowed() -> Result<(), OtToolsIoError> {
            let markers = MarkersFile::default().flex_slots[0].clone();
            assert_eq!(
                TrimConfig::from(&markers),
                TrimConfig {
                    start: 0,
                    end: 0,
                    length: 0,
                }
            );
            Ok(())
        }
    }
}

/// A helper struct for the OT Sample's Loop settings

#[derive(PartialEq, Debug, Clone, Copy)]
pub struct LoopConfig {
    /// Loop start position for the audio sample (n samples).
    pub start: u32,

    /// Length of the loop for the audio sample (n samples).
    pub length: u32,

    /// Type of looping mode.
    pub mode: LoopMode,
}

impl LoopConfig {
    pub fn new(start: u32, length: u32, mode: LoopMode) -> Self {
        Self {
            start,
            length,
            mode,
        }
    }
}

#[cfg(test)]
mod loop_config_new {

    use crate::samples::{LoopConfig, LoopMode};

    #[test]
    fn test_new_sample_loop_config_loop_off() {
        assert_eq!(
            LoopConfig::new(0, 10, LoopMode::Off),
            LoopConfig {
                start: 0,
                length: 10,
                mode: LoopMode::Off
            }
        );
    }

    #[test]
    fn test_new_sample_loop_config_umin_start_umax_length() {
        assert_eq!(
            LoopConfig::new(u32::MIN, u32::MAX, LoopMode::Off),
            LoopConfig {
                start: u32::MIN,
                length: u32::MAX,
                mode: LoopMode::Off
            }
        );
    }

    #[test]
    fn test_new_sample_loop_config_loop_normal() {
        assert_eq!(
            LoopConfig::new(0, 10, LoopMode::Normal),
            LoopConfig {
                start: 0,
                length: 10,
                mode: LoopMode::Normal
            }
        );
    }

    #[test]
    fn test_new_sample_loop_config_loop_pingpong() {
        assert_eq!(
            LoopConfig::new(0, 10, LoopMode::PingPong),
            LoopConfig {
                start: 0,
                length: 10,
                mode: LoopMode::PingPong
            }
        );
    }
}

impl From<SampleSettingsFile> for LoopConfig {
    fn from(decoded: SampleSettingsFile) -> Self {
        Self::new(
            decoded.loop_start,
            decoded.loop_len,
            LoopMode::try_from(&(decoded.loop_mode as u8)).unwrap_or(LoopMode::default()),
        )
    }
}

impl From<&SampleSettingsFile> for LoopConfig {
    fn from(decoded: &SampleSettingsFile) -> Self {
        Self::from(decoded.clone())
    }
}

#[cfg(test)]
mod loop_config_from {
    use super::{
        test_utils::create_mock_new, LoopConfig, LoopMode, OtToolsIoError, SampleSettingsFile,
        Slices, DEFAULT_GAIN, DEFAULT_TEMPO, SAMPLES_FILE_VERSION, SAMPLES_HEADER,
    };

    #[test]
    fn owned() -> Result<(), OtToolsIoError> {
        let s = create_mock_new(None, None)?;
        assert_eq!(
            LoopConfig::from(s),
            LoopConfig {
                start: 0,
                length: 0,
                mode: LoopMode::default(),
            }
        );
        Ok(())
    }
    #[test]
    fn borrowed() -> Result<(), OtToolsIoError> {
        let s = create_mock_new(None, None)?;
        assert_eq!(
            LoopConfig::from(&s),
            LoopConfig {
                start: 0,
                length: 0,
                mode: LoopMode::default(),
            }
        );
        Ok(())
    }

    fn mock_for_loop_conf(
        loop_start: u32,
        loop_len: u32,
        loop_mode: LoopMode,
    ) -> SampleSettingsFile {
        SampleSettingsFile {
            loop_len,
            loop_start,
            loop_mode: loop_mode.into(),
            header: SAMPLES_HEADER,
            datatype_version: SAMPLES_FILE_VERSION,
            tempo: DEFAULT_TEMPO,
            unknown: 0,
            trim_len: 0,
            stretch: 0,
            gain: DEFAULT_GAIN,
            quantization: 0,
            trim_start: 0,
            trim_end: 0,
            slices: Slices::default().slices,
            slices_len: 0,
            checksum: 0,
        }
    }

    #[test]
    fn test_umin_start_umax_len() {
        assert_eq!(
            LoopConfig::from(mock_for_loop_conf(u32::MIN, u32::MAX, LoopMode::Off)),
            LoopConfig {
                start: u32::MIN,
                length: u32::MAX,
                mode: LoopMode::Off
            }
        );
    }

    #[test]
    fn test_loop_off() {
        assert_eq!(
            LoopConfig::from(mock_for_loop_conf(0, 10, LoopMode::Off)),
            LoopConfig {
                start: 0,
                length: 10,
                mode: LoopMode::Off
            }
        );
    }

    #[test]
    fn test_loop_normal() {
        assert_eq!(
            LoopConfig::from(mock_for_loop_conf(0, 10, LoopMode::Normal)),
            LoopConfig {
                start: 0,
                length: 10,
                mode: LoopMode::Normal
            }
        );
    }

    #[test]
    fn test_loop_pingpong() {
        assert_eq!(
            LoopConfig::from(mock_for_loop_conf(0, 10, LoopMode::PingPong)),
            LoopConfig {
                start: 0,
                length: 10,
                mode: LoopMode::PingPong
            }
        );
    }
}