001    package helliker.id3;
002    
003    import java.io.*;
004    
005    /*
006     * Copyright (C) 2001,2002 Jonathan Hilliker
007     *
008     * This library is free software; you can redistribute it and/or
009     * modify it under the terms of the GNU Lesser General Public
010     * License as published by the Free Software Foundation; either
011     * version 2.1 of the License, or (at your option) any later version.
012     *
013     * This library is distributed in the hope that it will be useful,
014     * but WITHOUT ANY WARRANTY; without even the implied warranty of
015     * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
016     * Lesser General Public License for more details.
017     *
018     * You should have received a copy of the GNU Lesser General Public
019     * License along with this library; if not, write to the Free Software
020     * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
021     */
022    /** This class reads and writes id3v1.1 tags from/to files.
023     */
024    
025    public class ID3v1Tag implements ID3Tag {
026    
027        /** The size of an ID3v1 Tag
028         */
029        private static final int TAG_SIZE = 128;
030        /** The size of the Title
031         */
032        private static final int TITLE_SIZE = 30;
033        /** The size of the Artist
034         */
035        private static final int ARTIST_SIZE = 30;
036        /** The size of the Album
037         */
038        private static final int ALBUM_SIZE = 30;
039        /** The size of the Year
040         */
041        private static final int YEAR_SIZE = 4;
042        /** The size of the Comment
043         */
044        private static final int COMMENT_SIZE = 28;
045        /** The Track location
046         */
047        private static final int TRACK_LOCATION = 126;
048        /** The Genre location
049         */
050        private static final int GENRE_LOCATION = 127;
051        /** Maximum Number of genres ?
052         */
053        private static final int MAX_GENRE = 255;
054        /** Maximum Tracknumber ?
055         */
056        private static final int MAX_TRACK = 255;
057        /** Tag Start of ID3v1
058         */
059        private static final String TAG_START = "TAG";
060    
061        /** The MP3 File
062         */
063        private File mp3 = null;
064        /** Gives Information if header Exists ?
065         */
066        private boolean headerExists = false;
067        /** The title
068         */
069        private String title = null;
070        /** The artist
071         */
072        private String artist = null;
073        /** The album
074         */
075        private String album = null;
076        /** The year
077         */
078        private String year = null;
079        /** The Comment
080         */
081        private String comment = null;
082        /** The Genre
083         */
084        private int genre;
085        /** The Track Number
086         */
087        private int track;
088    
089        /** Create an id3v1tag from the file specified.  If the file contains a
090         * tag, the information is automatically extracted.  Supports only id3v1.1
091         * directly but id3v1.0 tags will most likely work correctly too.
092         *
093         * @exception FileNotFoundException if an error occurs
094         * @exception IOException if an error occurs
095         * @param mp3 the file to read/write the tag to
096         */
097        public ID3v1Tag(File mp3) throws IOException {
098      this.mp3 = mp3;
099    
100      title = "";
101      artist = "";
102      album = "";
103      year = "";
104      comment = "";
105      genre = -1;
106      track = -1;
107    
108      RandomAccessFile in = null;
109    
110      try {
111          in = new RandomAccessFile(mp3, "r");
112          headerExists = checkHeader(in);
113    
114          if (headerExists) {
115        readTag (in);
116          }
117      } finally {
118          if (in != null) {
119        in.close();
120          }
121      }
122        }
123    
124        /** Checks whether a header for the id3 tag exists yet
125         *
126         * @exception FileNotFoundException if an error occurs
127         * @exception IOException if an error occurs
128         * @param raf the open file to read from
129         * @return true if a tag is found
130         */
131        private boolean checkHeader(RandomAccessFile raf)
132      throws IOException {
133    
134      boolean retval = false;
135    
136      if (raf.length() > TAG_SIZE) {
137          raf.seek(raf.length() - TAG_SIZE);
138          byte[] buf = new byte[3];
139    
140          raf.readFully(buf);
141          String result = new String(buf, "ISO-8859-1");
142          retval = result.equals(TAG_START);
143      }
144    
145      return retval;
146        }
147    
148        /** Reads the data from the id3v1 tag
149         *
150         * @exception FileNotFoundException if an error occurs
151         * @exception IOException if an error occurs
152         * @param raf the open file to read from
153         */
154        private void readTag(RandomAccessFile raf)
155      throws IOException {
156    
157      raf.seek(raf.length() - TAG_SIZE);
158      byte[] buf = new byte[TAG_SIZE];
159      raf.readFully(buf);
160      String tag = new String(buf, "ISO-8859-1");
161      assert(tag.length() == TAG_SIZE);
162      int start = TAG_START.length();
163      title = chopSubstring(tag, start, start += TITLE_SIZE);
164      artist = chopSubstring(tag, start, start += ARTIST_SIZE);
165      album = chopSubstring(tag, start, start += ALBUM_SIZE);
166      year = chopSubstring(tag, start, start += YEAR_SIZE);
167      comment = chopSubstring(tag, start, start += COMMENT_SIZE);
168      track = (int) (buf[TRACK_LOCATION] & 0xff);  //reed - access genre ids > 127
169      genre = (int) (buf[GENRE_LOCATION] & 0xff);
170        }
171    
172        /** Finds the substring of the String parameter but ends the string
173         * with the first null byte encountered.
174         *
175         * @param s the string chop
176         * @param start where to start the string
177         * @param end where to end the string if a null byte isn't found
178         * @return the chopped string
179         */
180        private String chopSubstring(String s, int start, int end) {
181      String str = s.substring(start, end);
182      int loc = str.indexOf('\0');
183    
184      if (loc != -1) {
185          str = str.substring(0, loc);
186      }
187    
188      return str;
189        }
190    
191        /** Writes the information in this tag to the file specified in the
192         * constructor.  If a tag does not exist, one will be created.  If a tag
193         * already exists, it will be overwritten.
194         *
195         * @exception FileNotFoundException if an error occurs
196         * @exception IOException if an error occurs
197         */
198        public void writeTag() throws IOException {
199    
200      RandomAccessFile raf = null;
201    
202      try {
203          raf = new RandomAccessFile(mp3, "rw");
204    
205          if (headerExists) {
206        raf.seek(raf.length() - TAG_SIZE);
207          } else {
208        raf.seek(raf.length());
209          }
210    
211          raf.write(getBytes());
212      } finally {
213          if (raf != null) {
214        raf.close();
215          }
216      }
217    
218      headerExists = true;
219        }
220    
221        /** Returns a binary representation of this id3v1 tag.  It is in the correct
222         * format according to the id3v1.1 specifications.
223         *
224         * @return a binary representation of this id3v1 tag
225         */
226        public byte[] getBytes() {
227      byte[] tag = new byte[TAG_SIZE];
228      int bytesCopied = 0;
229    
230      try{
231      System.arraycopy(TAG_START.getBytes("ISO-8859-1"), 0, tag, bytesCopied ,
232                       TAG_START.length());
233      bytesCopied += TAG_START.length();
234      System.arraycopy(title.getBytes("ISO-8859-1"), 0, tag, bytesCopied, title.length());
235      bytesCopied += TITLE_SIZE;
236      System.arraycopy(artist.getBytes("ISO-8859-1"), 0, tag, bytesCopied, artist.length());
237      bytesCopied += ARTIST_SIZE;
238      System.arraycopy(album.getBytes("ISO-8859-1"), 0, tag, bytesCopied, album.length());
239      bytesCopied += ALBUM_SIZE;
240      System.arraycopy(year.getBytes("ISO-8859-1"), 0, tag, bytesCopied, year.length());
241      bytesCopied += YEAR_SIZE;
242      System.arraycopy(comment.getBytes("ISO-8859-1"), 0, tag, bytesCopied,
243                       comment.length());
244      } catch( UnsupportedEncodingException ex ){
245              // ISO-8859-1 is one of the encodings
246              // that JVMs must support
247              throw new Error(ex);
248      }
249      tag[TRACK_LOCATION] = (byte) track;
250      tag[GENRE_LOCATION] = (byte) genre;
251    
252      return tag;
253        }
254    
255        /** Converts a string to an array of bytes with the length specified
256         *
257         * @exception UnsupportedEncodingException When Encoding not Supported ?
258         * @param str the string to convert
259         * @param length the size of the byte array
260         * @return the array of bytes converted from the string
261         */
262        private byte[] getFieldBytes(String str, int length)
263      throws UnsupportedEncodingException {
264    
265      StringBuffer buf = new StringBuffer(str);
266    
267      for (int i = str.length(); i < length; i++) {
268          buf.append('\0');
269      }
270    
271      return buf.toString().getBytes("ISO-8859-1");
272        }
273    
274        /** Removes the id3v1 tag from the file specified in the constructor
275         *
276         * @exception FileNotFoundException if an error occurs
277         * @exception IOException if an error occurs
278         */
279        public void removeTag() throws IOException {
280      if (headerExists) {
281          RandomAccessFile raf = null;
282          /* Sanity restored by mr */
283          try {
284        raf = new RandomAccessFile(mp3, "rw");
285        raf.setLength(raf.length() - TAG_SIZE);
286          } finally {
287        if (raf != null) {
288            raf.close();
289        }
290          }
291    
292          headerExists = false;
293      }
294        }
295    
296    /** Removes the id3v1 tag from the file specified in the constructor
297         * @param b ignored
298         * @exception FileNotFoundException if an error occurs
299         * @exception IOException if an error occurs
300         */
301        public void removeTag(boolean b) throws IOException {
302            removeTag();
303        }
304    
305        /** Return the genre name based on the ID3/Nullsoft standards.  If the genre
306         * value is not valid, an empty String is returned.
307         *
308         * @return return the genre name or null if the genre value is not valid
309         */
310        public String getGenreString() {
311      return NullsoftID3GenreTable.getGenre(genre);
312        }
313    
314        /** Attempt to set the genre value of this tag from the string specified.
315         * The value returned is based on the ID3/Nullsoft standards.  Returns
316         * true if a match is found in the table and false otherwise.
317         *
318         * @param str the string value of the genre to attempt to set
319         * @return true if a match is found, false otherwise
320         */
321        public boolean setGenreString(String str) {
322      int result = NullsoftID3GenreTable.getGenre(str);
323      boolean retval = false;
324    
325      if (result != -1) {
326          genre = result;
327          retval = true;
328      }
329    
330      return retval;
331        }
332    
333        /** Checks if a tag exists
334         *
335         * @return true if a tag exists
336         */
337        public boolean tagExists() {
338      return headerExists;
339        }
340    
341        /** Return the title field of the tag
342         *
343         * @return the title field of the tag
344         */
345        public String getTitle() {
346      return title.trim();
347        }
348    
349        /** Set the title field of the tag.  The maximum size of the String is 30.
350         * If the size exceeds the maximum size, the String will be truncated.
351         *
352         * @param newTitle the title for the tag
353         */
354        public void setTitle(String newTitle) {
355      if (newTitle.length() > TITLE_SIZE) {
356          title = newTitle.substring(0, TITLE_SIZE);
357      } else {
358          title = newTitle;
359      }
360        }
361    
362        /** Return the artist field of the tag
363         *
364         * @return the artist field of the tag
365         */
366        public String getArtist() {
367      return artist.trim();
368        }
369    
370        /** Set the artist field of the tag.  The maximum size of the String is 30.
371         * If the size exceeds the maximum size, the String will be truncated.
372         *
373         * @param newArtist the artist for the tag
374         */
375        public void setArtist(String newArtist) {
376      if (newArtist.length() > ARTIST_SIZE) {
377          artist = newArtist.substring(0, ARTIST_SIZE);
378      } else {
379          artist = newArtist;
380      }
381        }
382    
383        /** Return the album field of the tag
384         *
385         * @return the album field of the tag
386         */
387        public String getAlbum() {
388      return album.trim();
389        }
390    
391        /** Set the album field of the tag.  The maximum size of the String is 30.
392         * If the size exceeds the maximum size, the String will be truncated.
393         *
394         * @param newAlbum the album for the tag
395         */
396        public void setAlbum(String newAlbum) {
397      if (newAlbum.length() > ALBUM_SIZE) {
398          album = newAlbum.substring(0, ALBUM_SIZE);
399      } else {
400          album = newAlbum;
401      }
402        }
403    
404        /** Return the year field of the tag
405         *
406         * @return the year field of the tag
407         */
408        public String getYear() {
409      return year.trim();
410        }
411    
412        /** Set the year field of the tag.  The maximum size of the String is 4.
413         * If the size exceeds the maximum size, the String will be truncated.
414         *
415         * @param newYear the year for the tag
416         */
417        public void setYear(String newYear) {
418      if (newYear.length() > YEAR_SIZE) {
419          year = newYear.substring(0, YEAR_SIZE);
420      } else {
421          year = newYear;
422      }
423        }
424    
425        /** Return the comment field of the tag
426         *
427         * @return the comment field of the tag
428         */
429        public String getComment() {
430      return comment.trim();
431        }
432    
433        /** Set the comment field of the tag.  The maximum size of the String is 30.
434         * If the size exceeds the maximum size, the String will be truncated.
435         *
436         * @param newComment the comment of the tag
437         */
438        public void setComment(String newComment) {
439      if (newComment.length() > COMMENT_SIZE) {
440          comment = newComment.substring(0, COMMENT_SIZE);
441      } else {
442          comment = newComment;
443      }
444        }
445    
446        /** Return the track field of the tag. This method will return
447         * 0 if the track byte is either 0x00 or 0xFF.
448         *
449         * @return an integer between 0 and 254 (inclusive)
450         */
451        public int getTrack() {
452            return (track == 255)? 0 : track;
453        }
454    
455        /** Set the track field of the tag.  The track number has to be between 0
456         * and 255.  If it is not, nothing will happen.
457         *
458         * @param newTrack the track of the tag
459         */
460        public void setTrack(int newTrack) {
461      if ((newTrack <= MAX_TRACK) && (newTrack >= 0)) {
462          track = newTrack;
463      }
464        }
465    
466        /** Return the genre field of the tag, -1 if tag doesn't exist
467         *
468         * @return the genre field of the tag
469         */
470        public int getGenre() {
471      return genre;
472        }
473    
474        /** Set the genre field of the tag.  This probably should not be greater
475         * than 115, but supports values from 0-255.
476         *
477         * @exception ID3FieldDataException if the value supplie is invalid
478         * @param newGenre the genre of the tag
479         */
480        public void setGenre(int newGenre) throws ID3FieldDataException {
481      if ((newGenre <= MAX_GENRE) && (newGenre >= 0)) {
482          genre = newGenre;
483      } else {
484          throw new ID3FieldDataException(
485                "Invalid genre value.  Must be between 0 and 255.");
486      }
487        }
488    
489        /** Return the size in bytes of the tag.  This returns 128 if the tag exists
490         * and 0 otherwise.
491         *
492         * @return the size of the tag in bytes
493         */
494        public int getSize() {
495      int retval = 0;
496    
497      if (headerExists) {
498          retval = TAG_SIZE;
499      }
500    
501      return retval;
502        }
503    
504        /** Returns a String representation of this object.  Contains all
505         * information within the tag.
506         *
507         * @return a String representation of this object
508         */
509        public String toString() {
510      return "ID3v1.1\nTagSize:\t\t\t" + getSize()
511            + " bytes\nTitle:\t\t\t\t" + getTitle()
512            + "\nArtist:\t\t\t\t"      + getArtist()
513            + "\nAlbum:\t\t\t\t"       + getAlbum()
514            + "\nYear:\t\t\t\t"        + getYear()
515            + "\nComment:\t\t\t"       + getComment()
516            + "\nTrack:\t\t\t\t"       + getTrack()
517            + "\nGenre:\t\t\t\t"       + getGenreString();
518        }
519    
520        /** Copies information from the ID3Tag parameter and inserts it into
521         * this tag.  Previous data will be overwritten. [NOT IMPLEMENTED]
522         *
523         * @param tag the tag to copy from
524         */
525        public void copyFrom(ID3Tag tag) {
526      // Not implemented yet
527        }
528    
529    } // ID3v1Tag
530    
531    
532    
533    
534    
535    
536    
537