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