2 * Sonitus - DelayFilter.java - Copyright © 2013 David Roden
4 * This program is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation, either version 3 of the License, or
7 * (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program. If not, see <http://www.gnu.org/licenses/>.
18 package net.pterodactylus.sonitus.data.filter;
20 import java.io.IOException;
21 import java.util.logging.Logger;
23 import net.pterodactylus.sonitus.data.AbstractFilter;
24 import net.pterodactylus.sonitus.data.Filter;
25 import net.pterodactylus.sonitus.data.Metadata;
28 * Rate limiting filter that only passes a specified amount of data per second
29 * from its {@link net.pterodactylus.sonitus.data.Source} to its {@link
30 * net.pterodactylus.sonitus.data.Sink}.
32 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
34 public class RateLimitingFilter extends AbstractFilter implements Filter {
37 private static final Logger logger = Logger.getLogger(RateLimitingFilter.class.getName());
39 /** The limiting rate in bytes/second. */
40 private final int rate;
42 /** The start time. */
43 private long startTime;
45 /** The number of bytes. */
49 * Creates a new rate limiting filter.
52 * The name of the filter
55 public RateLimitingFilter(String name, int rate) {
60 * Creates a new rate limiting filter.
63 * The name of the filter
65 * The limiting rate (in bytes/second)
66 * @param fastStartTime
67 * The amount of time at the start of the filtering during which no delay
69 public RateLimitingFilter(String name, int rate, long fastStartTime) {
72 this.counter = (long) (-rate * (fastStartTime / 1000.0));
80 public void open(Metadata metadata) throws IOException {
82 startTime = System.currentTimeMillis();
86 public void process(byte[] buffer) throws IOException {
87 super.process(buffer);
89 counter += buffer.length;
90 long waitTime = (long) (counter / (rate / 1000.0));
91 while ((System.currentTimeMillis() - startTime) < waitTime) {
93 long limitDelay = waitTime - (System.currentTimeMillis() - startTime);
94 logger.finest(String.format("Waiting %d ms...", limitDelay));
95 Thread.sleep(limitDelay);
96 } catch (InterruptedException ie1) {
97 /* ignore, keep looping. */
100 logger.finest(String.format("Processed %d Bytes during %d ms, that’s %.1f bytes/s.", counter, System.currentTimeMillis() - startTime, counter / ((System.currentTimeMillis() - startTime) / 1000.0)));