]> code.delx.au - pulseaudio/blob - src/pulsecore/ratelimit.c
add generic rate limiting implementation
[pulseaudio] / src / pulsecore / ratelimit.c
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 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, write to the Free Software
18 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
19 USA.
20 ***/
21
22 #ifdef HAVE_CONFIG_H
23 #include <config.h>
24 #endif
25
26 #include <pulsecore/rtclock.h>
27 #include <pulsecore/log.h>
28 #include <pulsecore/mutex.h>
29
30 #include "ratelimit.h"
31
32 static pa_static_mutex mutex;
33
34 /* Modelled after Linux' lib/ratelimit.c by Dave Young
35 * <hidave.darkstar@gmail.com>, which is licensed GPLv2. */
36
37 pa_bool_t pa_ratelimit_test(pa_ratelimit *r) {
38 pa_usec_t now;
39 pa_mutex *m;
40
41 now = pa_rtclock_usec();
42
43 m = pa_static_mutex_get(&mutex, FALSE, FALSE);
44 pa_mutex_lock(m);
45
46 pa_assert(r);
47 pa_assert(r->interval > 0);
48 pa_assert(r->burst > 0);
49
50 if (r->begin <= 0 ||
51 r->begin + r->interval < now) {
52
53 if (r->n_missed > 0)
54 pa_log_warn("%u events suppressed", r->n_missed);
55
56 r->begin = now;
57
58 /* Reset counters */
59 r->n_printed = 0;
60 r->n_missed = 0;
61 goto good;
62 }
63
64 if (r->n_printed <= r->burst)
65 goto good;
66
67 r->n_missed++;
68 pa_mutex_unlock(m);
69 return FALSE;
70
71 good:
72 r->n_printed++;
73 pa_mutex_unlock(m);
74 return TRUE;
75 }