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