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.ImmutableList;
38 import com.google.common.collect.ImmutableMultimap;
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");
74 for (ControlledComponent component : Lists.reverse(components())) {
75 logger.finest(String.format("Adding Listener to %s.", component.name()));
76 component.addMetadataListener(new MetadataListener() {
78 public void metadataUpdated(ControlledComponent component, Metadata metadata) {
79 if (!(component instanceof Source)) {
82 for (ControlledComponent controlledComponent : sinks((Source) component)) {
83 logger.fine(String.format("Updating Metadata from %s to %s as %s.", component.name(), controlledComponent.name(), metadata));
84 controlledComponent.metadataUpdated(metadata);
96 * Expose this pipeline’s source.
98 * @return This pipeline’s source
100 public Source source() {
105 * Returns all {@link Sink}s (or {@link Filter}s, really) that are connected to
109 * The source to get the sinks for
110 * @return The sinks connected to the given source, or an empty list if the
111 * source does not exist in this pipeline
113 public Collection<Sink> sinks(Source source) {
114 return sinks.get(source);
118 * Returns the traffic counters of the given controlled component.
120 * @param controlledComponent
121 * The controlled component to get the traffic counters for
122 * @return The traffic counters for the given controlled component
124 public TrafficCounter trafficCounter(ControlledComponent controlledComponent) {
127 for (Connection connection : connections) {
128 /* the connection where the source matches knows the output. */
129 if (connection.source.equals(controlledComponent)) {
130 output = connection.counter();
131 } else if (connection.sinks.contains(controlledComponent)) {
132 input = connection.counter();
135 return new TrafficCounter(input, output);
143 * Starts the pipeline.
145 * @throws IOException
146 * if any of the sinks can not be opened
147 * @throws IllegalStateException
148 * if the pipeline is already running
150 public void start() throws IOException, IllegalStateException {
151 if (!connections.isEmpty()) {
152 throw new IllegalStateException("Pipeline is already running!");
154 List<Source> sources = Lists.newArrayList();
156 /* collect all source->sink pairs. */
157 while (!sources.isEmpty()) {
158 Source source = sources.remove(0);
159 Collection<Sink> sinks = this.sinks.get(source);
160 connections.add(new Connection(source, sinks));
161 for (Sink sink : sinks) {
162 logger.info(String.format("Opening %s with %s...", sink.name(), source.metadata()));
163 sink.open(source.metadata());
164 if (sink instanceof Filter) {
165 sources.add((Source) sink);
169 for (Connection connection : connections) {
170 logger.info(String.format("Starting Connection from %s to %s.", connection.source.name(), FluentIterable.from(connection.sinks).transform(new Function<Sink, String>() {
172 public String apply(Sink sink) {
176 new Thread(connection).start();
181 if (!connections.isEmpty()) {
182 /* pipeline is not running. */
185 for (Connection connection : connections) {
195 public Iterator<ControlledComponent> iterator() {
196 return components().iterator();
204 * Returns all components of this pipeline, listed breadth-first, starting with
207 * @return All components of this pipeline
209 public List<ControlledComponent> components() {
210 ImmutableList.Builder<ControlledComponent> components = ImmutableList.builder();
211 List<ControlledComponent> currentComponents = Lists.newArrayList();
212 components.add(source);
213 currentComponents.add(source);
214 while (!currentComponents.isEmpty()) {
215 Collection<Sink> sinks = this.sinks((Source) currentComponents.remove(0));
216 for (Sink sink : sinks) {
217 components.add(sink);
218 if (sink instanceof Source) {
219 currentComponents.add(sink);
223 return components.build();
231 * Returns a new pipeline builder.
234 * The source at which to start
235 * @return A builder for a new pipeline
237 public static Builder builder(Source source) {
238 return new Builder(source);
242 * A builder for a {@link Pipeline}.
244 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
246 public static class Builder {
248 /** The source of the pipeline. */
249 private final Source source;
251 /** The sinks to which each source streams. */
252 private Multimap<Source, Sink> nextSinks = ArrayListMultimap.create();
254 /** The last added source. */
255 private Source lastSource;
258 * Creates a new builder.
261 * The source that starts the pipeline
263 private Builder(Source source) {
264 this.source = source;
269 * Adds a {@link Sink} (or {@link Filter} as a recipient for the last added
274 * @return This builder
275 * @throws IllegalStateException
276 * if the last added {@link Sink} was not also a {@link Source}
278 public Builder to(Sink sink) {
279 Preconditions.checkState(lastSource != null, "last added Sink was not a Source");
280 nextSinks.put(lastSource, sink);
281 lastSource = (sink instanceof Filter) ? (Source) sink : null;
286 * Locates the given source and sets it as the last added node so that the
287 * next invocation of {@link #to(Sink)} can “fork” the pipeline.
290 * The source to locate
291 * @return This builder
292 * @throws IllegalStateException
293 * if the given source was not previously added as a sink
295 public Builder find(Source source) {
296 Preconditions.checkState(nextSinks.containsValue(source));
302 * Builds the pipeline.
304 * @return The created pipeline
306 public Pipeline build() {
307 return new Pipeline(source, ImmutableMultimap.copyOf(nextSinks));
313 * A connection is responsible for streaming audio from one {@link Source} to
314 * an arbitrary number of {@link Sink}s it is connected to. A connection is
315 * started by creating a {@link Thread} wrapping it and starting said thread.
317 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
319 public class Connection implements Runnable {
322 private final Source source;
325 private final Collection<Sink> sinks;
327 /** Whether the feeder was stopped. */
328 private final AtomicBoolean stopped = new AtomicBoolean(false);
330 /** The executor service. */
331 private final ExecutorService executorService;
333 /** The time the connection was started. */
334 private long startTime;
336 /** The number of copied bytes. */
337 private long counter;
340 * Creates a new connection.
343 * The source of the stream
345 * The sinks to which to stream
347 public Connection(Source source, Collection<Sink> sinks) {
348 this.source = source;
350 if (sinks.size() < 2) {
351 executorService = MoreExecutors.sameThreadExecutor();
353 executorService = Executors.newCachedThreadPool();
362 * Returns the time this connection was started.
364 * @return The time this connection was started (in milliseconds since Jan 1,
367 public long startTime() {
372 * Returns the number of bytes that this connection has received from its
373 * source during its lifetime.
375 * @return The number of processed input bytes
377 public long counter() {
385 /** Stops this connection. */
396 startTime = System.currentTimeMillis();
397 while (!stopped.get()) {
401 logger.finest(String.format("Getting %d bytes from %s...", 4096, source));
402 buffer = source.get(4096);
403 logger.finest(String.format("Got %d bytes from %s.", buffer.length, source));
404 } catch (IOException ioe1) {
405 throw new IOException(String.format("I/O error while reading from %s.", source), ioe1);
407 List<Future<Void>> futures = executorService.invokeAll(FluentIterable.from(sinks).transform(new Function<Sink, Callable<Void>>() {
410 public Callable<Void> apply(final Sink sink) {
411 return new Callable<Void>() {
414 public Void call() throws Exception {
416 logger.finest(String.format("Sending %d bytes to %s.", buffer.length, sink));
417 sink.process(buffer);
418 logger.finest(String.format("Sent %d bytes to %s.", buffer.length, sink));
419 } catch (IOException ioe1) {
420 throw new IOException(String.format("I/O error while writing to %s", sink), ioe1);
427 /* check all threads for exceptions. */
428 for (Future<Void> future : futures) {
431 counter += buffer.length;
432 } catch (IOException e) {
436 } catch (InterruptedException e) {
440 } catch (ExecutionException e) {
451 * Container for input and output counters.
453 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
455 public static class TrafficCounter {
457 /** The number of input bytes. */
458 private final long input;
460 /** The number of output bytes. */
461 private final long output;
464 * Creates a new traffic counter.
467 * The number of input bytes (may be {@code -1} to signify non-available
470 * The number of output bytes (may be {@code -1} to signify non-available
473 public TrafficCounter(long input, long output) {
475 this.output = output;
483 * Returns the number of input bytes.
485 * @return The number of input bytes, or {@link Optional#absent()} if the
486 * component can not receive input
488 public Optional<Long> input() {
489 return (input == -1) ? Optional.<Long>absent() : Optional.of(input);
493 * Returns the number of output bytes.
495 * @return The number of output bytes, or {@link Optional#absent()} if the
496 * component can not send output
498 public Optional<Long> output() {
499 return (output == -1) ? Optional.<Long>absent() : Optional.of(output);