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