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.Format;
35 import net.pterodactylus.sonitus.data.Metadata;
36 import net.pterodactylus.sonitus.data.Sink;
37 import net.pterodactylus.sonitus.data.Source;
38 import net.pterodactylus.sonitus.io.InputStreamDrainer;
40 import com.google.common.base.Function;
41 import com.google.common.base.Joiner;
42 import com.google.common.base.Optional;
43 import com.google.common.collect.FluentIterable;
44 import com.google.common.io.BaseEncoding;
45 import com.google.common.io.Closeables;
48 * {@link Sink} implementation that delivers all incoming data to an Icecast2
51 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
53 public class Icecast2Sink implements Sink {
56 private static final Logger logger = Logger.getLogger(Icecast2Sink.class.getName());
58 /** The server name. */
59 private final String server;
61 /** The port number on the server. */
62 private final int port;
64 /** The source password. */
65 private final String password;
67 /** The stream mount point (without leading slash). */
68 private final String mountPoint;
70 /** The name of the server. */
71 private final String serverName;
73 /** The description of the server. */
74 private final String serverDescription;
76 /** The genre of the server. */
77 private final String genre;
79 /** Whether to publish the server. */
80 private final boolean publishServer;
82 /** The connected source. */
83 private Source source;
86 * Creates a new Icecast2 sink.
89 * The hostname of the server
91 * The port number of the server
95 * The stream mount point
97 * The name of the server
98 * @param serverDescription
99 * The description of the server
101 * The genre of the server
102 * @param publishServer
103 * {@code true} to publish the server in a public directory, {@code false} to
106 public Icecast2Sink(String server, int port, String password, String mountPoint, String serverName, String serverDescription, String genre, boolean publishServer) {
107 this.server = server;
109 this.password = password;
110 this.mountPoint = mountPoint;
111 this.serverName = serverName;
112 this.serverDescription = serverDescription;
114 this.publishServer = publishServer;
122 public void connect(Source source) throws ConnectException {
123 checkNotNull(source, "source must not be null");
125 this.source = source;
127 logger.info(String.format("Icecast2Sink: Connecting to %s:%d...", server, port));
128 final Socket socket = new Socket(server, port);
129 logger.info("Icecast2Sink: Connected.");
130 final OutputStream socketOutputStream = socket.getOutputStream();
131 final InputStream socketInputStream = socket.getInputStream();
133 sendLine(socketOutputStream, String.format("SOURCE /%s ICE/1.0", mountPoint));
134 sendLine(socketOutputStream, String.format("Authorization: Basic %s", generatePassword(password)));
135 sendLine(socketOutputStream, String.format("Content-Type: %s", getContentType(source.format())));
136 sendLine(socketOutputStream, String.format("ICE-Name: %s", serverName));
137 sendLine(socketOutputStream, String.format("ICE-Description: %s", serverDescription));
138 sendLine(socketOutputStream, String.format("ICE-Genre: %s", genre));
139 sendLine(socketOutputStream, String.format("ICE-Public: %d", publishServer ? 1 : 0));
140 sendLine(socketOutputStream, "");
141 socketOutputStream.flush();
143 new Thread(new InputStreamDrainer(socketInputStream)).start();
144 new Thread(new Connection(source) {
146 private long counter;
149 protected int bufferSize() {
154 protected void feed(byte[] buffer) throws IOException {
155 socketOutputStream.write(buffer);
156 socketOutputStream.flush();
157 counter += buffer.length;
158 logger.finest(String.format("Wrote %d Bytes.", counter));
162 protected void finish() throws IOException {
163 Closeables.close(socketOutputStream, true);
164 Closeables.close(socket, true);
169 } catch (IOException ioe1) {
170 throw new ConnectException(ioe1);
175 public void metadataUpdated() {
176 Metadata metadata = source.metadata();
177 String metadataString = String.format("%s (%s)", Joiner.on(" - ").skipNulls().join(FluentIterable.from(Arrays.asList(metadata.artist(), metadata.name())).transform(new Function<Optional<String>, Object>() {
180 public Object apply(Optional<String> input) {
181 return input.orNull();
184 logger.info(String.format("Updating metadata to %s", metadataString));
186 Socket socket = null;
187 OutputStream socketOutputStream = null;
189 socket = new Socket(server, port);
190 socketOutputStream = socket.getOutputStream();
192 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")));
193 sendLine(socketOutputStream, String.format("Authorization: Basic %s", generatePassword(password)));
194 sendLine(socketOutputStream, String.format("User-Agent: Mozilla/Sonitus"));
195 sendLine(socketOutputStream, "");
196 socketOutputStream.flush();
198 new InputStreamDrainer(socket.getInputStream()).run();
199 } catch (IOException ioe1) {
200 logger.log(Level.WARNING, "Could not update metadata!", ioe1);
203 Closeables.close(socketOutputStream, true);
204 Closeables.close(socket, true);
205 } catch (IOException ioe1) {
206 /* ignore, will not happen. */
216 * Sends the given line, followed by CR+LF, to the given output stream,
217 * encoding the complete line as UTF-8.
219 * @param outputStream
220 * The output stream to send the line to
223 * @throws IOException
224 * if an I/O error occurs
226 private static void sendLine(OutputStream outputStream, String line) throws IOException {
227 outputStream.write((line + "\r\n").getBytes("UTF-8"));
231 * Generates the Base64-encoded authorization information from the given
232 * password. A fixed username of “source” is used.
235 * The password to encode
236 * @return The encoded password
237 * @throws UnsupportedEncodingException
238 * if the UTF-8 encoding is not supported (which can never happen)
240 private static String generatePassword(String password) throws UnsupportedEncodingException {
241 return BaseEncoding.base64().encode(("source:" + password).getBytes("UTF-8"));
245 * Returns a MIME type for the given format. Currently only Vorbis, MP3, and
246 * PCM formats are recognized.
249 * The format to get a MIME type for
250 * @return The MIME type of the format
252 private static String getContentType(Format format) {
253 String encoding = format.encoding();
254 if ("Vorbis".equalsIgnoreCase(encoding)) {
257 if ("MP3".equalsIgnoreCase(encoding)) {
260 if ("PCM".equalsIgnoreCase(encoding)) {
261 return "audio/vnd.wave";
263 return "application/octet-stream";