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 "SkRect.h" 15 #include "SkRefCnt.h" 16 17 class SkStream; 18 19 class SkVMMemoryReporter : public SkRefCnt { 20 public: 21 virtual ~SkVMMemoryReporter(); 22 virtual bool reportMemory(size_t memorySize) = 0; 23 }; 24 25 /** \class SkImageDecoder 26 27 Base class for decoding compressed images into a SkBitmap 28 */ 29 class SkImageDecoder { 30 public: 31 virtual ~SkImageDecoder(); 32 33 // Should be consistent with kFormatName 34 enum Format { 35 kUnknown_Format, 36 kBMP_Format, 37 kGIF_Format, 38 kICO_Format, 39 kJPEG_Format, 40 kPNG_Format, 41 kWBMP_Format, 42 kWEBP_Format, 43 44 kLastKnownFormat = kWEBP_Format 45 }; 46 47 /** Contains the image format name. 48 * This should be consistent with Format. 49 * 50 * The format name gives a more meaningful error message than enum. 51 */ 52 static const char *kFormatName[8]; 53 54 /** Return the compressed data's format (see Format enum) 55 */ 56 virtual Format getFormat() const; 57 58 /** Return the compressed data's format name. 59 */ 60 const char* getFormatName() const { return kFormatName[getFormat()]; } 61 62 /** Returns true if the decoder should try to dither the resulting image. 63 The default setting is true. 64 */ 65 bool getDitherImage() const { return fDitherImage; } 66 67 /** Set to true if the the decoder should try to dither the resulting image. 68 The default setting is true. 69 */ 70 void setDitherImage(bool dither) { fDitherImage = dither; } 71 72 /** Returns true if the decoder should try to decode the 73 resulting image to a higher quality even at the expense of 74 the decoding speed. 75 */ 76 bool getPreferQualityOverSpeed() const { return fPreferQualityOverSpeed; } 77 78 /** Set to true if the the decoder should try to decode the 79 resulting image to a higher quality even at the expense of 80 the decoding speed. 81 */ 82 void setPreferQualityOverSpeed(bool qualityOverSpeed) { 83 fPreferQualityOverSpeed = qualityOverSpeed; 84 } 85 86 /** \class Peeker 87 88 Base class for optional callbacks to retrieve meta/chunk data out of 89 an image as it is being decoded. 90 */ 91 class Peeker : public SkRefCnt { 92 public: 93 /** Return true to continue decoding, or false to indicate an error, which 94 will cause the decoder to not return the image. 95 */ 96 virtual bool peek(const char tag[], const void* data, size_t length) = 0; 97 }; 98 99 Peeker* getPeeker() const { return fPeeker; } 100 Peeker* setPeeker(Peeker*); 101 102 /** \class Peeker 103 104 Base class for optional callbacks to retrieve meta/chunk data out of 105 an image as it is being decoded. 106 */ 107 class Chooser : public SkRefCnt { 108 public: 109 virtual void begin(int count) {} 110 virtual void inspect(int index, SkBitmap::Config config, int width, int height) {} 111 /** Return the index of the subimage you want, or -1 to choose none of them. 112 */ 113 virtual int choose() = 0; 114 }; 115 116 Chooser* getChooser() const { return fChooser; } 117 Chooser* setChooser(Chooser*); 118 119 /** This optional table describes the caller's preferred config based on 120 information about the src data. For this table, the src attributes are 121 described in terms of depth (index (8), 16, 32/24) and if there is 122 per-pixel alpha. These inputs combine to create an index into the 123 pref[] table, which contains the caller's preferred config for that 124 input, or kNo_Config if there is no preference. 125 126 To specify no preferrence, call setPrefConfigTable(NULL), which is 127 the default. 128 129 Note, it is still at the discretion of the codec as to what output 130 config is actually returned, as it may not be able to support the 131 caller's preference. 132 133 Here is how the index into the table is computed from the src: 134 depth [8, 16, 32/24] -> 0, 2, 4 135 alpha [no, yes] -> 0, 1 136 The two index values are OR'd together. 137 src: 8-index, no-alpha -> 0 138 src: 8-index, yes-alpha -> 1 139 src: 16bit, no-alpha -> 2 // e.g. 565 140 src: 16bit, yes-alpha -> 3 // e.g. 1555 141 src: 32/24, no-alpha -> 4 142 src: 32/24, yes-alpha -> 5 143 */ 144 void setPrefConfigTable(const SkBitmap::Config pref[6]); 145 146 SkBitmap::Allocator* getAllocator() const { return fAllocator; } 147 SkBitmap::Allocator* setAllocator(SkBitmap::Allocator*); 148 SkVMMemoryReporter* setReporter(SkVMMemoryReporter*); 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 width/height/config 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 width/height/config in bitmap 186 kDecodePixels_Mode //!< return entire bitmap (including pixels) 187 }; 188 189 /** Given a stream, decode it into the specified bitmap. 190 If the decoder can decompress the image, it calls bitmap.setConfig(), 191 and then if the Mode is kDecodePixels_Mode, call allocPixelRef(), 192 which will allocated a pixelRef. To access the pixel memory, the codec 193 needs to call lockPixels/unlockPixels on the 194 bitmap. It can then set the pixels with the decompressed image. 195 * If the image cannot be decompressed, return false. After the 196 * decoding, the function converts the decoded config in bitmap 197 * to pref if possible. Whether a conversion is feasible is 198 * tested by Bitmap::canCopyTo(pref). 199 200 note: document use of Allocator, Peeker and Chooser 201 */ 202 bool decode(SkStream*, SkBitmap* bitmap, SkBitmap::Config pref, Mode, bool reuseBitmap = false); 203 bool decode(SkStream* stream, SkBitmap* bitmap, Mode mode, bool reuseBitmap = false) { 204 return this->decode(stream, bitmap, SkBitmap::kNo_Config, mode, reuseBitmap); 205 } 206 207 /** 208 * Given a stream, build an index for doing tile-based decode. 209 * The built index will be saved in the decoder, and the image size will 210 * be returned in width and height. 211 * 212 * Return true for success or false on failure. 213 */ 214 virtual bool buildTileIndex(SkStream*, 215 int *width, int *height); 216 217 /** 218 * Decode a rectangle region in the image specified by rect. 219 * The method can only be called after buildTileIndex(). 220 * 221 * Return true for success. 222 * Return false if the index is never built or failing in decoding. 223 */ 224 virtual bool decodeRegion(SkBitmap* bitmap, SkIRect rect, 225 SkBitmap::Config pref); 226 227 /** Given a stream, this will try to find an appropriate decoder object. 228 If none is found, the method returns NULL. 229 */ 230 static SkImageDecoder* Factory(SkStream*); 231 232 /** Decode the image stored in the specified file, and store the result 233 in bitmap. Return true for success or false on failure. 234 235 If pref is kNo_Config, then the decoder is free to choose the most natural 236 config given the image data. If pref something other than kNo_Config, 237 the decoder will attempt to decode the image into that format, unless 238 there is a conflict (e.g. the image has per-pixel alpha and the bitmap's 239 config does not support that), in which case the decoder will choose a 240 closest match configuration. 241 242 @param format On success, if format is non-null, it is set to the format 243 of the decoded file. On failure it is ignored. 244 */ 245 static bool DecodeFile(const char file[], SkBitmap* bitmap, 246 SkBitmap::Config prefConfig, Mode, 247 Format* format = NULL); 248 static bool DecodeFile(const char file[], SkBitmap* bitmap) { 249 return DecodeFile(file, bitmap, SkBitmap::kNo_Config, 250 kDecodePixels_Mode, NULL); 251 } 252 /** Decode the image stored in the specified memory buffer, and store the 253 result in bitmap. Return true for success or false on failure. 254 255 If pref is kNo_Config, then the decoder is free to choose the most natural 256 config given the image data. If pref something other than kNo_Config, 257 the decoder will attempt to decode the image into that format, unless 258 there is a conflict (e.g. the image has per-pixel alpha and the bitmap's 259 config does not support that), in which case the decoder will choose a 260 closest match configuration. 261 262 @param format On success, if format is non-null, it is set to the format 263 of the decoded buffer. On failure it is ignored. 264 */ 265 static bool DecodeMemory(const void* buffer, size_t size, SkBitmap* bitmap, 266 SkBitmap::Config prefConfig, Mode, 267 Format* format = NULL); 268 static bool DecodeMemory(const void* buffer, size_t size, SkBitmap* bitmap){ 269 return DecodeMemory(buffer, size, bitmap, SkBitmap::kNo_Config, 270 kDecodePixels_Mode, NULL); 271 } 272 /** Decode the image stored in the specified SkStream, and store the result 273 in bitmap. Return true for success or false on failure. 274 275 If pref is kNo_Config, then the decoder is free to choose the most 276 natural config given the image data. If pref something other than 277 kNo_Config, the decoder will attempt to decode the image into that 278 format, unless there is a conflict (e.g. the image has per-pixel alpha 279 and the bitmap's config does not support that), in which case the 280 decoder will choose a closest match configuration. 281 282 @param format On success, if format is non-null, it is set to the format 283 of the decoded stream. On failure it is ignored. 284 */ 285 static bool DecodeStream(SkStream* stream, SkBitmap* bitmap, 286 SkBitmap::Config prefConfig, Mode, 287 Format* format = NULL); 288 static bool DecodeStream(SkStream* stream, SkBitmap* bitmap) { 289 return DecodeStream(stream, bitmap, SkBitmap::kNo_Config, 290 kDecodePixels_Mode, NULL); 291 } 292 293 /** Return the default config for the running device. 294 Currently this used as a suggestion to image decoders that need to guess 295 what config they should decode into. 296 Default is kNo_Config, but this can be changed with SetDeviceConfig() 297 */ 298 static SkBitmap::Config GetDeviceConfig(); 299 /** Set the default config for the running device. 300 Currently this used as a suggestion to image decoders that need to guess 301 what config they should decode into. 302 Default is kNo_Config. 303 This can be queried with GetDeviceConfig() 304 */ 305 static void SetDeviceConfig(SkBitmap::Config); 306 307 /** @cond UNIT_TEST */ 308 SkDEBUGCODE(static void UnitTest();) 309 /** @endcond */ 310 311 protected: 312 // must be overridden in subclasses. This guy is called by decode(...) 313 virtual bool onDecode(SkStream*, SkBitmap* bitmap, Mode) = 0; 314 315 // If the decoder wants to support tiled based decoding, 316 // this method must be overridden. This guy is called by buildTileIndex(...) 317 virtual bool onBuildTileIndex(SkStream*, 318 int *width, int *height) { 319 return false; 320 } 321 322 // If the decoder wants to support tiled based decoding, 323 // this method must be overridden. This guy is called by decodeRegion(...) 324 virtual bool onDecodeRegion(SkBitmap* bitmap, SkIRect rect) { 325 return false; 326 } 327 328 /* 329 * Crop a rectangle from the src Bitmap to the dest Bitmap. src and dest are 330 * both sampled by sampleSize from an original Bitmap. 331 * 332 * @param dest the destination Bitmap. 333 * @param src the source Bitmap that is sampled by sampleSize from the original 334 * Bitmap. 335 * @param sampleSize the sample size that src is sampled from the original Bitmap. 336 * @param (srcX, srcY) the upper-left point of the src Btimap in terms of 337 * the coordinate in the original Bitmap. 338 * @param (width, height) the width and height of the unsampled dest. 339 * @param (destX, destY) the upper-left point of the dest Bitmap in terms of 340 * the coordinate in the original Bitmap. 341 */ 342 virtual void cropBitmap(SkBitmap *dest, SkBitmap *src, int sampleSize, 343 int destX, int destY, int width, int height, 344 int srcX, int srcY); 345 346 347 348 /** Can be queried from within onDecode, to see if the user (possibly in 349 a different thread) has requested the decode to cancel. If this returns 350 true, your onDecode() should stop and return false. 351 Each subclass needs to decide how often it can query this, to balance 352 responsiveness with performance. 353 354 Calling this outside of onDecode() may return undefined values. 355 */ 356 357 public: 358 bool shouldCancelDecode() const { return fShouldCancelDecode; } 359 360 protected: 361 SkImageDecoder(); 362 363 // helper function for decoders to handle the (common) case where there is only 364 // once choice available in the image file. 365 bool chooseFromOneChoice(SkBitmap::Config config, int width, int height) const; 366 367 /* Helper for subclasses. Call this to allocate the pixel memory given the bitmap's 368 width/height/rowbytes/config. Returns true on success. This method handles checking 369 for an optional Allocator. 370 */ 371 bool allocPixelRef(SkBitmap*, SkColorTable*) const; 372 373 enum SrcDepth { 374 kIndex_SrcDepth, 375 k16Bit_SrcDepth, 376 k32Bit_SrcDepth 377 }; 378 /** The subclass, inside onDecode(), calls this to determine the config of 379 the returned bitmap. SrcDepth and hasAlpha reflect the raw data of the 380 src image. This routine returns the caller's preference given 381 srcDepth and hasAlpha, or kNo_Config if there is no preference. 382 383 Note: this also takes into account GetDeviceConfig(), so the subclass 384 need not call that. 385 */ 386 SkBitmap::Config getPrefConfig(SrcDepth, bool hasAlpha) const; 387 388 SkVMMemoryReporter* fReporter; 389 390 private: 391 Peeker* fPeeker; 392 Chooser* fChooser; 393 SkBitmap::Allocator* fAllocator; 394 int fSampleSize; 395 SkBitmap::Config fDefaultPref; // use if fUsePrefTable is false 396 SkBitmap::Config fPrefTable[6]; // use if fUsePrefTable is true 397 bool fDitherImage; 398 bool fUsePrefTable; 399 mutable bool fShouldCancelDecode; 400 bool fPreferQualityOverSpeed; 401 402 // illegal 403 SkImageDecoder(const SkImageDecoder&); 404 SkImageDecoder& operator=(const SkImageDecoder&); 405 }; 406 407 /** Calling newDecoder with a stream returns a new matching imagedecoder 408 instance, or NULL if none can be found. The caller must manage its ownership 409 of the stream as usual, calling unref() when it is done, as the returned 410 decoder may have called ref() (and if so, the decoder is responsible for 411 balancing its ownership when it is destroyed). 412 */ 413 class SkImageDecoderFactory : public SkRefCnt { 414 public: 415 virtual SkImageDecoder* newDecoder(SkStream*) = 0; 416 }; 417 418 class SkDefaultImageDecoderFactory : SkImageDecoderFactory { 419 public: 420 // calls SkImageDecoder::Factory(stream) 421 virtual SkImageDecoder* newDecoder(SkStream* stream) { 422 return SkImageDecoder::Factory(stream); 423 } 424 }; 425 426 427 #endif 428