87d94969a35114a2ecfc990bb467a948838bd75a
[sonitus.git] / src / main / java / net / pterodactylus / sonitus / data / sink / Icecast2Sink.java
1 /*
2  * Sonitus - Icecast2Sink.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 java.io.IOException;
21 import java.io.InputStream;
22 import java.io.OutputStream;
23 import java.io.UnsupportedEncodingException;
24 import java.net.Socket;
25 import java.net.URLEncoder;
26 import java.util.Collections;
27 import java.util.List;
28 import java.util.logging.Level;
29 import java.util.logging.Logger;
30
31 import net.pterodactylus.sonitus.data.Controller;
32 import net.pterodactylus.sonitus.data.Metadata;
33 import net.pterodactylus.sonitus.data.Sink;
34 import net.pterodactylus.sonitus.data.event.MetadataUpdated;
35 import net.pterodactylus.sonitus.io.InputStreamDrainer;
36
37 import com.google.common.eventbus.EventBus;
38 import com.google.common.io.BaseEncoding;
39 import com.google.common.io.Closeables;
40
41 /**
42  * {@link net.pterodactylus.sonitus.data.Sink} implementation that delivers all
43  * incoming data to an Icecast2 server.
44  *
45  * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
46  */
47 public class Icecast2Sink implements Sink {
48
49         /** The logger. */
50         private static final Logger logger = Logger.getLogger(Icecast2Sink.class.getName());
51
52         /** The event bus. */
53         private final EventBus eventBus;
54
55         /** The server name. */
56         private final String server;
57
58         /** The port number on the server. */
59         private final int port;
60
61         /** The source password. */
62         private final String password;
63
64         /** The stream mount point (without leading slash). */
65         private final String mountPoint;
66
67         /** The name of the server. */
68         private final String serverName;
69
70         /** The description of the server. */
71         private final String serverDescription;
72
73         /** The genre of the server. */
74         private final String genre;
75
76         /** Whether to publish the server. */
77         private final boolean publishServer;
78
79         /** The output stream to the server. */
80         private OutputStream socketOutputStream;
81
82         /** The current metadata. */
83         private Metadata metadata;
84
85         /**
86          * Creates a new Icecast2 sink.
87          *
88          * @param eventBus
89          *              The event bus
90          * @param server
91          *              The hostname of the server
92          * @param port
93          *              The port number of the server
94          * @param password
95          *              The source password
96          * @param mountPoint
97          *              The stream mount point
98          * @param serverName
99          *              The name of the server
100          * @param serverDescription
101          *              The description of the server
102          * @param genre
103          *              The genre of the server
104          * @param publishServer
105          *              {@code true} to publish the server in a public directory, {@code false} to
106          *              not publish it
107          */
108         public Icecast2Sink(EventBus eventBus, String server, int port, String password, String mountPoint, String serverName, String serverDescription, String genre, boolean publishServer) {
109                 this.eventBus = eventBus;
110                 this.server = server;
111                 this.port = port;
112                 this.password = password;
113                 this.mountPoint = mountPoint;
114                 this.serverName = serverName;
115                 this.serverDescription = serverDescription;
116                 this.genre = genre;
117                 this.publishServer = publishServer;
118         }
119
120         //
121         // CONTROLLED METHODS
122         //
123
124         @Override
125         public String name() {
126                 return String.format("icecast://%s:%d/%s", server, port, mountPoint);
127         }
128
129         @Override
130         public Metadata metadata() {
131                 return metadata;
132         }
133
134         @Override
135         public List<Controller<?>> controllers() {
136                 return Collections.emptyList();
137         }
138
139         //
140         // SINK METHODS
141         //
142
143         @Override
144         public void open(Metadata metadata) throws IOException {
145                 logger.info(String.format("Connecting to %s:%d...", server, port));
146                 Socket socket = new Socket(server, port);
147                 logger.info("Connected.");
148                 socketOutputStream = socket.getOutputStream();
149                 InputStream socketInputStream = socket.getInputStream();
150
151                 sendLine(socketOutputStream, String.format("SOURCE /%s ICE/1.0", mountPoint));
152                 sendLine(socketOutputStream, String.format("Authorization: Basic %s", generatePassword(password)));
153                 sendLine(socketOutputStream, String.format("Content-Type: %s", getContentType(metadata)));
154                 sendLine(socketOutputStream, String.format("ICE-Name: %s", serverName));
155                 sendLine(socketOutputStream, String.format("ICE-Description: %s", serverDescription));
156                 sendLine(socketOutputStream, String.format("ICE-Genre: %s", genre));
157                 sendLine(socketOutputStream, String.format("ICE-Public: %d", publishServer ? 1 : 0));
158                 sendLine(socketOutputStream, "");
159                 socketOutputStream.flush();
160
161                 new Thread(new InputStreamDrainer(socketInputStream)).start();
162
163                 metadataUpdated(metadata);
164         }
165
166         @Override
167         public void close() {
168                 try {
169                         Closeables.close(socketOutputStream, true);
170                 } catch (IOException e) {
171                         /* will never throw. */
172                 }
173         }
174
175         @Override
176         public void metadataUpdated(final Metadata metadata) {
177                 this.metadata = metadata;
178                 new Thread(new Runnable() {
179
180                         @Override
181                         public void run() {
182                                 String metadataString = String.format("%s (%s)", metadata.title(), "Sonitus");
183                                 logger.info(String.format("Updating metadata to %s", metadataString));
184
185                                 Socket socket = null;
186                                 OutputStream socketOutputStream = null;
187                                 try {
188                                         socket = new Socket(server, port);
189                                         socketOutputStream = socket.getOutputStream();
190
191                                         sendLine(socketOutputStream, String.format("GET /admin/metadata?pass=%s&mode=updinfo&mount=/%s&song=%s HTTP/1.0", password, mountPoint, URLEncoder.encode(metadataString, "UTF-8")));
192                                         sendLine(socketOutputStream, String.format("Authorization: Basic %s", generatePassword(password)));
193                                         sendLine(socketOutputStream, String.format("User-Agent: Mozilla/Sonitus"));
194                                         sendLine(socketOutputStream, "");
195                                         socketOutputStream.flush();
196
197                                         new InputStreamDrainer(socket.getInputStream()).run();
198                                 } catch (IOException ioe1) {
199                                         logger.log(Level.WARNING, "Could not update metadata!", ioe1);
200                                 } finally {
201                                         try {
202                                                 Closeables.close(socketOutputStream, true);
203                                                 if (socket != null) {
204                                                         socket.close();
205                                                 }
206                                         } catch (IOException ioe1) {
207                                                 /* ignore. */
208                                         }
209                                 }
210                         }
211                 }).start();
212                 eventBus.post(new MetadataUpdated(this, metadata));
213         }
214
215         @Override
216         public void process(byte[] buffer) throws IOException {
217                 socketOutputStream.write(buffer);
218                 socketOutputStream.flush();
219         }
220
221         //
222         // PRIVATE METHODS
223         //
224
225         /**
226          * Sends the given line, followed by CR+LF, to the given output stream,
227          * encoding the complete line as UTF-8.
228          *
229          * @param outputStream
230          *              The output stream to send the line to
231          * @param line
232          *              The line to send
233          * @throws java.io.IOException
234          *              if an I/O error occurs
235          */
236         private static void sendLine(OutputStream outputStream, String line) throws IOException {
237                 outputStream.write((line + "\r\n").getBytes("UTF-8"));
238         }
239
240         /**
241          * Generates the Base64-encoded authorization information from the given
242          * password. A fixed username of “source” is used.
243          *
244          * @param password
245          *              The password to encode
246          * @return The encoded password
247          * @throws java.io.UnsupportedEncodingException
248          *              if the UTF-8 encoding is not supported (which can never happen)
249          */
250         private static String generatePassword(String password) throws UnsupportedEncodingException {
251                 return BaseEncoding.base64().encode(("source:" + password).getBytes("UTF-8"));
252         }
253
254         /**
255          * Returns a MIME type for the given metadata. Currently only Vorbis, MP3, PCM,
256          * Ogg Vorbis, Opus, and FLAC formats are recognized.
257          *
258          * @param metadata
259          *              The metadata to get a MIME type for
260          * @return The MIME type of the metadata
261          */
262         private static String getContentType(Metadata metadata) {
263                 String encoding = metadata.encoding();
264                 if ("Vorbis".equalsIgnoreCase(encoding)) {
265                         return "audio/ogg";
266                 }
267                 if ("MP3".equalsIgnoreCase(encoding)) {
268                         return "audio/mpeg";
269                 }
270                 if ("PCM".equalsIgnoreCase(encoding)) {
271                         return "audio/vnd.wave";
272                 }
273                 if ("Vorbis".equalsIgnoreCase(encoding)) {
274                         return "application/ogg";
275                 }
276                 if ("Opus".equalsIgnoreCase(encoding)) {
277                         return "audio/ogg; codecs=opus";
278                 }
279                 if ("FLAC".equalsIgnoreCase(encoding)) {
280                         return "audio/flac";
281                 }
282                 return "application/octet-stream";
283         }
284
285 }