2 * Sonitus - Pipeline.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;
20 import java.io.IOException;
21 import java.util.Collection;
22 import java.util.Iterator;
23 import java.util.List;
24 import java.util.concurrent.Callable;
25 import java.util.concurrent.ExecutionException;
26 import java.util.concurrent.ExecutorService;
27 import java.util.concurrent.Executors;
28 import java.util.concurrent.Future;
29 import java.util.concurrent.atomic.AtomicBoolean;
30 import java.util.logging.Logger;
32 import com.google.common.base.Function;
33 import com.google.common.base.Optional;
34 import com.google.common.base.Preconditions;
35 import com.google.common.collect.ArrayListMultimap;
36 import com.google.common.collect.FluentIterable;
37 import com.google.common.collect.ImmutableMultimap;
38 import com.google.common.collect.ImmutableSet;
39 import com.google.common.collect.Lists;
40 import com.google.common.collect.Multimap;
41 import com.google.common.util.concurrent.MoreExecutors;
44 * A pipeline is responsible for streaming audio data from a {@link Source} to
45 * an arbitrary number of connected {@link Filter}s and {@link Sink}s.
47 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
49 public class Pipeline implements Iterable<ControlledComponent> {
52 private static final Logger logger = Logger.getLogger(Pipeline.class.getName());
54 /** The source of the audio stream. */
55 private final Source source;
57 /** The sinks for each source. */
58 private final Multimap<Source, Sink> sinks;
60 /** All started connections. */
61 private final List<Connection> connections = Lists.newArrayList();
64 * Creates a new pipeline.
67 * The source of the audio stream
69 * The sinks for each source
71 private Pipeline(Source source, Multimap<Source, Sink> sinks) {
72 this.source = Preconditions.checkNotNull(source, "source must not be null");
73 this.sinks = Preconditions.checkNotNull(sinks, "sinks must not be null");
81 * Expose this pipeline’s source.
83 * @return This pipeline’s source
85 public Source source() {
90 * Returns all {@link Sink}s (or {@link Filter}s, really) that are connected to
94 * The source to get the sinks for
95 * @return The sinks connected to the given source, or an empty list if the
96 * source does not exist in this pipeline
98 public Collection<Sink> sinks(Source source) {
99 return sinks.get(source);
103 * Returns the traffic counters of the given controlled component.
105 * @param controlledComponent
106 * The controlled component to get the traffic counters for
107 * @return The traffic counters for the given controlled component
109 public TrafficCounter trafficCounter(ControlledComponent controlledComponent) {
112 for (Connection connection : connections) {
113 /* the connection where the source matches knows the output. */
114 if (connection.source.equals(controlledComponent)) {
115 output = connection.counter();
116 } else if (connection.sinks.contains(controlledComponent)) {
117 input = connection.counter();
120 return new TrafficCounter(input, output);
128 * Starts the pipeline.
130 * @throws IOException
131 * if any of the sinks can not be opened
132 * @throws IllegalStateException
133 * if the pipeline is already running
135 public void start() throws IOException, IllegalStateException {
136 if (!connections.isEmpty()) {
137 throw new IllegalStateException("Pipeline is already running!");
139 List<Source> sources = Lists.newArrayList();
141 /* collect all source->sink pairs. */
142 while (!sources.isEmpty()) {
143 Source source = sources.remove(0);
144 Collection<Sink> sinks = this.sinks.get(source);
145 connections.add(new Connection(source, sinks));
146 for (Sink sink : sinks) {
147 sink.open(source.metadata());
148 if (sink instanceof Filter) {
149 sources.add((Source) sink);
153 for (Connection connection : connections) {
154 logger.info(String.format("Starting Connection from %s to %s.", connection.source, connection.sinks));
155 new Thread(connection).start();
160 if (!connections.isEmpty()) {
161 /* pipeline is not running. */
164 for (Connection connection : connections) {
174 public Iterator<ControlledComponent> iterator() {
175 return ImmutableSet.<ControlledComponent>builder().add(source).addAll(sinks.values()).build().iterator();
183 * Returns a new pipeline builder.
186 * The source at which to start
187 * @return A builder for a new pipeline
189 public static Builder builder(Source source) {
190 return new Builder(source);
194 * A builder for a {@link Pipeline}.
196 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
198 public static class Builder {
200 /** The source of the pipeline. */
201 private final Source source;
203 /** The sinks to which each source streams. */
204 private Multimap<Source, Sink> nextSinks = ArrayListMultimap.create();
206 /** The last added source. */
207 private Source lastSource;
210 * Creates a new builder.
213 * The source that starts the pipeline
215 private Builder(Source source) {
216 this.source = source;
221 * Adds a {@link Sink} (or {@link Filter} as a recipient for the last added
226 * @return This builder
227 * @throws IllegalStateException
228 * if the last added {@link Sink} was not also a {@link Source}
230 public Builder to(Sink sink) {
231 Preconditions.checkState(lastSource != null, "last added Sink was not a Source");
232 nextSinks.put(lastSource, sink);
233 lastSource = (sink instanceof Filter) ? (Source) sink : null;
238 * Locates the given source and sets it as the last added node so that the
239 * next invocation of {@link #to(Sink)} can “fork” the pipeline.
242 * The source to locate
243 * @return This builder
244 * @throws IllegalStateException
245 * if the given source was not previously added as a sink
247 public Builder find(Source source) {
248 Preconditions.checkState(nextSinks.containsValue(source));
254 * Builds the pipeline.
256 * @return The created pipeline
258 public Pipeline build() {
259 return new Pipeline(source, ImmutableMultimap.copyOf(nextSinks));
265 * A connection is responsible for streaming audio from one {@link Source} to
266 * an arbitrary number of {@link Sink}s it is connected to. A connection is
267 * started by creating a {@link Thread} wrapping it and starting said thread.
269 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
271 public class Connection implements Runnable {
274 private final Source source;
277 private final Collection<Sink> sinks;
279 /** Whether the feeder was stopped. */
280 private final AtomicBoolean stopped = new AtomicBoolean(false);
282 /** The executor service. */
283 private final ExecutorService executorService;
285 /** The number of copied bytes. */
286 private long counter;
289 * Creates a new connection.
292 * The source of the stream
294 * The sinks to which to stream
296 public Connection(Source source, Collection<Sink> sinks) {
297 this.source = source;
299 if (sinks.size() == 1) {
300 executorService = MoreExecutors.sameThreadExecutor();
302 executorService = Executors.newCachedThreadPool();
311 * Returns the number of bytes that this connection has received from its
312 * source during its lifetime.
314 * @return The number of processed input bytes
316 public long counter() {
324 /** Stops this connection. */
335 Metadata firstMetadata = null;
336 while (!stopped.get()) {
340 logger.finest(String.format("Getting %d bytes from %s...", 4096, source));
341 buffer = source.get(4096);
342 logger.finest(String.format("Got %d bytes from %s.", buffer.length, source));
343 } catch (IOException ioe1) {
344 throw new IOException(String.format("I/O error while reading from %s.", source), ioe1);
346 List<Future<Void>> futures = executorService.invokeAll(FluentIterable.from(sinks).transform(new Function<Sink, Callable<Void>>() {
349 public Callable<Void> apply(final Sink sink) {
350 return new Callable<Void>() {
353 public Void call() throws Exception {
355 logger.finest(String.format("Sending %d bytes to %s.", buffer.length, sink));
356 sink.process(buffer);
357 logger.finest(String.format("Sent %d bytes to %s.", buffer.length, sink));
358 } catch (IOException ioe1) {
359 throw new IOException(String.format("I/O error while writing to %s", sink), ioe1);
366 /* check all threads for exceptions. */
367 for (Future<Void> future : futures) {
370 counter += buffer.length;
371 } catch (IOException e) {
375 } catch (InterruptedException e) {
379 } catch (ExecutionException e) {
390 * Container for input and output counters.
392 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
394 public static class TrafficCounter {
396 /** The number of input bytes. */
397 private final long input;
399 /** The number of output bytes. */
400 private final long output;
403 * Creates a new traffic counter.
406 * The number of input bytes (may be {@code -1} to signify non-available
409 * The number of output bytes (may be {@code -1} to signify non-available
412 public TrafficCounter(long input, long output) {
414 this.output = output;
422 * Returns the number of input bytes.
424 * @return The number of input bytes, or {@link Optional#absent()} if the
425 * component can not receive input
427 public Optional<Long> input() {
428 return (input == -1) ? Optional.<Long>absent() : Optional.of(input);
432 * Returns the number of output bytes.
434 * @return The number of output bytes, or {@link Optional#absent()} if the
435 * component can not send output
437 public Optional<Long> output() {
438 return (output == -1) ? Optional.<Long>absent() : Optional.of(output);