001    package helliker.id3;
002    
003    import java.io.File;
004    import java.io.FileInputStream;
005    import java.io.FileOutputStream;
006    import java.io.IOException;
007    import java.nio.channels.FileChannel;
008    import java.security.MessageDigest;
009    import java.security.NoSuchAlgorithmException;
010    import java.util.logging.Logger;
011    
012    /*
013    Copyright (C) 2001,2002 Jonathan Hilliker
014    This library is free software; you can redistribute it and/or
015    modify it under the terms of the GNU Lesser General Public
016    License as published by the Free Software Foundation; either
017    version 2.1 of the License, or (at your option) any later version.
018    This library is distributed in the hope that it will be useful,
019    but WITHOUT ANY WARRANTY; without even the implied warranty of
020    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
021    Lesser General Public License for more details.
022    You should have received a copy of the GNU Lesser General Public
023    License along with this library; if not, write to the Free Software
024    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
025    */
026    /**
027    * Description: This class is a container of all the tags and data that can be
028    * extracted from the mp3 specified by the file. If there are no id3 tags
029    * present, tags will be created by using mutators and saving the data.
030    */
031    public class MP3File implements Comparable {
032        private final static Logger logger = Logger.getLogger(ID3v2Tag.class.getPackage().getName());
033    
034        /** Whether to analyze VBR files if necessary. */
035        private boolean analyzeVBR = true;
036    
037        /**
038        * Write ID3v1 and ID3v2 tags whether or not they exist. Precedence for
039        * reading will be given to id3v2 tags.
040        */
041        public static final int BOTH_TAGS = 0;
042    
043        /**
044        * Write and read from ID3v2 tags only. An ID3v2 tag will be created if an
045        * attempt is made to write.
046        */
047        public static final int ID3V2_ONLY = 1;
048    
049        /**
050        * Write and read from ID3v1 tags only. An ID3v1 tag will be created if an
051        * attempt is made to write.
052        */
053        public static final int ID3V1_ONLY = 2;
054    
055        /**
056        * Do not write or read from any id3 tags.
057        */
058        public static final int NO_TAGS = 3;
059    
060        /**
061        * Only write and read tags that already exist. Existing tags can be updated
062        * but new tags will not be created.
063        */
064        public static final int EXISTING_TAGS_ONLY = 4;
065    
066        /**
067        * The ID3v1 Tag position ???
068        */
069        private static final int ID3V1 = 5;
070        /**
071        * Another int for ID3v2 ???
072        */
073        private static final int ID3V2 = 6;
074    
075        /**
076        * The ID3v1 Tag
077        */
078        private ID3v1Tag id3v1 = null;
079        /**
080        * The ID3v2 Tag
081        */
082        private ID3v2Tag id3v2 = null;
083        /**
084        * The MPEG-Audio frameheader
085        */
086        private MPEGAudioFrameHeader head = null;
087        /**
088        * The MP3 File
089        */
090        private File mp3 = null;
091        /**
092        * The Tag Type
093        */
094        private int tagType = 0;
095    
096    
097        /**
098        * Create an MP3File object that reads and writes to the file with the
099        * filename fn. This assumes that you only want to read and write id3 tags
100        * that already exist in the file.
101        *
102        *@param fn                          the filename of the mp3
103        *@exception FileNotFoundException   if an error occurs
104        *@exception NoMPEGFramesException   if an error occurs
105        *@exception IOException             if an error occurs
106        *@exception ID3v2FormatException    if an error occurs
107        *@exception CorruptHeaderException  if an error occurs
108        */
109        public MP3File(String fn) throws NoMPEGFramesException,
110        IOException, ID3v2FormatException,
111        CorruptHeaderException {
112    
113            this(new File(fn));
114        }
115    
116    
117        /**
118        * Create an MP3File object that reads and writes to the specified file. This
119        * assumes that you only want to read and write id3 tags tha already exist in
120        * the file.
121        *
122        *@param mp3                         the file of the mp3
123        *@exception FileNotFoundException   if an error occurs
124        *@exception NoMPEGFramesException   if an error occurs
125        *@exception IOException             if an error occurs
126        *@exception ID3v2FormatException    if an error occurs
127        *@exception CorruptHeaderException  if an error occurs
128        */
129        public MP3File(File mp3) throws NoMPEGFramesException, IOException,
130        ID3v2FormatException, CorruptHeaderException {
131    
132            this(mp3, EXISTING_TAGS_ONLY);
133        }
134    
135    
136        /**
137        * Create an MP3File object that reads and writes to the file with the
138        * filename fn. The id3 tags that are read from and written are dependant upon
139        * the tagType argument. This could be either: BOTH_TAGS, ID3V2_ONLY,
140        * ID3V1_ONLY, NO_TAGS, or EXISTING_TAGS_ONLY.
141        *
142        *@param fn                          the filename of the mp3
143        *@param tagType                     determines what type of tags to write and
144        *      read from
145        *@exception FileNotFoundException   if an error occurs
146        *@exception NoMPEGFramesException   if an error occurs
147        *@exception IOException             if an error occurs
148        *@exception ID3v2FormatException    if an error occurs
149        *@exception CorruptHeaderException  if an error occurs
150        */
151        public MP3File(String fn, int tagType) throws NoMPEGFramesException,
152        IOException, ID3v2FormatException, CorruptHeaderException {
153    
154            this(new File(fn), tagType);
155        }
156    
157    
158        /**
159        * Create and MP3File object that reads and writes to the specified file. The
160        * id3 tags that are read from and written are dependant upon the tagType
161        * argument. This could be either: BOTH_TAGS, ID3V2_ONLY, ID3V1_ONLY, NO_TAGS,
162        * or EXISTING_TAGS_ONLY.
163        *
164        *@param mp3                         the file of the mp3
165        *@param tagType                     determines what type of tags to write and
166        *      read from
167        *@exception FileNotFoundException   if an error occurs
168        *@exception NoMPEGFramesException   if an error occurs
169        *@exception IOException             if an error occurs
170        *@exception ID3v2FormatException    if an error occurs
171        *@exception CorruptHeaderException  if an error occurs
172        */
173        public MP3File(File mp3, int tagType) throws
174                NoMPEGFramesException, IOException,
175                ID3v2FormatException, CorruptHeaderException
176        {
177    
178            this.mp3 = mp3;
179            this.tagType = tagType;
180    
181            // Start looking at the beginning of the file
182            id3v1 = new ID3v1Tag(mp3);
183            id3v2 = new ID3v2Tag(mp3);
184            //force MPEGAudioHeader to sync over at least twice the tag size
185            int tagsize = id3v2.tagExists()? id3v2.getTotalWrittenTagSize() : 0;
186            head = new MPEGAudioFrameHeader(mp3, 2 * tagsize);
187            long headloc = head.getLocation();
188            if(head.getLocation() != tagsize){
189                logger.fine(mp3 + "\naudio offset: " + headloc + " (0x" +
190                    Long.toHexString(headloc).toUpperCase() +
191                    ")\ntag size: "+tagsize+" (0x" + Long.toHexString(tagsize).toUpperCase() + ")");
192            }
193        }
194    
195    
196        /**
197        * Returns the length (in seconds) of the playing time of this mp3.
198        *
199        *@return   the playing time (in seconds) of this mp3
200        * @see #setAnalyzeVBRFiles
201        */
202        public int getPlayingTime() {
203            long time = 0;
204    
205            if (head.isVBR()) {
206                time = head.getVBRPlayingTime();
207                try{
208                    if(time == MPEGAudioFrameHeader.NULL && analyzeVBR &&
209                        head.analyzeVBR())
210                    {
211                        time = head.getVBRPlayingTime();
212                    }
213                } catch (IOException iox){
214                    logger.warning(iox.toString());
215                }
216            } else {
217                long datasize = (mp3.length() * 8) - id3v2.getTotalWrittenTagSize()
218                - id3v1.getSize();
219                long bps = head.getBitRate() * 1000;
220    
221                // Avoid divide by zero error
222                if (bps == 0) {
223                    time = 0;
224                } else {
225                    time = datasize / bps;
226                }
227            }
228    
229            return (time <= 0 || time > Integer.MAX_VALUE)? -1 : (int) time;
230        }
231    
232    
233        /**
234        * Return a formatted version of the getPlayingTime method. The string will be
235        * formated "m:ss" where 'm' is minutes and 'ss' is seconds.
236        *
237        *@return   a formatted version of the getPlayingTime method
238        */
239        public String getPlayingTimeString() {
240            String str;
241            long time = getPlayingTime();
242            long mins = time / 60;
243            long secs = Math.round((((double) time / 60) - (long) (time / 60)) * 60);
244    
245            str = mins + ":";
246    
247            if (secs < 10) {
248                str += "0" + secs;
249            } else {
250                str += "" + secs;
251            }
252    
253            return str;
254        }
255    
256    
257        /**
258        * Return the absolute path of this MP3File.
259        *
260        *@return   the absolute path of this MP3File
261        */
262        public String getPath() {
263            return mp3.getAbsolutePath();
264        }
265    
266    
267        /**
268        * Returns the parent directory of this MP3File.
269        *
270        *@return   the parent directory of this MP3File
271        */
272        public String getParent() {
273            return mp3.getAbsoluteFile().getParent();
274        }
275    
276    
277        /**
278        * Returns the filename of this MP3File.
279        *
280        *@return   the filename of this MP3File
281        */
282        public String getFileName() {
283            return mp3.getName();
284        }
285    
286    
287        /**
288        * Return the filesize of this MP3File (in bytes).
289        *
290        *@return   the filesize of this MP3File (in bytes)
291        */
292        public long getFileSize() {
293            return mp3.length();
294        }
295    
296    
297        /**
298        * Returns true if an id3v2 tag currently exists.
299        *
300        *@return   true if an id3v2 tag currently exists
301        */
302        public boolean id3v2Exists() {
303            return id3v2.tagExists();
304        }
305    
306    
307        /**
308        * Returns true if an id3v1 tag currently exists.
309        *
310        *@return   true if an id3v1 tag currently exists
311        */
312        public boolean id3v1Exists() {
313            return id3v1.tagExists();
314        }
315    
316    
317        /**
318        * Returns true if this file is an mp3. This means simply that an
319        * MPEGAudioFrameHeader was found and the layer is 3.
320        *
321        *@return   true if this file is an mp3
322        */
323        public boolean isMP3() {
324            return head.isMP3();
325        }
326    
327    
328        /**
329        * Returns true if this mp3 is a variable bitrate file.
330        *
331        *@return   true if this mp3 is a variable bitrate file.
332        */
333        public boolean isVBR() {
334            return head.isVBR();
335        }
336    
337        /** Sets whether to analyze VBR files without XING or VBRI header.
338        * @see #getPlayingTime
339        * @see #getBitRate
340        */
341        public void setAnalyzeVBRFiles(boolean b){
342            analyzeVBR = b;
343        }
344    
345    
346        /**
347        * Returns the bitrate of this mp3 in kbps. If the file is a VBR file then the
348        * average bitrate is returned.
349        *
350        *@return   the bitrate of this mp3 in kbps
351        *@see #setAnalyzeVBRFiles
352        */
353        public int getBitRate() {
354            int br = head.getBitRate();
355            try{
356                if(br == MPEGAudioFrameHeader.NULL && analyzeVBR && head.isVBR()
357                    && head.analyzeVBR())
358                {
359                    br = head.getBitRate();
360                }
361            } catch (IOException iox){
362                logger.warning(iox.toString());
363            }
364            return br;
365        }
366    
367    
368        /**
369        * Returns the sample rate of this mp3 in Hz.
370        *
371        *@return   the sample reate of this mp3 in Hz
372        */
373        public int getSampleRate() {
374            return head.getSampleRate();
375        }
376    
377    
378        /**
379        * Returns the emphasis of this mp3.
380        *
381        *@return   the emphasis of this mp3
382        */
383        public String getMPEGEmphasis() {
384            return head.getEmphasis();
385        }
386    
387    
388        /**
389        * Returns a string specifying the layer of the mpeg. Ex: Layer III
390        *
391        *@return   a string specifying the layer of the mpeg
392        */
393        public String getMPEGLayer() {
394            return head.getLayer();
395        }
396    
397    
398        /**
399        * Returns a string specifying the version of the mpeg. This can either be
400        * 1.0, 2.0, or 2.5.
401        *
402        *@return   a string specifying the version of the mpeg
403        */
404        public String getMPEGVersion() {
405            return head.getVersion();
406        }
407    
408    
409        /**
410        * Return the channel mode of the mpeg. Ex: Stereo
411        *
412        *@return   the channel mode of the mpeg
413        */
414        public String getMPEGChannelMode() {
415            return head.getChannelMode();
416        }
417    
418    
419        /**
420        * Returns true if this mpeg is copyrighted.
421        *
422        *@return   true if this mpeg is copyrighted
423        */
424        public boolean isMPEGCopyrighted() {
425            return head.isCopyrighted();
426        }
427    
428    
429        /**
430        * Returns true if this mpeg is the original.
431        *
432        *@return   true if this mpeg is the original
433        */
434        public boolean isMPEGOriginal() {
435            return head.isOriginal();
436        }
437    
438    
439        /**
440        * Returns true if this mpeg is protected by CRC.
441        *
442        *@return   true if this mpeg is protected by CRC
443        */
444        public boolean isMPEGProtected() {
445            return head.isProtected();
446        }
447    
448    
449        /**
450        * Returns true if the private bit is set in this mpeg.
451        *
452        *@return   true if the private bit is set in this mpeg
453        */
454        public boolean isMPEGPrivate() {
455            return head.privateBitSet();
456        }
457    
458    
459        /**
460        * Removes id3 tags from the file. The argument specifies which tags to
461        * remove. This can either be BOTH_TAGS, ID3V1_ONLY, ID3V2_ONLY, or
462        * EXISTING_TAGS_ONLY.
463        *
464        *@param type                       specifies what tag(s) to remove
465        *@exception FileNotFoundException  if an error occurs
466        *@exception IOException            if an error occurs
467        */
468        public void removeTags(int type)
469        throws IOException {
470    
471            removeTags(type, false);
472        }
473    
474        /**
475        * Removes id3 tags from the file. The argument specifies which tags to
476        * remove. This can either be BOTH_TAGS, ID3V1_ONLY, ID3V2_ONLY, or
477        * EXISTING_TAGS_ONLY.
478        *
479        *@param type                       specifies what tag(s) to remove
480        *@exception FileNotFoundException  if an error occurs
481        *@exception IOException            if an error occurs
482        */
483        public void removeTags(int type, boolean forceMpegOffset)
484        throws IOException {
485    
486            if (allow(ID3V1, type)) {
487                id3v1.removeTag(forceMpegOffset);
488            }
489            if (allow(ID3V2, type)) {
490                id3v2.removeTag(forceMpegOffset);
491            }
492        }
493    
494        /** Removes all non-audio data from the start of the specified file.
495        A corrupt ID3V2Tag cannot be removed via
496        {@link #removeTags} because trying to construct
497        an instance of this class on the file will throw
498        an exception. In this case you can try this static
499        method which will remove all non-audio Data from
500        <code>mp3</code>. **/
501        public static void removeLeadingGarbage(File mp3)
502                throws NoMPEGFramesException, IOException, CorruptHeaderException
503        {
504            long audio = (new MPEGAudioFrameHeader(mp3, 0)).getLocation();
505            if(audio == 0){
506                return;
507            }
508            File temp = null;
509            FileChannel in = new FileInputStream(mp3).getChannel();
510            try{
511                temp = File.createTempFile(mp3.getName(), "tmp.mp3",
512                    mp3.getAbsoluteFile().getParentFile());
513                FileChannel out = new FileOutputStream(temp).getChannel();
514                try{
515                    in.transferTo(audio, mp3.length() - audio, out);
516                } finally {
517                    out.close();
518                }
519            } finally {
520                in.close();
521            }
522    
523            if(!(mp3.delete() && temp.renameTo(mp3))){
524                throw new IOException("Error renaming temporary file " + temp + " to mp3.");
525            }
526        }
527    
528    
529        /**
530        * Writes the current state of the id3 tags to the file. What tags are written
531        * depends upon the tagType passed to the constructor.
532        *
533        *@exception FileNotFoundException  if an error occurs
534        *@exception IOException            if an error occurs
535        */
536        public void writeTags()
537        throws IOException {
538            writeTags(false);
539        }
540    
541        public void writeTags(boolean forceMpegOffset)
542        throws IOException {
543    
544            // Write out id3v2 first because if the filesize is changed when an
545            // id3v2 is written then the id3v1 may be moved away from the end
546            // of the file which would cause it to not be recognized.
547            if (allow(ID3V2)) {
548                id3v2.writeTag(forceMpegOffset);
549            }
550            if (allow(ID3V1)) {
551                id3v1.writeTag();
552            }
553        }
554    
555    
556        /**
557        * Set the title of this mp3.
558        *
559        *@param title  the title of the mp3
560        */
561        public void setTitle(String title) {
562            if (allow(ID3V1)) {
563                id3v1.setTitle(title);
564            }
565            if (allow(ID3V2)) {
566                id3v2.setTextFrame(ID3v2Frames.TITLE, title);
567            }
568        }
569    
570    
571        /**
572        * Set the album of this mp3.
573        *
574        *@param album  the album of the mp3
575        */
576        public void setAlbum(String album) {
577            if (allow(ID3V1)) {
578                id3v1.setAlbum(album);
579            }
580            if (allow(ID3V2)) {
581                id3v2.setTextFrame(ID3v2Frames.ALBUM, album);
582            }
583        }
584    
585    
586        /**
587        * Set the artist of this mp3.
588        *
589        *@param artist  the artist of the mp3
590        */
591        public void setArtist(String artist) {
592            if (allow(ID3V1)) {
593                id3v1.setArtist(artist);
594            }
595            if (allow(ID3V2)) {
596                id3v2.setTextFrame(ID3v2Frames.LEAD_PERFORMERS, artist);
597            }
598        }
599    
600    
601        /**
602        * Add a comment to this mp3.
603        *
604        *@param comment  a comment to add to the mp3
605        */
606        public void setComment(String comment) {
607            if (allow(ID3V1)) {
608                id3v1.setComment(comment);
609            }
610            if (allow(ID3V2)) {
611                id3v2.setCommentFrame("", comment);
612            }
613        }
614    
615    
616        /**
617        * Set the genre of this mp3.
618        *
619        *@param genre  the genre of the mp3
620        */
621        public void setGenre(String genre) {
622            if (allow(ID3V1)) {
623                id3v1.setGenreString(genre);
624            }
625            if (allow(ID3V2)) {
626                id3v2.setTextFrame(ID3v2Frames.CONTENT_TYPE, genre);
627            }
628        }
629    
630    
631        /**
632        * Set the year of this mp3.
633        *
634        *@param year  of the mp3
635        */
636        public void setYear(String year) {
637            if (allow(ID3V1)) {
638                id3v1.setYear(year);
639            }
640            if (allow(ID3V2)) {
641                id3v2.setTextFrame(ID3v2Frames.YEAR, year);
642            }
643        }
644    
645    
646        /**
647        * Set the track number of this mp3.
648        *
649        *@param track  the track number of this mp3
650        */
651        public void setTrack(int track) {
652            if (allow(ID3V1)) {
653                id3v1.setTrack(track);
654            }
655            if (allow(ID3V2)) {
656                id3v2.setTextFrame(ID3v2Frames.TRACK_NUMBER,
657                String.valueOf(track));
658            }
659        }
660    
661    
662        /**
663        * Set the track number with a String.
664        *
665        *@param track                      the track number of this mp3
666        *@exception NumberFormatException  if the String can't be parsed as an
667        *      integer
668        */
669        public void setTrack(String track){
670            if (allow(ID3V1)) {
671                id3v1.setTrack(Integer.parseInt(track));
672            }
673            if (allow(ID3V2)) {
674                id3v2.setTextFrame(ID3v2Frames.TRACK_NUMBER,
675                track);
676            }
677        }
678    
679    
680        /**
681        * Set the composer of this mp3 (id3v2 only).
682        *
683        *@param composer  the composer of this mp3
684        */
685        public void setComposer(String composer) {
686            if (allow(ID3V2)) {
687                id3v2.setTextFrame(ID3v2Frames.COMPOSER, composer);
688            }
689        }
690    
691    
692        /**
693        * Set the original artist of this mp3 (id3v2 only).
694        *
695        *@param artist  the original artist of this mp3
696        */
697        public void setOriginalArtist(String artist) {
698            if (allow(ID3V2)) {
699                id3v2.setTextFrame(ID3v2Frames.ORIGINAL_ARTIST, artist);
700            }
701        }
702    
703    
704        /**
705        * Add some copyright information to this mp3 (id3v2 only).
706        *
707        *@param copyright  copyright information related to this mp3
708        */
709        public void setCopyrightInfo(String copyright) {
710            if (allow(ID3V2)) {
711                id3v2.setTextFrame(ID3v2Frames.COPYRIGHT_MESSAGE, copyright);
712            }
713        }
714    
715    
716        /**
717        * Add a link to this mp3 (id3v2 only). This includes a description of the url
718        * and the url itself.
719        *
720        *@param desc  a description of the url
721        *@param url   the url itself
722        */
723        public void setUserDefinedURL(String desc, String url) {
724            if (allow(ID3V2)) {
725                id3v2.setUserDefinedURLFrame(desc, url);
726            }
727        }
728    
729    
730        /**
731        * Add a field of miscellaneous text (id3v2 only). This includes a description
732        * of the text and the text itself.
733        *
734        *@param desc  a description of the text
735        *@param text  the text itself
736        */
737        public void setUserDefinedText(String desc, String text) {
738            if (allow(ID3V2)) {
739                id3v2.setUserDefinedTextFrame(desc, text);
740            }
741        }
742    
743    
744        /**
745        * Set who encoded the mp3 (id3v2 only).
746        *
747        *@param encBy  who encoded the mp3
748        */
749        public void setEncodedBy(String encBy) {
750            if (allow(ID3V2)) {
751                id3v2.setTextFrame(ID3v2Frames.ENCODED_BY, encBy);
752            }
753        }
754    
755    
756        /**
757        * Set the text of the text frame specified by the id (id3v2 only). The id
758        * should be one of the static strings specifed in ID3v2Frames class. All id's
759        * that begin with 'T' (excluding "TXXX") are considered text frames.
760        *
761        *@param id    the id of the frame to set the data for
762        *@param data  the data to set
763        */
764        public void setTextFrame(String id, String data) {
765            if (allow(ID3V2)) {
766                id3v2.setTextFrame(id, data);
767            }
768        }
769    
770    
771        /**
772        * Set the data of the frame specified by the id (id3v2 only). The id should
773        * be one of the static strings specified in ID3v2Frames class.
774        *
775        *@param id    the id of the frame to set the data for
776        *@param data  the data to set
777        */
778        public void setFrameData(String id, byte[] data) {
779            if (allow(ID3V2)) {
780                id3v2.updateFrameData(id, data);
781            }
782        }
783    
784    
785        /**
786        * Returns the artist of the mp3 if set and the empty string if not.
787        *
788        *@return                          the artist of the mp3
789        *@exception ID3v2FormatException  if the data of the field is incorrect
790        */
791        public String getArtist() throws ID3v2FormatException {
792            String str = new String();
793    
794            if (allow(ID3V2)) {
795                str = id3v2.getFrameDataString(ID3v2Frames.LEAD_PERFORMERS);
796            } else if (allow(ID3V1)) {
797                str = id3v1.getArtist();
798            }
799    
800            return str;
801        }
802    
803    
804        /**
805        * Returns the album of the mp3 if set and the empty string if not.
806        *
807        *@return                          the album of the mp3
808        *@exception ID3v2FormatException  if the data of the field is incorrect
809        */
810        public String getAlbum() throws ID3v2FormatException {
811            String str = new String();
812    
813            if (allow(ID3V2)) {
814                str = id3v2.getFrameDataString(ID3v2Frames.ALBUM);
815            } else if (allow(ID3V1)) {
816                str = id3v1.getAlbum();
817            }
818    
819            return str;
820        }
821    
822    
823        /**
824        * Returns the comment field of this mp3 if set and the empty string if not.
825        *
826        *@return                          the comment field of this mp3
827        *@exception ID3v2FormatException  if the data of the field is incorrect
828        */
829        public String getComment() throws ID3v2FormatException {
830            String str = new String();
831    
832            if (allow(ID3V2)) {
833                str = id3v2.getFrameDataString(ID3v2Frames.COMMENTS);
834            } else if (allow(ID3V1)) {
835                str = id3v1.getComment();
836            }
837    
838            return str;
839        }
840    
841    
842        /**
843        * Returns the genre of this mp3 if set and the empty string if not.
844        *
845        *@return                          the genre of this mp3
846        *@exception ID3v2FormatException  if the data of this field is incorrect
847        */
848        public String getGenre() throws ID3v2FormatException {
849            String str = new String();
850    
851            if (allow(ID3V2)) {
852                str = id3v2.getFrameDataString(ID3v2Frames.CONTENT_TYPE);
853            } else if (allow(ID3V1)) {
854                str = id3v1.getGenreString();
855            }
856    
857            return str;
858        }
859    
860    
861        /**
862        * Returns the title of this mp3 if set and the empty string if not.
863        *
864        *@return                          the title of this mp3
865        *@exception ID3v2FormatException  if the data of this field is incorrect
866        */
867        public String getTitle() throws ID3v2FormatException {
868            String str = new String();
869    
870            if (allow(ID3V2)) {
871                str = id3v2.getFrameDataString(ID3v2Frames.TITLE);
872            } else if (allow(ID3V1)) {
873                str = id3v1.getTitle();
874            }
875    
876            return str;
877        }
878    
879    
880        /**
881        * Returns the track exactly as the track field of the id3 tag reads.
882        *
883        *@return                          the track of this mp3
884        *@exception ID3v2FormatException  if the data of this field is incorrect
885        */
886        public String getTrackString() throws ID3v2FormatException {
887            String str = new String();
888    
889            if (allow(ID3V2)) {
890                str = id3v2.getFrameDataString(ID3v2Frames.TRACK_NUMBER);
891            } else if (allow(ID3V1)) {
892                str = String.valueOf(id3v1.getTrack());
893            }
894    
895            return str;
896        }
897    
898    
899        /**
900        * Returns an integer value of the track number. If a track field of an id3v2
901        * tag has a '/' the number before the '/' will be returned. Returns null if
902        * there is an error parsing the track field.
903        *
904        *@return                          an int value of the track number
905        *@exception ID3v2FormatException  if an error occurs
906        */
907        public Integer getTrack()  throws ID3v2FormatException {
908            String str = getTrackString();
909            Integer track = null;
910            int loc = str.indexOf("/");
911    
912            try {
913                if (loc != -1) {
914                    str = str.substring(0, loc);
915                }
916    
917                track = Integer.valueOf(str);
918            } catch (NumberFormatException e) {
919                // Do nothing
920            }
921    
922            return (track != null && track.intValue() <= 0)? null : track;
923        }
924    
925    
926        /**
927        * Although not a standard, sometimes track numbers are expressed as "x/y"
928        * where x is the track number and y is the total number of tracks on an
929        * album. This method will attempt to return the y value. Returns -1 if there
930        * is an error parsing the field or if there is no id3v2 tag.
931        *
932        *@return                          the total number of tracks of the related
933        *      album
934        *@exception ID3v2FormatException  if an error occurs
935        */
936        public int getNumTracks() throws ID3v2FormatException {
937            String str = getTrackString();
938            int track = -1;
939            int loc = str.indexOf("/");
940    
941            try {
942                if (loc != -1) {
943                    str = str.substring(loc + 1, str.length());
944                    track = Integer.parseInt(str);
945                }
946            } catch (NumberFormatException e) {
947                // Do nothing
948            }
949    
950            return track;
951        }
952    
953    
954        /**
955        * Returns the year of this mp3 if set and the empty string if not.
956        *
957        *@return                          the year of this mp3
958        *@exception ID3v2FormatException  if the data of this field is incorrect
959        */
960        public String getYear() throws ID3v2FormatException {
961            String str = new String();
962    
963            if (allow(ID3V2)) {
964                str = id3v2.getFrameDataString(ID3v2Frames.YEAR);
965            } else if (allow(ID3V1)) {
966                str = id3v1.getYear();
967            }
968    
969            return str;
970        }
971    
972    
973        /**
974        * Returns the composer of this mp3 if set and the empty string if not (id3v2
975        * only).
976        *
977        *@return                          the composer of this mp3
978        *@exception ID3v2FormatException  if the data of this field is incorrect
979        */
980        public String getComposer() throws ID3v2FormatException {
981            String str = new String();
982    
983            if (allow(ID3V2)) {
984                str = id3v2.getFrameDataString(ID3v2Frames.COMPOSER);
985            }
986    
987            return str;
988        }
989    
990        public APICImage getAttachedPicture() throws ID3v2FormatException{
991            return (allow(ID3V2))? id3v2.getAttachedPicture() : null;
992        }
993    
994        public void setAttachedPicture(APICImage pic){
995            if (allow(ID3V2)) {
996                id3v2.setAttachedPicture(pic);
997            }
998        }
999    
1000        /**
1001        * Returns the original artist of this mp3 if set and the empty string if not
1002        * (id3v2 only).
1003        *
1004        *@return                          the original artist of this mp3
1005        *@exception ID3v2FormatException  if the data of this field is incorrect
1006        */
1007        public String getOriginalArtist() throws ID3v2FormatException {
1008            String str = new String();
1009    
1010            if (allow(ID3V2)) {
1011                str = id3v2.getFrameDataString(ID3v2Frames.ORIGINAL_ARTIST);
1012            }
1013    
1014            return str;
1015        }
1016    
1017    
1018        /**
1019        * Returns the copyright info of this mp3 if set and the empty string if not
1020        * (id3v2 only).
1021        *
1022        *@return                          the copyright info of this mp3
1023        *@exception ID3v2FormatException  if the data of this field is incorrect
1024        */
1025        public String getCopyrightInfo() throws ID3v2FormatException {
1026            String str = new String();
1027    
1028            if (allow(ID3V2)) {
1029                str = id3v2.getFrameDataString(ID3v2Frames.COPYRIGHT_MESSAGE);
1030            }
1031    
1032            return str;
1033        }
1034    
1035    
1036        /**
1037        * Returns the user defined url of this mp3 if set and the empty string if not
1038        * (id3v2 only).
1039        *
1040        *@return                          the user defined url of this mp3
1041        *@exception ID3v2FormatException  if the data of this field is incorrect
1042        */
1043        public String getUserDefinedURL() throws ID3v2FormatException {
1044            String str = new String();
1045    
1046            if (allow(ID3V2)) {
1047                str = id3v2.getFrameDataString(ID3v2Frames.USER_DEFINED_URL);
1048            }
1049    
1050            return str;
1051        }
1052    
1053    
1054        /**
1055        * Returns who encoded this mp3 if set and the empty string if not (id3v2
1056        * only).
1057        *
1058        *@return                          who encoded this mp3
1059        *@exception ID3v2FormatException  if the data of this field is incorrect
1060        */
1061        public String getEncodedBy() throws ID3v2FormatException {
1062            String str = new String();
1063    
1064            if (allow(ID3V2)) {
1065                str = id3v2.getFrameDataString(ID3v2Frames.ENCODED_BY);
1066            }
1067    
1068            return str;
1069        }
1070    
1071    
1072        /**
1073        * Returns the textual information contained in the frame specifed by the id.
1074        * If the frame does not contain any textual information or does not exist,
1075        * then the empty string is returned (id3v2 only). The id should be one of the
1076        * static strings defined in the ID3v2Frames class.
1077        *
1078        *@param id                        the id of the frame to get data from
1079        *@return                          the textual information of the frame
1080        *@exception ID3v2FormatException  if the data of the frame is incorrect
1081        */
1082        public String getFrameDataString(String id) throws ID3v2FormatException {
1083            String str = new String();
1084    
1085            if (allow(ID3V2)) {
1086                str = id3v2.getFrameDataString(id);
1087            }
1088    
1089            return str;
1090        }
1091    
1092    
1093        /**
1094        * Returns the data contained in the frame specified by the id (id3v2 only) .
1095        * If the frame does not exist, a zero length array will be returned. The id
1096        * should be one of the static strings defined in the ID3v2Frames class.
1097        *
1098        *@param id  the id of the frame to get data from
1099        *@return    the data contained in the frame
1100        */
1101        public byte[] getFrameDataBytes(String id) {
1102            byte[] b = new byte[0];
1103    
1104            if (allow(ID3V2)) {
1105                b = id3v2.getFrameData(id);
1106            }
1107    
1108            return b;
1109        }
1110    
1111    
1112        /**
1113        * Returns the currently set tagging type.
1114        *
1115        *@return   the current tagging type
1116        */
1117        public int getTaggingType() {
1118            return tagType;
1119        }
1120    
1121    
1122        /**
1123        * Set the tagging type. This determines what type of id3 tags are
1124        * read/written. This should be one of the constants defined by this class:
1125        * BOTH_TAGS, ID3V1_ONLY, ID3V2_ONLY, EXISTING_TAGS_ONLY, NO_TAGS
1126        *
1127        *@param newType  the new tagging type
1128        */
1129        public void setTaggingType(int newType) {
1130            tagType = newType;
1131        }
1132    
1133    
1134        /**
1135        * Return the current size of the tag(s) in bytes. What size is returned
1136        * depends on the type of tagging specified in the constructor.
1137        *
1138        *@return   the size of the tag(s) in bytes
1139        */
1140        public int getTagSize() {
1141            return getTagSize(tagType);
1142        }
1143    
1144        public long getAudioOffset(){
1145            return head.getLocation();
1146        }
1147    
1148        /**
1149        * Returns the current size of the tag(s) in bytes. What size is returned
1150        * depends on the type of tagging specified. The possible values for the type
1151        * is: BOTH_TAGS, ID3V1_ONLY, ID3V2_ONLY, EXISTING_TAGS_ONLY, NO_TAGS. If
1152        * BOTH_TAGS or EXISTING_TAGS_ONLY is used and both tags exist, then the size
1153        * of the two tags added will be returned.
1154        *
1155        *@param type  the tagging type
1156        *@return      the size of the tag(s) in bytes
1157        */
1158        public int getTagSize(int type) {
1159            int size = 0;
1160    
1161            if (allow(ID3V1, type)) {
1162                size += id3v1.getSize();
1163            }
1164            if (allow(ID3V2, type)) {
1165                // Extra check because size will return at least 10
1166                // because of header, even if the tag doesn't exist
1167                if (id3v2.tagExists()) {
1168                    size += id3v2.getTotalWrittenTagSize();
1169                }
1170            }
1171    
1172            return size;
1173        }
1174    
1175    
1176        /**
1177        * Checks whether it is ok to read or write from the tag version specified
1178        * based on the tagType passed to the constructor. The tagVersion parameter
1179        * should be either ID3V1 or ID3V2.
1180        *
1181        *@param tagVersion  the id3 version to check
1182        *@return            true if it is ok to proceed with the read/write
1183        */
1184        private boolean allow(int tagVersion) {
1185            return this.allow(tagVersion, tagType);
1186        }
1187    
1188    
1189        /**
1190        * Checks whether it is ok to read or write from the tag version specified
1191        * based on the tagType passed to the method. The tagVersion parameter should
1192        * be either ID3V1 or ID3V2. The type parameter should be either BOTH_TAGS,
1193        * ID3V1_ONLY, ID3V2_ONLY, NO_TAGS, or EXISTING_TAGS_ONLY.
1194        *
1195        *@param tagVersion  the id3 version to check
1196        *@param type        specifies what conditions the tags are allowed to proceed
1197        *@return            true if it is ok to proceed with the read/write
1198        */
1199        private boolean allow(int tagVersion, int type) {
1200            boolean retval = false;
1201    
1202            if (tagVersion == ID3V1) {
1203                retval = ((type == EXISTING_TAGS_ONLY) && id3v1.tagExists())
1204                || (type == ID3V1_ONLY) || (type == BOTH_TAGS);
1205            } else if (tagVersion == ID3V2) {
1206                retval = ((type == EXISTING_TAGS_ONLY) && id3v2.tagExists())
1207                || (type == ID3V2_ONLY) || (type == BOTH_TAGS);
1208            }
1209    
1210            return retval;
1211        }
1212    
1213    
1214        /**
1215        * Return a string representation of this object. This includes all the
1216        * information contained within the mpeg header and id3 tags as well as
1217        * certain file attributes.
1218        *
1219        *@return   a string representation of this object
1220        */
1221        public String toString() {
1222            return "MP3File" + "\nPath:\t\t\t\t" + mp3.getAbsolutePath()
1223            + "\nFileSize:\t\t\t" + mp3.length()
1224            + " bytes\nPlayingTime:\t\t\t" + getPlayingTimeString() + "\n"
1225            + head + "\n" + id3v1 + "\n" +  id3v2;
1226        }
1227    
1228    
1229        /**
1230        * Returns true if the object o is equal to this MP3File. This is true if the
1231        * mp3s share the same path.
1232        *
1233        *@param o  the object to compare
1234        *@return   true if the object o is equal to this MP3File
1235        */
1236        public boolean equals(Object o) {
1237            boolean equal = false;
1238    
1239            if (o instanceof MP3File) {
1240                equal = this.getPath().equals(((MP3File) o).getPath());
1241            }
1242    
1243            return equal;
1244        }
1245    
1246    
1247    
1248        /**
1249        * Compare this MP3File to the specified object. This comparson does a simple
1250        * compare of the two paths. If the other object is not an mp3, compareTo will
1251        * always return a positive number.
1252        *
1253        *@param o  the object to compare to this one
1254        *@return   a positive number if this object is greater than the other, 0 if
1255        *      the object are equal, or a negative number if this object is less than
1256        *      the other
1257        */
1258        public int compareTo(Object o) {
1259            int cmp = 1;
1260    
1261            if (o instanceof MP3File) {
1262                cmp = this.getPath().compareTo(((MP3File) o).getPath());
1263            }
1264    
1265            return cmp;
1266        }
1267    
1268        public byte[] getHash(String algorithm) throws IOException, NoSuchAlgorithmException{
1269            MessageDigest md = MessageDigest.getInstance(algorithm);
1270            if (mp3 == null ||! mp3.exists()){
1271                return null;
1272            } else {
1273                long n = mp3.length();
1274                byte[] bytes = new byte[(int) n];
1275                FileInputStream fis = new FileInputStream(mp3);
1276                int bytesread = fis.read(bytes);
1277                fis.close();
1278                assert bytesread == n: ""+bytesread+";"+n;
1279                return md.digest(bytes);
1280            }
1281        }
1282    
1283        public boolean hashEquals(String algorithm, MP3File f) throws IOException, NoSuchAlgorithmException{
1284            return this.getHash(algorithm).equals(f.getHash(algorithm));
1285        }
1286    
1287        public ID3v2Tag getV2Tag(){
1288            return id3v2;
1289        }
1290    
1291    }
1292