SkImageDecoder.h revision 2c7c7ee47d75e7815ea8db05e924ab55958cb402
1
2/*
3 * Copyright 2006 The Android Open Source Project
4 *
5 * Use of this source code is governed by a BSD-style license that can be
6 * found in the LICENSE file.
7 */
8
9
10#ifndef SkImageDecoder_DEFINED
11#define SkImageDecoder_DEFINED
12
13#include "SkBitmap.h"
14#include "SkImage.h"
15#include "SkRect.h"
16#include "SkRefCnt.h"
17#include "SkTRegistry.h"
18#include "SkTypes.h"
19
20class SkStream;
21class SkStreamRewindable;
22
23/** \class SkImageDecoder
24
25    Base class for decoding compressed images into a SkBitmap
26*/
27class SkImageDecoder : public SkNoncopyable {
28public:
29    virtual ~SkImageDecoder();
30
31    enum Format {
32        kUnknown_Format,
33        kBMP_Format,
34        kGIF_Format,
35        kICO_Format,
36        kJPEG_Format,
37        kPNG_Format,
38        kWBMP_Format,
39        kWEBP_Format,
40
41        kLastKnownFormat = kWEBP_Format,
42    };
43
44    /** Return the format of image this decoder can decode. If this decoder can decode multiple
45        formats, kUnknown_Format will be returned.
46    */
47    virtual Format getFormat() const;
48
49    /** Return the format of the SkStreamRewindable or kUnknown_Format if it cannot be determined.
50        Rewinds the stream before returning.
51    */
52    static Format GetStreamFormat(SkStreamRewindable*);
53
54    /** Return a readable string of the Format provided.
55    */
56    static const char* GetFormatName(Format);
57
58    /** Return a readable string of the value returned by getFormat().
59    */
60    const char* getFormatName() const;
61
62    /** Whether the decoder should skip writing zeroes to output if possible.
63    */
64    bool getSkipWritingZeroes() const { return fSkipWritingZeroes; }
65
66    /** Set to true if the decoder should skip writing any zeroes when
67        creating the output image.
68        This is a hint that may not be respected by the decoder.
69        It should only be used if it is known that the memory to write
70        to has already been set to 0; otherwise the resulting image will
71        have garbage.
72        This is ideal for images that contain a lot of completely transparent
73        pixels, but may be a performance hit for an image that has only a
74        few transparent pixels.
75        The default is false.
76    */
77    void setSkipWritingZeroes(bool skip) { fSkipWritingZeroes = skip; }
78
79    /** Returns true if the decoder should try to dither the resulting image.
80        The default setting is true.
81    */
82    bool getDitherImage() const { return fDitherImage; }
83
84    /** Set to true if the the decoder should try to dither the resulting image.
85        The default setting is true.
86    */
87    void setDitherImage(bool dither) { fDitherImage = dither; }
88
89    /** Returns true if the decoder should try to decode the
90        resulting image to a higher quality even at the expense of
91        the decoding speed.
92    */
93    bool getPreferQualityOverSpeed() const { return fPreferQualityOverSpeed; }
94
95    /** Set to true if the the decoder should try to decode the
96        resulting image to a higher quality even at the expense of
97        the decoding speed.
98    */
99    void setPreferQualityOverSpeed(bool qualityOverSpeed) {
100        fPreferQualityOverSpeed = qualityOverSpeed;
101    }
102
103    /** Set to true to require the decoder to return a bitmap with unpremultiplied
104        colors. The default is false, meaning the resulting bitmap will have its
105        colors premultiplied.
106        NOTE: Passing true to this function may result in a bitmap which cannot
107        be properly used by Skia.
108    */
109    void setRequireUnpremultipliedColors(bool request) {
110        fRequireUnpremultipliedColors = request;
111    }
112
113    /** Returns true if the decoder will only return bitmaps with unpremultiplied
114        colors.
115    */
116    bool getRequireUnpremultipliedColors() const { return fRequireUnpremultipliedColors; }
117
118    /** \class Peeker
119
120        Base class for optional callbacks to retrieve meta/chunk data out of
121        an image as it is being decoded.
122    */
123    class Peeker : public SkRefCnt {
124    public:
125        SK_DECLARE_INST_COUNT(Peeker)
126
127        /** Return true to continue decoding, or false to indicate an error, which
128            will cause the decoder to not return the image.
129        */
130        virtual bool peek(const char tag[], const void* data, size_t length) = 0;
131    private:
132        typedef SkRefCnt INHERITED;
133    };
134
135    Peeker* getPeeker() const { return fPeeker; }
136    Peeker* setPeeker(Peeker*);
137
138    /** \class Chooser
139
140        Base class for optional callbacks to choose an image from a format that
141        contains multiple images.
142    */
143    class Chooser : public SkRefCnt {
144    public:
145        SK_DECLARE_INST_COUNT(Chooser)
146
147        virtual void begin(int count) {}
148        virtual void inspect(int index, SkBitmap::Config config, int width, int height) {}
149        /** Return the index of the subimage you want, or -1 to choose none of them.
150        */
151        virtual int choose() = 0;
152
153    private:
154        typedef SkRefCnt INHERITED;
155    };
156
157    Chooser* getChooser() const { return fChooser; }
158    Chooser* setChooser(Chooser*);
159
160    /**
161     *  Optional table describing the caller's preferred config based on
162     *  information about the src data. Each field should be set to the
163     *  preferred config for a src described in the name of the field. The
164     *  src attributes are described in terms of depth (8-index,
165     *  8bit-grayscale, or 8-bits/component) and whether there is per-pixel
166     *  alpha (does not apply to grayscale). If the caller has no preference
167     *  for a particular src type, its slot should be set to kNo_Config.
168     *
169     *  NOTE ABOUT PREFERRED CONFIGS:
170     *  If a config is preferred, either using a pref table or as a parameter
171     *  to some flavor of decode, it is still at the discretion of the codec
172     *  as to what output config is actually returned, as it may not be able
173     *  to support the caller's preference.
174     *
175     *  If a bitmap is decoded into SkBitmap::A8_Config, the resulting bitmap
176     *  will either be a conversion of the grayscale in the case of a
177     *  grayscale source or the alpha channel in the case of a source with
178     *  an alpha channel.
179     */
180    struct PrefConfigTable {
181        SkBitmap::Config fPrefFor_8Index_NoAlpha_src;
182        SkBitmap::Config fPrefFor_8Index_YesAlpha_src;
183        SkBitmap::Config fPrefFor_8Gray_src;
184        SkBitmap::Config fPrefFor_8bpc_NoAlpha_src;
185        SkBitmap::Config fPrefFor_8bpc_YesAlpha_src;
186    };
187
188    /**
189     *  Set an optional table for specifying the caller's preferred config
190     *  based on information about the src data.
191     *
192     *  The default is no preference, which will assume the config set by
193     *  decode is preferred.
194     */
195    void setPrefConfigTable(const PrefConfigTable&);
196
197    /**
198     *  Do not use a PrefConfigTable to determine the output config. This
199     *  is the default, so there is no need to call unless a PrefConfigTable
200     *  was previously set.
201     */
202    void resetPrefConfigTable() { fUsePrefTable = false; }
203
204    SkBitmap::Allocator* getAllocator() const { return fAllocator; }
205    SkBitmap::Allocator* setAllocator(SkBitmap::Allocator*);
206
207    // sample-size, if set to > 1, tells the decoder to return a smaller than
208    // original bitmap, sampling 1 pixel for every size pixels. e.g. if sample
209    // size is set to 3, then the returned bitmap will be 1/3 as wide and high,
210    // and will contain 1/9 as many pixels as the original.
211    // Note: this is a hint, and the codec may choose to ignore this, or only
212    // approximate the sample size.
213    int getSampleSize() const { return fSampleSize; }
214    void setSampleSize(int size);
215
216    /** Reset the sampleSize to its default of 1
217     */
218    void resetSampleSize() { this->setSampleSize(1); }
219
220    /** Decoding is synchronous, but for long decodes, a different thread can
221        call this method safely. This sets a state that the decoders will
222        periodically check, and if they see it changed to cancel, they will
223        cancel. This will result in decode() returning false. However, there is
224        no guarantee that the decoder will see the state change in time, so
225        it is possible that cancelDecode() will be called, but will be ignored
226        and decode() will return true (assuming no other problems were
227        encountered).
228
229        This state is automatically reset at the beginning of decode().
230     */
231    void cancelDecode() {
232        // now the subclass must query shouldCancelDecode() to be informed
233        // of the request
234        fShouldCancelDecode = true;
235    }
236
237    /** Passed to the decode method. If kDecodeBounds_Mode is passed, then
238        only the bitmap's width/height/config need be set. If kDecodePixels_Mode
239        is passed, then the bitmap must have pixels or a pixelRef.
240    */
241    enum Mode {
242        kDecodeBounds_Mode, //!< only return width/height/config in bitmap
243        kDecodePixels_Mode  //!< return entire bitmap (including pixels)
244    };
245
246    /** Given a stream, decode it into the specified bitmap.
247        If the decoder can decompress the image, it calls bitmap.setConfig(),
248        and then if the Mode is kDecodePixels_Mode, call allocPixelRef(),
249        which will allocated a pixelRef. To access the pixel memory, the codec
250        needs to call lockPixels/unlockPixels on the
251        bitmap. It can then set the pixels with the decompressed image.
252    *   If the image cannot be decompressed, return false. After the
253    *   decoding, the function converts the decoded config in bitmap
254    *   to pref if possible. Whether a conversion is feasible is
255    *   tested by Bitmap::canCopyTo(pref).
256
257        If an SkBitmap::Allocator is installed via setAllocator, it will be
258        used to allocate the pixel memory. A clever allocator can be used
259        to allocate the memory from a cache, volatile memory, or even from
260        an existing bitmap's memory.
261
262        If a Peeker is installed via setPeeker, it may be used to peek into
263        meta data during the decode.
264
265        If a Chooser is installed via setChooser, it may be used to select
266        which image to return from a format that contains multiple images.
267    */
268    bool decode(SkStream*, SkBitmap* bitmap, SkBitmap::Config pref, Mode);
269    bool decode(SkStream* stream, SkBitmap* bitmap, Mode mode) {
270        return this->decode(stream, bitmap, SkBitmap::kNo_Config, mode);
271    }
272
273    /**
274     * Given a stream, build an index for doing tile-based decode.
275     * The built index will be saved in the decoder, and the image size will
276     * be returned in width and height.
277     *
278     * Return true for success or false on failure.
279     */
280    bool buildTileIndex(SkStreamRewindable*, int *width, int *height);
281
282    /**
283     * Decode a rectangle subset in the image.
284     * The method can only be called after buildTileIndex().
285     *
286     * Return true for success.
287     * Return false if the index is never built or failing in decoding.
288     */
289    bool decodeSubset(SkBitmap* bm, const SkIRect& subset, SkBitmap::Config pref);
290
291    /**
292     *  @Deprecated
293     *  Use decodeSubset instead.
294     */
295    bool decodeRegion(SkBitmap* bitmap, const SkIRect& rect, SkBitmap::Config pref) {
296        return this->decodeSubset(bitmap, rect, pref);
297    }
298
299    /** Given a stream, this will try to find an appropriate decoder object.
300        If none is found, the method returns NULL.
301    */
302    static SkImageDecoder* Factory(SkStreamRewindable*);
303
304    /** Decode the image stored in the specified file, and store the result
305        in bitmap. Return true for success or false on failure.
306
307        @param prefConfig If the PrefConfigTable is not set, prefer this config.
308                          See NOTE ABOUT PREFERRED CONFIGS.
309
310        @param format On success, if format is non-null, it is set to the format
311                      of the decoded file. On failure it is ignored.
312    */
313    static bool DecodeFile(const char file[], SkBitmap* bitmap,
314                           SkBitmap::Config prefConfig, Mode,
315                           Format* format = NULL);
316    static bool DecodeFile(const char file[], SkBitmap* bitmap) {
317        return DecodeFile(file, bitmap, SkBitmap::kNo_Config,
318                          kDecodePixels_Mode, NULL);
319    }
320    /** Decode the image stored in the specified memory buffer, and store the
321        result in bitmap. Return true for success or false on failure.
322
323        @param prefConfig If the PrefConfigTable is not set, prefer this config.
324                          See NOTE ABOUT PREFERRED CONFIGS.
325
326        @param format On success, if format is non-null, it is set to the format
327                       of the decoded buffer. On failure it is ignored.
328     */
329    static bool DecodeMemory(const void* buffer, size_t size, SkBitmap* bitmap,
330                             SkBitmap::Config prefConfig, Mode,
331                             Format* format = NULL);
332    static bool DecodeMemory(const void* buffer, size_t size, SkBitmap* bitmap){
333        return DecodeMemory(buffer, size, bitmap, SkBitmap::kNo_Config,
334                            kDecodePixels_Mode, NULL);
335    }
336
337    /**
338     *  Struct containing information about a pixel destination.
339     */
340    struct Target {
341        /**
342         *  Pre-allocated memory.
343         */
344        void*  fAddr;
345
346        /**
347         *  Rowbytes of the allocated memory.
348         */
349        size_t fRowBytes;
350    };
351
352    /**
353     *  Decode memory.
354     *  @param info Output parameter. Returns info about the encoded image.
355     *  @param target Contains the address of pixel memory to decode into
356     *         (which must be large enough to hold the width in info) and
357     *         the row bytes to use. If NULL, returns info and does not
358     *         decode pixels.
359     *  @return bool Whether the function succeeded.
360     *
361     *  Sample usage:
362     *  <code>
363     *      // Determine the image's info: width/height/config
364     *      SkImageInfo info;
365     *      bool success = DecodeMemoryToTarget(src, size, &info, NULL);
366     *      if (!success) return;
367     *      // Allocate space for the result:
368     *      SkBitmapFactory::Target target;
369     *      target.fAddr = malloc/other allocation
370     *      target.fRowBytes = ...
371     *      // Now decode the actual pixels into target. &info is optional,
372     *      // and could be NULL
373     *      success = DecodeMemoryToTarget(src, size, &info, &target);
374     *  </code>
375     */
376    static bool DecodeMemoryToTarget(const void* buffer, size_t size, SkImageInfo* info,
377                                     const Target* target);
378
379    /** Decode the image stored in the specified SkStreamRewindable, and store the result
380        in bitmap. Return true for success or false on failure.
381
382        @param prefConfig If the PrefConfigTable is not set, prefer this config.
383                          See NOTE ABOUT PREFERRED CONFIGS.
384
385        @param format On success, if format is non-null, it is set to the format
386                      of the decoded stream. On failure it is ignored.
387     */
388    static bool DecodeStream(SkStreamRewindable* stream, SkBitmap* bitmap,
389                             SkBitmap::Config prefConfig, Mode,
390                             Format* format = NULL);
391    static bool DecodeStream(SkStreamRewindable* stream, SkBitmap* bitmap) {
392        return DecodeStream(stream, bitmap, SkBitmap::kNo_Config,
393                            kDecodePixels_Mode, NULL);
394    }
395
396    /** Return the default config for the running device.
397        Currently this used as a suggestion to image decoders that need to guess
398        what config they should decode into.
399        Default is kNo_Config, but this can be changed with SetDeviceConfig()
400    */
401    static SkBitmap::Config GetDeviceConfig();
402    /** Set the default config for the running device.
403        Currently this used as a suggestion to image decoders that need to guess
404        what config they should decode into.
405        Default is kNo_Config.
406        This can be queried with GetDeviceConfig()
407    */
408    static void SetDeviceConfig(SkBitmap::Config);
409
410protected:
411    // must be overridden in subclasses. This guy is called by decode(...)
412    virtual bool onDecode(SkStream*, SkBitmap* bitmap, Mode) = 0;
413
414    // If the decoder wants to support tiled based decoding,
415    // this method must be overridden. This guy is called by buildTileIndex(...)
416    virtual bool onBuildTileIndex(SkStreamRewindable*, int *width, int *height) {
417        return false;
418    }
419
420    // If the decoder wants to support tiled based decoding,
421    // this method must be overridden. This guy is called by decodeRegion(...)
422    virtual bool onDecodeSubset(SkBitmap* bitmap, const SkIRect& rect) {
423        return false;
424    }
425
426    /*
427     * Crop a rectangle from the src Bitmap to the dest Bitmap. src and dst are
428     * both sampled by sampleSize from an original Bitmap.
429     *
430     * @param dst the destination bitmap.
431     * @param src the source bitmap that is sampled by sampleSize from the
432     *            original bitmap.
433     * @param sampleSize the sample size that src is sampled from the original bitmap.
434     * @param (dstX, dstY) the upper-left point of the dest bitmap in terms of
435     *                     the coordinate in the original bitmap.
436     * @param (width, height) the width and height of the unsampled dst.
437     * @param (srcX, srcY) the upper-left point of the src bitmap in terms of
438     *                     the coordinate in the original bitmap.
439     * @return bool Whether or not it succeeded.
440     */
441    bool cropBitmap(SkBitmap *dst, SkBitmap *src, int sampleSize,
442                    int dstX, int dstY, int width, int height,
443                    int srcX, int srcY);
444
445    /**
446     *  Copy all fields on this decoder to the other decoder. Used by subclasses
447     *  to decode a subimage using a different decoder, but with the same settings.
448     */
449    void copyFieldsToOther(SkImageDecoder* other);
450
451    /**
452     *  Return the default preference being used by the current or latest call to
453     *  decode.
454     */
455    SkBitmap::Config getDefaultPref() { return fDefaultPref; }
456
457    /** Can be queried from within onDecode, to see if the user (possibly in
458        a different thread) has requested the decode to cancel. If this returns
459        true, your onDecode() should stop and return false.
460        Each subclass needs to decide how often it can query this, to balance
461        responsiveness with performance.
462
463        Calling this outside of onDecode() may return undefined values.
464     */
465
466public:
467    bool shouldCancelDecode() const { return fShouldCancelDecode; }
468
469protected:
470    SkImageDecoder();
471
472    // helper function for decoders to handle the (common) case where there is only
473    // once choice available in the image file.
474    bool chooseFromOneChoice(SkBitmap::Config config, int width, int height) const;
475
476    /*  Helper for subclasses. Call this to allocate the pixel memory given the bitmap's
477        width/height/rowbytes/config. Returns true on success. This method handles checking
478        for an optional Allocator.
479    */
480    bool allocPixelRef(SkBitmap*, SkColorTable*) const;
481
482    /**
483     *  The raw data of the src image.
484     */
485    enum SrcDepth {
486        // Color-indexed.
487        kIndex_SrcDepth,
488        // Grayscale in 8 bits.
489        k8BitGray_SrcDepth,
490        // 8 bits per component. Used for 24 bit if there is no alpha.
491        k32Bit_SrcDepth,
492    };
493    /** The subclass, inside onDecode(), calls this to determine the config of
494        the returned bitmap. SrcDepth and hasAlpha reflect the raw data of the
495        src image. This routine returns the caller's preference given
496        srcDepth and hasAlpha, or kNo_Config if there is no preference.
497
498        Note: this also takes into account GetDeviceConfig(), so the subclass
499        need not call that.
500     */
501    SkBitmap::Config getPrefConfig(SrcDepth, bool hasAlpha) const;
502
503private:
504    Peeker*                 fPeeker;
505    Chooser*                fChooser;
506    SkBitmap::Allocator*    fAllocator;
507    int                     fSampleSize;
508    SkBitmap::Config        fDefaultPref;   // use if fUsePrefTable is false
509    PrefConfigTable         fPrefTable;     // use if fUsePrefTable is true
510    bool                    fDitherImage;
511    bool                    fUsePrefTable;
512    bool                    fSkipWritingZeroes;
513    mutable bool            fShouldCancelDecode;
514    bool                    fPreferQualityOverSpeed;
515    bool                    fRequireUnpremultipliedColors;
516};
517
518/** Calling newDecoder with a stream returns a new matching imagedecoder
519    instance, or NULL if none can be found. The caller must manage its ownership
520    of the stream as usual, calling unref() when it is done, as the returned
521    decoder may have called ref() (and if so, the decoder is responsible for
522    balancing its ownership when it is destroyed).
523 */
524class SkImageDecoderFactory : public SkRefCnt {
525public:
526    SK_DECLARE_INST_COUNT(SkImageDecoderFactory)
527
528    virtual SkImageDecoder* newDecoder(SkStreamRewindable*) = 0;
529
530private:
531    typedef SkRefCnt INHERITED;
532};
533
534class SkDefaultImageDecoderFactory : SkImageDecoderFactory {
535public:
536    // calls SkImageDecoder::Factory(stream)
537    virtual SkImageDecoder* newDecoder(SkStreamRewindable* stream) {
538        return SkImageDecoder::Factory(stream);
539    }
540};
541
542// This macro declares a global (i.e., non-class owned) creation entry point
543// for each decoder (e.g., CreateJPEGImageDecoder)
544#define DECLARE_DECODER_CREATOR(codec)          \
545    SkImageDecoder *Create ## codec ();
546
547// This macro defines the global creation entry point for each decoder. Each
548// decoder implementation that registers with the decoder factory must call it.
549#define DEFINE_DECODER_CREATOR(codec)           \
550    SkImageDecoder *Create ## codec () {        \
551        return SkNEW( Sk ## codec );            \
552    }
553
554// All the decoders known by Skia. Note that, depending on the compiler settings,
555// not all of these will be available
556DECLARE_DECODER_CREATOR(BMPImageDecoder);
557DECLARE_DECODER_CREATOR(GIFImageDecoder);
558DECLARE_DECODER_CREATOR(ICOImageDecoder);
559DECLARE_DECODER_CREATOR(JPEGImageDecoder);
560DECLARE_DECODER_CREATOR(PNGImageDecoder);
561DECLARE_DECODER_CREATOR(WBMPImageDecoder);
562DECLARE_DECODER_CREATOR(WEBPImageDecoder);
563
564
565// Typedefs to make registering decoder and formatter callbacks easier.
566// These have to be defined outside SkImageDecoder. :(
567typedef SkTRegistry<SkImageDecoder*(*)(SkStreamRewindable*)>        SkImageDecoder_DecodeReg;
568typedef SkTRegistry<SkImageDecoder::Format(*)(SkStreamRewindable*)> SkImageDecoder_FormatReg;
569
570#endif
571