2 * Sonitus - Icecast2Sink.java - Copyright © 2013 David Roden
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.
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.
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/>.
18 package net.pterodactylus.sonitus.data.sink;
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.Arrays;
27 import java.util.Collections;
28 import java.util.List;
29 import java.util.logging.Level;
30 import java.util.logging.Logger;
32 import net.pterodactylus.sonitus.data.Controller;
33 import net.pterodactylus.sonitus.data.Metadata;
34 import net.pterodactylus.sonitus.data.Sink;
35 import net.pterodactylus.sonitus.io.InputStreamDrainer;
37 import com.google.common.base.Function;
38 import com.google.common.base.Joiner;
39 import com.google.common.base.Optional;
40 import com.google.common.collect.FluentIterable;
41 import com.google.common.io.BaseEncoding;
42 import com.google.common.io.Closeables;
45 * {@link net.pterodactylus.sonitus.data.Sink} implementation that delivers all
46 * incoming data to an Icecast2 server.
48 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
50 public class Icecast2Sink implements Sink {
53 private static final Logger logger = Logger.getLogger(Icecast2Sink.class.getName());
55 /** The server name. */
56 private final String server;
58 /** The port number on the server. */
59 private final int port;
61 /** The source password. */
62 private final String password;
64 /** The stream mount point (without leading slash). */
65 private final String mountPoint;
67 /** The name of the server. */
68 private final String serverName;
70 /** The description of the server. */
71 private final String serverDescription;
73 /** The genre of the server. */
74 private final String genre;
76 /** Whether to publish the server. */
77 private final boolean publishServer;
79 private OutputStream socketOutputStream;
82 * Creates a new Icecast2 sink.
85 * The hostname of the server
87 * The port number of the server
91 * The stream mount point
93 * The name of the server
94 * @param serverDescription
95 * The description of the server
97 * The genre of the server
98 * @param publishServer
99 * {@code true} to publish the server in a public directory, {@code false} to
102 public Icecast2Sink(String server, int port, String password, String mountPoint, String serverName, String serverDescription, String genre, boolean publishServer) {
103 this.server = server;
105 this.password = password;
106 this.mountPoint = mountPoint;
107 this.serverName = serverName;
108 this.serverDescription = serverDescription;
110 this.publishServer = publishServer;
114 // CONTROLLED METHODS
118 public String name() {
119 return String.format("icecast://%s:%d/%s", server, port, mountPoint);
123 public List<Controller<?>> controllers() {
124 return Collections.emptyList();
132 public void open(Metadata metadata) throws IOException {
133 logger.info(String.format("Connecting to %s:%d...", server, port));
134 Socket socket = new Socket(server, port);
135 logger.info("Connected.");
136 socketOutputStream = socket.getOutputStream();
137 InputStream socketInputStream = socket.getInputStream();
139 sendLine(socketOutputStream, String.format("SOURCE /%s ICE/1.0", mountPoint));
140 sendLine(socketOutputStream, String.format("Authorization: Basic %s", generatePassword(password)));
141 sendLine(socketOutputStream, String.format("Content-Type: %s", getContentType(metadata)));
142 sendLine(socketOutputStream, String.format("ICE-Name: %s", serverName));
143 sendLine(socketOutputStream, String.format("ICE-Description: %s", serverDescription));
144 sendLine(socketOutputStream, String.format("ICE-Genre: %s", genre));
145 sendLine(socketOutputStream, String.format("ICE-Public: %d", publishServer ? 1 : 0));
146 sendLine(socketOutputStream, "");
147 socketOutputStream.flush();
149 new Thread(new InputStreamDrainer(socketInputStream)).start();
151 metadataUpdated(metadata);
155 public void close() {
157 Closeables.close(socketOutputStream, true);
158 } catch (IOException e) {
159 /* will never throw. */
164 public void metadataUpdated(final Metadata metadata) {
165 new Thread(new Runnable() {
169 String metadataString = String.format("%s (%s)", Joiner.on(" - ").skipNulls().join(FluentIterable.from(Arrays.asList(metadata.artist(), metadata.name())).transform(new Function<Optional<String>, Object>() {
172 public Object apply(Optional<String> input) {
173 return input.orNull();
176 logger.info(String.format("Updating metadata to %s", metadataString));
178 Socket socket = null;
179 OutputStream socketOutputStream = null;
181 socket = new Socket(server, port);
182 socketOutputStream = socket.getOutputStream();
184 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")));
185 sendLine(socketOutputStream, String.format("Authorization: Basic %s", generatePassword(password)));
186 sendLine(socketOutputStream, String.format("User-Agent: Mozilla/Sonitus"));
187 sendLine(socketOutputStream, "");
188 socketOutputStream.flush();
190 new InputStreamDrainer(socket.getInputStream()).run();
191 } catch (IOException ioe1) {
192 logger.log(Level.WARNING, "Could not update metadata!", ioe1);
195 Closeables.close(socketOutputStream, true);
196 if (socket != null) {
199 } catch (IOException ioe1) {
208 public void process(byte[] buffer) throws IOException {
209 socketOutputStream.write(buffer);
210 socketOutputStream.flush();
218 * Sends the given line, followed by CR+LF, to the given output stream,
219 * encoding the complete line as UTF-8.
221 * @param outputStream
222 * The output stream to send the line to
225 * @throws java.io.IOException
226 * if an I/O error occurs
228 private static void sendLine(OutputStream outputStream, String line) throws IOException {
229 outputStream.write((line + "\r\n").getBytes("UTF-8"));
233 * Generates the Base64-encoded authorization information from the given
234 * password. A fixed username of “source” is used.
237 * The password to encode
238 * @return The encoded password
239 * @throws java.io.UnsupportedEncodingException
240 * if the UTF-8 encoding is not supported (which can never happen)
242 private static String generatePassword(String password) throws UnsupportedEncodingException {
243 return BaseEncoding.base64().encode(("source:" + password).getBytes("UTF-8"));
247 * Returns a MIME type for the given metadata. Currently only Vorbis, MP3, PCM,
248 * Ogg Vorbis, Opus, and FLAC formats are recognized.
251 * The metadata to get a MIME type for
252 * @return The MIME type of the metadata
254 private static String getContentType(Metadata metadata) {
255 String encoding = metadata.encoding();
256 if ("Vorbis".equalsIgnoreCase(encoding)) {
259 if ("MP3".equalsIgnoreCase(encoding)) {
262 if ("PCM".equalsIgnoreCase(encoding)) {
263 return "audio/vnd.wave";
265 if ("Vorbis".equalsIgnoreCase(encoding)) {
266 return "application/ogg";
268 if ("Opus".equalsIgnoreCase(encoding)) {
269 return "audio/ogg; codecs=opus";
271 if ("FLAC".equalsIgnoreCase(encoding)) {
274 return "application/octet-stream";