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.EOFException;
21 import java.io.IOException;
22 import java.util.logging.Logger;
24 import net.pterodactylus.sonitus.data.ConnectException;
25 import net.pterodactylus.sonitus.data.Filter;
26 import net.pterodactylus.sonitus.data.Metadata;
27 import net.pterodactylus.sonitus.data.Source;
29 import com.google.common.base.Preconditions;
32 * Rate limiting filter that only passes a specified amount of data per second
33 * from its {@link Source} to its {@link net.pterodactylus.sonitus.data.Sink}.
35 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
37 public class RateLimitingFilter implements Filter {
40 private static final Logger logger = Logger.getLogger(RateLimitingFilter.class.getName());
42 /** The limiting rate in bytes/second. */
43 private final int rate;
46 private Source source;
49 * Creates a new rate limiting filter.
52 * The limiting rate (in bytes/second)
54 public RateLimitingFilter(int rate) {
63 public Metadata metadata() {
64 return source.metadata();
68 public byte[] get(int bufferSize) throws EOFException, IOException {
69 long now = System.currentTimeMillis();
70 byte[] buffer = source.get(bufferSize);
72 long waitTime = 1000 * buffer.length / rate;
73 while ((System.currentTimeMillis() - now) < waitTime) {
75 long limitDelay = waitTime - (System.currentTimeMillis() - now);
76 logger.finest(String.format("Waiting %d ms...", limitDelay));
77 Thread.sleep(limitDelay);
78 } catch (InterruptedException ie1) {
79 /* ignore, keep looping. */
86 public void connect(Source source) throws ConnectException {
87 Preconditions.checkNotNull(source, "source must not be null");
93 public void metadataUpdated() {