blob: 33ea1cad72e841884d6cb4ec85f6d7d47f0bbb5b [file] [log] [blame]
Chong Zhangea280cb2017-08-02 11:10:10 -07001/*
2 * Copyright (C) 2017 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17//#define LOG_NDEBUG 0
18#define LOG_TAG "HeifDecoderImpl"
19
20#include "HeifDecoderImpl.h"
21
22#include <stdio.h>
23
24#include <binder/IMemory.h>
Dongwon Kang49ce6712018-01-24 10:16:25 -080025#include <binder/MemoryDealer.h>
Chong Zhangea280cb2017-08-02 11:10:10 -070026#include <drm/drm_framework_common.h>
27#include <media/IDataSource.h>
28#include <media/mediametadataretriever.h>
Dongwon Kangd91dc5a2017-10-10 00:07:09 -070029#include <media/MediaSource.h>
Chong Zhangd3e0d862017-10-03 13:17:13 -070030#include <media/stagefright/foundation/ADebug.h>
Chong Zhangea280cb2017-08-02 11:10:10 -070031#include <private/media/VideoFrame.h>
32#include <utils/Log.h>
33#include <utils/RefBase.h>
Chong Zhang8541d302019-07-12 11:19:47 -070034#include <vector>
Chong Zhangea280cb2017-08-02 11:10:10 -070035
36HeifDecoder* createHeifDecoder() {
37 return new android::HeifDecoderImpl();
38}
39
40namespace android {
41
Chong Zhang8541d302019-07-12 11:19:47 -070042void initFrameInfo(HeifFrameInfo *info, const VideoFrame *videoFrame) {
43 info->mWidth = videoFrame->mWidth;
44 info->mHeight = videoFrame->mHeight;
45 info->mRotationAngle = videoFrame->mRotationAngle;
46 info->mBytesPerPixel = videoFrame->mBytesPerPixel;
Chong Zhang0af4db62019-08-23 15:34:58 -070047 info->mDurationUs = videoFrame->mDurationUs;
Chong Zhang8541d302019-07-12 11:19:47 -070048 if (videoFrame->mIccSize > 0) {
49 info->mIccData.assign(
50 videoFrame->getFlattenedIccData(),
51 videoFrame->getFlattenedIccData() + videoFrame->mIccSize);
52 } else {
53 // clear old Icc data if there is no Icc data.
54 info->mIccData.clear();
55 }
56}
57
Chong Zhangea280cb2017-08-02 11:10:10 -070058/*
59 * HeifDataSource
60 *
61 * Proxies data requests over IDataSource interface from MediaMetadataRetriever
62 * to the HeifStream interface we received from the heif decoder client.
63 */
64class HeifDataSource : public BnDataSource {
65public:
66 /*
67 * Constructs HeifDataSource; will take ownership of |stream|.
68 */
69 HeifDataSource(HeifStream* stream)
Chong Zhang3f3ffab2017-08-23 13:51:59 -070070 : mStream(stream), mEOS(false),
71 mCachedOffset(0), mCachedSize(0), mCacheBufferSize(0) {}
Chong Zhangea280cb2017-08-02 11:10:10 -070072
73 ~HeifDataSource() override {}
74
75 /*
76 * Initializes internal resources.
77 */
78 bool init();
79
80 sp<IMemory> getIMemory() override { return mMemory; }
81 ssize_t readAt(off64_t offset, size_t size) override;
82 status_t getSize(off64_t* size) override ;
83 void close() {}
84 uint32_t getFlags() override { return 0; }
85 String8 toString() override { return String8("HeifDataSource"); }
86 sp<DecryptHandle> DrmInitialization(const char*) override {
87 return nullptr;
88 }
89
90private:
Chong Zhangea280cb2017-08-02 11:10:10 -070091 enum {
Chong Zhang3f3ffab2017-08-23 13:51:59 -070092 /*
93 * Buffer size for passing the read data to mediaserver. Set to 64K
94 * (which is what MediaDataSource Java API's jni implementation uses).
95 */
Chong Zhangea280cb2017-08-02 11:10:10 -070096 kBufferSize = 64 * 1024,
Chong Zhang3f3ffab2017-08-23 13:51:59 -070097 /*
98 * Initial and max cache buffer size.
99 */
100 kInitialCacheBufferSize = 4 * 1024 * 1024,
101 kMaxCacheBufferSize = 64 * 1024 * 1024,
Chong Zhangea280cb2017-08-02 11:10:10 -0700102 };
103 sp<IMemory> mMemory;
104 std::unique_ptr<HeifStream> mStream;
Chong Zhangea280cb2017-08-02 11:10:10 -0700105 bool mEOS;
Chong Zhangcd031922018-08-24 13:03:19 -0700106 std::unique_ptr<uint8_t[]> mCache;
Chong Zhang3f3ffab2017-08-23 13:51:59 -0700107 off64_t mCachedOffset;
108 size_t mCachedSize;
109 size_t mCacheBufferSize;
Chong Zhangea280cb2017-08-02 11:10:10 -0700110};
111
112bool HeifDataSource::init() {
113 sp<MemoryDealer> memoryDealer =
114 new MemoryDealer(kBufferSize, "HeifDataSource");
115 mMemory = memoryDealer->allocate(kBufferSize);
116 if (mMemory == nullptr) {
117 ALOGE("Failed to allocate shared memory!");
118 return false;
119 }
Chong Zhang3f3ffab2017-08-23 13:51:59 -0700120 mCache.reset(new uint8_t[kInitialCacheBufferSize]);
121 if (mCache.get() == nullptr) {
122 ALOGE("mFailed to allocate cache!");
123 return false;
124 }
125 mCacheBufferSize = kInitialCacheBufferSize;
Chong Zhangea280cb2017-08-02 11:10:10 -0700126 return true;
127}
128
129ssize_t HeifDataSource::readAt(off64_t offset, size_t size) {
130 ALOGV("readAt: offset=%lld, size=%zu", (long long)offset, size);
131
Chong Zhang3f3ffab2017-08-23 13:51:59 -0700132 if (offset < mCachedOffset) {
Chong Zhangea280cb2017-08-02 11:10:10 -0700133 // try seek, then rewind/skip, fail if none worked
134 if (mStream->seek(offset)) {
135 ALOGV("readAt: seek to offset=%lld", (long long)offset);
Chong Zhang3f3ffab2017-08-23 13:51:59 -0700136 mCachedOffset = offset;
137 mCachedSize = 0;
Chong Zhangea280cb2017-08-02 11:10:10 -0700138 mEOS = false;
139 } else if (mStream->rewind()) {
140 ALOGV("readAt: rewind to offset=0");
Chong Zhang3f3ffab2017-08-23 13:51:59 -0700141 mCachedOffset = 0;
142 mCachedSize = 0;
Chong Zhangea280cb2017-08-02 11:10:10 -0700143 mEOS = false;
144 } else {
145 ALOGE("readAt: couldn't seek or rewind!");
146 mEOS = true;
147 }
148 }
149
Chong Zhang3f3ffab2017-08-23 13:51:59 -0700150 if (mEOS && (offset < mCachedOffset ||
151 offset >= (off64_t)(mCachedOffset + mCachedSize))) {
Chong Zhangea280cb2017-08-02 11:10:10 -0700152 ALOGV("readAt: EOS");
153 return ERROR_END_OF_STREAM;
154 }
155
Chong Zhang3f3ffab2017-08-23 13:51:59 -0700156 // at this point, offset must be >= mCachedOffset, other cases should
157 // have been caught above.
158 CHECK(offset >= mCachedOffset);
159
Sungtak Lee237f9032018-03-05 15:21:33 -0800160 off64_t resultOffset;
161 if (__builtin_add_overflow(offset, size, &resultOffset)) {
162 return ERROR_IO;
163 }
164
Chong Zhang3f3ffab2017-08-23 13:51:59 -0700165 if (size == 0) {
166 return 0;
Chong Zhangea280cb2017-08-02 11:10:10 -0700167 }
168
Chong Zhang3f3ffab2017-08-23 13:51:59 -0700169 // Can only read max of kBufferSize
Chong Zhangea280cb2017-08-02 11:10:10 -0700170 if (size > kBufferSize) {
171 size = kBufferSize;
172 }
Chong Zhang3f3ffab2017-08-23 13:51:59 -0700173
174 // copy from cache if the request falls entirely in cache
175 if (offset + size <= mCachedOffset + mCachedSize) {
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -0700176 memcpy(mMemory->unsecurePointer(), mCache.get() + offset - mCachedOffset, size);
Chong Zhang3f3ffab2017-08-23 13:51:59 -0700177 return size;
178 }
179
180 // need to fetch more, check if we need to expand the cache buffer.
181 if ((off64_t)(offset + size) > mCachedOffset + kMaxCacheBufferSize) {
182 // it's reaching max cache buffer size, need to roll window, and possibly
183 // expand the cache buffer.
184 size_t newCacheBufferSize = mCacheBufferSize;
Chong Zhangcd031922018-08-24 13:03:19 -0700185 std::unique_ptr<uint8_t[]> newCache;
Chong Zhang3f3ffab2017-08-23 13:51:59 -0700186 uint8_t* dst = mCache.get();
187 if (newCacheBufferSize < kMaxCacheBufferSize) {
188 newCacheBufferSize = kMaxCacheBufferSize;
189 newCache.reset(new uint8_t[newCacheBufferSize]);
190 dst = newCache.get();
191 }
192
193 // when rolling the cache window, try to keep about half the old bytes
194 // in case that the client goes back.
195 off64_t newCachedOffset = offset - (off64_t)(newCacheBufferSize / 2);
196 if (newCachedOffset < mCachedOffset) {
197 newCachedOffset = mCachedOffset;
198 }
199
200 int64_t newCachedSize = (int64_t)(mCachedOffset + mCachedSize) - newCachedOffset;
201 if (newCachedSize > 0) {
202 // in this case, the new cache region partially overlop the old cache,
203 // move the portion of the cache we want to save to the beginning of
204 // the cache buffer.
205 memcpy(dst, mCache.get() + newCachedOffset - mCachedOffset, newCachedSize);
206 } else if (newCachedSize < 0){
207 // in this case, the new cache region is entirely out of the old cache,
208 // in order to guarantee sequential read, we need to skip a number of
209 // bytes before reading.
210 size_t bytesToSkip = -newCachedSize;
211 size_t bytesSkipped = mStream->read(nullptr, bytesToSkip);
212 if (bytesSkipped != bytesToSkip) {
213 // bytesSkipped is invalid, there is not enough bytes to reach
214 // the requested offset.
215 ALOGE("readAt: skip failed, EOS");
216
217 mEOS = true;
218 mCachedOffset = newCachedOffset;
219 mCachedSize = 0;
220 return ERROR_END_OF_STREAM;
221 }
222 // set cache size to 0, since we're not keeping any old cache
223 newCachedSize = 0;
224 }
225
226 if (newCache.get() != nullptr) {
227 mCache.reset(newCache.release());
228 mCacheBufferSize = newCacheBufferSize;
229 }
230 mCachedOffset = newCachedOffset;
231 mCachedSize = newCachedSize;
232
233 ALOGV("readAt: rolling cache window to (%lld, %zu), cache buffer size %zu",
234 (long long)mCachedOffset, mCachedSize, mCacheBufferSize);
235 } else {
236 // expand cache buffer, but no need to roll the window
237 size_t newCacheBufferSize = mCacheBufferSize;
238 while (offset + size > mCachedOffset + newCacheBufferSize) {
239 newCacheBufferSize *= 2;
240 }
241 CHECK(newCacheBufferSize <= kMaxCacheBufferSize);
242 if (mCacheBufferSize < newCacheBufferSize) {
243 uint8_t* newCache = new uint8_t[newCacheBufferSize];
244 memcpy(newCache, mCache.get(), mCachedSize);
245 mCache.reset(newCache);
246 mCacheBufferSize = newCacheBufferSize;
247
248 ALOGV("readAt: current cache window (%lld, %zu), new cache buffer size %zu",
249 (long long) mCachedOffset, mCachedSize, mCacheBufferSize);
250 }
251 }
252 size_t bytesToRead = offset + size - mCachedOffset - mCachedSize;
253 size_t bytesRead = mStream->read(mCache.get() + mCachedSize, bytesToRead);
254 if (bytesRead > bytesToRead || bytesRead == 0) {
Chong Zhangea280cb2017-08-02 11:10:10 -0700255 // bytesRead is invalid
256 mEOS = true;
Chong Zhang3f3ffab2017-08-23 13:51:59 -0700257 bytesRead = 0;
258 } else if (bytesRead < bytesToRead) {
259 // read some bytes but not all, set EOS
Chong Zhangea280cb2017-08-02 11:10:10 -0700260 mEOS = true;
261 }
Chong Zhang3f3ffab2017-08-23 13:51:59 -0700262 mCachedSize += bytesRead;
263 ALOGV("readAt: current cache window (%lld, %zu)",
264 (long long) mCachedOffset, mCachedSize);
265
266 // here bytesAvailable could be negative if offset jumped past EOS.
267 int64_t bytesAvailable = mCachedOffset + mCachedSize - offset;
268 if (bytesAvailable <= 0) {
269 return ERROR_END_OF_STREAM;
270 }
271 if (bytesAvailable < (int64_t)size) {
272 size = bytesAvailable;
273 }
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -0700274 memcpy(mMemory->unsecurePointer(), mCache.get() + offset - mCachedOffset, size);
Chong Zhang3f3ffab2017-08-23 13:51:59 -0700275 return size;
Chong Zhangea280cb2017-08-02 11:10:10 -0700276}
277
278status_t HeifDataSource::getSize(off64_t* size) {
279 if (!mStream->hasLength()) {
280 *size = -1;
281 ALOGE("getSize: not supported!");
282 return ERROR_UNSUPPORTED;
283 }
284 *size = mStream->getLength();
285 ALOGV("getSize: size=%lld", (long long)*size);
286 return OK;
287}
288
289/////////////////////////////////////////////////////////////////////////
290
Chong Zhang0c1407f2018-05-02 17:09:05 -0700291struct HeifDecoderImpl::DecodeThread : public Thread {
292 explicit DecodeThread(HeifDecoderImpl *decoder) : mDecoder(decoder) {}
293
294private:
295 HeifDecoderImpl* mDecoder;
296
297 bool threadLoop();
298
299 DISALLOW_EVIL_CONSTRUCTORS(DecodeThread);
300};
301
302bool HeifDecoderImpl::DecodeThread::threadLoop() {
303 return mDecoder->decodeAsync();
304}
305
306/////////////////////////////////////////////////////////////////////////
307
Chong Zhangea280cb2017-08-02 11:10:10 -0700308HeifDecoderImpl::HeifDecoderImpl() :
309 // output color format should always be set via setOutputColor(), in case
310 // it's not, default to HAL_PIXEL_FORMAT_RGB_565.
311 mOutputColor(HAL_PIXEL_FORMAT_RGB_565),
Chong Zhang3f3ffab2017-08-23 13:51:59 -0700312 mCurScanline(0),
Chong Zhang8541d302019-07-12 11:19:47 -0700313 mTotalScanline(0),
Chong Zhangd3e0d862017-10-03 13:17:13 -0700314 mFrameDecoded(false),
315 mHasImage(false),
Chong Zhang0c1407f2018-05-02 17:09:05 -0700316 mHasVideo(false),
Chong Zhang8541d302019-07-12 11:19:47 -0700317 mSequenceLength(0),
Chong Zhang0c1407f2018-05-02 17:09:05 -0700318 mAvailableLines(0),
319 mNumSlices(1),
320 mSliceHeight(0),
321 mAsyncDecodeDone(false) {
Chong Zhangea280cb2017-08-02 11:10:10 -0700322}
323
324HeifDecoderImpl::~HeifDecoderImpl() {
Chong Zhang0c1407f2018-05-02 17:09:05 -0700325 if (mThread != nullptr) {
326 mThread->join();
327 }
Chong Zhangea280cb2017-08-02 11:10:10 -0700328}
329
330bool HeifDecoderImpl::init(HeifStream* stream, HeifFrameInfo* frameInfo) {
Chong Zhang3f3ffab2017-08-23 13:51:59 -0700331 mFrameDecoded = false;
Chong Zhangd3e0d862017-10-03 13:17:13 -0700332 mFrameMemory.clear();
333
Chong Zhangea280cb2017-08-02 11:10:10 -0700334 sp<HeifDataSource> dataSource = new HeifDataSource(stream);
335 if (!dataSource->init()) {
336 return false;
337 }
338 mDataSource = dataSource;
339
340 mRetriever = new MediaMetadataRetriever();
Chong Zhangd3e0d862017-10-03 13:17:13 -0700341 status_t err = mRetriever->setDataSource(mDataSource, "image/heif");
Chong Zhangea280cb2017-08-02 11:10:10 -0700342 if (err != OK) {
343 ALOGE("failed to set data source!");
344
345 mRetriever.clear();
346 mDataSource.clear();
347 return false;
348 }
349 ALOGV("successfully set data source.");
350
Chong Zhangd3e0d862017-10-03 13:17:13 -0700351 const char* hasImage = mRetriever->extractMetadata(METADATA_KEY_HAS_IMAGE);
Chong Zhangea280cb2017-08-02 11:10:10 -0700352 const char* hasVideo = mRetriever->extractMetadata(METADATA_KEY_HAS_VIDEO);
Chong Zhangd3e0d862017-10-03 13:17:13 -0700353
354 mHasImage = hasImage && !strcasecmp(hasImage, "yes");
355 mHasVideo = hasVideo && !strcasecmp(hasVideo, "yes");
Chong Zhang8541d302019-07-12 11:19:47 -0700356
357 HeifFrameInfo* defaultInfo = nullptr;
Chong Zhangd3e0d862017-10-03 13:17:13 -0700358 if (mHasImage) {
359 // image index < 0 to retrieve primary image
Chong Zhang8541d302019-07-12 11:19:47 -0700360 sp<IMemory> sharedMem = mRetriever->getImageAtIndex(
Chong Zhangd3e0d862017-10-03 13:17:13 -0700361 -1, mOutputColor, true /*metaOnly*/);
Chong Zhang8541d302019-07-12 11:19:47 -0700362
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -0700363 if (sharedMem == nullptr || sharedMem->unsecurePointer() == nullptr) {
Chong Zhang8541d302019-07-12 11:19:47 -0700364 ALOGE("init: videoFrame is a nullptr");
365 return false;
366 }
367
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -0700368 // TODO: Using unsecurePointer() has some associated security pitfalls
369 // (see declaration for details).
370 // Either document why it is safe in this case or address the
371 // issue (e.g. by copying).
372 VideoFrame* videoFrame = static_cast<VideoFrame*>(sharedMem->unsecurePointer());
Chong Zhang8541d302019-07-12 11:19:47 -0700373
374 ALOGV("Image dimension %dx%d, display %dx%d, angle %d, iccSize %d",
375 videoFrame->mWidth,
376 videoFrame->mHeight,
377 videoFrame->mDisplayWidth,
378 videoFrame->mDisplayHeight,
379 videoFrame->mRotationAngle,
380 videoFrame->mIccSize);
381
382 initFrameInfo(&mImageInfo, videoFrame);
383
384 if (videoFrame->mTileHeight >= 512) {
385 // Try decoding in slices only if the image has tiles and is big enough.
386 mSliceHeight = videoFrame->mTileHeight;
387 ALOGV("mSliceHeight %u", mSliceHeight);
388 }
389
390 defaultInfo = &mImageInfo;
Chong Zhangea280cb2017-08-02 11:10:10 -0700391 }
392
Chong Zhang8541d302019-07-12 11:19:47 -0700393 if (mHasVideo) {
394 sp<IMemory> sharedMem = mRetriever->getFrameAtTime(0,
395 MediaSource::ReadOptions::SEEK_PREVIOUS_SYNC,
396 mOutputColor, true /*metaOnly*/);
397
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -0700398 if (sharedMem == nullptr || sharedMem->unsecurePointer() == nullptr) {
Chong Zhang8541d302019-07-12 11:19:47 -0700399 ALOGE("init: videoFrame is a nullptr");
400 return false;
401 }
402
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -0700403 // TODO: Using unsecurePointer() has some associated security pitfalls
404 // (see declaration for details).
405 // Either document why it is safe in this case or address the
406 // issue (e.g. by copying).
407 VideoFrame* videoFrame = static_cast<VideoFrame*>(
408 sharedMem->unsecurePointer());
Chong Zhang8541d302019-07-12 11:19:47 -0700409
410 ALOGV("Sequence dimension %dx%d, display %dx%d, angle %d, iccSize %d",
411 videoFrame->mWidth,
412 videoFrame->mHeight,
413 videoFrame->mDisplayWidth,
414 videoFrame->mDisplayHeight,
415 videoFrame->mRotationAngle,
416 videoFrame->mIccSize);
417
418 initFrameInfo(&mSequenceInfo, videoFrame);
419
420 mSequenceLength = atoi(mRetriever->extractMetadata(METADATA_KEY_VIDEO_FRAME_COUNT));
421
422 if (defaultInfo == nullptr) {
423 defaultInfo = &mSequenceInfo;
424 }
425 }
426
427 if (defaultInfo == nullptr) {
428 ALOGD("No valid image or sequence available");
Chong Zhangea280cb2017-08-02 11:10:10 -0700429 return false;
430 }
431
Chong Zhangea280cb2017-08-02 11:10:10 -0700432 if (frameInfo != nullptr) {
Chong Zhang8541d302019-07-12 11:19:47 -0700433 *frameInfo = *defaultInfo;
Chong Zhangea280cb2017-08-02 11:10:10 -0700434 }
Chong Zhang8541d302019-07-12 11:19:47 -0700435
436 // default total scanline, this might change if decodeSequence() is used
437 mTotalScanline = defaultInfo->mHeight;
438
439 return true;
440}
441
442bool HeifDecoderImpl::getSequenceInfo(
443 HeifFrameInfo* frameInfo, size_t *frameCount) {
444 ALOGV("%s", __FUNCTION__);
445 if (!mHasVideo) {
446 return false;
447 }
448 if (frameInfo != nullptr) {
449 *frameInfo = mSequenceInfo;
450 }
451 if (frameCount != nullptr) {
452 *frameCount = mSequenceLength;
Chong Zhang0c1407f2018-05-02 17:09:05 -0700453 }
Chong Zhangea280cb2017-08-02 11:10:10 -0700454 return true;
455}
456
457bool HeifDecoderImpl::getEncodedColor(HeifEncodedColor* /*outColor*/) const {
458 ALOGW("getEncodedColor: not implemented!");
459 return false;
460}
461
462bool HeifDecoderImpl::setOutputColor(HeifColorFormat heifColor) {
463 switch(heifColor) {
464 case kHeifColorFormat_RGB565:
465 {
466 mOutputColor = HAL_PIXEL_FORMAT_RGB_565;
467 return true;
468 }
469 case kHeifColorFormat_RGBA_8888:
470 {
471 mOutputColor = HAL_PIXEL_FORMAT_RGBA_8888;
472 return true;
473 }
474 case kHeifColorFormat_BGRA_8888:
475 {
476 mOutputColor = HAL_PIXEL_FORMAT_BGRA_8888;
477 return true;
478 }
479 default:
480 break;
481 }
482 ALOGE("Unsupported output color format %d", heifColor);
483 return false;
484}
485
Chong Zhang0c1407f2018-05-02 17:09:05 -0700486bool HeifDecoderImpl::decodeAsync() {
487 for (size_t i = 1; i < mNumSlices; i++) {
488 ALOGV("decodeAsync(): decoding slice %zu", i);
489 size_t top = i * mSliceHeight;
490 size_t bottom = (i + 1) * mSliceHeight;
Chong Zhang8541d302019-07-12 11:19:47 -0700491 if (bottom > mImageInfo.mHeight) {
492 bottom = mImageInfo.mHeight;
Chong Zhang0c1407f2018-05-02 17:09:05 -0700493 }
494 sp<IMemory> frameMemory = mRetriever->getImageRectAtIndex(
Chong Zhang8541d302019-07-12 11:19:47 -0700495 -1, mOutputColor, 0, top, mImageInfo.mWidth, bottom);
Chong Zhang0c1407f2018-05-02 17:09:05 -0700496 {
497 Mutex::Autolock autolock(mLock);
498
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -0700499 if (frameMemory == nullptr || frameMemory->unsecurePointer() == nullptr) {
Chong Zhang0c1407f2018-05-02 17:09:05 -0700500 mAsyncDecodeDone = true;
501 mScanlineReady.signal();
502 break;
503 }
504 mFrameMemory = frameMemory;
505 mAvailableLines = bottom;
506 ALOGV("decodeAsync(): available lines %zu", mAvailableLines);
507 mScanlineReady.signal();
508 }
509 }
510 // Aggressive clear to avoid holding on to resources
511 mRetriever.clear();
512 mDataSource.clear();
513 return false;
514}
515
Chong Zhangea280cb2017-08-02 11:10:10 -0700516bool HeifDecoderImpl::decode(HeifFrameInfo* frameInfo) {
Chong Zhang3f3ffab2017-08-23 13:51:59 -0700517 // reset scanline pointer
518 mCurScanline = 0;
519
520 if (mFrameDecoded) {
521 return true;
522 }
523
Chong Zhang0c1407f2018-05-02 17:09:05 -0700524 // See if we want to decode in slices to allow client to start
525 // scanline processing in parallel with decode. If this fails
526 // we fallback to decoding the full frame.
Chong Zhang8541d302019-07-12 11:19:47 -0700527 if (mHasImage) {
528 if (mSliceHeight >= 512 &&
529 mImageInfo.mWidth >= 3000 &&
530 mImageInfo.mHeight >= 2000 ) {
531 // Try decoding in slices only if the image has tiles and is big enough.
532 mNumSlices = (mImageInfo.mHeight + mSliceHeight - 1) / mSliceHeight;
533 ALOGV("mSliceHeight %u, mNumSlices %zu", mSliceHeight, mNumSlices);
Chong Zhang0c1407f2018-05-02 17:09:05 -0700534 }
535
Chong Zhang8541d302019-07-12 11:19:47 -0700536 if (mNumSlices > 1) {
537 // get first slice and metadata
538 sp<IMemory> frameMemory = mRetriever->getImageRectAtIndex(
539 -1, mOutputColor, 0, 0, mImageInfo.mWidth, mSliceHeight);
Chong Zhang0c1407f2018-05-02 17:09:05 -0700540
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -0700541 if (frameMemory == nullptr || frameMemory->unsecurePointer() == nullptr) {
Chong Zhang8541d302019-07-12 11:19:47 -0700542 ALOGE("decode: metadata is a nullptr");
543 return false;
544 }
545
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -0700546 // TODO: Using unsecurePointer() has some associated security pitfalls
547 // (see declaration for details).
548 // Either document why it is safe in this case or address the
549 // issue (e.g. by copying).
550 VideoFrame* videoFrame = static_cast<VideoFrame*>(frameMemory->unsecurePointer());
Chong Zhang8541d302019-07-12 11:19:47 -0700551
552 if (frameInfo != nullptr) {
553 initFrameInfo(frameInfo, videoFrame);
554 }
555 mFrameMemory = frameMemory;
556 mAvailableLines = mSliceHeight;
557 mThread = new DecodeThread(this);
558 if (mThread->run("HeifDecode", ANDROID_PRIORITY_FOREGROUND) == OK) {
559 mFrameDecoded = true;
560 return true;
561 }
562 // Fallback to decode without slicing
563 mThread.clear();
564 mNumSlices = 1;
565 mSliceHeight = 0;
566 mAvailableLines = 0;
567 mFrameMemory.clear();
Chong Zhang0c1407f2018-05-02 17:09:05 -0700568 }
Chong Zhang0c1407f2018-05-02 17:09:05 -0700569 }
570
Chong Zhangd3e0d862017-10-03 13:17:13 -0700571 if (mHasImage) {
572 // image index < 0 to retrieve primary image
573 mFrameMemory = mRetriever->getImageAtIndex(-1, mOutputColor);
574 } else if (mHasVideo) {
575 mFrameMemory = mRetriever->getFrameAtTime(0,
576 MediaSource::ReadOptions::SEEK_PREVIOUS_SYNC, mOutputColor);
577 }
578
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -0700579 if (mFrameMemory == nullptr || mFrameMemory->unsecurePointer() == nullptr) {
Chong Zhang0c1407f2018-05-02 17:09:05 -0700580 ALOGE("decode: videoFrame is a nullptr");
Chong Zhangea280cb2017-08-02 11:10:10 -0700581 return false;
582 }
583
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -0700584 // TODO: Using unsecurePointer() has some associated security pitfalls
585 // (see declaration for details).
586 // Either document why it is safe in this case or address the
587 // issue (e.g. by copying).
588 VideoFrame* videoFrame = static_cast<VideoFrame*>(mFrameMemory->unsecurePointer());
Chong Zhang3f3ffab2017-08-23 13:51:59 -0700589 if (videoFrame->mSize == 0 ||
590 mFrameMemory->size() < videoFrame->getFlattenedSize()) {
Chong Zhang0c1407f2018-05-02 17:09:05 -0700591 ALOGE("decode: videoFrame size is invalid");
Chong Zhang3f3ffab2017-08-23 13:51:59 -0700592 return false;
593 }
594
Chong Zhangea280cb2017-08-02 11:10:10 -0700595 ALOGV("Decoded dimension %dx%d, display %dx%d, angle %d, rowbytes %d, size %d",
596 videoFrame->mWidth,
597 videoFrame->mHeight,
598 videoFrame->mDisplayWidth,
599 videoFrame->mDisplayHeight,
600 videoFrame->mRotationAngle,
601 videoFrame->mRowBytes,
602 videoFrame->mSize);
603
604 if (frameInfo != nullptr) {
Chong Zhang8541d302019-07-12 11:19:47 -0700605 initFrameInfo(frameInfo, videoFrame);
606
Chong Zhangea280cb2017-08-02 11:10:10 -0700607 }
Chong Zhang3f3ffab2017-08-23 13:51:59 -0700608 mFrameDecoded = true;
Chong Zhang4c6398b2017-09-07 17:43:19 -0700609
Chong Zhang0c1407f2018-05-02 17:09:05 -0700610 // Aggressively clear to avoid holding on to resources
Chong Zhang4c6398b2017-09-07 17:43:19 -0700611 mRetriever.clear();
612 mDataSource.clear();
Chong Zhangea280cb2017-08-02 11:10:10 -0700613 return true;
614}
615
Chong Zhang8541d302019-07-12 11:19:47 -0700616bool HeifDecoderImpl::decodeSequence(int frameIndex, HeifFrameInfo* frameInfo) {
617 ALOGV("%s: frame index %d", __FUNCTION__, frameIndex);
618 if (!mHasVideo) {
619 return false;
620 }
621
622 if (frameIndex < 0 || frameIndex >= mSequenceLength) {
623 ALOGE("invalid frame index: %d, total frames %zu", frameIndex, mSequenceLength);
624 return false;
625 }
626
627 mCurScanline = 0;
628
629 // set total scanline to sequence height now
630 mTotalScanline = mSequenceInfo.mHeight;
631
632 mFrameMemory = mRetriever->getFrameAtIndex(frameIndex, mOutputColor);
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -0700633 if (mFrameMemory == nullptr || mFrameMemory->unsecurePointer() == nullptr) {
Chong Zhang8541d302019-07-12 11:19:47 -0700634 ALOGE("decode: videoFrame is a nullptr");
635 return false;
636 }
637
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -0700638 // TODO: Using unsecurePointer() has some associated security pitfalls
639 // (see declaration for details).
640 // Either document why it is safe in this case or address the
641 // issue (e.g. by copying).
642 VideoFrame* videoFrame = static_cast<VideoFrame*>(mFrameMemory->unsecurePointer());
Chong Zhang8541d302019-07-12 11:19:47 -0700643 if (videoFrame->mSize == 0 ||
644 mFrameMemory->size() < videoFrame->getFlattenedSize()) {
645 ALOGE("decode: videoFrame size is invalid");
646 return false;
647 }
648
649 ALOGV("Decoded dimension %dx%d, display %dx%d, angle %d, rowbytes %d, size %d",
650 videoFrame->mWidth,
651 videoFrame->mHeight,
652 videoFrame->mDisplayWidth,
653 videoFrame->mDisplayHeight,
654 videoFrame->mRotationAngle,
655 videoFrame->mRowBytes,
656 videoFrame->mSize);
657
658 if (frameInfo != nullptr) {
659 initFrameInfo(frameInfo, videoFrame);
660 }
661 return true;
662}
663
Chong Zhang0c1407f2018-05-02 17:09:05 -0700664bool HeifDecoderImpl::getScanlineInner(uint8_t* dst) {
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -0700665 if (mFrameMemory == nullptr || mFrameMemory->unsecurePointer() == nullptr) {
Chong Zhangea280cb2017-08-02 11:10:10 -0700666 return false;
667 }
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -0700668 // TODO: Using unsecurePointer() has some associated security pitfalls
669 // (see declaration for details).
670 // Either document why it is safe in this case or address the
671 // issue (e.g. by copying).
672 VideoFrame* videoFrame = static_cast<VideoFrame*>(mFrameMemory->unsecurePointer());
Chong Zhangea280cb2017-08-02 11:10:10 -0700673 uint8_t* src = videoFrame->getFlattenedData() + videoFrame->mRowBytes * mCurScanline++;
Chong Zhang70b0afd2018-02-27 12:43:06 -0800674 memcpy(dst, src, videoFrame->mBytesPerPixel * videoFrame->mWidth);
Chong Zhangea280cb2017-08-02 11:10:10 -0700675 return true;
676}
677
Chong Zhang0c1407f2018-05-02 17:09:05 -0700678bool HeifDecoderImpl::getScanline(uint8_t* dst) {
Chong Zhang8541d302019-07-12 11:19:47 -0700679 if (mCurScanline >= mTotalScanline) {
Chong Zhang0c1407f2018-05-02 17:09:05 -0700680 ALOGE("no more scanline available");
681 return false;
Chong Zhangea280cb2017-08-02 11:10:10 -0700682 }
Chong Zhangea280cb2017-08-02 11:10:10 -0700683
Chong Zhang0c1407f2018-05-02 17:09:05 -0700684 if (mNumSlices > 1) {
685 Mutex::Autolock autolock(mLock);
686
687 while (!mAsyncDecodeDone && mCurScanline >= mAvailableLines) {
688 mScanlineReady.wait(mLock);
689 }
690 return (mCurScanline < mAvailableLines) ? getScanlineInner(dst) : false;
691 }
692
693 return getScanlineInner(dst);
694}
695
696size_t HeifDecoderImpl::skipScanlines(size_t count) {
Chong Zhangea280cb2017-08-02 11:10:10 -0700697 uint32_t oldScanline = mCurScanline;
698 mCurScanline += count;
Chong Zhang8541d302019-07-12 11:19:47 -0700699 if (mCurScanline > mTotalScanline) {
700 mCurScanline = mTotalScanline;
Chong Zhangea280cb2017-08-02 11:10:10 -0700701 }
702 return (mCurScanline > oldScanline) ? (mCurScanline - oldScanline) : 0;
703}
704
705} // namespace android