ot-tools-io 0.11.3

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

//! Data type and trait implementations for [`Slice`] data in [`SlotMarkers`][crate::types::SlotMarkers] and
//! [`SampleSettingsFile`][crate::SampleSettingsFile] types.

use crate::traits::SwapBytes;
use crate::{Defaults, IsDefault, OtToolsIoError};
use ot_tools_io_derive::{
    ArrayDefaults, AsMutDerive, AsRefDerive, BoxedArrayDefaults, IsDefaultCheck,
};
use serde::{Deserialize, Serialize};
use std::array::from_fn;
use thiserror::Error;

/// Errors specific to [`Slice`]s.
///
/// Most of the time this will be casted into an [`OtToolsIoError`] instance in a return type.
#[derive(Debug, Error, PartialEq)]
pub enum SliceError {
    /// There's a problem with the slice loop point value.
    /// Likely outside the accepted bounds of the `trim_start` and `trim_end` fields.
    #[error("invalid slice loop point: {value}")]
    LoopPoint { value: u32 },
    /// There's a problem with one of the trim values.
    /// Usually one of `trim_start`/`trim_end` is before/after the other when it shouldn't be.
    #[error("invalid slice trim: start={start} end={end}")]
    Trim { start: u32, end: u32 },
}

/// 'Slice' markers for a sample, based on audio array sample positions.
/// Arrays of slices are 64-length and present in both
/// [`SampleSettingsFile`][crate::SampleSettingsFile]s and
/// [`SlotMarkers`][crate::types::SlotMarkers] types.
///
/// # Slice marker points outside slot trim range
///
/// This is permitted by the Octatrack.
/// You can have [`Slice`] `trim_start` and `trim_end` values outside the bounds of the slots's
/// main trim range.
#[derive(
    Copy,
    Clone,
    Debug,
    Eq,
    Hash,
    Ord,
    PartialEq,
    PartialOrd,
    Serialize,
    Deserialize,
    ArrayDefaults,
    BoxedArrayDefaults,
    AsMutDerive,
    AsRefDerive,
    IsDefaultCheck,
)]
pub struct Slice {
    /// Start position for the [`Slice`].
    /// Number of audio samples.
    /// Essentially the same behaviour as `trim_start` field in [`SlotMarkers`][smarks],
    /// but for a particular [`Slice`].
    ///
    /// ## Validation
    ///
    /// `trim_start` must be less than `trim_end`.
    ///
    /// [smarks]: crate::markers::SlotMarkers
    pub trim_start: u32,

    /// End position for the [`Slice`].
    /// Number of audio samples.
    /// Essentially the same behaviour as `trim_end` field in [`SlotMarkers`][smarks],
    /// but for a particular slice.
    ///
    /// ## Validation
    ///
    /// `trim_end` must be greater than `trim_start`.
    ///
    /// [smarks]: crate::markers::SlotMarkers
    pub trim_end: u32,

    /// Loop start position for the [`Slice`].
    /// Number of audio samples.
    /// Essentially the same behaviour as `loop_point` field in [`SlotMarkers`][smarks],
    /// but for a particular slice.
    ///
    /// From the Octatrack manual
    /// > 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
    ///
    /// ## Naming convention
    ///
    /// This is actually `Loop Point` in the Octatrack manual.
    /// I will change the field name at some point.
    ///
    /// ## Disabling the loop point
    ///
    /// Use the [`SLICE_LOOP_POINT_DISABLED`] const to disable the [`Slice`]'s loop point.
    ///
    /// From the Octatrack manual
    ///
    /// > Sample slices without loop points will not be looped.
    /// > Read more about loop points in section “13.2.1 TRIM” on page 81.
    /// >
    /// > -- page 86
    ///
    /// ## Validation
    ///
    /// For an initialized slice,
    /// `loop_point` must be non-zero (see [`SLICE_LOOP_POINT_DISABLED`])
    /// or the `trim_end` field must be non-zero.
    /// Additionally, `loop_point` must be within the bounds of `trim_start` and `trim_end` values.
    ///
    /// [smarks]: crate::markers::SlotMarkers
    pub loop_start: u32,
}

/// Used to set a [`Slice`]'s loop point as 'Disabled'.
/// (no looping will ever be possible for this slice? not sure, need to check manual).
///
/// Using this value is **not** the same as zero-ing a slice (de-init-ing a slice).
pub const SLICE_LOOP_POINT_DISABLED: u32 = 0xFFFFFFFF;

impl Slice {
    /// Create a new active/initialized slice.
    ///
    /// # Un-initialized / inactive slice data
    ///
    /// Do not use this method for creating un-initialized slice data, i.e. wherever there are
    /// inactive slices in a slice array field.
    /// Use [`Slice::default`] in those cases (sets all field values to zero).
    ///
    /// # Default value for `loop_start`
    ///
    /// Providing `None` as the `loop_start` argument will default to the
    /// [`SLICE_LOOP_POINT_DISABLED`] value (`0xFFFFFFFF`).
    ///
    /// See the above note on inactive slices.
    ///
    /// # Example
    ///
    /// ```rust
    /// use ot_tools_io::OtToolsIoError;
    /// use ot_tools_io::slices::{Slice, SLICE_LOOP_POINT_DISABLED, SliceError};
    ///
    /// # fn main() -> Result<(), OtToolsIoError> {
    /// // has loop point
    /// assert_eq!(
    ///     Slice::new(100, 200, Some(150))?,
    ///     Slice { trim_start: 100, trim_end: 200, loop_start: 150}
    /// );
    /// // no loop point for sample settings file data
    /// assert_eq!(
    ///     Slice::new(100, 200, None)?,
    ///     Slice { trim_start: 100, trim_end: 200, loop_start: SLICE_LOOP_POINT_DISABLED}
    /// );
    /// // GOTCHA! an un-init-ed Slice type has a zero for the loop point, e.g. for a new markers file
    /// assert_eq!(
    ///     Slice::new(0, 0, Some(0))?,
    ///     Slice { trim_start: 0, trim_end: 0, loop_start: 0}
    /// );
    /// // trim start can equal trim end (usually empty slices)
    /// assert_eq!(
    ///     Slice::new(100, 100, None)?,
    ///     Slice { trim_start: 100, trim_end: 100, loop_start: SLICE_LOOP_POINT_DISABLED}
    /// );
    /// // cannot have trim start after trim end
    /// assert_eq!(
    ///     Slice::new(200, 100, None).unwrap_err().to_string(),
    ///     OtToolsIoError::Slice(SliceError::Trim {start: 200, end: 100}).to_string()
    /// );
    /// // can have a loop point at trim start
    /// assert_eq!(
    ///     Slice::new(100, 200, Some(100))?,
    ///     Slice { trim_start: 100, trim_end: 200, loop_start: 100}
    /// );
    /// // cannot have a loop point at trim end
    /// assert_eq!(
    ///     Slice::new(100, 200, Some(200)).unwrap_err().to_string(),
    ///     OtToolsIoError::Slice(SliceError::LoopPoint {value: 200}).to_string()
    /// );
    /// // cannot have a loop point before trim start
    /// assert_eq!(
    ///     Slice::new(100, 200, Some(50)).unwrap_err().to_string(),
    ///     OtToolsIoError::Slice(SliceError::LoopPoint {value: 50}).to_string()
    /// );
    /// // cannot have a loop point after trim end
    /// assert_eq!(
    ///     Slice::new(100, 200, Some(500)).unwrap_err().to_string(),
    ///     OtToolsIoError::Slice(SliceError::LoopPoint {value: 500}).to_string()
    /// );
    /// # Ok(()) }
    /// ```
    pub fn new(
        trim_start: u32,
        trim_end: u32,
        loop_start: Option<u32>,
    ) -> Result<Self, OtToolsIoError> {
        // default for a NEW slice is Disabled
        // default for un-init-ed data is zero
        let loop_point = loop_start.unwrap_or(SLICE_LOOP_POINT_DISABLED);

        let x = Self {
            trim_start,
            trim_end,
            loop_start: loop_point,
        };

        x.validate()?;

        Ok(x)
    }

    /// "De-inits" all fields to zero values.
    pub fn deinit(&mut self) {
        self.trim_start = 0;
        self.trim_end = 0;
        self.loop_start = 0;
    }

    /// Runs a series of validation checks on the field values for an instance of the type.
    ///
    /// Will return an appropriate error if a problem is discovered with a field's value.
    ///
    /// Read through the fields on [`Slice`] to find out which ones are checked and how
    /// they are checked.
    ///
    /// You can also look at the documentation example for [`Slice::new`].
    ///
    /// # Valid Example
    /// ```
    /// use ot_tools_io::OtToolsIoError;
    /// use ot_tools_io::types::Slice;
    /// # fn main() -> Result<(), OtToolsIoError> {
    ///
    /// let good_slice = Slice {
    ///     trim_start: 100,
    ///     trim_end: 200,
    ///     loop_start: 150,
    /// };
    ///
    /// assert!(good_slice.validate().is_ok());
    /// # Ok(()) }
    /// ```
    ///
    /// # Invalid Trim Example
    /// ```
    /// use ot_tools_io::OtToolsIoError;
    /// use ot_tools_io::types::Slice;
    /// use ot_tools_io::errors::SliceError;
    /// # fn main() -> Result<(), OtToolsIoError> {
    ///
    /// let bad_slice = Slice {
    ///     trim_start: 2000,
    ///     trim_end: 100,
    ///     loop_start: 0,
    /// };
    ///
    /// assert_eq!(
    ///     bad_slice.validate().unwrap_err().to_string(),
    ///     OtToolsIoError::Slice(
    ///         SliceError::Trim {start: 2000, end: 100}
    ///     ).to_string(),
    /// );
    /// # Ok(()) }
    /// ```
    ///
    /// # Invalid Loop Example
    /// ```
    /// use ot_tools_io::OtToolsIoError;
    /// use ot_tools_io::types::Slice;
    /// use ot_tools_io::errors::SliceError;
    /// # fn main() -> Result<(), OtToolsIoError> {
    ///
    /// let bad_slice = Slice {
    ///     trim_start: 100,
    ///     trim_end: 2000,
    ///     loop_start: 5,
    /// };
    ///
    /// assert_eq!(
    ///     bad_slice.validate().unwrap_err().to_string(),
    ///     OtToolsIoError::Slice(
    ///         SliceError::LoopPoint {value : 5}
    ///     ).to_string(),
    /// );
    /// # Ok(()) }
    /// ```
    pub fn validate(&self) -> Result<(), OtToolsIoError> {
        // default (uninitialized) is always valid
        if self.is_default() {
            return Ok(());
        }

        // Trim start can only be equal to trim end when slice is uninitialized
        if self.trim_start > self.trim_end {
            return Err(SliceError::Trim {
                start: self.trim_start,
                end: self.trim_end,
            }
            .into());
        }

        // slice loop point in trim range or slice loop point is disabled
        if !crate::loop_point_is_in_trim_range(self.loop_start, self.trim_start, self.trim_end)
            && self.loop_start != SLICE_LOOP_POINT_DISABLED
        {
            return Err(SliceError::LoopPoint {
                value: self.loop_start,
            }
            .into());
        }
        Ok(())
    }
}

#[allow(clippy::derivable_impls)]
impl Default for Slice {
    fn default() -> Self {
        Self {
            trim_start: 0,
            trim_end: 0,
            // initialized data for slices is always 0 ...
            // BUT when we create a slice on the device, the loop point is set
            // to DISABLED (0xFFFFFFFF) ...
            //
            // but users don't see that the data is actually mutated after
            // initialization ... so this is one of those weird places where
            // 'default' is not what a user might expect to see as 'default'
            loop_start: 0,
        }
    }
}

impl SwapBytes for Slice {
    fn swap_bytes(self) -> Self {
        Self {
            trim_start: self.trim_start.swap_bytes(),
            trim_end: self.trim_end.swap_bytes(),
            loop_start: self.loop_start.swap_bytes(),
        }
    }
}

#[cfg(test)]
mod deinit {
    use crate::slices::Slice;
    use crate::{IsDefault, OtToolsIoError};
    #[test]
    fn ok() -> Result<(), OtToolsIoError> {
        let mut x = Slice::new(100, 200, Some(150))?;
        x.deinit();
        assert!(x.is_default());
        Ok(())
    }
}

#[cfg(test)]
mod test {
    use crate::slices::Slice;
    use crate::slices::SliceError;
    use crate::slices::SLICE_LOOP_POINT_DISABLED;
    use crate::OtToolsIoError;

    #[test]
    fn ok_no_offset_no_loop() {
        let valid = Slice {
            trim_start: 0,
            trim_end: 1000,
            loop_start: SLICE_LOOP_POINT_DISABLED,
        };

        let s = Slice::new(0, 1000, None);

        assert!(s.is_ok());
        assert_eq!(valid, s.unwrap());
    }

    #[test]
    fn ok_loop_point() {
        let valid = Slice {
            trim_start: 0,
            trim_end: 1000,
            loop_start: 0,
        };

        let s = Slice::new(0, 1000, Some(0));

        assert!(s.is_ok());
        assert_eq!(valid, s.unwrap());
    }

    #[test]
    fn err_loop_end() {
        let s = Slice::new(0, 1000, Some(1000));
        assert!(s.is_err());
        assert_eq!(
            s.unwrap_err().to_string(),
            OtToolsIoError::Slice(SliceError::LoopPoint { value: 1000 }).to_string()
        );
    }

    #[test]
    fn err_trim() {
        let (start, end) = (1001, 1000);
        let s = Slice::new(start, end, None);
        assert!(s.is_err());
        assert_eq!(
            s.unwrap_err().to_string(),
            OtToolsIoError::Slice(SliceError::Trim { start, end }).to_string()
        );
    }

    #[test]
    fn ok_offset_100_no_loop() {
        let valid = Slice {
            trim_start: 100,
            trim_end: 1100,
            loop_start: SLICE_LOOP_POINT_DISABLED,
        };

        let s = Slice::new(100, 1100, None);

        assert!(s.is_ok());
        assert_eq!(valid, s.unwrap());
    }

    #[test]
    fn ok_offset_100_with_loop_200() {
        let valid = Slice {
            trim_start: 100,
            trim_end: 1100,
            loop_start: 200,
        };

        let s = Slice::new(100, 1100, Some(200));

        assert!(s.is_ok());
        assert_eq!(valid, s.unwrap());
    }
}