1 /* 2 * Copyright 2006 The Android Open Source Project 3 * 4 * Use of this source code is governed by a BSD-style license that can be 5 * found in the LICENSE file. 6 */ 7 8 #ifndef SkImageDecoder_DEFINED 9 #define SkImageDecoder_DEFINED 10 11 #include "SkBitmap.h" 12 #include "SkImage.h" 13 #include "SkPngChunkReader.h" 14 #include "SkRect.h" 15 #include "SkRefCnt.h" 16 #include "SkTRegistry.h" 17 #include "SkTypes.h" 18 19 class SkStream; 20 class SkStreamRewindable; 21 22 /** \class SkImageDecoder 23 24 Base class for decoding compressed images into a SkBitmap 25 */ 26 class SkImageDecoder : SkNoncopyable { 27 public: 28 virtual ~SkImageDecoder(); 29 30 // TODO (scroggo): Merge with SkEncodedFormat 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 kPKM_Format, 41 kKTX_Format, 42 kASTC_Format, 43 44 kLastKnownFormat = kKTX_Format, 45 }; 46 47 /** Return the format of image this decoder can decode. If this decoder can decode multiple 48 formats, kUnknown_Format will be returned. 49 */ 50 virtual Format getFormat() const; 51 52 /** If planes or rowBytes is NULL, decodes the header and computes componentSizes 53 for memory allocation. 54 Otherwise, decodes the YUV planes into the provided image planes and 55 updates componentSizes to the final image size. 56 Returns whether the decoding was successful. 57 */ 58 bool decodeYUV8Planes(SkStream* stream, SkISize componentSizes[3], void* planes[3], 59 size_t rowBytes[3], SkYUVColorSpace*); 60 61 /** Return the format of the SkStreamRewindable or kUnknown_Format if it cannot be determined. 62 Rewinds the stream before returning. 63 */ 64 static Format GetStreamFormat(SkStreamRewindable*); 65 66 /** Return a readable string of the Format provided. 67 */ 68 static const char* GetFormatName(Format); 69 70 /** Return a readable string of the value returned by getFormat(). 71 */ 72 const char* getFormatName() const; 73 74 /** Whether the decoder should skip writing zeroes to output if possible. 75 */ 76 bool getSkipWritingZeroes() const { return fSkipWritingZeroes; } 77 78 /** Set to true if the decoder should skip writing any zeroes when 79 creating the output image. 80 This is a hint that may not be respected by the decoder. 81 It should only be used if it is known that the memory to write 82 to has already been set to 0; otherwise the resulting image will 83 have garbage. 84 This is ideal for images that contain a lot of completely transparent 85 pixels, but may be a performance hit for an image that has only a 86 few transparent pixels. 87 The default is false. 88 */ 89 void setSkipWritingZeroes(bool skip) { fSkipWritingZeroes = skip; } 90 91 /** Returns true if the decoder should try to dither the resulting image. 92 The default setting is true. 93 */ 94 bool getDitherImage() const { return fDitherImage; } 95 96 /** Set to true if the the decoder should try to dither the resulting image. 97 The default setting is true. 98 */ 99 void setDitherImage(bool dither) { fDitherImage = dither; } 100 101 /** Returns true if the decoder should try to decode the 102 resulting image to a higher quality even at the expense of 103 the decoding speed. 104 */ 105 bool getPreferQualityOverSpeed() const { return fPreferQualityOverSpeed; } 106 107 /** Set to true if the the decoder should try to decode the 108 resulting image to a higher quality even at the expense of 109 the decoding speed. 110 */ 111 void setPreferQualityOverSpeed(bool qualityOverSpeed) { 112 fPreferQualityOverSpeed = qualityOverSpeed; 113 } 114 115 /** Set to true to require the decoder to return a bitmap with unpremultiplied 116 colors. The default is false, meaning the resulting bitmap will have its 117 colors premultiplied. 118 NOTE: Passing true to this function may result in a bitmap which cannot 119 be properly used by Skia. 120 */ 121 void setRequireUnpremultipliedColors(bool request) { 122 fRequireUnpremultipliedColors = request; 123 } 124 125 /** Returns true if the decoder will only return bitmaps with unpremultiplied 126 colors. 127 */ 128 bool getRequireUnpremultipliedColors() const { return fRequireUnpremultipliedColors; } 129 130 SkPngChunkReader* getPeeker() const { return fPeeker; } 131 SkPngChunkReader* setPeeker(SkPngChunkReader*); 132 133 /** 134 * By default, the codec will try to comply with the "pref" colortype 135 * that is passed to decode() or decodeSubset(). However, this can be called 136 * to override that, causing the codec to try to match the src depth instead 137 * (as shown below). 138 * 139 * src_8Index -> kIndex_8_SkColorType 140 * src_8Gray -> kN32_SkColorType 141 * src_8bpc -> kN32_SkColorType 142 */ 143 void setPreserveSrcDepth(bool preserve) { 144 fPreserveSrcDepth = preserve; 145 } 146 147 SkBitmap::Allocator* getAllocator() const { return fAllocator; } 148 SkBitmap::Allocator* setAllocator(SkBitmap::Allocator*); 149 150 // sample-size, if set to > 1, tells the decoder to return a smaller than 151 // original bitmap, sampling 1 pixel for every size pixels. e.g. if sample 152 // size is set to 3, then the returned bitmap will be 1/3 as wide and high, 153 // and will contain 1/9 as many pixels as the original. 154 // Note: this is a hint, and the codec may choose to ignore this, or only 155 // approximate the sample size. 156 int getSampleSize() const { return fSampleSize; } 157 void setSampleSize(int size); 158 159 /** Reset the sampleSize to its default of 1 160 */ 161 void resetSampleSize() { this->setSampleSize(1); } 162 163 /** Decoding is synchronous, but for long decodes, a different thread can 164 call this method safely. This sets a state that the decoders will 165 periodically check, and if they see it changed to cancel, they will 166 cancel. This will result in decode() returning false. However, there is 167 no guarantee that the decoder will see the state change in time, so 168 it is possible that cancelDecode() will be called, but will be ignored 169 and decode() will return true (assuming no other problems were 170 encountered). 171 172 This state is automatically reset at the beginning of decode(). 173 */ 174 void cancelDecode() { 175 // now the subclass must query shouldCancelDecode() to be informed 176 // of the request 177 fShouldCancelDecode = true; 178 } 179 180 /** Passed to the decode method. If kDecodeBounds_Mode is passed, then 181 only the bitmap's info need be set. If kDecodePixels_Mode 182 is passed, then the bitmap must have pixels or a pixelRef. 183 */ 184 enum Mode { 185 kDecodeBounds_Mode, //!< only return info in bitmap 186 kDecodePixels_Mode //!< return entire bitmap (including pixels) 187 }; 188 189 /** Result of a decode. If read as a boolean, a partial success is 190 considered a success (true). 191 */ 192 enum Result { 193 kFailure = 0, //!< Image failed to decode. bitmap will be 194 // unchanged. 195 kPartialSuccess = 1, //!< Part of the image decoded. The rest is 196 // filled in automatically 197 kSuccess = 2 //!< The entire image was decoded, if Mode is 198 // kDecodePixels_Mode, or the bounds were 199 // decoded, in kDecodeBounds_Mode. 200 }; 201 202 /** Given a stream, decode it into the specified bitmap. 203 If the decoder can decompress the image, it calls bitmap.setInfo(), 204 and then if the Mode is kDecodePixels_Mode, call allocPixelRef(), 205 which will allocated a pixelRef. To access the pixel memory, the codec 206 needs to call lockPixels/unlockPixels on the 207 bitmap. It can then set the pixels with the decompressed image. 208 * If the image cannot be decompressed, return kFailure. After the 209 * decoding, the function converts the decoded colortype in bitmap 210 * to pref if possible. Whether a conversion is feasible is 211 * tested by Bitmap::canCopyTo(pref). 212 213 If an SkBitmap::Allocator is installed via setAllocator, it will be 214 used to allocate the pixel memory. A clever allocator can be used 215 to allocate the memory from a cache, volatile memory, or even from 216 an existing bitmap's memory. 217 218 If an SkPngChunkReader is installed via setPeeker, it may be used to 219 peek into meta data during the decode. 220 */ 221 Result decode(SkStream*, SkBitmap* bitmap, SkColorType pref, Mode); 222 Result decode(SkStream* stream, SkBitmap* bitmap, Mode mode) { 223 return this->decode(stream, bitmap, kUnknown_SkColorType, mode); 224 } 225 226 /** Given a stream, this will try to find an appropriate decoder object. 227 If none is found, the method returns NULL. 228 */ 229 static SkImageDecoder* Factory(SkStreamRewindable*); 230 231 /** Decode the image stored in the specified file, and store the result 232 in bitmap. Return true for success or false on failure. 233 234 @param pref Prefer this colortype. 235 236 @param format On success, if format is non-null, it is set to the format 237 of the decoded file. On failure it is ignored. 238 */ 239 static bool DecodeFile(const char file[], SkBitmap* bitmap, SkColorType pref, Mode, 240 Format* format = NULL); 241 static bool DecodeFile(const char file[], SkBitmap* bitmap) { 242 return DecodeFile(file, bitmap, kUnknown_SkColorType, kDecodePixels_Mode, NULL); 243 } 244 245 /** Decode the image stored in the specified memory buffer, and store the 246 result in bitmap. Return true for success or false on failure. 247 248 @param pref Prefer this colortype. 249 250 @param format On success, if format is non-null, it is set to the format 251 of the decoded buffer. On failure it is ignored. 252 */ 253 static bool DecodeMemory(const void* buffer, size_t size, SkBitmap* bitmap, SkColorType pref, 254 Mode, Format* format = NULL); 255 static bool DecodeMemory(const void* buffer, size_t size, SkBitmap* bitmap){ 256 return DecodeMemory(buffer, size, bitmap, kUnknown_SkColorType, kDecodePixels_Mode, NULL); 257 } 258 259 /** Decode the image stored in the specified SkStreamRewindable, and store the result 260 in bitmap. Return true for success or false on failure. 261 262 @param pref Prefer this colortype. 263 264 @param format On success, if format is non-null, it is set to the format 265 of the decoded stream. On failure it is ignored. 266 */ 267 static bool DecodeStream(SkStreamRewindable* stream, SkBitmap* bitmap, SkColorType pref, Mode, 268 Format* format = NULL); 269 static bool DecodeStream(SkStreamRewindable* stream, SkBitmap* bitmap) { 270 return DecodeStream(stream, bitmap, kUnknown_SkColorType, kDecodePixels_Mode, NULL); 271 } 272 273 protected: 274 // must be overridden in subclasses. This guy is called by decode(...) 275 virtual Result onDecode(SkStream*, SkBitmap* bitmap, Mode) = 0; 276 277 /** If planes or rowBytes is NULL, decodes the header and computes componentSizes 278 for memory allocation. 279 Otherwise, decodes the YUV planes into the provided image planes and 280 updates componentSizes to the final image size. 281 Returns whether the decoding was successful. 282 */ 283 virtual bool onDecodeYUV8Planes(SkStream*, SkISize[3] /*componentSizes*/, 284 void*[3] /*planes*/, size_t[3] /*rowBytes*/, 285 SkYUVColorSpace*) { 286 return false; 287 } 288 289 /** 290 * Copy all fields on this decoder to the other decoder. Used by subclasses 291 * to decode a subimage using a different decoder, but with the same settings. 292 */ 293 void copyFieldsToOther(SkImageDecoder* other); 294 295 /** Can be queried from within onDecode, to see if the user (possibly in 296 a different thread) has requested the decode to cancel. If this returns 297 true, your onDecode() should stop and return false. 298 Each subclass needs to decide how often it can query this, to balance 299 responsiveness with performance. 300 301 Calling this outside of onDecode() may return undefined values. 302 */ 303 304 public: 305 bool shouldCancelDecode() const { return fShouldCancelDecode; } 306 307 protected: 308 SkImageDecoder(); 309 310 /** 311 * Return the default preference being used by the current or latest call to decode. 312 */ 313 SkColorType getDefaultPref() { return fDefaultPref; } 314 315 /* Helper for subclasses. Call this to allocate the pixel memory given the bitmap's info. 316 Returns true on success. This method handles checking for an optional Allocator. 317 */ 318 bool allocPixelRef(SkBitmap*, SkColorTable*) const; 319 320 /** 321 * The raw data of the src image. 322 */ 323 enum SrcDepth { 324 // Color-indexed. 325 kIndex_SrcDepth, 326 // Grayscale in 8 bits. 327 k8BitGray_SrcDepth, 328 // 8 bits per component. Used for 24 bit if there is no alpha. 329 k32Bit_SrcDepth, 330 }; 331 /** The subclass, inside onDecode(), calls this to determine the colorType of 332 the returned bitmap. SrcDepth and hasAlpha reflect the raw data of the 333 src image. This routine returns the caller's preference given 334 srcDepth and hasAlpha, or kUnknown_SkColorType if there is no preference. 335 */ 336 SkColorType getPrefColorType(SrcDepth, bool hasAlpha) const; 337 338 private: 339 SkPngChunkReader* fPeeker; 340 SkBitmap::Allocator* fAllocator; 341 int fSampleSize; 342 SkColorType fDefaultPref; // use if fUsePrefTable is false 343 bool fPreserveSrcDepth; 344 bool fDitherImage; 345 bool fSkipWritingZeroes; 346 mutable bool fShouldCancelDecode; 347 bool fPreferQualityOverSpeed; 348 bool fRequireUnpremultipliedColors; 349 }; 350 351 /** Calling newDecoder with a stream returns a new matching imagedecoder 352 instance, or NULL if none can be found. The caller must manage its ownership 353 of the stream as usual, calling unref() when it is done, as the returned 354 decoder may have called ref() (and if so, the decoder is responsible for 355 balancing its ownership when it is destroyed). 356 */ 357 class SkImageDecoderFactory : public SkRefCnt { 358 public: 359 360 361 virtual SkImageDecoder* newDecoder(SkStreamRewindable*) = 0; 362 363 private: 364 typedef SkRefCnt INHERITED; 365 }; 366 367 class SkDefaultImageDecoderFactory : SkImageDecoderFactory { 368 public: 369 // calls SkImageDecoder::Factory(stream) 370 virtual SkImageDecoder* newDecoder(SkStreamRewindable* stream) { 371 return SkImageDecoder::Factory(stream); 372 } 373 }; 374 375 // This macro declares a global (i.e., non-class owned) creation entry point 376 // for each decoder (e.g., CreateJPEGImageDecoder) 377 #define DECLARE_DECODER_CREATOR(codec) \ 378 SkImageDecoder *Create ## codec (); 379 380 // This macro defines the global creation entry point for each decoder. Each 381 // decoder implementation that registers with the decoder factory must call it. 382 #define DEFINE_DECODER_CREATOR(codec) \ 383 SkImageDecoder* Create##codec() { return new Sk##codec; } 384 385 // All the decoders known by Skia. Note that, depending on the compiler settings, 386 // not all of these will be available 387 DECLARE_DECODER_CREATOR(BMPImageDecoder); 388 DECLARE_DECODER_CREATOR(GIFImageDecoder); 389 DECLARE_DECODER_CREATOR(ICOImageDecoder); 390 DECLARE_DECODER_CREATOR(JPEGImageDecoder); 391 DECLARE_DECODER_CREATOR(PNGImageDecoder); 392 DECLARE_DECODER_CREATOR(WBMPImageDecoder); 393 DECLARE_DECODER_CREATOR(WEBPImageDecoder); 394 DECLARE_DECODER_CREATOR(PKMImageDecoder); 395 DECLARE_DECODER_CREATOR(KTXImageDecoder); 396 DECLARE_DECODER_CREATOR(ASTCImageDecoder); 397 398 // Typedefs to make registering decoder and formatter callbacks easier. 399 // These have to be defined outside SkImageDecoder. :( 400 typedef SkTRegistry<SkImageDecoder*(*)(SkStreamRewindable*)> SkImageDecoder_DecodeReg; 401 typedef SkTRegistry<SkImageDecoder::Format(*)(SkStreamRewindable*)> SkImageDecoder_FormatReg; 402 403 #endif 404