2 * Copyright 2006 The Android Open Source Project
4 * Use of this source code is governed by a BSD-style license that can be
5 * found in the LICENSE file.
8 #ifndef SkImageDecoder_DEFINED
9 #define SkImageDecoder_DEFINED
15 #include "SkTRegistry.h"
19 class SkStreamRewindable;
21 /** \class SkImageDecoder
23 Base class for decoding compressed images into a SkBitmap
25 class SkImageDecoder : SkNoncopyable {
27 virtual ~SkImageDecoder();
42 kLastKnownFormat = kKTX_Format,
45 /** Return the format of image this decoder can decode. If this decoder can decode multiple
46 formats, kUnknown_Format will be returned.
48 virtual Format getFormat() const;
50 /** Return the format of the SkStreamRewindable or kUnknown_Format if it cannot be determined.
51 Rewinds the stream before returning.
53 static Format GetStreamFormat(SkStreamRewindable*);
55 /** Return a readable string of the Format provided.
57 static const char* GetFormatName(Format);
59 /** Return a readable string of the value returned by getFormat().
61 const char* getFormatName() const;
63 /** Whether the decoder should skip writing zeroes to output if possible.
65 bool getSkipWritingZeroes() const { return fSkipWritingZeroes; }
67 /** Set to true if the decoder should skip writing any zeroes when
68 creating the output image.
69 This is a hint that may not be respected by the decoder.
70 It should only be used if it is known that the memory to write
71 to has already been set to 0; otherwise the resulting image will
73 This is ideal for images that contain a lot of completely transparent
74 pixels, but may be a performance hit for an image that has only a
75 few transparent pixels.
78 void setSkipWritingZeroes(bool skip) { fSkipWritingZeroes = skip; }
80 /** Returns true if the decoder should try to dither the resulting image.
81 The default setting is true.
83 bool getDitherImage() const { return fDitherImage; }
85 /** Set to true if the the decoder should try to dither the resulting image.
86 The default setting is true.
88 void setDitherImage(bool dither) { fDitherImage = dither; }
90 /** Returns true if the decoder should try to decode the
91 resulting image to a higher quality even at the expense of
94 bool getPreferQualityOverSpeed() const { return fPreferQualityOverSpeed; }
96 /** Set to true if the the decoder should try to decode the
97 resulting image to a higher quality even at the expense of
100 void setPreferQualityOverSpeed(bool qualityOverSpeed) {
101 fPreferQualityOverSpeed = qualityOverSpeed;
104 /** Set to true to require the decoder to return a bitmap with unpremultiplied
105 colors. The default is false, meaning the resulting bitmap will have its
106 colors premultiplied.
107 NOTE: Passing true to this function may result in a bitmap which cannot
108 be properly used by Skia.
110 void setRequireUnpremultipliedColors(bool request) {
111 fRequireUnpremultipliedColors = request;
114 /** Returns true if the decoder will only return bitmaps with unpremultiplied
117 bool getRequireUnpremultipliedColors() const { return fRequireUnpremultipliedColors; }
121 Base class for optional callbacks to retrieve meta/chunk data out of
122 an image as it is being decoded.
124 class Peeker : public SkRefCnt {
126 SK_DECLARE_INST_COUNT(Peeker)
128 /** Return true to continue decoding, or false to indicate an error, which
129 will cause the decoder to not return the image.
131 virtual bool peek(const char tag[], const void* data, size_t length) = 0;
133 typedef SkRefCnt INHERITED;
136 Peeker* getPeeker() const { return fPeeker; }
137 Peeker* setPeeker(Peeker*);
139 #ifdef SK_SUPPORT_LEGACY_IMAGEDECODER_CHOOSER
142 Base class for optional callbacks to choose an image from a format that
143 contains multiple images.
145 class Chooser : public SkRefCnt {
147 SK_DECLARE_INST_COUNT(Chooser)
149 virtual void begin(int count) {}
150 virtual void inspect(int index, SkBitmap::Config config, int width, int height) {}
151 /** Return the index of the subimage you want, or -1 to choose none of them.
153 virtual int choose() = 0;
156 typedef SkRefCnt INHERITED;
159 Chooser* getChooser() const { return fChooser; }
160 Chooser* setChooser(Chooser*);
163 #ifdef SK_SUPPORT_LEGACY_BITMAP_CONFIG
165 * Optional table describing the caller's preferred config based on
166 * information about the src data. Each field should be set to the
167 * preferred config for a src described in the name of the field. The
168 * src attributes are described in terms of depth (8-index,
169 * 8bit-grayscale, or 8-bits/component) and whether there is per-pixel
170 * alpha (does not apply to grayscale). If the caller has no preference
171 * for a particular src type, its slot should be set to kNo_Config.
173 * NOTE ABOUT PREFERRED CONFIGS:
174 * If a config is preferred, either using a pref table or as a parameter
175 * to some flavor of decode, it is still at the discretion of the codec
176 * as to what output config is actually returned, as it may not be able
177 * to support the caller's preference.
179 * If a bitmap is decoded into SkBitmap::A8_Config, the resulting bitmap
180 * will either be a conversion of the grayscale in the case of a
181 * grayscale source or the alpha channel in the case of a source with
184 struct PrefConfigTable {
185 SkBitmap::Config fPrefFor_8Index_NoAlpha_src;
186 SkBitmap::Config fPrefFor_8Index_YesAlpha_src;
187 SkBitmap::Config fPrefFor_8Gray_src;
188 SkBitmap::Config fPrefFor_8bpc_NoAlpha_src;
189 SkBitmap::Config fPrefFor_8bpc_YesAlpha_src;
193 * Set an optional table for specifying the caller's preferred config
194 * based on information about the src data.
196 * The default is no preference, which will assume the config set by
197 * decode is preferred.
199 void setPrefConfigTable(const PrefConfigTable&);
202 * Do not use a PrefConfigTable to determine the output config. This
203 * is the default, so there is no need to call unless a PrefConfigTable
204 * was previously set.
206 void resetPrefConfigTable() { fUsePrefTable = false; }
210 * By default, the codec will try to comply with the "pref" colortype
211 * that is passed to decode() or decodeSubset(). However, this can be called
212 * to override that, causing the codec to try to match the src depth instead
215 * src_8Index -> kIndex_8_SkColorType
216 * src_8Gray -> kN32_SkColorType
217 * src_8bpc -> kN32_SkColorType
219 void setPreserveSrcDepth(bool preserve) {
220 fPreserveSrcDepth = preserve;
223 SkBitmap::Allocator* getAllocator() const { return fAllocator; }
224 SkBitmap::Allocator* setAllocator(SkBitmap::Allocator*);
226 // sample-size, if set to > 1, tells the decoder to return a smaller than
227 // original bitmap, sampling 1 pixel for every size pixels. e.g. if sample
228 // size is set to 3, then the returned bitmap will be 1/3 as wide and high,
229 // and will contain 1/9 as many pixels as the original.
230 // Note: this is a hint, and the codec may choose to ignore this, or only
231 // approximate the sample size.
232 int getSampleSize() const { return fSampleSize; }
233 void setSampleSize(int size);
235 /** Reset the sampleSize to its default of 1
237 void resetSampleSize() { this->setSampleSize(1); }
239 /** Decoding is synchronous, but for long decodes, a different thread can
240 call this method safely. This sets a state that the decoders will
241 periodically check, and if they see it changed to cancel, they will
242 cancel. This will result in decode() returning false. However, there is
243 no guarantee that the decoder will see the state change in time, so
244 it is possible that cancelDecode() will be called, but will be ignored
245 and decode() will return true (assuming no other problems were
248 This state is automatically reset at the beginning of decode().
250 void cancelDecode() {
251 // now the subclass must query shouldCancelDecode() to be informed
253 fShouldCancelDecode = true;
256 /** Passed to the decode method. If kDecodeBounds_Mode is passed, then
257 only the bitmap's info need be set. If kDecodePixels_Mode
258 is passed, then the bitmap must have pixels or a pixelRef.
261 kDecodeBounds_Mode, //!< only return info in bitmap
262 kDecodePixels_Mode //!< return entire bitmap (including pixels)
265 /** Given a stream, decode it into the specified bitmap.
266 If the decoder can decompress the image, it calls bitmap.setInfo(),
267 and then if the Mode is kDecodePixels_Mode, call allocPixelRef(),
268 which will allocated a pixelRef. To access the pixel memory, the codec
269 needs to call lockPixels/unlockPixels on the
270 bitmap. It can then set the pixels with the decompressed image.
271 * If the image cannot be decompressed, return false. After the
272 * decoding, the function converts the decoded colortype in bitmap
273 * to pref if possible. Whether a conversion is feasible is
274 * tested by Bitmap::canCopyTo(pref).
276 If an SkBitmap::Allocator is installed via setAllocator, it will be
277 used to allocate the pixel memory. A clever allocator can be used
278 to allocate the memory from a cache, volatile memory, or even from
279 an existing bitmap's memory.
281 If a Peeker is installed via setPeeker, it may be used to peek into
282 meta data during the decode.
284 bool decode(SkStream*, SkBitmap* bitmap, SkColorType pref, Mode);
285 bool decode(SkStream* stream, SkBitmap* bitmap, Mode mode) {
286 return this->decode(stream, bitmap, kUnknown_SkColorType, mode);
290 * Given a stream, build an index for doing tile-based decode.
291 * The built index will be saved in the decoder, and the image size will
292 * be returned in width and height.
294 * Return true for success or false on failure.
296 bool buildTileIndex(SkStreamRewindable*, int *width, int *height);
299 * Decode a rectangle subset in the image.
300 * The method can only be called after buildTileIndex().
302 * Return true for success.
303 * Return false if the index is never built or failing in decoding.
305 bool decodeSubset(SkBitmap* bm, const SkIRect& subset, SkColorType pref);
307 /** Given a stream, this will try to find an appropriate decoder object.
308 If none is found, the method returns NULL.
310 static SkImageDecoder* Factory(SkStreamRewindable*);
312 /** Decode the image stored in the specified file, and store the result
313 in bitmap. Return true for success or false on failure.
315 @param pref If the PrefConfigTable is not set, prefer this colortype.
316 See NOTE ABOUT PREFERRED CONFIGS.
318 @param format On success, if format is non-null, it is set to the format
319 of the decoded file. On failure it is ignored.
321 static bool DecodeFile(const char file[], SkBitmap* bitmap, SkColorType pref, Mode,
322 Format* format = NULL);
323 static bool DecodeFile(const char file[], SkBitmap* bitmap) {
324 return DecodeFile(file, bitmap, kUnknown_SkColorType, kDecodePixels_Mode, NULL);
327 /** Decode the image stored in the specified memory buffer, and store the
328 result in bitmap. Return true for success or false on failure.
330 @param pref If the PrefConfigTable is not set, prefer this colortype.
331 See NOTE ABOUT PREFERRED CONFIGS.
333 @param format On success, if format is non-null, it is set to the format
334 of the decoded buffer. On failure it is ignored.
336 static bool DecodeMemory(const void* buffer, size_t size, SkBitmap* bitmap, SkColorType pref,
337 Mode, Format* format = NULL);
338 static bool DecodeMemory(const void* buffer, size_t size, SkBitmap* bitmap){
339 return DecodeMemory(buffer, size, bitmap, kUnknown_SkColorType, kDecodePixels_Mode, NULL);
343 * Struct containing information about a pixel destination.
347 * Pre-allocated memory.
352 * Rowbytes of the allocated memory.
357 /** Decode the image stored in the specified SkStreamRewindable, and store the result
358 in bitmap. Return true for success or false on failure.
360 @param pref If the PrefConfigTable is not set, prefer this colortype.
361 See NOTE ABOUT PREFERRED CONFIGS.
363 @param format On success, if format is non-null, it is set to the format
364 of the decoded stream. On failure it is ignored.
366 static bool DecodeStream(SkStreamRewindable* stream, SkBitmap* bitmap, SkColorType pref, Mode,
367 Format* format = NULL);
368 static bool DecodeStream(SkStreamRewindable* stream, SkBitmap* bitmap) {
369 return DecodeStream(stream, bitmap, kUnknown_SkColorType, kDecodePixels_Mode, NULL);
373 // must be overridden in subclasses. This guy is called by decode(...)
374 virtual bool onDecode(SkStream*, SkBitmap* bitmap, Mode) = 0;
376 // If the decoder wants to support tiled based decoding,
377 // this method must be overridden. This guy is called by buildTileIndex(...)
378 virtual bool onBuildTileIndex(SkStreamRewindable*, int *width, int *height) {
382 // If the decoder wants to support tiled based decoding,
383 // this method must be overridden. This guy is called by decodeRegion(...)
384 virtual bool onDecodeSubset(SkBitmap* bitmap, const SkIRect& rect) {
389 * Crop a rectangle from the src Bitmap to the dest Bitmap. src and dst are
390 * both sampled by sampleSize from an original Bitmap.
392 * @param dst the destination bitmap.
393 * @param src the source bitmap that is sampled by sampleSize from the
395 * @param sampleSize the sample size that src is sampled from the original bitmap.
396 * @param (dstX, dstY) the upper-left point of the dest bitmap in terms of
397 * the coordinate in the original bitmap.
398 * @param (width, height) the width and height of the unsampled dst.
399 * @param (srcX, srcY) the upper-left point of the src bitmap in terms of
400 * the coordinate in the original bitmap.
401 * @return bool Whether or not it succeeded.
403 bool cropBitmap(SkBitmap *dst, SkBitmap *src, int sampleSize,
404 int dstX, int dstY, int width, int height,
408 * Copy all fields on this decoder to the other decoder. Used by subclasses
409 * to decode a subimage using a different decoder, but with the same settings.
411 void copyFieldsToOther(SkImageDecoder* other);
413 /** Can be queried from within onDecode, to see if the user (possibly in
414 a different thread) has requested the decode to cancel. If this returns
415 true, your onDecode() should stop and return false.
416 Each subclass needs to decide how often it can query this, to balance
417 responsiveness with performance.
419 Calling this outside of onDecode() may return undefined values.
423 bool shouldCancelDecode() const { return fShouldCancelDecode; }
429 * Return the default preference being used by the current or latest call to decode.
431 SkColorType getDefaultPref() { return fDefaultPref; }
433 #ifdef SK_SUPPORT_LEGACY_IMAGEDECODER_CHOOSER
434 // helper function for decoders to handle the (common) case where there is only
435 // once choice available in the image file.
436 bool chooseFromOneChoice(SkColorType, int width, int height) const;
439 /* Helper for subclasses. Call this to allocate the pixel memory given the bitmap's info.
440 Returns true on success. This method handles checking for an optional Allocator.
442 bool allocPixelRef(SkBitmap*, SkColorTable*) const;
445 * The raw data of the src image.
450 // Grayscale in 8 bits.
452 // 8 bits per component. Used for 24 bit if there is no alpha.
455 /** The subclass, inside onDecode(), calls this to determine the colorType of
456 the returned bitmap. SrcDepth and hasAlpha reflect the raw data of the
457 src image. This routine returns the caller's preference given
458 srcDepth and hasAlpha, or kUnknown_SkColorType if there is no preference.
460 SkColorType getPrefColorType(SrcDepth, bool hasAlpha) const;
464 #ifdef SK_SUPPORT_LEGACY_IMAGEDECODER_CHOOSER
467 SkBitmap::Allocator* fAllocator;
469 SkColorType fDefaultPref; // use if fUsePrefTable is false
470 #ifdef SK_SUPPORT_LEGACY_BITMAP_CONFIG
471 PrefConfigTable fPrefTable; // use if fUsePrefTable is true
474 bool fPreserveSrcDepth;
476 bool fSkipWritingZeroes;
477 mutable bool fShouldCancelDecode;
478 bool fPreferQualityOverSpeed;
479 bool fRequireUnpremultipliedColors;
482 /** Calling newDecoder with a stream returns a new matching imagedecoder
483 instance, or NULL if none can be found. The caller must manage its ownership
484 of the stream as usual, calling unref() when it is done, as the returned
485 decoder may have called ref() (and if so, the decoder is responsible for
486 balancing its ownership when it is destroyed).
488 class SkImageDecoderFactory : public SkRefCnt {
490 SK_DECLARE_INST_COUNT(SkImageDecoderFactory)
492 virtual SkImageDecoder* newDecoder(SkStreamRewindable*) = 0;
495 typedef SkRefCnt INHERITED;
498 class SkDefaultImageDecoderFactory : SkImageDecoderFactory {
500 // calls SkImageDecoder::Factory(stream)
501 virtual SkImageDecoder* newDecoder(SkStreamRewindable* stream) {
502 return SkImageDecoder::Factory(stream);
506 // This macro declares a global (i.e., non-class owned) creation entry point
507 // for each decoder (e.g., CreateJPEGImageDecoder)
508 #define DECLARE_DECODER_CREATOR(codec) \
509 SkImageDecoder *Create ## codec ();
511 // This macro defines the global creation entry point for each decoder. Each
512 // decoder implementation that registers with the decoder factory must call it.
513 #define DEFINE_DECODER_CREATOR(codec) \
514 SkImageDecoder *Create ## codec () { \
515 return SkNEW( Sk ## codec ); \
518 // All the decoders known by Skia. Note that, depending on the compiler settings,
519 // not all of these will be available
520 DECLARE_DECODER_CREATOR(BMPImageDecoder);
521 DECLARE_DECODER_CREATOR(GIFImageDecoder);
522 DECLARE_DECODER_CREATOR(ICOImageDecoder);
523 DECLARE_DECODER_CREATOR(JPEGImageDecoder);
524 DECLARE_DECODER_CREATOR(PNGImageDecoder);
525 DECLARE_DECODER_CREATOR(WBMPImageDecoder);
526 DECLARE_DECODER_CREATOR(WEBPImageDecoder);
527 DECLARE_DECODER_CREATOR(PKMImageDecoder);
528 DECLARE_DECODER_CREATOR(KTXImageDecoder);
529 DECLARE_DECODER_CREATOR(ASTCImageDecoder);
531 // Typedefs to make registering decoder and formatter callbacks easier.
532 // These have to be defined outside SkImageDecoder. :(
533 typedef SkTRegistry<SkImageDecoder*(*)(SkStreamRewindable*)> SkImageDecoder_DecodeReg;
534 typedef SkTRegistry<SkImageDecoder::Format(*)(SkStreamRewindable*)> SkImageDecoder_FormatReg;