1/***
2  This file is part of PulseAudio.
3
4  Copyright 2009 Lennart Poettering
5
6  PulseAudio is free software; you can redistribute it and/or modify
7  it under the terms of the GNU Lesser General Public License as
8  published by the Free Software Foundation; either version 2.1 of the
9  License, or (at your option) any later version.
10
11  PulseAudio is distributed in the hope that it will be useful, but
12  WITHOUT ANY WARRANTY; without even the implied warranty of
13  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14  General Public License for more details.
15
16  You should have received a copy of the GNU Lesser General Public
17  License along with PulseAudio; if not, see <http://www.gnu.org/licenses/>.
18***/
19
20#ifdef HAVE_CONFIG_H
21#include <config.h>
22#endif
23
24#include <pulse/rtclock.h>
25
26#include <pulsecore/log.h>
27#include <pulsecore/mutex.h>
28
29#include "ratelimit.h"
30
31static pa_static_mutex mutex = PA_STATIC_MUTEX_INIT;
32
33/* Modelled after Linux' lib/ratelimit.c by Dave Young
34 * <hidave.darkstar@gmail.com>, which is licensed GPLv2. */
35
36bool pa_ratelimit_test(pa_ratelimit *r, pa_log_level_t t) {
37    pa_usec_t now;
38    pa_mutex *m;
39
40    now = pa_rtclock_now();
41
42    m = pa_static_mutex_get(&mutex, false, false);
43    pa_mutex_lock(m);
44
45    pa_assert(r);
46    pa_assert(r->interval > 0);
47    pa_assert(r->burst > 0);
48
49    if (r->begin <= 0 ||
50        r->begin + r->interval < now) {
51
52        if (r->n_missed > 0)
53            pa_logl(t, "%u events suppressed", r->n_missed);
54
55        r->begin = now;
56
57        /* Reset counters */
58        r->n_printed = 0;
59        r->n_missed = 0;
60        goto good;
61    }
62
63    if (r->n_printed <= r->burst)
64        goto good;
65
66    r->n_missed++;
67    pa_mutex_unlock(m);
68    return false;
69
70good:
71    r->n_printed++;
72    pa_mutex_unlock(m);
73    return true;
74}
75