Send metadata updates events when the metadata changes.
[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.FloatControl.Type.VOLUME;
21
22 import java.io.IOException;
23 import java.io.OutputStream;
24 import java.util.Arrays;
25 import java.util.List;
26 import java.util.logging.Logger;
27 import javax.sound.sampled.AudioFormat;
28 import javax.sound.sampled.AudioSystem;
29 import javax.sound.sampled.FloatControl;
30 import javax.sound.sampled.LineUnavailableException;
31 import javax.sound.sampled.SourceDataLine;
32
33 import net.pterodactylus.sonitus.data.Controller;
34 import net.pterodactylus.sonitus.data.Metadata;
35 import net.pterodactylus.sonitus.data.Sink;
36 import net.pterodactylus.sonitus.data.Source;
37 import net.pterodactylus.sonitus.data.controller.Fader;
38 import net.pterodactylus.sonitus.data.controller.Switch;
39 import net.pterodactylus.sonitus.data.event.MetadataUpdated;
40 import net.pterodactylus.sonitus.io.IntegralWriteOutputStream;
41
42 import com.google.common.base.Preconditions;
43 import com.google.common.eventbus.EventBus;
44
45 /**
46  * {@link Sink} implementation that uses the JDK’s {@link AudioSystem} to play
47  * all {@link Source}s.
48  *
49  * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
50  */
51 public class AudioSink implements Sink {
52
53         /** The logger. */
54         private static final Logger logger = Logger.getLogger(AudioSink.class.getName());
55
56         /** The event bus. */
57         private final EventBus eventBus;
58
59         /** The volume fader. */
60         private final Fader volumeFader;
61
62         /** The “mute” switch. */
63         private final Switch muteSwitch;
64
65         /** The current metadata. */
66         private Metadata metadata;
67
68         /** The audio output. */
69         private SourceDataLine sourceDataLine;
70
71         /** A buffered output stream to ensure correct writing to the source data line. */
72         private OutputStream sourceDataLineOutputStream = new IntegralWriteOutputStream(new OutputStream() {
73
74                 @Override
75                 public void write(int b) throws IOException {
76                 }
77
78                 @Override
79                 public void write(byte[] b) throws IOException {
80                         write(b, 0, b.length);
81                 }
82
83                 @Override
84                 public void write(byte[] b, int off, int len) throws IOException {
85                         if (sourceDataLine != null) {
86                                 sourceDataLine.write(b, off, len);
87                         }
88                 }
89         }, 1024);
90
91         /**
92          * Creates a new audio sink.
93          *
94          * @param eventBus
95          *              The event bus
96          */
97         public AudioSink(EventBus eventBus) {
98                 this.eventBus = eventBus;
99                 volumeFader = new Fader("Volume") {
100
101                         @Override
102                         protected void valueSet(Double value) {
103                                 if (sourceDataLine != null) {
104                                         FloatControl volumeControl = (FloatControl) sourceDataLine.getControl(VOLUME);
105                                         volumeControl.setValue((float) (value * volumeControl.getMaximum()));
106                                 }
107                         }
108                 };
109                 muteSwitch = new Switch("Mute") {
110
111                         private float previousValue;
112
113                         @Override
114                         protected void valueSet(Boolean value) {
115                                 if (sourceDataLine != null) {
116                                         FloatControl volumeControl = (FloatControl) sourceDataLine.getControl(VOLUME);
117                                         if (value) {
118                                                 previousValue = volumeControl.getValue();
119                                                 volumeControl.setValue(0);
120                                         } else {
121                                                 volumeControl.setValue(previousValue);
122                                         }
123                                 }
124                         }
125                 };
126         }
127
128         //
129         // CONTROLLED METHODS
130         //
131
132         @Override
133         public String name() {
134                 return "Audio Output";
135         }
136
137         @Override
138         public Metadata metadata() {
139                 return metadata;
140         }
141
142         @Override
143         public List<Controller<?>> controllers() {
144                 return Arrays.<Controller<?>>asList(volumeFader, muteSwitch);
145         }
146
147         //
148         // SINK METHODS
149         //
150
151         @Override
152         public void open(Metadata metadata) throws IOException {
153                 Preconditions.checkArgument(metadata.encoding().equalsIgnoreCase("PCM"), "source must be PCM-encoded");
154                 AudioFormat audioFormat = new AudioFormat(metadata.frequency(), 16, metadata.channels(), true, false);
155                 try {
156                         sourceDataLine = AudioSystem.getSourceDataLine(audioFormat);
157                         sourceDataLine.open(audioFormat);
158                         sourceDataLine.start();
159                         metadataUpdated(metadata);
160                 } catch (LineUnavailableException e) {
161                         /* TODO */
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                 logger.info(String.format("Now playing %s.", metadata));
175                 this.metadata = metadata;
176                 eventBus.post(new MetadataUpdated(this, metadata));
177         }
178
179         @Override
180         public void process(byte[] buffer) throws IOException {
181                 sourceDataLineOutputStream.write(buffer);
182                 logger.finest(String.format("AudioSink: Wrote %d Bytes.", buffer.length));
183         }
184
185 }