923012e2640da80bcee51c1b20f07acc06aec9a7
[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 time this connection was started.
343                  *
344                  * @return The time this connection was started (in milliseconds since Jan 1,
345                  *         1970 UTC)
346                  */
347                 public long startTime() {
348                         return startTime;
349                 }
350
351                 /**
352                  * Returns the number of bytes that this connection has received from its
353                  * source during its lifetime.
354                  *
355                  * @return The number of processed input bytes
356                  */
357                 public long counter() {
358                         return counter;
359                 }
360
361                 //
362                 // ACTIONS
363                 //
364
365                 /** Stops this connection. */
366                 public void stop() {
367                         stopped.set(true);
368                 }
369
370                 //
371                 // RUNNABLE METHODS
372                 //
373
374                 @Override
375                 public void run() {
376                         startTime = System.currentTimeMillis();
377                         while (!stopped.get()) {
378                                 try {
379                                         final DataPacket dataPacket;
380                                         try {
381                                                 logger.finest(String.format("Getting %d bytes from %s...", 4096, source.name()));
382                                                 dataPacket = source.get(4096);
383                                                 logger.finest(String.format("Got %d bytes from %s.", dataPacket.buffer().length, source.name()));
384                                         } catch (IOException ioe1) {
385                                                 throw new IOException(String.format("I/O error while reading from %s.", source.name()), ioe1);
386                                         }
387                                         List<Future<Void>> futures = executorService.invokeAll(FluentIterable.from(sinks).transform(new Function<Filter, Callable<Void>>() {
388
389                                                 @Override
390                                                 public Callable<Void> apply(final Filter sink) {
391                                                         return new Callable<Void>() {
392
393                                                                 @Override
394                                                                 public Void call() throws Exception {
395                                                                         try {
396                                                                                 logger.finest(String.format("Sending %d bytes to %s.", dataPacket.buffer().length, sink.name()));
397                                                                                 sink.process(dataPacket);
398                                                                                 logger.finest(String.format("Sent %d bytes to %s.", dataPacket.buffer().length, sink.name()));
399                                                                         } catch (IOException ioe1) {
400                                                                                 throw new IOException(String.format("I/O error while writing to %s", sink.name()), ioe1);
401                                                                         }
402                                                                         return null;
403                                                                 }
404                                                         };
405                                                 }
406                                         }).toList());
407                                         /* check all threads for exceptions. */
408                                         for (Future<Void> future : futures) {
409                                                 future.get();
410                                         }
411                                         counter += dataPacket.buffer().length;
412                                 } catch (IOException e) {
413                                         /* TODO */
414                                         e.printStackTrace();
415                                         break;
416                                 } catch (InterruptedException e) {
417                                         /* TODO */
418                                         e.printStackTrace();
419                                         break;
420                                 } catch (ExecutionException e) {
421                                         /* TODO */
422                                         e.printStackTrace();
423                                         break;
424                                 }
425                         }
426                 }
427
428         }
429
430         /**
431          * Container for input and output counters.
432          *
433          * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
434          */
435         public static class TrafficCounter {
436
437                 /** The number of input bytes. */
438                 private final long input;
439
440                 /** The number of output bytes. */
441                 private final long output;
442
443                 /**
444                  * Creates a new traffic counter.
445                  *
446                  * @param input
447                  *              The number of input bytes (may be {@code -1} to signify non-available
448                  *              input)
449                  * @param output
450                  *              The number of output bytes (may be {@code -1} to signify non-available
451                  *              output)
452                  */
453                 public TrafficCounter(long input, long output) {
454                         this.input = input;
455                         this.output = output;
456                 }
457
458                 //
459                 // ACCESSORS
460                 //
461
462                 /**
463                  * Returns the number of input bytes.
464                  *
465                  * @return The number of input bytes, or {@link Optional#absent()} if the
466                  *         filter did not receive input
467                  */
468                 public Optional<Long> input() {
469                         return (input == -1) ? Optional.<Long>absent() : Optional.of(input);
470                 }
471
472                 /**
473                  * Returns the number of output bytes.
474                  *
475                  * @return The number of output bytes, or {@link Optional#absent()} if the
476                  *         filter did not send output
477                  */
478                 public Optional<Long> output() {
479                         return (output == -1) ? Optional.<Long>absent() : Optional.of(output);
480                 }
481
482         }
483
484 }