blob: 8dae251fa6cc9869bf010dd64680fe70e0fef5a9 [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>
34
35HeifDecoder* createHeifDecoder() {
36 return new android::HeifDecoderImpl();
37}
38
39namespace android {
40
41/*
42 * HeifDataSource
43 *
44 * Proxies data requests over IDataSource interface from MediaMetadataRetriever
45 * to the HeifStream interface we received from the heif decoder client.
46 */
47class HeifDataSource : public BnDataSource {
48public:
49 /*
50 * Constructs HeifDataSource; will take ownership of |stream|.
51 */
52 HeifDataSource(HeifStream* stream)
Chong Zhang3f3ffab2017-08-23 13:51:59 -070053 : mStream(stream), mEOS(false),
54 mCachedOffset(0), mCachedSize(0), mCacheBufferSize(0) {}
Chong Zhangea280cb2017-08-02 11:10:10 -070055
56 ~HeifDataSource() override {}
57
58 /*
59 * Initializes internal resources.
60 */
61 bool init();
62
63 sp<IMemory> getIMemory() override { return mMemory; }
64 ssize_t readAt(off64_t offset, size_t size) override;
65 status_t getSize(off64_t* size) override ;
66 void close() {}
67 uint32_t getFlags() override { return 0; }
68 String8 toString() override { return String8("HeifDataSource"); }
69 sp<DecryptHandle> DrmInitialization(const char*) override {
70 return nullptr;
71 }
72
73private:
Chong Zhangea280cb2017-08-02 11:10:10 -070074 enum {
Chong Zhang3f3ffab2017-08-23 13:51:59 -070075 /*
76 * Buffer size for passing the read data to mediaserver. Set to 64K
77 * (which is what MediaDataSource Java API's jni implementation uses).
78 */
Chong Zhangea280cb2017-08-02 11:10:10 -070079 kBufferSize = 64 * 1024,
Chong Zhang3f3ffab2017-08-23 13:51:59 -070080 /*
81 * Initial and max cache buffer size.
82 */
83 kInitialCacheBufferSize = 4 * 1024 * 1024,
84 kMaxCacheBufferSize = 64 * 1024 * 1024,
Chong Zhangea280cb2017-08-02 11:10:10 -070085 };
86 sp<IMemory> mMemory;
87 std::unique_ptr<HeifStream> mStream;
Chong Zhangea280cb2017-08-02 11:10:10 -070088 bool mEOS;
Chong Zhang3f3ffab2017-08-23 13:51:59 -070089 std::unique_ptr<uint8_t> mCache;
90 off64_t mCachedOffset;
91 size_t mCachedSize;
92 size_t mCacheBufferSize;
Chong Zhangea280cb2017-08-02 11:10:10 -070093};
94
95bool HeifDataSource::init() {
96 sp<MemoryDealer> memoryDealer =
97 new MemoryDealer(kBufferSize, "HeifDataSource");
98 mMemory = memoryDealer->allocate(kBufferSize);
99 if (mMemory == nullptr) {
100 ALOGE("Failed to allocate shared memory!");
101 return false;
102 }
Chong Zhang3f3ffab2017-08-23 13:51:59 -0700103 mCache.reset(new uint8_t[kInitialCacheBufferSize]);
104 if (mCache.get() == nullptr) {
105 ALOGE("mFailed to allocate cache!");
106 return false;
107 }
108 mCacheBufferSize = kInitialCacheBufferSize;
Chong Zhangea280cb2017-08-02 11:10:10 -0700109 return true;
110}
111
112ssize_t HeifDataSource::readAt(off64_t offset, size_t size) {
113 ALOGV("readAt: offset=%lld, size=%zu", (long long)offset, size);
114
Chong Zhang3f3ffab2017-08-23 13:51:59 -0700115 if (offset < mCachedOffset) {
Chong Zhangea280cb2017-08-02 11:10:10 -0700116 // try seek, then rewind/skip, fail if none worked
117 if (mStream->seek(offset)) {
118 ALOGV("readAt: seek to offset=%lld", (long long)offset);
Chong Zhang3f3ffab2017-08-23 13:51:59 -0700119 mCachedOffset = offset;
120 mCachedSize = 0;
Chong Zhangea280cb2017-08-02 11:10:10 -0700121 mEOS = false;
122 } else if (mStream->rewind()) {
123 ALOGV("readAt: rewind to offset=0");
Chong Zhang3f3ffab2017-08-23 13:51:59 -0700124 mCachedOffset = 0;
125 mCachedSize = 0;
Chong Zhangea280cb2017-08-02 11:10:10 -0700126 mEOS = false;
127 } else {
128 ALOGE("readAt: couldn't seek or rewind!");
129 mEOS = true;
130 }
131 }
132
Chong Zhang3f3ffab2017-08-23 13:51:59 -0700133 if (mEOS && (offset < mCachedOffset ||
134 offset >= (off64_t)(mCachedOffset + mCachedSize))) {
Chong Zhangea280cb2017-08-02 11:10:10 -0700135 ALOGV("readAt: EOS");
136 return ERROR_END_OF_STREAM;
137 }
138
Chong Zhang3f3ffab2017-08-23 13:51:59 -0700139 // at this point, offset must be >= mCachedOffset, other cases should
140 // have been caught above.
141 CHECK(offset >= mCachedOffset);
142
Sungtak Lee237f9032018-03-05 15:21:33 -0800143 off64_t resultOffset;
144 if (__builtin_add_overflow(offset, size, &resultOffset)) {
145 return ERROR_IO;
146 }
147
Chong Zhang3f3ffab2017-08-23 13:51:59 -0700148 if (size == 0) {
149 return 0;
Chong Zhangea280cb2017-08-02 11:10:10 -0700150 }
151
Chong Zhang3f3ffab2017-08-23 13:51:59 -0700152 // Can only read max of kBufferSize
Chong Zhangea280cb2017-08-02 11:10:10 -0700153 if (size > kBufferSize) {
154 size = kBufferSize;
155 }
Chong Zhang3f3ffab2017-08-23 13:51:59 -0700156
157 // copy from cache if the request falls entirely in cache
158 if (offset + size <= mCachedOffset + mCachedSize) {
159 memcpy(mMemory->pointer(), mCache.get() + offset - mCachedOffset, size);
160 return size;
161 }
162
163 // need to fetch more, check if we need to expand the cache buffer.
164 if ((off64_t)(offset + size) > mCachedOffset + kMaxCacheBufferSize) {
165 // it's reaching max cache buffer size, need to roll window, and possibly
166 // expand the cache buffer.
167 size_t newCacheBufferSize = mCacheBufferSize;
168 std::unique_ptr<uint8_t> newCache;
169 uint8_t* dst = mCache.get();
170 if (newCacheBufferSize < kMaxCacheBufferSize) {
171 newCacheBufferSize = kMaxCacheBufferSize;
172 newCache.reset(new uint8_t[newCacheBufferSize]);
173 dst = newCache.get();
174 }
175
176 // when rolling the cache window, try to keep about half the old bytes
177 // in case that the client goes back.
178 off64_t newCachedOffset = offset - (off64_t)(newCacheBufferSize / 2);
179 if (newCachedOffset < mCachedOffset) {
180 newCachedOffset = mCachedOffset;
181 }
182
183 int64_t newCachedSize = (int64_t)(mCachedOffset + mCachedSize) - newCachedOffset;
184 if (newCachedSize > 0) {
185 // in this case, the new cache region partially overlop the old cache,
186 // move the portion of the cache we want to save to the beginning of
187 // the cache buffer.
188 memcpy(dst, mCache.get() + newCachedOffset - mCachedOffset, newCachedSize);
189 } else if (newCachedSize < 0){
190 // in this case, the new cache region is entirely out of the old cache,
191 // in order to guarantee sequential read, we need to skip a number of
192 // bytes before reading.
193 size_t bytesToSkip = -newCachedSize;
194 size_t bytesSkipped = mStream->read(nullptr, bytesToSkip);
195 if (bytesSkipped != bytesToSkip) {
196 // bytesSkipped is invalid, there is not enough bytes to reach
197 // the requested offset.
198 ALOGE("readAt: skip failed, EOS");
199
200 mEOS = true;
201 mCachedOffset = newCachedOffset;
202 mCachedSize = 0;
203 return ERROR_END_OF_STREAM;
204 }
205 // set cache size to 0, since we're not keeping any old cache
206 newCachedSize = 0;
207 }
208
209 if (newCache.get() != nullptr) {
210 mCache.reset(newCache.release());
211 mCacheBufferSize = newCacheBufferSize;
212 }
213 mCachedOffset = newCachedOffset;
214 mCachedSize = newCachedSize;
215
216 ALOGV("readAt: rolling cache window to (%lld, %zu), cache buffer size %zu",
217 (long long)mCachedOffset, mCachedSize, mCacheBufferSize);
218 } else {
219 // expand cache buffer, but no need to roll the window
220 size_t newCacheBufferSize = mCacheBufferSize;
221 while (offset + size > mCachedOffset + newCacheBufferSize) {
222 newCacheBufferSize *= 2;
223 }
224 CHECK(newCacheBufferSize <= kMaxCacheBufferSize);
225 if (mCacheBufferSize < newCacheBufferSize) {
226 uint8_t* newCache = new uint8_t[newCacheBufferSize];
227 memcpy(newCache, mCache.get(), mCachedSize);
228 mCache.reset(newCache);
229 mCacheBufferSize = newCacheBufferSize;
230
231 ALOGV("readAt: current cache window (%lld, %zu), new cache buffer size %zu",
232 (long long) mCachedOffset, mCachedSize, mCacheBufferSize);
233 }
234 }
235 size_t bytesToRead = offset + size - mCachedOffset - mCachedSize;
236 size_t bytesRead = mStream->read(mCache.get() + mCachedSize, bytesToRead);
237 if (bytesRead > bytesToRead || bytesRead == 0) {
Chong Zhangea280cb2017-08-02 11:10:10 -0700238 // bytesRead is invalid
239 mEOS = true;
Chong Zhang3f3ffab2017-08-23 13:51:59 -0700240 bytesRead = 0;
241 } else if (bytesRead < bytesToRead) {
242 // read some bytes but not all, set EOS
Chong Zhangea280cb2017-08-02 11:10:10 -0700243 mEOS = true;
244 }
Chong Zhang3f3ffab2017-08-23 13:51:59 -0700245 mCachedSize += bytesRead;
246 ALOGV("readAt: current cache window (%lld, %zu)",
247 (long long) mCachedOffset, mCachedSize);
248
249 // here bytesAvailable could be negative if offset jumped past EOS.
250 int64_t bytesAvailable = mCachedOffset + mCachedSize - offset;
251 if (bytesAvailable <= 0) {
252 return ERROR_END_OF_STREAM;
253 }
254 if (bytesAvailable < (int64_t)size) {
255 size = bytesAvailable;
256 }
257 memcpy(mMemory->pointer(), mCache.get() + offset - mCachedOffset, size);
258 return size;
Chong Zhangea280cb2017-08-02 11:10:10 -0700259}
260
261status_t HeifDataSource::getSize(off64_t* size) {
262 if (!mStream->hasLength()) {
263 *size = -1;
264 ALOGE("getSize: not supported!");
265 return ERROR_UNSUPPORTED;
266 }
267 *size = mStream->getLength();
268 ALOGV("getSize: size=%lld", (long long)*size);
269 return OK;
270}
271
272/////////////////////////////////////////////////////////////////////////
273
274HeifDecoderImpl::HeifDecoderImpl() :
275 // output color format should always be set via setOutputColor(), in case
276 // it's not, default to HAL_PIXEL_FORMAT_RGB_565.
277 mOutputColor(HAL_PIXEL_FORMAT_RGB_565),
Chong Zhang3f3ffab2017-08-23 13:51:59 -0700278 mCurScanline(0),
Chong Zhangd3e0d862017-10-03 13:17:13 -0700279 mFrameDecoded(false),
280 mHasImage(false),
281 mHasVideo(false) {
Chong Zhangea280cb2017-08-02 11:10:10 -0700282}
283
284HeifDecoderImpl::~HeifDecoderImpl() {
285}
286
287bool HeifDecoderImpl::init(HeifStream* stream, HeifFrameInfo* frameInfo) {
Chong Zhang3f3ffab2017-08-23 13:51:59 -0700288 mFrameDecoded = false;
Chong Zhangd3e0d862017-10-03 13:17:13 -0700289 mFrameMemory.clear();
290
Chong Zhangea280cb2017-08-02 11:10:10 -0700291 sp<HeifDataSource> dataSource = new HeifDataSource(stream);
292 if (!dataSource->init()) {
293 return false;
294 }
295 mDataSource = dataSource;
296
297 mRetriever = new MediaMetadataRetriever();
Chong Zhangd3e0d862017-10-03 13:17:13 -0700298 status_t err = mRetriever->setDataSource(mDataSource, "image/heif");
Chong Zhangea280cb2017-08-02 11:10:10 -0700299 if (err != OK) {
300 ALOGE("failed to set data source!");
301
302 mRetriever.clear();
303 mDataSource.clear();
304 return false;
305 }
306 ALOGV("successfully set data source.");
307
Chong Zhangd3e0d862017-10-03 13:17:13 -0700308 const char* hasImage = mRetriever->extractMetadata(METADATA_KEY_HAS_IMAGE);
Chong Zhangea280cb2017-08-02 11:10:10 -0700309 const char* hasVideo = mRetriever->extractMetadata(METADATA_KEY_HAS_VIDEO);
Chong Zhangd3e0d862017-10-03 13:17:13 -0700310
311 mHasImage = hasImage && !strcasecmp(hasImage, "yes");
312 mHasVideo = hasVideo && !strcasecmp(hasVideo, "yes");
313 if (mHasImage) {
314 // image index < 0 to retrieve primary image
315 mFrameMemory = mRetriever->getImageAtIndex(
316 -1, mOutputColor, true /*metaOnly*/);
317 } else if (mHasVideo) {
318 mFrameMemory = mRetriever->getFrameAtTime(0,
319 MediaSource::ReadOptions::SEEK_PREVIOUS_SYNC,
320 mOutputColor, true /*metaOnly*/);
Chong Zhangea280cb2017-08-02 11:10:10 -0700321 }
322
Chong Zhangea280cb2017-08-02 11:10:10 -0700323 if (mFrameMemory == nullptr || mFrameMemory->pointer() == nullptr) {
324 ALOGE("getFrameAtTime: videoFrame is a nullptr");
325 return false;
326 }
327
328 VideoFrame* videoFrame = static_cast<VideoFrame*>(mFrameMemory->pointer());
329
330 ALOGV("Meta dimension %dx%d, display %dx%d, angle %d, iccSize %d",
331 videoFrame->mWidth,
332 videoFrame->mHeight,
333 videoFrame->mDisplayWidth,
334 videoFrame->mDisplayHeight,
335 videoFrame->mRotationAngle,
336 videoFrame->mIccSize);
337
338 if (frameInfo != nullptr) {
339 frameInfo->set(
Chong Zhang70b0afd2018-02-27 12:43:06 -0800340 videoFrame->mWidth,
341 videoFrame->mHeight,
Chong Zhangea280cb2017-08-02 11:10:10 -0700342 videoFrame->mRotationAngle,
343 videoFrame->mBytesPerPixel,
344 videoFrame->mIccSize,
345 videoFrame->getFlattenedIccData());
346 }
347 return true;
348}
349
350bool HeifDecoderImpl::getEncodedColor(HeifEncodedColor* /*outColor*/) const {
351 ALOGW("getEncodedColor: not implemented!");
352 return false;
353}
354
355bool HeifDecoderImpl::setOutputColor(HeifColorFormat heifColor) {
356 switch(heifColor) {
357 case kHeifColorFormat_RGB565:
358 {
359 mOutputColor = HAL_PIXEL_FORMAT_RGB_565;
360 return true;
361 }
362 case kHeifColorFormat_RGBA_8888:
363 {
364 mOutputColor = HAL_PIXEL_FORMAT_RGBA_8888;
365 return true;
366 }
367 case kHeifColorFormat_BGRA_8888:
368 {
369 mOutputColor = HAL_PIXEL_FORMAT_BGRA_8888;
370 return true;
371 }
372 default:
373 break;
374 }
375 ALOGE("Unsupported output color format %d", heifColor);
376 return false;
377}
378
379bool HeifDecoderImpl::decode(HeifFrameInfo* frameInfo) {
Chong Zhang3f3ffab2017-08-23 13:51:59 -0700380 // reset scanline pointer
381 mCurScanline = 0;
382
383 if (mFrameDecoded) {
384 return true;
385 }
386
Chong Zhangd3e0d862017-10-03 13:17:13 -0700387 if (mHasImage) {
388 // image index < 0 to retrieve primary image
389 mFrameMemory = mRetriever->getImageAtIndex(-1, mOutputColor);
390 } else if (mHasVideo) {
391 mFrameMemory = mRetriever->getFrameAtTime(0,
392 MediaSource::ReadOptions::SEEK_PREVIOUS_SYNC, mOutputColor);
393 }
394
Chong Zhangea280cb2017-08-02 11:10:10 -0700395 if (mFrameMemory == nullptr || mFrameMemory->pointer() == nullptr) {
396 ALOGE("getFrameAtTime: videoFrame is a nullptr");
397 return false;
398 }
399
400 VideoFrame* videoFrame = static_cast<VideoFrame*>(mFrameMemory->pointer());
Chong Zhang3f3ffab2017-08-23 13:51:59 -0700401 if (videoFrame->mSize == 0 ||
402 mFrameMemory->size() < videoFrame->getFlattenedSize()) {
403 ALOGE("getFrameAtTime: videoFrame size is invalid");
404 return false;
405 }
406
Chong Zhangea280cb2017-08-02 11:10:10 -0700407 ALOGV("Decoded dimension %dx%d, display %dx%d, angle %d, rowbytes %d, size %d",
408 videoFrame->mWidth,
409 videoFrame->mHeight,
410 videoFrame->mDisplayWidth,
411 videoFrame->mDisplayHeight,
412 videoFrame->mRotationAngle,
413 videoFrame->mRowBytes,
414 videoFrame->mSize);
415
416 if (frameInfo != nullptr) {
417 frameInfo->set(
Chong Zhang70b0afd2018-02-27 12:43:06 -0800418 videoFrame->mWidth,
419 videoFrame->mHeight,
Chong Zhangea280cb2017-08-02 11:10:10 -0700420 videoFrame->mRotationAngle,
421 videoFrame->mBytesPerPixel,
422 videoFrame->mIccSize,
423 videoFrame->getFlattenedIccData());
424 }
Chong Zhang3f3ffab2017-08-23 13:51:59 -0700425 mFrameDecoded = true;
Chong Zhang4c6398b2017-09-07 17:43:19 -0700426
427 // Aggressive clear to avoid holding on to resources
428 mRetriever.clear();
429 mDataSource.clear();
Chong Zhangea280cb2017-08-02 11:10:10 -0700430 return true;
431}
432
433bool HeifDecoderImpl::getScanline(uint8_t* dst) {
434 if (mFrameMemory == nullptr || mFrameMemory->pointer() == nullptr) {
435 return false;
436 }
437 VideoFrame* videoFrame = static_cast<VideoFrame*>(mFrameMemory->pointer());
Chong Zhang70b0afd2018-02-27 12:43:06 -0800438 if (mCurScanline >= videoFrame->mHeight) {
Chong Zhangee079fe2017-08-23 13:51:17 -0700439 ALOGE("no more scanline available");
Chong Zhangea280cb2017-08-02 11:10:10 -0700440 return false;
441 }
442 uint8_t* src = videoFrame->getFlattenedData() + videoFrame->mRowBytes * mCurScanline++;
Chong Zhang70b0afd2018-02-27 12:43:06 -0800443 memcpy(dst, src, videoFrame->mBytesPerPixel * videoFrame->mWidth);
Chong Zhangea280cb2017-08-02 11:10:10 -0700444 return true;
445}
446
447size_t HeifDecoderImpl::skipScanlines(size_t count) {
448 if (mFrameMemory == nullptr || mFrameMemory->pointer() == nullptr) {
449 return 0;
450 }
451 VideoFrame* videoFrame = static_cast<VideoFrame*>(mFrameMemory->pointer());
452
453 uint32_t oldScanline = mCurScanline;
454 mCurScanline += count;
Chong Zhang70b0afd2018-02-27 12:43:06 -0800455 if (mCurScanline > videoFrame->mHeight) {
456 mCurScanline = videoFrame->mHeight;
Chong Zhangea280cb2017-08-02 11:10:10 -0700457 }
458 return (mCurScanline > oldScanline) ? (mCurScanline - oldScanline) : 0;
459}
460
461} // namespace android