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 uint8_t colorDepth = heifDecoder->getColorDepth();
180
181 SkEncodedInfo info = SkEncodedInfo::Make(heifInfo.mWidth, heifInfo.mHeight,
182 SkEncodedInfo::kYUV_Color, SkEncodedInfo::kOpaque_Alpha,
183 /*bitsPerComponent*/ 8, std::move(profile), colorDepth);
184 SkEncodedOrigin orientation = get_orientation(heifInfo);
185
186 *result = kSuccess;
187 return std::unique_ptr<SkCodec>(new SkHeifCodec(
188 std::move(info), heifDecoder.release(), orientation, frameCount > 1, format));
189 }
190
SkHeifCodec(SkEncodedInfo && info,HeifDecoder * heifDecoder,SkEncodedOrigin origin,bool useAnimation,SkEncodedImageFormat format)191 SkHeifCodec::SkHeifCodec(
192 SkEncodedInfo&& info,
193 HeifDecoder* heifDecoder,
194 SkEncodedOrigin origin,
195 bool useAnimation,
196 SkEncodedImageFormat format)
197 : INHERITED(std::move(info), skcms_PixelFormat_RGBA_8888, nullptr, origin)
198 , fHeifDecoder(heifDecoder)
199 , fSwizzleSrcRow(nullptr)
200 , fColorXformSrcRow(nullptr)
201 , fUseAnimation(useAnimation)
202 , fFormat(format)
203 {}
204
conversionSupported(const SkImageInfo & dstInfo,bool srcIsOpaque,bool needsColorXform)205 bool SkHeifCodec::conversionSupported(const SkImageInfo& dstInfo, bool srcIsOpaque,
206 bool needsColorXform) {
207 SkASSERT(srcIsOpaque);
208
209 if (kUnknown_SkAlphaType == dstInfo.alphaType()) {
210 return false;
211 }
212
213 if (kOpaque_SkAlphaType != dstInfo.alphaType()) {
214 SkCodecPrintf("Warning: an opaque image should be decoded as opaque "
215 "- it is being decoded as non-opaque, which will draw slower\n");
216 }
217
218 uint8_t colorDepth = fHeifDecoder->getColorDepth();
219 switch (dstInfo.colorType()) {
220 case kRGBA_8888_SkColorType:
221 this->setSrcXformFormat(skcms_PixelFormat_RGBA_8888);
222 return fHeifDecoder->setOutputColor(kHeifColorFormat_RGBA_8888);
223
224 case kBGRA_8888_SkColorType:
225 this->setSrcXformFormat(skcms_PixelFormat_RGBA_8888);
226 return fHeifDecoder->setOutputColor(kHeifColorFormat_BGRA_8888);
227
228 case kRGB_565_SkColorType:
229 this->setSrcXformFormat(skcms_PixelFormat_RGBA_8888);
230 if (needsColorXform) {
231 return fHeifDecoder->setOutputColor(kHeifColorFormat_RGBA_8888);
232 } else {
233 return fHeifDecoder->setOutputColor(kHeifColorFormat_RGB565);
234 }
235
236 case kRGBA_1010102_SkColorType:
237 this->setSrcXformFormat(skcms_PixelFormat_RGBA_1010102);
238 return fHeifDecoder->setOutputColor(kHeifColorFormat_RGBA_1010102);
239
240 case kRGBA_F16_SkColorType:
241 SkASSERT(needsColorXform);
242 if (srcIsOpaque && colorDepth == 10) {
243 this->setSrcXformFormat(skcms_PixelFormat_RGBA_1010102);
244 return fHeifDecoder->setOutputColor(kHeifColorFormat_RGBA_1010102);
245 } else {
246 this->setSrcXformFormat(skcms_PixelFormat_RGBA_8888);
247 return fHeifDecoder->setOutputColor(kHeifColorFormat_RGBA_8888);
248 }
249
250 default:
251 return false;
252 }
253 }
254
readRows(const SkImageInfo & dstInfo,void * dst,size_t rowBytes,int count,const Options & opts)255 int SkHeifCodec::readRows(const SkImageInfo& dstInfo, void* dst, size_t rowBytes, int count,
256 const Options& opts) {
257 // When fSwizzleSrcRow is non-null, it means that we need to swizzle. In this case,
258 // we will always decode into fSwizzlerSrcRow before swizzling into the next buffer.
259 // We can never swizzle "in place" because the swizzler may perform sampling and/or
260 // subsetting.
261 // When fColorXformSrcRow is non-null, it means that we need to color xform and that
262 // we cannot color xform "in place" (many times we can, but not when the dst is F16).
263 // In this case, we will color xform from fColorXformSrcRow into the dst.
264 uint8_t* decodeDst = (uint8_t*) dst;
265 uint32_t* swizzleDst = (uint32_t*) dst;
266 size_t decodeDstRowBytes = rowBytes;
267 size_t swizzleDstRowBytes = rowBytes;
268 int dstWidth = opts.fSubset ? opts.fSubset->width() : dstInfo.width();
269 if (fSwizzleSrcRow && fColorXformSrcRow) {
270 decodeDst = fSwizzleSrcRow;
271 swizzleDst = fColorXformSrcRow;
272 decodeDstRowBytes = 0;
273 swizzleDstRowBytes = 0;
274 dstWidth = fSwizzler->swizzleWidth();
275 } else if (fColorXformSrcRow) {
276 decodeDst = (uint8_t*) fColorXformSrcRow;
277 swizzleDst = fColorXformSrcRow;
278 decodeDstRowBytes = 0;
279 swizzleDstRowBytes = 0;
280 } else if (fSwizzleSrcRow) {
281 decodeDst = fSwizzleSrcRow;
282 decodeDstRowBytes = 0;
283 dstWidth = fSwizzler->swizzleWidth();
284 }
285
286 for (int y = 0; y < count; y++) {
287 if (!fHeifDecoder->getScanline(decodeDst)) {
288 return y;
289 }
290
291 if (fSwizzler) {
292 fSwizzler->swizzle(swizzleDst, decodeDst);
293 }
294
295 if (this->colorXform()) {
296 this->applyColorXform(dst, swizzleDst, dstWidth);
297 dst = SkTAddOffset<void>(dst, rowBytes);
298 }
299
300 decodeDst = SkTAddOffset<uint8_t>(decodeDst, decodeDstRowBytes);
301 swizzleDst = SkTAddOffset<uint32_t>(swizzleDst, swizzleDstRowBytes);
302 }
303
304 return count;
305 }
306
onGetFrameCount()307 int SkHeifCodec::onGetFrameCount() {
308 if (!fUseAnimation) {
309 return 1;
310 }
311
312 if (fFrameHolder.size() == 0) {
313 size_t frameCount;
314 HeifFrameInfo frameInfo;
315 if (!fHeifDecoder->getSequenceInfo(&frameInfo, &frameCount)
316 || frameCount <= 1) {
317 fUseAnimation = false;
318 return 1;
319 }
320 fFrameHolder.reserve(frameCount);
321 for (size_t i = 0; i < frameCount; i++) {
322 Frame* frame = fFrameHolder.appendNewFrame();
323 frame->setXYWH(0, 0, frameInfo.mWidth, frameInfo.mHeight);
324 frame->setDisposalMethod(SkCodecAnimation::DisposalMethod::kKeep);
325 // Currently we don't know the duration until the frame is actually
326 // decoded (onGetFrameInfo is also called before frame is decoded).
327 // For now, fill it base on the value reported for the sequence.
328 frame->setDuration(frameInfo.mDurationUs / 1000);
329 frame->setRequiredFrame(SkCodec::kNoFrame);
330 frame->setHasAlpha(false);
331 }
332 }
333
334 return fFrameHolder.size();
335 }
336
onGetFrame(int i) const337 const SkFrame* SkHeifCodec::FrameHolder::onGetFrame(int i) const {
338 return static_cast<const SkFrame*>(this->frame(i));
339 }
340
appendNewFrame()341 SkHeifCodec::Frame* SkHeifCodec::FrameHolder::appendNewFrame() {
342 const int i = this->size();
343 fFrames.emplace_back(i); // TODO: need to handle frame duration here
344 return &fFrames[i];
345 }
346
frame(int i) const347 const SkHeifCodec::Frame* SkHeifCodec::FrameHolder::frame(int i) const {
348 SkASSERT(i >= 0 && i < this->size());
349 return &fFrames[i];
350 }
351
editFrameAt(int i)352 SkHeifCodec::Frame* SkHeifCodec::FrameHolder::editFrameAt(int i) {
353 SkASSERT(i >= 0 && i < this->size());
354 return &fFrames[i];
355 }
356
onGetFrameInfo(int i,FrameInfo * frameInfo) const357 bool SkHeifCodec::onGetFrameInfo(int i, FrameInfo* frameInfo) const {
358 if (i >= fFrameHolder.size()) {
359 return false;
360 }
361
362 const Frame* frame = fFrameHolder.frame(i);
363 if (!frame) {
364 return false;
365 }
366
367 if (frameInfo) {
368 frame->fillIn(frameInfo, true);
369 }
370
371 return true;
372 }
373
onGetRepetitionCount()374 int SkHeifCodec::onGetRepetitionCount() {
375 return kRepetitionCountInfinite;
376 }
377
378 /*
379 * Performs the heif decode
380 */
onGetPixels(const SkImageInfo & dstInfo,void * dst,size_t dstRowBytes,const Options & options,int * rowsDecoded)381 SkCodec::Result SkHeifCodec::onGetPixels(const SkImageInfo& dstInfo,
382 void* dst, size_t dstRowBytes,
383 const Options& options,
384 int* rowsDecoded) {
385 if (options.fSubset) {
386 // Not supporting subsets on this path for now.
387 // TODO: if the heif has tiles, we can support subset here, but
388 // need to retrieve tile config from metadata retriever first.
389 return kUnimplemented;
390 }
391
392 bool success;
393 if (fUseAnimation) {
394 success = fHeifDecoder->decodeSequence(options.fFrameIndex, &fFrameInfo);
395 fFrameHolder.editFrameAt(options.fFrameIndex)->setDuration(
396 fFrameInfo.mDurationUs / 1000);
397 } else {
398 success = fHeifDecoder->decode(&fFrameInfo);
399 }
400
401 if (!success) {
402 return kInvalidInput;
403 }
404
405 fSwizzler.reset(nullptr);
406 this->allocateStorage(dstInfo);
407
408 int rows = this->readRows(dstInfo, dst, dstRowBytes, dstInfo.height(), options);
409 if (rows < dstInfo.height()) {
410 *rowsDecoded = rows;
411 return kIncompleteInput;
412 }
413
414 return kSuccess;
415 }
416
allocateStorage(const SkImageInfo & dstInfo)417 void SkHeifCodec::allocateStorage(const SkImageInfo& dstInfo) {
418 int dstWidth = dstInfo.width();
419
420 size_t swizzleBytes = 0;
421 if (fSwizzler) {
422 swizzleBytes = fFrameInfo.mBytesPerPixel * fFrameInfo.mWidth;
423 dstWidth = fSwizzler->swizzleWidth();
424 SkASSERT(!this->colorXform() || SkIsAlign4(swizzleBytes));
425 }
426
427 size_t xformBytes = 0;
428 if (this->colorXform() && (kRGBA_F16_SkColorType == dstInfo.colorType() ||
429 kRGB_565_SkColorType == dstInfo.colorType())) {
430 xformBytes = dstWidth * sizeof(uint32_t);
431 }
432
433 size_t totalBytes = swizzleBytes + xformBytes;
434 fStorage.reset(totalBytes);
435 if (totalBytes > 0) {
436 fSwizzleSrcRow = (swizzleBytes > 0) ? fStorage.get() : nullptr;
437 fColorXformSrcRow = (xformBytes > 0) ?
438 SkTAddOffset<uint32_t>(fStorage.get(), swizzleBytes) : nullptr;
439 }
440 }
441
initializeSwizzler(const SkImageInfo & dstInfo,const Options & options)442 void SkHeifCodec::initializeSwizzler(
443 const SkImageInfo& dstInfo, const Options& options) {
444 SkImageInfo swizzlerDstInfo = dstInfo;
445 switch (this->getSrcXformFormat()) {
446 case skcms_PixelFormat_RGBA_8888:
447 swizzlerDstInfo = swizzlerDstInfo.makeColorType(kRGBA_8888_SkColorType);
448 break;
449 case skcms_PixelFormat_RGBA_1010102:
450 swizzlerDstInfo = swizzlerDstInfo.makeColorType(kRGBA_1010102_SkColorType);
451 break;
452 default:
453 SkASSERT(false);
454 }
455
456 int srcBPP = 4;
457 if (dstInfo.colorType() == kRGB_565_SkColorType && !this->colorXform()) {
458 srcBPP = 2;
459 }
460
461 fSwizzler = SkSwizzler::MakeSimple(srcBPP, swizzlerDstInfo, options);
462 SkASSERT(fSwizzler);
463 }
464
getSampler(bool createIfNecessary)465 SkSampler* SkHeifCodec::getSampler(bool createIfNecessary) {
466 if (!createIfNecessary || fSwizzler) {
467 SkASSERT(!fSwizzler || (fSwizzleSrcRow && fStorage.get() == fSwizzleSrcRow));
468 return fSwizzler.get();
469 }
470
471 this->initializeSwizzler(this->dstInfo(), this->options());
472 this->allocateStorage(this->dstInfo());
473 return fSwizzler.get();
474 }
475
onRewind()476 bool SkHeifCodec::onRewind() {
477 fSwizzler.reset(nullptr);
478 fSwizzleSrcRow = nullptr;
479 fColorXformSrcRow = nullptr;
480 fStorage.reset();
481
482 return true;
483 }
484
onStartScanlineDecode(const SkImageInfo & dstInfo,const Options & options)485 SkCodec::Result SkHeifCodec::onStartScanlineDecode(
486 const SkImageInfo& dstInfo, const Options& options) {
487 // TODO: For now, just decode the whole thing even when there is a subset.
488 // If the heif image has tiles, we could potentially do this much faster,
489 // but the tile configuration needs to be retrieved from the metadata.
490 if (!fHeifDecoder->decode(&fFrameInfo)) {
491 return kInvalidInput;
492 }
493
494 if (options.fSubset) {
495 this->initializeSwizzler(dstInfo, options);
496 } else {
497 fSwizzler.reset(nullptr);
498 }
499
500 this->allocateStorage(dstInfo);
501
502 return kSuccess;
503 }
504
onGetScanlines(void * dst,int count,size_t dstRowBytes)505 int SkHeifCodec::onGetScanlines(void* dst, int count, size_t dstRowBytes) {
506 return this->readRows(this->dstInfo(), dst, dstRowBytes, count, this->options());
507 }
508
onSkipScanlines(int count)509 bool SkHeifCodec::onSkipScanlines(int count) {
510 return count == (int) fHeifDecoder->skipScanlines(count);
511 }
512
513 #endif // SK_HAS_HEIF_LIBRARY
514