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.UnsupportedEncodingException;
005    import java.net.MalformedURLException;
006    import java.net.URL;
007    import java.nio.ByteBuffer;
008    import java.nio.CharBuffer;
009    import java.nio.charset.CharacterCodingException;
010    import java.nio.charset.Charset;
011    import java.nio.charset.CharsetEncoder;
012    import java.nio.charset.CodingErrorAction;
013    import java.util.logging.Logger;
014    
015    /*
016       Copyright (C) 2007 Moritz Ringler
017       This library is free software; you can redistribute it and/or
018       modify it under the terms of the GNU Lesser General Public
019       License as published by the Free Software Foundation; either
020       version 2.1 of the License, or (at your option) any later version.
021       This library is distributed in the hope that it will be useful,
022       but WITHOUT ANY WARRANTY; without even the implied warranty of
023       MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
024       Lesser General Public License for more details.
025       You should have received a copy of the GNU Lesser General Public
026       License along with this library; if not, write to the Free Software
027       Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
028      */
029    
030    public final class APICImage{
031        private static final Logger logger = Logger.getLogger(APICImage.class.getPackage().getName());
032        private String description = "";
033        private String mimeType;
034        private URL url;
035        private byte[] imageData;
036        private PictureType type = PictureType.Other;
037    
038        public static final String MIME_TYPE_LINK = "-->";
039        public static final String MIME_TYPE_PNG = "image/png";
040        public static final String MIME_TYPE_JPEG = "image/jpeg";
041        public static final String MIME_TYPE_GENERIC = "image/";
042    
043        /** @throws NullPointerException if any of the arguments is null
044            @throws IllegalArgumentException if imageData.length == 0
045          */
046        public APICImage(String mimeType, byte[] imageData){
047            if(imageData.length == 0){
048                throw new IllegalArgumentException("image data must have length >= 1");
049            }
050            this.mimeType = mimeType.toString(); //throws NPE if necessary
051            this.imageData = imageData;
052            this.url = null;
053        }
054    
055        /** @throws NullPointerException if the argument is null */
056        public APICImage(URL url){
057            url.toString(); //throws NPE if necessary
058            this.url = url;
059            this.imageData = null;
060            mimeType = MIME_TYPE_LINK;
061        }
062    
063        /** This package private constructor parses an APIC Id3v2 frame. */
064        APICImage(ID3v2Frame apicframe) throws ID3v2FormatException{
065            final byte[] data = apicframe.getFrameData();
066    
067            //read encoding byte
068            final int iencoding = data[0];
069            if(iencoding < 0 || iencoding >= ID3v2Frame.ENC_TYPES.length){
070                throw new ID3v2FormatException("Unknown encoding byte in APIC frame 0x" + Integer.toHexString(iencoding));
071            }
072            final String encoding = ID3v2Frame.ENC_TYPES[iencoding];
073            //System.out.println("Encoding " + encoding);
074    
075            //read mime type
076            int start = 1;
077            int end = 1;
078            for(end = start; end < data.length; end++){
079                if(data[end] == 0x00){
080                    break;
081                }
082            }
083            if(end +3 >= data.length){
084                throw new ID3v2FormatException("Premature end of APIC frame.");
085            }
086            int len = end - start;
087            /* Spec says: In the event that the MIME media type name is omitted,
088                "image/" will be implied. */
089            try{
090            mimeType = (len == 0)? MIME_TYPE_GENERIC :
091                new String(data, start, len, "ISO-8859-1");
092            } catch (UnsupportedEncodingException ex){
093                throw new Error(ex);
094            }
095            //this error seems to be common, we fix it directly on reading
096            if("image/jpg".equals(mimeType)){
097                mimeType = "image/jpeg";
098            }
099            //System.out.println("Mime Type " + mimeType);
100    
101            //read picture type byte
102            int ipicType = data[end + 1];
103            if(ipicType < 0 || ipicType >= PictureType.length()){
104                throw new ID3v2FormatException("Unknown picture type byte in APIC frame 0x" + Integer.toHexString(ipicType));
105            }
106            type = PictureType.valueOf(ipicType);
107            //System.out.println("Type " + type);
108    
109            //read description
110            start = end + 2;
111            int dataOffset = ID3v2Frame.getValOffset(data, 0, start);
112            if(dataOffset == data.length){
113                throw new ID3v2FormatException("Premature end of APIC frame.");
114            }
115            end = dataOffset;
116            while(data[end - 1] == 0x00){
117                end--;
118            }
119            len = end - start;
120            try{
121                description = (len <= 0)
122                ? ""
123                : new String(data, start, len, encoding);
124            } catch (UnsupportedEncodingException ex){
125                throw new Error(ex);
126            }
127            //System.out.println("Description " + description);
128    
129            //read url or image data
130            start = dataOffset;
131            end = data.length;
132            len = end - start;
133            if("-->".equals(mimeType)){
134                try{
135                    url = new URL(new String(data, start, len, "ISO-8859-1"));
136                } catch (UnsupportedEncodingException ex){
137                    throw new Error(ex);
138                } catch (MalformedURLException ex){
139                    throw new ID3v2FormatException(ex);
140                }
141                //System.out.println("URL " + url);
142            } else {
143                imageData = new byte[len];
144                System.arraycopy(data, start, imageData, 0, len);
145                //System.out.println("imageData " + imageData);
146            }
147    
148        }
149    
150        /**
151         * Returns the value of type.
152         */
153        public PictureType getType()
154        {
155            return type;
156        }
157    
158        /**
159         * Sets the value of type.
160         * @param type The value to assign type.
161         * @throws NullPointerException if type is null
162         */
163        public void setType(PictureType type)
164        {
165            type.toString(); //called for the side effect of possibly throwing a NPE
166            this.type = type;
167        }
168    
169    
170         /** Returns the value of description.
171         */
172        public String getDescription()
173        {
174            return description;
175        }
176    
177        /**
178         * Sets the value of description.
179         * @param description The value to assign description.
180         * @throws NullPointerException if description is null
181         * @throws IllegalArgumentException if description.length() > 64
182         */
183        public void setDescription(String description)
184        {
185            if(description.length() > 64){
186                throw new IllegalArgumentException("Description must not have more than 64 characters.");
187            }
188            this.description = description;
189        }
190    
191        /**
192         * Returns the value of mimeType.
193         */
194        public String getMimeType()
195        {
196            return mimeType;
197        }
198    
199    
200        /**
201         * Returns the value of url.
202         */
203        public URL getURL()
204        {
205            return url;
206        }
207    
208        /**
209         * Sets the value of url.
210         * @param url The value to assign url.
211         */
212        public void setURL(URL url)
213        {
214            if(url == null){
215                throw new IllegalArgumentException("url must be non-null.");
216            }
217            this.url = url;
218            this.mimeType = MIME_TYPE_LINK;
219            this.imageData = null;
220        }
221    
222        /**
223         * Returns the value of imageData.
224         */
225        public byte[] getImageData()
226        {
227            return imageData;
228        }
229    
230        /**
231         * Sets the value of imageData.
232         * @param imageData The value to assign imageData.
233         */
234        public void setImageData(byte[] imageData, String mimeType)
235        {
236            if(imageData.length == 0){
237                throw new IllegalArgumentException("image data must have length >= 1");
238            }
239            this.imageData = imageData;
240            this.mimeType = mimeType.toString(); //will throw NPE if necessary
241            this.url = null;
242        }
243    
244        public boolean equals(Object o){
245            if(this == o){
246                return true;
247            }
248            boolean result = false;
249            if(o instanceof APICImage){
250                APICImage other = (APICImage) o;
251                result = (type == other.type);
252                result = result && (description == null)
253                        ? (other.description == null)
254                        : description.equals(other.description);
255                result = result && ((url == null)
256                        ? (other.url == null)
257                        : url.equals(other.url));
258                result = result && ((imageData == null)
259                        ? (other.imageData == null)
260                        : imageData.equals(other.imageData));
261                result = result && ((mimeType == null)
262                        ? (other.mimeType == null)
263                        : mimeType.equals(other.mimeType));
264            }
265            return result;
266        }
267    
268        public int hashcode(){
269            int result = 19;
270            result = 43 * result + type.ordinal();
271            result = 43 * result +
272                        ((description == null)? 0 : description.hashCode());
273            result = 43 * result +
274                        ((mimeType == null)? 0 : mimeType.hashCode());
275            result = 43 * result +
276                        ((imageData == null)? 0 : imageData.hashCode());
277            result = 43 * result +
278                        ((url == null)? 0 : url.hashCode());
279            return result;
280        }
281    
282        public String toString(){
283            StringBuffer sb = new StringBuffer();
284            if(description != null){
285                sb.append(description).append(' ');
286            }
287            sb.append('(').append(type.name()).append(", ");
288            if(url == null){
289                sb.append(mimeType).append(", ");
290                sb.append(Math.ceil(imageData.length/1000)).append(" kB");
291            } else {
292                sb.append(url);
293            }
294            return sb.append(')').toString();
295        }
296    
297        byte[] toFrameData(){
298            final CharsetEncoder isolatinEncoder =
299                    Charset.forName("ISO-8859-1").newEncoder()
300                    .onMalformedInput(CodingErrorAction.REPORT)
301                    .onUnmappableCharacter(CodingErrorAction.REPORT);
302    
303            // encode description
304            ByteBuffer bdesc = null;
305            boolean isoLatin = true;
306            if( description == null || description.length() == 0){
307                bdesc = ByteBuffer.allocate(0);
308            } else {
309                isolatinEncoder.reset();
310                isoLatin = isolatinEncoder.canEncode(description);
311                final CharsetEncoder encoder = (isoLatin)
312                    ? isolatinEncoder
313                    : Charset.forName("UTF-16").newEncoder();
314                encoder.reset();
315                // Spec says: The description has a maximum length of 64 characters
316                try{
317                bdesc = encoder.encode(
318                    CharBuffer.wrap(description, 0,
319                        Math.min(description.length(), 64)));
320                } catch (CharacterCodingException ex){
321                    logger.warning(ex.toString());
322                    logger.warning("APIC: Omitting description");
323                    bdesc = ByteBuffer.allocate(0);
324                }
325            }
326    
327            final int size =
328                1 + //encoding byte
329                mimeType.length() + 1 + //null-terminated mime type
330                1 + // picture type
331                bdesc.limit() + // description length
332                ((isoLatin)? 1 : 2) + //null terminator(s)
333                ((url == null)? imageData.length : url.toString().length());
334    
335            final byte[] result = new byte[size];
336            int pos = 0;
337    
338            //write encoding
339            result[pos++] = (byte) (isoLatin ? 0x00 : 0x01);
340    
341            //write null-terminated mime type
342            isolatinEncoder.reset();
343            ByteBuffer bmime = null;
344            try{
345                bmime = isolatinEncoder.encode(CharBuffer.wrap(mimeType));
346            } catch (CharacterCodingException ex){
347                logger.warning(ex.toString());
348                logger.warning("APIC: Omitting mime type.");
349                bmime = ByteBuffer.allocate(0);
350            }
351            int len = bmime.limit();
352            bmime.get(result, pos, len);
353            pos += len;
354            result[pos++] = 0x00;
355    
356            //write picture type
357            result[pos++] = type.byteValue();
358    
359            //write null-terminated description
360            len = bdesc.limit();
361            bdesc.get(result, pos, len);
362            pos += len;
363            result[pos++] = 0x00;
364            if(!isoLatin){
365                result[pos++] = 0x00;
366            }
367    
368            //copy image data or write URL
369            if(url == null){
370                len = imageData.length;
371                System.arraycopy(imageData, 0, result, pos, imageData.length);
372                pos += len;
373            } else {
374                isolatinEncoder.reset();
375                ByteBuffer burl = null;
376                try{
377                    burl = isolatinEncoder
378                    .onMalformedInput(CodingErrorAction.REPLACE)
379                    .onUnmappableCharacter(CodingErrorAction.REPLACE)
380                    .encode(CharBuffer.wrap(url.toString()));
381                } catch (CharacterCodingException ex){
382                    throw new Error(ex);
383                }
384                len = burl.limit();
385                burl.get(result, pos, len);
386                pos += len;
387            }
388            assert(pos == result.length);
389            return result;
390        }
391    
392        /** typesafe enum for picture type */
393        public static final class PictureType{
394            private final int byteval;
395            private final String name;
396            private static final PictureType[] values = new PictureType[21];
397            private static int ordinal = 0;
398    
399            private PictureType(String name){
400                byteval = ordinal++;
401                this.name = name;
402                values[byteval] = this;
403            }
404    
405            public String toString(){
406                return name;
407            }
408    
409            public String name(){
410                return name;
411            }
412    
413            public int ordinal(){
414                return byteval;
415            }
416    
417            public byte byteValue(){
418                return (byte) byteval;
419            }
420    
421            public static final PictureType Other = new PictureType("Other");                                 //$00  Other
422            public static final PictureType FileIcon32 = new PictureType("FileIcon32x32");                    //$01  32x32 pixels 'file icon' (PNG only)
423            public static final PictureType FileIconOther = new PictureType("FileIconOther");                 //$02  Other file icon
424            public static final PictureType CoverFront = new PictureType("CoverFront");                       //$03  Cover (front)
425            public static final PictureType CoverBack = new PictureType("CoverBack");                         //$04  Cover (back)
426            public static final PictureType LeafletPage = new PictureType("LeafletPage");                     //$05  Leaflet page
427            public static final PictureType Media = new PictureType("Media");                                 //$06  Media (e.g. lable side of CD)
428            public static final PictureType LeadArtist = new PictureType("LeadArtist");                       //$07  Lead artist/lead performer/soloist
429            public static final PictureType Artist = new PictureType("Artist");                               //$08  Artist/performer
430            public static final PictureType Conductor = new PictureType("Conductor");                         //$09  Conductor
431            public static final PictureType BandOrOrchestra = new PictureType("BandOrOrchestra");             //$0A  Band/Orchestra
432            public static final PictureType Composer = new PictureType("Composer");                           //$0B  Composer
433            public static final PictureType Lyricist = new PictureType("Lyricist");                           //$0C  Lyricist/text writer
434            public static final PictureType RecordingLocation = new PictureType("RecordingLocation");         //$0D  Recording Location
435            public static final PictureType DuringRecording = new PictureType("DuringRecording");             //$0E  During recording
436            public static final PictureType DuringPerformance = new PictureType("DuringPerformance");         //$0F  During performance
437            public static final PictureType MovieCapture = new PictureType("MovieCapture");                   //$10  Movie/video screen capture
438            public static final PictureType BrightColouredFish = new PictureType("BrightColouredFish");       //$11  A bright coloured fish
439            public static final PictureType Illustration = new PictureType("Illustration");                   //$12  Illustration
440            public static final PictureType BandOrArtistLogo = new PictureType("BandOrArtistLogo");           //$13  Band/artist logotype
441            public static final PictureType PublisherOrStudioLogo = new PictureType("PublisherOrStudioLogo"); //$14  Publisher/Studio logotype
442    
443            /** @throws ArrayIndexOutOfBoundsException if bbyte is out of range */
444            public static PictureType valueOf(int bbyte){
445                return values[bbyte];
446            }
447    
448            /** @throws IllegalArgumentException if name is not one of the known picture types
449            *   @throws NullPointerException if name is null
450            */
451            public static PictureType valueOf(String name){
452                for(int i=0; i<ordinal; i++){
453                    if(name.equals(values[i].name())){
454                        return values[i];
455                    }
456                }
457                throw new IllegalArgumentException("Unknown PictureType " + name);
458            }
459    
460            public static int length(){
461                return ordinal;
462            }
463    
464            public static PictureType[] values(){
465                return (PictureType[]) values.clone();
466            }
467        }
468    
469    }