2 * Sonitus - MultiSource.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 static com.google.common.base.Preconditions.*;
22 import java.io.EOFException;
23 import java.io.IOException;
24 import java.util.concurrent.atomic.AtomicReference;
25 import java.util.logging.Logger;
27 import net.pterodactylus.sonitus.data.ConnectException;
28 import net.pterodactylus.sonitus.data.Filter;
29 import net.pterodactylus.sonitus.data.Metadata;
30 import net.pterodactylus.sonitus.data.ReusableSink;
31 import net.pterodactylus.sonitus.data.Source;
32 import net.pterodactylus.sonitus.data.event.SourceFinishedEvent;
34 import com.google.common.eventbus.EventBus;
35 import com.google.inject.Inject;
38 * {@link ReusableSink} implementation that supports changing the source without
39 * letting the {@link net.pterodactylus.sonitus.data.Sink} know.
41 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
43 public class MultiSourceFilter implements Filter, ReusableSink {
46 private static final Logger logger = Logger.getLogger(MultiSourceFilter.class.getName());
49 private final EventBus eventBus;
51 /** The current source. */
52 private final AtomicReference<Source> source = new AtomicReference<Source>();
55 public MultiSourceFilter(EventBus eventBus) {
56 this.eventBus = eventBus;
60 public Metadata metadata() {
61 return source.get().metadata();
65 public byte[] get(int bufferSize) throws EOFException, IOException {
66 return source.get().get(bufferSize);
70 public void connect(Source source) throws ConnectException {
71 checkNotNull(source, "source must not be null");
73 Source oldSource = this.source.getAndSet(source);
74 if (oldSource != null) {
75 checkArgument(oldSource.metadata().channels() == source.metadata().channels(), "source’s channel count must equal existing source’s channel count");
76 checkArgument(oldSource.metadata().frequency() == source.metadata().frequency(), "source’s frequency must equal existing source’s frequency");
77 checkArgument(oldSource.metadata().encoding().equalsIgnoreCase(source.metadata().encoding()), "source’s encoding must equal existing source’s encoding");
79 eventBus.post(new SourceFinishedEvent(oldSource));
84 public void metadataUpdated() {