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