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