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