001    package net.sourceforge.mp3dings;
002    
003    /* Mp3dings - manage mp3 meta-information
004     * Copyright (C) 2003 Moritz Ringler
005     * $Id: Mp3FileReader.java 94 2007-10-30 16:31:44Z ringler $
006     *
007     * This program is free software; you can redistribute it and/or
008     * modify it under the terms of the GNU General Public License
009     * as published by the Free Software Foundation; either version 2
010     * of the License, or (at your option) any later version.
011     *
012     * This program is distributed in the hope that it will be useful,
013     * but WITHOUT ANY WARRANTY; without even the implied warranty of
014     * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
015     * GNU General Public License for more details.
016     *
017     * You should have received a copy of the GNU General Public License
018     * along with this program; if not, write to the Free Software
019     * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
020     */
021    
022    import java.io.File;
023    import java.io.FileNotFoundException;
024    import java.io.IOException;
025    import java.util.logging.Level;
026    import java.util.logging.Logger;
027    import java.util.regex.Matcher;
028    import java.util.regex.Pattern;
029    import de.mospace.lang.FullTextString;
030    import helliker.id3.CorruptHeaderException;
031    import helliker.id3.ID3v2FormatException;
032    import helliker.id3.MP3File;
033    import helliker.id3.NoMPEGFramesException;
034    import helliker.id3.NullsoftID3GenreTable;
035    import net.sourceforge.mp3dings.filter.FilterCollection;
036    import net.sourceforge.mp3dings.utils.FilenamePatterns;
037    
038    /** The Mp3FileReader provides methods to read information from
039    * mp3 files and their ID3 tags. Not thread-safe. **/
040    public class Mp3FileReader{
041        private static final Logger logger = Logger.getLogger(Mp3FileReader.class.getPackage().getName());
042        /** constants for constructor */
043        public static final int ID3V1 = 1;
044        public static final int ID3V2 = 2;
045        private transient MP3File mp3file;
046        private transient File lastfile;
047    
048        private int tagtype = 0;
049        FilterCollection filters = null;
050        /* Patterns for ID3-tag information processing*/
051        /* match at least one non-whitespace */
052        static final Pattern id3NonNull = Pattern.compile("\\S");
053        /* match something of the form (##) or (#) */
054        static final Pattern id3Genre = Pattern.compile("\\((\\d{1,2})\\)");
055        /* Patterns for tidying*/
056        /* match junk that displays as nasty little boxes */
057        protected static Pattern tidyJunk =
058                Pattern.compile("[^\\u0020-\\u02ff\n\r\t]");
059        /* match trailing whitespace */
060        protected static Pattern tidyTrim = Pattern.compile("\\s$");
061        private FilenamePatterns fnpatterns;
062    
063        public Mp3FileReader(){
064            fnpatterns = FilenamePatterns.load(
065                Globals.getPrefNode().node("filenamePatterns")
066            );
067            tagtype = 0;
068        }
069    
070        public Mp3FileReader(FilterCollection fc){
071            this();
072            setFilters(fc);
073            tagtype = 0;
074        }
075    
076        public Mp3FileReader(FilterCollection fc, int tagtype){
077            this(fc);
078            if(tagtype != ID3V1 && tagtype != ID3V2){
079                throw new IllegalArgumentException("Illegal value for tagtype.");
080            }
081            this.tagtype = tagtype;
082        }
083    
084        /**
085         * Guesses artist, track and title from each filename.
086         * Adds the information gathered in this way to the spreadsheet.
087         */
088        public Object getFilenameField(String filename, Field field){
089            Object val = fnpatterns.apply(filename, field);
090            if (val == null){
091                return null;
092            }
093            return postProcessField(field, val);
094        }
095    
096        public void setFilters(FilterCollection fc){
097            filters = fc;
098        }
099    
100        public Object getField(File f, Field field){
101            return getID3Field(f, field);
102        }
103    
104        public Object getID3Field(File mp3, Field field){
105            Object result = null;
106            if (field == Field.SIZE){
107                result = postProcessField(field, new Long(mp3.length()));
108            } else if (field == Field.FILENAME){
109                result = postProcessField(field, mp3.getName());
110            } else if (field == Field.FULLPATH){
111                result = postProcessField(field, mp3.getAbsolutePath());
112            }  else {
113                try{
114                    if(lastfile == null ||
115                        !lastfile.getPath().equals(mp3.getAbsolutePath()))
116                    {
117                        mp3file = null;
118                        mp3file = (tagtype == 0)
119                        ? new MP3File(mp3)
120                        : new MP3File(mp3, (tagtype == ID3V1)
121                            ? MP3File.ID3V1_ONLY
122                            : MP3File.ID3V2_ONLY);
123                    }
124                    if(mp3file == null){
125                        return null;
126                    } else {
127                        boolean b = Globals.getPrefNode().getBoolean("analyzeVBRFiles", true);
128                        mp3file.setAnalyzeVBRFiles(b);
129                    }
130                    result = getID3Field(field);
131                } catch (RuntimeException rx){
132                    logger.severe("Error reading " + field + " from " + mp3);
133                    Globals.logStackTrace(logger, Level.SEVERE, rx);
134                } catch (Exception x){
135                    logger.warning("Error reading " + field + " info from " + mp3
136                        + "\n" + x.toString());
137                } finally {
138                    lastfile = mp3;
139                }
140            }
141            return result;
142        }
143    
144        private Object getID3Field(Field field) throws ID3v2FormatException{
145            Object val = null;
146            if(field == Field.ATTACHED_PICTURE){
147                val = mp3file.getAttachedPicture();
148            } else if (field == Field.ARTIST){
149                val = mp3file.getArtist();
150            } else if (field == Field.TITLE){
151                val = mp3file.getTitle();
152            } else if (field == Field.ALBUM){
153                val = mp3file.getAlbum();
154            } else if (field == Field.TRACK){
155                val = mp3file.getTrack();
156            } else if (field == Field.YEAR){
157                val = mp3file.getYear();
158            } else if (field == Field.GENRE){
159                val = mp3file.getGenre();
160            } else if (field == Field.COMMENT){
161                val = mp3file.getComment();
162            } else if (field == Field.LENGTH){
163                int time = mp3file.getPlayingTime();
164                val = (time <= 0)? null : new Integer(time);
165            } else {
166                val = mp3file.getFrameDataString(field.id3v2Frame());
167            }
168            //postProcessField will coerce val to be of the correct type
169            return postProcessField(field, val);
170        }
171    
172        static private String tidy(String s){
173            //String str;
174            //Matcher m = tidyJunk.matcher(s);
175            //str = m.replaceAll("");
176            return tidyTrim.matcher(s).replaceAll("");
177        }
178    
179        public Object postProcessField(Field field, Object val){
180            if (val == null){
181                return null;
182            }
183            Object result = null;
184            String stringVal = null;
185            Number numVal = null;
186            Matcher m;
187            if (field == Field.GENRE){
188                stringVal = (String) val;
189                if(id3NonNull.matcher(stringVal).find()){
190                    m = id3Genre.matcher(stringVal);
191                    String genre;
192                    if(m.find()){
193                        int tn;
194                        try{
195                            tn = Integer.parseInt(m.group(1));
196                        } catch (NumberFormatException ex){
197                            return null;
198                        }
199                        genre = NullsoftID3GenreTable.getGenre(tn);
200                        if (genre!= null) {
201                            stringVal = genre;
202                        }
203                    }
204                }
205                result = stringVal;
206            }
207            if(result == null){
208                switch (field.type()){
209    
210                    case Field.TYPE_STRING:
211                        stringVal = (String) val;
212                        if( (stringVal == null) ||
213                            !id3NonNull.matcher(stringVal).find()
214                        ){
215                            result = null;
216                        } else {
217                            result = tidy(stringVal);
218                        }
219                        break;
220    
221                    case Field.TYPE_LONGTEXT:
222                        stringVal = (val==null)? null : val.toString();
223                        if( (stringVal == null) ||
224                            !id3NonNull.matcher(stringVal).find()
225                        ){
226                            result = null;
227                        } else {
228                            result = new FullTextString(tidy(stringVal));
229                        }
230                        break;
231    
232                    case Field.TYPE_NUMERIC:
233                        if(val instanceof Number){
234                            result = val;
235                        } else {
236                            stringVal = String.valueOf(val);
237                            if(!id3NonNull.matcher(stringVal).find()){
238                                result = null;
239                            } else {
240                                try{
241                                    double dval = Double.parseDouble(stringVal);
242                                    boolean isInt = false;
243                                    long lval = -1;
244                                    try{
245                                        lval = Long.parseLong(stringVal);
246                                        isInt = (lval == dval);
247                                    } catch (NumberFormatException ignore){
248                                    }
249                                    if(isInt){
250                                        if(lval <= Integer.MAX_VALUE
251                                            && lval >= Integer.MIN_VALUE){
252                                            result = new Integer((int) lval);
253                                        } else {
254                                            result = new Long(lval);
255                                        }
256                                    } else {
257                                        result = new Double(dval);
258                                    }
259                                } catch (NumberFormatException ex){
260                                    result = null;
261                                }
262                            }
263                        }
264                        break;
265    
266                    default:
267                        Object rawresult = val;
268                        if(rawresult == null || (field.typeAsClass().isInstance(rawresult))){
269                            result = rawresult;
270                        } else {
271                            logger.severe("Error filtering value " + val + " of field " + field);
272                            logger.severe(rawresult + " is not an instance of type " + field.typeAsClass());
273                        }
274                }
275            }
276            return filters.filter(field, result);
277        }
278    }