2 * Copyright (C) 2015 Tim Mayberry <mojofunk@gmail.com>
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 2 of the License, or
7 * (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
26 // Could call it FrameTimer and make it more generic
27 // Could be an interface and or include clock source
28 // include sample count/processed frames in iteration?
34 , m_samples_per_cycle (0)
38 void set_samplerate (double samplerate) { m_samplerate = samplerate; }
40 double get_samplerate () const { return m_samplerate; }
42 double get_sample_length_us () const { return 1e6 / m_samplerate; }
44 double get_length_us () const
46 return get_sample_length_us () * m_samples_per_cycle;
49 void set_samples_per_cycle (uint32_t samples)
51 m_samples_per_cycle = samples;
54 uint32_t get_samples_per_cycle () const { return m_samples_per_cycle; }
56 // rint?? that may round to sample outside of cycle?
58 uint32_t samples_since_cycle_start (int64_t timer_val) const
60 if (timer_val < m_cycle_start) {
63 return std::max((double)0, (timer_val - get_start ()) / get_sample_length_us ());
66 int64_t timestamp_from_sample_offset (uint32_t sample_offset)
68 return m_cycle_start + get_sample_length_us () * sample_offset;
71 bool valid () const { return m_samples_per_cycle && m_samplerate; }
73 bool in_cycle(int64_t timer_value_us) const
75 return (timer_value_us >= get_start()) && (timer_value_us < get_next_start());
78 void reset_start (int64_t timestamp) { m_cycle_start = timestamp; }
80 int64_t get_start () const { return m_cycle_start; }
82 int64_t microseconds_since_start (int64_t timestamp) const
84 return timestamp - m_cycle_start;
87 int64_t microseconds_since_start (uint32_t samples) const
89 return m_cycle_start + samples * get_sample_length_us ();
92 int64_t get_next_start () const
94 return m_cycle_start + rint (get_length_us ());
98 int64_t m_cycle_start;
100 uint32_t m_samplerate;
101 uint32_t m_samples_per_cycle;
104 #endif // CYCLE_TIMER_H