Add metadata listeners to components.
[sonitus.git] / src / main / java / net / pterodactylus / sonitus / data / sink / AudioSink.java
1 /*
2  * Sonitus - AudioSink.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.sink;
19
20 import static javax.sound.sampled.BooleanControl.Type.MUTE;
21 import static javax.sound.sampled.FloatControl.Type.VOLUME;
22
23 import java.io.IOException;
24 import java.io.OutputStream;
25 import java.util.Arrays;
26 import java.util.List;
27 import java.util.logging.Logger;
28 import javax.sound.sampled.AudioFormat;
29 import javax.sound.sampled.AudioSystem;
30 import javax.sound.sampled.BooleanControl;
31 import javax.sound.sampled.Control;
32 import javax.sound.sampled.DataLine;
33 import javax.sound.sampled.FloatControl;
34 import javax.sound.sampled.LineUnavailableException;
35 import javax.sound.sampled.SourceDataLine;
36
37 import net.pterodactylus.sonitus.data.AbstractControlledComponent;
38 import net.pterodactylus.sonitus.data.Controller;
39 import net.pterodactylus.sonitus.data.Metadata;
40 import net.pterodactylus.sonitus.data.Sink;
41 import net.pterodactylus.sonitus.data.Source;
42 import net.pterodactylus.sonitus.data.controller.Fader;
43 import net.pterodactylus.sonitus.data.controller.Switch;
44 import net.pterodactylus.sonitus.data.event.MetadataUpdated;
45 import net.pterodactylus.sonitus.io.IntegralWriteOutputStream;
46
47 import com.google.common.base.Preconditions;
48 import com.google.common.eventbus.EventBus;
49
50 /**
51  * {@link Sink} implementation that uses the JDK’s {@link AudioSystem} to play
52  * all {@link Source}s.
53  *
54  * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
55  */
56 public class AudioSink extends AbstractControlledComponent implements Sink {
57
58         /** The logger. */
59         private static final Logger logger = Logger.getLogger(AudioSink.class.getName());
60
61         /** The event bus. */
62         private final EventBus eventBus;
63
64         /** The volume fader. */
65         private final Fader volumeFader;
66
67         /** The “mute” switch. */
68         private final Switch muteSwitch;
69
70         /** The current metadata. */
71         private Metadata metadata;
72
73         /** The audio output. */
74         private SourceDataLine sourceDataLine;
75
76         /** A buffered output stream to ensure correct writing to the source data line. */
77         private OutputStream sourceDataLineOutputStream = new IntegralWriteOutputStream(new OutputStream() {
78
79                 @Override
80                 public void write(int b) throws IOException {
81                 }
82
83                 @Override
84                 public void write(byte[] b) throws IOException {
85                         write(b, 0, b.length);
86                 }
87
88                 @Override
89                 public void write(byte[] b, int off, int len) throws IOException {
90                         if (sourceDataLine != null) {
91                                 sourceDataLine.write(b, off, len);
92                         }
93                 }
94         }, 1024);
95
96         /**
97          * Creates a new audio sink.
98          *
99          * @param eventBus
100          *              The event bus
101          */
102         public AudioSink(EventBus eventBus) {
103                 this.eventBus = eventBus;
104                 volumeFader = new Fader("Volume") {
105
106                         @Override
107                         protected void valueSet(Double value) {
108                                 /* search for preferred volume control. */
109                                 FloatControl volumeControl = getVolumeControl(sourceDataLine);
110                                 if (volumeControl == null) {
111                                         /* could not find volume control! */
112                                         return;
113                                 }
114
115                                 volumeControl.setValue((float) (value * volumeControl.getMaximum()));
116                         }
117                 };
118                 muteSwitch = new Switch("Mute") {
119
120                         /** The previous value in case we have to emulate the mute control. */
121                         private float previousValue;
122
123                         @Override
124                         protected void valueSet(Boolean value) {
125                                 /* search for mute control. */
126                                 BooleanControl muteControl = getMuteControl(sourceDataLine);
127                                 if (muteControl != null) {
128                                         muteControl.setValue(value);
129                                         return;
130                                 }
131
132                                 /* could not find mute control, use volume control! */
133                                 FloatControl volumeControl = getVolumeControl(sourceDataLine);
134                                 if (volumeControl == null) {
135                                         /* no volume control, either? */
136                                         return;
137                                 }
138
139                                 if (value) {
140                                         previousValue = volumeControl.getValue();
141                                         volumeControl.setValue(0);
142                                 } else {
143                                         volumeControl.setValue(previousValue);
144                                 }
145                         }
146
147                 };
148         }
149
150         //
151         // CONTROLLED METHODS
152         //
153
154         @Override
155         public String name() {
156                 return "Audio Output";
157         }
158
159         @Override
160         public Metadata metadata() {
161                 return metadata;
162         }
163
164         @Override
165         public List<Controller<?>> controllers() {
166                 return Arrays.<Controller<?>>asList(volumeFader, muteSwitch);
167         }
168
169         //
170         // SINK METHODS
171         //
172
173         @Override
174         public void open(Metadata metadata) throws IOException {
175                 Preconditions.checkArgument(metadata.encoding().equalsIgnoreCase("PCM"), "source must be PCM-encoded");
176                 AudioFormat audioFormat = new AudioFormat(metadata.frequency(), 16, metadata.channels(), true, false);
177                 try {
178                         sourceDataLine = AudioSystem.getSourceDataLine(audioFormat);
179                         sourceDataLine.open(audioFormat);
180                         sourceDataLine.start();
181                         metadataUpdated(metadata);
182                 } catch (LineUnavailableException e) {
183                         /* TODO */
184                         sourceDataLine = null;
185                         throw new IOException(e);
186                 }
187         }
188
189         @Override
190         public void close() {
191                 sourceDataLine.stop();
192                 sourceDataLine.close();
193         }
194
195         @Override
196         public void metadataUpdated(Metadata metadata) {
197                 logger.info(String.format("Now playing %s.", metadata));
198                 this.metadata = metadata;
199                 fireMetadataUpdated(metadata);
200                 eventBus.post(new MetadataUpdated(this, metadata));
201         }
202
203         @Override
204         public void process(byte[] buffer) throws IOException {
205                 sourceDataLineOutputStream.write(buffer);
206                 logger.finest(String.format("AudioSink: Wrote %d Bytes.", buffer.length));
207         }
208
209         //
210         // PRIVATE METHODS
211         //
212
213         /**
214          * Returns the {@link FloatControl.Type.VOLUME} control.
215          *
216          * @param dataLine
217          *              The data line to search for the control
218          * @return The control, or {@code null} if no volume control could be found
219          */
220         private static FloatControl getVolumeControl(DataLine dataLine) {
221                 return getControl(dataLine, VOLUME, FloatControl.class);
222         }
223
224         /**
225          * Returns the {@link BooleanControl.Type.MUTE} control.
226          *
227          * @param dataLine
228          *              The data line to search for the control
229          * @return The control, or {@code null} if no mute control could be found
230          */
231         private static BooleanControl getMuteControl(DataLine dataLine) {
232                 return getControl(dataLine, MUTE, BooleanControl.class);
233         }
234
235         /**
236          * Searches the given data line for a control of the given type and returns it.
237          * If the given data line is {@code null}, {@code null} is returned.
238          *
239          * @param dataLine
240          *              The data line to search for a control
241          * @param controlType
242          *              The type of the control to search
243          * @param controlClass
244          *              The class of the control
245          * @param <T>
246          *              The class of the control
247          * @return The control, or {@code null} if no control could be found
248          */
249         private static <T> T getControl(DataLine dataLine, Control.Type controlType, Class<T> controlClass) {
250                 if (dataLine == null) {
251                         return null;
252                 }
253                 Control[] controls = dataLine.getControls();
254                 for (Control control : controls) {
255                         if (control.getType().equals(controlType)) {
256                                 return (T) control;
257                         }
258                 }
259                 return null;
260         }
261
262 }