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 static com.google.common.base.Preconditions.*;
22 import java.io.IOException;
23 import java.io.InputStream;
24 import java.io.OutputStream;
25 import java.io.UnsupportedEncodingException;
26 import java.net.Socket;
27 import java.net.URLEncoder;
28 import java.util.Arrays;
29 import java.util.logging.Level;
30 import java.util.logging.Logger;
32 import net.pterodactylus.sonitus.data.ConnectException;
33 import net.pterodactylus.sonitus.data.Connection;
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.io.InputStreamDrainer;
39 import com.google.common.base.Function;
40 import com.google.common.base.Joiner;
41 import com.google.common.base.Optional;
42 import com.google.common.collect.FluentIterable;
43 import com.google.common.io.BaseEncoding;
44 import com.google.common.io.Closeables;
47 * {@link Sink} implementation that delivers all incoming data to an Icecast2
50 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
52 public class Icecast2Sink implements Sink {
55 private static final Logger logger = Logger.getLogger(Icecast2Sink.class.getName());
57 /** The server name. */
58 private final String server;
60 /** The port number on the server. */
61 private final int port;
63 /** The source password. */
64 private final String password;
66 /** The stream mount point (without leading slash). */
67 private final String mountPoint;
69 /** The name of the server. */
70 private final String serverName;
72 /** The description of the server. */
73 private final String serverDescription;
75 /** The genre of the server. */
76 private final String genre;
78 /** Whether to publish the server. */
79 private final boolean publishServer;
81 /** The connected source. */
82 private Source source;
85 * Creates a new Icecast2 sink.
88 * The hostname of the server
90 * The port number of the server
94 * The stream mount point
96 * The name of the server
97 * @param serverDescription
98 * The description of the server
100 * The genre of the server
101 * @param publishServer
102 * {@code true} to publish the server in a public directory, {@code false} to
105 public Icecast2Sink(String server, int port, String password, String mountPoint, String serverName, String serverDescription, String genre, boolean publishServer) {
106 this.server = server;
108 this.password = password;
109 this.mountPoint = mountPoint;
110 this.serverName = serverName;
111 this.serverDescription = serverDescription;
113 this.publishServer = publishServer;
121 public void connect(Source source) throws ConnectException {
122 checkNotNull(source, "source must not be null");
124 this.source = source;
126 logger.info(String.format("Icecast2Sink: Connecting to %s:%d...", server, port));
127 final Socket socket = new Socket(server, port);
128 logger.info("Icecast2Sink: Connected.");
129 final OutputStream socketOutputStream = socket.getOutputStream();
130 final InputStream socketInputStream = socket.getInputStream();
132 sendLine(socketOutputStream, String.format("SOURCE /%s ICE/1.0", mountPoint));
133 sendLine(socketOutputStream, String.format("Authorization: Basic %s", generatePassword(password)));
134 sendLine(socketOutputStream, String.format("Content-Type: %s", getContentType(source.metadata())));
135 sendLine(socketOutputStream, String.format("ICE-Name: %s", serverName));
136 sendLine(socketOutputStream, String.format("ICE-Description: %s", serverDescription));
137 sendLine(socketOutputStream, String.format("ICE-Genre: %s", genre));
138 sendLine(socketOutputStream, String.format("ICE-Public: %d", publishServer ? 1 : 0));
139 sendLine(socketOutputStream, "");
140 socketOutputStream.flush();
142 new Thread(new InputStreamDrainer(socketInputStream)).start();
143 new Thread(new Connection(source) {
145 private long counter;
148 protected int bufferSize() {
153 protected void feed(byte[] buffer) throws IOException {
154 socketOutputStream.write(buffer);
155 socketOutputStream.flush();
156 counter += buffer.length;
157 logger.finest(String.format("Wrote %d Bytes.", counter));
161 protected void finish() throws IOException {
162 Closeables.close(socketOutputStream, true);
163 if (socket != null) {
170 } catch (IOException ioe1) {
171 throw new ConnectException(ioe1);
176 public void metadataUpdated() {
177 Metadata metadata = source.metadata();
178 String metadataString = String.format("%s (%s)", Joiner.on(" - ").skipNulls().join(FluentIterable.from(Arrays.asList(metadata.artist(), metadata.name())).transform(new Function<Optional<String>, Object>() {
181 public Object apply(Optional<String> input) {
182 return input.orNull();
185 logger.info(String.format("Updating metadata to %s", metadataString));
187 Socket socket = null;
188 OutputStream socketOutputStream = null;
190 socket = new Socket(server, port);
191 socketOutputStream = socket.getOutputStream();
193 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")));
194 sendLine(socketOutputStream, String.format("Authorization: Basic %s", generatePassword(password)));
195 sendLine(socketOutputStream, String.format("User-Agent: Mozilla/Sonitus"));
196 sendLine(socketOutputStream, "");
197 socketOutputStream.flush();
199 new InputStreamDrainer(socket.getInputStream()).run();
200 } catch (IOException ioe1) {
201 logger.log(Level.WARNING, "Could not update metadata!", ioe1);
204 Closeables.close(socketOutputStream, true);
205 if (socket != null) {
208 } catch (IOException ioe1) {
219 * Sends the given line, followed by CR+LF, to the given output stream,
220 * encoding the complete line as UTF-8.
222 * @param outputStream
223 * The output stream to send the line to
226 * @throws IOException
227 * if an I/O error occurs
229 private static void sendLine(OutputStream outputStream, String line) throws IOException {
230 outputStream.write((line + "\r\n").getBytes("UTF-8"));
234 * Generates the Base64-encoded authorization information from the given
235 * password. A fixed username of “source” is used.
238 * The password to encode
239 * @return The encoded password
240 * @throws UnsupportedEncodingException
241 * if the UTF-8 encoding is not supported (which can never happen)
243 private static String generatePassword(String password) throws UnsupportedEncodingException {
244 return BaseEncoding.base64().encode(("source:" + password).getBytes("UTF-8"));
248 * Returns a MIME type for the given metadata. Currently only Vorbis, MP3, and
249 * PCM formats are recognized.
252 * The metadata to get a MIME type for
253 * @return The MIME type of the metadata
255 private static String getContentType(Metadata metadata) {
256 String encoding = metadata.encoding();
257 if ("Vorbis".equalsIgnoreCase(encoding)) {
260 if ("MP3".equalsIgnoreCase(encoding)) {
263 if ("PCM".equalsIgnoreCase(encoding)) {
264 return "audio/vnd.wave";
266 return "application/octet-stream";