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