1/*
2 * Copyright 2006 The Android Open Source Project
3 *
4 * Use of this source code is governed by a BSD-style license that can be
5 * found in the LICENSE file.
6 */
7
8#include "SkColorPriv.h"
9#include "SkImageDecoder.h"
10#include "SkStream.h"
11#include "SkStreamHelpers.h"
12#include "SkTypes.h"
13
14class SkICOImageDecoder : public SkImageDecoder {
15public:
16    SkICOImageDecoder();
17
18    virtual Format getFormat() const SK_OVERRIDE {
19        return kICO_Format;
20    }
21
22protected:
23    virtual bool onDecode(SkStream* stream, SkBitmap* bm, Mode) SK_OVERRIDE;
24
25private:
26    typedef SkImageDecoder INHERITED;
27};
28
29/////////////////////////////////////////////////////////////////////////////////////////
30
31//read bytes starting from the begin-th index in the buffer
32//read in Intel order, and return an integer
33
34#define readByte(buffer,begin) buffer[begin]
35#define read2Bytes(buffer,begin) buffer[begin]+(buffer[begin+1]<<8)
36#define read4Bytes(buffer,begin) buffer[begin]+(buffer[begin+1]<<8)+(buffer[begin+2]<<16)+(buffer[begin+3]<<24)
37
38/////////////////////////////////////////////////////////////////////////////////////////
39
40SkICOImageDecoder::SkICOImageDecoder()
41{
42}
43
44//helpers - my function pointer will call one of these, depending on the bitCount, each time through the inner loop
45static void editPixelBit1(const int pixelNo, const unsigned char* buf,
46            const int xorOffset, int& x, int y, const int w,
47            SkBitmap* bm, int alphaByte, int m, int shift, SkPMColor* colors);
48static void editPixelBit4(const int pixelNo, const unsigned char* buf,
49            const int xorOffset, int& x, int y, const int w,
50            SkBitmap* bm, int alphaByte, int m, int shift, SkPMColor* colors);
51static void editPixelBit8(const int pixelNo, const unsigned char* buf,
52            const int xorOffset, int& x, int y, const int w,
53            SkBitmap* bm, int alphaByte, int m, int shift, SkPMColor* colors);
54static void editPixelBit24(const int pixelNo, const unsigned char* buf,
55            const int xorOffset, int& x, int y, const int w,
56            SkBitmap* bm, int alphaByte, int m, int shift, SkPMColor* colors);
57static void editPixelBit32(const int pixelNo, const unsigned char* buf,
58            const int xorOffset, int& x, int y, const int w,
59            SkBitmap* bm, int alphaByte, int m, int shift, SkPMColor* colors);
60
61
62static int calculateRowBytesFor8888(int w, int bitCount)
63{
64    //  Default rowBytes is w << 2 for kARGB_8888
65    //  In the case of a 4 bit image with an odd width, we need to add some
66    //  so we can go off the end of the drawn bitmap.
67    //  Add 4 to ensure that it is still a multiple of 4.
68    if (4 == bitCount && (w & 0x1)) {
69        return (w + 1) << 2;
70    }
71    //  Otherwise return 0, which will allow it to be calculated automatically.
72    return 0;
73}
74
75bool SkICOImageDecoder::onDecode(SkStream* stream, SkBitmap* bm, Mode mode)
76{
77    SkAutoMalloc autoMal;
78    const size_t length = CopyStreamToStorage(&autoMal, stream);
79    if (0 == length) {
80        return false;
81    }
82
83    unsigned char* buf = (unsigned char*)autoMal.get();
84
85    //these should always be the same - should i use for error checking? - what about files that have some
86    //incorrect values, but still decode properly?
87    int reserved = read2Bytes(buf, 0);    // 0
88    int type = read2Bytes(buf, 2);        // 1
89    if (reserved != 0 || type != 1)
90        return false;
91    int count = read2Bytes(buf, 4);
92
93    //need to at least have enough space to hold the initial table of info
94    if (length < (size_t)(6 + count*16))
95        return false;
96
97    int choice;
98    Chooser* chooser = this->getChooser();
99    //FIXME:if no chooser, consider providing the largest color image
100    //what are the odds that the largest image would be monochrome?
101    if (NULL == chooser) {
102        choice = 0;
103    } else {
104        chooser->begin(count);
105        for (int i = 0; i < count; i++)
106        {
107            //need to find out the config, width, and height from the stream
108            int width = readByte(buf, 6 + i*16);
109            int height = readByte(buf, 7 + i*16);
110            int offset = read4Bytes(buf, 18 + i*16);
111            int bitCount = read2Bytes(buf, offset+14);
112            SkBitmap::Config c;
113            //currently only provide ARGB_8888_, but maybe we want kIndex8_Config for 1 and 4, and possibly 8?
114            //or maybe we'll determine this based on the provided config
115            switch (bitCount)
116            {
117                case 1:
118                case 4:
119                    // In reality, at least for the moment, these will be decoded into kARGB_8888 bitmaps.
120                    // However, this will be used to distinguish between the lower quality 1bpp and 4 bpp
121                    // images and the higher quality images.
122                    c = SkBitmap::kIndex8_Config;
123                    break;
124                case 8:
125                case 24:
126                case 32:
127                    c = SkBitmap::kARGB_8888_Config;
128                    break;
129                default:
130                    SkDEBUGF(("Image with %ibpp not supported\n", bitCount));
131                    continue;
132            }
133            chooser->inspect(i, c, width, height);
134        }
135        choice = chooser->choose();
136    }
137
138    //you never know what the chooser is going to supply
139    if (choice >= count || choice < 0)
140        return false;
141
142    //skip ahead to the correct header
143    //commented out lines are not used, but if i switch to other read method, need to know how many to skip
144    //otherwise, they could be used for error checking
145    int w = readByte(buf, 6 + choice*16);
146    int h = readByte(buf, 7 + choice*16);
147    int colorCount = readByte(buf, 8 + choice*16);
148    //int reservedToo = readByte(buf, 9 + choice*16);   //0
149    //int planes = read2Bytes(buf, 10 + choice*16);       //1 - but often 0
150    //int fakeBitCount = read2Bytes(buf, 12 + choice*16); //should be real - usually 0
151    int size = read4Bytes(buf, 14 + choice*16);           //matters?
152    int offset = read4Bytes(buf, 18 + choice*16);
153    if ((size_t)(offset + size) > length)
154        return false;
155
156    // Check to see if this is a PNG image inside the ICO
157    {
158        SkMemoryStream subStream(buf + offset, size, false);
159        SkAutoTDelete<SkImageDecoder> otherDecoder(SkImageDecoder::Factory(&subStream));
160        if (otherDecoder.get() != NULL) {
161            // Set fields on the other decoder to be the same as this one.
162            this->copyFieldsToOther(otherDecoder.get());
163            if(otherDecoder->decode(&subStream, bm, this->getDefaultPref(), mode)) {
164                return true;
165            }
166        }
167    }
168
169    //int infoSize = read4Bytes(buf, offset);             //40
170    //int width = read4Bytes(buf, offset+4);              //should == w
171    //int height = read4Bytes(buf, offset+8);             //should == 2*h
172    //int planesToo = read2Bytes(buf, offset+12);         //should == 1 (does it?)
173    int bitCount = read2Bytes(buf, offset+14);
174
175    void (*placePixel)(const int pixelNo, const unsigned char* buf,
176        const int xorOffset, int& x, int y, const int w,
177        SkBitmap* bm, int alphaByte, int m, int shift, SkPMColor* colors) = NULL;
178    switch (bitCount)
179    {
180        case 1:
181            placePixel = &editPixelBit1;
182            colorCount = 2;
183            break;
184        case 4:
185            placePixel = &editPixelBit4;
186            colorCount = 16;
187            break;
188        case 8:
189            placePixel = &editPixelBit8;
190            colorCount = 256;
191            break;
192        case 24:
193            placePixel = &editPixelBit24;
194            colorCount = 0;
195            break;
196        case 32:
197            placePixel = &editPixelBit32;
198            colorCount = 0;
199            break;
200        default:
201            SkDEBUGF(("Decoding %ibpp is unimplemented\n", bitCount));
202            return false;
203    }
204
205    //these should all be zero, but perhaps are not - need to check
206    //int compression = read4Bytes(buf, offset+16);       //0
207    //int imageSize = read4Bytes(buf, offset+20);         //0 - sometimes has a value
208    //int xPixels = read4Bytes(buf, offset+24);           //0
209    //int yPixels = read4Bytes(buf, offset+28);           //0
210    //int colorsUsed = read4Bytes(buf, offset+32)         //0 - might have an actual value though
211    //int colorsImportant = read4Bytes(buf, offset+36);   //0
212
213    int begin = offset + 40;
214    //this array represents the colortable
215    //if i allow other types of bitmaps, it may actually be used as a part of the bitmap
216    SkPMColor* colors = NULL;
217    int blue, green, red;
218    if (colorCount)
219    {
220        colors = new SkPMColor[colorCount];
221        for (int j = 0; j < colorCount; j++)
222        {
223            //should this be a function - maybe a #define?
224            blue = readByte(buf, begin + 4*j);
225            green = readByte(buf, begin + 4*j + 1);
226            red = readByte(buf, begin + 4*j + 2);
227            colors[j] = SkPackARGB32(0xFF, red & 0xFF, green & 0xFF, blue & 0xFF);
228        }
229    }
230    int bitWidth = w*bitCount;
231    int test = bitWidth & 0x1F;
232    int mask = -(((test >> 4) | (test >> 3) | (test >> 2) | (test >> 1) | test) & 0x1);    //either 0xFFFFFFFF or 0
233    int lineBitWidth = (bitWidth & 0xFFFFFFE0) + (0x20 & mask);
234    int lineWidth = lineBitWidth/bitCount;
235
236    int xorOffset = begin + colorCount*4;   //beginning of the color bitmap
237                                            //other read method means we will just be here already
238    int andOffset = xorOffset + ((lineWidth*h*bitCount) >> 3);
239
240    /*int */test = w & 0x1F;   //the low 5 bits - we are rounding up to the next 32 (2^5)
241    /*int */mask = -(((test >> 4) | (test >> 3) | (test >> 2) | (test >> 1) | test) & 0x1);    //either 0xFFFFFFFF or 0
242    int andLineWidth = (w & 0xFFFFFFE0) + (0x20 & mask);
243    //if we allow different Configs, everything is the same til here
244    //change the config, and use different address getter, and place index vs color, and add the color table
245    //FIXME: what is the tradeoff in size?
246    //if the andbitmap (mask) is all zeroes, then we can easily do an index bitmap
247    //however, with small images with large colortables, maybe it's better to still do argb_8888
248
249    bm->setConfig(SkBitmap::kARGB_8888_Config, w, h, calculateRowBytesFor8888(w, bitCount));
250
251    if (SkImageDecoder::kDecodeBounds_Mode == mode) {
252        delete[] colors;
253        return true;
254    }
255
256    if (!this->allocPixelRef(bm, NULL))
257    {
258        delete[] colors;
259        return false;
260    }
261
262    SkAutoLockPixels alp(*bm);
263
264    for (int y = 0; y < h; y++)
265    {
266        for (int x = 0; x < w; x++)
267        {
268            //U32* address = bm->getAddr32(x, y);
269
270            //check the alpha bit first, but pass it along to the function to figure out how to deal with it
271            int andPixelNo = andLineWidth*(h-y-1)+x;
272            //only need to get a new alphaByte when x %8 == 0
273            //but that introduces an if and a mod - probably much slower
274            //that's ok, it's just a read of an array, not a stream
275            int alphaByte = readByte(buf, andOffset + (andPixelNo >> 3));
276            int shift = 7 - (andPixelNo & 0x7);
277            int m = 1 << shift;
278
279            int pixelNo = lineWidth*(h-y-1)+x;
280            placePixel(pixelNo, buf, xorOffset, x, y, w, bm, alphaByte, m, shift, colors);
281
282        }
283    }
284
285    delete [] colors;
286    //ensure we haven't read off the end?
287    //of course this doesn't help us if the andOffset was a lie...
288    //return andOffset + (andLineWidth >> 3) <= length;
289    return true;
290}   //onDecode
291
292//function to place the pixel, determined by the bitCount
293static void editPixelBit1(const int pixelNo, const unsigned char* buf,
294            const int xorOffset, int& x, int y, const int w,
295            SkBitmap* bm, int alphaByte, int m, int shift, SkPMColor* colors)
296{
297    // note that this should be the same as/similar to the AND bitmap
298    SkPMColor* address = bm->getAddr32(x,y);
299    int byte = readByte(buf, xorOffset + (pixelNo >> 3));
300    int colorBit;
301    int alphaBit;
302    // Read all of the bits in this byte.
303    int i = x + 8;
304    // Pin to the width so we do not write outside the bounds of
305    // our color table.
306    i = i > w ? w : i;
307    // While loop to check all 8 bits individually.
308    while (x < i)
309    {
310
311        colorBit = (byte & m) >> shift;
312        alphaBit = (alphaByte & m) >> shift;
313        *address = (alphaBit-1)&(colors[colorBit]);
314        x++;
315        // setup for the next pixel
316        address = address + 1;
317        m = m >> 1;
318        shift -= 1;
319    }
320    x--;
321}
322static void editPixelBit4(const int pixelNo, const unsigned char* buf,
323            const int xorOffset, int& x, int y, const int w,
324            SkBitmap* bm, int alphaByte, int m, int shift, SkPMColor* colors)
325{
326    SkPMColor* address = bm->getAddr32(x, y);
327    int byte = readByte(buf, xorOffset + (pixelNo >> 1));
328    int pixel = (byte >> 4) & 0xF;
329    int alphaBit = (alphaByte & m) >> shift;
330    *address = (alphaBit-1)&(colors[pixel]);
331    x++;
332    //if w is odd, x may be the same as w, which means we are writing to an unused portion of the bitmap
333    //but that's okay, since i've added an extra rowByte for just this purpose
334    address = address + 1;
335    pixel = byte & 0xF;
336    m = m >> 1;
337    alphaBit = (alphaByte & m) >> (shift-1);
338    //speed up trick here
339    *address = (alphaBit-1)&(colors[pixel]);
340}
341
342static void editPixelBit8(const int pixelNo, const unsigned char* buf,
343            const int xorOffset, int& x, int y, const int w,
344            SkBitmap* bm, int alphaByte, int m, int shift, SkPMColor* colors)
345{
346    SkPMColor* address = bm->getAddr32(x, y);
347    int pixel = readByte(buf, xorOffset + pixelNo);
348    int alphaBit = (alphaByte & m) >> shift;
349    *address = (alphaBit-1)&(colors[pixel]);
350}
351
352static void editPixelBit24(const int pixelNo, const unsigned char* buf,
353            const int xorOffset, int& x, int y, const int w,
354            SkBitmap* bm, int alphaByte, int m, int shift, SkPMColor* colors)
355{
356    SkPMColor* address = bm->getAddr32(x, y);
357    int blue = readByte(buf, xorOffset + 3*pixelNo);
358    int green = readByte(buf, xorOffset + 3*pixelNo + 1);
359    int red = readByte(buf, xorOffset + 3*pixelNo + 2);
360    int alphaBit = (alphaByte & m) >> shift;
361    //alphaBit == 1 => alpha = 0
362    int alpha = (alphaBit-1) & 0xFF;
363    *address = SkPreMultiplyARGB(alpha, red, green, blue);
364}
365
366static void editPixelBit32(const int pixelNo, const unsigned char* buf,
367            const int xorOffset, int& x, int y, const int w,
368            SkBitmap* bm, int alphaByte, int m, int shift, SkPMColor* colors)
369{
370    SkPMColor* address = bm->getAddr32(x, y);
371    int blue = readByte(buf, xorOffset + 4*pixelNo);
372    int green = readByte(buf, xorOffset + 4*pixelNo + 1);
373    int red = readByte(buf, xorOffset + 4*pixelNo + 2);
374    int alphaBit = (alphaByte & m) >> shift;
375#if 1 // don't trust the alphaBit for 32bit images <mrr>
376    alphaBit = 0;
377#endif
378    int alpha = readByte(buf, xorOffset + 4*pixelNo + 3) & ((alphaBit-1)&0xFF);
379    *address = SkPreMultiplyARGB(alpha, red, green, blue);
380}
381
382///////////////////////////////////////////////////////////////////////////////
383DEFINE_DECODER_CREATOR(ICOImageDecoder);
384/////////////////////////////////////////////////////////////////////////////////////////
385
386static bool is_ico(SkStream* stream) {
387    // Check to see if the first four bytes are 0,0,1,0
388    // FIXME: Is that required and sufficient?
389    SkAutoMalloc autoMal(4);
390    unsigned char* buf = (unsigned char*)autoMal.get();
391    stream->read((void*)buf, 4);
392    int reserved = read2Bytes(buf, 0);
393    int type = read2Bytes(buf, 2);
394    if (reserved != 0 || type != 1) {
395        // This stream does not represent an ICO image.
396        return false;
397    }
398    return true;
399}
400
401#include "SkTRegistry.h"
402
403static SkImageDecoder* sk_libico_dfactory(SkStream* stream) {
404    if (is_ico(stream)) {
405        return SkNEW(SkICOImageDecoder);
406    }
407    return NULL;
408}
409
410static SkTRegistry<SkImageDecoder*, SkStream*> gReg(sk_libico_dfactory);
411
412static SkImageDecoder::Format get_format_ico(SkStream* stream) {
413    if (is_ico(stream)) {
414        return SkImageDecoder::kICO_Format;
415    }
416    return SkImageDecoder::kUnknown_Format;
417}
418
419static SkTRegistry<SkImageDecoder::Format, SkStream*> gFormatReg(get_format_ico);
420