2 * Sonitus - MetadataStream.java - Copyright © 2013 David Roden
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.
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.
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/>.
18 package net.pterodactylus.sonitus.io;
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;
33 import net.pterodactylus.sonitus.data.ContentMetadata;
35 import com.google.common.base.Optional;
36 import com.google.common.collect.Maps;
39 * Wrapper around an {@link InputStream} that can separate metadata out of
40 * icecast audio streams.
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.
46 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
48 public class MetadataStream extends FilterInputStream {
50 /** The UTF-8 charset. */
51 private static final Charset utf8Charset = Charset.forName("UTF-8");
53 /** The interval of the metadata blocks. */
54 private final int metadataInterval;
56 /** How many bytes of stream are left before a metadata block is expected. */
57 private int streamRemaining;
59 /** The last parsed metadata. */
60 private Optional<ContentMetadata> contentMetadata = Optional.absent();
63 * Creates a new metadata stream.
66 * The input stream to parse metadata out of
67 * @param metadataInterval
68 * The interval at which metadata blocks are weaved into the stream
70 public MetadataStream(InputStream inputStream, int metadataInterval) {
72 this.metadataInterval = metadataInterval;
73 this.streamRemaining = metadataInterval;
81 * Returns the last parsed content metadata of this stream.
83 * @return The last parsed content metadata
85 public Optional<ContentMetadata> getContentMetadata() {
86 return contentMetadata;
94 * Parses the metadata from the given byte array.
96 * @param metadataBuffer
97 * @return The parsed metadata, or {@link Optional#absent()} if the metadata
100 private static Optional<ContentMetadata> parseMetadata(byte[] metadataBuffer) {
102 /* the byte array may be padded with NULs. */
103 int realLength = metadataBuffer.length;
104 while ((realLength > -1) && (metadataBuffer[realLength - 1] == 0)) {
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);
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");
122 metadataString = decodedBuffer.flip().toString();
124 int currentOffset = 0;
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) {
133 String key = metadataString.substring(currentOffset, equalSign);
134 int semicolon = metadataString.indexOf(';', equalSign);
135 if (semicolon == -1) {
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);
142 metadataAttributes.put(key, value);
143 currentOffset = semicolon + 1;
146 if (!metadataAttributes.containsKey("StreamTitle")) {
147 return Optional.absent();
150 return Optional.of(new ContentMetadata(metadataAttributes.get("StreamTitle")));
152 } catch (UnsupportedEncodingException uee1) {
153 /* should never happen. */
154 throw new RuntimeException("UTF-8 not supported");
159 // INPUTSTREAM METHODS
163 public int read() throws IOException {
164 int data = super.read();
168 if (streamRemaining > 0) {
170 } else if (data == 0) {
171 /* 0-byte metadata follows, ignore. */
172 streamRemaining = metadataInterval - 1;
175 /* loop until we’ve read all metadata. */
176 byte[] metadataBuffer = new byte[data * 16];
177 int metadataPosition = 0;
179 int metadataByte = super.read();
180 if (metadataByte == -1) {
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);
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;
196 } while (metadataBuffer != null);
203 public int read(byte[] buffer) throws IOException {
204 return read(buffer, 0, buffer.length);
208 public int read(byte[] buffer, int offset, int length) throws IOException {
209 for (int index = offset; index < (offset + length); ++index) {
212 return (index > offset) ? (index - offset) : -1;
214 buffer[index] = (byte) data;