timer.c 1.94 KB
Newer Older
1
/*
Max Kellermann's avatar
Max Kellermann committed
2
 * Copyright (C) 2003-2011 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.h"
22
#include "audio_format.h"
23
#include "clock.h"
24

25 26
#include <glib.h>

27 28
#include <assert.h>
#include <limits.h>
29
#include <stddef.h>
30

31
struct timer *timer_new(const struct audio_format *af)
32
{
33
	struct timer *timer = g_new(struct timer, 1);
34 35
	timer->time = 0;
	timer->started = 0;
36
	timer->rate = af->sample_rate * audio_format_frame_size(af);
37 38 39 40

	return timer;
}

41
void timer_free(struct timer *timer)
42
{
43
	g_free(timer);
44 45
}

46
void timer_start(struct timer *timer)
47
{
48
	timer->time = monotonic_clock_us();
49 50 51
	timer->started = 1;
}

52
void timer_reset(struct timer *timer)
53 54 55 56 57
{
	timer->time = 0;
	timer->started = 0;
}

58
void timer_add(struct timer *timer, int size)
59 60 61 62 63 64
{
	assert(timer->started);

	timer->time += ((uint64_t)size * 1000000) / timer->rate;
}

65
unsigned
66
timer_delay(const struct timer *timer)
67
{
68
	int64_t delay = (int64_t)(timer->time - monotonic_clock_us()) / 1000;
69 70 71
	if (delay < 0)
		return 0;

72 73
	if (delay > G_MAXINT)
		delay = G_MAXINT;
74

75
	return delay;
76 77
}

78
void timer_sync(struct timer *timer)
79
{
Max Kellermann's avatar
Max Kellermann committed
80
	int64_t sleep_duration;
81 82 83

	assert(timer->started);

84
	sleep_duration = timer->time - monotonic_clock_us();
Max Kellermann's avatar
Max Kellermann committed
85
	if (sleep_duration > 0)
86
		g_usleep(sleep_duration);
87
}