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