Add metadata stream parser and test case.
[sonitus.git] / src / main / java / net / pterodactylus / sonitus / io / MetadataStream.java
1 /*
2  * Sonitus - MetadataStream.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.io;
19
20 import java.io.BufferedInputStream;
21 import java.io.FilterInputStream;
22 import java.io.IOException;
23 import java.io.InputStream;
24 import java.io.UnsupportedEncodingException;
25 import java.nio.ByteBuffer;
26 import java.nio.CharBuffer;
27 import java.nio.charset.Charset;
28 import java.nio.charset.CharsetDecoder;
29 import java.nio.charset.CoderResult;
30 import java.nio.charset.CodingErrorAction;
31 import java.util.Map;
32
33 import net.pterodactylus.sonitus.data.ContentMetadata;
34
35 import com.google.common.base.Optional;
36 import com.google.common.collect.Maps;
37
38 /**
39  * Wrapper around an {@link InputStream} that can separate metadata out of
40  * icecast audio streams.
41  * <p/>
42  * {@link #read(byte[])} and {@link #read(byte[], int, int)} are implemented
43  * using {@link #read()} so wrapping the underlying stream into a {@link
44  * BufferedInputStream} is highly recommended.
45  *
46  * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
47  */
48 public class MetadataStream extends FilterInputStream {
49
50         /** The UTF-8 charset. */
51         private static final Charset utf8Charset = Charset.forName("UTF-8");
52
53         /** The interval of the metadata blocks. */
54         private final int metadataInterval;
55
56         /** How many bytes of stream are left before a metadata block is expected. */
57         private int streamRemaining;
58
59         /** The last parsed metadata. */
60         private Optional<ContentMetadata> contentMetadata = Optional.absent();
61
62         /**
63          * Creates a new metadata stream.
64          *
65          * @param inputStream
66          *              The input stream to parse metadata out of
67          * @param metadataInterval
68          *              The interval at which metadata blocks are weaved into the stream
69          */
70         public MetadataStream(InputStream inputStream, int metadataInterval) {
71                 super(inputStream);
72                 this.metadataInterval = metadataInterval;
73                 this.streamRemaining = metadataInterval;
74         }
75
76         //
77         // ACCESSORS
78         //
79
80         /**
81          * Returns the last parsed content metadata of this stream.
82          *
83          * @return The last parsed content metadata
84          */
85         public Optional<ContentMetadata> getContentMetadata() {
86                 return contentMetadata;
87         }
88
89         //
90         // PRIVATE METHODS
91         //
92
93         /**
94          * Parses the metadata from the given byte array.
95          *
96          * @param metadataBuffer
97          * @return The parsed metadata, or {@link Optional#absent()} if the metadata
98          *         could not be parsed
99          */
100         private static Optional<ContentMetadata> parseMetadata(byte[] metadataBuffer) {
101
102                 /* the byte array may be padded with NULs. */
103                 int realLength = metadataBuffer.length;
104                 while ((realLength > -1) && (metadataBuffer[realLength - 1] == 0)) {
105                         realLength--;
106                 }
107
108                 try {
109
110                         /* decode the byte array as a UTF-8 string. */
111                         CharsetDecoder utf8Decoder = utf8Charset.newDecoder();
112                         utf8Decoder.onMalformedInput(CodingErrorAction.REPORT);
113                         CharBuffer decodedBuffer = CharBuffer.allocate(realLength);
114                         CoderResult utf8Result = utf8Decoder.decode(ByteBuffer.wrap(metadataBuffer, 0, realLength), decodedBuffer, true);
115                         utf8Decoder.flush(decodedBuffer);
116
117                         /* use latin-1 as fallback if decoding as UTF-8 failed. */
118                         String metadataString;
119                         if (utf8Result.isMalformed()) {
120                                 metadataString = new String(metadataBuffer, 0, realLength, "ISO8859-1");
121                         } else {
122                                 metadataString = decodedBuffer.flip().toString();
123                         }
124                         int currentOffset = 0;
125
126                         /* metadata has the form of key='value'[;key='value'[…]] */
127                         Map<String, String> metadataAttributes = Maps.newHashMap();
128                         while (currentOffset < metadataString.length()) {
129                                 int equalSign = metadataString.indexOf('=', currentOffset);
130                                 if (equalSign == -1) {
131                                         break;
132                                 }
133                                 String key = metadataString.substring(currentOffset, equalSign);
134                                 int semicolon = metadataString.indexOf(';', equalSign);
135                                 if (semicolon == -1) {
136                                         break;
137                                 }
138                                 String value = metadataString.substring(equalSign + 1, semicolon);
139                                 if ((value.startsWith("'") && value.endsWith("'")) || (value.startsWith("\"") && value.endsWith("\""))) {
140                                         value = value.substring(1, value.length() - 1);
141                                 }
142                                 metadataAttributes.put(key, value);
143                                 currentOffset = semicolon + 1;
144                         }
145
146                         if (!metadataAttributes.containsKey("StreamTitle")) {
147                                 return Optional.absent();
148                         }
149
150                         return Optional.of(new ContentMetadata(metadataAttributes.get("StreamTitle")));
151
152                 } catch (UnsupportedEncodingException uee1) {
153                         /* should never happen. */
154                         throw new RuntimeException("UTF-8 not supported");
155                 }
156         }
157
158         //
159         // INPUTSTREAM METHODS
160         //
161
162         @Override
163         public int read() throws IOException {
164                 int data = super.read();
165                 if (data == -1) {
166                         return -1;
167                 }
168                 if (streamRemaining > 0) {
169                         --streamRemaining;
170                 } else if (data == 0) {
171                         /* 0-byte metadata follows, ignore. */
172                         streamRemaining = metadataInterval - 1;
173                         data = super.read();
174                 } else {
175                         /* loop until we’ve read all metadata. */
176                         byte[] metadataBuffer = new byte[data * 16];
177                         int metadataPosition = 0;
178                         do {
179                                 int metadataByte = super.read();
180                                 if (metadataByte == -1) {
181                                         return -1;
182                                 }
183                                 metadataBuffer[metadataPosition++] = (byte) metadataByte;
184                                 if (metadataPosition == metadataBuffer.length) {
185                                         /* parse metadata. */
186                                         Optional<ContentMetadata> parsedMetadata = parseMetadata(metadataBuffer);
187                                         if (parsedMetadata.isPresent()) {
188                                                 contentMetadata = parseMetadata(metadataBuffer);
189                                         }
190                                         /* reset metadata buffer and position. */
191                                         metadataBuffer = null;
192                                         metadataPosition = 0;
193                                         /* we read one more byte after the loop. */
194                                         streamRemaining = metadataInterval - 1;
195                                 }
196                         } while (metadataBuffer != null);
197                         data = super.read();
198                 }
199                 return data;
200         }
201
202         @Override
203         public int read(byte[] buffer) throws IOException {
204                 return read(buffer, 0, buffer.length);
205         }
206
207         @Override
208         public int read(byte[] buffer, int offset, int length) throws IOException {
209                 for (int index = offset; index < (offset + length); ++index) {
210                         int data = read();
211                         if (data == -1) {
212                                 return (index > offset) ? (index - offset) : -1;
213                         }
214                         buffer[index] = (byte) data;
215                 }
216                 return length;
217         }
218
219 }