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 frame->fillIn(frameInfo, true);
352 }
353
354 return true;
355 }
356
onGetRepetitionCount()357 int SkHeifCodec::onGetRepetitionCount() {
358 return kRepetitionCountInfinite;
359 }
360
361 /*
362 * Performs the heif decode
363 */
onGetPixels(const SkImageInfo & dstInfo,void * dst,size_t dstRowBytes,const Options & options,int * rowsDecoded)364 SkCodec::Result SkHeifCodec::onGetPixels(const SkImageInfo& dstInfo,
365 void* dst, size_t dstRowBytes,
366 const Options& options,
367 int* rowsDecoded) {
368 if (options.fSubset) {
369 // Not supporting subsets on this path for now.
370 // TODO: if the heif has tiles, we can support subset here, but
371 // need to retrieve tile config from metadata retriever first.
372 return kUnimplemented;
373 }
374
375 bool success;
376 if (fUseAnimation) {
377 success = fHeifDecoder->decodeSequence(options.fFrameIndex, &fFrameInfo);
378 fFrameHolder.editFrameAt(options.fFrameIndex)->setDuration(
379 fFrameInfo.mDurationUs / 1000);
380 } else {
381 success = fHeifDecoder->decode(&fFrameInfo);
382 }
383
384 if (!success) {
385 return kInvalidInput;
386 }
387
388 fSwizzler.reset(nullptr);
389 this->allocateStorage(dstInfo);
390
391 int rows = this->readRows(dstInfo, dst, dstRowBytes, dstInfo.height(), options);
392 if (rows < dstInfo.height()) {
393 *rowsDecoded = rows;
394 return kIncompleteInput;
395 }
396
397 return kSuccess;
398 }
399
allocateStorage(const SkImageInfo & dstInfo)400 void SkHeifCodec::allocateStorage(const SkImageInfo& dstInfo) {
401 int dstWidth = dstInfo.width();
402
403 size_t swizzleBytes = 0;
404 if (fSwizzler) {
405 swizzleBytes = fFrameInfo.mBytesPerPixel * fFrameInfo.mWidth;
406 dstWidth = fSwizzler->swizzleWidth();
407 SkASSERT(!this->colorXform() || SkIsAlign4(swizzleBytes));
408 }
409
410 size_t xformBytes = 0;
411 if (this->colorXform() && (kRGBA_F16_SkColorType == dstInfo.colorType() ||
412 kRGB_565_SkColorType == dstInfo.colorType())) {
413 xformBytes = dstWidth * sizeof(uint32_t);
414 }
415
416 size_t totalBytes = swizzleBytes + xformBytes;
417 fStorage.reset(totalBytes);
418 if (totalBytes > 0) {
419 fSwizzleSrcRow = (swizzleBytes > 0) ? fStorage.get() : nullptr;
420 fColorXformSrcRow = (xformBytes > 0) ?
421 SkTAddOffset<uint32_t>(fStorage.get(), swizzleBytes) : nullptr;
422 }
423 }
424
initializeSwizzler(const SkImageInfo & dstInfo,const Options & options)425 void SkHeifCodec::initializeSwizzler(
426 const SkImageInfo& dstInfo, const Options& options) {
427 SkImageInfo swizzlerDstInfo = dstInfo;
428 if (this->colorXform()) {
429 // The color xform will be expecting RGBA 8888 input.
430 swizzlerDstInfo = swizzlerDstInfo.makeColorType(kRGBA_8888_SkColorType);
431 }
432
433 int srcBPP = 4;
434 if (dstInfo.colorType() == kRGB_565_SkColorType && !this->colorXform()) {
435 srcBPP = 2;
436 }
437
438 fSwizzler = SkSwizzler::MakeSimple(srcBPP, swizzlerDstInfo, options);
439 SkASSERT(fSwizzler);
440 }
441
getSampler(bool createIfNecessary)442 SkSampler* SkHeifCodec::getSampler(bool createIfNecessary) {
443 if (!createIfNecessary || fSwizzler) {
444 SkASSERT(!fSwizzler || (fSwizzleSrcRow && fStorage.get() == fSwizzleSrcRow));
445 return fSwizzler.get();
446 }
447
448 this->initializeSwizzler(this->dstInfo(), this->options());
449 this->allocateStorage(this->dstInfo());
450 return fSwizzler.get();
451 }
452
onRewind()453 bool SkHeifCodec::onRewind() {
454 fSwizzler.reset(nullptr);
455 fSwizzleSrcRow = nullptr;
456 fColorXformSrcRow = nullptr;
457 fStorage.reset();
458
459 return true;
460 }
461
onStartScanlineDecode(const SkImageInfo & dstInfo,const Options & options)462 SkCodec::Result SkHeifCodec::onStartScanlineDecode(
463 const SkImageInfo& dstInfo, const Options& options) {
464 // TODO: For now, just decode the whole thing even when there is a subset.
465 // If the heif image has tiles, we could potentially do this much faster,
466 // but the tile configuration needs to be retrieved from the metadata.
467 if (!fHeifDecoder->decode(&fFrameInfo)) {
468 return kInvalidInput;
469 }
470
471 if (options.fSubset) {
472 this->initializeSwizzler(dstInfo, options);
473 } else {
474 fSwizzler.reset(nullptr);
475 }
476
477 this->allocateStorage(dstInfo);
478
479 return kSuccess;
480 }
481
onGetScanlines(void * dst,int count,size_t dstRowBytes)482 int SkHeifCodec::onGetScanlines(void* dst, int count, size_t dstRowBytes) {
483 return this->readRows(this->dstInfo(), dst, dstRowBytes, count, this->options());
484 }
485
onSkipScanlines(int count)486 bool SkHeifCodec::onSkipScanlines(int count) {
487 return count == (int) fHeifDecoder->skipScanlines(count);
488 }
489
490 #endif // SK_HAS_HEIF_LIBRARY
491