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