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
///! JACK transport wrappers.
///! See the [transport design api docs](https://jackaudio.org/api/transport-design.html) for more info.
use crate::{Frames, Time};
use jack_sys as j;
use std::sync::Weak;

pub type Result<T> = ::std::result::Result<T, crate::Error>;

/// A structure for querying and manipulating the JACK transport.
pub struct Transport {
    pub(crate) client_ptr: *mut j::jack_client_t,
    pub(crate) client_life: Weak<()>,
}

/// A structure representing the transport position.
#[repr(transparent)]
pub struct TransportPosition(j::jack_position_t);

/// A representation of transport state.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TransportState {
    Stopped,
    Rolling,
    Starting,
}

/// A helper struct encapsulating both `TransportState` and `TransportPosition`.
#[derive(Debug)]
pub struct TransportStatePosition {
    pub pos: TransportPosition,
    pub state: TransportState,
}

/// Transport Bar Beat Tick data.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct TransportBBT {
    /// Time signature bar, 1 or more.
    pub bar: usize,
    /// Time signature beat, 1 <= beat <= sig_num.
    pub beat: usize,
    /// current tick-within-beat
    /// # Remarks
    /// * Should be >= 0 and < ticks_per_beat: the first tick is tick 0.
    pub tick: usize,
    /// Time Signature "numerator". Jack calls this `beats_per_bar`.
    pub sig_num: f32,
    /// Time Signature "denominator". Jack calls this `beat_type`.
    pub sig_denom: f32,
    /// Number of ticks within a beat.
    /// # Remarks
    /// * Usually a moderately large integer with many denominators, such as 1920.0
    pub ticks_per_beat: f64,
    /// BPM, quantized to block size. This means when the tempo is not constant within this block,
    /// the BPM value should adapted to compensate for this. This is different from most fields in
    /// this struct, which specify the value at the beginning of the block rather than an average.
    pub bpm: f64,
    /// Number of ticks that have elapsed between frame 0 and the first beat of the current measure.
    pub bar_start_tick: f64,
}

/// An error validating a TransportBBT
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum TransportBBTValidationError {
    ///`bar` must be greater than zero
    BarZero,
    ///`beat` must be greater than zero and less than `sig_num`
    BeatRange,
    ///There must more than zero ticks per beat
    TicksPerBeatRange,
    ///Time signature numerator, `sig_num` must be greater than zero
    SigNumRange,
    ///Time signature denominator, `sig_denom` must be greater than zero
    SigDenomRange,
    ///`bpm` must be greater than or equal to zero
    BPMRange,
    ///`tick` must be less than `ticks_per_beat`
    TickRange,
}

impl std::fmt::Display for TransportBBTValidationError {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        write!(f, "TransportBBTValidationError: {:?}", &self)
    }
}

impl std::error::Error for TransportBBTValidationError {}

impl Transport {
    fn with_client<F: Fn(*mut j::jack_client_t) -> R, R>(&self, func: F) -> Result<R> {
        if self.client_life.upgrade().is_some() {
            Ok(func(self.client_ptr))
        } else {
            Err(crate::Error::ClientIsNoLongerAlive)
        }
    }

    /// Start the JACK transport rolling.
    ///
    /// # Remarks
    ///
    /// * Any client can make this request at any time.
    /// * It takes effect no sooner than the next process cycle, perhaps later if there are
    /// slow-sync clients.
    /// * This function is realtime-safe.
    pub fn start(&self) -> Result<()> {
        self.with_client(|ptr| unsafe {
            j::jack_transport_start(ptr);
        })
    }

    /// Stop the JACK transport.
    ///
    /// # Remarks
    ///
    /// * Any client can make this request at any time.
    /// * It takes effect on the next process cycle.
    /// * This function is realtime-safe.
    pub fn stop(&self) -> Result<()> {
        self.with_client(|ptr| unsafe {
            j::jack_transport_stop(ptr);
        })
    }

    /// Request a new transport position.
    ///
    /// # Arguments
    ///
    /// * `pos` - requested new transport position.
    ///
    /// # Remarks
    ///
    /// * May be called at any time by any client.
    /// * The new position takes effect in two process cycles.
    /// * If there are slow-sync clients and the transport is already rolling, it will enter the `TransportState::Starting` state and begin invoking their sync_callbacks until ready.
    /// * This function is realtime-safe.
    pub fn reposition(&self, pos: &TransportPosition) -> Result<()> {
        Self::result_from_ffi(
            self.with_client(|ptr| unsafe {
                j::jack_transport_reposition(ptr, &pos.0 as *const j::jack_position_t)
            }),
            (),
        )
    }

    /// Reposition the transport to a new frame number.
    ///
    /// # Arguments
    ///
    /// * `frame` - frame number of new transport position.
    ///
    /// # Remarks
    ///
    /// * May be called at any time by any client.
    /// * The new position takes effect in two process cycles.
    /// * If there are slow-sync clients and the transport is already rolling, it will enter the JackTransportStarting state and begin invoking their sync_callbacks until ready.
    /// * This function is realtime-safe.
    pub fn locate(&self, frame: Frames) -> Result<()> {
        Self::result_from_ffi(
            self.with_client(|ptr| unsafe { j::jack_transport_locate(ptr, frame) }),
            (),
        )
    }

    //helper to convert to TransportState
    pub(crate) fn state_from_ffi(state: j::jack_transport_state_t) -> TransportState {
        match state {
            j::JackTransportStopped => TransportState::Stopped,
            j::JackTransportStarting => TransportState::Starting,
            //the JackTransportLooping state is no longer used
            _ => TransportState::Rolling,
        }
    }

    //helper to create generic error from jack response
    fn result_from_ffi<R>(v: Result<::libc::c_int>, r: R) -> Result<R> {
        match v {
            Ok(0) => Ok(r),
            Ok(_) => Err(crate::Error::UnknownError),
            Err(e) => Err(e),
        }
    }

    /// Query the current transport state and position.
    ///
    /// # Remarks
    ///
    /// * This function is realtime-safe, and can be called from any thread.
    /// * If called from the process thread, `pos` corresponds to the first frame of the current cycle and the state returned is valid for the entire cycle.
    pub fn query(&self) -> Result<TransportStatePosition> {
        self.with_client(|ptr| {
            let mut pos: std::mem::MaybeUninit<TransportPosition> = std::mem::MaybeUninit::zeroed();
            let state = Self::state_from_ffi(unsafe {
                j::jack_transport_query(
                    ptr,
                    pos.as_mut_ptr() as *mut jack_sys::Struct__jack_position,
                )
            });
            TransportStatePosition {
                pos: unsafe { pos.assume_init() },
                state,
            }
        })
    }

    /// Query the current transport state.
    ///
    /// # Remarks
    ///
    /// * This function is realtime-safe, and can be called from any thread.
    /// * If called from the process thread, the state returned is valid for the entire cycle.
    pub fn query_state(&self) -> Result<TransportState> {
        self.with_client(|ptr| {
            Self::state_from_ffi(unsafe { j::jack_transport_query(ptr, std::ptr::null_mut()) })
        })
    }
}

//all exposed methods are realtime safe
unsafe impl Send for Transport {}
unsafe impl Sync for Transport {}

impl TransportPosition {
    /// Query to see if the BarBeatsTick data is valid.
    pub fn valid_bbt(&self) -> bool {
        (self.0.valid & j::JackPositionBBT) != 0
    }

    /// Query to see if the frame offset of BarBeatsTick data is valid.
    pub fn valid_bbt_frame_offset(&self) -> bool {
        (self.0.valid & j::JackBBTFrameOffset) != 0
    }

    /*
    /// Query to see if the Timecode data is valid.
    pub fn valid_timecode(&self) -> bool {
        (self.0.valid & j::JackPositionTimecode) != 0
    }

    /// Query to see if the Audio/Video ratio is valid.
    pub fn valid_avr(&self) -> bool {
        (self.0.valid & j::JackAudioVideoRatio) != 0
    }

    /// Query to see if the Video frame offset is valid.
    pub fn valid_video_frame_offset(&self) -> bool {
        (self.0.valid & j::JackVideoFrameOffset) != 0
    }
    */

    /// Get the frame number on the transport timeline.
    ///
    /// # Remarks
    /// * This is not the same as what jack_frame_time returns.
    pub fn frame(&self) -> Frames {
        self.0.frame
    }

    /// Set the frame number on the transport timeline.
    pub fn set_frame(&mut self, frame: Frames) {
        self.0.frame = frame;
    }

    /// Get the current frame rate, in frames per second.
    ///
    /// # Remarks
    /// * This is only set by the server so it will be `None` if this struct hasn't come from the
    /// sever.
    pub fn frame_rate(&self) -> Option<Frames> {
        if self.0.frame_rate > 0 {
            Some(self.0.frame_rate)
        } else {
            None
        }
    }

    /// Get a microsecond timestamp.
    ///
    /// # Remarks
    /// * This is only set by the server so it will be `None` if this struct hasn't come from the
    /// sever.
    /// * Guaranteed to be monotonic, but not necessarily linear.
    /// * The absolute value is implementation-dependent (i.e. it could be wall-clock, time since
    /// jack started, uptime, etc).
    pub fn usecs(&self) -> Option<Time> {
        // NOTE could it actually be 0 and come from the server?
        if self.0.usecs > 0 {
            Some(self.0.usecs)
        } else {
            None
        }
    }

    /// Get the BarBeatsTick data if it is valid.
    pub fn bbt(&self) -> Option<TransportBBT> {
        if self.valid_bbt() {
            TransportBBT {
                bar: self.0.bar as _,
                beat: self.0.beat as _,
                tick: self.0.tick as _,
                sig_num: self.0.beats_per_bar,
                sig_denom: self.0.beat_type,
                ticks_per_beat: self.0.ticks_per_beat,
                bpm: self.0.beats_per_minute,
                bar_start_tick: self.0.bar_start_tick,
            }
            .validated()
            .ok()
        } else {
            None
        }
    }

    /// Set the BarBeatsTick data in this position.
    ///
    /// # Arguments
    /// * `bbt` - The data to set in the position. `None` will invalidate the BarBeatsTick data.
    ///
    /// # Remarks
    /// * If the bbt does not validate, will leave the pre-existing data intact.
    pub fn set_bbt(
        &mut self,
        bbt: Option<TransportBBT>,
    ) -> std::result::Result<(), TransportBBTValidationError> {
        match bbt {
            None => {
                self.0.valid &= !j::JackPositionBBT;
                Ok(())
            }
            Some(bbt) => match bbt.validated() {
                Ok(bbt) => {
                    self.0.bar = bbt.bar as _;
                    self.0.beat = bbt.beat as _;
                    self.0.tick = bbt.tick as _;
                    self.0.beats_per_bar = bbt.sig_num;
                    self.0.beat_type = bbt.sig_denom;
                    self.0.ticks_per_beat = bbt.ticks_per_beat;
                    self.0.beats_per_minute = bbt.bpm;
                    self.0.bar_start_tick = bbt.bar_start_tick;
                    self.0.valid |= j::JackPositionBBT;
                    Ok(())
                }
                Err(e) => Err(e),
            },
        }
    }

    /// Get the frame offset for the BBT fields.
    ///
    /// # Remarks
    ///
    /// * Should be assumed to be 0 if `None`.
    /// * If this value is Some(0), the bbt time refers to the first frame of this cycle.
    /// * Otherwise, the bbt time refers to a frame that many frames **before** the start of the cycle.
    pub fn bbt_offset(&self) -> Option<Frames> {
        if self.valid_bbt_frame_offset() {
            Some(self.0.bbt_offset)
        } else {
            None
        }
    }

    /// Set the frame offset for the BBT fields.
    ///
    /// # Arguments
    /// * `frame` - The value to set to the offset. `None` will invalidate the offset data.
    ///
    /// # Remarks
    ///
    /// * If this value is 0, the bbt time refers to the first frame of this cycle.
    /// * Otherwise, the bbt time refers to a frame that many frames **before** the start of the cycle.
    pub fn set_bbt_offset(&mut self, frame: Option<Frames>) -> std::result::Result<(), Frames> {
        match frame {
            None => {
                self.0.valid &= !j::JackBBTFrameOffset;
                Ok(())
            }
            Some(frame) => {
                self.0.bbt_offset = frame;
                self.0.valid |= j::JackBBTFrameOffset;
                Ok(())
            }
        }
    }
}

impl std::fmt::Debug for TransportPosition {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let mut s = f.debug_struct("TransportPosition");
        let unique_1 = self.0.unique_1;
        let usecs = self.0.usecs;
        let frame = self.0.frame;
        let frame_rate = self.0.frame_rate;
        let valid = self.0.valid != 0;
        let mut d = s
            .field("unique_1", &unique_1)
            .field("usecs", &usecs)
            .field("frame", &frame)
            .field("frame_rate", &frame_rate)
            .field("valid", &valid);
        if let Some(bbt) = self.bbt() {
            d = d.field("bbt", &bbt);
        }
        d.finish()
    }
}

impl TransportBBT {
    /// Set bar, beat, tick
    ///
    /// # Example
    /// ```
    /// use jack::TransportBBT;
    /// let bbt = TransportBBT::default().with_bbt(4, 2, 14).validated();
    /// assert!(bbt.is_ok());
    /// let bbt = bbt.unwrap();
    /// assert_eq!(bbt.bar, 4);
    /// assert_eq!(bbt.beat, 2);
    /// assert_eq!(bbt.tick, 14);
    /// ```
    pub fn with_bbt(&'_ mut self, bar: usize, beat: usize, tick: usize) -> &'_ mut Self {
        self.bar = bar;
        self.beat = beat;
        self.tick = tick;
        self
    }

    /// Set Beats Per Minute.
    pub fn with_bpm(&'_ mut self, bpm: f64) -> &'_ mut Self {
        self.bpm = bpm;
        self
    }

    /// Set the time signature.
    pub fn with_timesig(&'_ mut self, num: f32, denom: f32) -> &'_ mut Self {
        self.sig_num = num;
        self.sig_denom = denom;
        self
    }

    /// Set ticks per beat.
    pub fn with_ticks_per_beat(&'_ mut self, ticks_per_beat: f64) -> &'_ mut Self {
        self.ticks_per_beat = ticks_per_beat;
        self
    }

    /// Set bar start tick.
    pub fn with_bar_start_tick(&'_ mut self, tick: f64) -> &'_ mut Self {
        self.bar_start_tick = tick;
        self
    }

    /// Validate contents.
    pub fn validated(&'_ self) -> std::result::Result<Self, TransportBBTValidationError> {
        if self.bar == 0 {
            Err(TransportBBTValidationError::BarZero)
        } else if self.beat == 0 || self.beat > self.sig_num.ceil() as _ {
            Err(TransportBBTValidationError::BeatRange)
        } else if self.ticks_per_beat <= 0. {
            Err(TransportBBTValidationError::TicksPerBeatRange)
        } else if self.sig_num <= 0. {
            Err(TransportBBTValidationError::SigNumRange)
        } else if self.sig_denom <= 0. {
            Err(TransportBBTValidationError::SigDenomRange)
        } else if self.bpm < 0. {
            Err(TransportBBTValidationError::BPMRange)
        } else if self.tick >= self.ticks_per_beat.ceil() as _ {
            Err(TransportBBTValidationError::TickRange)
        } else {
            Ok(*self)
        }
    }

    pub fn valid(&self) -> bool {
        self.validated().is_ok()
    }
}

impl Default for TransportPosition {
    fn default() -> Self {
        //safe to zero
        unsafe { std::mem::MaybeUninit::zeroed().assume_init() }
    }
}

impl Default for TransportBBT {
    fn default() -> Self {
        Self {
            bar: 1,
            beat: 1,
            tick: 0,
            sig_num: 4.,
            sig_denom: 4.,
            ticks_per_beat: 1920.,
            bpm: 120.,
            bar_start_tick: 0.,
        }
    }
}

#[cfg(test)]
mod test {
    mod position {
        use crate::{TransportBBT, TransportPosition};
        #[test]
        fn default() {
            let p: TransportPosition = Default::default();
            assert!(!p.valid_bbt());
            assert!(!p.valid_bbt_frame_offset());
            assert_eq!(p.frame(), 0);
            assert_eq!(p.bbt(), None);
            assert_eq!(p.bbt_offset(), None);
            assert_eq!(p.frame_rate(), None);
            assert_eq!(p.usecs(), None);
        }

        #[test]
        fn usecs() {
            let mut p: TransportPosition = Default::default();
            assert_eq!(p.usecs(), None);
            p.0.usecs = 1;
            assert_eq!(p.usecs(), Some(1));
            p.0.usecs = 0;
            assert_eq!(p.usecs(), None);
            p.0.usecs = 2084;
            assert_eq!(p.usecs(), Some(2084));
        }

        #[test]
        fn frame_rate() {
            let mut p: TransportPosition = Default::default();
            assert_eq!(p.frame_rate(), None);
            p.0.frame_rate = 44100;
            assert_eq!(p.frame_rate(), Some(44100));
            p.0.frame_rate = 0;
            assert_eq!(p.frame_rate(), None);
            p.0.frame_rate = 48000;
            assert_eq!(p.frame_rate(), Some(48000));
        }

        #[test]
        fn bbt_invalid() {
            let mut i: TransportPosition = Default::default();
            let mut v: TransportPosition = Default::default();
            let def: TransportBBT = Default::default();

            assert!(!i.valid_bbt());
            assert_eq!(i.set_bbt(None), Ok(()));
            assert!(!i.valid_bbt());

            assert!(!v.valid_bbt());
            assert_eq!(v.set_bbt(Some(def)), Ok(()));
            assert_eq!(v.bbt(), Some(def));

            let mut t = |b| {
                assert!(i.set_bbt(Some(b)).is_err());
                assert!(v.set_bbt(Some(b)).is_err());
                assert!(!i.valid_bbt());
                assert!(v.valid_bbt());
                assert_eq!(i.bbt(), None);
                assert_eq!(v.bbt(), Some(def));
            };

            let mut bbt = TransportBBT {
                bar: 0,
                ..Default::default()
            };
            t(bbt);

            bbt = Default::default();
            bbt.beat = 0;
            t(bbt);

            bbt.beat = 5;
            t(bbt);

            bbt = Default::default();
            bbt.tick = 1921;
            t(bbt);
            bbt.tick = 1920;
            t(bbt);

            bbt = Default::default();
            bbt.bpm = -1.0;
            t(bbt);

            bbt = Default::default();
            bbt.ticks_per_beat = -1.0;
            t(bbt);
            bbt.ticks_per_beat = 0.0;
            t(bbt);

            bbt = Default::default();
            bbt.sig_num = 0.0;
            t(bbt);
            bbt.sig_num = -1.0;
            t(bbt);

            bbt = Default::default();
            bbt.sig_denom = 0.0;
            t(bbt);
            bbt.sig_denom = -1.0;
            t(bbt);

            bbt = Default::default();
            bbt.sig_num = 7.0;
            bbt.beat = 8;
            t(bbt);

            bbt = Default::default();
            bbt.ticks_per_beat = 96.0;
            bbt.tick = 96;
            t(bbt);
        }

        #[test]
        fn bbt_valid() {
            let mut p: TransportPosition = Default::default();
            let mut b: TransportBBT = Default::default();
            let i = TransportBBT {
                beat: 5, //invalid
                ..Default::default()
            };

            assert!(!i.valid());

            assert!(!p.valid_bbt());
            assert_eq!(p.set_bbt(Some(b)), Ok(()));
            assert!(p.valid_bbt());
            assert_eq!(p.bbt(), Some(b));

            let mut t = |b: TransportBBT| {
                assert!(b.valid());
                assert_eq!(p.set_bbt(Some(b)), Ok(()));
                assert_eq!(p.bbt(), Some(b));
                assert!(p.set_bbt(Some(i)).is_err());
                assert_eq!(p.bbt(), Some(b));
            };

            for i in 1..10 {
                b.bar = i;
                t(b);
            }

            for i in 1..=4 {
                b.beat = i;
                t(b);
            }

            b.sig_num = 7.;
            for i in 1..=7 {
                b.beat = i;
                t(b);
            }

            b.beat = 1;
            b.sig_num = 4.;
            b.ticks_per_beat = 96.0;
            for i in 0..96 {
                b.tick = i;
                t(b);
            }

            for i in (10..300).step_by(7) {
                b.bpm = i as _;
                t(b);
            }
        }
    }
    mod bbt {
        use crate::{TransportBBT, TransportBBTValidationError};

        fn approx_eq(a: f32, b: f32) -> bool {
            (a - b).abs() < f32::EPSILON
        }

        #[test]
        fn default() {
            let bbt: TransportBBT = Default::default();
            assert_eq!(bbt.bar, 1);
            assert_eq!(bbt.beat, 1);
            assert_eq!(bbt.tick, 0);
            assert!(approx_eq(bbt.sig_num, 4.0), "{} != {}", bbt.sig_num, 4.0);
            assert!(
                approx_eq(bbt.sig_denom, 4.0),
                "{} != {}",
                bbt.sig_denom,
                4.0
            );
            assert!(
                approx_eq(bbt.ticks_per_beat as f32, 1920.0),
                "{} != {}",
                bbt.ticks_per_beat,
                1920.0
            );
            assert!(approx_eq(bbt.bpm as f32, 120.0), "{} != {}", bbt.bpm, 120.0);
            assert!(
                approx_eq(bbt.bar_start_tick as f32, 0.0),
                "{} != {}",
                bbt.bar_start_tick,
                0.0
            );
        }

        #[test]
        fn builder_valid() {
            let mut bbt = TransportBBT::default();
            assert_eq!(
                TransportBBT::default().with_bbt(1, 1, 0).validated(),
                Ok(bbt)
            );

            bbt.bar = 100;
            bbt.beat = 2;
            bbt.tick = 230;
            assert_eq!(
                TransportBBT::default().with_bbt(100, 2, 230).validated(),
                Ok(bbt)
            );

            bbt = Default::default();
            bbt.sig_num = 7.0;
            bbt.sig_denom = 8.0;
            assert_eq!(
                TransportBBT::default().with_timesig(7.0, 8.0).validated(),
                Ok(bbt)
            );

            bbt = Default::default();
            bbt.ticks_per_beat = 2000.0;
            assert_eq!(
                TransportBBT::default()
                    .with_ticks_per_beat(2000.0)
                    .validated(),
                Ok(bbt)
            );

            bbt = Default::default();
            bbt.bar_start_tick = 1023.0;
            assert_eq!(
                TransportBBT::default()
                    .with_bar_start_tick(1023.0)
                    .validated(),
                Ok(bbt)
            );

            bbt = Default::default();
            bbt.bar = 2;
            bbt.beat = 3;
            bbt.tick = 20;
            bbt.bpm = 23.0;
            bbt.ticks_per_beat = 96.0;
            bbt.sig_num = 12.0;
            bbt.sig_denom = 5.0;
            bbt.bar_start_tick = 4.3;

            assert_eq!(
                TransportBBT::default()
                    .with_bbt(bbt.bar, bbt.beat, bbt.tick)
                    .with_bpm(bbt.bpm)
                    .with_ticks_per_beat(bbt.ticks_per_beat)
                    .with_timesig(bbt.sig_num, bbt.sig_denom)
                    .with_bar_start_tick(bbt.bar_start_tick)
                    .validated(),
                Ok(bbt)
            );

            //can simply use setters, could create invalid data..
            bbt = TransportBBT::default();
            bbt.with_bpm(120.0);
            assert!(
                approx_eq(bbt.bpm as f32, 120.0),
                "{} != {},",
                bbt.bpm,
                120.0
            );
        }

        #[test]
        fn builder_invalid() {
            let mut bbt = TransportBBT {
                bpm: -1023.0,
                ..TransportBBT::default()
            };
            assert_eq!(
                TransportBBT::default().with_bpm(bbt.bpm).validated(),
                Err(TransportBBTValidationError::BPMRange)
            );

            bbt = Default::default();
            bbt.bar = 0;
            assert_eq!(
                TransportBBT::default().with_bbt(0, 1, 0).validated(),
                Err(TransportBBTValidationError::BarZero)
            );

            bbt = Default::default();
            bbt.tick = bbt.ticks_per_beat as usize;
            assert_eq!(
                TransportBBT::default().with_bbt(1, 1, bbt.tick).validated(),
                Err(TransportBBTValidationError::TickRange)
            );

            for beat in &[0, 7] {
                bbt = Default::default();
                bbt.beat = *beat;
                assert_eq!(
                    TransportBBT::default().with_bbt(1, bbt.beat, 0).validated(),
                    Err(TransportBBTValidationError::BeatRange)
                );
            }
        }
    }
}