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 "SkTypes.h"
9
10 #ifdef SK_HAS_HEIF_LIBRARY
11 #include "SkCodec.h"
12 #include "SkCodecPriv.h"
13 #include "SkColorData.h"
14 #include "SkEndian.h"
15 #include "SkStream.h"
16 #include "SkHeifCodec.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
MakeFromStream(std::unique_ptr<SkStream> stream,Result * result)121 std::unique_ptr<SkCodec> SkHeifCodec::MakeFromStream(
122 std::unique_ptr<SkStream> stream, Result* result) {
123 std::unique_ptr<HeifDecoder> heifDecoder(createHeifDecoder());
124 if (heifDecoder.get() == nullptr) {
125 *result = kInternalError;
126 return nullptr;
127 }
128
129 HeifFrameInfo frameInfo;
130 if (!heifDecoder->init(new SkHeifStreamWrapper(stream.release()),
131 &frameInfo)) {
132 *result = kInvalidInput;
133 return nullptr;
134 }
135
136 SkEncodedInfo info = SkEncodedInfo::Make(
137 SkEncodedInfo::kYUV_Color, SkEncodedInfo::kOpaque_Alpha, 8);
138
139 SkEncodedOrigin orientation = get_orientation(frameInfo);
140
141 sk_sp<SkColorSpace> colorSpace = nullptr;
142 if ((frameInfo.mIccSize > 0) && (frameInfo.mIccData != nullptr)) {
143 colorSpace = SkColorSpace::MakeICC(frameInfo.mIccData.get(),
144 frameInfo.mIccSize);
145 }
146 if (!colorSpace || colorSpace->type() != SkColorSpace::kRGB_Type) {
147 colorSpace = SkColorSpace::MakeSRGB();
148 }
149
150 *result = kSuccess;
151 return std::unique_ptr<SkCodec>(new SkHeifCodec(frameInfo.mWidth, frameInfo.mHeight,
152 info, heifDecoder.release(), std::move(colorSpace), orientation));
153 }
154
SkHeifCodec(int width,int height,const SkEncodedInfo & info,HeifDecoder * heifDecoder,sk_sp<SkColorSpace> colorSpace,SkEncodedOrigin origin)155 SkHeifCodec::SkHeifCodec(int width, int height, const SkEncodedInfo& info,
156 HeifDecoder* heifDecoder, sk_sp<SkColorSpace> colorSpace, SkEncodedOrigin origin)
157 : INHERITED(width, height, info, SkColorSpaceXform::kRGBA_8888_ColorFormat,
158 nullptr, std::move(colorSpace), origin)
159 , fHeifDecoder(heifDecoder)
160 , fSwizzleSrcRow(nullptr)
161 , fColorXformSrcRow(nullptr)
162 {}
163
164 /*
165 * Checks if the conversion between the input image and the requested output
166 * image has been implemented
167 * Sets the output color format
168 */
setOutputColorFormat(const SkImageInfo & dstInfo)169 bool SkHeifCodec::setOutputColorFormat(const SkImageInfo& dstInfo) {
170 if (kUnknown_SkAlphaType == dstInfo.alphaType()) {
171 return false;
172 }
173
174 if (kOpaque_SkAlphaType != dstInfo.alphaType()) {
175 SkCodecPrintf("Warning: an opaque image should be decoded as opaque "
176 "- it is being decoded as non-opaque, which will draw slower\n");
177 }
178
179 switch (dstInfo.colorType()) {
180 case kRGBA_8888_SkColorType:
181 return fHeifDecoder->setOutputColor(kHeifColorFormat_RGBA_8888);
182
183 case kBGRA_8888_SkColorType:
184 return fHeifDecoder->setOutputColor(kHeifColorFormat_BGRA_8888);
185
186 case kRGB_565_SkColorType:
187 if (this->colorXform()) {
188 return fHeifDecoder->setOutputColor(kHeifColorFormat_RGBA_8888);
189 } else {
190 return fHeifDecoder->setOutputColor(kHeifColorFormat_RGB565);
191 }
192
193 case kRGBA_F16_SkColorType:
194 SkASSERT(this->colorXform());
195
196 if (!dstInfo.colorSpace()->gammaIsLinear()) {
197 return false;
198 }
199 return fHeifDecoder->setOutputColor(kHeifColorFormat_RGBA_8888);
200
201 default:
202 return false;
203 }
204 }
205
readRows(const SkImageInfo & dstInfo,void * dst,size_t rowBytes,int count,const Options & opts)206 int SkHeifCodec::readRows(const SkImageInfo& dstInfo, void* dst, size_t rowBytes, int count,
207 const Options& opts) {
208 // When fSwizzleSrcRow is non-null, it means that we need to swizzle. In this case,
209 // we will always decode into fSwizzlerSrcRow before swizzling into the next buffer.
210 // We can never swizzle "in place" because the swizzler may perform sampling and/or
211 // subsetting.
212 // When fColorXformSrcRow is non-null, it means that we need to color xform and that
213 // we cannot color xform "in place" (many times we can, but not when the dst is F16).
214 // In this case, we will color xform from fColorXformSrcRow into the dst.
215 uint8_t* decodeDst = (uint8_t*) dst;
216 uint32_t* swizzleDst = (uint32_t*) dst;
217 size_t decodeDstRowBytes = rowBytes;
218 size_t swizzleDstRowBytes = rowBytes;
219 int dstWidth = opts.fSubset ? opts.fSubset->width() : dstInfo.width();
220 if (fSwizzleSrcRow && fColorXformSrcRow) {
221 decodeDst = fSwizzleSrcRow;
222 swizzleDst = fColorXformSrcRow;
223 decodeDstRowBytes = 0;
224 swizzleDstRowBytes = 0;
225 dstWidth = fSwizzler->swizzleWidth();
226 } else if (fColorXformSrcRow) {
227 decodeDst = (uint8_t*) fColorXformSrcRow;
228 swizzleDst = fColorXformSrcRow;
229 decodeDstRowBytes = 0;
230 swizzleDstRowBytes = 0;
231 } else if (fSwizzleSrcRow) {
232 decodeDst = fSwizzleSrcRow;
233 decodeDstRowBytes = 0;
234 dstWidth = fSwizzler->swizzleWidth();
235 }
236
237 for (int y = 0; y < count; y++) {
238 if (!fHeifDecoder->getScanline(decodeDst)) {
239 return y;
240 }
241
242 if (fSwizzler) {
243 fSwizzler->swizzle(swizzleDst, decodeDst);
244 }
245
246 if (this->colorXform()) {
247 this->applyColorXform(dst, swizzleDst, dstWidth, kOpaque_SkAlphaType);
248 dst = SkTAddOffset<void>(dst, rowBytes);
249 }
250
251 decodeDst = SkTAddOffset<uint8_t>(decodeDst, decodeDstRowBytes);
252 swizzleDst = SkTAddOffset<uint32_t>(swizzleDst, swizzleDstRowBytes);
253 }
254
255 return count;
256 }
257
258 /*
259 * Performs the heif decode
260 */
onGetPixels(const SkImageInfo & dstInfo,void * dst,size_t dstRowBytes,const Options & options,int * rowsDecoded)261 SkCodec::Result SkHeifCodec::onGetPixels(const SkImageInfo& dstInfo,
262 void* dst, size_t dstRowBytes,
263 const Options& options,
264 int* rowsDecoded) {
265 if (options.fSubset) {
266 // Not supporting subsets on this path for now.
267 // TODO: if the heif has tiles, we can support subset here, but
268 // need to retrieve tile config from metadata retriever first.
269 return kUnimplemented;
270 }
271
272 // Check if we can decode to the requested destination and set the output color space
273 if (!this->setOutputColorFormat(dstInfo)) {
274 return kInvalidConversion;
275 }
276
277 if (!fHeifDecoder->decode(&fFrameInfo)) {
278 return kInvalidInput;
279 }
280
281 fSwizzler.reset(nullptr);
282 this->allocateStorage(dstInfo);
283
284 int rows = this->readRows(dstInfo, dst, dstRowBytes, dstInfo.height(), options);
285 if (rows < dstInfo.height()) {
286 *rowsDecoded = rows;
287 return kIncompleteInput;
288 }
289
290 return kSuccess;
291 }
292
allocateStorage(const SkImageInfo & dstInfo)293 void SkHeifCodec::allocateStorage(const SkImageInfo& dstInfo) {
294 int dstWidth = dstInfo.width();
295
296 size_t swizzleBytes = 0;
297 if (fSwizzler) {
298 swizzleBytes = fFrameInfo.mBytesPerPixel * fFrameInfo.mWidth;
299 dstWidth = fSwizzler->swizzleWidth();
300 SkASSERT(!this->colorXform() || SkIsAlign4(swizzleBytes));
301 }
302
303 size_t xformBytes = 0;
304 if (this->colorXform() && (kRGBA_F16_SkColorType == dstInfo.colorType() ||
305 kRGB_565_SkColorType == dstInfo.colorType())) {
306 xformBytes = dstWidth * sizeof(uint32_t);
307 }
308
309 size_t totalBytes = swizzleBytes + xformBytes;
310 fStorage.reset(totalBytes);
311 if (totalBytes > 0) {
312 fSwizzleSrcRow = (swizzleBytes > 0) ? fStorage.get() : nullptr;
313 fColorXformSrcRow = (xformBytes > 0) ?
314 SkTAddOffset<uint32_t>(fStorage.get(), swizzleBytes) : nullptr;
315 }
316 }
317
initializeSwizzler(const SkImageInfo & dstInfo,const Options & options)318 void SkHeifCodec::initializeSwizzler(
319 const SkImageInfo& dstInfo, const Options& options) {
320 SkImageInfo swizzlerDstInfo = dstInfo;
321 if (this->colorXform()) {
322 // The color xform will be expecting RGBA 8888 input.
323 swizzlerDstInfo = swizzlerDstInfo.makeColorType(kRGBA_8888_SkColorType);
324 }
325
326 int srcBPP = 4;
327 if (dstInfo.colorType() == kRGB_565_SkColorType && !this->colorXform()) {
328 srcBPP = 2;
329 }
330
331 fSwizzler = SkSwizzler::MakeSimple(srcBPP, swizzlerDstInfo, options);
332 SkASSERT(fSwizzler);
333 }
334
getSampler(bool createIfNecessary)335 SkSampler* SkHeifCodec::getSampler(bool createIfNecessary) {
336 if (!createIfNecessary || fSwizzler) {
337 SkASSERT(!fSwizzler || (fSwizzleSrcRow && fStorage.get() == fSwizzleSrcRow));
338 return fSwizzler.get();
339 }
340
341 this->initializeSwizzler(this->dstInfo(), this->options());
342 this->allocateStorage(this->dstInfo());
343 return fSwizzler.get();
344 }
345
onStartScanlineDecode(const SkImageInfo & dstInfo,const Options & options)346 SkCodec::Result SkHeifCodec::onStartScanlineDecode(
347 const SkImageInfo& dstInfo, const Options& options) {
348 // Check if we can decode to the requested destination and set the output color space
349 if (!this->setOutputColorFormat(dstInfo)) {
350 return kInvalidConversion;
351 }
352
353 // TODO: For now, just decode the whole thing even when there is a subset.
354 // If the heif image has tiles, we could potentially do this much faster,
355 // but the tile configuration needs to be retrieved from the metadata.
356 if (!fHeifDecoder->decode(&fFrameInfo)) {
357 return kInvalidInput;
358 }
359
360 if (options.fSubset) {
361 this->initializeSwizzler(dstInfo, options);
362 } else {
363 fSwizzler.reset(nullptr);
364 }
365
366 this->allocateStorage(dstInfo);
367
368 return kSuccess;
369 }
370
onGetScanlines(void * dst,int count,size_t dstRowBytes)371 int SkHeifCodec::onGetScanlines(void* dst, int count, size_t dstRowBytes) {
372 return this->readRows(this->dstInfo(), dst, dstRowBytes, count, this->options());
373 }
374
onSkipScanlines(int count)375 bool SkHeifCodec::onSkipScanlines(int count) {
376 return count == (int) fHeifDecoder->skipScanlines(count);
377 }
378
379 #endif // SK_HAS_HEIF_LIBRARY
380