001    package helliker.id3;
002    
003    import java.io.RandomAccessFile;
004    import java.io.IOException;
005    import java.io.File;
006    import java.io.FileInputStream;
007    import java.nio.ByteBuffer;
008    import java.nio.channels.FileChannel;
009    import java.util.logging.Level;
010    import java.util.logging.Logger;
011    
012    /*
013    Copyright (C) 2001,2002 Jonathan Hilliker
014    Copyright (C) 2007 Moritz Ringler
015    This library is free software; you can redistribute it and/or
016    modify it under the terms of the GNU Lesser General Public
017    License as published by the Free Software Foundation; either
018    version 2.1 of the License, or (at your option) any later version.
019    This library is distributed in the hope that it will be useful,
020    but WITHOUT ANY WARRANTY; without even the implied warranty of
021    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
022    Lesser General Public License for more details.
023    You should have received a copy of the GNU Lesser General Public
024    License along with this library; if not, write to the Free Software
025    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
026    */
027    /**
028    * This class reads through the file specified and tries to find an mpeg frame.
029    * It then reads data from the header of the first frame encountered. <br/>
030    *
031    * @author    Jonathan Hilliker
032    * @version   1.8
033    */
034    public class MPEGAudioFrameHeader {
035        private static final Logger logger = Logger.getLogger(MPEGAudioFrameHeader.class.getPackage().getName());
036    
037        /** The size of the IO buffer, this will also be the maximum number of bytes
038        read during one recursion of findOffset. **/
039        private final int CHUNK_SIZE = 0x4000;
040    
041        public final static int FREE_FORMAT = -2;
042    
043        public final static int NULL = -1;
044    
045        /**
046        * MPEG Version 2.5
047        */
048        public final static int MPEG_V_25 = 0;
049        /**
050        * MPEG Version 2
051        */
052        public final static int MPEG_V_2 = 2;
053        /**
054        * MPEG Version 1
055        */
056        public final static int MPEG_V_1 = 3;
057        /**
058        * Layer III
059        */
060        public final static int MPEG_L_3 = 1;
061        /**
062        * Layer II
063        */
064        public final static int MPEG_L_2 = 2;
065        /**
066        * Layer I
067        */
068        public final static int MPEG_L_1 = 3;
069        /**
070        * Mono
071        */
072        public final static int MONO_MODE = 3;
073    
074        /**
075        * The string with which a ID3 Tag starts
076        */
077        private static final String TAG_START = "ID3";
078    
079        /**
080        * Header Size
081        */
082        private static final int HEADER_SIZE = 4;
083    
084        /** the number of bytes that findOffset is guaranteed
085        * to read from the mp3 file
086        */
087        private static final int HEADER_BUFFER_SIZE = 500;
088    
089        /**
090        * Maximum Tries for trying to find an MP3 frame
091        */
092        private static final int MAX_TRIES = 9;
093        /**
094        * The MPEG Bitrate Table. -2 means "free bitrate" and -1 means "not allowed".
095        */
096        private static final int[][] bitrateTable = {
097            {FREE_FORMAT, FREE_FORMAT, FREE_FORMAT, FREE_FORMAT, FREE_FORMAT},
098            {32, 32, 32, 32, 8},
099            {64, 48, 40, 48, 16},
100            {96, 56, 48, 56, 24},
101            {128, 64, 56, 64, 32},
102            {160, 80, 64, 80, 40},
103            {192, 96, 80, 96, 48},
104            {224, 112, 96, 112, 56},
105            {256, 128, 112, 128, 64},
106            {288, 160, 128, 144, 80},
107            {320, 192, 160, 160, 96},
108            {352, 224, 192, 176, 112},
109            {384, 256, 224, 192, 128},
110            {416, 320, 256, 224, 144},
111            {448, 384, 320, 256, 160},
112        {NULL, NULL, NULL, NULL, NULL}};
113        /**
114        * The MPEG Sample rate Table
115        */
116        private static final int[][] sampleTable = {
117            {44100, 22050, 11025},
118            {48000, 24000, 12000},
119            {32000, 16000, 8000},
120        {NULL, NULL, NULL}};
121    
122    
123        /**
124        * MPEG Version Lables
125        */
126        private static final String[] versionLabels = {"MPEG Version 2.5", null,
127            "MPEG Version 2.0", "MPEG Version 1.0"};
128        /**
129        * MPEG Layer Lables
130        */
131        private static final String[] layerLabels = {null, "Layer III", "Layer II",
132            "Layer I"};
133        /**
134        * MPEG ChannelLables
135        */
136        private static final String[] channelLabels = {"Stereo", "Joint Stereo (STEREO)",
137            "Dual Channel (STEREO)",
138        "Single Channel (MONO)"};
139        /**
140        * Emphasis Lables
141        */
142        private static final String[] emphasisLabels = {"none", "50/15 ms", null,
143        "CCIT J.17"};
144        /**
145        * MPEG slot lengths
146        */
147        private static final int[] slotLength = {NULL, 1, 1, 4};// in bytes
148    
149        /**
150        * VBR Header
151        */
152        private VBRHeader vbrHeader = null;
153        /**
154        * The MP3 File
155        */
156        private File mp3 = null;
157        /**
158        * The Version
159        */
160        private int version;
161        /**
162        * The Layer
163        */
164        private int layer;
165        /**
166        * The Bitrate
167        */
168        private int bitRate;
169        /**
170        * The free format bitrate as detected from the distance of sync words
171        */
172        private int ffBitRate = NULL;
173        /** Whether a variable bit rate has been detected.*/
174        private boolean vbr = false;
175    
176        private int vbrPlayingTime = NULL;
177        /**
178        * The Samplerate
179        */
180        private int sampleRate;
181        /**
182        * The Channel mode
183        */
184        private int channelMode;
185        /**
186        * Copyright Flag
187        */
188        private boolean copyrighted;
189        /**
190        * CRC Flag
191        */
192        private boolean crced;
193        /**
194        * Original Flag
195        */
196        private boolean original;
197        /**
198        * Private Bit
199        */
200        private boolean privateBit;
201        /**
202        * Emphais
203        */
204        private int emphasis;
205        /**
206        * Header Location in File?
207        */
208        private long location;
209        /**
210        * Padding Flag
211        */
212        private boolean padding;
213    
214        /** Loggging control */
215        private static Level lev = Level.FINE;
216    
217    
218        /**
219        * Create an MPEGAudioFrameHeader from the file specified. Upon creation
220        * information will be read in from the first frame header the object
221        * encounters in the file.
222        *
223        *@param mp3                         the file to read from
224        *@exception NoMPEGFramesException   if the file is not a valid mpeg
225        *@exception FileNotFoundException   if an error occurs
226        *@exception IOException             if an error occurs
227        */
228        public MPEGAudioFrameHeader(File mp3)
229        throws NoMPEGFramesException, IOException{
230            this(mp3, 0);
231        }
232    
233    
234        /**
235        * Create an MPEGAudioFrameHeader from the file specified. Upon creation
236        * information will be read in from the first frame header the object
237        * encounters in the file. The offset tells the object where to start
238        * searching for an MPEG frame. If you know the size of an id3v2 tag attached
239        * to the file and pass it to this ctor, it will take less time to find the
240        * frame.
241        *
242        *@param mp3                         the file to read from
243        *@param minSyncRange                this is the minimum length of the file
244        *                                   that is searched for consecutive
245        *                                   headers
246        *@exception NoMPEGFramesException   if the file is not a valid mpeg
247        *@exception FileNotFoundException   if an error occurs
248        *@exception IOException             if an error occurs
249        */
250        public MPEGAudioFrameHeader(File mp3, int minSyncRange)
251        throws NoMPEGFramesException, IOException
252        {
253    
254            this.mp3 = mp3;
255            location = 0;
256            int sync = (int) Math.min(mp3.length()*3/4, minSyncRange);
257    
258            FileChannel channel = new FileInputStream(mp3).getChannel();
259            ByteBuffer bb = ByteBuffer.allocate(CHUNK_SIZE);
260            try{
261                while(true){
262                    clear();
263                    //look for a candidate Audio Frame Header
264                    channel.position(location);
265                    location = findOffset(bb, channel, 200);
266                    if (location == NULL) {
267                        throw new NoMPEGFramesException(mp3);
268                    }
269                    logger.log(lev,
270                        "Found syncword at " + hex(location));
271    
272                    //parse the header; does not affect bb position
273                    readHeader(bb);
274    
275                    //look for a xing header; does not affect bb position
276                    vbrHeader = new XingVBRHeader(bb, layer, version,
277                            sampleRate, channelMode, mp3.length());
278                    if(vbrHeader.exists()){
279                        logger.log(lev, "Found Xing header.");
280                    } else {
281                        vbrHeader = null;
282                    }
283    
284                    //look for a VBRI header; does not affect bb position
285                    if(vbrHeader == null){
286                        vbrHeader = new VBRIHeader(bb, layer, version, sampleRate);
287                        if(vbrHeader.exists()){
288                            logger.log(lev, "Found VBRI header.");
289                        } else {
290                            vbrHeader = null;
291                        }
292                    }
293    
294                    if(vbrHeader != null){
295                        vbr = true;
296                        //we have found a VBR header in this frame so this
297                        //must be the first valid mpeg frame
298                        break;
299                    }
300    
301                    // we test whether we have really found a header by
302                    // looking for consecutive headers/snyc words
303                    channel.position(location);
304                    if(bitRate == FREE_FORMAT){
305                        if(testFreeFormat(channel, bb, sync)){
306                            break;
307                        }
308                    } else {
309                       if(testKnownBitRate(channel, bb, sync)){
310                            break;
311                       }
312                    }
313                    location++;
314                }
315            } finally {
316                channel.close();
317            }
318            logger.log(lev, mp3 + " audio offset is 0x" + Long.toHexString(location).toUpperCase());
319            logger.log(lev, toString());
320        }
321    
322        private boolean testKnownBitRate(FileChannel channel, ByteBuffer bb, int minSyncRange) throws IOException{
323            boolean result = false;
324            long length = getUnpaddedFrameLength(bitRate);
325            logger.log(lev, "known bitrate test with framelength " + length);
326            return sync(channel, bb, minSyncRange, length, false);
327        }
328    
329        /** Tries to find consecutive mpeg audio frame headers. If the mp3 file
330            is a VBR file without header, and minSyncRange is equal to
331            the size of the file, this method will calculate and store
332            the vbr playing time in a new PseudoVBRHeader.
333            @param channel the input file channel positioned at
334                            the beginning of the last header found
335            @param bb an I/O buffer that contains at its position the bytes of
336                            the last header found
337            @param minSyncRange the minimum number of bytes from the file
338                            to use for synchronization
339            @param frameLength the unpadded length of a single frame as determined
340                            from previously found headers
341            @param cbr whether to assume a constant bitrate
342            @return if consecutive mpeg audio frame headers were found
343        **/
344        private boolean sync(FileChannel channel, ByteBuffer bb, int minSyncRange, long frameLength, boolean cbr) throws IOException{
345            boolean result = false;
346            long loc = channel.position();
347            long len = frameLength;
348    
349            long firstloc = loc;
350            int framecount = 1;
351    
352            do{
353                boolean pad = BinaryParser.bitSet(bb.get(bb.position() + 2), 1);
354                long nextLoc = loc + len + (pad? slotLength[layer] : 0);
355                framecount++;
356    
357                //look for another consecutive syncword
358                if(nextLoc > loc && nextLoc < channel.size()){
359                    channel.position(nextLoc);
360                    long nextOffs = findOffset(bb, channel, 0);
361                    result = (nextOffs == nextLoc);
362                    if(result){
363                        loc = nextLoc;
364                        if(!cbr){
365                            byte brbyte = bb.get(bb.position() + 2);
366                            int br = findBitRate(BinaryParser.convertToDecimal(brbyte, 4, 7));
367                            long newlen = getUnpaddedFrameLength(br);
368                            if(newlen != len){
369                                vbr = true;
370                            }
371                            len = newlen;
372                        }
373                    } else {
374                        logger.log(lev, "Expected frame at offset " + hex(nextLoc) +
375                            ((nextOffs < 0)
376                            ? " found none."
377                            : " found one at " + hex(nextOffs)));
378                    }
379                } else {
380                    result = false;
381                }
382            } while(result && loc < minSyncRange);
383    
384            //calculate and store VBR playing time and average bitrate
385            if(vbrHeader == null && minSyncRange == channel.size() && vbr){
386                long numbytes = loc + len - firstloc;
387                if(numbytes < Integer.MAX_VALUE){
388                    vbrHeader = new PseudoVBRHeader(framecount, (int) numbytes,
389                        layer, version, sampleRate);
390                }
391            }
392    
393            return result;
394        }
395    
396        private static String hex(long longval){
397            return "0x" + Long.toHexString(longval).toUpperCase();
398        }
399    
400        private boolean testFreeFormat(FileChannel channel, ByteBuffer bb, int minSyncRange) throws IOException{
401            logger.log(Level.FINER, "free format test");
402            boolean result = false;
403            //Free format: must find the frame length experimentally
404            channel.position(location + 1);
405            long loc2 = findOffset(bb, channel, 0);//maxRecursion = 0 limits detectable framelength to CHUNK_SIZE
406            if(loc2 == NULL){
407                return false;
408            }
409    
410            long length = loc2 - location - (padding? slotLength[layer] : 0);
411            channel.position(loc2);
412            if(sync(channel, bb, minSyncRange, length, true)){
413                result = true;
414                ffBitRate = calculateBitrate(length);
415            }
416            return result;
417        }
418    
419        private void clear(){
420            version = NULL;
421            layer = NULL;
422            bitRate = NULL;
423            sampleRate = NULL;
424            channelMode = NULL;
425            copyrighted = false;
426            crced = false;
427            original = false;
428            emphasis = NULL;
429            padding = false;
430        }
431    
432        /** When this method returns bb.hasRemaining() will be true
433            iff an FF byte was found. In that case the buffer will
434            be positioned at the FF byte.
435          */
436        private static void findFF(ByteBuffer bb){
437            while(bb.hasRemaining()){
438                if((bb.get() & 0xFF) == 0xFF){
439                    bb.position(bb.position() - 1);
440                    return;
441                }
442            }
443        }
444    
445        private boolean testFrameHeader(ByteBuffer bb){
446            boolean result = false;
447            bb.mark(); //mark the position of the ff byte
448            byte test = bb.get(); //the ff byte
449            if ((test & 0xFF) == 0xFF){
450                test = bb.get();
451                // Frame sync and layer version tests
452                if ( BinaryParser.matchPattern(test, "111xxxxx") && //frame sync
453                    !BinaryParser.matchPattern(test, "xxxxx00x") && //valid layer
454                    ( version == NULL || version == BinaryParser.convertToDecimal(test, 3, 4)) &&
455                    ( layer == NULL || layer == BinaryParser.convertToDecimal(test, 1, 2)))
456                {
457                    test = bb.get();
458                    if (!BinaryParser.matchPattern(test, "1111xxxx") && //valid bitrate
459                        !BinaryParser.matchPattern(test, "xxxx11xx") && //valid sampling rate
460                        (bitRate != FREE_FORMAT ||
461                         FREE_FORMAT == findBitRate(BinaryParser.convertToDecimal(test, 4, 7))))
462                    {
463                        test = bb.get();
464                        if (!BinaryParser.matchPattern(test, "xxxxxx10")) //valid emphasis
465                        {
466                            result = true;
467                        }
468                    }
469                }
470            }
471            bb.reset(); //return the buffer position to the ff byte
472            return result;
473        }
474    
475        //private long findOffset(ByteBuffer bb, FileChannel channel) throws IOException{
476          //  return findOffset(bb, channel, Integer.MAX_VALUE);
477        //}
478    
479        /**
480        * Attempts to find the location of the first valid mpeg frame in the file.
481        * If the return value is not NULL the byte buffer will be positioned at the
482        * first header byte and will contain at least HEADER_BUFFER_SIZE bytes
483        * of the input file after that position
484        * (to allow reading the Xing header from it).
485        *
486        *@param channel                     the file to scan
487        *@param bb                          a byte buffer with capacity > HEADER_BUFFER_SIZE
488        *@param maxRecurse                  the maximum number of times this method
489        *                                   is allowed to recurse before it finds a
490        *                                   valid header, this limits the maximum
491                                            number of bytes read from the file to
492                                            maxRecurse * bb.capacity()
493        *@return                            the location of the first mpeg
494        *      frame or NULL if it fails
495        *@exception IOException             if an error occurs
496        * @throws IllegalArgumentException if the bb is too small.
497        */
498        private long findOffset(ByteBuffer bb, FileChannel channel, int maxRecurse) throws IOException{
499            if(bb.capacity() <= HEADER_BUFFER_SIZE ){
500                throw new IllegalArgumentException("Buffer is too small.");
501            }
502            long offs = channel.position();
503    
504            //Fill buffer from file
505            bb.clear();
506            for(int bytesread = 0; bytesread != -1 && bb.hasRemaining();){
507                 bytesread = channel.read(bb);
508            }
509            bb.flip();
510    
511            //We require more than HEADER_BUFFER_SIZE bytes
512            if(bb.remaining() <= HEADER_BUFFER_SIZE) {
513                logger.log(lev, "Reached end of file.");
514                return NULL;
515            }
516    
517            //Look for 0xFF byte
518            findFF(bb);
519    
520            while(bb.remaining() >= HEADER_BUFFER_SIZE){
521                if(testFrameHeader(bb)){
522                    return channel.position() - bb.remaining();
523                }
524                // not a valid header, so look for next FF byte
525                bb.get(); //skip the old FF byte
526                findFF(bb);
527            }
528    
529            if(maxRecurse == 0){
530                logger.log(lev, "Reached maximum recursion level.");
531                return -1;
532            }
533    
534            //Position the channel at the position of the last found FF byte
535            //Since we're here, we have either advanced the buffer position
536            //through findFF or by traversing the loop and calling bb.get().
537            //Therefore bb.remaining() is less than the number of bytes read
538            //from the file and therefore the following call will always advance
539            //the file position compared to the entry of the method.
540            //Thus, we avoid inifinite recursion
541            channel.position(channel.position() - bb.remaining());
542            assert(channel.position() > offs);
543    
544            return findOffset(bb, channel, maxRecurse - 1);
545        }
546    
547    
548        /**
549        * Read in all the information found in the mpeg header.
550        *
551        *@param raf                         the open file to find the frame in
552        *@param location                    the location of the header (found by
553        *      findFrame)
554        */
555        private void readHeader(ByteBuffer bb){
556            bb.mark();
557            byte[] head = new byte[HEADER_SIZE];
558            bb.get(head);
559    
560            version = BinaryParser.convertToDecimal(head[1], 3, 4);
561            layer = BinaryParser.convertToDecimal(head[1], 1, 2);
562            bitRate = findBitRate(BinaryParser.convertToDecimal(head[2], 4, 7));
563            sampleRate = findSampleRate(BinaryParser.convertToDecimal(head[2], 2, 3));
564            padding = BinaryParser.bitSet(head[2], 1);
565            privateBit = BinaryParser.bitSet(head[2], 0);
566            channelMode = BinaryParser.convertToDecimal(head[3], 6, 7);
567            copyrighted = BinaryParser.bitSet(head[3], 3);
568            crced = !BinaryParser.bitSet(head[1], 0);
569            original = BinaryParser.bitSet(head[3], 2);
570            emphasis = BinaryParser.convertToDecimal(head[3], 0, 1);
571            bb.reset();
572    
573    
574        }
575    
576    
577        /**
578        * Based on the bitrate index found in the header, try to find and set the
579        * bitrate from the table.
580        *
581        *@param bitrateIndex  the bitrate index read from the header
582        */
583        private int findBitRate(int bitrateIndex) {
584            int ind = NULL;
585    
586            if (version == MPEG_V_1) {
587                if (layer == MPEG_L_1) {
588                    ind = 0;
589                } else if (layer == MPEG_L_2) {
590                    ind = 1;
591                } else if (layer == MPEG_L_3) {
592                    ind = 2;
593                }
594            } else if ((version == MPEG_V_2) || (version == MPEG_V_25)) {
595                if (layer == MPEG_L_1) {
596                    ind = 3;
597                } else if ((layer == MPEG_L_2) || (layer == MPEG_L_3)) {
598                    ind = 4;
599                }
600            }
601    
602            if ((ind != NULL) && (bitrateIndex >= 0) && (bitrateIndex <= 15)) {
603                return bitrateTable[bitrateIndex][ind];
604            } else {
605                return NULL;
606            }
607        }
608    
609    
610        /**
611        * Based on the sample rate index found in the header, attempt to lookup and
612        * set the sample rate from the table.
613        *
614        *@param sampleIndex  the sample rate index read from the header
615        */
616        private int findSampleRate(int sampleIndex) {
617            int ind = NULL;
618    
619            switch (version) {
620                case MPEG_V_1:
621                ind = 0;
622                break;
623                case MPEG_V_2:
624                ind = 1;
625                break;
626                case MPEG_V_25:
627                ind = 2;
628            }
629    
630            if ((ind != NULL) && (sampleIndex >= 0) && (sampleIndex <= 3)) {
631                return sampleTable[sampleIndex][ind];
632            }
633            return NULL;
634        }
635    
636        private int getUnpaddedFrameLength(int bitrate){
637            if(layer == MPEG_L_1){
638                return 48000 * bitrate/sampleRate;
639            } else {
640                int coeff =
641                    (layer == MPEG_L_3 && version != MPEG_V_1) ? 72000 : 144000;
642                return coeff * bitrate/sampleRate;
643            }
644        }
645    
646        /**
647        * Computes the length of the frame found. This is not necessarily constant
648        * for all frames.
649        * @return   the length of the frame found
650        */
651        public int getFrameLength() {
652            int pad = (padding)? 1 : 0;
653            if(layer == MPEG_L_1){
654                return (12000 * getBitRate()/sampleRate + pad) * 4;
655            } else {
656                int coeff =
657                    (layer == MPEG_L_3 && version != MPEG_V_1) ? 72000 : 144000;
658                return (coeff * getBitRate()/ sampleRate + pad);
659            }
660        }
661    
662        /** Calculates the bibtrate from the length of an unpadded frame. This is
663         * the inverse of the calculation performed by {@link #getFrameLength}.
664         * @param length the length in bytes of an unpadded frame
665         **/
666        public int calculateBitrate(long length){
667            if(layer == MPEG_L_1){
668                return (int) (length * sampleRate/48000);
669            } else {
670                int coeff =
671                    (layer == MPEG_L_3 && version != MPEG_V_1) ? 72000 : 144000;
672                return (int) (length * sampleRate/coeff);
673            }
674        }
675    
676    
677        /**
678        * Return a string representation of this object. Includes all information
679        * read in.
680        *
681        *@return   a string representation of this object
682        */
683        public String toString() {
684            String str = new String();
685    
686            str = getVersion() + " " + getLayer()
687            + "\nBitRate:\t\t\t" + getBitRate()
688            + "kbps\nSampleRate:\t\t\t" + getSampleRate()
689            + "Hz\nChannelMode:\t\t\t" + getChannelMode()
690            + "\nCopyrighted:\t\t\t" + isCopyrighted()
691            + "\nOriginal:\t\t\t" + isOriginal()
692            + "\nCRC:\t\t\t\t" + isProtected()
693            + "\nEmphasis:\t\t\t" + getEmphasis()
694            + "\nOffset:\t\t\t\t" + getLocation()
695            + "\nPrivateBit:\t\t\t" + privateBitSet()
696            + "\nPadding:\t\t\t" + hasPadding()
697            + "\nFrameLength:\t\t\t" + getFrameLength()
698            + "\nVBR:\t\t\t\t" + isVBR();
699            if(!isVBR()){
700                str += "\nNumFrames:\t\t\t\t" + getNumFrames();
701            } else if (vbrHeader != null) {
702                str += "\n" + vbrHeader.toString();
703            }
704    
705            return str;
706        }
707    
708    
709        /**
710        * Return the version of the mpeg in string form. Ex: MPEG Version 1.0
711        *
712        *@return   the version of the mpeg
713        */
714        public String getVersion() {
715            String str = null;
716    
717            if ((version >= 0) && (version < versionLabels.length)) {
718                str = versionLabels[version];
719            }
720    
721            return str;
722        }
723    
724    
725        /**
726        * Return the layer description of the mpeg in string form. Ex: Layer III
727        *
728        *@return   the layer description of the mpeg
729        */
730        public String getLayer() {
731            String str = null;
732    
733            if ((layer >= 0) && (layer < layerLabels.length)) {
734                str = layerLabels[layer];
735            }
736    
737            return str;
738        }
739    
740    
741        /**
742        * Return the channel mode of the mpeg in string form. Ex: Joint Stereo
743        * (STEREO)
744        *
745        *@return   the channel mode of the mpeg
746        */
747        public String getChannelMode() {
748            String str = null;
749    
750            if ((channelMode >= 0) && (channelMode < channelLabels.length)) {
751                str = channelLabels[channelMode];
752            }
753    
754            return str;
755        }
756    
757    
758        /**
759        * Returns the sample rate of the mpeg in Hz
760        *
761        *@return   the sample rate of the mpeg in Hz
762        */
763        public int getSampleRate() {
764            return sampleRate;
765        }
766    
767    
768        /**
769        * Returns true if the audio is copyrighted
770        *
771        *@return   true if the audio is copyrighted
772        */
773        public boolean isCopyrighted() {
774            return copyrighted;
775        }
776    
777    
778        /**
779        * Returns true if this mpeg is protected by CRC
780        *
781        *@return   true if this mpeg is protected by CRC
782        */
783        public boolean isProtected() {
784            return crced;
785        }
786    
787    
788        /**
789        * Returns true if this is the original media
790        *
791        *@return   true if this is the original media
792        */
793        public boolean isOriginal() {
794            return original;
795        }
796    
797    
798        /**
799        * Returns true if this mpeg is encoded in VBR
800        *
801        *@return   if VBR is present
802        */
803        public boolean isVBR() {
804            return vbr;
805        }
806    
807    
808        /**
809        * Returns the emphasis. I don't know what this means, it just does it...
810        *
811        *@return   the emphasis
812        */
813        public String getEmphasis() {
814            String str = null;
815    
816            if ((emphasis >= 0) && (emphasis < emphasisLabels.length)) {
817                str = emphasisLabels[emphasis];
818            }
819    
820            return str;
821        }
822    
823    
824        /**
825        * Returns the offset at which the first mpeg frame was found in the file.
826        *
827        *@return   the offset of the mpeg data
828        */
829        public long getLocation() {
830            return location;
831        }
832    
833    
834        /**
835        * Returns true if the file passed to the constructor is an mp3 (MPEG layer
836        * III).
837        *
838        *@return   true if the file is an mp3
839        */
840        public boolean isMP3() {
841            return (layer == MPEG_L_3);
842        }
843    
844    
845        /**
846        * Returns true if the mpeg frames are padded in this file.
847        *
848        *@return   true if the mpeg frames are padded in this file
849        */
850        public boolean hasPadding() {
851            return padding;
852        }
853    
854    
855        /**
856        * Returns true if the private bit is set.
857        *
858        *@return   true if the private bit is set
859        */
860        public boolean privateBitSet() {
861            return privateBit;
862        }
863    
864    
865        /**
866        * Returns the playing time of a variable bitrate file.
867        * For VBR files with XING or VBRI header,
868        * this method returns the playing time read from the header.
869        * For VBR files without header this method will return NULL or the actual
870        * playing time if a previous call to analyzeVBR() succeeded.
871        *
872        * @return the playing time of this mpeg in seconds or NULL
873        */
874        public int getVBRPlayingTime() {
875            int result = NULL;
876            if(vbrHeader != null){
877                result = vbrHeader.getPlayingTime();
878            }
879            return result;
880        }
881    
882        /** Analyzes a VBR file that does not have a XING of VBRI header.
883            @return true iff the mp3 file is a VBR file without header, had not
884                previously been analyzed successfully, and was successfully
885                analyzed as a result of calling this method.
886        */
887        public boolean analyzeVBR() throws IOException{
888            boolean result = false;
889            if(vbr && vbrHeader == null){
890                logger.log(lev, "Analyzing VBR");
891                FileChannel channel = (new FileInputStream(mp3)).getChannel();
892                try{
893                    channel.position(location);
894                    ByteBuffer bb = ByteBuffer.allocate(HEADER_BUFFER_SIZE + 1);
895                    long offs = findOffset(bb, channel, 0);
896                    assert(offs == location);
897                    channel.position(location);
898                    long fileLength = channel.size();
899                    if(fileLength < Integer.MAX_VALUE){
900                        sync(channel, bb, (int) fileLength, getUnpaddedFrameLength(bitRate), false);
901                    }
902                    logger.log(lev, String.valueOf(vbrHeader));
903                    result = (vbrHeader != null);
904                } finally {
905                    channel.close();
906                }
907            }
908            return result;
909        }
910    
911    
912        /**
913        * Returns the bitrate of this mpeg. For VBR files with XING or VBRI header,
914        * this method returns the average bit rate read from the header.
915        * For VBR files without header this method will return NULL or the actual
916        * average bitrate if a previous call to analyzeVBR() succeeded.
917        *
918        *@return   the bitrate of this mpeg (in kbps)
919        */
920        public int getBitRate() {
921            int br = NULL;
922    
923            if (vbrHeader != null) {
924                br = vbrHeader.getAvgBitrate();
925            } else if (bitRate == FREE_FORMAT){
926                br = (ffBitRate > 0)? ffBitRate : FREE_FORMAT;
927            } else {
928                br = bitRate;
929            }
930    
931            return br;
932        }
933    
934    
935        /**
936        * Returns the number of frames in this mpeg file. For CBR files,
937        * this does not subtract the size of an id3v1 tag if present so it is not
938        * deadly accurate. For VBR files with XING or VBRI header, this method
939        * returns the number of frames read from the header. For VBR files without
940        * header this method will return NULL or the actual framecount if a previous
941        * call to {@link #analyzeVBR} succeeded.
942        *
943        *@return   the number of frames in this mpeg file
944        */
945        public int getNumFrames() {
946            int num = NULL;
947    
948            if (vbrHeader != null) {
949                num = vbrHeader.getNumFrames();
950            } else {
951                num = ((int) (mp3.length() - location)) / getFrameLength();
952            }
953    
954            return num;
955        }
956    
957        public static void main(String[] argv) throws Exception{
958            lev = Level.INFO;
959            for(int i=0; i<argv.length; i++){
960                File f = new File(argv[i]);
961                MPEGAudioFrameHeader mpeg = new MPEGAudioFrameHeader(f, 20000);
962                System.out.println(f.getName());
963                System.out.println("audiooffset: " + hex(mpeg.getLocation()));
964            }
965        }
966    
967    }
968