2 * Sonitus - Mp3Identifier.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.IOException;
21 import java.io.InputStream;
23 import net.pterodactylus.sonitus.data.Metadata;
25 import com.google.common.base.Optional;
26 import javazoom.jl.decoder.Bitstream;
27 import javazoom.jl.decoder.BitstreamException;
28 import javazoom.jl.decoder.Header;
29 import org.blinkenlights.jid3.ID3Exception;
30 import org.blinkenlights.jid3.v2.ID3V2Tag;
33 * Identifies MP3 files.
35 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
37 public class Mp3Identifier {
40 * Tries to identify the MP3 file contained in the given stream.
44 * @return The identified metadata, or {@link Optional#absent()} if the
45 * metadata can not be identified
47 * if an I/O error occurs
49 public static Optional<Metadata> identify(InputStream inputStream) throws IOException {
50 Bitstream bitstream = new Bitstream(inputStream);
51 Optional<ID3V2Tag> id3v2Tag = Optional.absent();
53 InputStream id3v2Stream = bitstream.getRawID3v2();
54 id3v2Stream.read(new byte[3]);
55 id3v2Tag = Optional.fromNullable(ID3V2Tag.read(id3v2Stream));
56 } catch (ID3Exception id3e1) {
57 /* ID3v2 tag could not be parsed, don’t cry about it. */
60 Header frame = bitstream.readFrame();
62 return Optional.absent();
64 Metadata metadata = new Metadata(frame.mode() == Header.SINGLE_CHANNEL ? 1 : 2, frame.frequency(), "MP3");
65 if (id3v2Tag.isPresent()) {
66 metadata = metadata.artist(id3v2Tag.get().getArtist());
67 metadata = metadata.name(id3v2Tag.get().getTitle());
69 return Optional.of(metadata);
70 } catch (BitstreamException be1) {
71 return Optional.absent();