• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright 2015 Google Inc.
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 SkCodec_DEFINED
9 #define SkCodec_DEFINED
10 
11 #include "../private/SkNoncopyable.h"
12 #include "../private/SkTemplates.h"
13 #include "../private/SkEncodedInfo.h"
14 #include "SkCodecAnimation.h"
15 #include "SkColor.h"
16 #include "SkEncodedImageFormat.h"
17 #include "SkEncodedOrigin.h"
18 #include "SkImageInfo.h"
19 #include "SkPixmap.h"
20 #include "SkSize.h"
21 #include "SkStream.h"
22 #include "SkTypes.h"
23 #include "SkYUVASizeInfo.h"
24 
25 #include <vector>
26 
27 class SkColorSpace;
28 class SkData;
29 class SkFrameHolder;
30 class SkPngChunkReader;
31 class SkSampler;
32 
33 namespace DM {
34 class CodecSrc;
35 class ColorCodecSrc;
36 }
37 
38 /**
39  *  Abstraction layer directly on top of an image codec.
40  */
41 class SK_API SkCodec : SkNoncopyable {
42 public:
43     /**
44      *  Minimum number of bytes that must be buffered in SkStream input.
45      *
46      *  An SkStream passed to NewFromStream must be able to use this many
47      *  bytes to determine the image type. Then the same SkStream must be
48      *  passed to the correct decoder to read from the beginning.
49      *
50      *  This can be accomplished by implementing peek() to support peeking
51      *  this many bytes, or by implementing rewind() to be able to rewind()
52      *  after reading this many bytes.
53      */
MinBufferedBytesNeeded()54     static constexpr size_t MinBufferedBytesNeeded() { return 32; }
55 
56     /**
57      *  Error codes for various SkCodec methods.
58      */
59     enum Result {
60         /**
61          *  General return value for success.
62          */
63         kSuccess,
64         /**
65          *  The input is incomplete. A partial image was generated.
66          */
67         kIncompleteInput,
68         /**
69          *  Like kIncompleteInput, except the input had an error.
70          *
71          *  If returned from an incremental decode, decoding cannot continue,
72          *  even with more data.
73          */
74         kErrorInInput,
75         /**
76          *  The generator cannot convert to match the request, ignoring
77          *  dimensions.
78          */
79         kInvalidConversion,
80         /**
81          *  The generator cannot scale to requested size.
82          */
83         kInvalidScale,
84         /**
85          *  Parameters (besides info) are invalid. e.g. NULL pixels, rowBytes
86          *  too small, etc.
87          */
88         kInvalidParameters,
89         /**
90          *  The input did not contain a valid image.
91          */
92         kInvalidInput,
93         /**
94          *  Fulfilling this request requires rewinding the input, which is not
95          *  supported for this input.
96          */
97         kCouldNotRewind,
98         /**
99          *  An internal error, such as OOM.
100          */
101         kInternalError,
102         /**
103          *  This method is not implemented by this codec.
104          *  FIXME: Perhaps this should be kUnsupported?
105          */
106         kUnimplemented,
107     };
108 
109     /**
110      *  Readable string representing the error code.
111      */
112     static const char* ResultToString(Result);
113 
114     /**
115      *  If this stream represents an encoded image that we know how to decode,
116      *  return an SkCodec that can decode it. Otherwise return NULL.
117      *
118      *  As stated above, this call must be able to peek or read
119      *  MinBufferedBytesNeeded to determine the correct format, and then start
120      *  reading from the beginning. First it will attempt to peek, and it
121      *  assumes that if less than MinBufferedBytesNeeded bytes (but more than
122      *  zero) are returned, this is because the stream is shorter than this,
123      *  so falling back to reading would not provide more data. If peek()
124      *  returns zero bytes, this call will instead attempt to read(). This
125      *  will require that the stream can be rewind()ed.
126      *
127      *  If Result is not NULL, it will be set to either kSuccess if an SkCodec
128      *  is returned or a reason for the failure if NULL is returned.
129      *
130      *  If SkPngChunkReader is not NULL, take a ref and pass it to libpng if
131      *  the image is a png.
132      *
133      *  If the SkPngChunkReader is not NULL then:
134      *      If the image is not a PNG, the SkPngChunkReader will be ignored.
135      *      If the image is a PNG, the SkPngChunkReader will be reffed.
136      *      If the PNG has unknown chunks, the SkPngChunkReader will be used
137      *      to handle these chunks.  SkPngChunkReader will be called to read
138      *      any unknown chunk at any point during the creation of the codec
139      *      or the decode.  Note that if SkPngChunkReader fails to read a
140      *      chunk, this could result in a failure to create the codec or a
141      *      failure to decode the image.
142      *      If the PNG does not contain unknown chunks, the SkPngChunkReader
143      *      will not be used or modified.
144      *
145      *  If NULL is returned, the stream is deleted immediately. Otherwise, the
146      *  SkCodec takes ownership of it, and will delete it when done with it.
147      */
148     static std::unique_ptr<SkCodec> MakeFromStream(std::unique_ptr<SkStream>, Result* = nullptr,
149                                                    SkPngChunkReader* = nullptr);
150 
151     /**
152      *  If this data represents an encoded image that we know how to decode,
153      *  return an SkCodec that can decode it. Otherwise return NULL.
154      *
155      *  If the SkPngChunkReader is not NULL then:
156      *      If the image is not a PNG, the SkPngChunkReader will be ignored.
157      *      If the image is a PNG, the SkPngChunkReader will be reffed.
158      *      If the PNG has unknown chunks, the SkPngChunkReader will be used
159      *      to handle these chunks.  SkPngChunkReader will be called to read
160      *      any unknown chunk at any point during the creation of the codec
161      *      or the decode.  Note that if SkPngChunkReader fails to read a
162      *      chunk, this could result in a failure to create the codec or a
163      *      failure to decode the image.
164      *      If the PNG does not contain unknown chunks, the SkPngChunkReader
165      *      will not be used or modified.
166      */
167     static std::unique_ptr<SkCodec> MakeFromData(sk_sp<SkData>, SkPngChunkReader* = nullptr);
168 
169     virtual ~SkCodec();
170 
171     /**
172      *  Return a reasonable SkImageInfo to decode into.
173      */
getInfo()174     SkImageInfo getInfo() const { return fEncodedInfo.makeImageInfo(); }
175 
dimensions()176     SkISize dimensions() const { return {fEncodedInfo.width(), fEncodedInfo.height()}; }
bounds()177     SkIRect bounds() const {
178         return SkIRect::MakeWH(fEncodedInfo.width(), fEncodedInfo.height());
179     }
180 
181     /**
182      *  Returns the image orientation stored in the EXIF data.
183      *  If there is no EXIF data, or if we cannot read the EXIF data, returns kTopLeft.
184      */
getOrigin()185     SkEncodedOrigin getOrigin() const { return fOrigin; }
186 
187     /**
188      *  Return a size that approximately supports the desired scale factor.
189      *  The codec may not be able to scale efficiently to the exact scale
190      *  factor requested, so return a size that approximates that scale.
191      *  The returned value is the codec's suggestion for the closest valid
192      *  scale that it can natively support
193      */
getScaledDimensions(float desiredScale)194     SkISize getScaledDimensions(float desiredScale) const {
195         // Negative and zero scales are errors.
196         SkASSERT(desiredScale > 0.0f);
197         if (desiredScale <= 0.0f) {
198             return SkISize::Make(0, 0);
199         }
200 
201         // Upscaling is not supported. Return the original size if the client
202         // requests an upscale.
203         if (desiredScale >= 1.0f) {
204             return this->dimensions();
205         }
206         return this->onGetScaledDimensions(desiredScale);
207     }
208 
209     /**
210      *  Return (via desiredSubset) a subset which can decoded from this codec,
211      *  or false if this codec cannot decode subsets or anything similar to
212      *  desiredSubset.
213      *
214      *  @param desiredSubset In/out parameter. As input, a desired subset of
215      *      the original bounds (as specified by getInfo). If true is returned,
216      *      desiredSubset may have been modified to a subset which is
217      *      supported. Although a particular change may have been made to
218      *      desiredSubset to create something supported, it is possible other
219      *      changes could result in a valid subset.
220      *      If false is returned, desiredSubset's value is undefined.
221      *  @return true if this codec supports decoding desiredSubset (as
222      *      returned, potentially modified)
223      */
getValidSubset(SkIRect * desiredSubset)224     bool getValidSubset(SkIRect* desiredSubset) const {
225         return this->onGetValidSubset(desiredSubset);
226     }
227 
228     /**
229      *  Format of the encoded data.
230      */
getEncodedFormat()231     SkEncodedImageFormat getEncodedFormat() const { return this->onGetEncodedFormat(); }
232 
233     /**
234      *  Whether or not the memory passed to getPixels is zero initialized.
235      */
236     enum ZeroInitialized {
237         /**
238          *  The memory passed to getPixels is zero initialized. The SkCodec
239          *  may take advantage of this by skipping writing zeroes.
240          */
241         kYes_ZeroInitialized,
242         /**
243          *  The memory passed to getPixels has not been initialized to zero,
244          *  so the SkCodec must write all zeroes to memory.
245          *
246          *  This is the default. It will be used if no Options struct is used.
247          */
248         kNo_ZeroInitialized,
249     };
250 
251     /**
252      *  Additional options to pass to getPixels.
253      */
254     struct Options {
OptionsOptions255         Options()
256             : fZeroInitialized(kNo_ZeroInitialized)
257             , fSubset(nullptr)
258             , fFrameIndex(0)
259             , fPriorFrame(kNoFrame)
260         {}
261 
262         ZeroInitialized            fZeroInitialized;
263         /**
264          *  If not NULL, represents a subset of the original image to decode.
265          *  Must be within the bounds returned by getInfo().
266          *  If the EncodedFormat is SkEncodedImageFormat::kWEBP (the only one which
267          *  currently supports subsets), the top and left values must be even.
268          *
269          *  In getPixels and incremental decode, we will attempt to decode the
270          *  exact rectangular subset specified by fSubset.
271          *
272          *  In a scanline decode, it does not make sense to specify a subset
273          *  top or subset height, since the client already controls which rows
274          *  to get and which rows to skip.  During scanline decodes, we will
275          *  require that the subset top be zero and the subset height be equal
276          *  to the full height.  We will, however, use the values of
277          *  subset left and subset width to decode partial scanlines on calls
278          *  to getScanlines().
279          */
280         const SkIRect*             fSubset;
281 
282         /**
283          *  The frame to decode.
284          *
285          *  Only meaningful for multi-frame images.
286          */
287         int                        fFrameIndex;
288 
289         /**
290          *  If not kNoFrame, the dst already contains the prior frame at this index.
291          *
292          *  Only meaningful for multi-frame images.
293          *
294          *  If fFrameIndex needs to be blended with a prior frame (as reported by
295          *  getFrameInfo[fFrameIndex].fRequiredFrame), the client can set this to
296          *  any non-kRestorePrevious frame in [fRequiredFrame, fFrameIndex) to
297          *  indicate that that frame is already in the dst. Options.fZeroInitialized
298          *  is ignored in this case.
299          *
300          *  If set to kNoFrame, the codec will decode any necessary required frame(s) first.
301          */
302         int                        fPriorFrame;
303     };
304 
305     /**
306      *  Decode into the given pixels, a block of memory of size at
307      *  least (info.fHeight - 1) * rowBytes + (info.fWidth *
308      *  bytesPerPixel)
309      *
310      *  Repeated calls to this function should give the same results,
311      *  allowing the PixelRef to be immutable.
312      *
313      *  @param info A description of the format (config, size)
314      *         expected by the caller.  This can simply be identical
315      *         to the info returned by getInfo().
316      *
317      *         This contract also allows the caller to specify
318      *         different output-configs, which the implementation can
319      *         decide to support or not.
320      *
321      *         A size that does not match getInfo() implies a request
322      *         to scale. If the generator cannot perform this scale,
323      *         it will return kInvalidScale.
324      *
325      *         If the info contains a non-null SkColorSpace, the codec
326      *         will perform the appropriate color space transformation.
327      *         If the caller passes in the same color space that was
328      *         reported by the codec, the color space transformation is
329      *         a no-op.
330      *
331      *  If a scanline decode is in progress, scanline mode will end, requiring the client to call
332      *  startScanlineDecode() in order to return to decoding scanlines.
333      *
334      *  @return Result kSuccess, or another value explaining the type of failure.
335      */
336     Result getPixels(const SkImageInfo& info, void* pixels, size_t rowBytes, const Options*);
337 
338     /**
339      *  Simplified version of getPixels() that uses the default Options.
340      */
getPixels(const SkImageInfo & info,void * pixels,size_t rowBytes)341     Result getPixels(const SkImageInfo& info, void* pixels, size_t rowBytes) {
342         return this->getPixels(info, pixels, rowBytes, nullptr);
343     }
344 
345     Result getPixels(const SkPixmap& pm, const Options* opts = nullptr) {
346         return this->getPixels(pm.info(), pm.writable_addr(), pm.rowBytes(), opts);
347     }
348 
349     /**
350      *  If decoding to YUV is supported, this returns true.  Otherwise, this
351      *  returns false and does not modify any of the parameters.
352      *
353      *  @param sizeInfo   Output parameter indicating the sizes and required
354      *                    allocation widths of the Y, U, V, and A planes. Given current codec
355      *                    limitations the size of the A plane will always be 0 and the Y, U, V
356      *                    channels will always be planar.
357      *  @param colorSpace Output parameter.  If non-NULL this is set to kJPEG,
358      *                    otherwise this is ignored.
359      */
queryYUV8(SkYUVASizeInfo * sizeInfo,SkYUVColorSpace * colorSpace)360     bool queryYUV8(SkYUVASizeInfo* sizeInfo, SkYUVColorSpace* colorSpace) const {
361         if (nullptr == sizeInfo) {
362             return false;
363         }
364 
365         bool result = this->onQueryYUV8(sizeInfo, colorSpace);
366         if (result) {
367             for (int i = 0; i <= 2; ++i) {
368                 SkASSERT(sizeInfo->fSizes[i].fWidth > 0 && sizeInfo->fSizes[i].fHeight > 0 &&
369                          sizeInfo->fWidthBytes[i] > 0);
370             }
371             SkASSERT(!sizeInfo->fSizes[3].fWidth &&
372                      !sizeInfo->fSizes[3].fHeight &&
373                      !sizeInfo->fWidthBytes[3]);
374         }
375         return result;
376     }
377 
378     /**
379      *  Returns kSuccess, or another value explaining the type of failure.
380      *  This always attempts to perform a full decode.  If the client only
381      *  wants size, it should call queryYUV8().
382      *
383      *  @param sizeInfo   Needs to exactly match the values returned by the
384      *                    query, except the WidthBytes may be larger than the
385      *                    recommendation (but not smaller).
386      *  @param planes     Memory for each of the Y, U, and V planes.
387      */
getYUV8Planes(const SkYUVASizeInfo & sizeInfo,void * planes[SkYUVASizeInfo::kMaxCount])388     Result getYUV8Planes(const SkYUVASizeInfo& sizeInfo, void* planes[SkYUVASizeInfo::kMaxCount]) {
389         if (!planes || !planes[0] || !planes[1] || !planes[2]) {
390             return kInvalidInput;
391         }
392         SkASSERT(!planes[3]); // TODO: is this a fair assumption?
393 
394         if (!this->rewindIfNeeded()) {
395             return kCouldNotRewind;
396         }
397 
398         return this->onGetYUV8Planes(sizeInfo, planes);
399     }
400 
401     /**
402      *  Prepare for an incremental decode with the specified options.
403      *
404      *  This may require a rewind.
405      *
406      *  If kIncompleteInput is returned, may be called again after more data has
407      *  been provided to the source SkStream.
408      *
409      *  @param dstInfo Info of the destination. If the dimensions do not match
410      *      those of getInfo, this implies a scale.
411      *  @param dst Memory to write to. Needs to be large enough to hold the subset,
412      *      if present, or the full image as described in dstInfo.
413      *  @param options Contains decoding options, including if memory is zero
414      *      initialized and whether to decode a subset.
415      *  @return Enum representing success or reason for failure.
416      */
417     Result startIncrementalDecode(const SkImageInfo& dstInfo, void* dst, size_t rowBytes,
418             const Options*);
419 
startIncrementalDecode(const SkImageInfo & dstInfo,void * dst,size_t rowBytes)420     Result startIncrementalDecode(const SkImageInfo& dstInfo, void* dst, size_t rowBytes) {
421         return this->startIncrementalDecode(dstInfo, dst, rowBytes, nullptr);
422     }
423 
424     /**
425      *  Start/continue the incremental decode.
426      *
427      *  Not valid to call before a call to startIncrementalDecode() returns
428      *  kSuccess.
429      *
430      *  If kIncompleteInput is returned, may be called again after more data has
431      *  been provided to the source SkStream.
432      *
433      *  Unlike getPixels and getScanlines, this does not do any filling. This is
434      *  left up to the caller, since they may be skipping lines or continuing the
435      *  decode later. In the latter case, they may choose to initialize all lines
436      *  first, or only initialize the remaining lines after the first call.
437      *
438      *  @param rowsDecoded Optional output variable returning the total number of
439      *      lines initialized. Only meaningful if this method returns kIncompleteInput.
440      *      Otherwise the implementation may not set it.
441      *      Note that some implementations may have initialized this many rows, but
442      *      not necessarily finished those rows (e.g. interlaced PNG). This may be
443      *      useful for determining what rows the client needs to initialize.
444      *  @return kSuccess if all lines requested in startIncrementalDecode have
445      *      been completely decoded. kIncompleteInput otherwise.
446      */
447     Result incrementalDecode(int* rowsDecoded = nullptr) {
448         if (!fStartedIncrementalDecode) {
449             return kInvalidParameters;
450         }
451         return this->onIncrementalDecode(rowsDecoded);
452     }
453 
454     /**
455      * The remaining functions revolve around decoding scanlines.
456      */
457 
458     /**
459      *  Prepare for a scanline decode with the specified options.
460      *
461      *  After this call, this class will be ready to decode the first scanline.
462      *
463      *  This must be called in order to call getScanlines or skipScanlines.
464      *
465      *  This may require rewinding the stream.
466      *
467      *  Not all SkCodecs support this.
468      *
469      *  @param dstInfo Info of the destination. If the dimensions do not match
470      *      those of getInfo, this implies a scale.
471      *  @param options Contains decoding options, including if memory is zero
472      *      initialized.
473      *  @return Enum representing success or reason for failure.
474      */
475     Result startScanlineDecode(const SkImageInfo& dstInfo, const Options* options);
476 
477     /**
478      *  Simplified version of startScanlineDecode() that uses the default Options.
479      */
startScanlineDecode(const SkImageInfo & dstInfo)480     Result startScanlineDecode(const SkImageInfo& dstInfo) {
481         return this->startScanlineDecode(dstInfo, nullptr);
482     }
483 
484     /**
485      *  Write the next countLines scanlines into dst.
486      *
487      *  Not valid to call before calling startScanlineDecode().
488      *
489      *  @param dst Must be non-null, and large enough to hold countLines
490      *      scanlines of size rowBytes.
491      *  @param countLines Number of lines to write.
492      *  @param rowBytes Number of bytes per row. Must be large enough to hold
493      *      a scanline based on the SkImageInfo used to create this object.
494      *  @return the number of lines successfully decoded.  If this value is
495      *      less than countLines, this will fill the remaining lines with a
496      *      default value.
497      */
498     int getScanlines(void* dst, int countLines, size_t rowBytes);
499 
500     /**
501      *  Skip count scanlines.
502      *
503      *  Not valid to call before calling startScanlineDecode().
504      *
505      *  The default version just calls onGetScanlines and discards the dst.
506      *  NOTE: If skipped lines are the only lines with alpha, this default
507      *  will make reallyHasAlpha return true, when it could have returned
508      *  false.
509      *
510      *  @return true if the scanlines were successfully skipped
511      *          false on failure, possible reasons for failure include:
512      *              An incomplete input image stream.
513      *              Calling this function before calling startScanlineDecode().
514      *              If countLines is less than zero or so large that it moves
515      *                  the current scanline past the end of the image.
516      */
517     bool skipScanlines(int countLines);
518 
519     /**
520      *  The order in which rows are output from the scanline decoder is not the
521      *  same for all variations of all image types.  This explains the possible
522      *  output row orderings.
523      */
524     enum SkScanlineOrder {
525         /*
526          * By far the most common, this indicates that the image can be decoded
527          * reliably using the scanline decoder, and that rows will be output in
528          * the logical order.
529          */
530         kTopDown_SkScanlineOrder,
531 
532         /*
533          * This indicates that the scanline decoder reliably outputs rows, but
534          * they will be returned in reverse order.  If the scanline format is
535          * kBottomUp, the nextScanline() API can be used to determine the actual
536          * y-coordinate of the next output row, but the client is not forced
537          * to take advantage of this, given that it's not too tough to keep
538          * track independently.
539          *
540          * For full image decodes, it is safe to get all of the scanlines at
541          * once, since the decoder will handle inverting the rows as it
542          * decodes.
543          *
544          * For subset decodes and sampling, it is simplest to get and skip
545          * scanlines one at a time, using the nextScanline() API.  It is
546          * possible to ask for larger chunks at a time, but this should be used
547          * with caution.  As with full image decodes, the decoder will handle
548          * inverting the requested rows, but rows will still be delivered
549          * starting from the bottom of the image.
550          *
551          * Upside down bmps are an example.
552          */
553         kBottomUp_SkScanlineOrder,
554     };
555 
556     /**
557      *  An enum representing the order in which scanlines will be returned by
558      *  the scanline decoder.
559      *
560      *  This is undefined before startScanlineDecode() is called.
561      */
getScanlineOrder()562     SkScanlineOrder getScanlineOrder() const { return this->onGetScanlineOrder(); }
563 
564     /**
565      *  Returns the y-coordinate of the next row to be returned by the scanline
566      *  decoder.
567      *
568      *  This will equal fCurrScanline, except in the case of strangely
569      *  encoded image types (bottom-up bmps).
570      *
571      *  Results are undefined when not in scanline decoding mode.
572      */
nextScanline()573     int nextScanline() const { return this->outputScanline(fCurrScanline); }
574 
575     /**
576      *  Returns the output y-coordinate of the row that corresponds to an input
577      *  y-coordinate.  The input y-coordinate represents where the scanline
578      *  is located in the encoded data.
579      *
580      *  This will equal inputScanline, except in the case of strangely
581      *  encoded image types (bottom-up bmps, interlaced gifs).
582      */
583     int outputScanline(int inputScanline) const;
584 
585     /**
586      *  Return the number of frames in the image.
587      *
588      *  May require reading through the stream.
589      */
getFrameCount()590     int getFrameCount() {
591         return this->onGetFrameCount();
592     }
593 
594     // Sentinel value used when a frame index implies "no frame":
595     // - FrameInfo::fRequiredFrame set to this value means the frame
596     //   is independent.
597     // - Options::fPriorFrame set to this value means no (relevant) prior frame
598     //   is residing in dst's memory.
599     static constexpr int kNoFrame = -1;
600 
601     // This transitional definition was added in August 2018, and will eventually be removed.
602 #ifdef SK_LEGACY_SKCODEC_NONE_ENUM
603     static constexpr int kNone = kNoFrame;
604 #endif
605 
606     /**
607      *  Information about individual frames in a multi-framed image.
608      */
609     struct FrameInfo {
610         /**
611          *  The frame that this frame needs to be blended with, or
612          *  kNoFrame if this frame is independent.
613          *
614          *  Note that this is the *earliest* frame that can be used
615          *  for blending. Any frame from [fRequiredFrame, i) can be
616          *  used, unless its fDisposalMethod is kRestorePrevious.
617          */
618         int fRequiredFrame;
619 
620         /**
621          *  Number of milliseconds to show this frame.
622          */
623         int fDuration;
624 
625         /**
626          *  Whether the end marker for this frame is contained in the stream.
627          *
628          *  Note: this does not guarantee that an attempt to decode will be complete.
629          *  There could be an error in the stream.
630          */
631         bool fFullyReceived;
632 
633         /**
634          *  This is conservative; it will still return non-opaque if e.g. a
635          *  color index-based frame has a color with alpha but does not use it.
636          */
637         SkAlphaType fAlphaType;
638 
639         /**
640          *  How this frame should be modified before decoding the next one.
641          */
642         SkCodecAnimation::DisposalMethod fDisposalMethod;
643     };
644 
645     /**
646      *  Return info about a single frame.
647      *
648      *  Only supported by multi-frame images. Does not read through the stream,
649      *  so it should be called after getFrameCount() to parse any frames that
650      *  have not already been parsed.
651      */
getFrameInfo(int index,FrameInfo * info)652     bool getFrameInfo(int index, FrameInfo* info) const {
653         if (index < 0) {
654             return false;
655         }
656         return this->onGetFrameInfo(index, info);
657     }
658 
659     /**
660      *  Return info about all the frames in the image.
661      *
662      *  May require reading through the stream to determine info about the
663      *  frames (including the count).
664      *
665      *  As such, future decoding calls may require a rewind.
666      *
667      *  For still (non-animated) image codecs, this will return an empty vector.
668      */
669     std::vector<FrameInfo> getFrameInfo();
670 
671     static constexpr int kRepetitionCountInfinite = -1;
672 
673     /**
674      *  Return the number of times to repeat, if this image is animated. This number does not
675      *  include the first play through of each frame. For example, a repetition count of 4 means
676      *  that each frame is played 5 times and then the animation stops.
677      *
678      *  It can return kRepetitionCountInfinite, a negative number, meaning that the animation
679      *  should loop forever.
680      *
681      *  May require reading the stream to find the repetition count.
682      *
683      *  As such, future decoding calls may require a rewind.
684      *
685      *  For still (non-animated) image codecs, this will return 0.
686      */
getRepetitionCount()687     int getRepetitionCount() {
688         return this->onGetRepetitionCount();
689     }
690 
691 protected:
getEncodedInfo()692     const SkEncodedInfo& getEncodedInfo() const { return fEncodedInfo; }
693 
694     using XformFormat = skcms_PixelFormat;
695 
696     SkCodec(SkEncodedInfo&&,
697             XformFormat srcFormat,
698             std::unique_ptr<SkStream>,
699             SkEncodedOrigin = kTopLeft_SkEncodedOrigin);
700 
onGetScaledDimensions(float)701     virtual SkISize onGetScaledDimensions(float /*desiredScale*/) const {
702         // By default, scaling is not supported.
703         return this->dimensions();
704     }
705 
706     // FIXME: What to do about subsets??
707     /**
708      *  Subclasses should override if they support dimensions other than the
709      *  srcInfo's.
710      */
onDimensionsSupported(const SkISize &)711     virtual bool onDimensionsSupported(const SkISize&) {
712         return false;
713     }
714 
715     virtual SkEncodedImageFormat onGetEncodedFormat() const = 0;
716 
717     /**
718      * @param rowsDecoded When the encoded image stream is incomplete, this function
719      *                    will return kIncompleteInput and rowsDecoded will be set to
720      *                    the number of scanlines that were successfully decoded.
721      *                    This will allow getPixels() to fill the uninitialized memory.
722      */
723     virtual Result onGetPixels(const SkImageInfo& info,
724                                void* pixels, size_t rowBytes, const Options&,
725                                int* rowsDecoded) = 0;
726 
onQueryYUV8(SkYUVASizeInfo *,SkYUVColorSpace *)727     virtual bool onQueryYUV8(SkYUVASizeInfo*, SkYUVColorSpace*) const {
728         return false;
729     }
730 
onGetYUV8Planes(const SkYUVASizeInfo &,void * [SkYUVASizeInfo::kMaxCount])731     virtual Result onGetYUV8Planes(const SkYUVASizeInfo&,
732                                    void*[SkYUVASizeInfo::kMaxCount] /*planes*/) {
733         return kUnimplemented;
734     }
735 
onGetValidSubset(SkIRect *)736     virtual bool onGetValidSubset(SkIRect* /*desiredSubset*/) const {
737         // By default, subsets are not supported.
738         return false;
739     }
740 
741     /**
742      *  If the stream was previously read, attempt to rewind.
743      *
744      *  If the stream needed to be rewound, call onRewind.
745      *  @returns true if the codec is at the right position and can be used.
746      *      false if there was a failure to rewind.
747      *
748      *  This is called by getPixels(), getYUV8Planes(), startIncrementalDecode() and
749      *  startScanlineDecode(). Subclasses may call if they need to rewind at another time.
750      */
751     bool SK_WARN_UNUSED_RESULT rewindIfNeeded();
752 
753     /**
754      *  Called by rewindIfNeeded, if the stream needed to be rewound.
755      *
756      *  Subclasses should do any set up needed after a rewind.
757      */
onRewind()758     virtual bool onRewind() {
759         return true;
760     }
761 
762     /**
763      * Get method for the input stream
764      */
stream()765     SkStream* stream() {
766         return fStream.get();
767     }
768 
769     /**
770      *  The remaining functions revolve around decoding scanlines.
771      */
772 
773     /**
774      *  Most images types will be kTopDown and will not need to override this function.
775      */
onGetScanlineOrder()776     virtual SkScanlineOrder onGetScanlineOrder() const { return kTopDown_SkScanlineOrder; }
777 
dstInfo()778     const SkImageInfo& dstInfo() const { return fDstInfo; }
779 
options()780     const Options& options() const { return fOptions; }
781 
782     /**
783      *  Returns the number of scanlines that have been decoded so far.
784      *  This is unaffected by the SkScanlineOrder.
785      *
786      *  Returns -1 if we have not started a scanline decode.
787      */
currScanline()788     int currScanline() const { return fCurrScanline; }
789 
790     virtual int onOutputScanline(int inputScanline) const;
791 
792     /**
793      *  Return whether we can convert to dst.
794      *
795      *  Will be called for the appropriate frame, prior to initializing the colorXform.
796      */
797     virtual bool conversionSupported(const SkImageInfo& dst, bool srcIsOpaque,
798                                      bool needsColorXform);
799 
800     // Some classes never need a colorXform e.g.
801     // - ICO uses its embedded codec's colorXform
802     // - WBMP is just Black/White
usesColorXform()803     virtual bool usesColorXform() const { return true; }
804     void applyColorXform(void* dst, const void* src, int count) const;
805 
colorXform()806     bool colorXform() const { return fXformTime != kNo_XformTime; }
xformOnDecode()807     bool xformOnDecode() const { return fXformTime == kDecodeRow_XformTime; }
808 
onGetFrameCount()809     virtual int onGetFrameCount() {
810         return 1;
811     }
812 
onGetFrameInfo(int,FrameInfo *)813     virtual bool onGetFrameInfo(int, FrameInfo*) const {
814         return false;
815     }
816 
onGetRepetitionCount()817     virtual int onGetRepetitionCount() {
818         return 0;
819     }
820 
821 private:
822     const SkEncodedInfo                fEncodedInfo;
823     const XformFormat                  fSrcXformFormat;
824     std::unique_ptr<SkStream>          fStream;
825     bool                               fNeedsRewind;
826     const SkEncodedOrigin              fOrigin;
827 
828     SkImageInfo                        fDstInfo;
829     Options                            fOptions;
830 
831     enum XformTime {
832         kNo_XformTime,
833         kPalette_XformTime,
834         kDecodeRow_XformTime,
835     };
836     XformTime                          fXformTime;
837     XformFormat                        fDstXformFormat; // Based on fDstInfo.
838     skcms_ICCProfile                   fDstProfile;
839     skcms_AlphaFormat                  fDstXformAlphaFormat;
840 
841     // Only meaningful during scanline decodes.
842     int                                fCurrScanline;
843 
844     bool                               fStartedIncrementalDecode;
845 
846     bool initializeColorXform(const SkImageInfo& dstInfo, SkEncodedInfo::Alpha, bool srcIsOpaque);
847 
848     /**
849      *  Return whether these dimensions are supported as a scale.
850      *
851      *  The codec may choose to cache the information about scale and subset.
852      *  Either way, the same information will be passed to onGetPixels/onStart
853      *  on success.
854      *
855      *  This must return true for a size returned from getScaledDimensions.
856      */
dimensionsSupported(const SkISize & dim)857     bool dimensionsSupported(const SkISize& dim) {
858         return dim == this->dimensions() || this->onDimensionsSupported(dim);
859     }
860 
861     /**
862      *  For multi-framed images, return the object with information about the frames.
863      */
getFrameHolder()864     virtual const SkFrameHolder* getFrameHolder() const {
865         return nullptr;
866     }
867 
868     /**
869      *  Check for a valid Options.fFrameIndex, and decode prior frames if necessary.
870      */
871     Result handleFrameIndex(const SkImageInfo&, void* pixels, size_t rowBytes, const Options&);
872 
873     // Methods for scanline decoding.
onStartScanlineDecode(const SkImageInfo &,const Options &)874     virtual Result onStartScanlineDecode(const SkImageInfo& /*dstInfo*/,
875             const Options& /*options*/) {
876         return kUnimplemented;
877     }
878 
onStartIncrementalDecode(const SkImageInfo &,void *,size_t,const Options &)879     virtual Result onStartIncrementalDecode(const SkImageInfo& /*dstInfo*/, void*, size_t,
880             const Options&) {
881         return kUnimplemented;
882     }
883 
onIncrementalDecode(int *)884     virtual Result onIncrementalDecode(int*) {
885         return kUnimplemented;
886     }
887 
888 
onSkipScanlines(int)889     virtual bool onSkipScanlines(int /*countLines*/) { return false; }
890 
onGetScanlines(void *,int,size_t)891     virtual int onGetScanlines(void* /*dst*/, int /*countLines*/, size_t /*rowBytes*/) { return 0; }
892 
893     /**
894      * On an incomplete decode, getPixels() and getScanlines() will call this function
895      * to fill any uinitialized memory.
896      *
897      * @param dstInfo        Contains the destination color type
898      *                       Contains the destination alpha type
899      *                       Contains the destination width
900      *                       The height stored in this info is unused
901      * @param dst            Pointer to the start of destination pixel memory
902      * @param rowBytes       Stride length in destination pixel memory
903      * @param zeroInit       Indicates if memory is zero initialized
904      * @param linesRequested Number of lines that the client requested
905      * @param linesDecoded   Number of lines that were successfully decoded
906      */
907     void fillIncompleteImage(const SkImageInfo& dstInfo, void* dst, size_t rowBytes,
908             ZeroInitialized zeroInit, int linesRequested, int linesDecoded);
909 
910     /**
911      *  Return an object which will allow forcing scanline decodes to sample in X.
912      *
913      *  May create a sampler, if one is not currently being used. Otherwise, does
914      *  not affect ownership.
915      *
916      *  Only valid during scanline decoding or incremental decoding.
917      */
getSampler(bool)918     virtual SkSampler* getSampler(bool /*createIfNecessary*/) { return nullptr; }
919 
920     friend class DM::CodecSrc;  // for fillIncompleteImage
921     friend class SkSampledCodec;
922     friend class SkIcoCodec;
923     friend class SkAndroidCodec; // for fEncodedInfo
924 };
925 #endif // SkCodec_DEFINED
926