2 * Sonitus - IdentifyingStream.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.FilterInputStream;
21 import java.io.IOException;
22 import java.io.InputStream;
24 import net.pterodactylus.sonitus.data.Format;
26 import com.google.common.base.Optional;
27 import com.google.common.io.ByteStreams;
30 * Wrapper around an {@link InputStream} that identifies the {@link Format} of
33 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
35 public class IdentifyingInputStream extends FilterInputStream {
37 /** The identified format. */
38 private final Format format;
41 * Creates a new identifying input stream.
44 * The input stream to wrap
46 * The format of the stream
48 private IdentifyingInputStream(InputStream inputStream, Format format) {
58 * Returns the identified format.
60 * @return The identified format
62 public Format format() {
71 * Tries to identify the given input stream.
74 * The input stream to identify
75 * @return An identifying input stream that delivers the original stream and
76 * the format it detected, or {@link com.google.common.base.Optional#absent()}
77 * if no format could be identified
79 * if an I/O error occurs
81 public static Optional<IdentifyingInputStream> create(InputStream inputStream) throws IOException {
83 /* remember everything we read here. */
84 RememberingInputStream rememberingInputStream = new RememberingInputStream(inputStream);
86 /* try Ogg Vorbis first. */
87 Optional<Format> format = OggVorbisIdentifier.identify(rememberingInputStream);
88 if (format.isPresent()) {
89 return Optional.of(new IdentifyingInputStream(rememberingInputStream.remembered(), format.get()));
93 rememberingInputStream = new RememberingInputStream(rememberingInputStream.remembered());
94 InputStream limitedInputStream = ByteStreams.limit(rememberingInputStream, 1048576);
95 format = Mp3Identifier.identify(limitedInputStream);
96 if (format.isPresent()) {
97 return Optional.of(new IdentifyingInputStream(rememberingInputStream.remembered(), format.get()));
100 return Optional.absent();