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 "SkRect.h" 14 #include "SkRefCnt.h" 15 #include "SkTRegistry.h" 16 #include "SkTypes.h" 17 18 class SkStream; 19 class SkStreamRewindable; 20 21 /** \class SkImageDecoder 22 23 Base class for decoding compressed images into a SkBitmap 24 */ 25 class SkImageDecoder : SkNoncopyable { 26 public: 27 virtual ~SkImageDecoder(); 28 29 enum Format { 30 kUnknown_Format, 31 kBMP_Format, 32 kGIF_Format, 33 kICO_Format, 34 kJPEG_Format, 35 kPNG_Format, 36 kWBMP_Format, 37 kWEBP_Format, 38 kPKM_Format, 39 kKTX_Format, 40 kASTC_Format, 41 42 kLastKnownFormat = kKTX_Format, 43 }; 44 45 /** Return the format of image this decoder can decode. If this decoder can decode multiple 46 formats, kUnknown_Format will be returned. 47 */ 48 virtual Format getFormat() const; 49 50 /** Return the format of the SkStreamRewindable or kUnknown_Format if it cannot be determined. 51 Rewinds the stream before returning. 52 */ 53 static Format GetStreamFormat(SkStreamRewindable*); 54 55 /** Return a readable string of the Format provided. 56 */ 57 static const char* GetFormatName(Format); 58 59 /** Return a readable string of the value returned by getFormat(). 60 */ 61 const char* getFormatName() const; 62 63 /** Whether the decoder should skip writing zeroes to output if possible. 64 */ 65 bool getSkipWritingZeroes() const { return fSkipWritingZeroes; } 66 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 72 have garbage. 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. 76 The default is false. 77 */ 78 void setSkipWritingZeroes(bool skip) { fSkipWritingZeroes = skip; } 79 80 /** Returns true if the decoder should try to dither the resulting image. 81 The default setting is true. 82 */ 83 bool getDitherImage() const { return fDitherImage; } 84 85 /** Set to true if the the decoder should try to dither the resulting image. 86 The default setting is true. 87 */ 88 void setDitherImage(bool dither) { fDitherImage = dither; } 89 90 /** Returns true if the decoder should try to decode the 91 resulting image to a higher quality even at the expense of 92 the decoding speed. 93 */ 94 bool getPreferQualityOverSpeed() const { return fPreferQualityOverSpeed; } 95 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 98 the decoding speed. 99 */ 100 void setPreferQualityOverSpeed(bool qualityOverSpeed) { 101 fPreferQualityOverSpeed = qualityOverSpeed; 102 } 103 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. 109 */ 110 void setRequireUnpremultipliedColors(bool request) { 111 fRequireUnpremultipliedColors = request; 112 } 113 114 /** Returns true if the decoder will only return bitmaps with unpremultiplied 115 colors. 116 */ 117 bool getRequireUnpremultipliedColors() const { return fRequireUnpremultipliedColors; } 118 119 /** \class Peeker 120 121 Base class for optional callbacks to retrieve meta/chunk data out of 122 an image as it is being decoded. 123 */ 124 class Peeker : public SkRefCnt { 125 public: 126 SK_DECLARE_INST_COUNT(Peeker) 127 128 /** Return true to continue decoding, or false to indicate an error, which 129 will cause the decoder to not return the image. 130 */ 131 virtual bool peek(const char tag[], const void* data, size_t length) = 0; 132 private: 133 typedef SkRefCnt INHERITED; 134 }; 135 136 Peeker* getPeeker() const { return fPeeker; } 137 Peeker* setPeeker(Peeker*); 138 139 #ifdef SK_SUPPORT_LEGACY_IMAGEDECODER_CHOOSER 140 /** \class Chooser 141 142 Base class for optional callbacks to choose an image from a format that 143 contains multiple images. 144 */ 145 class Chooser : public SkRefCnt { 146 public: 147 SK_DECLARE_INST_COUNT(Chooser) 148 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. 152 */ 153 virtual int choose() = 0; 154 155 private: 156 typedef SkRefCnt INHERITED; 157 }; 158 159 Chooser* getChooser() const { return fChooser; } 160 Chooser* setChooser(Chooser*); 161 #endif 162 163 /** 164 * By default, the codec will try to comply with the "pref" colortype 165 * that is passed to decode() or decodeSubset(). However, this can be called 166 * to override that, causing the codec to try to match the src depth instead 167 * (as shown below). 168 * 169 * src_8Index -> kIndex_8_SkColorType 170 * src_8Gray -> kN32_SkColorType 171 * src_8bpc -> kN32_SkColorType 172 */ 173 void setPreserveSrcDepth(bool preserve) { 174 fPreserveSrcDepth = preserve; 175 } 176 177 SkBitmap::Allocator* getAllocator() const { return fAllocator; } 178 SkBitmap::Allocator* setAllocator(SkBitmap::Allocator*); 179 180 // sample-size, if set to > 1, tells the decoder to return a smaller than 181 // original bitmap, sampling 1 pixel for every size pixels. e.g. if sample 182 // size is set to 3, then the returned bitmap will be 1/3 as wide and high, 183 // and will contain 1/9 as many pixels as the original. 184 // Note: this is a hint, and the codec may choose to ignore this, or only 185 // approximate the sample size. 186 int getSampleSize() const { return fSampleSize; } 187 void setSampleSize(int size); 188 189 /** Reset the sampleSize to its default of 1 190 */ 191 void resetSampleSize() { this->setSampleSize(1); } 192 193 /** Decoding is synchronous, but for long decodes, a different thread can 194 call this method safely. This sets a state that the decoders will 195 periodically check, and if they see it changed to cancel, they will 196 cancel. This will result in decode() returning false. However, there is 197 no guarantee that the decoder will see the state change in time, so 198 it is possible that cancelDecode() will be called, but will be ignored 199 and decode() will return true (assuming no other problems were 200 encountered). 201 202 This state is automatically reset at the beginning of decode(). 203 */ 204 void cancelDecode() { 205 // now the subclass must query shouldCancelDecode() to be informed 206 // of the request 207 fShouldCancelDecode = true; 208 } 209 210 /** Passed to the decode method. If kDecodeBounds_Mode is passed, then 211 only the bitmap's info need be set. If kDecodePixels_Mode 212 is passed, then the bitmap must have pixels or a pixelRef. 213 */ 214 enum Mode { 215 kDecodeBounds_Mode, //!< only return info in bitmap 216 kDecodePixels_Mode //!< return entire bitmap (including pixels) 217 }; 218 219 /** Given a stream, decode it into the specified bitmap. 220 If the decoder can decompress the image, it calls bitmap.setInfo(), 221 and then if the Mode is kDecodePixels_Mode, call allocPixelRef(), 222 which will allocated a pixelRef. To access the pixel memory, the codec 223 needs to call lockPixels/unlockPixels on the 224 bitmap. It can then set the pixels with the decompressed image. 225 * If the image cannot be decompressed, return false. After the 226 * decoding, the function converts the decoded colortype in bitmap 227 * to pref if possible. Whether a conversion is feasible is 228 * tested by Bitmap::canCopyTo(pref). 229 230 If an SkBitmap::Allocator is installed via setAllocator, it will be 231 used to allocate the pixel memory. A clever allocator can be used 232 to allocate the memory from a cache, volatile memory, or even from 233 an existing bitmap's memory. 234 235 If a Peeker is installed via setPeeker, it may be used to peek into 236 meta data during the decode. 237 */ 238 bool decode(SkStream*, SkBitmap* bitmap, SkColorType pref, Mode); 239 bool decode(SkStream* stream, SkBitmap* bitmap, Mode mode) { 240 return this->decode(stream, bitmap, kUnknown_SkColorType, mode); 241 } 242 243 /** 244 * Given a stream, build an index for doing tile-based decode. 245 * The built index will be saved in the decoder, and the image size will 246 * be returned in width and height. 247 * 248 * Return true for success or false on failure. 249 */ 250 bool buildTileIndex(SkStreamRewindable*, int *width, int *height); 251 252 /** 253 * Decode a rectangle subset in the image. 254 * The method can only be called after buildTileIndex(). 255 * 256 * Return true for success. 257 * Return false if the index is never built or failing in decoding. 258 */ 259 bool decodeSubset(SkBitmap* bm, const SkIRect& subset, SkColorType pref); 260 261 /** Given a stream, this will try to find an appropriate decoder object. 262 If none is found, the method returns NULL. 263 */ 264 static SkImageDecoder* Factory(SkStreamRewindable*); 265 266 /** Decode the image stored in the specified file, and store the result 267 in bitmap. Return true for success or false on failure. 268 269 @param pref If the PrefConfigTable is not set, prefer this colortype. 270 See NOTE ABOUT PREFERRED CONFIGS. 271 272 @param format On success, if format is non-null, it is set to the format 273 of the decoded file. On failure it is ignored. 274 */ 275 static bool DecodeFile(const char file[], SkBitmap* bitmap, SkColorType pref, Mode, 276 Format* format = NULL); 277 static bool DecodeFile(const char file[], SkBitmap* bitmap) { 278 return DecodeFile(file, bitmap, kUnknown_SkColorType, kDecodePixels_Mode, NULL); 279 } 280 281 /** Decode the image stored in the specified memory buffer, and store the 282 result in bitmap. Return true for success or false on failure. 283 284 @param pref If the PrefConfigTable is not set, prefer this colortype. 285 See NOTE ABOUT PREFERRED CONFIGS. 286 287 @param format On success, if format is non-null, it is set to the format 288 of the decoded buffer. On failure it is ignored. 289 */ 290 static bool DecodeMemory(const void* buffer, size_t size, SkBitmap* bitmap, SkColorType pref, 291 Mode, Format* format = NULL); 292 static bool DecodeMemory(const void* buffer, size_t size, SkBitmap* bitmap){ 293 return DecodeMemory(buffer, size, bitmap, kUnknown_SkColorType, kDecodePixels_Mode, NULL); 294 } 295 296 /** 297 * Struct containing information about a pixel destination. 298 */ 299 struct Target { 300 /** 301 * Pre-allocated memory. 302 */ 303 void* fAddr; 304 305 /** 306 * Rowbytes of the allocated memory. 307 */ 308 size_t fRowBytes; 309 }; 310 311 /** Decode the image stored in the specified SkStreamRewindable, and store the result 312 in bitmap. Return true for success or false on failure. 313 314 @param pref If the PrefConfigTable is not set, prefer this colortype. 315 See NOTE ABOUT PREFERRED CONFIGS. 316 317 @param format On success, if format is non-null, it is set to the format 318 of the decoded stream. On failure it is ignored. 319 */ 320 static bool DecodeStream(SkStreamRewindable* stream, SkBitmap* bitmap, SkColorType pref, Mode, 321 Format* format = NULL); 322 static bool DecodeStream(SkStreamRewindable* stream, SkBitmap* bitmap) { 323 return DecodeStream(stream, bitmap, kUnknown_SkColorType, kDecodePixels_Mode, NULL); 324 } 325 326 protected: 327 // must be overridden in subclasses. This guy is called by decode(...) 328 virtual bool onDecode(SkStream*, SkBitmap* bitmap, Mode) = 0; 329 330 // If the decoder wants to support tiled based decoding, 331 // this method must be overridden. This guy is called by buildTileIndex(...) 332 virtual bool onBuildTileIndex(SkStreamRewindable*, int *width, int *height) { 333 return false; 334 } 335 336 // If the decoder wants to support tiled based decoding, 337 // this method must be overridden. This guy is called by decodeRegion(...) 338 virtual bool onDecodeSubset(SkBitmap* bitmap, const SkIRect& rect) { 339 return false; 340 } 341 342 /* 343 * Crop a rectangle from the src Bitmap to the dest Bitmap. src and dst are 344 * both sampled by sampleSize from an original Bitmap. 345 * 346 * @param dst the destination bitmap. 347 * @param src the source bitmap that is sampled by sampleSize from the 348 * original bitmap. 349 * @param sampleSize the sample size that src is sampled from the original bitmap. 350 * @param (dstX, dstY) the upper-left point of the dest bitmap in terms of 351 * the coordinate in the original bitmap. 352 * @param (width, height) the width and height of the unsampled dst. 353 * @param (srcX, srcY) the upper-left point of the src bitmap in terms of 354 * the coordinate in the original bitmap. 355 * @return bool Whether or not it succeeded. 356 */ 357 bool cropBitmap(SkBitmap *dst, SkBitmap *src, int sampleSize, 358 int dstX, int dstY, int width, int height, 359 int srcX, int srcY); 360 361 /** 362 * Copy all fields on this decoder to the other decoder. Used by subclasses 363 * to decode a subimage using a different decoder, but with the same settings. 364 */ 365 void copyFieldsToOther(SkImageDecoder* other); 366 367 /** Can be queried from within onDecode, to see if the user (possibly in 368 a different thread) has requested the decode to cancel. If this returns 369 true, your onDecode() should stop and return false. 370 Each subclass needs to decide how often it can query this, to balance 371 responsiveness with performance. 372 373 Calling this outside of onDecode() may return undefined values. 374 */ 375 376 public: 377 bool shouldCancelDecode() const { return fShouldCancelDecode; } 378 379 protected: 380 SkImageDecoder(); 381 382 /** 383 * Return the default preference being used by the current or latest call to decode. 384 */ 385 SkColorType getDefaultPref() { return fDefaultPref; } 386 387 #ifdef SK_SUPPORT_LEGACY_IMAGEDECODER_CHOOSER 388 // helper function for decoders to handle the (common) case where there is only 389 // once choice available in the image file. 390 bool chooseFromOneChoice(SkColorType, int width, int height) const; 391 #endif 392 393 /* Helper for subclasses. Call this to allocate the pixel memory given the bitmap's info. 394 Returns true on success. This method handles checking for an optional Allocator. 395 */ 396 bool allocPixelRef(SkBitmap*, SkColorTable*) const; 397 398 /** 399 * The raw data of the src image. 400 */ 401 enum SrcDepth { 402 // Color-indexed. 403 kIndex_SrcDepth, 404 // Grayscale in 8 bits. 405 k8BitGray_SrcDepth, 406 // 8 bits per component. Used for 24 bit if there is no alpha. 407 k32Bit_SrcDepth, 408 }; 409 /** The subclass, inside onDecode(), calls this to determine the colorType of 410 the returned bitmap. SrcDepth and hasAlpha reflect the raw data of the 411 src image. This routine returns the caller's preference given 412 srcDepth and hasAlpha, or kUnknown_SkColorType if there is no preference. 413 */ 414 SkColorType getPrefColorType(SrcDepth, bool hasAlpha) const; 415 416 private: 417 Peeker* fPeeker; 418 #ifdef SK_SUPPORT_LEGACY_IMAGEDECODER_CHOOSER 419 Chooser* fChooser; 420 #endif 421 SkBitmap::Allocator* fAllocator; 422 int fSampleSize; 423 SkColorType fDefaultPref; // use if fUsePrefTable is false 424 bool fPreserveSrcDepth; 425 bool fDitherImage; 426 bool fSkipWritingZeroes; 427 mutable bool fShouldCancelDecode; 428 bool fPreferQualityOverSpeed; 429 bool fRequireUnpremultipliedColors; 430 }; 431 432 /** Calling newDecoder with a stream returns a new matching imagedecoder 433 instance, or NULL if none can be found. The caller must manage its ownership 434 of the stream as usual, calling unref() when it is done, as the returned 435 decoder may have called ref() (and if so, the decoder is responsible for 436 balancing its ownership when it is destroyed). 437 */ 438 class SkImageDecoderFactory : public SkRefCnt { 439 public: 440 SK_DECLARE_INST_COUNT(SkImageDecoderFactory) 441 442 virtual SkImageDecoder* newDecoder(SkStreamRewindable*) = 0; 443 444 private: 445 typedef SkRefCnt INHERITED; 446 }; 447 448 class SkDefaultImageDecoderFactory : SkImageDecoderFactory { 449 public: 450 // calls SkImageDecoder::Factory(stream) 451 virtual SkImageDecoder* newDecoder(SkStreamRewindable* stream) { 452 return SkImageDecoder::Factory(stream); 453 } 454 }; 455 456 // This macro declares a global (i.e., non-class owned) creation entry point 457 // for each decoder (e.g., CreateJPEGImageDecoder) 458 #define DECLARE_DECODER_CREATOR(codec) \ 459 SkImageDecoder *Create ## codec (); 460 461 // This macro defines the global creation entry point for each decoder. Each 462 // decoder implementation that registers with the decoder factory must call it. 463 #define DEFINE_DECODER_CREATOR(codec) \ 464 SkImageDecoder *Create ## codec () { \ 465 return SkNEW( Sk ## codec ); \ 466 } 467 468 // All the decoders known by Skia. Note that, depending on the compiler settings, 469 // not all of these will be available 470 DECLARE_DECODER_CREATOR(BMPImageDecoder); 471 DECLARE_DECODER_CREATOR(GIFImageDecoder); 472 DECLARE_DECODER_CREATOR(ICOImageDecoder); 473 DECLARE_DECODER_CREATOR(JPEGImageDecoder); 474 DECLARE_DECODER_CREATOR(PNGImageDecoder); 475 DECLARE_DECODER_CREATOR(WBMPImageDecoder); 476 DECLARE_DECODER_CREATOR(WEBPImageDecoder); 477 DECLARE_DECODER_CREATOR(PKMImageDecoder); 478 DECLARE_DECODER_CREATOR(KTXImageDecoder); 479 DECLARE_DECODER_CREATOR(ASTCImageDecoder); 480 481 // Typedefs to make registering decoder and formatter callbacks easier. 482 // These have to be defined outside SkImageDecoder. :( 483 typedef SkTRegistry<SkImageDecoder*(*)(SkStreamRewindable*)> SkImageDecoder_DecodeReg; 484 typedef SkTRegistry<SkImageDecoder::Format(*)(SkStreamRewindable*)> SkImageDecoder_FormatReg; 485 486 #endif 487