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 static com.google.common.io.Closeables.close;
21 import static net.pterodactylus.sonitus.io.mp3.Frame.ChannelMode.SINGLE_CHANNEL;
23 import java.io.ByteArrayInputStream;
24 import java.io.IOException;
25 import java.io.InputStream;
26 import java.util.Arrays;
28 import net.pterodactylus.sonitus.data.Metadata;
29 import net.pterodactylus.sonitus.io.mp3.Frame;
30 import net.pterodactylus.sonitus.io.mp3.Parser;
32 import com.google.common.base.Optional;
33 import org.blinkenlights.jid3.ID3Exception;
34 import org.blinkenlights.jid3.v2.ID3V2Tag;
37 * Identifies MP3 files.
39 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
41 public class Mp3Identifier {
44 * Tries to identify the MP3 file contained in the given stream.
48 * @return The identified metadata, or {@link Optional#absent()} if the
49 * metadata can not be identified
51 * if an I/O error occurs
53 public static Optional<Metadata> identify(InputStream inputStream) throws IOException {
54 Parser mp3Parser = new Parser(inputStream);
55 Frame frame = mp3Parser.nextFrame();
56 Metadata metadata = new Metadata((frame.channelMode() == SINGLE_CHANNEL) ? 1 : 2, frame.samplingRate(), "MP3");
57 /* check for ID3v2 tag. */
58 Optional<byte[]> id3v2TagBuffer = mp3Parser.getId3Tag();
59 if (id3v2TagBuffer.isPresent()) {
60 byte[] buffer = id3v2TagBuffer.get();
61 ByteArrayInputStream tagInputStream = new ByteArrayInputStream(Arrays.copyOfRange(buffer, 3, buffer.length));
63 /* skip “ID3” header tag. */
64 ID3V2Tag id3v2Tag = ID3V2Tag.read(tagInputStream);
65 if (id3v2Tag != null) {
66 metadata = metadata.artist(id3v2Tag.getArtist()).name(id3v2Tag.getTitle());
68 } catch (ID3Exception id3e1) {
69 id3e1.printStackTrace();
71 close(tagInputStream, true);
74 return Optional.of(metadata);