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