Add name to all controlled components.
[sonitus.git] / src / main / java / net / pterodactylus / sonitus / data / source / StreamSource.java
1 /*
2  * Sonitus - StreamSource.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.source;
19
20 import java.io.BufferedInputStream;
21 import java.io.IOException;
22 import java.net.HttpURLConnection;
23 import java.net.URL;
24 import java.net.URLConnection;
25 import java.util.Collections;
26 import java.util.List;
27 import java.util.Map;
28
29 import net.pterodactylus.sonitus.data.ContentMetadata;
30 import net.pterodactylus.sonitus.data.Controller;
31 import net.pterodactylus.sonitus.data.FormatMetadata;
32 import net.pterodactylus.sonitus.data.Metadata;
33 import net.pterodactylus.sonitus.data.Source;
34 import net.pterodactylus.sonitus.io.MetadataStream;
35
36 import com.google.common.base.Optional;
37 import com.google.common.collect.Maps;
38 import com.google.common.primitives.Ints;
39
40 /**
41  * {@link Source} implementation that can download an audio stream from a
42  * streaming server.
43  * <p/>
44  * Currently only “audio/mpeg” (aka MP3) streams are supported.
45  *
46  * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
47  */
48 public class StreamSource implements Source {
49
50         /** The URL of the stream. */
51         private final String streamUrl;
52
53         /** The name of the station. */
54         private final String streamName;
55
56         /** The metadata stream. */
57         private final MetadataStream metadataStream;
58
59         /** The current metadata. */
60         private Metadata metadata;
61
62         /**
63          * Creates a new stream source. This will also connect to the server and parse
64          * the response header for vital information (sampling frequency, number of
65          * channels, etc.).
66          *
67          * @param streamUrl
68          *              The URL of the stream
69          * @throws IOException
70          *              if an I/O error occurs
71          */
72         public StreamSource(String streamUrl) throws IOException {
73                 this.streamUrl = streamUrl;
74                 URL url = new URL(streamUrl);
75
76                 /* set up connection. */
77                 URLConnection urlConnection = url.openConnection();
78                 if (!(urlConnection instanceof HttpURLConnection)) {
79                         throw new IllegalArgumentException("Not an HTTP URL!");
80                 }
81                 HttpURLConnection httpUrlConnection = (HttpURLConnection) urlConnection;
82                 httpUrlConnection.setRequestProperty("ICY-Metadata", "1");
83
84                 /* connect. */
85                 httpUrlConnection.connect();
86
87                 /* check content type. */
88                 String contentType = httpUrlConnection.getContentType();
89                 if (!contentType.startsWith("audio/mpeg")) {
90                         throw new IllegalArgumentException("Not an MP3 stream!");
91                 }
92
93                 /* get ice-audio-info header. */
94                 String iceAudioInfo = httpUrlConnection.getHeaderField("ICE-Audio-Info");
95                 if (iceAudioInfo == null) {
96                         throw new IllegalArgumentException("No ICE Audio Info!");
97                 }
98
99                 /* parse ice-audio-info header. */
100                 String[] audioInfos = iceAudioInfo.split(";");
101                 Map<String, Integer> audioParameters = Maps.newHashMap();
102                 for (String audioInfo : audioInfos) {
103                         String key = audioInfo.substring(0, audioInfo.indexOf('=')).toLowerCase();
104                         int value = Ints.tryParse(audioInfo.substring(audioInfo.indexOf('=') + 1));
105                         audioParameters.put(key, value);
106                 }
107
108                 /* check metadata interval. */
109                 String metadataIntervalHeader = httpUrlConnection.getHeaderField("ICY-MetaInt");
110                 if (metadataIntervalHeader == null) {
111                         throw new IllegalArgumentException("No Metadata Interval header!");
112                 }
113                 Integer metadataInterval = Ints.tryParse(metadataIntervalHeader);
114                 if (metadataInterval == null) {
115                         throw new IllegalArgumentException(String.format("Invalid Metadata Interval header: %s", metadataIntervalHeader));
116                 }
117
118                 metadata = new Metadata(new FormatMetadata(audioParameters.get("ice-channels"), audioParameters.get("ice-samplerate"), "MP3"), new ContentMetadata());
119                 metadataStream = new MetadataStream(new BufferedInputStream(httpUrlConnection.getInputStream()), metadataInterval);
120                 streamName = httpUrlConnection.getHeaderField("ICY-Name");
121         }
122
123         //
124         // CONTROLLED METHODS
125         //
126
127         @Override
128         public String name() {
129                 return streamName;
130         }
131
132         @Override
133         public List<Controller<?>> controllers() {
134                 return Collections.emptyList();
135         }
136
137         //
138         // SOURCE METHODS
139         //
140
141         @Override
142         public Metadata metadata() {
143                 Optional<ContentMetadata> streamMetadata = metadataStream.getContentMetadata();
144                 if (!streamMetadata.isPresent()) {
145                         return metadata;
146                 }
147                 return metadata = metadata.title(streamMetadata.get().title());
148         }
149
150         @Override
151         public byte[] get(int bufferSize) throws IOException {
152                 byte[] buffer = new byte[bufferSize];
153                 metadataStream.read(buffer);
154                 return buffer;
155         }
156
157         //
158         // OBJECT METHODS
159         //
160
161         @Override
162         public String toString() {
163                 return String.format("StreamSource(%s,%s)", streamUrl, metadata);
164         }
165
166 }