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 /** If planes or rowBytes is NULL, decodes the header and computes componentSizes
51 for memory allocation.
52 Otherwise, decodes the YUV planes into the provided image planes and
53 updates componentSizes to the final image size.
54 Returns whether the decoding was successful.
56 bool decodeYUV8Planes(SkStream* stream, SkISize componentSizes[3], void* planes[3],
57 size_t rowBytes[3], SkYUVColorSpace*);
59 /** Return the format of the SkStreamRewindable or kUnknown_Format if it cannot be determined.
60 Rewinds the stream before returning.
62 static Format GetStreamFormat(SkStreamRewindable*);
64 /** Return a readable string of the Format provided.
66 static const char* GetFormatName(Format);
68 /** Return a readable string of the value returned by getFormat().
70 const char* getFormatName() const;
72 /** Whether the decoder should skip writing zeroes to output if possible.
74 bool getSkipWritingZeroes() const { return fSkipWritingZeroes; }
76 /** Set to true if the decoder should skip writing any zeroes when
77 creating the output image.
78 This is a hint that may not be respected by the decoder.
79 It should only be used if it is known that the memory to write
80 to has already been set to 0; otherwise the resulting image will
82 This is ideal for images that contain a lot of completely transparent
83 pixels, but may be a performance hit for an image that has only a
84 few transparent pixels.
87 void setSkipWritingZeroes(bool skip) { fSkipWritingZeroes = skip; }
89 /** Returns true if the decoder should try to dither the resulting image.
90 The default setting is true.
92 bool getDitherImage() const { return fDitherImage; }
94 /** Set to true if the the decoder should try to dither the resulting image.
95 The default setting is true.
97 void setDitherImage(bool dither) { fDitherImage = dither; }
99 /** Returns true if the decoder should try to decode the
100 resulting image to a higher quality even at the expense of
103 bool getPreferQualityOverSpeed() const { return fPreferQualityOverSpeed; }
105 /** Set to true if the the decoder should try to decode the
106 resulting image to a higher quality even at the expense of
109 void setPreferQualityOverSpeed(bool qualityOverSpeed) {
110 fPreferQualityOverSpeed = qualityOverSpeed;
113 /** Set to true to require the decoder to return a bitmap with unpremultiplied
114 colors. The default is false, meaning the resulting bitmap will have its
115 colors premultiplied.
116 NOTE: Passing true to this function may result in a bitmap which cannot
117 be properly used by Skia.
119 void setRequireUnpremultipliedColors(bool request) {
120 fRequireUnpremultipliedColors = request;
123 /** Returns true if the decoder will only return bitmaps with unpremultiplied
126 bool getRequireUnpremultipliedColors() const { return fRequireUnpremultipliedColors; }
130 Base class for optional callbacks to retrieve meta/chunk data out of
131 an image as it is being decoded.
133 class Peeker : public SkRefCnt {
135 SK_DECLARE_INST_COUNT(Peeker)
137 /** Return true to continue decoding, or false to indicate an error, which
138 will cause the decoder to not return the image.
140 virtual bool peek(const char tag[], const void* data, size_t length) = 0;
142 typedef SkRefCnt INHERITED;
145 Peeker* getPeeker() const { return fPeeker; }
146 Peeker* setPeeker(Peeker*);
148 #ifdef SK_SUPPORT_LEGACY_IMAGEDECODER_CHOOSER
151 Base class for optional callbacks to choose an image from a format that
152 contains multiple images.
154 class Chooser : public SkRefCnt {
156 SK_DECLARE_INST_COUNT(Chooser)
158 virtual void begin(int count) {}
159 virtual void inspect(int index, SkBitmap::Config config, int width, int height) {}
160 /** Return the index of the subimage you want, or -1 to choose none of them.
162 virtual int choose() = 0;
165 typedef SkRefCnt INHERITED;
168 Chooser* getChooser() const { return fChooser; }
169 Chooser* setChooser(Chooser*);
173 * By default, the codec will try to comply with the "pref" colortype
174 * that is passed to decode() or decodeSubset(). However, this can be called
175 * to override that, causing the codec to try to match the src depth instead
178 * src_8Index -> kIndex_8_SkColorType
179 * src_8Gray -> kN32_SkColorType
180 * src_8bpc -> kN32_SkColorType
182 void setPreserveSrcDepth(bool preserve) {
183 fPreserveSrcDepth = preserve;
186 SkBitmap::Allocator* getAllocator() const { return fAllocator; }
187 SkBitmap::Allocator* setAllocator(SkBitmap::Allocator*);
189 // sample-size, if set to > 1, tells the decoder to return a smaller than
190 // original bitmap, sampling 1 pixel for every size pixels. e.g. if sample
191 // size is set to 3, then the returned bitmap will be 1/3 as wide and high,
192 // and will contain 1/9 as many pixels as the original.
193 // Note: this is a hint, and the codec may choose to ignore this, or only
194 // approximate the sample size.
195 int getSampleSize() const { return fSampleSize; }
196 void setSampleSize(int size);
198 /** Reset the sampleSize to its default of 1
200 void resetSampleSize() { this->setSampleSize(1); }
202 /** Decoding is synchronous, but for long decodes, a different thread can
203 call this method safely. This sets a state that the decoders will
204 periodically check, and if they see it changed to cancel, they will
205 cancel. This will result in decode() returning false. However, there is
206 no guarantee that the decoder will see the state change in time, so
207 it is possible that cancelDecode() will be called, but will be ignored
208 and decode() will return true (assuming no other problems were
211 This state is automatically reset at the beginning of decode().
213 void cancelDecode() {
214 // now the subclass must query shouldCancelDecode() to be informed
216 fShouldCancelDecode = true;
219 /** Passed to the decode method. If kDecodeBounds_Mode is passed, then
220 only the bitmap's info need be set. If kDecodePixels_Mode
221 is passed, then the bitmap must have pixels or a pixelRef.
224 kDecodeBounds_Mode, //!< only return info in bitmap
225 kDecodePixels_Mode //!< return entire bitmap (including pixels)
228 /** Result of a decode. If read as a boolean, a partial success is
229 considered a success (true).
232 kFailure = 0, //!< Image failed to decode. bitmap will be
234 kPartialSuccess = 1, //!< Part of the image decoded. The rest is
235 // filled in automatically
236 kSuccess = 2 //!< The entire image was decoded, if Mode is
237 // kDecodePixels_Mode, or the bounds were
238 // decoded, in kDecodeBounds_Mode.
241 /** Given a stream, decode it into the specified bitmap.
242 If the decoder can decompress the image, it calls bitmap.setInfo(),
243 and then if the Mode is kDecodePixels_Mode, call allocPixelRef(),
244 which will allocated a pixelRef. To access the pixel memory, the codec
245 needs to call lockPixels/unlockPixels on the
246 bitmap. It can then set the pixels with the decompressed image.
247 * If the image cannot be decompressed, return kFailure. After the
248 * decoding, the function converts the decoded colortype in bitmap
249 * to pref if possible. Whether a conversion is feasible is
250 * tested by Bitmap::canCopyTo(pref).
252 If an SkBitmap::Allocator is installed via setAllocator, it will be
253 used to allocate the pixel memory. A clever allocator can be used
254 to allocate the memory from a cache, volatile memory, or even from
255 an existing bitmap's memory.
257 If a Peeker is installed via setPeeker, it may be used to peek into
258 meta data during the decode.
260 Result decode(SkStream*, SkBitmap* bitmap, SkColorType pref, Mode);
261 Result decode(SkStream* stream, SkBitmap* bitmap, Mode mode) {
262 return this->decode(stream, bitmap, kUnknown_SkColorType, mode);
266 * Given a stream, build an index for doing tile-based decode.
267 * The built index will be saved in the decoder, and the image size will
268 * be returned in width and height.
270 * Return true for success or false on failure.
272 bool buildTileIndex(SkStreamRewindable*, int *width, int *height);
275 * Decode a rectangle subset in the image.
276 * The method can only be called after buildTileIndex().
278 * Return true for success.
279 * Return false if the index is never built or failing in decoding.
281 bool decodeSubset(SkBitmap* bm, const SkIRect& subset, SkColorType pref);
283 /** Given a stream, this will try to find an appropriate decoder object.
284 If none is found, the method returns NULL.
286 static SkImageDecoder* Factory(SkStreamRewindable*);
288 /** Decode the image stored in the specified file, and store the result
289 in bitmap. Return true for success or false on failure.
291 @param pref If the PrefConfigTable is not set, prefer this colortype.
292 See NOTE ABOUT PREFERRED CONFIGS.
294 @param format On success, if format is non-null, it is set to the format
295 of the decoded file. On failure it is ignored.
297 static bool DecodeFile(const char file[], SkBitmap* bitmap, SkColorType pref, Mode,
298 Format* format = NULL);
299 static bool DecodeFile(const char file[], SkBitmap* bitmap) {
300 return DecodeFile(file, bitmap, kUnknown_SkColorType, kDecodePixels_Mode, NULL);
303 /** Decode the image stored in the specified memory buffer, and store the
304 result in bitmap. Return true for success or false on failure.
306 @param pref If the PrefConfigTable is not set, prefer this colortype.
307 See NOTE ABOUT PREFERRED CONFIGS.
309 @param format On success, if format is non-null, it is set to the format
310 of the decoded buffer. On failure it is ignored.
312 static bool DecodeMemory(const void* buffer, size_t size, SkBitmap* bitmap, SkColorType pref,
313 Mode, Format* format = NULL);
314 static bool DecodeMemory(const void* buffer, size_t size, SkBitmap* bitmap){
315 return DecodeMemory(buffer, size, bitmap, kUnknown_SkColorType, kDecodePixels_Mode, NULL);
319 * Struct containing information about a pixel destination.
323 * Pre-allocated memory.
328 * Rowbytes of the allocated memory.
333 /** Decode the image stored in the specified SkStreamRewindable, and store the result
334 in bitmap. Return true for success or false on failure.
336 @param pref If the PrefConfigTable is not set, prefer this colortype.
337 See NOTE ABOUT PREFERRED CONFIGS.
339 @param format On success, if format is non-null, it is set to the format
340 of the decoded stream. On failure it is ignored.
342 static bool DecodeStream(SkStreamRewindable* stream, SkBitmap* bitmap, SkColorType pref, Mode,
343 Format* format = NULL);
344 static bool DecodeStream(SkStreamRewindable* stream, SkBitmap* bitmap) {
345 return DecodeStream(stream, bitmap, kUnknown_SkColorType, kDecodePixels_Mode, NULL);
349 // must be overridden in subclasses. This guy is called by decode(...)
350 virtual Result onDecode(SkStream*, SkBitmap* bitmap, Mode) = 0;
352 // If the decoder wants to support tiled based decoding,
353 // this method must be overridden. This guy is called by buildTileIndex(...)
354 virtual bool onBuildTileIndex(SkStreamRewindable*, int *width, int *height) {
358 // If the decoder wants to support tiled based decoding,
359 // this method must be overridden. This guy is called by decodeRegion(...)
360 virtual bool onDecodeSubset(SkBitmap* bitmap, const SkIRect& rect) {
364 /** If planes or rowBytes is NULL, decodes the header and computes componentSizes
365 for memory allocation.
366 Otherwise, decodes the YUV planes into the provided image planes and
367 updates componentSizes to the final image size.
368 Returns whether the decoding was successful.
370 virtual bool onDecodeYUV8Planes(SkStream* stream, SkISize componentSizes[3], void* planes[3],
371 size_t rowBytes[3], SkYUVColorSpace*) {
376 * Crop a rectangle from the src Bitmap to the dest Bitmap. src and dst are
377 * both sampled by sampleSize from an original Bitmap.
379 * @param dst the destination bitmap.
380 * @param src the source bitmap that is sampled by sampleSize from the
382 * @param sampleSize the sample size that src is sampled from the original bitmap.
383 * @param (dstX, dstY) the upper-left point of the dest bitmap in terms of
384 * the coordinate in the original bitmap.
385 * @param (width, height) the width and height of the unsampled dst.
386 * @param (srcX, srcY) the upper-left point of the src bitmap in terms of
387 * the coordinate in the original bitmap.
388 * @return bool Whether or not it succeeded.
390 bool cropBitmap(SkBitmap *dst, SkBitmap *src, int sampleSize,
391 int dstX, int dstY, int width, int height,
395 * Copy all fields on this decoder to the other decoder. Used by subclasses
396 * to decode a subimage using a different decoder, but with the same settings.
398 void copyFieldsToOther(SkImageDecoder* other);
400 /** Can be queried from within onDecode, to see if the user (possibly in
401 a different thread) has requested the decode to cancel. If this returns
402 true, your onDecode() should stop and return false.
403 Each subclass needs to decide how often it can query this, to balance
404 responsiveness with performance.
406 Calling this outside of onDecode() may return undefined values.
410 bool shouldCancelDecode() const { return fShouldCancelDecode; }
416 * Return the default preference being used by the current or latest call to decode.
418 SkColorType getDefaultPref() { return fDefaultPref; }
420 #ifdef SK_SUPPORT_LEGACY_IMAGEDECODER_CHOOSER
421 // helper function for decoders to handle the (common) case where there is only
422 // once choice available in the image file.
423 bool chooseFromOneChoice(SkColorType, int width, int height) const;
426 /* Helper for subclasses. Call this to allocate the pixel memory given the bitmap's info.
427 Returns true on success. This method handles checking for an optional Allocator.
429 bool allocPixelRef(SkBitmap*, SkColorTable*) const;
432 * The raw data of the src image.
437 // Grayscale in 8 bits.
439 // 8 bits per component. Used for 24 bit if there is no alpha.
442 /** The subclass, inside onDecode(), calls this to determine the colorType of
443 the returned bitmap. SrcDepth and hasAlpha reflect the raw data of the
444 src image. This routine returns the caller's preference given
445 srcDepth and hasAlpha, or kUnknown_SkColorType if there is no preference.
447 SkColorType getPrefColorType(SrcDepth, bool hasAlpha) const;
451 #ifdef SK_SUPPORT_LEGACY_IMAGEDECODER_CHOOSER
454 SkBitmap::Allocator* fAllocator;
456 SkColorType fDefaultPref; // use if fUsePrefTable is false
457 bool fPreserveSrcDepth;
459 bool fSkipWritingZeroes;
460 mutable bool fShouldCancelDecode;
461 bool fPreferQualityOverSpeed;
462 bool fRequireUnpremultipliedColors;
465 /** Calling newDecoder with a stream returns a new matching imagedecoder
466 instance, or NULL if none can be found. The caller must manage its ownership
467 of the stream as usual, calling unref() when it is done, as the returned
468 decoder may have called ref() (and if so, the decoder is responsible for
469 balancing its ownership when it is destroyed).
471 class SkImageDecoderFactory : public SkRefCnt {
473 SK_DECLARE_INST_COUNT(SkImageDecoderFactory)
475 virtual SkImageDecoder* newDecoder(SkStreamRewindable*) = 0;
478 typedef SkRefCnt INHERITED;
481 class SkDefaultImageDecoderFactory : SkImageDecoderFactory {
483 // calls SkImageDecoder::Factory(stream)
484 virtual SkImageDecoder* newDecoder(SkStreamRewindable* stream) {
485 return SkImageDecoder::Factory(stream);
489 // This macro declares a global (i.e., non-class owned) creation entry point
490 // for each decoder (e.g., CreateJPEGImageDecoder)
491 #define DECLARE_DECODER_CREATOR(codec) \
492 SkImageDecoder *Create ## codec ();
494 // This macro defines the global creation entry point for each decoder. Each
495 // decoder implementation that registers with the decoder factory must call it.
496 #define DEFINE_DECODER_CREATOR(codec) \
497 SkImageDecoder *Create ## codec () { \
498 return SkNEW( Sk ## codec ); \
501 // All the decoders known by Skia. Note that, depending on the compiler settings,
502 // not all of these will be available
503 DECLARE_DECODER_CREATOR(BMPImageDecoder);
504 DECLARE_DECODER_CREATOR(GIFImageDecoder);
505 DECLARE_DECODER_CREATOR(ICOImageDecoder);
506 DECLARE_DECODER_CREATOR(JPEGImageDecoder);
507 DECLARE_DECODER_CREATOR(PNGImageDecoder);
508 DECLARE_DECODER_CREATOR(WBMPImageDecoder);
509 DECLARE_DECODER_CREATOR(WEBPImageDecoder);
510 DECLARE_DECODER_CREATOR(PKMImageDecoder);
511 DECLARE_DECODER_CREATOR(KTXImageDecoder);
512 DECLARE_DECODER_CREATOR(ASTCImageDecoder);
514 // Typedefs to make registering decoder and formatter callbacks easier.
515 // These have to be defined outside SkImageDecoder. :(
516 typedef SkTRegistry<SkImageDecoder*(*)(SkStreamRewindable*)> SkImageDecoder_DecodeReg;
517 typedef SkTRegistry<SkImageDecoder::Format(*)(SkStreamRewindable*)> SkImageDecoder_FormatReg;