Pull all interfaces into a single interface: Filter.
[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.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;
43
44 /**
45  * A pipeline is responsible for streaming audio data from a {@link Filter} to
46  * an arbitrary number of connected {@link Filter}s.
47  *
48  * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
49  */
50 public class Pipeline implements Iterable<Filter> {
51
52         /** The logger. */
53         private static final Logger logger = Logger.getLogger(Pipeline.class.getName());
54
55         /** The source of the audio stream. */
56         private final Filter source;
57
58         /** The filters for each source. */
59         private final ListMultimap<Filter, Filter> filters;
60
61         /** All started connections. */
62         private final List<Connection> connections = Lists.newArrayList();
63
64         /**
65          * Creates a new pipeline.
66          *
67          * @param source
68          *              The source of the audio stream
69          * @param filters
70          *              The filters for each source
71          */
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() {
78
79                                 @Override
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);
84                                         }
85                                 }
86                         });
87                 }
88         }
89
90         //
91         // ACCESSORS
92         //
93
94         /**
95          * Expose this pipeline’s source.
96          *
97          * @return This pipeline’s source
98          */
99         public Filter source() {
100                 return source;
101         }
102
103         /**
104          * Returns all {@link Filter}s that are connected to the given filter.
105          *
106          * @param 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
110          */
111         public List<Filter> filters(Filter filter) {
112                 return filters.get(filter);
113         }
114
115         /**
116          * Returns the traffic counters of the given filter.
117          *
118          * @param filter
119          *              The filter to get the traffic counters for
120          * @return The traffic counters for the given filter
121          */
122         public TrafficCounter trafficCounter(Filter filter) {
123                 long input = -1;
124                 long output = -1;
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();
131                         }
132                 }
133                 return new TrafficCounter(input, output);
134         }
135
136         //
137         // ACTIONS
138         //
139
140         /**
141          * Starts the pipeline.
142          *
143          * @throws IOException
144          *              if any of the filters can not be opened
145          * @throws IllegalStateException
146          *              if the pipeline is already running
147          */
148         public void start() throws IOException, IllegalStateException {
149                 if (!connections.isEmpty()) {
150                         throw new IllegalStateException("Pipeline is already running!");
151                 }
152                 List<Filter> filters = Lists.newArrayList();
153                 filters.add(source);
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());
162                                 filters.add(sink);
163                         }
164                 }
165                 for (Connection connection : connections) {
166                         String threadName = String.format("%s → %s.", connection.source.name(), FluentIterable.from(connection.sinks).transform(new Function<Filter, String>() {
167
168                                 @Override
169                                 public String apply(Filter sink) {
170                                         return sink.name();
171                                 }
172                         }));
173                         logger.info(String.format("Starting Thread: %s", threadName));
174                         new Thread(connection, threadName).start();
175                 }
176         }
177
178         public void stop() {
179                 if (!connections.isEmpty()) {
180                         /* pipeline is not running. */
181                         return;
182                 }
183                 for (Connection connection : connections) {
184                         connection.stop();
185                 }
186         }
187
188         //
189         // ITERABLE METHODS
190         //
191
192         @Override
193         public Iterator<Filter> iterator() {
194                 return filters().iterator();
195         }
196
197         //
198         // PRIVATE METHODS
199         //
200
201         /**
202          * Returns all filters of this pipeline, listed breadth-first, starting with
203          * the source.
204          *
205          * @return All filters of this pipeline
206          */
207         public List<Filter> filters() {
208                 ImmutableList.Builder<Filter> filters = ImmutableList.builder();
209                 List<Filter> remainingFilters = Lists.newArrayList();
210                 filters.add(source);
211                 remainingFilters.add(source);
212                 while (!remainingFilters.isEmpty()) {
213                         Collection<Filter> sinks = this.filters(remainingFilters.remove(0));
214                         for (Filter sink : sinks) {
215                                 filters.add(sink);
216                                 remainingFilters.add(sink);
217                         }
218                 }
219                 return filters.build();
220         }
221
222         //
223         // STATIC METHODS
224         //
225
226         /**
227          * Returns a new pipeline builder.
228          *
229          * @param source
230          *              The source at which to start
231          * @return A builder for a new pipeline
232          */
233         public static Builder builder(Filter source) {
234                 return new Builder(source);
235         }
236
237         /**
238          * A builder for a {@link Pipeline}.
239          *
240          * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
241          */
242         public static class Builder {
243
244                 /** The source of the pipeline. */
245                 private final Filter source;
246
247                 /** The filters to which each source streams. */
248                 private Multimap<Filter, Filter> nextSinks = ArrayListMultimap.create();
249
250                 /** The last added source. */
251                 private Filter lastSource;
252
253                 /**
254                  * Creates a new builder.
255                  *
256                  * @param source
257                  *              The source that starts the pipeline
258                  */
259                 private Builder(Filter source) {
260                         this.source = source;
261                         lastSource = source;
262                 }
263
264                 /**
265                  * Adds a {@link Filter} as a recipient for the last added source.
266                  *
267                  * @param sink
268                  *              The sink to add
269                  * @return This builder
270                  */
271                 public Builder to(Filter sink) {
272                         nextSinks.put(lastSource, sink);
273                         lastSource = sink;
274                         return this;
275                 }
276
277                 /**
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.
280                  *
281                  * @param source
282                  *              The source to locate
283                  * @return This builder
284                  * @throws IllegalStateException
285                  *              if the given source was not previously added as a sink
286                  */
287                 public Builder find(Filter source) {
288                         Preconditions.checkState(nextSinks.containsValue(source));
289                         lastSource = source;
290                         return this;
291                 }
292
293                 /**
294                  * Builds the pipeline.
295                  *
296                  * @return The created pipeline
297                  */
298                 public Pipeline build() {
299                         return new Pipeline(source, ImmutableMultimap.copyOf(nextSinks));
300                 }
301
302         }
303
304         /**
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.
308          *
309          * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
310          */
311         public class Connection implements Runnable {
312
313                 /** The source. */
314                 private final Filter source;
315
316                 /** The filters. */
317                 private final Collection<Filter> sinks;
318
319                 /** Whether the feeder was stopped. */
320                 private final AtomicBoolean stopped = new AtomicBoolean(false);
321
322                 /** The executor service. */
323                 private final ExecutorService executorService;
324
325                 /** The time the connection was started. */
326                 private long startTime;
327
328                 /** The number of copied bytes. */
329                 private long counter;
330
331                 /**
332                  * Creates a new connection.
333                  *
334                  * @param source
335                  *              The source of the stream
336                  * @param sinks
337                  *              The filters to which to stream
338                  */
339                 public Connection(Filter source, Collection<Filter> sinks) {
340                         this.source = source;
341                         this.sinks = sinks;
342                         if (sinks.size() < 2) {
343                                 executorService = MoreExecutors.sameThreadExecutor();
344                         } else {
345                                 executorService = Executors.newCachedThreadPool();
346                         }
347                 }
348
349                 //
350                 // ACCESSORS
351                 //
352
353                 /**
354                  * Returns the time this connection was started.
355                  *
356                  * @return The time this connection was started (in milliseconds since Jan 1,
357                  *         1970 UTC)
358                  */
359                 public long startTime() {
360                         return startTime;
361                 }
362
363                 /**
364                  * Returns the number of bytes that this connection has received from its
365                  * source during its lifetime.
366                  *
367                  * @return The number of processed input bytes
368                  */
369                 public long counter() {
370                         return counter;
371                 }
372
373                 //
374                 // ACTIONS
375                 //
376
377                 /** Stops this connection. */
378                 public void stop() {
379                         stopped.set(true);
380                 }
381
382                 //
383                 // RUNNABLE METHODS
384                 //
385
386                 @Override
387                 public void run() {
388                         startTime = System.currentTimeMillis();
389                         while (!stopped.get()) {
390                                 try {
391                                         final byte[] buffer;
392                                         try {
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);
398                                         }
399                                         List<Future<Void>> futures = executorService.invokeAll(FluentIterable.from(sinks).transform(new Function<Filter, Callable<Void>>() {
400
401                                                 @Override
402                                                 public Callable<Void> apply(final Filter sink) {
403                                                         return new Callable<Void>() {
404
405                                                                 @Override
406                                                                 public Void call() throws Exception {
407                                                                         try {
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);
413                                                                         }
414                                                                         return null;
415                                                                 }
416                                                         };
417                                                 }
418                                         }).toList());
419                                         /* check all threads for exceptions. */
420                                         for (Future<Void> future : futures) {
421                                                 future.get();
422                                         }
423                                         counter += buffer.length;
424                                 } catch (IOException e) {
425                                         /* TODO */
426                                         e.printStackTrace();
427                                         break;
428                                 } catch (InterruptedException e) {
429                                         /* TODO */
430                                         e.printStackTrace();
431                                         break;
432                                 } catch (ExecutionException e) {
433                                         /* TODO */
434                                         e.printStackTrace();
435                                         break;
436                                 }
437                         }
438                 }
439
440         }
441
442         /**
443          * Container for input and output counters.
444          *
445          * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
446          */
447         public static class TrafficCounter {
448
449                 /** The number of input bytes. */
450                 private final long input;
451
452                 /** The number of output bytes. */
453                 private final long output;
454
455                 /**
456                  * Creates a new traffic counter.
457                  *
458                  * @param input
459                  *              The number of input bytes (may be {@code -1} to signify non-available
460                  *              input)
461                  * @param output
462                  *              The number of output bytes (may be {@code -1} to signify non-available
463                  *              output)
464                  */
465                 public TrafficCounter(long input, long output) {
466                         this.input = input;
467                         this.output = output;
468                 }
469
470                 //
471                 // ACCESSORS
472                 //
473
474                 /**
475                  * Returns the number of input bytes.
476                  *
477                  * @return The number of input bytes, or {@link Optional#absent()} if the
478                  *         filter did not receive input
479                  */
480                 public Optional<Long> input() {
481                         return (input == -1) ? Optional.<Long>absent() : Optional.of(input);
482                 }
483
484                 /**
485                  * Returns the number of output bytes.
486                  *
487                  * @return The number of output bytes, or {@link Optional#absent()} if the
488                  *         filter did not send output
489                  */
490                 public Optional<Long> output() {
491                         return (output == -1) ? Optional.<Long>absent() : Optional.of(output);
492                 }
493
494         }
495
496 }