001    package helliker.id3;
002    // CHANGED BY MORITZ RINGLER (mr) for mp3dings
003    // $Id: ID3v2Tag.java,v 1.16 2006/08/12 12:38:37 ringler Exp $
004    import java.io.File;
005    import java.io.FileInputStream;
006    import java.io.FileOutputStream;
007    import java.io.IOException;
008    import java.io.InputStream;
009    import java.io.RandomAccessFile;
010    import java.nio.ByteBuffer;
011    import java.nio.channels.FileChannel;
012    import java.nio.channels.FileLock;
013    import java.nio.charset.Charset;
014    import java.nio.charset.CharsetEncoder;
015    import java.nio.charset.CharacterCodingException;
016    import java.nio.CharBuffer;
017    import java.util.Arrays;
018    import java.util.logging.Level;
019    import java.util.logging.Logger;
020    
021    
022    /*
023       Copyright (C) 2001,2002 Jonathan Hilliker
024       with modifications
025       Copyright (C) 2007-2008 Moritz Ringler
026       This library is free software; you can redistribute it and/or
027       modify it under the terms of the GNU Lesser General Public
028       License as published by the Free Software Foundation; either
029       version 2.1 of the License, or (at your option) any later version.
030       This library is distributed in the hope that it will be useful,
031       but WITHOUT ANY WARRANTY; without even the implied warranty of
032       MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
033       Lesser General Public License for more details.
034       You should have received a copy of the GNU Lesser General Public
035       License along with this library; if not, write to the Free Software
036       Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
037      */
038    /**
039     * This class reads and writes id3v2 tags from a file.<br />
040     * */
041    public class ID3v2Tag extends AbstractID3v2Tag {
042      /* Only the I/O-related parts of ID3v2Tag are implemented here,
043         the data manipulation stuff is implemented in AbstractID3v2Tag. */
044    
045      public static class CorruptHeaderException extends IOException{
046          private final File file;
047          private final long audioOffset;
048          private final long tagLength;
049    
050          public CorruptHeaderException(File f, long off, long taglen){
051              file = f;
052              audioOffset = off;
053              tagLength = taglen;
054          }
055    
056          public long getTagLength(){
057              return tagLength;
058          }
059    
060          public long getAudioOffset(){
061              return audioOffset;
062          }
063    
064          public File getFile(){
065              return file;
066          }
067    
068          public String getMessage(){
069              StringBuffer sb = new StringBuffer("Corrupt header in file ");
070              sb.append(file);
071              sb.append(". Audio data begins at offset ");
072              sb.append(audioOffset);
073              sb.append(" (0x");
074              sb.append(Long.toHexString(audioOffset));
075              sb.append("), ");
076              sb.append(" ID3v2 tag ends at offset ");
077              sb.append(tagLength);
078              sb.append(" (0x").append(Long.toHexString(tagLength)).append(").");
079              return sb.toString();
080          }
081      }
082    
083    
084      // mp3Ext writes padding (wrongfully) as "MP3ext V...."
085      /**
086       * MP3 Ext badid
087       */
088      private static final String MP3EXT_BADID = "MP3e";
089    
090      // Used to calculate padding change
091      /**
092       * The maximum allowed padding size in bytes.
093       */
094      private static final int NEWTAG_LIMIT = 160000;
095    
096      /**
097       * The File.
098       */
099      private File mp3 = null;
100    
101      /**
102       * The tag header.
103       */
104      private ID3v2Header head = null;
105    
106      /**
107       * The extended tag header.
108       */
109      private ID3v2ExtendedHeader ext_head = null;
110    
111      /**
112       * The tag footer.
113       */
114      private ID3v2Footer foot = null;
115    
116      /** total size of the id3v2 tag in the file */
117      private int totalWrittenTagSize;
118    
119      /**
120       * size of the in-file padding
121       */
122      private int writtenPadding;
123    
124      /**
125       * whether the ID3v2 tag exists in the file
126       */
127      private boolean exists;
128    
129      /**
130       * Create an id3v2 tag bound to the file provided as a parameter. If a tag
131       * exists in the file already, then all the information in the tag will be
132       * extracted. If a tag doesn't exist, then this is the file that will be
133       * written to when the writeTag method is called.
134       *
135       *@param mp3                        the file to write/read the the tag
136       *      information to/from
137       *@exception FileNotFoundException  if an error occurs
138       *@exception IOException            if an error occurs
139       *@exception ID3v2FormatException   if an exisiting id3v2 tag isn't correct
140       */
141      public ID3v2Tag(File mp3)
142         throws IOException, ID3v2FormatException {
143        this.mp3 = mp3;
144        //this.mpegOffset = mpegOffset;
145    
146        head = new ID3v2Header(mp3);
147        exists = head.headerExists();
148    
149        if (exists) {
150          if (head.getExtendedHeader()) {
151            ext_head = new ID3v2ExtendedHeader(mp3);
152          }
153          if (head.getFooter()) {
154            foot = new ID3v2Footer(mp3,
155              head.getTagSize() + head.getHeaderSize());
156          }
157    
158          RandomAccessFile in = null;
159    
160          try {
161            in = new RandomAccessFile(mp3, "r");
162    
163            // For now only support id3v2.3.0 or greater
164            if (head.getMajorVersion() >= 3) {
165              parseFrames(in);
166            }
167          } finally {
168            if (in != null) {
169              in.close();
170            }
171          }
172    
173          /* the value returned by head.getTagSize is initially read from
174          *  the tag header.
175          * <blockquote>
176          * The ID3v2 tag size is the size of the complete tag after
177          * unsychronisation, including padding, excluding the header but not
178          * excluding the extended header (total tag size - 10). Only 28 bits
179          * (representing up to 256MB) are used in the size description to avoid
180          * the introduction of 'false syncsignals'.
181          * </blockquote>
182          */
183          int mutableTagSize = head.getTagSize();
184          if(mutableTagSize > 1000000){
185              throw new ID3v2FormatException("Tag too large.");
186          }
187    
188          totalWrittenTagSize = mutableTagSize;
189          if(exists){
190              totalWrittenTagSize += head.getHeaderSize();
191              if (head.getFooter()) {
192                  totalWrittenTagSize += foot.getFooterSize();
193              }
194          }
195          // Check to validate tag size taken out because MusicMatch
196          // has some bugs that causes the check to fail
197        }
198      }
199    
200    
201      /**
202       * Read the frames from the file and create ID3v2Frame objects from the data
203       * found. Should only be called from the constructor.
204       *
205       *@param raf                       the open file to read from
206       *@exception IOException           if an error occurs
207       *@exception ID3v2FormatException  if an error occurs
208       */
209      private void parseFrames(RandomAccessFile raf)
210         throws IOException, ID3v2FormatException {
211    
212        int offset = head.getHeaderSize();
213        // Actually length of frames + padding
214        int framesLength = head.getTagSize();
215        int bytesRead = 0;
216        int curLength = 0;
217        ID3v2Frame frame = null;
218        String id = null;
219        byte[] buf;
220        byte[] flags;
221        boolean done = false;
222    
223        if (head.getExtendedHeader()) {
224          framesLength -= ext_head.getSize();
225          offset += ext_head.getSize();
226        }
227    
228        raf.seek(offset);
229    
230        while ((bytesRead < framesLength) && !done) {
231          buf = new byte[4];
232          bytesRead += raf.read(buf);
233          id = new String(buf);
234    
235          if (!(id.equals(MP3EXT_BADID) || id.indexOf(0) != -1)) {
236            bytesRead += 4;
237            curLength = raf.readInt();
238    
239            // Added by Reed
240            if (curLength < 0 || curLength > framesLength - bytesRead) {
241              throw new ID3v2FormatException("ID3v2Tag.parseFrames: "
242                                             + "Invalid frame size");
243            }
244    
245            flags = new byte[2];
246            bytesRead += raf.read(flags);
247            buf = new byte[curLength];
248            bytesRead += raf.read(buf);
249            frame = new ID3v2Frame(id, flags, buf);
250    
251            /* The following line violates the specification in cases where
252            * multiple frames of the same kind are allowed.
253            * Of multiple frames with the same ID only the last one in the tag
254            * will be preserved
255            */
256            //frames.put(id, frame);
257            /* Here we preserve all frames that we encounter, but we will
258             * modify only the first frame of a given id, since this is the one
259             * that we will find at its proper name in frames.
260             */
261            if(frames.containsKey(id)){
262                int i = 0;
263                String key = id + (i++);
264                while(frames.containsKey(key)){
265                    key = id + (i++);
266                }
267                frames.put(key, frame);
268            } else {
269                frames.put(id, frame);
270            }
271    
272          } else {
273            // We've hit padding so stop reading
274            done = true;
275            bytesRead -= buf.length;
276          }
277        }
278    
279        raf.seek(offset + bytesRead);
280        byte[] buff  = new byte[0x4000];
281        int numbytes = 0;
282        int pad = 0;
283        READLOOP: while(numbytes != -1){
284            numbytes = raf.read(buff);
285            for(int i=0; i<numbytes; i++){
286                if(buff[i] == 0){
287                    pad++;
288                } else {
289                    break READLOOP;
290                }
291            }
292        }
293        writtenPadding = pad;
294        logger.fine(mp3.getName() + " ID3tag\n"+
295                "offset: " + offset +
296                "\nbytesread: " + bytesRead +
297                "\nframeslength: " + framesLength +
298                "\npadding: " + writtenPadding);
299      }
300    
301      public void writeTag() throws IOException{
302          writeTag(false);
303      }
304    
305      /**
306       * Saves all the information in the tag to the file passed to the constructor.
307       * If a tag doesn't exist, a tag is prepended to the file. If the new tag size
308       * is less than the old size + padding, then the old tag and part of the
309       * old padding will be overwritten. Otherwise, a new tag will be
310       * prepended to the file.<br>
311       * This method fixes incorrect header size information where this can
312       * be done without any risk of data loss.
313       *
314       *@exception FileNotFoundException  if an error occurs
315       *@exception IOException            if an error occurs
316       */
317      public void writeTag(boolean forceMpegOffset) throws IOException {
318          /* test whether mp3 is writable */
319          if(!mp3.canWrite()){
320              throw new IOException("Cannot modify mp3 file.");
321          }
322    
323          /* calculate the size of the complete written tag */
324          int minTotalSize = minimumTotalSize();
325          int writtenTagLength = getWrittenTagLength(forceMpegOffset);
326          int pad = calculatePadding(minTotalSize, writtenTagLength);
327          int totalSize = minTotalSize + pad;
328    
329          /* Creates the new tag in-memory.*/
330          byte[] id3 = getBytes(totalSize);
331    
332          if (totalSize <= writtenTagLength) {// the file does not need to change size
333              logger.fine(mp3.getName() + ": changing id3 tag in place.");
334              writeTagSimple(id3);
335          } else { //the tag needs to grow
336              logger.fine(mp3.getName() + ": writing new file with new tag.");
337              writeTagTempFile(id3, writtenTagLength);
338          }
339          /* update the in-file tag and padding sizes. */
340          writtenPadding = pad;
341          totalWrittenTagSize = totalSize;
342          exists = true;
343      }
344    
345      private int calculatePadding(int minTotalSize, int writtenTagLength){
346          int pad = writtenTagLength - minTotalSize;
347          if (pad < 0){
348              int newTagSize = (writtenTagLength <= 0)
349                    ? 512
350                    : 2 * writtenTagLength;
351              for (; newTagSize < minTotalSize; newTagSize *= 2);
352              if (newTagSize <= NEWTAG_LIMIT) {
353                  pad = newTagSize - minTotalSize;
354              } else {
355                  // Gee if it's over the limit this tag is pretty big,
356                  // so screw padding altogether
357                  pad = 0;
358              }
359          }
360          return pad;
361      }
362    
363      /** Compares the size of the complete written tag
364      *  to the return value of {@link MPEGAudioFrameHeader#findOffset}.
365      *  If both numbers are equal (as they should be) this method will return their
366      *  common value. Otherwise if useMpegOffset is true the audio data offset
367      *  will be used, if it is false a CorruptHeaderException will be thrown.
368      *
369      * @return the total written tag size otherwise
370      * @see writeTag
371      * @see removeTag
372      **/
373      private int getWrittenTagLength(boolean useMpegOffset) throws IOException{
374          int result = totalWrittenTagSize;
375    
376          //find beginning of audio data
377          int mpegOffset = 0;
378          try{
379            long tmp = (new MPEGAudioFrameHeader(mp3, 2 * totalWrittenTagSize + 10)).getLocation();
380            if(tmp >= Integer.MAX_VALUE){
381                throw new IOException("No MPEG audio frame header found in first " +
382                    Integer.MAX_VALUE + " bytes.");
383            }
384            mpegOffset = (int) tmp;
385          } catch (IOException iox){
386              throw iox;
387          } catch (RuntimeException rx){
388              throw rx;
389          } catch (Exception ex){
390              IOException iox = new IOException(ex.getMessage());
391              iox.initCause(iox);
392              throw iox;
393          }
394    
395          //see if beginning of audio data is identical to tag length
396          if(mpegOffset != totalWrittenTagSize){
397              if(useMpegOffset){
398                  logger.info(
399                        mp3.getName() +
400                        ": Audio offset does not equal ID3v2 tag size:\n" +
401                        "\tAudio offset:" + mpegOffset +
402                        " (0x" + Long.toHexString(mpegOffset) + ")\n" +
403                        "\tTotal written tag size: " + totalWrittenTagSize +
404                        " (0x" + Long.toHexString(totalWrittenTagSize) + ")\n" +
405                        "Using audio offset (forced).");
406                  result = mpegOffset;
407              } else {
408                  throw new CorruptHeaderException(mp3, mpegOffset, totalWrittenTagSize);
409              }
410          }
411          return result;
412      }
413    
414      /* Checks whether bytes between start and end are all null. */
415      private boolean isPadding(long start, long end) throws IOException{
416          int length = (int) (end - start);
417          boolean isPadding = true;
418          InputStream in = new FileInputStream(mp3);
419          try{
420              byte[] b = new byte[length];
421              isPadding = (in.skip(start) == start) &&
422                          (in.available() >= length) &&
423                          (in.read(b,0,length) == length);
424              for(int i=0; i<length && isPadding; i++){
425                  isPadding = (b[i] == 0);
426              }
427          } finally {
428              in.close();
429          }
430          return isPadding;
431      }
432    
433      private void writeTagSimple(byte[] id3) throws IOException {
434          RandomAccessFile raf = null;
435          try {
436              raf = new RandomAccessFile(mp3, "rw");
437              raf.seek(0);
438              raf.write(id3);
439          } finally { //cleanup
440              /* close random access file */
441              if (raf != null) {
442                  raf.close();
443              }
444          }
445      }
446    
447      private void writeTagTempFile(byte[] id3, int tagEnd) throws IOException {
448          FileChannel source = null, target = null;
449          FileOutputStream tfos = null;
450          FileLock targetLock = null;
451          File tf = null;
452          try {
453              /* Create a temporary file to write to, use efficient NIO API */
454              String tmpfilename = mp3.getName();
455              tmpfilename = tmpfilename.replaceFirst("\\.mp3$","");
456              if(tmpfilename.length() < 3){
457                  tmpfilename += "mp3dings";
458              }
459              tf = File.createTempFile(tmpfilename,".tmp.mp3",mp3.getAbsoluteFile().getParentFile());
460              tfos = new FileOutputStream(tf);
461              target = tfos.getChannel();
462              targetLock = target.tryLock();
463              if(targetLock == null){
464                  throw new IOException("Cannot lock temporary target file.");
465              }
466              /* Create a file channel to read from */
467              source = new FileInputStream(mp3).getChannel();
468              /* write the new tag to the temp target*/
469              target.write(ByteBuffer.wrap(id3));
470              /* copy the audio portion of the mp3 to the temp target */
471              source.transferTo(tagEnd, source.size() - tagEnd, target);
472          } catch (IOException x){
473              /* if an error occurred delete the temp file. */
474              if(tf != null && tf.exists()){
475                  /* release file locks */
476                  if(targetLock != null){
477                      targetLock.release();
478                  }
479                  /* close target file output stream and channel */
480                  if (tfos != null){
481                      tfos.close();
482                  }
483                  tf.delete();
484                  tf = null;
485              }
486              throw x; //finally-block will be executed anyways
487          } finally { //cleanup
488              /* release file locks */
489              if(targetLock != null){
490                  targetLock.release();
491              }
492              /* close target file output stream and channel */
493              if (tfos != null){
494                  tfos.close();
495              }
496              /* close source file channel */
497              if (source != null){
498                  source.close();
499              }
500          }
501          /* replace the source mp3 with the succesfully completed target file */
502          String message;
503          if(tf == null){
504              message = "Could not tag file "+mp3.getName();
505              logger.severe(message);
506               throw new IOException(message);
507          } else if (!tf.exists()){
508              message = "Temporary file has disappeared: "+tf.getName();
509              logger.severe(message);
510               throw new IOException(message);
511          } else if (!mp3.delete()){
512              message = "Cannot overwrite file "+mp3.getName();
513              logger.severe(message);
514              tf.delete();
515              throw new IOException(message);
516          } else if (!tf.renameTo(mp3)){
517              message = "Cannot rename temporary mp3 file " + tf.getName() +
518                        "->" + mp3.getName();
519              logger.severe(message);
520              throw new IOException(message);
521          }
522      }
523    
524      /**
525       * Remove an existing id3v2 tag from the file passed to the constructor.
526       *
527       *@exception FileNotFoundException  if an error occurs
528       *@exception IOException            if an error occurs
529       */
530      public void removeTag() throws IOException {
531        removeTag(false);
532      }
533    
534      public void removeTag(boolean forceMpegOffset) throws IOException {
535        if (exists || forceMpegOffset) {
536            int offset = getWrittenTagLength(forceMpegOffset);
537            writeTagTempFile(new byte[]{},offset);
538        }
539        exists = false;
540        totalWrittenTagSize = 0;
541        writtenPadding = 0;
542      }
543    
544      /**
545       * Return a binary representation of this object to be written to a file. This
546       * is in the format of the id3v2 specifications. This includes the header,
547       * extended header (if it exists), the frames, padding (if it exists), and a
548       * footer (if it exists).
549       *
550       *@return   a binary representation of this id3v2 tag
551       */
552      private byte[] getBytes(int totalSize) {
553        byte[] b = new byte[totalSize];
554        int bytesCopied = 0;
555    
556        /* update header size information */
557        int mutableTagSize = totalSize;
558        mutableTagSize -= head.getHeaderSize();
559        if (head.getFooter()) {
560           mutableTagSize -= foot.getFooterSize();
561        }
562        head.setTagSize(mutableTagSize);
563    
564        /* add header */
565        int length = head.getHeaderSize();
566        System.arraycopy(head.getBytes(), 0, b, bytesCopied, length);
567        bytesCopied += length;
568        assert bytesCopied == 10; //header size should always equal 10
569    
570        /* add extended header if it exists */
571        if (head.getExtendedHeader()) {
572          length = ext_head.getSize();
573          System.arraycopy(ext_head.getBytes(), 0, b, bytesCopied, length);
574          bytesCopied += length;
575        }
576    
577        /* add the actual data frames */
578        length = frames.getLength();
579        System.arraycopy(frames.getBytes(), 0, b, bytesCopied, length);
580        bytesCopied += length;
581    
582        /* add padding */
583        // Bytes should all be zero's by default
584        int pad = b.length - bytesCopied;
585        if (head.getFooter()) {
586            pad -= foot.getFooterSize();
587        }
588        assert (pad >= 0);
589        Arrays.fill(b, bytesCopied, bytesCopied + pad, (byte) 0);
590        bytesCopied += pad;
591    
592        /* add footer if it exists */
593        if (head.getFooter()) {
594          length = foot.getFooterSize();
595          System.arraycopy(foot.getBytes(), 0, b, bytesCopied, length);
596          bytesCopied += length;
597        }
598        assert (bytesCopied == b.length);
599    
600        return b;
601      }
602    
603      /**
604       * Returns true if an id3v2 tag exists in the file that was passed to the
605       * constructor and false otherwise
606       *
607       *@return   true if an id3v2 tag exists in the file passed to the ctor
608       */
609      public boolean tagExists() {
610        return exists;
611      }
612    
613      private int minimumMutableSize(){
614          int minsize = frames.getLength();
615          if (head.getExtendedHeader()) {
616              minsize += ext_head.getSize();
617          }
618          return minsize;
619      }
620    
621      private int minimumTotalSize(){
622          int minSize = minimumMutableSize();
623          if(exists){
624              minSize += head.getHeaderSize();
625              if (head.getFooter()) {
626                  minSize += foot.getFooterSize();
627              }
628          }
629          return minSize;
630      }
631    
632      public int getTotalWrittenTagSize(){
633          return totalWrittenTagSize;
634      }
635    
636    
637      /**
638       * Return a string representation of this object. This includes all data
639       * contained in all parts of this tag.
640       *
641       *@return   a string representation of this object
642       */
643      public String toString() {
644        String str = head.toString();
645    
646        str += "\nTotalWrittenTagSize:\t\t\t" + totalWrittenTagSize + " bytes";
647    
648        if (head.getExtendedHeader()) {
649          str += "\n" + ext_head.toString();
650        }
651    
652        str += "\n" + frames.toString();
653    
654        if (head.getFooter()) {
655          str += foot.toString();
656        }
657    
658        return str;
659      }
660    
661    
662      /**
663       * Copies information from the ID3Tag parameter and inserts it into this tag.
664       * Previous data will be overwritten. [NOT IMPLEMENTED]
665       *
666       *@param tag  the tag to copy from
667       */
668      public void copyFrom(ID3Tag tag) {
669          throw new Error("Not implemented");
670        // Not implemented yet
671      }
672    
673    }
674