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