Timer.cxx 1.82 KB
Newer Older
1
/*
2
 * Copyright (C) 2003-2013 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 <glib.h>

27 28
#include <limits>

29 30
#include <assert.h>
#include <limits.h>
31
#include <stddef.h>
32

33
Timer::Timer(const AudioFormat af)
34 35
	: time(0),
	  started(false),
36
	 rate(af.sample_rate * af.GetFrameSize())
37 38 39
{
}

40
void Timer::Start()
41
{
42
	time = MonotonicClockUS();
43
	started = true;
44 45
}

46
void Timer::Reset()
47
{
48 49
	time = 0;
	started = false;
50 51
}

52
void Timer::Add(int size)
53
{
54
	assert(started);
55

56 57
	// (size samples) / (rate samples per second) = duration seconds
	// duration seconds * 1000000 = duration us
58
	time += ((uint64_t)size * 1000000) / rate;
59 60
}

61
unsigned Timer::GetDelay() const
62
{
63
	int64_t delay = (int64_t)(time - MonotonicClockUS()) / 1000;
64 65 66
	if (delay < 0)
		return 0;

67 68
	if (delay > std::numeric_limits<int>::max())
		delay = std::numeric_limits<int>::max();
69

70
	return delay;
71 72
}

73
void Timer::Synchronize() const
74
{
Max Kellermann's avatar
Max Kellermann committed
75
	int64_t sleep_duration;
76

77
	assert(started);
78

79
	sleep_duration = time - MonotonicClockUS();
Max Kellermann's avatar
Max Kellermann committed
80
	if (sleep_duration > 0)
81
		g_usleep(sleep_duration);
82
}