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
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
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
/*
SPDX-License-Identifier: GPL-3.0-or-later
Copyright © 2024 Mike Robeson [dijksterhuis]
*/

//! Models for pattern data within a bank.
use crate::{Defaults, HasHeaderField, OtToolsIoError};
use ot_tools_io_derive::{
    ArrayDefaults, BoxedBigArrayDefaults, ContainerArrayMethods, IsDefaultCheck,
};
use std::array::from_fn;
use std::slice::{Iter, IterMut};

use crate::parts::{
    AudioTrackAmpParamsValues, AudioTrackFxParamsValues, LfoParamsValues, MidiTrackArpParamsValues,
    MidiTrackCc1ParamsValues, MidiTrackCc2ParamsValues, MidiTrackMidiParamsValues,
};
use serde::{Deserialize, Serialize};
use serde_big_array::{Array, BigArray};

const PATTERN_HEADER: [u8; 8] = [0x50, 0x54, 0x52, 0x4e, 0x00, 0x00, 0x00, 0x00];

/// Header array for a MIDI track section in binary data files: `MTRA`
const MIDI_TRACK_HEADER: [u8; 4] = [0x4d, 0x54, 0x52, 0x41];

/// Header array for a MIDI track section in binary data files: `TRAC`
const AUDIO_TRACK_HEADER: [u8; 4] = [0x54, 0x52, 0x41, 0x43];

/// A Trig's parameter locks on the Playback/Machine page for an Audio Track.
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Copy)]
pub struct AudioTrackParameterLockPlayback {
    pub param1: u8,
    pub param2: u8,
    pub param3: u8,
    pub param4: u8,
    pub param5: u8,
    pub param6: u8,
}

impl Default for AudioTrackParameterLocks {
    fn default() -> Self {
        // 255 -> disabled

        // NOTE: the `part.rs` `default` methods for each of these type has
        // fields all set to the correct defaults for the TRACK view, not p-lock
        // trigS. So don't try and use the type's `default` method here as you
        // will end up with a bunch of p-locks on trigs for all the default
        // values. (Although maybe that's a desired feature for some workflows).

        // Yes, this comment is duplicated below. It is to make sur you've seen
        // it.
        Self {
            machine: AudioTrackParameterLockPlayback {
                param1: 255,
                param2: 255,
                param3: 255,
                param4: 255,
                param5: 255,
                param6: 255,
            },
            lfo: LfoParamsValues {
                spd1: 255,
                spd2: 255,
                spd3: 255,
                dep1: 255,
                dep2: 255,
                dep3: 255,
            },
            amp: AudioTrackAmpParamsValues {
                atk: 255,
                hold: 255,
                rel: 255,
                vol: 255,
                bal: 255,
                f: 255,
            },
            fx1: AudioTrackFxParamsValues {
                param_1: 255,
                param_2: 255,
                param_3: 255,
                param_4: 255,
                param_5: 255,
                param_6: 255,
            },
            fx2: AudioTrackFxParamsValues {
                param_1: 255,
                param_2: 255,
                param_3: 255,
                param_4: 255,
                param_5: 255,
                param_6: 255,
            },
            static_slot_id: 255,
            flex_slot_id: 255,
        }
    }
}

/// A single trig's parameter locks on an Audio Track.
#[derive(
    Debug,
    Serialize,
    Deserialize,
    Clone,
    PartialEq,
    Copy,
    ArrayDefaults,
    BoxedBigArrayDefaults,
    IsDefaultCheck,
)]
pub struct AudioTrackParameterLocks {
    pub machine: AudioTrackParameterLockPlayback,
    pub lfo: LfoParamsValues,
    pub amp: AudioTrackAmpParamsValues,
    pub fx1: AudioTrackFxParamsValues,
    pub fx2: AudioTrackFxParamsValues,
    /// P-Lock to change an audio track's static machine sample slot assignment per trig
    pub static_slot_id: u8,
    /// P-Lock to change an audio track's flex machine sample slot assignment per trig
    pub flex_slot_id: u8,
}

#[derive(
    Debug,
    Serialize,
    Deserialize,
    Clone,
    PartialEq,
    ArrayDefaults,
    BoxedBigArrayDefaults,
    IsDefaultCheck,
    ContainerArrayMethods,
)]
pub struct AudioTrackParameterLocksArray(pub Box<Array<AudioTrackParameterLocks, 64>>);

/// MIDI Track parameter locks.
#[derive(
    Debug, Serialize, Deserialize, Clone, PartialEq, Copy, ArrayDefaults, BoxedBigArrayDefaults,
)]
pub struct MidiTrackParameterLocks {
    pub midi: MidiTrackMidiParamsValues,
    pub lfo: LfoParamsValues,
    pub arp: MidiTrackArpParamsValues,
    pub ctrl1: MidiTrackCc1ParamsValues,
    pub ctrl2: MidiTrackCc2ParamsValues,

    #[serde(with = "BigArray")]
    unknown: [u8; 2],
}

impl Default for MidiTrackParameterLocks {
    fn default() -> Self {
        // 255 -> disabled

        // NOTE: the `part.rs` `default` methods for each of these type has
        // fields all set to the correct defaults for the TRACK view, not p-lock
        // trigS. So don't try and use the type's `default` method here as you
        // will end up with a bunch of p-locks on trigs for all the default
        // values. (Although maybe that's a desired feature for some workflows).

        // Yes, this comment is duplicated above. It is to make sur you've seen
        // it.

        Self {
            midi: MidiTrackMidiParamsValues {
                note: 255,
                vel: 255,
                len: 255,
                not2: 255,
                not3: 255,
                not4: 255,
            },
            lfo: LfoParamsValues {
                spd1: 255,
                spd2: 255,
                spd3: 255,
                dep1: 255,
                dep2: 255,
                dep3: 255,
            },
            arp: MidiTrackArpParamsValues {
                tran: 255,
                leg: 255,
                mode: 255,
                spd: 255,
                rnge: 255,
                nlen: 255,
            },
            ctrl1: MidiTrackCc1ParamsValues {
                pb: 255,
                at: 255,
                cc1: 255,
                cc2: 255,
                cc3: 255,
                cc4: 255,
            },
            ctrl2: MidiTrackCc2ParamsValues {
                cc5: 255,
                cc6: 255,
                cc7: 255,
                cc8: 255,
                cc9: 255,
                cc10: 255,
            },
            unknown: [255, 255],
        }
    }
}

/// Audio & MIDI Track Pattern playback settings.
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Copy)]
pub struct TrackPatternSettings {
    /// Silence any existing audio playback on the Audio Track when switching Patterns.
    pub start_silent: u8,

    /// Trigger Audio Track playback without any quantization or syncing to other Audio Tracks.
    pub plays_free: u8,

    /// Quantization when this Audio Track is Triggered for Playback.
    ///
    /// Options
    /// ```text
    /// N/A and ONE: 0 (Default)
    /// ONE2: 1
    /// HOLD: 2
    /// ```
    pub trig_mode: u8,

    /// Track Trigger Quantization.
    ///
    /// Options
    /// ```text
    /// N/A and TR.LEN: 0 (Default)
    /// 1/16: 1
    /// 2/16: 2
    /// 3/16: 3
    /// 4/16: 4
    /// 6/16: 5
    /// 8/16: 6
    /// 12/16: 7
    /// 16/16: 8
    /// 24/16: 9
    /// 32/16: 10
    /// 48/16: 11
    /// 64/16: 12
    /// 96/16: 13
    /// 128/16: 14
    /// 192/16: 15
    /// 256/16: 16
    /// DIRECT: 255
    /// ```
    pub trig_quant: u8,

    /// Whether to play the track as a `ONESHOT` track.
    pub oneshot_trk: u8,
}

impl Default for TrackPatternSettings {
    fn default() -> Self {
        Self {
            start_silent: 255,
            plays_free: 0,
            trig_mode: 0,
            trig_quant: 0,
            oneshot_trk: 0,
        }
    }
}

/// Trig bitmasks array for Audio Tracks.
/// Can be converted into an array of booleans using the `get_track_trigs_from_bitmasks` function.
///
/// Trig bitmask arrays have bitmasks stored in this order, which is slightly confusing (pay attention to the difference with 7 + 8!):
/// 1. 1st half of the 4th page
/// 2. 2nd half of the 4th page
/// 3. 1st half of the 3rd page
/// 4. 2nd half of the 3rd page
/// 5. 1st half of the 2nd page
/// 6. 2nd half of the 2nd page
/// 7. 2nd half of the 1st page
/// 8. 1st half of the 1st page
///
/// ### Bitmask values for trig positions
/// With single trigs in a half-page
/// ```text
/// positions
/// 1 2 3 4 5 6 7 8 | mask value
/// ----------------|-----------
/// - - - - - - - - | 0
/// x - - - - - - - | 1
/// - x - - - - - - | 2
/// - - x - - - - - | 4
/// - - - x - - - - | 8
/// - - - - x - - - | 16
/// - - - - - x - - | 32
/// - - - - - - x - | 64
/// - - - - - - - x | 128
/// ```
///
/// When there are multiple trigs in a half-page, the individual position values are summed together:
///
/// ```text
/// 1 2 3 4 5 6 7 8 | mask value
/// ----------------|-----------
/// x x - - - - - - | 1 + 2 = 3
/// x x x x - - - - | 1 + 2 + 4 + 8 = 15
/// ```
/// ### Fuller diagram of mask values
///
/// ```text
/// positions
/// 1 2 3 4 5 6 7 8 | mask value
/// ----------------|-----------
/// x - - - - - - - | 1
/// - x - - - - - - | 2
/// x x - - - - - - | 3
/// - - x - - - - - | 4
/// x - x - - - - - | 5
/// - x x - - - - - | 6
/// x x x - - - - - | 7
/// - - - x - - - - | 8
/// x - - x - - - - | 9
/// - x - x - - - - | 10
/// x x - x - - - - | 11
/// - - x x - - - - | 12
/// x - x x - - - - | 13
/// - x x x - - - - | 14
/// x x x x - - - - | 15
/// ................|....
/// x x x x x x - - | 63
/// ................|....
/// - - - - - - - x | 128
/// ................|....
/// - x - x - x - x | 170
/// ................|....
/// - - - - x x x x | 240
/// ................|....
/// x x x x x x x x | 255
/// ```
///
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
pub struct AudioTrackTrigMasks {
    /// Trigger Trig masks -- indicate which Trigger Trigs are active.
    /// Base track Trig masks are stored backwards, meaning
    /// the first 8 Trig positions are the last bytes in this section.
    #[serde(with = "BigArray")]
    pub trigger: [u8; 8],

    /// Envelope Trig masks -- indicate which Envelope Trigs are active.
    /// See the description of the `trig_trig_masks` field for an
    /// explanation of how the masking works.
    #[serde(with = "BigArray")]
    pub trigless: [u8; 8],

    /// Parameter-Lock Trig masks -- indicate which Parameter-Lock Trigs are active.
    /// See the description of the `trig_trig_masks` field for an
    /// explanation of how the masking works.    
    #[serde(with = "BigArray")]
    pub plock: [u8; 8],

    /// Hold Trig masks -- indicate which Hold Trigs are active.
    /// See the description of the `trig_trig_masks` field for an
    /// explanation of how the masking works.
    #[serde(with = "BigArray")]
    pub oneshot: [u8; 8],

    /// Recorder Trig masks -- indicate which Recorder Trigs are active.
    /// These seem to function differently to the main Track Trig masks.
    /// Filling up Recorder Trigs on a Pattern results in a 32 length array
    /// instead of 8 length.
    /// Possible that the Trig type is stored in this array as well.
    #[serde(with = "BigArray")]
    pub recorder: [u8; 32],

    /// Swing trigs Trig masks.
    #[serde(with = "BigArray")]
    pub swing: [u8; 8],

    /// Parameter Slide trigs Trig masks.
    #[serde(with = "BigArray")]
    pub slide: [u8; 8],
}

impl Default for AudioTrackTrigMasks {
    fn default() -> Self {
        Self {
            trigger: from_fn(|_| 0),
            trigless: from_fn(|_| 0),
            plock: from_fn(|_| 0),
            oneshot: from_fn(|_| 0),
            recorder: from_fn(|_| 0),
            swing: from_fn(|_| 170),
            slide: from_fn(|_| 0),
        }
    }
}

/// Audio Track custom scaling when the Pattern is in PER TRACK scale mode.
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Copy)]
pub struct TrackPerTrackModeScale {
    /// The Audio Track's Length when Pattern is in Per Track mode.
    /// Default: 16
    pub per_track_len: u8,

    /// The Audio Track's Scale when Pattern is in Per Track mode.
    ///
    /// Options
    /// ```text
    /// 0 -> 2x
    /// 1 -> 3/2x
    /// 2 -> 1x (Default)
    /// 3 -> 3/4x
    /// 4 -> 1/2x
    /// 5 -> 1/4x
    /// 6 -> 1/8x
    /// ```
    pub per_track_scale: u8,
}

impl Default for TrackPerTrackModeScale {
    fn default() -> Self {
        Self {
            per_track_len: 16,
            per_track_scale: 2,
        }
    }
}

/// Track trigs assigned on an Audio Track within a Pattern
#[derive(PartialEq, Debug, Serialize, Deserialize, Clone, BoxedBigArrayDefaults)]
pub struct AudioTrackTrigs {
    /// Header data section
    ///
    /// example data:
    /// ```text
    /// TRAC
    /// 54 52 41 43
    /// ```
    #[serde(with = "BigArray")]
    pub header: [u8; 4],

    /// Unknown data.
    #[serde(with = "BigArray")]
    pub unknown_1: [u8; 4],

    /// The zero indexed track number
    pub track_id: u8,

    /// Trig masks contain the Trig step locations for different trig types
    pub trig_masks: AudioTrackTrigMasks,

    /// The scale of this Audio Track in Per Track Pattern mode.
    pub scale_per_track_mode: TrackPerTrackModeScale,

    /// Amount of swing when a Swing Trig is active for the Track.
    /// Maximum is `30` (`80` on device), minimum is `0` (`50` on device).
    pub swing_amount: u8,

    /// Pattern settings for this Audio Track
    pub pattern_settings: TrackPatternSettings,

    /// Unknown data.
    pub unknown_2: u8,

    /// Parameter-Lock data for all Trigs.
    // note -- stack overflow if tring to use #[serde(with = "BigArray")]
    pub plocks: AudioTrackParameterLocksArray,

    /// What the hell is this field?!?!
    /// It **has to** be something to do with trigs, but i have no idea what it could be.
    #[serde(with = "BigArray")]
    pub unknown_3: [u8; 64],

    /// Trig Offsets, Trig Counts and Trig Conditions
    /// ====
    /// This is ..... slightly frustrating.
    ///
    /// This 64 length array consisting of a pair of bytes for each array element hold three
    /// data references... Trig Cunts and Trig Conditions use the two bytes independently,
    /// so they're easier to explain first
    ///
    /// Trig Counts and Trig Conditions
    /// ====
    ///
    /// Trig Counts and Trig Conditions data is interleaved for each trig.
    /// For Trig position 1, array index 0 is the count value and array index 1 is the Trig
    /// Condition.
    ///
    /// For trig counts (1st byte), the value (zero-indexed) is multiplied by 32.
    /// - 8 trig counts (7 repeats) --> 7 * 3 = 224
    /// - 4 trig counts (3 repeats) -- 3 * 32 = 96
    /// - 1 trig counts (0 repeats) -- 0 * 32 = 0
    ///
    /// For conditionals, see the `TrigCondition` enum and associated traits for more details.
    /// The maximum value for a Trig Condition byte is 64.
    ///
    /// ```rust
    /// // no trig micro-timings at all
    /// [
    ///     // trig 1
    ///     [
    ///         0,   // trig counts (number)
    ///         0,   // trig condition (enum rep)
    ///     ],
    ///     // trig 2
    ///     [
    ///         224, // trig counts (max value)
    ///         64,  // trig condition (max value)
    ///     ],
    ///     // trig 3
    ///     [
    ///         32,  // trig counts (minimum non-zero value)
    ///         1,   // trig condition (minimum non-zero value)
    ///     ],
    ///     // ... and so on
    /// ];
    /// ```
    ///
    /// Trig Offsets
    /// ====
    ///
    /// Trig Offset values use both of these interleaved bytes on top of the
    /// trig repeat and trig condition values... Which makes life more complex
    /// and somewhat frustrating.
    ///
    /// Inspected values
    /// - -23/384 -> 1st byte 20, 2nd byte 128
    /// - -1/32 -> 1st byte 26, 2nd byte 0
    /// - -1/64 -> 1st byte 29, 2nd byte 0
    /// - -1/128 -> 1st byte 30, 2nd byte 128
    /// - 1/128 -> 1st byte 1, 2nd byte 128
    /// - 1/64 -> 1st byte 3, 2nd byte 0
    /// - 1/32 -> 1st byte 6, 2nd byte 0
    /// - 23/384 -> 1st byte 11, 2nd byte 128
    ///
    /// #### 1st byte
    /// The 1st byte only has 31 possible values: 255 - 224 (trig count max) = 31.
    /// So it makes sense sort of that this is a mask? I guess?
    ///
    /// #### 2nd byte
    /// From what I can tell, the second offset byte is either 0 or 128.
    /// So a 2nd byte for an offset adjusted trig with a `8:8` trig condition is either
    /// - 128 + 64 = 192
    /// - 0 + 64 = 64
    ///
    /// So you will need to a `x.rem_euclid(128)` somewhere if you want to parse this.
    ///
    /// Combining the trig offset with trig count and trig conditions, we end up with
    /// ```rust
    /// [
    ///     // trig one, -23/384 offset with 1x trig count and None condition
    ///     [
    ///         20,  // 20 + (32 * 0)
    ///         128, // 128 + 0
    ///     ],
    ///     // trig two, -23/384 offset with 2x trig count and Fill condition
    ///     [
    ///         52,  // 20 + (32 * 1)
    ///         129, // 128 + 1
    ///     ],
    ///     // trig three, -23/384 offset with 3x trig count and Fill condition
    ///     [
    ///         84,  // 20 + (32 * 2)
    ///         129, // 128 + 1
    ///     ],
    ///     // trig four, -23/384 offset with 3x trig count and NotFill condition
    ///     [
    ///         84,  // 20 + (32 * 2)
    ///         130, // 128 + 2
    ///     ],
    ///     // trig five, +1/32 offset with 2x trig count and Fill condition
    ///     [
    ///         38,  // 6 + (32 * 1)
    ///         1,   // 0 + 1
    ///     ],
    ///     // trig six, +1/32 offset with 3x trig count and Fill condition
    ///     [
    ///         70,  // 6 + (32 * 2)
    ///         1,   // 0 + 1
    ///     ],
    ///     // trig seven, +1/32 offset with 3x trig count and NotFill condition
    ///     [
    ///         70,  // 6 + (32 * 2)
    ///         2,   // 0 + 2
    ///     ],
    ///     // .... and so on
    /// ];
    /// ```
    ///
    /// #### Extending pages and offsets
    ///
    /// If you have a trig offset on Trig 1 with only one pattern page activated,
    /// the trig offsets for Trig 1 are replicated over the relevant trig
    /// positions for each first trig in the inactive pages in this array.
    ///
    /// So, for a 1/32 offset on trig 1 with only one page active, you get the
    /// following values showing up in this array:
    /// - pair of bytes at array index 15 -> 1/32
    /// - pair of bytes at array index 31 -> 1/32
    /// - pair of bytes at array index 47 -> 1/32
    ///
    /// This does not happen for offset values at any other trig position
    /// (from what I can tell in my limited testing -- trig values 2-4 and 9-11
    /// inclusive are not replicated in the same way).
    ///
    /// This 'replicating trig offset values over unused pages' behaviour does
    /// not happen for trig counts. I haven't tested whether this applies to trig
    /// conditions yet.
    ///
    /// It seems that this behaviour could be to make sure the octatrack plays
    /// correctly offset trigs when you extend a page live, i.e. when extending
    /// a one-page pattern to a two-page pattern, if there is a negative offset
    /// value there the octatrack will need to play the offset trig before the
    /// first page has completed.
    ///
    /// Or it could be a bug :shrug:
    #[serde(with = "BigArray")]
    pub trig_offsets_repeats_conditions: [[u8; 2]; 64],
}

impl Default for AudioTrackTrigs {
    fn default() -> Self {
        Self {
            header: AUDIO_TRACK_HEADER,
            unknown_1: from_fn(|_| 0),
            track_id: 0,
            trig_masks: AudioTrackTrigMasks::default(),
            scale_per_track_mode: TrackPerTrackModeScale::default(),
            swing_amount: 0,
            pattern_settings: TrackPatternSettings::default(),
            unknown_2: 0,
            plocks: AudioTrackParameterLocksArray::default(),
            unknown_3: from_fn(|_| 0),
            trig_offsets_repeats_conditions: from_fn(|_| [0, 0]),
        }
    }
}

// need to implement manually to handle track_id field
impl<const N: usize> Defaults<[Self; N]> for AudioTrackTrigs {
    fn defaults() -> [Self; N]
    where
        Self: Default,
    {
        from_fn(|i| Self {
            track_id: i as u8,
            ..Default::default()
        })
    }
}

#[cfg(test)]
mod audio_track_trigs_defaults {
    use crate::patterns::AudioTrackTrigs;
    use crate::Defaults;

    fn defs() -> [AudioTrackTrigs; 8] {
        AudioTrackTrigs::defaults()
    }

    #[test]
    fn ok_track_ids() -> Result<(), ()> {
        for i in 0..8 {
            println!("Track: {} Track ID: {i}", i + 1);
            assert_eq!(defs()[i].track_id, i as u8);
        }
        Ok(())
    }
}

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

#[cfg(test)]
mod audio_track_trigs_header {
    use crate::patterns::AudioTrackTrigs;
    use crate::{
        test_utils::get_blank_proj_dirpath, BankFile, HasHeaderField, OctatrackFileIO,
        OtToolsIoError,
    };
    #[test]
    fn file_read_valid() -> Result<(), OtToolsIoError> {
        let path = get_blank_proj_dirpath().join("bank01.work");
        let x = BankFile::from_data_file(&path)?.patterns[0]
            .clone()
            .audio_track_trigs;
        assert!(x[0].check_header()?);
        Ok(())
    }

    #[test]
    fn file_read_invalid() -> Result<(), OtToolsIoError> {
        let path = get_blank_proj_dirpath().join("bank01.work");
        let x = BankFile::from_data_file(&path)?.patterns[0]
            .clone()
            .audio_track_trigs;
        let mut trigs = x[0].clone();
        trigs.header[0] = 254;
        trigs.header[1] = 254;
        trigs.header[2] = 254;
        trigs.header[3] = 254;
        assert!(!trigs.check_header()?);
        Ok(())
    }

    #[test]
    fn default_valid() -> Result<(), OtToolsIoError> {
        let trigs = AudioTrackTrigs::default();
        assert!(trigs.check_header()?);
        Ok(())
    }

    #[test]
    fn default_invalid() -> Result<(), OtToolsIoError> {
        let mut trigs = AudioTrackTrigs::default();
        trigs.header[0] = 0x01;
        trigs.header[1] = 0x01;
        trigs.header[2] = 0x50;
        assert!(!trigs.check_header()?);
        Ok(())
    }
}

#[derive(PartialEq, Debug, Serialize, Deserialize, Clone, ContainerArrayMethods)]
pub struct AudioTrackTrigsArray(pub [AudioTrackTrigs; 8]);

/// MIDI Track Trig masks.
/// Can be converted into an array of booleans using the `get_track_trigs_from_bitmasks` function.
/// See `AudioTrackTrigMasks` for more information.
///
/// Trig mask arrays have data stored in this order, which is slightly confusing (pay attention to the difference with 7 + 8!):
/// 1. 1st half of the 4th page
/// 2. 2nd half of the 4th page
/// 3. 1st half of the 3rd page
/// 4. 2nd half of the 3rd page
/// 5. 1st half of the 2nd page
/// 6. 2nd half of the 2nd page
/// 7. 2nd half of the 1st page
/// 8. 1st half of the 1st page
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Copy)]
pub struct MidiTrackTrigMasks {
    /// Note Trig masks.
    #[serde(with = "BigArray")]
    pub trigger: [u8; 8],

    /// Trigless Trig masks.
    #[serde(with = "BigArray")]
    pub trigless: [u8; 8],

    /// Parameter Lock Trig masks.
    /// Note this only stores data for exclusive parameter lock *trigs* (light green trigs).
    #[serde(with = "BigArray")]
    pub plock: [u8; 8],

    /// Swing trigs mask.
    #[serde(with = "BigArray")]
    pub swing: [u8; 8],

    /// this is a block of 8, so looks like a trig mask for tracks,
    /// but I can't think of what it could be.
    #[serde(with = "BigArray")]
    pub unknown: [u8; 8],
}

impl Default for MidiTrackTrigMasks {
    fn default() -> Self {
        Self {
            trigger: from_fn(|_| 0),
            trigless: from_fn(|_| 0),
            plock: from_fn(|_| 0),
            swing: from_fn(|_| 170),
            unknown: from_fn(|_| 0),
        }
    }
}

/// Track trigs assigned on an Audio Track within a Pattern
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, BoxedBigArrayDefaults)]
pub struct MidiTrackTrigs {
    /// Header data section
    ///
    /// example data:
    /// ```text
    /// MTRA
    /// 4d 54 52 41
    /// ```
    #[serde(with = "BigArray")]
    pub header: [u8; 4],

    /// Unknown data.
    #[serde(with = "BigArray")]
    pub unknown_1: [u8; 4],

    /// The zero indexed track number
    pub track_id: u8,

    /// MIDI Track Trig masks contain the Trig step locations for different trig types
    pub trig_masks: MidiTrackTrigMasks,

    /// The scale of this MIDI Track in Per Track Pattern mode.
    pub scale_per_track_mode: TrackPerTrackModeScale,

    /// Amount of swing when a Swing Trig is active for the Track.
    /// Maximum is `30` (`80` on device), minimum is `0` (`50` on device).
    pub swing_amount: u8,

    /// Pattern settings for this MIDI Track
    pub pattern_settings: TrackPatternSettings,

    /// trig properties -- p-locks etc.
    /// the big `0xff` value block within tracks basically.
    /// 32 bytes per trig -- 6x parameters for 5x pages plus 2x extra fields at the end.
    ///
    /// For audio tracks, the 2x extra fields at the end are for sample locks,
    /// but there's no such concept for MIDI tracks.
    /// It seems like Elektron devs reused their data structures for P-Locks on both Audio + MIDI tracks.
    // note -- stack overflow if trying to use #[serde(with = "BigArray")]
    pub plocks: Box<Array<MidiTrackParameterLocks, 64>>,

    /// See the documentation for `AudioTrackTrigs` on how this field works.
    #[serde(with = "BigArray")]
    pub trig_offsets_repeats_conditions: [[u8; 2]; 64],
}

impl Default for MidiTrackTrigs {
    fn default() -> Self {
        Self {
            header: MIDI_TRACK_HEADER,
            unknown_1: from_fn(|_| 0),
            track_id: 0,
            trig_masks: MidiTrackTrigMasks::default(),
            scale_per_track_mode: TrackPerTrackModeScale::default(),
            swing_amount: 0,
            pattern_settings: TrackPatternSettings::default(),
            plocks: MidiTrackParameterLocks::defaults(),
            trig_offsets_repeats_conditions: from_fn(|_| [0, 0]),
        }
    }
}

// needs to be manually implemented
impl<const N: usize> Defaults<[Self; N]> for MidiTrackTrigs {
    fn defaults() -> [Self; N]
    where
        Self: Default,
    {
        from_fn(|i| Self {
            track_id: i as u8,
            ..Default::default()
        })
    }
}

#[cfg(test)]
mod midi_track_trigs_defaults {

    use crate::patterns::MidiTrackTrigs;
    use crate::Defaults;

    fn defs() -> [MidiTrackTrigs; 8] {
        MidiTrackTrigs::defaults()
    }

    #[test]
    fn ok_track_ids() -> Result<(), ()> {
        for i in 0..8 {
            println!("Track: {} Track ID: {i}", i + 1);
            assert_eq!(defs()[i].track_id, i as u8);
        }
        Ok(())
    }
}

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

#[cfg(test)]
mod midi_track_trigs_header {
    use crate::patterns::MidiTrackTrigs;
    use crate::{
        test_utils::get_blank_proj_dirpath, BankFile, HasHeaderField, OctatrackFileIO,
        OtToolsIoError,
    };
    #[test]
    fn file_read_valid() -> Result<(), OtToolsIoError> {
        let path = get_blank_proj_dirpath().join("bank01.work");
        let x = BankFile::from_data_file(&path)?.patterns[0]
            .clone()
            .midi_track_trigs;
        assert!(x[0].check_header()?);
        Ok(())
    }

    #[test]
    fn file_read_invalid() -> Result<(), OtToolsIoError> {
        let path = get_blank_proj_dirpath().join("bank01.work");
        let x = BankFile::from_data_file(&path)?.patterns[0]
            .clone()
            .midi_track_trigs;
        let mut trigs = x[0].clone();
        trigs.header[0] = 254;
        trigs.header[1] = 254;
        trigs.header[2] = 254;
        trigs.header[3] = 254;
        assert!(!trigs.check_header()?);
        Ok(())
    }

    #[test]
    fn default_valid() -> Result<(), OtToolsIoError> {
        let trigs = MidiTrackTrigs::default();
        assert!(trigs.check_header()?);
        Ok(())
    }

    #[test]
    fn default_invalid() -> Result<(), OtToolsIoError> {
        let mut trigs = MidiTrackTrigs::default();
        trigs.header[0] = 0x01;
        trigs.header[1] = 0x01;
        trigs.header[2] = 0x50;
        assert!(!trigs.check_header()?);
        Ok(())
    }
}

#[derive(PartialEq, Debug, Serialize, Deserialize, Clone, ContainerArrayMethods)]
pub struct MidiTrackTrigsArray(pub [MidiTrackTrigs; 8]);

/// Pattern level scaling settings.
/// Some of these settings still apply when the pattern is in Per-Track scaling mode.
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
pub struct PatternScaleSettings {
    /// Multiply this value by `master_len_per_track` to get
    /// the real Master Length in Per Track Pattern mode.
    ///
    /// This field must be set to `255` when Master Length in
    /// Per Track Pattern mode is set to `INF`.
    ///
    /// ```text
    /// 0: From 2 steps to 255 steps.
    /// 1: From 256 steps to 511 steps.
    /// 2: From 512 steps to 767 steps.
    /// 3: From 768 steps to 1023 steps.
    /// 4: 1024 steps only.
    /// 255: `INF`.
    /// ```
    pub master_len_per_track_multiplier: u8,

    /// Master Length in Per Track Pattern mode.
    /// Must multiply this by multiplier like this `(x + 1) * (mult + 1)` to get the real number.
    ///
    /// This field must be set to `255` when Master Length in
    /// Per Track Pattern mode is set to `INF`.
    ///
    /// Minimum value is 2 when the multiplier equals 0.
    pub master_len_per_track: u8,

    /// The Audio Track's Scale when Pattern is in Per Track mode.
    ///
    /// Options
    /// ```text
    /// 0 -> 2x
    /// 1 -> 3/2x
    /// 2 -> 1x (Default)
    /// 3 -> 3/4x
    /// 4 -> 1/2x
    /// 5 -> 1/4x
    /// 6 -> 1/8x
    /// ```
    pub master_scale_per_track: u8,

    /// Master Pattern Length.
    /// Determines Pattern Length for all Tracks when NOT in Per Track mode.
    pub master_len: u8,

    /// Master Pattern playback multiplier.
    ///
    /// Options
    /// ```text
    /// 0 -> 2x
    /// 1 -> 3/2x
    /// 2 -> 1x (Default)
    /// 3 -> 3/4x
    /// 4 -> 1/2x
    /// 5 -> 1/4x
    /// 6 -> 1/8x
    /// ```
    pub master_scale: u8,

    /// Scale mode for the Pattern.
    ///
    /// Options
    /// ```text
    /// NORMAL: 0 (Default)
    /// PER TRACK: 1
    /// ```
    pub scale_mode: u8,
}

impl Default for PatternScaleSettings {
    fn default() -> Self {
        Self {
            master_len_per_track_multiplier: 0,
            master_len_per_track: 16,
            master_scale_per_track: 2,
            master_len: 16,
            master_scale: 2,
            scale_mode: 0,
        }
    }
}

/// Chaining behaviour for the pattern.
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
pub struct PatternChainBehavior {
    /// When `use_project_setting` field is set to `1`/`true`
    /// this field should be set to `N/A` with a value of `255`.
    pub use_pattern_setting: u8,

    /// Pattern Chain Behaviour -- Use the Project level setting for chain
    /// behaviour and disable any Pattern level chaining behaviour.
    /// Numeric Boolean.
    /// When this is `1` the `use_pattern_setting` should be set to `255`.
    pub use_project_setting: u8,
}

// allow the verbose implementation to keep things
// - (a) standardized across all types
// - (b) easier for non-rustaceans to follow when reading through data structures
#[allow(clippy::derivable_impls)]
impl Default for PatternChainBehavior {
    fn default() -> Self {
        Self {
            use_pattern_setting: 0,
            use_project_setting: 0,
        }
    }
}

/// A pattern of trigs stored in the bank.
#[derive(
    PartialEq,
    Debug,
    Serialize,
    Deserialize,
    Clone,
    ArrayDefaults,
    BoxedBigArrayDefaults,
    IsDefaultCheck,
)]
pub struct Pattern {
    /// Header indicating start of pattern section
    ///
    /// example data:
    /// ```text
    /// PTRN....
    /// 50 54 52 4e 00 00 00 00
    /// ```
    #[serde(with = "BigArray")]
    pub header: [u8; 8],

    /// Audio Track data
    pub audio_track_trigs: AudioTrackTrigsArray,

    /// MIDI Track data
    pub midi_track_trigs: MidiTrackTrigsArray,

    /// Pattern scaling controls and settings
    pub scale: PatternScaleSettings,

    /// Pattern chaining behaviour and settings
    pub chain_behaviour: PatternChainBehavior,

    /// Unknown data.
    pub unknown: u8,

    /// The Part of a Bank assigned to a Pattern.
    /// Part 1 = 0; Part 2 = 1; Part 3 = 2; Part 4 = 3.
    /// Credit to [@sezare56 on elektronauts for catching this one](https://www.elektronauts.com/t/octalib-a-simple-octatrack-librarian/225192/27)
    pub part_assignment: u8,

    /// Pattern setting for Tempo.
    ///
    /// The Tempo value is split across both `tempo_1` and `tempo_2`.
    /// Yet to figure out how they relate to each other.
    ///
    /// Value of 120 BPM is 11 for this field.
    /// Value of 30 BPM is 2 for this field.
    pub tempo_1: u8,

    /// Pattern setting for Tempo.
    ///
    /// The Tempo value is split across both `tempo_1` and `tempo_2`.
    /// Tet to figure out how they relate to each other.
    ///
    /// Value of 120 BPM is `64` for this field.
    /// Value of 30 BPM is `208` for this field.
    pub tempo_2: u8,
}

impl Default for Pattern {
    fn default() -> Self {
        Self {
            header: PATTERN_HEADER,
            audio_track_trigs: AudioTrackTrigsArray::default(),
            midi_track_trigs: MidiTrackTrigsArray::default(),
            scale: PatternScaleSettings::default(),
            chain_behaviour: PatternChainBehavior::default(),
            unknown: 0,
            part_assignment: 0,
            // **I believe** these two mask values make the tempo 120.0 BPM
            // don't quote me on that though
            tempo_1: 11,
            tempo_2: 64,
        }
    }
}

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

#[cfg(test)]
mod pattern_header {
    use crate::{
        patterns::Pattern, test_utils::get_blank_proj_dirpath, BankFile, HasHeaderField,
        OctatrackFileIO, OtToolsIoError,
    };
    #[test]
    fn file_read_valid() -> Result<(), OtToolsIoError> {
        let path = get_blank_proj_dirpath().join("bank01.work");
        let pattern = BankFile::from_data_file(&path)?.patterns[0].clone();
        assert!(pattern.check_header()?);
        Ok(())
    }

    #[test]
    fn file_read_invalid() -> Result<(), OtToolsIoError> {
        let path = get_blank_proj_dirpath().join("bank01.work");
        let mut pattern = BankFile::from_data_file(&path)?.patterns[0].clone();
        pattern.header[0] = 254;
        pattern.header[1] = 254;
        pattern.header[2] = 254;
        pattern.header[3] = 254;
        assert!(!pattern.check_header()?);
        Ok(())
    }

    #[test]
    fn default_valid() -> Result<(), OtToolsIoError> {
        let pattern = Pattern::default();
        assert!(pattern.check_header()?);
        Ok(())
    }

    #[test]
    fn default_invalid() -> Result<(), OtToolsIoError> {
        let mut pattern = Pattern::default();
        pattern.header[0] = 0x01;
        pattern.header[1] = 0x01;
        pattern.header[7] = 0x50;
        assert!(!pattern.check_header()?);
        Ok(())
    }
}

#[derive(PartialEq, Debug, Serialize, Deserialize, Clone, ContainerArrayMethods)]
pub struct PatternArray(pub Box<Array<Pattern, 16>>);