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