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