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.ListMultimap;
40 import com.google.common.collect.Lists;
41 import com.google.common.collect.Multimap;
42 import com.google.common.util.concurrent.MoreExecutors;
45 * A pipeline is responsible for streaming audio data from a {@link Filter} to
46 * an arbitrary number of connected {@link Filter}s.
48 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
50 public class Pipeline implements Iterable<Filter> {
53 private static final Logger logger = Logger.getLogger(Pipeline.class.getName());
55 /** The source of the audio stream. */
56 private final Filter source;
58 /** The filters for each source. */
59 private final ListMultimap<Filter, Filter> filters;
61 /** All started connections. */
62 private final List<Connection> connections = Lists.newArrayList();
65 * Creates a new pipeline.
68 * The source of the audio stream
70 * The filters for each source
72 private Pipeline(Filter source, Multimap<Filter, Filter> filters) {
73 this.source = Preconditions.checkNotNull(source, "source must not be null");
74 this.filters = ArrayListMultimap.create(Preconditions.checkNotNull(filters, "filters must not be null"));
82 * Expose this pipeline’s source.
84 * @return This pipeline’s source
86 public Filter source() {
91 * Returns all {@link Filter}s that are connected to the given filter.
94 * The filter to get the connected filters for
95 * @return The filters connected to the given filter, or an empty list if the
96 * filter does not exist in this pipeline, or is not connected to any filters
98 public List<Filter> filters(Filter filter) {
99 return filters.get(filter);
103 * Returns the traffic counters of the given filter.
106 * The filter to get the traffic counters for
107 * @return The traffic counters for the given filter
109 public TrafficCounter trafficCounter(Filter filter) {
112 for (Connection connection : connections) {
113 /* the connection where the source matches knows the output. */
114 if (connection.source.equals(filter)) {
115 output = connection.counter();
116 } else if (connection.sinks.contains(filter)) {
117 input = connection.counter();
120 return new TrafficCounter(input, output);
128 * Starts the pipeline.
130 * @throws IOException
131 * if any of the filters 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<Filter> filters = Lists.newArrayList();
141 source.open(Metadata.UNKNOWN);
142 /* collect all source->sink pairs. */
143 while (!filters.isEmpty()) {
144 Filter filter = filters.remove(0);
145 Collection<Filter> sinks = this.filters.get(filter);
146 connections.add(new Connection(filter, sinks));
147 for (Filter sink : sinks) {
148 logger.info(String.format("Opening %s with %s...", sink.name(), source.metadata()));
149 sink.open(filter.metadata());
153 for (Connection connection : connections) {
154 String threadName = String.format("%s → %s.", connection.source.name(), FluentIterable.from(connection.sinks).transform(new Function<Filter, String>() {
157 public String apply(Filter sink) {
161 logger.info(String.format("Starting Thread: %s", threadName));
162 new Thread(connection, threadName).start();
167 if (!connections.isEmpty()) {
168 /* pipeline is not running. */
171 for (Connection connection : connections) {
181 public Iterator<Filter> iterator() {
182 return filters().iterator();
190 * Returns all filters of this pipeline, listed breadth-first, starting with
193 * @return All filters of this pipeline
195 public List<Filter> filters() {
196 ImmutableList.Builder<Filter> filters = ImmutableList.builder();
197 List<Filter> remainingFilters = Lists.newArrayList();
199 remainingFilters.add(source);
200 while (!remainingFilters.isEmpty()) {
201 Collection<Filter> sinks = this.filters(remainingFilters.remove(0));
202 for (Filter sink : sinks) {
204 remainingFilters.add(sink);
207 return filters.build();
215 * Returns a new pipeline builder.
218 * The source at which to start
219 * @return A builder for a new pipeline
221 public static Builder builder(Filter source) {
222 return new Builder(source);
226 * A builder for a {@link Pipeline}.
228 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
230 public static class Builder {
232 /** The source of the pipeline. */
233 private final Filter source;
235 /** The filters to which each source streams. */
236 private Multimap<Filter, Filter> nextSinks = ArrayListMultimap.create();
238 /** The last added source. */
239 private Filter lastSource;
242 * Creates a new builder.
245 * The source that starts the pipeline
247 private Builder(Filter source) {
248 this.source = source;
253 * Adds a {@link Filter} as a recipient for the last added source.
257 * @return This builder
259 public Builder to(Filter sink) {
260 nextSinks.put(lastSource, sink);
266 * Locates the given source and sets it as the last added node so that the
267 * next invocation of {@link #to(Filter)} can “fork” the pipeline.
270 * The source to locate
271 * @return This builder
272 * @throws IllegalStateException
273 * if the given source was not previously added as a sink
275 public Builder find(Filter source) {
276 Preconditions.checkState(nextSinks.containsValue(source));
282 * Builds the pipeline.
284 * @return The created pipeline
286 public Pipeline build() {
287 return new Pipeline(source, ImmutableMultimap.copyOf(nextSinks));
293 * A connection is responsible for streaming audio from one {@link Filter} to
294 * an arbitrary number of {@link Filter}s it is connected to. A connection is
295 * started by creating a {@link Thread} wrapping it and starting said thread.
297 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
299 public static class Connection implements Runnable {
302 private final Filter source;
305 private final Collection<Filter> sinks;
307 /** Whether the feeder was stopped. */
308 private final AtomicBoolean stopped = new AtomicBoolean(false);
310 /** The executor service. */
311 private final ExecutorService executorService;
313 /** The time the connection was started. */
314 private long startTime;
316 /** The number of copied bytes. */
317 private long counter;
320 * Creates a new connection.
323 * The source of the stream
325 * The filters to which to stream
327 public Connection(Filter source, Collection<Filter> sinks) {
328 this.source = source;
330 if (sinks.size() < 2) {
331 executorService = MoreExecutors.sameThreadExecutor();
333 executorService = Executors.newCachedThreadPool();
342 * Returns the source of this connection.
344 * @return The source of this connection
346 public Filter source() {
351 * Returns the sinks of this connection.
353 * @return The sinks of this connection
355 public Collection<Filter> sinks() {
360 * Returns the time this connection was started.
362 * @return The time this connection was started (in milliseconds since Jan 1,
365 public long startTime() {
370 * Returns the number of bytes that this connection has received from its
371 * source during its lifetime.
373 * @return The number of processed input bytes
375 public long counter() {
383 /** Stops this connection. */
394 startTime = System.currentTimeMillis();
395 while (!stopped.get()) {
397 final DataPacket dataPacket;
399 logger.finest(String.format("Getting %d bytes from %s...", 4096, source.name()));
400 dataPacket = source.get(4096);
401 logger.finest(String.format("Got %d bytes from %s.", dataPacket.buffer().length, source.name()));
402 } catch (IOException ioe1) {
403 throw new IOException(String.format("I/O error while reading from %s.", source.name()), ioe1);
405 List<Future<Void>> futures = executorService.invokeAll(FluentIterable.from(sinks).transform(new Function<Filter, Callable<Void>>() {
408 public Callable<Void> apply(final Filter sink) {
409 return new Callable<Void>() {
412 public Void call() throws Exception {
414 logger.finest(String.format("Sending %d bytes to %s.", dataPacket.buffer().length, sink.name()));
415 sink.process(dataPacket);
416 logger.finest(String.format("Sent %d bytes to %s.", dataPacket.buffer().length, sink.name()));
417 } catch (IOException ioe1) {
418 throw new IOException(String.format("I/O error while writing to %s", sink.name()), ioe1);
425 /* check all threads for exceptions. */
426 for (Future<Void> future : futures) {
429 counter += dataPacket.buffer().length;
430 } catch (IOException e) {
434 } catch (InterruptedException e) {
438 } catch (ExecutionException e) {
449 * Container for input and output counters.
451 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
453 public static class TrafficCounter {
455 /** The number of input bytes. */
456 private final long input;
458 /** The number of output bytes. */
459 private final long output;
462 * Creates a new traffic counter.
465 * The number of input bytes (may be {@code -1} to signify non-available
468 * The number of output bytes (may be {@code -1} to signify non-available
471 public TrafficCounter(long input, long output) {
473 this.output = output;
481 * Returns the number of input bytes.
483 * @return The number of input bytes, or {@link Optional#absent()} if the
484 * filter did not receive input
486 public Optional<Long> input() {
487 return (input == -1) ? Optional.<Long>absent() : Optional.of(input);
491 * Returns the number of output bytes.
493 * @return The number of output bytes, or {@link Optional#absent()} if the
494 * filter did not send output
496 public Optional<Long> output() {
497 return (output == -1) ? Optional.<Long>absent() : Optional.of(output);