Home | History | Annotate | Download | only in images
      1 /*
      2  * Copyright (C) 2006 The Android Open Source Project
      3  *
      4  * Licensed under the Apache License, Version 2.0 (the "License");
      5  * you may not use this file except in compliance with the License.
      6  * You may obtain a copy of the License at
      7  *
      8  *      http://www.apache.org/licenses/LICENSE-2.0
      9  *
     10  * Unless required by applicable law or agreed to in writing, software
     11  * distributed under the License is distributed on an "AS IS" BASIS,
     12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     13  * See the License for the specific language governing permissions and
     14  * limitations under the License.
     15  */
     16 
     17 #ifndef SkImageDecoder_DEFINED
     18 #define SkImageDecoder_DEFINED
     19 
     20 #include "SkBitmap.h"
     21 #include "SkRect.h"
     22 #include "SkRefCnt.h"
     23 
     24 class SkStream;
     25 
     26 class SkVMMemoryReporter : public SkRefCnt {
     27 public:
     28     virtual ~SkVMMemoryReporter();
     29     virtual bool reportMemory(size_t memorySize) = 0;
     30 };
     31 
     32 /** \class SkImageDecoder
     33 
     34     Base class for decoding compressed images into a SkBitmap
     35 */
     36 class SkImageDecoder {
     37 public:
     38     virtual ~SkImageDecoder();
     39 
     40     // Should be consistent with kFormatName
     41     enum Format {
     42         kUnknown_Format,
     43         kBMP_Format,
     44         kGIF_Format,
     45         kICO_Format,
     46         kJPEG_Format,
     47         kPNG_Format,
     48         kWBMP_Format,
     49         kWEBP_Format,
     50 
     51         kLastKnownFormat = kWEBP_Format
     52     };
     53 
     54     /** Contains the image format name.
     55      *  This should be consistent with Format.
     56      *
     57      *  The format name gives a more meaningful error message than enum.
     58      */
     59     static const char *kFormatName[8];
     60 
     61     /** Return the compressed data's format (see Format enum)
     62     */
     63     virtual Format getFormat() const;
     64 
     65     /** Return the compressed data's format name.
     66     */
     67     const char* getFormatName() const { return kFormatName[getFormat()]; }
     68 
     69     /** Returns true if the decoder should try to dither the resulting image.
     70         The default setting is true.
     71     */
     72     bool getDitherImage() const { return fDitherImage; }
     73 
     74     /** Set to true if the the decoder should try to dither the resulting image.
     75         The default setting is true.
     76     */
     77     void setDitherImage(bool dither) { fDitherImage = dither; }
     78 
     79     /** Returns true if the decoder should try to decode the
     80         resulting image to a higher quality even at the expense of
     81         the decoding speed.
     82     */
     83     bool getPreferQualityOverSpeed() const { return fPreferQualityOverSpeed; }
     84 
     85     /** Set to true if the the decoder should try to decode the
     86         resulting image to a higher quality even at the expense of
     87         the decoding speed.
     88     */
     89     void setPreferQualityOverSpeed(bool qualityOverSpeed) {
     90         fPreferQualityOverSpeed = qualityOverSpeed;
     91     }
     92 
     93     /** \class Peeker
     94 
     95         Base class for optional callbacks to retrieve meta/chunk data out of
     96         an image as it is being decoded.
     97     */
     98     class Peeker : public SkRefCnt {
     99     public:
    100         /** Return true to continue decoding, or false to indicate an error, which
    101             will cause the decoder to not return the image.
    102         */
    103         virtual bool peek(const char tag[], const void* data, size_t length) = 0;
    104     };
    105 
    106     Peeker* getPeeker() const { return fPeeker; }
    107     Peeker* setPeeker(Peeker*);
    108 
    109     /** \class Peeker
    110 
    111         Base class for optional callbacks to retrieve meta/chunk data out of
    112         an image as it is being decoded.
    113     */
    114     class Chooser : public SkRefCnt {
    115     public:
    116         virtual void begin(int count) {}
    117         virtual void inspect(int index, SkBitmap::Config config, int width, int height) {}
    118         /** Return the index of the subimage you want, or -1 to choose none of them.
    119         */
    120         virtual int choose() = 0;
    121     };
    122 
    123     Chooser* getChooser() const { return fChooser; }
    124     Chooser* setChooser(Chooser*);
    125 
    126     /** This optional table describes the caller's preferred config based on
    127         information about the src data. For this table, the src attributes are
    128         described in terms of depth (index (8), 16, 32/24) and if there is
    129         per-pixel alpha. These inputs combine to create an index into the
    130         pref[] table, which contains the caller's preferred config for that
    131         input, or kNo_Config if there is no preference.
    132 
    133         To specify no preferrence, call setPrefConfigTable(NULL), which is
    134         the default.
    135 
    136         Note, it is still at the discretion of the codec as to what output
    137         config is actually returned, as it may not be able to support the
    138         caller's preference.
    139 
    140         Here is how the index into the table is computed from the src:
    141             depth [8, 16, 32/24] -> 0, 2, 4
    142             alpha [no, yes] -> 0, 1
    143         The two index values are OR'd together.
    144             src: 8-index, no-alpha  -> 0
    145             src: 8-index, yes-alpha -> 1
    146             src: 16bit,   no-alpha  -> 2    // e.g. 565
    147             src: 16bit,   yes-alpha -> 3    // e.g. 1555
    148             src: 32/24,   no-alpha  -> 4
    149             src: 32/24,   yes-alpha -> 5
    150      */
    151     void setPrefConfigTable(const SkBitmap::Config pref[6]);
    152 
    153     SkBitmap::Allocator* getAllocator() const { return fAllocator; }
    154     SkBitmap::Allocator* setAllocator(SkBitmap::Allocator*);
    155     SkVMMemoryReporter* setReporter(SkVMMemoryReporter*);
    156 
    157     // sample-size, if set to > 1, tells the decoder to return a smaller than
    158     // original bitmap, sampling 1 pixel for every size pixels. e.g. if sample
    159     // size is set to 3, then the returned bitmap will be 1/3 as wide and high,
    160     // and will contain 1/9 as many pixels as the original.
    161     // Note: this is a hint, and the codec may choose to ignore this, or only
    162     // approximate the sample size.
    163     int getSampleSize() const { return fSampleSize; }
    164     void setSampleSize(int size);
    165 
    166     /** Reset the sampleSize to its default of 1
    167      */
    168     void resetSampleSize() { this->setSampleSize(1); }
    169 
    170     /** Decoding is synchronous, but for long decodes, a different thread can
    171         call this method safely. This sets a state that the decoders will
    172         periodically check, and if they see it changed to cancel, they will
    173         cancel. This will result in decode() returning false. However, there is
    174         no guarantee that the decoder will see the state change in time, so
    175         it is possible that cancelDecode() will be called, but will be ignored
    176         and decode() will return true (assuming no other problems were
    177         encountered).
    178 
    179         This state is automatically reset at the beginning of decode().
    180      */
    181     void cancelDecode() {
    182         // now the subclass must query shouldCancelDecode() to be informed
    183         // of the request
    184         fShouldCancelDecode = true;
    185     }
    186 
    187     /** Passed to the decode method. If kDecodeBounds_Mode is passed, then
    188         only the bitmap's width/height/config need be set. If kDecodePixels_Mode
    189         is passed, then the bitmap must have pixels or a pixelRef.
    190     */
    191     enum Mode {
    192         kDecodeBounds_Mode, //!< only return width/height/config in bitmap
    193         kDecodePixels_Mode  //!< return entire bitmap (including pixels)
    194     };
    195 
    196     /** Given a stream, decode it into the specified bitmap.
    197         If the decoder can decompress the image, it calls bitmap.setConfig(),
    198         and then if the Mode is kDecodePixels_Mode, call allocPixelRef(),
    199         which will allocated a pixelRef. To access the pixel memory, the codec
    200         needs to call lockPixels/unlockPixels on the
    201         bitmap. It can then set the pixels with the decompressed image.
    202     *   If the image cannot be decompressed, return false. After the
    203     *   decoding, the function converts the decoded config in bitmap
    204     *   to pref if possible. Whether a conversion is feasible is
    205     *   tested by Bitmap::canCopyTo(pref).
    206 
    207         note: document use of Allocator, Peeker and Chooser
    208     */
    209     bool decode(SkStream*, SkBitmap* bitmap, SkBitmap::Config pref, Mode, bool reuseBitmap = false);
    210     bool decode(SkStream* stream, SkBitmap* bitmap, Mode mode, bool reuseBitmap = false) {
    211         return this->decode(stream, bitmap, SkBitmap::kNo_Config, mode, reuseBitmap);
    212     }
    213 
    214     /**
    215      * Given a stream, build an index for doing tile-based decode.
    216      * The built index will be saved in the decoder, and the image size will
    217      * be returned in width and height.
    218      *
    219      * Return true for success or false on failure.
    220      */
    221     virtual bool buildTileIndex(SkStream*,
    222                                 int *width, int *height);
    223 
    224     /**
    225      * Decode a rectangle region in the image specified by rect.
    226      * The method can only be called after buildTileIndex().
    227      *
    228      * Return true for success.
    229      * Return false if the index is never built or failing in decoding.
    230      */
    231     virtual bool decodeRegion(SkBitmap* bitmap, SkIRect rect,
    232                               SkBitmap::Config pref);
    233 
    234     /** Given a stream, this will try to find an appropriate decoder object.
    235         If none is found, the method returns NULL.
    236     */
    237     static SkImageDecoder* Factory(SkStream*);
    238 
    239     /** Decode the image stored in the specified file, and store the result
    240         in bitmap. Return true for success or false on failure.
    241 
    242         If pref is kNo_Config, then the decoder is free to choose the most natural
    243         config given the image data. If pref something other than kNo_Config,
    244         the decoder will attempt to decode the image into that format, unless
    245         there is a conflict (e.g. the image has per-pixel alpha and the bitmap's
    246         config does not support that), in which case the decoder will choose a
    247         closest match configuration.
    248 
    249         @param format On success, if format is non-null, it is set to the format
    250                       of the decoded file. On failure it is ignored.
    251     */
    252     static bool DecodeFile(const char file[], SkBitmap* bitmap,
    253                            SkBitmap::Config prefConfig, Mode,
    254                            Format* format = NULL);
    255     static bool DecodeFile(const char file[], SkBitmap* bitmap) {
    256         return DecodeFile(file, bitmap, SkBitmap::kNo_Config,
    257                           kDecodePixels_Mode, NULL);
    258     }
    259     /** Decode the image stored in the specified memory buffer, and store the
    260         result in bitmap. Return true for success or false on failure.
    261 
    262         If pref is kNo_Config, then the decoder is free to choose the most natural
    263         config given the image data. If pref something other than kNo_Config,
    264         the decoder will attempt to decode the image into that format, unless
    265         there is a conflict (e.g. the image has per-pixel alpha and the bitmap's
    266         config does not support that), in which case the decoder will choose a
    267         closest match configuration.
    268 
    269         @param format On success, if format is non-null, it is set to the format
    270                        of the decoded buffer. On failure it is ignored.
    271      */
    272     static bool DecodeMemory(const void* buffer, size_t size, SkBitmap* bitmap,
    273                              SkBitmap::Config prefConfig, Mode,
    274                              Format* format = NULL);
    275     static bool DecodeMemory(const void* buffer, size_t size, SkBitmap* bitmap){
    276         return DecodeMemory(buffer, size, bitmap, SkBitmap::kNo_Config,
    277                             kDecodePixels_Mode, NULL);
    278     }
    279     /** Decode the image stored in the specified SkStream, and store the result
    280         in bitmap. Return true for success or false on failure.
    281 
    282         If pref is kNo_Config, then the decoder is free to choose the most
    283         natural config given the image data. If pref something other than
    284         kNo_Config, the decoder will attempt to decode the image into that
    285         format, unless there is a conflict (e.g. the image has per-pixel alpha
    286         and the bitmap's config does not support that), in which case the
    287         decoder will choose a closest match configuration.
    288 
    289         @param format On success, if format is non-null, it is set to the format
    290                       of the decoded stream. On failure it is ignored.
    291      */
    292     static bool DecodeStream(SkStream* stream, SkBitmap* bitmap,
    293                              SkBitmap::Config prefConfig, Mode,
    294                              Format* format = NULL);
    295     static bool DecodeStream(SkStream* stream, SkBitmap* bitmap) {
    296         return DecodeStream(stream, bitmap, SkBitmap::kNo_Config,
    297                             kDecodePixels_Mode, NULL);
    298     }
    299 
    300     /** Return the default config for the running device.
    301         Currently this used as a suggestion to image decoders that need to guess
    302         what config they should decode into.
    303         Default is kNo_Config, but this can be changed with SetDeviceConfig()
    304     */
    305     static SkBitmap::Config GetDeviceConfig();
    306     /** Set the default config for the running device.
    307         Currently this used as a suggestion to image decoders that need to guess
    308         what config they should decode into.
    309         Default is kNo_Config.
    310         This can be queried with GetDeviceConfig()
    311     */
    312     static void SetDeviceConfig(SkBitmap::Config);
    313 
    314   /** @cond UNIT_TEST */
    315     SkDEBUGCODE(static void UnitTest();)
    316   /** @endcond */
    317 
    318 protected:
    319     // must be overridden in subclasses. This guy is called by decode(...)
    320     virtual bool onDecode(SkStream*, SkBitmap* bitmap, Mode) = 0;
    321 
    322     // If the decoder wants to support tiled based decoding,
    323     // this method must be overridden. This guy is called by buildTileIndex(...)
    324     virtual bool onBuildTileIndex(SkStream*,
    325                 int *width, int *height) {
    326         return false;
    327     }
    328 
    329     // If the decoder wants to support tiled based decoding,
    330     // this method must be overridden. This guy is called by decodeRegion(...)
    331     virtual bool onDecodeRegion(SkBitmap* bitmap, SkIRect rect) {
    332         return false;
    333     }
    334 
    335     /*
    336      * Crop a rectangle from the src Bitmap to the dest Bitmap. src and dest are
    337      * both sampled by sampleSize from an original Bitmap.
    338      *
    339      * @param dest the destination Bitmap.
    340      * @param src the source Bitmap that is sampled by sampleSize from the original
    341      *            Bitmap.
    342      * @param sampleSize the sample size that src is sampled from the original Bitmap.
    343      * @param (srcX, srcY) the upper-left point of the src Btimap in terms of
    344      *                     the coordinate in the original Bitmap.
    345      * @param (width, height) the width and height of the unsampled dest.
    346      * @param (destX, destY) the upper-left point of the dest Bitmap in terms of
    347      *                       the coordinate in the original Bitmap.
    348      */
    349     virtual void cropBitmap(SkBitmap *dest, SkBitmap *src, int sampleSize,
    350                             int destX, int destY, int width, int height,
    351                             int srcX, int srcY);
    352 
    353 
    354 
    355     /** Can be queried from within onDecode, to see if the user (possibly in
    356         a different thread) has requested the decode to cancel. If this returns
    357         true, your onDecode() should stop and return false.
    358         Each subclass needs to decide how often it can query this, to balance
    359         responsiveness with performance.
    360 
    361         Calling this outside of onDecode() may return undefined values.
    362      */
    363 
    364 public:
    365     bool shouldCancelDecode() const { return fShouldCancelDecode; }
    366 
    367 protected:
    368     SkImageDecoder();
    369 
    370     // helper function for decoders to handle the (common) case where there is only
    371     // once choice available in the image file.
    372     bool chooseFromOneChoice(SkBitmap::Config config, int width, int height) const;
    373 
    374     /*  Helper for subclasses. Call this to allocate the pixel memory given the bitmap's
    375         width/height/rowbytes/config. Returns true on success. This method handles checking
    376         for an optional Allocator.
    377     */
    378     bool allocPixelRef(SkBitmap*, SkColorTable*) const;
    379 
    380     enum SrcDepth {
    381         kIndex_SrcDepth,
    382         k16Bit_SrcDepth,
    383         k32Bit_SrcDepth
    384     };
    385     /** The subclass, inside onDecode(), calls this to determine the config of
    386         the returned bitmap. SrcDepth and hasAlpha reflect the raw data of the
    387         src image. This routine returns the caller's preference given
    388         srcDepth and hasAlpha, or kNo_Config if there is no preference.
    389 
    390         Note: this also takes into account GetDeviceConfig(), so the subclass
    391         need not call that.
    392      */
    393     SkBitmap::Config getPrefConfig(SrcDepth, bool hasAlpha) const;
    394 
    395     SkVMMemoryReporter*      fReporter;
    396 
    397 private:
    398     Peeker*                 fPeeker;
    399     Chooser*                fChooser;
    400     SkBitmap::Allocator*    fAllocator;
    401     int                     fSampleSize;
    402     SkBitmap::Config        fDefaultPref;   // use if fUsePrefTable is false
    403     SkBitmap::Config        fPrefTable[6];  // use if fUsePrefTable is true
    404     bool                    fDitherImage;
    405     bool                    fUsePrefTable;
    406     mutable bool            fShouldCancelDecode;
    407     bool                    fPreferQualityOverSpeed;
    408 
    409     // illegal
    410     SkImageDecoder(const SkImageDecoder&);
    411     SkImageDecoder& operator=(const SkImageDecoder&);
    412 };
    413 
    414 /** Calling newDecoder with a stream returns a new matching imagedecoder
    415     instance, or NULL if none can be found. The caller must manage its ownership
    416     of the stream as usual, calling unref() when it is done, as the returned
    417     decoder may have called ref() (and if so, the decoder is responsible for
    418     balancing its ownership when it is destroyed).
    419  */
    420 class SkImageDecoderFactory : public SkRefCnt {
    421 public:
    422     virtual SkImageDecoder* newDecoder(SkStream*) = 0;
    423 };
    424 
    425 class SkDefaultImageDecoderFactory : SkImageDecoderFactory {
    426 public:
    427     // calls SkImageDecoder::Factory(stream)
    428     virtual SkImageDecoder* newDecoder(SkStream* stream) {
    429         return SkImageDecoder::Factory(stream);
    430     }
    431 };
    432 
    433 
    434 #endif
    435