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