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"));
75 for (Filter filter : Lists.reverse(filters())) {
76 logger.finest(String.format("Adding Listener to %s.", filter.name()));
77 filter.addMetadataListener(new MetadataListener() {
80 public void metadataUpdated(Filter filter, Metadata metadata) {
81 for (Filter sinks : filters(filter)) {
82 logger.fine(String.format("Updating Metadata from %s to %s as %s.", filter.name(), sinks.name(), metadata));
83 sinks.metadataUpdated(metadata);
95 * Expose this pipeline’s source.
97 * @return This pipeline’s source
99 public Filter source() {
104 * Returns all {@link Filter}s that are connected to the given filter.
107 * The filter to get the connected filters for
108 * @return The filters connected to the given filter, or an empty list if the
109 * filter does not exist in this pipeline, or is not connected to any filters
111 public List<Filter> filters(Filter filter) {
112 return filters.get(filter);
116 * Returns the traffic counters of the given filter.
119 * The filter to get the traffic counters for
120 * @return The traffic counters for the given filter
122 public TrafficCounter trafficCounter(Filter filter) {
125 for (Connection connection : connections) {
126 /* the connection where the source matches knows the output. */
127 if (connection.source.equals(filter)) {
128 output = connection.counter();
129 } else if (connection.sinks.contains(filter)) {
130 input = connection.counter();
133 return new TrafficCounter(input, output);
141 * Starts the pipeline.
143 * @throws IOException
144 * if any of the filters can not be opened
145 * @throws IllegalStateException
146 * if the pipeline is already running
148 public void start() throws IOException, IllegalStateException {
149 if (!connections.isEmpty()) {
150 throw new IllegalStateException("Pipeline is already running!");
152 List<Filter> filters = Lists.newArrayList();
154 /* collect all source->sink pairs. */
155 while (!filters.isEmpty()) {
156 Filter filter = filters.remove(0);
157 Collection<Filter> sinks = this.filters.get(filter);
158 connections.add(new Connection(filter, sinks));
159 for (Filter sink : sinks) {
160 logger.info(String.format("Opening %s with %s...", sink.name(), source.metadata()));
161 sink.open(filter.metadata());
165 for (Connection connection : connections) {
166 String threadName = String.format("%s → %s.", connection.source.name(), FluentIterable.from(connection.sinks).transform(new Function<Filter, String>() {
169 public String apply(Filter sink) {
173 logger.info(String.format("Starting Thread: %s", threadName));
174 new Thread(connection, threadName).start();
179 if (!connections.isEmpty()) {
180 /* pipeline is not running. */
183 for (Connection connection : connections) {
193 public Iterator<Filter> iterator() {
194 return filters().iterator();
202 * Returns all filters of this pipeline, listed breadth-first, starting with
205 * @return All filters of this pipeline
207 public List<Filter> filters() {
208 ImmutableList.Builder<Filter> filters = ImmutableList.builder();
209 List<Filter> remainingFilters = Lists.newArrayList();
211 remainingFilters.add(source);
212 while (!remainingFilters.isEmpty()) {
213 Collection<Filter> sinks = this.filters(remainingFilters.remove(0));
214 for (Filter sink : sinks) {
216 remainingFilters.add(sink);
219 return filters.build();
227 * Returns a new pipeline builder.
230 * The source at which to start
231 * @return A builder for a new pipeline
233 public static Builder builder(Filter source) {
234 return new Builder(source);
238 * A builder for a {@link Pipeline}.
240 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
242 public static class Builder {
244 /** The source of the pipeline. */
245 private final Filter source;
247 /** The filters to which each source streams. */
248 private Multimap<Filter, Filter> nextSinks = ArrayListMultimap.create();
250 /** The last added source. */
251 private Filter lastSource;
254 * Creates a new builder.
257 * The source that starts the pipeline
259 private Builder(Filter source) {
260 this.source = source;
265 * Adds a {@link Filter} as a recipient for the last added source.
269 * @return This builder
271 public Builder to(Filter sink) {
272 nextSinks.put(lastSource, sink);
278 * Locates the given source and sets it as the last added node so that the
279 * next invocation of {@link #to(Filter)} can “fork” the pipeline.
282 * The source to locate
283 * @return This builder
284 * @throws IllegalStateException
285 * if the given source was not previously added as a sink
287 public Builder find(Filter source) {
288 Preconditions.checkState(nextSinks.containsValue(source));
294 * Builds the pipeline.
296 * @return The created pipeline
298 public Pipeline build() {
299 return new Pipeline(source, ImmutableMultimap.copyOf(nextSinks));
305 * A connection is responsible for streaming audio from one {@link Filter} to
306 * an arbitrary number of {@link Filter}s it is connected to. A connection is
307 * started by creating a {@link Thread} wrapping it and starting said thread.
309 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
311 public class Connection implements Runnable {
314 private final Filter source;
317 private final Collection<Filter> sinks;
319 /** Whether the feeder was stopped. */
320 private final AtomicBoolean stopped = new AtomicBoolean(false);
322 /** The executor service. */
323 private final ExecutorService executorService;
325 /** The time the connection was started. */
326 private long startTime;
328 /** The number of copied bytes. */
329 private long counter;
332 * Creates a new connection.
335 * The source of the stream
337 * The filters to which to stream
339 public Connection(Filter source, Collection<Filter> sinks) {
340 this.source = source;
342 if (sinks.size() < 2) {
343 executorService = MoreExecutors.sameThreadExecutor();
345 executorService = Executors.newCachedThreadPool();
354 * Returns the time this connection was started.
356 * @return The time this connection was started (in milliseconds since Jan 1,
359 public long startTime() {
364 * Returns the number of bytes that this connection has received from its
365 * source during its lifetime.
367 * @return The number of processed input bytes
369 public long counter() {
377 /** Stops this connection. */
388 startTime = System.currentTimeMillis();
389 while (!stopped.get()) {
393 logger.finest(String.format("Getting %d bytes from %s...", 4096, source.name()));
394 buffer = source.get(4096);
395 logger.finest(String.format("Got %d bytes from %s.", buffer.length, source.name()));
396 } catch (IOException ioe1) {
397 throw new IOException(String.format("I/O error while reading from %s.", source.name()), ioe1);
399 List<Future<Void>> futures = executorService.invokeAll(FluentIterable.from(sinks).transform(new Function<Filter, Callable<Void>>() {
402 public Callable<Void> apply(final Filter sink) {
403 return new Callable<Void>() {
406 public Void call() throws Exception {
408 logger.finest(String.format("Sending %d bytes to %s.", buffer.length, sink.name()));
409 sink.process(buffer);
410 logger.finest(String.format("Sent %d bytes to %s.", buffer.length, sink.name()));
411 } catch (IOException ioe1) {
412 throw new IOException(String.format("I/O error while writing to %s", sink.name()), ioe1);
419 /* check all threads for exceptions. */
420 for (Future<Void> future : futures) {
423 counter += buffer.length;
424 } catch (IOException e) {
428 } catch (InterruptedException e) {
432 } catch (ExecutionException e) {
443 * Container for input and output counters.
445 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
447 public static class TrafficCounter {
449 /** The number of input bytes. */
450 private final long input;
452 /** The number of output bytes. */
453 private final long output;
456 * Creates a new traffic counter.
459 * The number of input bytes (may be {@code -1} to signify non-available
462 * The number of output bytes (may be {@code -1} to signify non-available
465 public TrafficCounter(long input, long output) {
467 this.output = output;
475 * Returns the number of input bytes.
477 * @return The number of input bytes, or {@link Optional#absent()} if the
478 * filter did not receive input
480 public Optional<Long> input() {
481 return (input == -1) ? Optional.<Long>absent() : Optional.of(input);
485 * Returns the number of output bytes.
487 * @return The number of output bytes, or {@link Optional#absent()} if the
488 * filter did not send output
490 public Optional<Long> output() {
491 return (output == -1) ? Optional.<Long>absent() : Optional.of(output);