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
use core::fmt::Display;

use num_traits::{FromPrimitive, ToPrimitive, Zero};

use crate::ltc_decoder::bit_decoder::{BitDecoder, BitVal};
use crate::ltc_frame::LtcFrame;
use crate::TimecodeFrame;

mod bit_decoder;

//pub trait Sample: Copy + Zero + std::ops::Div<f64>+ FromPrimitive + Ord + Sync + Send + 'static {}
//pub trait Sample: Zero + Ord + Clone + Copy + 'static {}

pub trait Sample: Zero + Ord + Clone + Copy + FromPrimitive + ToPrimitive + Display + 'static {}

impl<T> Sample for T where T: Zero + Ord + Clone + Copy + FromPrimitive + ToPrimitive + Display + 'static {}

pub struct LtcDecoder<T: Sample> {
    ltc_frame: LtcFrame,
    bit_decoder: BitDecoder<T>,
    sampling_rate: f32,
}

impl<T: Sample> LtcDecoder<T> {
    pub fn new<S: ToPrimitive>(sampling_rate: S) -> Self {
        Self {
            ltc_frame: LtcFrame::new_empty(),
            bit_decoder: BitDecoder::new(),
            sampling_rate: sampling_rate.to_f32().expect("Invalid sampling rate"),
        }
    }
}

impl<T: Sample> LtcDecoder<T> {
    /// Push received audio-sample-point one after another in this function. From time to time
    /// a Timecode-Frame will be returned to tell the current received timecode
    pub fn get_timecode_frame(&mut self, sample: T) -> Option<TimecodeFrame> {
        self.ltc_frame.sample_received();
        match self.bit_decoder.get_bit(sample) {
            BitVal::None => { return None; }
            BitVal::Invalid => {
                self.invalidate();
                return None;
            }
            BitVal::True => { self.ltc_frame.shift_bit(true); }
            BitVal::False => { self.ltc_frame.shift_bit(false); }
        }
        if let Some((data, samples_for_frame)) = self.ltc_frame.get_data() {
            Some(data.make_ltc_frame(self.sample_count_to_duration_s(samples_for_frame)))
        } else {
            None
        }
    }
    fn sample_count_to_duration_s(&self, sample_count: usize) -> f32 {
        (sample_count as f32) / self.sampling_rate
    }

    /// In case some unexpected data is received, this function invalidates the decoder to restart
    /// synchronizing on the heartbeat of the data
    fn invalidate(&mut self) {
        self.ltc_frame.invalidate();
        self.bit_decoder.invalidate();
    }
}

#[cfg(test)]
mod tests {
    use core::ops::Shl;
    use std::fs::File;
    use std::io;
    use std::io::Read;

    use num_traits::Zero;
    use wav::BitDepth;

    use crate::ltc_decoder::{LtcDecoder, Sample};
    use crate::{TimecodeFrame};
    use crate::FramesPerSecond::{Thirty, TwentyFive, TwentyFour};

    #[test]
    fn test_sample_trait() {
        test_zero(0_i64);
        test_zero(0_i32);
        test_zero(0_i16);
        test_zero(0_i8);
        test_zero(0_u64);
        test_zero(0_u32);
        test_zero(0_u16);
        test_zero(0_u8);

        test_ord(0_i64);
        test_ord(0_i32);
        test_ord(0_i16);
        test_ord(0_i8);
        test_ord(0_u64);
        test_ord(0_u32);
        test_ord(0_u16);
        test_ord(0_u8);

        test_clone(0_i64);
        test_clone(0_i32);
        test_clone(0_i16);
        test_clone(0_i8);
        test_clone(0_u64);
        test_clone(0_u32);
        test_clone(0_u16);
        test_clone(0_u8);

        test_copy(0_i64);
        test_copy(0_i32);
        test_copy(0_i16);
        test_copy(0_i8);
        test_copy(0_u64);
        test_copy(0_u32);
        test_copy(0_u16);
        test_copy(0_u8);

        test_shl(0_i64);
        test_shl(0_i32);
        test_shl(0_i16);
        test_shl(0_i8);
        test_shl(0_u64);
        test_shl(0_u32);
        test_shl(0_u16);
        test_shl(0_u8);

        test_sample(0_i64);
        test_sample(0_i32);
        test_sample(0_i16);
        test_sample(0_i8);
        test_sample(0_u64);
        test_sample(0_u32);
        test_sample(0_u16);
        test_sample(0_u8);
    }

    fn test_zero<T: Zero>(_s: T) {
        assert!(true);
    }

    fn test_ord<T: Ord>(_s: T) {
        assert!(true);
    }

    fn test_clone<T: Clone>(_s: T) {
        assert!(true);
    }

    fn test_copy<T: Copy>(_s: T) {
        assert!(true);
    }

    fn test_sample<T: Sample>(_s: T) {
        assert!(true);
    }

    fn test_shl<T: Shl>(_s: T) {
        assert!(true);
    }

    #[test]
    fn test_ltc_00100000_2mins_25fps_44100x8() {
        test_timecode_file("testfiles/LTC_00100000_2mins_25fps_44100x8.wav",
                           TimecodeFrame::new(0, 10, 0, 1, TwentyFive),
                           TimecodeFrame::new(0, 12, 1, 0, TwentyFive))
    }


    #[test]
    fn test_ltc_00500000_2mins_30fps_44100x8() {
        test_timecode_file("testfiles/LTC_00500000_2mins_30fps_44100x8.wav",
                           TimecodeFrame::new(0, 50, 0, 1, Thirty),
                           TimecodeFrame::new(0, 52, 1, 0, Thirty))
    }

    #[test]
    fn test_ltc_10000000_2mins_24fps_44100x16() {
        test_timecode_file("testfiles/LTC_10000000_2mins_24fps_44100x16.wav",
                           TimecodeFrame::new(10, 0, 0, 1, TwentyFour),
                           TimecodeFrame::new(10, 2, 1, 0, TwentyFour))
    }

    #[test]
    fn test_ltc_10100000_2mins_25fps_44100x16() {
        test_timecode_file("testfiles/LTC_10100000_2mins_25fps_44100x16.wav",
                           TimecodeFrame::new(10, 10, 0, 1, TwentyFive),
                           TimecodeFrame::new(10, 12, 1, 0, TwentyFive))
    }

    #[test]
    fn test_ltc_10400000_2mins_30fps_44100x16() {
        test_timecode_file("testfiles/LTC_10400000_2mins_30fps_44100x16.wav",
                           TimecodeFrame::new(10, 40, 0, 1, Thirty),
                           TimecodeFrame::new(10, 42, 1, 0, Thirty))
    }

    #[test]
    fn test_ltc_10500000_2mins_24fps_48000x16() {
        test_timecode_file("testfiles/LTC_10500000_2mins_24fps_48000x16.wav",
                           TimecodeFrame::new(10, 50, 0, 1, TwentyFour),
                           TimecodeFrame::new(10, 52, 1, 0, TwentyFour))
    }

    #[test]
    fn test_ltc_11000000_2mins_25fps_48000x16() {
        test_timecode_file("testfiles/LTC_11000000_2mins_25fps_48000x16.wav",
                           TimecodeFrame::new(11, 0, 0, 1, TwentyFive),
                           TimecodeFrame::new(11, 2, 1, 0, TwentyFive))
    }

    #[test]
    fn test_ltc_11300000_2mins_30fps_48000x16() {
        test_timecode_file("testfiles/LTC_11300000_2mins_30fps_48000x16.wav",
                           TimecodeFrame::new(11, 30, 0, 1, Thirty),
                           TimecodeFrame::new(11, 32, 1, 0, Thirty))
    }

    #[test]
    fn test_ltc_11400000_2mins_24fps_44100x16() {
        test_timecode_file("testfiles/LTC_11400000_2mins_24fps_44100x16.wav",
                           TimecodeFrame::new(11, 40, 0, 1, TwentyFour),
                           TimecodeFrame::new(11, 42, 1, 0, TwentyFour))
    }

    #[test]
    fn test_ltc_11500000_2mins_25fps_44100x16() {
        test_timecode_file("testfiles/LTC_11500000_2mins_25fps_44100x16.wav",
                           TimecodeFrame::new(11, 50, 0, 1, TwentyFive),
                           TimecodeFrame::new(11, 52, 1, 0, TwentyFive))
    }

    #[test]
    fn test_ltc_12200000_2mins_30fps_44100x16() {
        test_timecode_file("testfiles/LTC_12200000_2mins_30fps_44100x16.wav",
                           TimecodeFrame::new(12, 20, 0, 1, Thirty),
                           TimecodeFrame::new(12, 22, 1, 0, Thirty))
    }


    /// runs a test on decoding timecode sample by sample with specifing the first expected decoded
    /// Frame (usually 1 frame above the start of the audio, because the lib needs some tim to sync)
    /// and the last expected decoded Frame
    fn test_timecode_file(file: &str, first_tc: TimecodeFrame, last_tc: TimecodeFrame) {
        let mut file = File::open(file).expect("File not found");
        let (sampling_rate, data) = get_timecode_file_data(&mut file);
        match data {
            BitDepth::Eight(samples) => test_timecode_frames(sampling_rate, samples, first_tc, last_tc),
            BitDepth::Sixteen(samples) => test_timecode_frames(sampling_rate, samples, first_tc, last_tc),
            BitDepth::TwentyFour(samples) => test_timecode_frames(sampling_rate, samples, first_tc, last_tc),
            BitDepth::ThirtyTwoFloat(_) => panic!("Unsupported format"),
            BitDepth::Empty => panic!("File is empty")
        }
    }

    /// runs a test on decoding timecode sample by sample with specifing the first expected decoded
    /// Frame (usually 1 frame above the start of the audio, because the lib needs some tim to sync)
    /// and the last expected decoded Frame
    fn test_timecode_frames<T: Sample>(sampling_rate: u32, samples: Vec<T>, first_tc: TimecodeFrame, last_tc: TimecodeFrame) {
        let mut decoder = LtcDecoder::<T>::new(sampling_rate);
        let mut timecode = first_tc.clone();
        for sample in samples {
            if let Some(tc) = decoder.get_timecode_frame(sample) {
                assert_eq!(tc, timecode);
                timecode.add_frame();
            }
        }
        assert_eq!(timecode, last_tc);
    }

    /// Returns sample rate and data from a wav file that contains timecode data for testing
    fn get_timecode_file_data<R>(file: &mut R) -> (u32, BitDepth)
        where R: io::Seek + Read, {
        let (header, data) = wav::read(file).expect("could not open timecode file");
        let data = get_left_channel(header.channel_count, data);
        (header.sampling_rate, data)
    }

    /// Handles if a file is stereo
    fn get_left_channel(channel_count: u16, samples: BitDepth) -> BitDepth {
        if channel_count == 1 {
            return samples;
        }
        if channel_count > 2 {
            panic!("No more than two channels supported");
        }
        match samples {
            BitDepth::Eight(samples) => BitDepth::Eight(samples.iter().skip(1).step_by(2).copied().collect()),
            BitDepth::Sixteen(samples) => BitDepth::Sixteen(samples.iter().skip(1).step_by(2).copied().collect()),
            BitDepth::TwentyFour(samples) => BitDepth::TwentyFour(samples.iter().skip(1).step_by(2).copied().collect()),
            BitDepth::ThirtyTwoFloat(samples) => BitDepth::ThirtyTwoFloat(samples.iter().skip(1).step_by(2).copied().collect()),
            BitDepth::Empty => BitDepth::Empty
        }
    }
}