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;
29 * Wrapper around an {@link InputStream} that identifies the {@link Format} of
32 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
34 public class IdentifyingInputStream extends FilterInputStream {
36 /** The identified format. */
37 private final Format format;
40 * Creates a new identifying input stream.
43 * The input stream to wrap
45 * The format of the stream
47 private IdentifyingInputStream(InputStream inputStream, Format format) {
57 * Returns the identified format.
59 * @return The identified format
61 public Format format() {
70 * Tries to identify the given input stream.
73 * The input stream to identify
74 * @return An identifying input stream that delivers the original stream and
75 * the format it detected, or {@link com.google.common.base.Optional#absent()}
76 * if no format could be identified
78 * if an I/O error occurs
80 public static Optional<IdentifyingInputStream> create(InputStream inputStream) throws IOException {
82 /* remember everything we read here. */
83 RememberingInputStream rememberingInputStream = new RememberingInputStream(inputStream);
85 /* try Ogg Vorbis first. */
86 Optional<Format> format = OggVorbisIdentifier.identify(rememberingInputStream);
87 if (format.isPresent()) {
88 return Optional.of(new IdentifyingInputStream(rememberingInputStream.remembered(), format.get()));
91 return Optional.absent();