Timer.cxx 1.58 KB
Newer Older
1
/*
2
 * Copyright 2003-2016 The Music Player Daemon Project
3
 * http://www.musicpd.org
4 5 6 7 8 9 10 11 12 13
 *
 * 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.
14 15 16 17
 *
 * 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.
18 19
 */

20
#include "config.h"
21
#include "Timer.hxx"
22
#include "AudioFormat.hxx"
23
#include "system/Clock.hxx"
24

25 26
#include <limits>

27
#include <assert.h>
28

29
Timer::Timer(const AudioFormat af)
30 31
	: time(0),
	  started(false),
32
	 rate(af.sample_rate * af.GetFrameSize())
33 34 35
{
}

36
void Timer::Start()
37
{
38
	time = MonotonicClockUS();
39
	started = true;
40 41
}

42
void Timer::Reset()
43
{
44 45
	time = 0;
	started = false;
46 47
}

48
void Timer::Add(int size)
49
{
50
	assert(started);
51

52 53
	// (size samples) / (rate samples per second) = duration seconds
	// duration seconds * 1000000 = duration us
54
	time += ((uint64_t)size * 1000000) / rate;
55 56
}

57
unsigned Timer::GetDelay() const
58
{
59
	int64_t delay = (int64_t)(time - MonotonicClockUS()) / 1000;
60 61 62
	if (delay < 0)
		return 0;

63 64
	if (delay > std::numeric_limits<int>::max())
		delay = std::numeric_limits<int>::max();
65

66
	return delay;
67
}