mpd/src/Timer.cxx

81 lines
1.8 KiB
C++
Raw Normal View History

/*
2011-01-29 10:13:54 +01:00
* Copyright (C) 2003-2011 The Music Player Daemon Project
* http://www.musicpd.org
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include "config.h"
2013-05-12 15:03:42 +02:00
#include "Timer.hxx"
2013-08-03 21:00:50 +02:00
#include "AudioFormat.hxx"
2013-10-15 09:38:12 +02:00
#include "system/Clock.hxx"
2009-01-03 14:52:53 +01:00
#include <glib.h>
#include <assert.h>
#include <limits.h>
2009-01-03 14:52:53 +01:00
#include <stddef.h>
2013-08-03 21:00:50 +02:00
Timer::Timer(const AudioFormat af)
2013-05-12 15:03:42 +02:00
: time(0),
started(false),
2013-08-03 21:00:50 +02:00
rate(af.sample_rate * af.GetFrameSize())
{
}
2013-05-12 15:03:42 +02:00
void Timer::Start()
{
2013-10-15 09:38:12 +02:00
time = MonotonicClockUS();
2013-05-12 15:03:42 +02:00
started = true;
}
2013-05-12 15:03:42 +02:00
void Timer::Reset()
{
2013-05-12 15:03:42 +02:00
time = 0;
started = false;
}
2013-05-12 15:03:42 +02:00
void Timer::Add(int size)
{
2013-05-12 15:03:42 +02:00
assert(started);
// (size samples) / (rate samples per second) = duration seconds
// duration seconds * 1000000 = duration us
2013-05-12 15:03:42 +02:00
time += ((uint64_t)size * 1000000) / rate;
}
2013-05-12 15:03:42 +02:00
unsigned Timer::GetDelay() const
2010-11-05 09:39:50 +01:00
{
2013-10-15 09:38:12 +02:00
int64_t delay = (int64_t)(time - MonotonicClockUS()) / 1000;
2010-11-05 09:39:50 +01:00
if (delay < 0)
return 0;
if (delay > G_MAXINT)
delay = G_MAXINT;
2010-11-05 09:39:50 +01:00
return delay;
2010-11-05 09:39:50 +01:00
}
2013-05-12 15:03:42 +02:00
void Timer::Synchronize() const
{
int64_t sleep_duration;
2013-05-12 15:03:42 +02:00
assert(started);
2013-10-15 09:38:12 +02:00
sleep_duration = time - MonotonicClockUS();
if (sleep_duration > 0)
g_usleep(sleep_duration);
}