timer.c 2.04 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

24 25
#include <glib.h>

26 27 28
#include <assert.h>
#include <limits.h>
#include <sys/time.h>
29
#include <stddef.h>
30 31 32 33 34 35 36 37 38 39

static uint64_t now(void)
{
	struct timeval tv;

	gettimeofday(&tv, NULL);

	return ((uint64_t)tv.tv_sec * 1000000) + tv.tv_usec;
}

40
struct timer *timer_new(const struct audio_format *af)
41
{
42
	struct timer *timer = g_new(struct timer, 1);
43 44
	timer->time = 0;
	timer->started = 0;
45
	timer->rate = af->sample_rate * audio_format_frame_size(af);
46 47 48 49

	return timer;
}

50
void timer_free(struct timer *timer)
51
{
52
	g_free(timer);
53 54
}

55
void timer_start(struct timer *timer)
56
{
57
	timer->time = now();
58 59 60
	timer->started = 1;
}

61
void timer_reset(struct timer *timer)
62 63 64 65 66
{
	timer->time = 0;
	timer->started = 0;
}

67
void timer_add(struct timer *timer, int size)
68 69 70 71 72 73
{
	assert(timer->started);

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

74
unsigned
75
timer_delay(const struct timer *timer)
76
{
77
	int64_t delay = (int64_t)(timer->time - now()) / 1000;
78 79 80
	if (delay < 0)
		return 0;

81 82
	if (delay > G_MAXINT)
		delay = G_MAXINT;
83 84 85 86

	return delay / 1000;
}

87
void timer_sync(struct timer *timer)
88
{
Max Kellermann's avatar
Max Kellermann committed
89
	int64_t sleep_duration;
90 91 92

	assert(timer->started);

Max Kellermann's avatar
Max Kellermann committed
93 94
	sleep_duration = timer->time - now();
	if (sleep_duration > 0)
95
		g_usleep(sleep_duration);
96
}