• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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     */
getFormatName()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     */
getDitherImage()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     */
setDitherImage(bool dither)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     */
getPreferQualityOverSpeed()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     */
setPreferQualityOverSpeed(bool qualityOverSpeed)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         SK_DECLARE_INST_COUNT(Peeker)
94 
95         /** Return true to continue decoding, or false to indicate an error, which
96             will cause the decoder to not return the image.
97         */
98         virtual bool peek(const char tag[], const void* data, size_t length) = 0;
99     private:
100         typedef SkRefCnt INHERITED;
101     };
102 
getPeeker()103     Peeker* getPeeker() const { return fPeeker; }
104     Peeker* setPeeker(Peeker*);
105 
106     /** \class Peeker
107 
108         Base class for optional callbacks to retrieve meta/chunk data out of
109         an image as it is being decoded.
110     */
111     class Chooser : public SkRefCnt {
112     public:
SK_DECLARE_INST_COUNT(Chooser)113         SK_DECLARE_INST_COUNT(Chooser)
114 
115         virtual void begin(int count) {}
inspect(int index,SkBitmap::Config config,int width,int height)116         virtual void inspect(int index, SkBitmap::Config config, int width, int height) {}
117         /** Return the index of the subimage you want, or -1 to choose none of them.
118         */
119         virtual int choose() = 0;
120 
121     private:
122         typedef SkRefCnt INHERITED;
123     };
124 
getChooser()125     Chooser* getChooser() const { return fChooser; }
126     Chooser* setChooser(Chooser*);
127 
128     /** This optional table describes the caller's preferred config based on
129         information about the src data. For this table, the src attributes are
130         described in terms of depth (index (8), 16, 32/24) and if there is
131         per-pixel alpha. These inputs combine to create an index into the
132         pref[] table, which contains the caller's preferred config for that
133         input, or kNo_Config if there is no preference.
134 
135         To specify no preferrence, call setPrefConfigTable(NULL), which is
136         the default.
137 
138         Note, it is still at the discretion of the codec as to what output
139         config is actually returned, as it may not be able to support the
140         caller's preference.
141 
142         Here is how the index into the table is computed from the src:
143             depth [8, 16, 32/24] -> 0, 2, 4
144             alpha [no, yes] -> 0, 1
145         The two index values are OR'd together.
146             src: 8-index, no-alpha  -> 0
147             src: 8-index, yes-alpha -> 1
148             src: 16bit,   no-alpha  -> 2    // e.g. 565
149             src: 16bit,   yes-alpha -> 3    // e.g. 1555
150             src: 32/24,   no-alpha  -> 4
151             src: 32/24,   yes-alpha -> 5
152      */
153     void setPrefConfigTable(const SkBitmap::Config pref[6]);
154 
getAllocator()155     SkBitmap::Allocator* getAllocator() const { return fAllocator; }
156     SkBitmap::Allocator* setAllocator(SkBitmap::Allocator*);
157     SkVMMemoryReporter* setReporter(SkVMMemoryReporter*);
158 
159     // sample-size, if set to > 1, tells the decoder to return a smaller than
160     // original bitmap, sampling 1 pixel for every size pixels. e.g. if sample
161     // size is set to 3, then the returned bitmap will be 1/3 as wide and high,
162     // and will contain 1/9 as many pixels as the original.
163     // Note: this is a hint, and the codec may choose to ignore this, or only
164     // approximate the sample size.
getSampleSize()165     int getSampleSize() const { return fSampleSize; }
166     void setSampleSize(int size);
167 
168     /** Reset the sampleSize to its default of 1
169      */
resetSampleSize()170     void resetSampleSize() { this->setSampleSize(1); }
171 
172     /** Decoding is synchronous, but for long decodes, a different thread can
173         call this method safely. This sets a state that the decoders will
174         periodically check, and if they see it changed to cancel, they will
175         cancel. This will result in decode() returning false. However, there is
176         no guarantee that the decoder will see the state change in time, so
177         it is possible that cancelDecode() will be called, but will be ignored
178         and decode() will return true (assuming no other problems were
179         encountered).
180 
181         This state is automatically reset at the beginning of decode().
182      */
cancelDecode()183     void cancelDecode() {
184         // now the subclass must query shouldCancelDecode() to be informed
185         // of the request
186         fShouldCancelDecode = true;
187     }
188 
189     /** Passed to the decode method. If kDecodeBounds_Mode is passed, then
190         only the bitmap's width/height/config need be set. If kDecodePixels_Mode
191         is passed, then the bitmap must have pixels or a pixelRef.
192     */
193     enum Mode {
194         kDecodeBounds_Mode, //!< only return width/height/config in bitmap
195         kDecodePixels_Mode  //!< return entire bitmap (including pixels)
196     };
197 
198     /** Given a stream, decode it into the specified bitmap.
199         If the decoder can decompress the image, it calls bitmap.setConfig(),
200         and then if the Mode is kDecodePixels_Mode, call allocPixelRef(),
201         which will allocated a pixelRef. To access the pixel memory, the codec
202         needs to call lockPixels/unlockPixels on the
203         bitmap. It can then set the pixels with the decompressed image.
204     *   If the image cannot be decompressed, return false. After the
205     *   decoding, the function converts the decoded config in bitmap
206     *   to pref if possible. Whether a conversion is feasible is
207     *   tested by Bitmap::canCopyTo(pref).
208 
209         note: document use of Allocator, Peeker and Chooser
210     */
211     bool decode(SkStream*, SkBitmap* bitmap, SkBitmap::Config pref, Mode, bool reuseBitmap = false);
212     bool decode(SkStream* stream, SkBitmap* bitmap, Mode mode, bool reuseBitmap = false) {
213         return this->decode(stream, bitmap, SkBitmap::kNo_Config, mode, reuseBitmap);
214     }
215 
216     /**
217      * Given a stream, build an index for doing tile-based decode.
218      * The built index will be saved in the decoder, and the image size will
219      * be returned in width and height.
220      *
221      * Return true for success or false on failure.
222      */
223     virtual bool buildTileIndex(SkStream*,
224                                 int *width, int *height);
225 
226     /**
227      * Decode a rectangle region in the image specified by rect.
228      * The method can only be called after buildTileIndex().
229      *
230      * Return true for success.
231      * Return false if the index is never built or failing in decoding.
232      */
233     virtual bool decodeRegion(SkBitmap* bitmap, SkIRect rect,
234                               SkBitmap::Config pref);
235 
236     /** Given a stream, this will try to find an appropriate decoder object.
237         If none is found, the method returns NULL.
238     */
239     static SkImageDecoder* Factory(SkStream*);
240 
241     /** Decode the image stored in the specified file, and store the result
242         in bitmap. Return true for success or false on failure.
243 
244         If pref is kNo_Config, then the decoder is free to choose the most natural
245         config given the image data. If pref something other than kNo_Config,
246         the decoder will attempt to decode the image into that format, unless
247         there is a conflict (e.g. the image has per-pixel alpha and the bitmap's
248         config does not support that), in which case the decoder will choose a
249         closest match configuration.
250 
251         @param format On success, if format is non-null, it is set to the format
252                       of the decoded file. On failure it is ignored.
253     */
254     static bool DecodeFile(const char file[], SkBitmap* bitmap,
255                            SkBitmap::Config prefConfig, Mode,
256                            Format* format = NULL);
DecodeFile(const char file[],SkBitmap * bitmap)257     static bool DecodeFile(const char file[], SkBitmap* bitmap) {
258         return DecodeFile(file, bitmap, SkBitmap::kNo_Config,
259                           kDecodePixels_Mode, NULL);
260     }
261     /** Decode the image stored in the specified memory buffer, and store the
262         result in bitmap. Return true for success or false on failure.
263 
264         If pref is kNo_Config, then the decoder is free to choose the most natural
265         config given the image data. If pref something other than kNo_Config,
266         the decoder will attempt to decode the image into that format, unless
267         there is a conflict (e.g. the image has per-pixel alpha and the bitmap's
268         config does not support that), in which case the decoder will choose a
269         closest match configuration.
270 
271         @param format On success, if format is non-null, it is set to the format
272                        of the decoded buffer. On failure it is ignored.
273      */
274     static bool DecodeMemory(const void* buffer, size_t size, SkBitmap* bitmap,
275                              SkBitmap::Config prefConfig, Mode,
276                              Format* format = NULL);
DecodeMemory(const void * buffer,size_t size,SkBitmap * bitmap)277     static bool DecodeMemory(const void* buffer, size_t size, SkBitmap* bitmap){
278         return DecodeMemory(buffer, size, bitmap, SkBitmap::kNo_Config,
279                             kDecodePixels_Mode, NULL);
280     }
281     /** Decode the image stored in the specified SkStream, and store the result
282         in bitmap. Return true for success or false on failure.
283 
284         If pref is kNo_Config, then the decoder is free to choose the most
285         natural config given the image data. If pref something other than
286         kNo_Config, the decoder will attempt to decode the image into that
287         format, unless there is a conflict (e.g. the image has per-pixel alpha
288         and the bitmap's config does not support that), in which case the
289         decoder will choose a closest match configuration.
290 
291         @param format On success, if format is non-null, it is set to the format
292                       of the decoded stream. On failure it is ignored.
293      */
294     static bool DecodeStream(SkStream* stream, SkBitmap* bitmap,
295                              SkBitmap::Config prefConfig, Mode,
296                              Format* format = NULL);
DecodeStream(SkStream * stream,SkBitmap * bitmap)297     static bool DecodeStream(SkStream* stream, SkBitmap* bitmap) {
298         return DecodeStream(stream, bitmap, SkBitmap::kNo_Config,
299                             kDecodePixels_Mode, NULL);
300     }
301 
302     /** Return the default config for the running device.
303         Currently this used as a suggestion to image decoders that need to guess
304         what config they should decode into.
305         Default is kNo_Config, but this can be changed with SetDeviceConfig()
306     */
307     static SkBitmap::Config GetDeviceConfig();
308     /** Set the default config for the running device.
309         Currently this used as a suggestion to image decoders that need to guess
310         what config they should decode into.
311         Default is kNo_Config.
312         This can be queried with GetDeviceConfig()
313     */
314     static void SetDeviceConfig(SkBitmap::Config);
315 
316   /** @cond UNIT_TEST */
317     SkDEBUGCODE(static void UnitTest();)
318   /** @endcond */
319 
320 protected:
321     // must be overridden in subclasses. This guy is called by decode(...)
322     virtual bool onDecode(SkStream*, SkBitmap* bitmap, Mode) = 0;
323 
324     // If the decoder wants to support tiled based decoding,
325     // this method must be overridden. This guy is called by buildTileIndex(...)
onBuildTileIndex(SkStream *,int * width,int * height)326     virtual bool onBuildTileIndex(SkStream*,
327                 int *width, int *height) {
328         return false;
329     }
330 
331     // If the decoder wants to support tiled based decoding,
332     // this method must be overridden. This guy is called by decodeRegion(...)
onDecodeRegion(SkBitmap * bitmap,SkIRect rect)333     virtual bool onDecodeRegion(SkBitmap* bitmap, SkIRect rect) {
334         return false;
335     }
336 
337     /*
338      * Crop a rectangle from the src Bitmap to the dest Bitmap. src and dest are
339      * both sampled by sampleSize from an original Bitmap.
340      *
341      * @param dest the destination Bitmap.
342      * @param src the source Bitmap that is sampled by sampleSize from the original
343      *            Bitmap.
344      * @param sampleSize the sample size that src is sampled from the original Bitmap.
345      * @param (srcX, srcY) the upper-left point of the src Btimap in terms of
346      *                     the coordinate in the original Bitmap.
347      * @param (width, height) the width and height of the unsampled dest.
348      * @param (destX, destY) the upper-left point of the dest Bitmap in terms of
349      *                       the coordinate in the original Bitmap.
350      */
351     virtual void cropBitmap(SkBitmap *dest, SkBitmap *src, int sampleSize,
352                             int destX, int destY, int width, int height,
353                             int srcX, int srcY);
354 
355 
356 
357     /** Can be queried from within onDecode, to see if the user (possibly in
358         a different thread) has requested the decode to cancel. If this returns
359         true, your onDecode() should stop and return false.
360         Each subclass needs to decide how often it can query this, to balance
361         responsiveness with performance.
362 
363         Calling this outside of onDecode() may return undefined values.
364      */
365 
366 public:
shouldCancelDecode()367     bool shouldCancelDecode() const { return fShouldCancelDecode; }
368 
369 protected:
370     SkImageDecoder();
371 
372     // helper function for decoders to handle the (common) case where there is only
373     // once choice available in the image file.
374     bool chooseFromOneChoice(SkBitmap::Config config, int width, int height) const;
375 
376     /*  Helper for subclasses. Call this to allocate the pixel memory given the bitmap's
377         width/height/rowbytes/config. Returns true on success. This method handles checking
378         for an optional Allocator.
379     */
380     bool allocPixelRef(SkBitmap*, SkColorTable*) const;
381 
382     enum SrcDepth {
383         kIndex_SrcDepth,
384         k16Bit_SrcDepth,
385         k32Bit_SrcDepth
386     };
387     /** The subclass, inside onDecode(), calls this to determine the config of
388         the returned bitmap. SrcDepth and hasAlpha reflect the raw data of the
389         src image. This routine returns the caller's preference given
390         srcDepth and hasAlpha, or kNo_Config if there is no preference.
391 
392         Note: this also takes into account GetDeviceConfig(), so the subclass
393         need not call that.
394      */
395     SkBitmap::Config getPrefConfig(SrcDepth, bool hasAlpha) const;
396 
397     SkVMMemoryReporter*      fReporter;
398 
399 private:
400     Peeker*                 fPeeker;
401     Chooser*                fChooser;
402     SkBitmap::Allocator*    fAllocator;
403     int                     fSampleSize;
404     SkBitmap::Config        fDefaultPref;   // use if fUsePrefTable is false
405     SkBitmap::Config        fPrefTable[6];  // use if fUsePrefTable is true
406     bool                    fDitherImage;
407     bool                    fUsePrefTable;
408     mutable bool            fShouldCancelDecode;
409     bool                    fPreferQualityOverSpeed;
410 
411     // illegal
412     SkImageDecoder(const SkImageDecoder&);
413     SkImageDecoder& operator=(const SkImageDecoder&);
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(SkStream*) = 0;
427 
428 private:
429     typedef SkRefCnt INHERITED;
430 };
431 
432 class SkDefaultImageDecoderFactory : SkImageDecoderFactory {
433 public:
434     // calls SkImageDecoder::Factory(stream)
newDecoder(SkStream * stream)435     virtual SkImageDecoder* newDecoder(SkStream* 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 
462 #endif
463