2
* Copyright (C) 2005-2008 by Pieter Palmers
3
* Copytight (C) 2012 by Jonathan Woithe
5
* This file is part of FFADO
6
* FFADO = Free Firewire (pro-)audio drivers for linux
8
* FFADO is based upon FreeBoB.
10
* This program is free software: you can redistribute it and/or modify
11
* it under the terms of the GNU General Public License as published by
12
* the Free Software Foundation, either version 2 of the License, or
13
* (at your option) version 3 of the License.
15
* This program is distributed in the hope that it will be useful,
16
* but WITHOUT ANY WARRANTY; without even the implied warranty of
17
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18
* GNU General Public License for more details.
20
* You should have received a copy of the GNU General Public License
21
* along with this program. If not, see <http://www.gnu.org/licenses/>.
25
#include "SystemTimeSource.h"
28
// needed for clock_nanosleep
36
DECLARE_GLOBAL_DEBUG_MODULE;
40
static clockid_t clock_id = CLOCK_REALTIME;
43
SystemTimeSource::setSource(clockid_t id)
46
// Determine at runtime whether the kernel has support for the
47
// requested clock source.
48
if (clock_gettime(id, &tp) == 0) {
56
SystemTimeSource::getSource(void)
62
SystemTimeSource::clockGettime(struct timespec *tp)
64
return clock_gettime(clock_id, tp);
68
SystemTimeSource::SleepUsecRelative(ffado_microsecs_t usecs)
72
ts.tv_sec = usecs / (1000000LL);
73
ts.tv_nsec = (usecs % (1000000LL)) * 1000LL;
74
clock_nanosleep(clock_id, 0, &ts, NULL);
78
SystemTimeSource::SleepUsecAbsolute(ffado_microsecs_t wake_at_usec)
80
#if USE_ABSOLUTE_NANOSLEEP
82
ts.tv_sec = wake_at_usec / (1000000LL);
83
ts.tv_nsec = (wake_at_usec % (1000000LL)) * 1000LL;
84
debugOutputExtreme(DEBUG_LEVEL_VERBOSE,
85
"clock_nanosleep until %"PRId64" sec, %"PRId64" nanosec\n",
86
(int64_t)ts.tv_sec, (int64_t)ts.tv_nsec);
87
int err = clock_nanosleep(clock_id, TIMER_ABSTIME, &ts, NULL);
89
// maybe signal occurred, but we're going to ignore that
91
debugOutputExtreme(DEBUG_LEVEL_VERBOSE,
95
// only sleep if needed
96
ffado_microsecs_t now = getCurrentTime();
97
if(wake_at_usec >= now) {
98
ffado_microsecs_t to_sleep = wake_at_usec - now;
99
SleepUsecRelative(to_sleep);
105
SystemTimeSource::SleepUsecRandom(ffado_microsecs_t max_usec)
107
long int rnd = random();
108
long long int tmp = (rnd*max_usec);
110
ffado_microsecs_t usec = tmp;
111
SleepUsecRelative(usec);
116
SystemTimeSource::getCurrentTime()
118
return getCurrentTimeAsUsecs();
122
SystemTimeSource::getCurrentTimeAsUsecs()
125
clock_gettime(clock_id, &ts);
126
return (ffado_microsecs_t)(ts.tv_sec * 1000000LL + ts.tv_nsec / 1000LL);
129
} // end of namespace Util