Add method to notify sink when a source has updated its metadata.
[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 static com.google.common.base.Preconditions.*;
21
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.util.logging.Logger;
28
29 import net.pterodactylus.sonitus.data.ConnectException;
30 import net.pterodactylus.sonitus.data.Connection;
31 import net.pterodactylus.sonitus.data.Format;
32 import net.pterodactylus.sonitus.data.Sink;
33 import net.pterodactylus.sonitus.data.Source;
34 import net.pterodactylus.sonitus.io.InputStreamDrainer;
35
36 import com.google.common.io.BaseEncoding;
37 import com.google.common.io.Closeables;
38
39 /**
40  * {@link Sink} implementation that delivers all incoming data to an Icecast2
41  * server.
42  *
43  * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
44  */
45 public class Icecast2Sink implements Sink {
46
47         /** The logger. */
48         private static final Logger logger = Logger.getLogger(Icecast2Sink.class.getName());
49
50         /** The server name. */
51         private final String server;
52
53         /** The port number on the server. */
54         private final int port;
55
56         /** The source password. */
57         private final String password;
58
59         /** The stream mount point (without leading slash). */
60         private final String mountPoint;
61
62         /** The name of the server. */
63         private final String serverName;
64
65         /** The description of the server. */
66         private final String serverDescription;
67
68         /** The genre of the server. */
69         private final String genre;
70
71         /** Whether to publish the server. */
72         private final boolean publishServer;
73
74         /**
75          * Creates a new Icecast2 sink.
76          *
77          * @param server
78          *              The hostname of the server
79          * @param port
80          *              The port number of the server
81          * @param password
82          *              The source password
83          * @param mountPoint
84          *              The stream mount point
85          * @param serverName
86          *              The name of the server
87          * @param serverDescription
88          *              The description of the server
89          * @param genre
90          *              The genre of the server
91          * @param publishServer
92          *              {@code true} to publish the server in a public directory, {@code false} to
93          *              not publish it
94          */
95         public Icecast2Sink(String server, int port, String password, String mountPoint, String serverName, String serverDescription, String genre, boolean publishServer) {
96                 this.server = server;
97                 this.port = port;
98                 this.password = password;
99                 this.mountPoint = mountPoint;
100                 this.serverName = serverName;
101                 this.serverDescription = serverDescription;
102                 this.genre = genre;
103                 this.publishServer = publishServer;
104         }
105
106         //
107         // SINK METHODS
108         //
109
110         @Override
111         public void connect(Source source) throws ConnectException {
112                 checkNotNull(source, "source must not be null");
113
114                 try {
115                         logger.info(String.format("Icecast2Sink: Connecting to %s:%d...", server, port));
116                         final Socket socket = new Socket(server, port);
117                         logger.info("Icecast2Sink: Connected.");
118                         final OutputStream socketOutputStream = socket.getOutputStream();
119                         final InputStream socketInputStream = socket.getInputStream();
120
121                         sendLine(socketOutputStream, String.format("SOURCE /%s ICE/1.0", mountPoint));
122                         sendLine(socketOutputStream, String.format("Authorization: Basic %s", generatePassword(password)));
123                         sendLine(socketOutputStream, String.format("Content-Type: %s", getContentType(source.format())));
124                         sendLine(socketOutputStream, String.format("ICE-Name: %s", serverName));
125                         sendLine(socketOutputStream, String.format("ICE-Description: %s", serverDescription));
126                         sendLine(socketOutputStream, String.format("ICE-Genre: %s", genre));
127                         sendLine(socketOutputStream, String.format("ICE-Public: %d", publishServer ? 1 : 0));
128                         sendLine(socketOutputStream, "");
129                         socketOutputStream.flush();
130
131                         new Thread(new InputStreamDrainer(socketInputStream)).start();
132                         new Thread(new Connection(source) {
133
134                                 private long counter;
135
136                                 @Override
137                                 protected int bufferSize() {
138                                         return 4096;
139                                 }
140
141                                 @Override
142                                 protected void feed(byte[] buffer) throws IOException {
143                                         socketOutputStream.write(buffer);
144                                         socketOutputStream.flush();
145                                         counter += buffer.length;
146                                         logger.finest(String.format("Wrote %d Bytes.", counter));
147                                 }
148
149                                 @Override
150                                 protected void finish() throws IOException {
151                                         Closeables.close(socketOutputStream, true);
152                                         Closeables.close(socket, true);
153                                 }
154                         }).start();
155                 } catch (IOException ioe1) {
156                         throw new ConnectException(ioe1);
157                 }
158         }
159
160         @Override
161         public void metadataUpdated() {
162         }
163
164         //
165         // PRIVATE METHODS
166         //
167
168         /**
169          * Sends the given line, followed by CR+LF, to the given output stream,
170          * encoding the complete line as UTF-8.
171          *
172          * @param outputStream
173          *              The output stream to send the line to
174          * @param line
175          *              The line to send
176          * @throws IOException
177          *              if an I/O error occurs
178          */
179         private static void sendLine(OutputStream outputStream, String line) throws IOException {
180                 outputStream.write((line + "\r\n").getBytes("UTF-8"));
181         }
182
183         /**
184          * Generates the Base64-encoded authorization information from the given
185          * password. A fixed username of “source” is used.
186          *
187          * @param password
188          *              The password to encode
189          * @return The encoded password
190          * @throws UnsupportedEncodingException
191          *              if the UTF-8 encoding is not supported (which can never happen)
192          */
193         private static String generatePassword(String password) throws UnsupportedEncodingException {
194                 return BaseEncoding.base64().encode(("source:" + password).getBytes("UTF-8"));
195         }
196
197         /**
198          * Returns a MIME type for the given format. Currently only Vorbis, MP3, and
199          * PCM formats are recognized.
200          *
201          * @param format
202          *              The format to get a MIME type for
203          * @return The MIME type of the format
204          */
205         private static String getContentType(Format format) {
206                 String encoding = format.encoding();
207                 if ("Vorbis".equalsIgnoreCase(encoding)) {
208                         return "audio/ogg";
209                 }
210                 if ("MP3".equalsIgnoreCase(encoding)) {
211                         return "audio/mpeg";
212                 }
213                 if ("PCM".equalsIgnoreCase(encoding)) {
214                         return "audio/vnd.wave";
215                 }
216                 return "application/octet-stream";
217         }
218
219 }