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