e9a550b38d0bb97bc009c110997b1b77e162085b
[sonitus.git] / src / main / java / net / pterodactylus / sonitus / io / Mp3Identifier.java
1 /*
2  * Sonitus - Mp3Identifier.java - Copyright © 2013 David Roden
3  *
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.
8  *
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.
13  *
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/>.
16  */
17
18 package net.pterodactylus.sonitus.io;
19
20 import java.io.IOException;
21 import java.io.InputStream;
22
23 import net.pterodactylus.sonitus.data.Metadata;
24
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
30 /**
31  * Identifies MP3 files.
32  *
33  * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
34  */
35 public class Mp3Identifier {
36
37         /**
38          * Tries to identify the MP3 file contained in the given stream.
39          *
40          * @param inputStream
41          *              The input stream
42          * @return The identified metadata, or {@link Optional#absent()} if the
43          *         metadata can not be identified
44          * @throws IOException
45          *              if an I/O error occurs
46          */
47         public static Optional<Metadata> identify(InputStream inputStream) throws IOException {
48                 Bitstream bitstream = new Bitstream(inputStream);
49                 try {
50                         Header frame = bitstream.readFrame();
51                         if (frame == null) {
52                                 return Optional.absent();
53                         }
54                         return Optional.of(new Metadata(frame.mode() == Header.SINGLE_CHANNEL ? 1 : 2, frame.frequency(), "MP3"));
55                 } catch (BitstreamException be1) {
56                         return Optional.absent();
57                 }
58         }
59
60 }