Add metadata listeners to 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.AbstractControlledComponent;
30 import net.pterodactylus.sonitus.data.ContentMetadata;
31 import net.pterodactylus.sonitus.data.Controller;
32 import net.pterodactylus.sonitus.data.FormatMetadata;
33 import net.pterodactylus.sonitus.data.Metadata;
34 import net.pterodactylus.sonitus.data.Source;
35 import net.pterodactylus.sonitus.data.event.MetadataUpdated;
36 import net.pterodactylus.sonitus.io.MetadataStream;
37
38 import com.google.common.base.Optional;
39 import com.google.common.collect.Maps;
40 import com.google.common.eventbus.EventBus;
41 import com.google.common.primitives.Ints;
42
43 /**
44  * {@link Source} 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 AbstractControlledComponent implements Source {
52
53         /** The event bus. */
54         private final EventBus eventBus;
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         /** The current metadata. */
66         private Metadata metadata;
67
68         /**
69          * Creates a new stream source. This will also connect to the server and parse
70          * the response header for vital information (sampling frequency, number of
71          * channels, etc.).
72          *
73          * @param eventBus
74          *              The event bus
75          * @param streamUrl
76          *              The URL of the stream
77          * @throws IOException
78          *              if an I/O error occurs
79          */
80         public StreamSource(EventBus eventBus, String streamUrl) throws IOException {
81                 this.eventBus = eventBus;
82                 this.streamUrl = streamUrl;
83                 URL url = new URL(streamUrl);
84
85                 /* set up connection. */
86                 URLConnection urlConnection = url.openConnection();
87                 if (!(urlConnection instanceof HttpURLConnection)) {
88                         throw new IllegalArgumentException("Not an HTTP URL!");
89                 }
90                 HttpURLConnection httpUrlConnection = (HttpURLConnection) urlConnection;
91                 httpUrlConnection.setRequestProperty("ICY-Metadata", "1");
92
93                 /* connect. */
94                 httpUrlConnection.connect();
95
96                 /* check content type. */
97                 String contentType = httpUrlConnection.getContentType();
98                 if (!contentType.startsWith("audio/mpeg")) {
99                         throw new IllegalArgumentException("Not an MP3 stream!");
100                 }
101
102                 /* get ice-audio-info header. */
103                 String iceAudioInfo = httpUrlConnection.getHeaderField("ICE-Audio-Info");
104                 if (iceAudioInfo == null) {
105                         throw new IllegalArgumentException("No ICE Audio Info!");
106                 }
107
108                 /* parse ice-audio-info header. */
109                 String[] audioInfos = iceAudioInfo.split(";");
110                 Map<String, Integer> audioParameters = Maps.newHashMap();
111                 for (String audioInfo : audioInfos) {
112                         String key = audioInfo.substring(0, audioInfo.indexOf('=')).toLowerCase();
113                         int value = Ints.tryParse(audioInfo.substring(audioInfo.indexOf('=') + 1));
114                         audioParameters.put(key, value);
115                 }
116
117                 /* check metadata interval. */
118                 String metadataIntervalHeader = httpUrlConnection.getHeaderField("ICY-MetaInt");
119                 if (metadataIntervalHeader == null) {
120                         throw new IllegalArgumentException("No Metadata Interval header!");
121                 }
122                 Integer metadataInterval = Ints.tryParse(metadataIntervalHeader);
123                 if (metadataInterval == null) {
124                         throw new IllegalArgumentException(String.format("Invalid Metadata Interval header: %s", metadataIntervalHeader));
125                 }
126
127                 metadata = new Metadata(new FormatMetadata(audioParameters.get("ice-channels"), audioParameters.get("ice-samplerate"), "MP3"), new ContentMetadata());
128                 metadataStream = new MetadataStream(new BufferedInputStream(httpUrlConnection.getInputStream()), metadataInterval);
129                 streamName = httpUrlConnection.getHeaderField("ICY-Name");
130         }
131
132         //
133         // CONTROLLED METHODS
134         //
135
136         @Override
137         public String name() {
138                 return streamName;
139         }
140
141         @Override
142         public List<Controller<?>> controllers() {
143                 return Collections.emptyList();
144         }
145
146         //
147         // SOURCE METHODS
148         //
149
150         @Override
151         public Metadata metadata() {
152                 Optional<ContentMetadata> streamMetadata = metadataStream.getContentMetadata();
153                 if (!streamMetadata.isPresent()) {
154                         return metadata;
155                 }
156                 metadata = metadata.title(streamMetadata.get().title());
157                 fireMetadataUpdated(metadata);
158                 eventBus.post(new MetadataUpdated(this, metadata));
159                 return metadata;
160         }
161
162         @Override
163         public byte[] get(int bufferSize) throws IOException {
164                 byte[] buffer = new byte[bufferSize];
165                 metadataStream.read(buffer);
166                 return buffer;
167         }
168
169         //
170         // OBJECT METHODS
171         //
172
173         @Override
174         public String toString() {
175                 return String.format("StreamSource(%s,%s)", streamUrl, metadata);
176         }
177
178 }