• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright 2017 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 #include "include/core/SkTypes.h"
9 
10 #ifdef SK_HAS_HEIF_LIBRARY
11 #include "include/codec/SkCodec.h"
12 #include "include/core/SkStream.h"
13 #include "include/private/SkColorData.h"
14 #include "src/codec/SkCodecPriv.h"
15 #include "src/codec/SkHeifCodec.h"
16 #include "src/core/SkEndian.h"
17 
18 #define FOURCC(c1, c2, c3, c4) \
19     ((c1) << 24 | (c2) << 16 | (c3) << 8 | (c4))
20 
IsHeif(const void * buffer,size_t bytesRead)21 bool SkHeifCodec::IsHeif(const void* buffer, size_t bytesRead) {
22     // Parse the ftyp box up to bytesRead to determine if this is HEIF.
23     // Any valid ftyp box should have at least 8 bytes.
24     if (bytesRead < 8) {
25         return false;
26     }
27 
28     uint32_t* ptr = (uint32_t*)buffer;
29     uint64_t chunkSize = SkEndian_SwapBE32(ptr[0]);
30     uint32_t chunkType = SkEndian_SwapBE32(ptr[1]);
31 
32     if (chunkType != FOURCC('f', 't', 'y', 'p')) {
33         return false;
34     }
35 
36     int64_t offset = 8;
37     if (chunkSize == 1) {
38         // This indicates that the next 8 bytes represent the chunk size,
39         // and chunk data comes after that.
40         if (bytesRead < 16) {
41             return false;
42         }
43         auto* chunkSizePtr = SkTAddOffset<const uint64_t>(buffer, offset);
44         chunkSize = SkEndian_SwapBE64(*chunkSizePtr);
45         if (chunkSize < 16) {
46             // The smallest valid chunk is 16 bytes long in this case.
47             return false;
48         }
49         offset += 8;
50     } else if (chunkSize < 8) {
51         // The smallest valid chunk is 8 bytes long.
52         return false;
53     }
54 
55     if (chunkSize > bytesRead) {
56         chunkSize = bytesRead;
57     }
58     int64_t chunkDataSize = chunkSize - offset;
59     // It should at least have major brand (4-byte) and minor version (4-bytes).
60     // The rest of the chunk (if any) is a list of (4-byte) compatible brands.
61     if (chunkDataSize < 8) {
62         return false;
63     }
64 
65     uint32_t numCompatibleBrands = (chunkDataSize - 8) / 4;
66     for (size_t i = 0; i < numCompatibleBrands + 2; ++i) {
67         if (i == 1) {
68             // Skip this index, it refers to the minorVersion,
69             // not a brand.
70             continue;
71         }
72         auto* brandPtr = SkTAddOffset<const uint32_t>(buffer, offset + 4 * i);
73         uint32_t brand = SkEndian_SwapBE32(*brandPtr);
74         if (brand == FOURCC('m', 'i', 'f', '1') || brand == FOURCC('h', 'e', 'i', 'c')
75          || brand == FOURCC('m', 's', 'f', '1') || brand == FOURCC('h', 'e', 'v', 'c')) {
76             return true;
77         }
78     }
79     return false;
80 }
81 
get_orientation(const HeifFrameInfo & frameInfo)82 static SkEncodedOrigin get_orientation(const HeifFrameInfo& frameInfo) {
83     switch (frameInfo.mRotationAngle) {
84         case 0:   return kTopLeft_SkEncodedOrigin;
85         case 90:  return kRightTop_SkEncodedOrigin;
86         case 180: return kBottomRight_SkEncodedOrigin;
87         case 270: return kLeftBottom_SkEncodedOrigin;
88     }
89     return kDefault_SkEncodedOrigin;
90 }
91 
92 struct SkHeifStreamWrapper : public HeifStream {
SkHeifStreamWrapperSkHeifStreamWrapper93     SkHeifStreamWrapper(SkStream* stream) : fStream(stream) {}
94 
~SkHeifStreamWrapperSkHeifStreamWrapper95     ~SkHeifStreamWrapper() override {}
96 
readSkHeifStreamWrapper97     size_t read(void* buffer, size_t size) override {
98         return fStream->read(buffer, size);
99     }
100 
rewindSkHeifStreamWrapper101     bool rewind() override {
102         return fStream->rewind();
103     }
104 
seekSkHeifStreamWrapper105     bool seek(size_t position) override {
106         return fStream->seek(position);
107     }
108 
hasLengthSkHeifStreamWrapper109     bool hasLength() const override {
110         return fStream->hasLength();
111     }
112 
getLengthSkHeifStreamWrapper113     size_t getLength() const override {
114         return fStream->getLength();
115     }
116 
117 private:
118     std::unique_ptr<SkStream> fStream;
119 };
120 
121 #ifndef SK_LEGACY_HEIF_API
releaseProc(const void * ptr,void * context)122 static void releaseProc(const void* ptr, void* context) {
123     delete reinterpret_cast<std::vector<uint8_t>*>(context);
124 }
125 #endif
126 
MakeFromStream(std::unique_ptr<SkStream> stream,SkCodec::SelectionPolicy selectionPolicy,Result * result)127 std::unique_ptr<SkCodec> SkHeifCodec::MakeFromStream(std::unique_ptr<SkStream> stream,
128         SkCodec::SelectionPolicy selectionPolicy, Result* result) {
129     std::unique_ptr<HeifDecoder> heifDecoder(createHeifDecoder());
130     if (heifDecoder.get() == nullptr) {
131         *result = kInternalError;
132         return nullptr;
133     }
134 
135     HeifFrameInfo heifInfo;
136     if (!heifDecoder->init(new SkHeifStreamWrapper(stream.release()), &heifInfo)) {
137         *result = kInvalidInput;
138         return nullptr;
139     }
140 
141 #ifndef SK_LEGACY_HEIF_API
142     size_t frameCount = 1;
143     if (selectionPolicy == SkCodec::SelectionPolicy::kPreferAnimation) {
144         HeifFrameInfo sequenceInfo;
145         if (heifDecoder->getSequenceInfo(&sequenceInfo, &frameCount) &&
146                 frameCount > 1) {
147             heifInfo = std::move(sequenceInfo);
148         }
149     }
150 #endif
151 
152     std::unique_ptr<SkEncodedInfo::ICCProfile> profile = nullptr;
153 #ifdef SK_LEGACY_HEIF_API
154     if ((heifInfo.mIccSize > 0) && (heifInfo.mIccData != nullptr)) {
155         // FIXME: Would it be possible to use MakeWithoutCopy?
156         auto icc = SkData::MakeWithCopy(heifInfo.mIccData.get(), heifInfo.mIccSize);
157         profile = SkEncodedInfo::ICCProfile::Make(std::move(icc));
158     }
159 #else
160     if (heifInfo.mIccData.size() > 0) {
161         auto iccData = new std::vector<uint8_t>(std::move(heifInfo.mIccData));
162         auto icc = SkData::MakeWithProc(iccData->data(), iccData->size(), releaseProc, iccData);
163         profile = SkEncodedInfo::ICCProfile::Make(std::move(icc));
164     }
165 #endif
166     if (profile && profile->profile()->data_color_space != skcms_Signature_RGB) {
167         // This will result in sRGB.
168         profile = nullptr;
169     }
170 
171     SkEncodedInfo info = SkEncodedInfo::Make(heifInfo.mWidth, heifInfo.mHeight,
172             SkEncodedInfo::kYUV_Color, SkEncodedInfo::kOpaque_Alpha, 8, std::move(profile));
173     SkEncodedOrigin orientation = get_orientation(heifInfo);
174 
175     *result = kSuccess;
176     return std::unique_ptr<SkCodec>(new SkHeifCodec(
177             std::move(info), heifDecoder.release(), orientation
178 #ifndef SK_LEGACY_HEIF_API
179             , frameCount > 1
180 #endif
181             ));
182 }
183 
SkHeifCodec(SkEncodedInfo && info,HeifDecoder * heifDecoder,SkEncodedOrigin origin,bool useAnimation)184 SkHeifCodec::SkHeifCodec(
185         SkEncodedInfo&& info,
186         HeifDecoder* heifDecoder,
187         SkEncodedOrigin origin
188 #ifndef SK_LEGACY_HEIF_API
189         , bool useAnimation
190 #endif
191         )
192     : INHERITED(std::move(info), skcms_PixelFormat_RGBA_8888, nullptr, origin)
193     , fHeifDecoder(heifDecoder)
194     , fSwizzleSrcRow(nullptr)
195     , fColorXformSrcRow(nullptr)
196 #ifndef SK_LEGACY_HEIF_API
197     , fUseAnimation(useAnimation)
198 #endif
199 {}
200 
conversionSupported(const SkImageInfo & dstInfo,bool srcIsOpaque,bool needsColorXform)201 bool SkHeifCodec::conversionSupported(const SkImageInfo& dstInfo, bool srcIsOpaque,
202                                       bool needsColorXform) {
203     SkASSERT(srcIsOpaque);
204 
205     if (kUnknown_SkAlphaType == dstInfo.alphaType()) {
206         return false;
207     }
208 
209     if (kOpaque_SkAlphaType != dstInfo.alphaType()) {
210         SkCodecPrintf("Warning: an opaque image should be decoded as opaque "
211                 "- it is being decoded as non-opaque, which will draw slower\n");
212     }
213 
214     switch (dstInfo.colorType()) {
215         case kRGBA_8888_SkColorType:
216             return fHeifDecoder->setOutputColor(kHeifColorFormat_RGBA_8888);
217 
218         case kBGRA_8888_SkColorType:
219             return fHeifDecoder->setOutputColor(kHeifColorFormat_BGRA_8888);
220 
221         case kRGB_565_SkColorType:
222             if (needsColorXform) {
223                 return fHeifDecoder->setOutputColor(kHeifColorFormat_RGBA_8888);
224             } else {
225                 return fHeifDecoder->setOutputColor(kHeifColorFormat_RGB565);
226             }
227 
228         case kRGBA_F16_SkColorType:
229             SkASSERT(needsColorXform);
230             return fHeifDecoder->setOutputColor(kHeifColorFormat_RGBA_8888);
231 
232         default:
233             return false;
234     }
235 }
236 
readRows(const SkImageInfo & dstInfo,void * dst,size_t rowBytes,int count,const Options & opts)237 int SkHeifCodec::readRows(const SkImageInfo& dstInfo, void* dst, size_t rowBytes, int count,
238                           const Options& opts) {
239     // When fSwizzleSrcRow is non-null, it means that we need to swizzle.  In this case,
240     // we will always decode into fSwizzlerSrcRow before swizzling into the next buffer.
241     // We can never swizzle "in place" because the swizzler may perform sampling and/or
242     // subsetting.
243     // When fColorXformSrcRow is non-null, it means that we need to color xform and that
244     // we cannot color xform "in place" (many times we can, but not when the dst is F16).
245     // In this case, we will color xform from fColorXformSrcRow into the dst.
246     uint8_t* decodeDst = (uint8_t*) dst;
247     uint32_t* swizzleDst = (uint32_t*) dst;
248     size_t decodeDstRowBytes = rowBytes;
249     size_t swizzleDstRowBytes = rowBytes;
250     int dstWidth = opts.fSubset ? opts.fSubset->width() : dstInfo.width();
251     if (fSwizzleSrcRow && fColorXformSrcRow) {
252         decodeDst = fSwizzleSrcRow;
253         swizzleDst = fColorXformSrcRow;
254         decodeDstRowBytes = 0;
255         swizzleDstRowBytes = 0;
256         dstWidth = fSwizzler->swizzleWidth();
257     } else if (fColorXformSrcRow) {
258         decodeDst = (uint8_t*) fColorXformSrcRow;
259         swizzleDst = fColorXformSrcRow;
260         decodeDstRowBytes = 0;
261         swizzleDstRowBytes = 0;
262     } else if (fSwizzleSrcRow) {
263         decodeDst = fSwizzleSrcRow;
264         decodeDstRowBytes = 0;
265         dstWidth = fSwizzler->swizzleWidth();
266     }
267 
268     for (int y = 0; y < count; y++) {
269         if (!fHeifDecoder->getScanline(decodeDst)) {
270             return y;
271         }
272 
273         if (fSwizzler) {
274             fSwizzler->swizzle(swizzleDst, decodeDst);
275         }
276 
277         if (this->colorXform()) {
278             this->applyColorXform(dst, swizzleDst, dstWidth);
279             dst = SkTAddOffset<void>(dst, rowBytes);
280         }
281 
282         decodeDst = SkTAddOffset<uint8_t>(decodeDst, decodeDstRowBytes);
283         swizzleDst = SkTAddOffset<uint32_t>(swizzleDst, swizzleDstRowBytes);
284     }
285 
286     return count;
287 }
288 
289 #ifndef SK_LEGACY_HEIF_API
onGetFrameCount()290 int SkHeifCodec::onGetFrameCount() {
291     if (!fUseAnimation) {
292         return 1;
293     }
294 
295     if (fFrameHolder.size() == 0) {
296         size_t frameCount;
297         HeifFrameInfo frameInfo;
298         if (!fHeifDecoder->getSequenceInfo(&frameInfo, &frameCount)
299                 || frameCount <= 1) {
300             fUseAnimation = false;
301             return 1;
302         }
303         fFrameHolder.reserve(frameCount);
304         for (size_t i = 0; i < frameCount; i++) {
305             Frame* frame = fFrameHolder.appendNewFrame();
306             frame->setXYWH(0, 0, frameInfo.mWidth, frameInfo.mHeight);
307             frame->setDisposalMethod(SkCodecAnimation::DisposalMethod::kKeep);
308             // TODO: fill in per-frame durations
309             // Currently we don't know the duration until the frame is actually
310             // decoded (onGetFrameInfo is also called before frame is decoded).
311             // For now, fill it base on the value reported for the sequence.
312             frame->setDuration(frameInfo.mDurationUs / 1000);
313             frame->setRequiredFrame(SkCodec::kNoFrame);
314             frame->setHasAlpha(false);
315         }
316     }
317 
318     return fFrameHolder.size();
319 }
320 
onGetFrame(int i) const321 const SkFrame* SkHeifCodec::FrameHolder::onGetFrame(int i) const {
322     return static_cast<const SkFrame*>(this->frame(i));
323 }
324 
appendNewFrame()325 SkHeifCodec::Frame* SkHeifCodec::FrameHolder::appendNewFrame() {
326     const int i = this->size();
327     fFrames.emplace_back(i); // TODO: need to handle frame duration here
328     return &fFrames[i];
329 }
330 
frame(int i) const331 const SkHeifCodec::Frame* SkHeifCodec::FrameHolder::frame(int i) const {
332     SkASSERT(i >= 0 && i < this->size());
333     return &fFrames[i];
334 }
335 
onGetFrameInfo(int i,FrameInfo * frameInfo) const336 bool SkHeifCodec::onGetFrameInfo(int i, FrameInfo* frameInfo) const {
337     if (i >= fFrameHolder.size()) {
338         return false;
339     }
340 
341     const Frame* frame = fFrameHolder.frame(i);
342     if (!frame) {
343         return false;
344     }
345 
346     if (frameInfo) {
347         frameInfo->fRequiredFrame = SkCodec::kNoFrame;
348         frameInfo->fDuration = frame->getDuration();
349         frameInfo->fFullyReceived = true;
350         frameInfo->fAlphaType = kOpaque_SkAlphaType;
351         frameInfo->fDisposalMethod = SkCodecAnimation::DisposalMethod::kKeep;
352     }
353 
354     return true;
355 }
356 
onGetRepetitionCount()357 int SkHeifCodec::onGetRepetitionCount() {
358     return kRepetitionCountInfinite;
359 }
360 #endif // SK_LEGACY_HEIF_API
361 
362 /*
363  * Performs the heif decode
364  */
onGetPixels(const SkImageInfo & dstInfo,void * dst,size_t dstRowBytes,const Options & options,int * rowsDecoded)365 SkCodec::Result SkHeifCodec::onGetPixels(const SkImageInfo& dstInfo,
366                                          void* dst, size_t dstRowBytes,
367                                          const Options& options,
368                                          int* rowsDecoded) {
369     if (options.fSubset) {
370         // Not supporting subsets on this path for now.
371         // TODO: if the heif has tiles, we can support subset here, but
372         // need to retrieve tile config from metadata retriever first.
373         return kUnimplemented;
374     }
375 
376 #ifdef SK_LEGACY_HEIF_API
377     if (!fHeifDecoder->decode(&fFrameInfo)) {
378         return kInvalidInput;
379     }
380 #else
381     bool success;
382     if (fUseAnimation) {
383         success = fHeifDecoder->decodeSequence(options.fFrameIndex, &fFrameInfo);
384     } else {
385         success = fHeifDecoder->decode(&fFrameInfo);
386     }
387 
388     if (!success) {
389         return kInvalidInput;
390     }
391 #endif // SK_LEGACY_HEIF_API
392 
393     fSwizzler.reset(nullptr);
394     this->allocateStorage(dstInfo);
395 
396     int rows = this->readRows(dstInfo, dst, dstRowBytes, dstInfo.height(), options);
397     if (rows < dstInfo.height()) {
398         *rowsDecoded = rows;
399         return kIncompleteInput;
400     }
401 
402     return kSuccess;
403 }
404 
allocateStorage(const SkImageInfo & dstInfo)405 void SkHeifCodec::allocateStorage(const SkImageInfo& dstInfo) {
406     int dstWidth = dstInfo.width();
407 
408     size_t swizzleBytes = 0;
409     if (fSwizzler) {
410         swizzleBytes = fFrameInfo.mBytesPerPixel * fFrameInfo.mWidth;
411         dstWidth = fSwizzler->swizzleWidth();
412         SkASSERT(!this->colorXform() || SkIsAlign4(swizzleBytes));
413     }
414 
415     size_t xformBytes = 0;
416     if (this->colorXform() && (kRGBA_F16_SkColorType == dstInfo.colorType() ||
417                                kRGB_565_SkColorType == dstInfo.colorType())) {
418         xformBytes = dstWidth * sizeof(uint32_t);
419     }
420 
421     size_t totalBytes = swizzleBytes + xformBytes;
422     fStorage.reset(totalBytes);
423     if (totalBytes > 0) {
424         fSwizzleSrcRow = (swizzleBytes > 0) ? fStorage.get() : nullptr;
425         fColorXformSrcRow = (xformBytes > 0) ?
426                 SkTAddOffset<uint32_t>(fStorage.get(), swizzleBytes) : nullptr;
427     }
428 }
429 
initializeSwizzler(const SkImageInfo & dstInfo,const Options & options)430 void SkHeifCodec::initializeSwizzler(
431         const SkImageInfo& dstInfo, const Options& options) {
432     SkImageInfo swizzlerDstInfo = dstInfo;
433     if (this->colorXform()) {
434         // The color xform will be expecting RGBA 8888 input.
435         swizzlerDstInfo = swizzlerDstInfo.makeColorType(kRGBA_8888_SkColorType);
436     }
437 
438     int srcBPP = 4;
439     if (dstInfo.colorType() == kRGB_565_SkColorType && !this->colorXform()) {
440         srcBPP = 2;
441     }
442 
443     fSwizzler = SkSwizzler::MakeSimple(srcBPP, swizzlerDstInfo, options);
444     SkASSERT(fSwizzler);
445 }
446 
getSampler(bool createIfNecessary)447 SkSampler* SkHeifCodec::getSampler(bool createIfNecessary) {
448     if (!createIfNecessary || fSwizzler) {
449         SkASSERT(!fSwizzler || (fSwizzleSrcRow && fStorage.get() == fSwizzleSrcRow));
450         return fSwizzler.get();
451     }
452 
453     this->initializeSwizzler(this->dstInfo(), this->options());
454     this->allocateStorage(this->dstInfo());
455     return fSwizzler.get();
456 }
457 
onRewind()458 bool SkHeifCodec::onRewind() {
459     fSwizzler.reset(nullptr);
460     fSwizzleSrcRow = nullptr;
461     fColorXformSrcRow = nullptr;
462     fStorage.reset();
463 
464     return true;
465 }
466 
onStartScanlineDecode(const SkImageInfo & dstInfo,const Options & options)467 SkCodec::Result SkHeifCodec::onStartScanlineDecode(
468         const SkImageInfo& dstInfo, const Options& options) {
469     // TODO: For now, just decode the whole thing even when there is a subset.
470     // If the heif image has tiles, we could potentially do this much faster,
471     // but the tile configuration needs to be retrieved from the metadata.
472     if (!fHeifDecoder->decode(&fFrameInfo)) {
473         return kInvalidInput;
474     }
475 
476     if (options.fSubset) {
477         this->initializeSwizzler(dstInfo, options);
478     } else {
479         fSwizzler.reset(nullptr);
480     }
481 
482     this->allocateStorage(dstInfo);
483 
484     return kSuccess;
485 }
486 
onGetScanlines(void * dst,int count,size_t dstRowBytes)487 int SkHeifCodec::onGetScanlines(void* dst, int count, size_t dstRowBytes) {
488     return this->readRows(this->dstInfo(), dst, dstRowBytes, count, this->options());
489 }
490 
onSkipScanlines(int count)491 bool SkHeifCodec::onSkipScanlines(int count) {
492     return count == (int) fHeifDecoder->skipScanlines(count);
493 }
494 
495 #endif // SK_HAS_HEIF_LIBRARY
496