Rename “Controlled” to “ControlledComponent.”
[sonitus.git] / src / main / java / net / pterodactylus / sonitus / data / Pipeline.java
1 /*
2  * Sonitus - Pipeline.java - Copyright © 2013 David Roden
3  *
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.
8  *
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.
13  *
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/>.
16  */
17
18 package net.pterodactylus.sonitus.data;
19
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;
31
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;
42
43 /**
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.
46  *
47  * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
48  */
49 public class Pipeline implements Iterable<ControlledComponent> {
50
51         /** The logger. */
52         private static final Logger logger = Logger.getLogger(Pipeline.class.getName());
53
54         /** The source of the audio stream. */
55         private final Source source;
56
57         /** The sinks for each source. */
58         private final Multimap<Source, Sink> sinks;
59
60         /** All started connections. */
61         private final List<Connection> connections = Lists.newArrayList();
62
63         /**
64          * Creates a new pipeline.
65          *
66          * @param source
67          *              The source of the audio stream
68          * @param sinks
69          *              The sinks for each source
70          */
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         }
75
76         //
77         // ACCESSORS
78         //
79
80         /**
81          * Expose this pipeline’s source.
82          *
83          * @return This pipeline’s source
84          */
85         public Source source() {
86                 return source;
87         }
88
89         /**
90          * Returns all {@link Sink}s (or {@link Filter}s, really) that are connected to
91          * the given source.
92          *
93          * @param source
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
97          */
98         public Collection<Sink> sinks(Source source) {
99                 return sinks.get(source);
100         }
101
102         /**
103          * Returns the traffic counters of the given controlled component.
104          *
105          * @param controlledComponent
106          *              The controlled component to get the traffic counters for
107          * @return The traffic counters for the given controlled component
108          */
109         public TrafficCounter trafficCounter(ControlledComponent controlledComponent) {
110                 long input = -1;
111                 long output = -1;
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();
118                         }
119                 }
120                 return new TrafficCounter(input, output);
121         }
122
123         //
124         // ACTIONS
125         //
126
127         /**
128          * Starts the pipeline.
129          *
130          * @throws IOException
131          *              if any of the sinks can not be opened
132          * @throws IllegalStateException
133          *              if the pipeline is already running
134          */
135         public void start() throws IOException, IllegalStateException {
136                 if (!connections.isEmpty()) {
137                         throw new IllegalStateException("Pipeline is already running!");
138                 }
139                 List<Source> sources = Lists.newArrayList();
140                 sources.add(source);
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);
150                                 }
151                         }
152                 }
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();
156                 }
157         }
158
159         public void stop() {
160                 if (!connections.isEmpty()) {
161                         /* pipeline is not running. */
162                         return;
163                 }
164                 for (Connection connection : connections) {
165                         connection.stop();
166                 }
167         }
168
169         //
170         // ITERABLE METHODS
171         //
172
173         @Override
174         public Iterator<ControlledComponent> iterator() {
175                 return ImmutableSet.<ControlledComponent>builder().add(source).addAll(sinks.values()).build().iterator();
176         }
177
178         //
179         // STATIC METHODS
180         //
181
182         /**
183          * Returns a new pipeline builder.
184          *
185          * @param source
186          *              The source at which to start
187          * @return A builder for a new pipeline
188          */
189         public static Builder builder(Source source) {
190                 return new Builder(source);
191         }
192
193         /**
194          * A builder for a {@link Pipeline}.
195          *
196          * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
197          */
198         public static class Builder {
199
200                 /** The source of the pipeline. */
201                 private final Source source;
202
203                 /** The sinks to which each source streams. */
204                 private Multimap<Source, Sink> nextSinks = ArrayListMultimap.create();
205
206                 /** The last added source. */
207                 private Source lastSource;
208
209                 /**
210                  * Creates a new builder.
211                  *
212                  * @param source
213                  *              The source that starts the pipeline
214                  */
215                 private Builder(Source source) {
216                         this.source = source;
217                         lastSource = source;
218                 }
219
220                 /**
221                  * Adds a {@link Sink} (or {@link Filter} as a recipient for the last added
222                  * {@link Source}.
223                  *
224                  * @param sink
225                  *              The sink to add
226                  * @return This builder
227                  * @throws IllegalStateException
228                  *              if the last added {@link Sink} was not also a {@link Source}
229                  */
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;
234                         return this;
235                 }
236
237                 /**
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.
240                  *
241                  * @param source
242                  *              The source to locate
243                  * @return This builder
244                  * @throws IllegalStateException
245                  *              if the given source was not previously added as a sink
246                  */
247                 public Builder find(Source source) {
248                         Preconditions.checkState(nextSinks.containsValue(source));
249                         lastSource = source;
250                         return this;
251                 }
252
253                 /**
254                  * Builds the pipeline.
255                  *
256                  * @return The created pipeline
257                  */
258                 public Pipeline build() {
259                         return new Pipeline(source, ImmutableMultimap.copyOf(nextSinks));
260                 }
261
262         }
263
264         /**
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.
268          *
269          * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
270          */
271         public class Connection implements Runnable {
272
273                 /** The source. */
274                 private final Source source;
275
276                 /** The sinks. */
277                 private final Collection<Sink> sinks;
278
279                 /** Whether the feeder was stopped. */
280                 private final AtomicBoolean stopped = new AtomicBoolean(false);
281
282                 /** The executor service. */
283                 private final ExecutorService executorService;
284
285                 /** The number of copied bytes. */
286                 private long counter;
287
288                 /**
289                  * Creates a new connection.
290                  *
291                  * @param source
292                  *              The source of the stream
293                  * @param sinks
294                  *              The sinks to which to stream
295                  */
296                 public Connection(Source source, Collection<Sink> sinks) {
297                         this.source = source;
298                         this.sinks = sinks;
299                         if (sinks.size() == 1) {
300                                 executorService = MoreExecutors.sameThreadExecutor();
301                         } else {
302                                 executorService = Executors.newCachedThreadPool();
303                         }
304                 }
305
306                 //
307                 // ACCESSORS
308                 //
309
310                 /**
311                  * Returns the number of bytes that this connection has received from its
312                  * source during its lifetime.
313                  *
314                  * @return The number of processed input bytes
315                  */
316                 public long counter() {
317                         return counter;
318                 }
319
320                 //
321                 // ACTIONS
322                 //
323
324                 /** Stops this connection. */
325                 public void stop() {
326                         stopped.set(true);
327                 }
328
329                 //
330                 // RUNNABLE METHODS
331                 //
332
333                 @Override
334                 public void run() {
335                         Metadata firstMetadata = null;
336                         while (!stopped.get()) {
337                                 try {
338                                         final Metadata lastMetadata = firstMetadata;
339                                         final Metadata metadata = firstMetadata = source.metadata();
340                                         final byte[] buffer;
341                                         try {
342                                                 logger.finest(String.format("Getting %d bytes from %s...", 4096, source));
343                                                 buffer = source.get(4096);
344                                                 logger.finest(String.format("Got %d bytes from %s.", buffer.length, source));
345                                         } catch (IOException ioe1) {
346                                                 throw new IOException(String.format("I/O error while reading from %s.", source), ioe1);
347                                         }
348                                         List<Future<Void>> futures = executorService.invokeAll(FluentIterable.from(sinks).transform(new Function<Sink, Callable<Void>>() {
349
350                                                 @Override
351                                                 public Callable<Void> apply(final Sink sink) {
352                                                         return new Callable<Void>() {
353
354                                                                 @Override
355                                                                 public Void call() throws Exception {
356                                                                         if (!metadata.equals(lastMetadata)) {
357                                                                                 sink.metadataUpdated(metadata);
358                                                                         }
359                                                                         try {
360                                                                                 logger.finest(String.format("Sending %d bytes to %s.", buffer.length, sink));
361                                                                                 sink.process(buffer);
362                                                                                 logger.finest(String.format("Sent %d bytes to %s.", buffer.length, sink));
363                                                                         } catch (IOException ioe1) {
364                                                                                 throw new IOException(String.format("I/O error while writing to %s", sink), ioe1);
365                                                                         }
366                                                                         return null;
367                                                                 }
368                                                         };
369                                                 }
370                                         }).toList());
371                                         /* check all threads for exceptions. */
372                                         for (Future<Void> future : futures) {
373                                                 future.get();
374                                         }
375                                         counter += buffer.length;
376                                 } catch (IOException e) {
377                                         /* TODO */
378                                         e.printStackTrace();
379                                         break;
380                                 } catch (InterruptedException e) {
381                                         /* TODO */
382                                         e.printStackTrace();
383                                         break;
384                                 } catch (ExecutionException e) {
385                                         /* TODO */
386                                         e.printStackTrace();
387                                         break;
388                                 }
389                         }
390                 }
391
392         }
393
394         /**
395          * Container for input and output counters.
396          *
397          * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
398          */
399         public static class TrafficCounter {
400
401                 /** The number of input bytes. */
402                 private final long input;
403
404                 /** The number of output bytes. */
405                 private final long output;
406
407                 /**
408                  * Creates a new traffic counter.
409                  *
410                  * @param input
411                  *              The number of input bytes (may be {@code -1} to signify non-available
412                  *              input)
413                  * @param output
414                  *              The number of output bytes (may be {@code -1} to signify non-available
415                  *              output)
416                  */
417                 public TrafficCounter(long input, long output) {
418                         this.input = input;
419                         this.output = output;
420                 }
421
422                 //
423                 // ACCESSORS
424                 //
425
426                 /**
427                  * Returns the number of input bytes.
428                  *
429                  * @return The number of input bytes, or {@link Optional#absent()} if the
430                  *         component can not receive input
431                  */
432                 public Optional<Long> input() {
433                         return (input == -1) ? Optional.<Long>absent() : Optional.of(input);
434                 }
435
436                 /**
437                  * Returns the number of output bytes.
438                  *
439                  * @return The number of output bytes, or {@link Optional#absent()} if the
440                  *         component can not send output
441                  */
442                 public Optional<Long> output() {
443                         return (output == -1) ? Optional.<Long>absent() : Optional.of(output);
444                 }
445
446         }
447
448 }