blob: 3eba863108f71ff747d7df12319d9972de06b6b3 [file] [log] [blame]
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001/*
2 * Copyright (C) 2019 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_TAG "Camera3-HeicCompositeStream"
18#define ATRACE_TAG ATRACE_TAG_CAMERA
19//#define LOG_NDEBUG 0
20
21#include <linux/memfd.h>
22#include <pthread.h>
23#include <sys/syscall.h>
24
25#include <android/hardware/camera/device/3.5/types.h>
26#include <gui/Surface.h>
27#include <utils/Log.h>
28#include <utils/Trace.h>
29
30#include <media/ICrypto.h>
31#include <media/MediaCodecBuffer.h>
32#include <media/stagefright/foundation/ABuffer.h>
33#include <media/stagefright/foundation/AMessage.h>
34#include <media/stagefright/foundation/MediaDefs.h>
35#include <media/stagefright/MediaCodecConstants.h>
36
37#include "common/CameraDeviceBase.h"
38#include "utils/ExifUtils.h"
39#include "HeicEncoderInfoManager.h"
40#include "HeicCompositeStream.h"
41
42using android::hardware::camera::device::V3_5::CameraBlob;
43using android::hardware::camera::device::V3_5::CameraBlobId;
44
45namespace android {
46namespace camera3 {
47
48HeicCompositeStream::HeicCompositeStream(wp<CameraDeviceBase> device,
49 wp<hardware::camera2::ICameraDeviceCallbacks> cb) :
50 CompositeStream(device, cb),
51 mUseHeic(false),
52 mNumOutputTiles(1),
53 mOutputWidth(0),
54 mOutputHeight(0),
55 mMaxHeicBufferSize(0),
56 mGridWidth(HeicEncoderInfoManager::kGridWidth),
57 mGridHeight(HeicEncoderInfoManager::kGridHeight),
58 mGridRows(1),
59 mGridCols(1),
60 mUseGrid(false),
61 mAppSegmentStreamId(-1),
62 mAppSegmentSurfaceId(-1),
63 mAppSegmentBufferAcquired(false),
64 mMainImageStreamId(-1),
65 mMainImageSurfaceId(-1),
66 mYuvBufferAcquired(false),
67 mProducerListener(new ProducerListener()),
68 mOutputBufferCounter(0),
69 mGridTimestampUs(0) {
70}
71
72HeicCompositeStream::~HeicCompositeStream() {
73 // Call deinitCodec in case stream hasn't been deleted yet to avoid any
74 // memory/resource leak.
75 deinitCodec();
76
77 mInputAppSegmentBuffers.clear();
78 mCodecOutputBuffers.clear();
79
80 mAppSegmentStreamId = -1;
81 mAppSegmentSurfaceId = -1;
82 mAppSegmentConsumer.clear();
83 mAppSegmentSurface.clear();
84
85 mMainImageStreamId = -1;
86 mMainImageSurfaceId = -1;
87 mMainImageConsumer.clear();
88 mMainImageSurface.clear();
89}
90
91bool HeicCompositeStream::isHeicCompositeStream(const sp<Surface> &surface) {
92 ANativeWindow *anw = surface.get();
93 status_t err;
94 int format;
95 if ((err = anw->query(anw, NATIVE_WINDOW_FORMAT, &format)) != OK) {
96 String8 msg = String8::format("Failed to query Surface format: %s (%d)", strerror(-err),
97 err);
98 ALOGE("%s: %s", __FUNCTION__, msg.string());
99 return false;
100 }
101
102 int dataspace;
103 if ((err = anw->query(anw, NATIVE_WINDOW_DEFAULT_DATASPACE, &dataspace)) != OK) {
104 String8 msg = String8::format("Failed to query Surface dataspace: %s (%d)", strerror(-err),
105 err);
106 ALOGE("%s: %s", __FUNCTION__, msg.string());
107 return false;
108 }
109
110 return ((format == HAL_PIXEL_FORMAT_BLOB) && (dataspace == HAL_DATASPACE_HEIF));
111}
112
113status_t HeicCompositeStream::createInternalStreams(const std::vector<sp<Surface>>& consumers,
114 bool /*hasDeferredConsumer*/, uint32_t width, uint32_t height, int format,
115 camera3_stream_rotation_t rotation, int *id, const String8& physicalCameraId,
116 std::vector<int> *surfaceIds, int /*streamSetId*/, bool /*isShared*/) {
117
118 sp<CameraDeviceBase> device = mDevice.promote();
119 if (!device.get()) {
120 ALOGE("%s: Invalid camera device!", __FUNCTION__);
121 return NO_INIT;
122 }
123
124 status_t res = initializeCodec(width, height, device);
125 if (res != OK) {
126 ALOGE("%s: Failed to initialize HEIC/HEVC codec: %s (%d)",
127 __FUNCTION__, strerror(-res), res);
128 return NO_INIT;
129 }
130
131 sp<IGraphicBufferProducer> producer;
132 sp<IGraphicBufferConsumer> consumer;
133 BufferQueue::createBufferQueue(&producer, &consumer);
134 mAppSegmentConsumer = new CpuConsumer(consumer, 1);
135 mAppSegmentConsumer->setFrameAvailableListener(this);
136 mAppSegmentConsumer->setName(String8("Camera3-HeicComposite-AppSegmentStream"));
137 mAppSegmentSurface = new Surface(producer);
138
139 res = device->createStream(mAppSegmentSurface, mAppSegmentMaxSize, 1, format,
140 kAppSegmentDataSpace, rotation, &mAppSegmentStreamId, physicalCameraId, surfaceIds);
141 if (res == OK) {
142 mAppSegmentSurfaceId = (*surfaceIds)[0];
143 } else {
144 ALOGE("%s: Failed to create JPEG App segment stream: %s (%d)", __FUNCTION__,
145 strerror(-res), res);
146 return res;
147 }
148
149 if (!mUseGrid) {
150 res = mCodec->createInputSurface(&producer);
151 if (res != OK) {
152 ALOGE("%s: Failed to create input surface for Heic codec: %s (%d)",
153 __FUNCTION__, strerror(-res), res);
154 return res;
155 }
156 } else {
157 BufferQueue::createBufferQueue(&producer, &consumer);
158 mMainImageConsumer = new CpuConsumer(consumer, 1);
159 mMainImageConsumer->setFrameAvailableListener(this);
160 mMainImageConsumer->setName(String8("Camera3-HeicComposite-HevcInputYUVStream"));
161 }
162 mMainImageSurface = new Surface(producer);
163
164 res = mCodec->start();
165 if (res != OK) {
166 ALOGE("%s: Failed to start codec: %s (%d)", __FUNCTION__,
167 strerror(-res), res);
168 return res;
169 }
170
171 std::vector<int> sourceSurfaceId;
172 //Use YUV_888 format if framework tiling is needed.
173 int srcStreamFmt = mUseGrid ? HAL_PIXEL_FORMAT_YCbCr_420_888 :
174 HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED;
175 res = device->createStream(mMainImageSurface, width, height, srcStreamFmt, kHeifDataSpace,
176 rotation, id, physicalCameraId, &sourceSurfaceId);
177 if (res == OK) {
178 mMainImageSurfaceId = sourceSurfaceId[0];
179 mMainImageStreamId = *id;
180 } else {
181 ALOGE("%s: Failed to create main image stream: %s (%d)", __FUNCTION__,
182 strerror(-res), res);
183 return res;
184 }
185
186 mOutputSurface = consumers[0];
187 res = registerCompositeStreamListener(getStreamId());
188 if (res != OK) {
189 ALOGE("%s: Failed to register HAL main image stream", __FUNCTION__);
190 return res;
191 }
192
193 return res;
194}
195
196status_t HeicCompositeStream::deleteInternalStreams() {
197 requestExit();
198 auto res = join();
199 if (res != OK) {
200 ALOGE("%s: Failed to join with the main processing thread: %s (%d)", __FUNCTION__,
201 strerror(-res), res);
202 }
203
204 deinitCodec();
205
206 if (mAppSegmentStreamId >= 0) {
207 sp<CameraDeviceBase> device = mDevice.promote();
208 if (!device.get()) {
209 ALOGE("%s: Invalid camera device!", __FUNCTION__);
210 return NO_INIT;
211 }
212
213 res = device->deleteStream(mAppSegmentStreamId);
214 mAppSegmentStreamId = -1;
215 }
216
217 return res;
218}
219
220void HeicCompositeStream::onBufferReleased(const BufferInfo& bufferInfo) {
221 Mutex::Autolock l(mMutex);
222
223 if (bufferInfo.mError) return;
224
225 mCodecOutputBufferTimestamps.push(bufferInfo.mTimestamp);
226}
227
228// We need to get the settings early to handle the case where the codec output
229// arrives earlier than result metadata.
230void HeicCompositeStream::onBufferRequestForFrameNumber(uint64_t frameNumber, int streamId,
231 const CameraMetadata& settings) {
232 ATRACE_ASYNC_BEGIN("HEIC capture", frameNumber);
233
234 Mutex::Autolock l(mMutex);
235 if (mErrorState || (streamId != getStreamId())) {
236 return;
237 }
238
239 mPendingCaptureResults.emplace(frameNumber, CameraMetadata());
240
241 camera_metadata_ro_entry entry;
242
243 int32_t orientation = 0;
244 entry = settings.find(ANDROID_JPEG_ORIENTATION);
245 if (entry.count == 1) {
246 orientation = entry.data.i32[0];
247 }
248
249 int32_t quality = kDefaultJpegQuality;
250 entry = settings.find(ANDROID_JPEG_QUALITY);
251 if (entry.count == 1) {
252 quality = entry.data.i32[0];
253 }
254
255 mSettingsByFrameNumber[frameNumber] = std::make_pair(orientation, quality);
256}
257
258void HeicCompositeStream::onFrameAvailable(const BufferItem& item) {
259 if (item.mDataSpace == static_cast<android_dataspace>(kAppSegmentDataSpace)) {
260 ALOGV("%s: JPEG APP segments buffer with ts: %" PRIu64 " ms. arrived!",
261 __func__, ns2ms(item.mTimestamp));
262
263 Mutex::Autolock l(mMutex);
264 if (!mErrorState) {
265 mInputAppSegmentBuffers.push_back(item.mTimestamp);
266 mInputReadyCondition.signal();
267 }
268 } else if (item.mDataSpace == kHeifDataSpace) {
269 ALOGV("%s: YUV_888 buffer with ts: %" PRIu64 " ms. arrived!",
270 __func__, ns2ms(item.mTimestamp));
271
272 Mutex::Autolock l(mMutex);
273 if (!mUseGrid) {
274 ALOGE("%s: YUV_888 internal stream is only supported for HEVC tiling",
275 __FUNCTION__);
276 return;
277 }
278 if (!mErrorState) {
279 mInputYuvBuffers.push_back(item.mTimestamp);
280 mInputReadyCondition.signal();
281 }
282 } else {
283 ALOGE("%s: Unexpected data space: 0x%x", __FUNCTION__, item.mDataSpace);
284 }
285}
286
287status_t HeicCompositeStream::getCompositeStreamInfo(const OutputStreamInfo &streamInfo,
288 const CameraMetadata& ch, std::vector<OutputStreamInfo>* compositeOutput /*out*/) {
289 if (compositeOutput == nullptr) {
290 return BAD_VALUE;
291 }
292
293 compositeOutput->clear();
294
295 bool useGrid, useHeic;
296 bool isSizeSupported = isSizeSupportedByHeifEncoder(
297 streamInfo.width, streamInfo.height, &useHeic, &useGrid, nullptr);
298 if (!isSizeSupported) {
299 // Size is not supported by either encoder.
300 return OK;
301 }
302
303 compositeOutput->insert(compositeOutput->end(), 2, streamInfo);
304
305 // JPEG APPS segments Blob stream info
306 (*compositeOutput)[0].width = calcAppSegmentMaxSize(ch);
307 (*compositeOutput)[0].height = 1;
308 (*compositeOutput)[0].format = HAL_PIXEL_FORMAT_BLOB;
309 (*compositeOutput)[0].dataSpace = kAppSegmentDataSpace;
310 (*compositeOutput)[0].consumerUsage = GRALLOC_USAGE_SW_READ_OFTEN;
311
312 // YUV/IMPLEMENTATION_DEFINED stream info
313 (*compositeOutput)[1].width = streamInfo.width;
314 (*compositeOutput)[1].height = streamInfo.height;
315 (*compositeOutput)[1].format = useGrid ? HAL_PIXEL_FORMAT_YCbCr_420_888 :
316 HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED;
317 (*compositeOutput)[1].dataSpace = kHeifDataSpace;
318 (*compositeOutput)[1].consumerUsage = useHeic ? GRALLOC_USAGE_HW_IMAGE_ENCODER :
319 useGrid ? GRALLOC_USAGE_SW_READ_OFTEN : GRALLOC_USAGE_HW_VIDEO_ENCODER;
320
321 return NO_ERROR;
322}
323
324bool HeicCompositeStream::isSizeSupportedByHeifEncoder(int32_t width, int32_t height,
325 bool* useHeic, bool* useGrid, int64_t* stall) {
326 static HeicEncoderInfoManager& heicManager = HeicEncoderInfoManager::getInstance();
327 return heicManager.isSizeSupported(width, height, useHeic, useGrid, stall);
328}
329
330bool HeicCompositeStream::isInMemoryTempFileSupported() {
331 int memfd = syscall(__NR_memfd_create, "HEIF-try-memfd", MFD_CLOEXEC);
332 if (memfd == -1) {
333 if (errno != ENOSYS) {
334 ALOGE("%s: Failed to create tmpfs file. errno %d", __FUNCTION__, errno);
335 }
336 return false;
337 }
338 close(memfd);
339 return true;
340}
341
342void HeicCompositeStream::onHeicOutputFrameAvailable(
343 const CodecOutputBufferInfo& outputBufferInfo) {
344 Mutex::Autolock l(mMutex);
345
346 ALOGV("%s: index %d, offset %d, size %d, time %" PRId64 ", flags 0x%x",
347 __FUNCTION__, outputBufferInfo.index, outputBufferInfo.offset,
348 outputBufferInfo.size, outputBufferInfo.timeUs, outputBufferInfo.flags);
349
350 if (!mErrorState) {
351 if ((outputBufferInfo.size > 0) &&
352 ((outputBufferInfo.flags & MediaCodec::BUFFER_FLAG_CODECCONFIG) == 0)) {
353 mCodecOutputBuffers.push_back(outputBufferInfo);
354 mInputReadyCondition.signal();
355 } else {
356 mCodec->releaseOutputBuffer(outputBufferInfo.index);
357 }
358 } else {
359 mCodec->releaseOutputBuffer(outputBufferInfo.index);
360 }
361}
362
363void HeicCompositeStream::onHeicInputFrameAvailable(int32_t index) {
364 Mutex::Autolock l(mMutex);
365
366 if (!mUseGrid) {
367 ALOGE("%s: Codec YUV input mode must only be used for Hevc tiling mode", __FUNCTION__);
368 return;
369 }
370
371 mCodecInputBuffers.push_back(index);
372 mInputReadyCondition.signal();
373}
374
375void HeicCompositeStream::onHeicFormatChanged(sp<AMessage>& newFormat) {
376 if (newFormat == nullptr) {
377 ALOGE("%s: newFormat must not be null!", __FUNCTION__);
378 return;
379 }
380
381 Mutex::Autolock l(mMutex);
382
383 AString mime;
384 AString mimeHeic(MIMETYPE_IMAGE_ANDROID_HEIC);
385 newFormat->findString(KEY_MIME, &mime);
386 if (mime != mimeHeic) {
387 // For HEVC codec, below keys need to be filled out or overwritten so that the
388 // muxer can handle them as HEIC output image.
389 newFormat->setString(KEY_MIME, mimeHeic);
390 newFormat->setInt32(KEY_WIDTH, mOutputWidth);
391 newFormat->setInt32(KEY_HEIGHT, mOutputHeight);
392 if (mUseGrid) {
393 newFormat->setInt32(KEY_TILE_WIDTH, mGridWidth);
394 newFormat->setInt32(KEY_TILE_HEIGHT, mGridHeight);
395 newFormat->setInt32(KEY_GRID_ROWS, mGridRows);
396 newFormat->setInt32(KEY_GRID_COLUMNS, mGridCols);
397 }
398 }
399 newFormat->setInt32(KEY_IS_DEFAULT, 1 /*isPrimary*/);
400
401 int32_t gridRows, gridCols;
402 if (newFormat->findInt32(KEY_GRID_ROWS, &gridRows) &&
403 newFormat->findInt32(KEY_GRID_COLUMNS, &gridCols)) {
404 mNumOutputTiles = gridRows * gridCols;
405 } else {
406 mNumOutputTiles = 1;
407 }
408
409 ALOGV("%s: mNumOutputTiles is %zu", __FUNCTION__, mNumOutputTiles);
410 mFormat = newFormat;
411}
412
413void HeicCompositeStream::onHeicCodecError() {
414 Mutex::Autolock l(mMutex);
415 mErrorState = true;
416}
417
418status_t HeicCompositeStream::configureStream() {
419 if (isRunning()) {
420 // Processing thread is already running, nothing more to do.
421 return NO_ERROR;
422 }
423
424 if (mOutputSurface.get() == nullptr) {
425 ALOGE("%s: No valid output surface set!", __FUNCTION__);
426 return NO_INIT;
427 }
428
429 auto res = mOutputSurface->connect(NATIVE_WINDOW_API_CAMERA, mProducerListener);
430 if (res != OK) {
431 ALOGE("%s: Unable to connect to native window for stream %d",
432 __FUNCTION__, mMainImageStreamId);
433 return res;
434 }
435
436 if ((res = native_window_set_buffers_format(mOutputSurface.get(), HAL_PIXEL_FORMAT_BLOB))
437 != OK) {
438 ALOGE("%s: Unable to configure stream buffer format for stream %d", __FUNCTION__,
439 mMainImageStreamId);
440 return res;
441 }
442
443 ANativeWindow *anwConsumer = mOutputSurface.get();
444 int maxConsumerBuffers;
445 if ((res = anwConsumer->query(anwConsumer, NATIVE_WINDOW_MIN_UNDEQUEUED_BUFFERS,
446 &maxConsumerBuffers)) != OK) {
447 ALOGE("%s: Unable to query consumer undequeued"
448 " buffer count for stream %d", __FUNCTION__, mMainImageStreamId);
449 return res;
450 }
451
452 // Cannot use SourceSurface buffer count since it could be codec's 512*512 tile
453 // buffer count.
454 int maxProducerBuffers = 1;
455 if ((res = native_window_set_buffer_count(
456 anwConsumer, maxProducerBuffers + maxConsumerBuffers)) != OK) {
457 ALOGE("%s: Unable to set buffer count for stream %d", __FUNCTION__, mMainImageStreamId);
458 return res;
459 }
460
461 if ((res = native_window_set_buffers_dimensions(anwConsumer, mMaxHeicBufferSize, 1)) != OK) {
462 ALOGE("%s: Unable to set buffer dimension %zu x 1 for stream %d: %s (%d)",
463 __FUNCTION__, mMaxHeicBufferSize, mMainImageStreamId, strerror(-res), res);
464 return res;
465 }
466
467 run("HeicCompositeStreamProc");
468
469 return NO_ERROR;
470}
471
472status_t HeicCompositeStream::insertGbp(SurfaceMap* /*out*/outSurfaceMap,
473 Vector<int32_t>* /*out*/outputStreamIds, int32_t* /*out*/currentStreamId) {
474 if (outSurfaceMap->find(mAppSegmentStreamId) == outSurfaceMap->end()) {
475 (*outSurfaceMap)[mAppSegmentStreamId] = std::vector<size_t>();
476 outputStreamIds->push_back(mAppSegmentStreamId);
477 }
478 (*outSurfaceMap)[mAppSegmentStreamId].push_back(mAppSegmentSurfaceId);
479
480 if (outSurfaceMap->find(mMainImageStreamId) == outSurfaceMap->end()) {
481 (*outSurfaceMap)[mMainImageStreamId] = std::vector<size_t>();
482 outputStreamIds->push_back(mMainImageStreamId);
483 }
484 (*outSurfaceMap)[mMainImageStreamId].push_back(mMainImageSurfaceId);
485
486 if (currentStreamId != nullptr) {
487 *currentStreamId = mMainImageStreamId;
488 }
489
490 return NO_ERROR;
491}
492
493void HeicCompositeStream::onShutter(const CaptureResultExtras& resultExtras, nsecs_t timestamp) {
494 Mutex::Autolock l(mMutex);
495 if (mErrorState) {
496 return;
497 }
498
499 if (mSettingsByFrameNumber.find(resultExtras.frameNumber) != mSettingsByFrameNumber.end()) {
500 mFrameNumberMap.emplace(resultExtras.frameNumber, timestamp);
501 mSettingsByTimestamp[timestamp] = mSettingsByFrameNumber[resultExtras.frameNumber];
502 mSettingsByFrameNumber.erase(resultExtras.frameNumber);
503 mInputReadyCondition.signal();
504 }
505}
506
507void HeicCompositeStream::compilePendingInputLocked() {
508 while (!mSettingsByTimestamp.empty()) {
509 auto it = mSettingsByTimestamp.begin();
510 mPendingInputFrames[it->first].orientation = it->second.first;
511 mPendingInputFrames[it->first].quality = it->second.second;
512 mSettingsByTimestamp.erase(it);
513 }
514
515 while (!mInputAppSegmentBuffers.empty() && !mAppSegmentBufferAcquired) {
516 CpuConsumer::LockedBuffer imgBuffer;
517 auto it = mInputAppSegmentBuffers.begin();
518 auto res = mAppSegmentConsumer->lockNextBuffer(&imgBuffer);
519 if (res == NOT_ENOUGH_DATA) {
520 // Canot not lock any more buffers.
521 break;
522 } else if ((res != OK) || (*it != imgBuffer.timestamp)) {
523 if (res != OK) {
524 ALOGE("%s: Error locking JPEG_APP_SEGMENTS image buffer: %s (%d)", __FUNCTION__,
525 strerror(-res), res);
526 } else {
527 ALOGE("%s: Expecting JPEG_APP_SEGMENTS buffer with time stamp: %" PRId64
528 " received buffer with time stamp: %" PRId64, __FUNCTION__,
529 *it, imgBuffer.timestamp);
530 }
531 mPendingInputFrames[*it].error = true;
532 mInputAppSegmentBuffers.erase(it);
533 continue;
534 }
535
536 if ((mPendingInputFrames.find(imgBuffer.timestamp) != mPendingInputFrames.end()) &&
537 (mPendingInputFrames[imgBuffer.timestamp].error)) {
538 mAppSegmentConsumer->unlockBuffer(imgBuffer);
539 } else {
540 mPendingInputFrames[imgBuffer.timestamp].appSegmentBuffer = imgBuffer;
541 mAppSegmentBufferAcquired = true;
542 }
543 mInputAppSegmentBuffers.erase(it);
544 }
545
546 while (!mInputYuvBuffers.empty() && !mYuvBufferAcquired) {
547 CpuConsumer::LockedBuffer imgBuffer;
548 auto it = mInputYuvBuffers.begin();
549 auto res = mMainImageConsumer->lockNextBuffer(&imgBuffer);
550 if (res == NOT_ENOUGH_DATA) {
551 // Canot not lock any more buffers.
552 break;
553 } else if (res != OK) {
554 ALOGE("%s: Error locking YUV_888 image buffer: %s (%d)", __FUNCTION__,
555 strerror(-res), res);
556 mPendingInputFrames[*it].error = true;
557 mInputYuvBuffers.erase(it);
558 continue;
559 } else if (*it != imgBuffer.timestamp) {
560 ALOGW("%s: Expecting YUV_888 buffer with time stamp: %" PRId64 " received buffer with "
561 "time stamp: %" PRId64, __FUNCTION__, *it, imgBuffer.timestamp);
562 mPendingInputFrames[*it].error = true;
563 mInputYuvBuffers.erase(it);
564 continue;
565 }
566
567 if ((mPendingInputFrames.find(imgBuffer.timestamp) != mPendingInputFrames.end()) &&
568 (mPendingInputFrames[imgBuffer.timestamp].error)) {
569 mMainImageConsumer->unlockBuffer(imgBuffer);
570 } else {
571 mPendingInputFrames[imgBuffer.timestamp].yuvBuffer = imgBuffer;
572 mYuvBufferAcquired = true;
573 }
574 mInputYuvBuffers.erase(it);
575 }
576
577 while (!mCodecOutputBuffers.empty()) {
578 auto it = mCodecOutputBuffers.begin();
579 // Bitstream buffer timestamp doesn't necessarily directly correlate with input
580 // buffer timestamp. Assume encoder input to output is FIFO, use a queue
581 // to look up timestamp.
582 int64_t bufferTime = -1;
583 if (mCodecOutputBufferTimestamps.empty()) {
584 ALOGE("%s: Failed to find buffer timestamp for codec output buffer!", __FUNCTION__);
585 } else {
586 // Direct mapping between camera timestamp (in ns) and codec timestamp (in us).
587 bufferTime = mCodecOutputBufferTimestamps.front();
588 mOutputBufferCounter++;
589 if (mOutputBufferCounter == mNumOutputTiles) {
590 mCodecOutputBufferTimestamps.pop();
591 mOutputBufferCounter = 0;
592 }
593
594 mPendingInputFrames[bufferTime].codecOutputBuffers.push_back(*it);
595 }
596 mCodecOutputBuffers.erase(it);
597 }
598
599 while (!mFrameNumberMap.empty()) {
600 auto it = mFrameNumberMap.begin();
601 mPendingInputFrames[it->second].frameNumber = it->first;
602 mFrameNumberMap.erase(it);
603 }
604
605 // Heic composition doesn't depend on capture result, so no need to check
606 // mErrorFrameNumbers. Just remove them.
607 mErrorFrameNumbers.clear();
608
609 // Distribute codec input buffers to be filled out from YUV output
610 for (auto it = mPendingInputFrames.begin();
611 it != mPendingInputFrames.end() && mCodecInputBuffers.size() > 0; it++) {
612 InputFrame& inputFrame(it->second);
613 if (inputFrame.codecInputCounter < mGridRows * mGridCols) {
614 // Available input tiles that are required for the current input
615 // image.
616 size_t newInputTiles = std::min(mCodecInputBuffers.size(),
617 mGridRows * mGridCols - inputFrame.codecInputCounter);
618 for (size_t i = 0; i < newInputTiles; i++) {
619 CodecInputBufferInfo inputInfo =
620 { mCodecInputBuffers[0], mGridTimestampUs++, inputFrame.codecInputCounter };
621 inputFrame.codecInputBuffers.push_back(inputInfo);
622
623 mCodecInputBuffers.erase(mCodecInputBuffers.begin());
624 inputFrame.codecInputCounter++;
625 }
626 break;
627 }
628 }
629}
630
631bool HeicCompositeStream::getNextReadyInputLocked(int64_t *currentTs /*out*/) {
632 if (currentTs == nullptr) {
633 return false;
634 }
635
636 bool newInputAvailable = false;
637 for (const auto& it : mPendingInputFrames) {
638 bool appSegmentBufferReady = (it.second.appSegmentBuffer.data != nullptr) &&
639 !it.second.appSegmentWritten;
640 bool codecOutputReady = !it.second.codecOutputBuffers.empty();
641 bool codecInputReady = (it.second.yuvBuffer.data != nullptr) &&
642 (!it.second.codecInputBuffers.empty());
643 if ((!it.second.error) &&
644 (it.first < *currentTs) &&
645 (appSegmentBufferReady || codecOutputReady || codecInputReady)) {
646 *currentTs = it.first;
647 newInputAvailable = true;
648 break;
649 }
650 }
651
652 return newInputAvailable;
653}
654
655int64_t HeicCompositeStream::getNextFailingInputLocked(int64_t *currentTs /*out*/) {
656 int64_t res = -1;
657 if (currentTs == nullptr) {
658 return res;
659 }
660
661 for (const auto& it : mPendingInputFrames) {
662 if (it.second.error && !it.second.errorNotified && (it.first < *currentTs)) {
663 *currentTs = it.first;
664 res = it.second.frameNumber;
665 break;
666 }
667 }
668
669 return res;
670}
671
672status_t HeicCompositeStream::processInputFrame(nsecs_t timestamp,
673 InputFrame &inputFrame) {
674 ATRACE_CALL();
675 status_t res = OK;
676
677 bool appSegmentBufferReady = inputFrame.appSegmentBuffer.data != nullptr &&
678 !inputFrame.appSegmentWritten;
679 bool codecOutputReady = inputFrame.codecOutputBuffers.size() > 0;
680 bool codecInputReady = inputFrame.yuvBuffer.data != nullptr &&
681 !inputFrame.codecInputBuffers.empty();
682
683 if (!appSegmentBufferReady && !codecOutputReady && !codecInputReady) {
684 ALOGW("%s: No valid appSegmentBuffer/codec input/outputBuffer available!", __FUNCTION__);
685 return OK;
686 }
687
688 // Handle inputs for Hevc tiling
689 if (codecInputReady) {
690 res = processCodecInputFrame(inputFrame);
691 if (res != OK) {
692 ALOGE("%s: Failed to process codec input frame: %s (%d)", __FUNCTION__,
693 strerror(-res), res);
694 return res;
695 }
696 }
697
698 // Initialize and start muxer if not yet done so
699 if (inputFrame.muxer == nullptr) {
700 res = startMuxerForInputFrame(timestamp, inputFrame);
701 if (res != OK) {
702 ALOGE("%s: Failed to create and start muxer: %s (%d)", __FUNCTION__,
703 strerror(-res), res);
704 return res;
705 }
706 }
707
708 // Write JPEG APP segments data to the muxer.
709 if (appSegmentBufferReady && inputFrame.muxer != nullptr) {
710 res = processAppSegment(timestamp, inputFrame);
711 if (res != OK) {
712 ALOGE("%s: Failed to process JPEG APP segments: %s (%d)", __FUNCTION__,
713 strerror(-res), res);
714 return res;
715 }
716 }
717
718 // Write media codec bitstream buffers to muxer.
719 while (!inputFrame.codecOutputBuffers.empty()) {
720 res = processOneCodecOutputFrame(timestamp, inputFrame);
721 if (res != OK) {
722 ALOGE("%s: Failed to process codec output frame: %s (%d)", __FUNCTION__,
723 strerror(-res), res);
724 return res;
725 }
726 }
727
728 if (inputFrame.appSegmentWritten && inputFrame.pendingOutputTiles == 0) {
729 res = processCompletedInputFrame(timestamp, inputFrame);
730 if (res != OK) {
731 ALOGE("%s: Failed to process completed input frame: %s (%d)", __FUNCTION__,
732 strerror(-res), res);
733 return res;
734 }
735 }
736
737 return res;
738}
739
740status_t HeicCompositeStream::startMuxerForInputFrame(nsecs_t timestamp, InputFrame &inputFrame) {
741 sp<ANativeWindow> outputANW = mOutputSurface;
742 if (inputFrame.codecOutputBuffers.size() == 0) {
743 // No single codec output buffer has been generated. Continue to
744 // wait.
745 return OK;
746 }
747
748 auto res = outputANW->dequeueBuffer(mOutputSurface.get(), &inputFrame.anb, &inputFrame.fenceFd);
749 if (res != OK) {
750 ALOGE("%s: Error retrieving output buffer: %s (%d)", __FUNCTION__, strerror(-res),
751 res);
752 return res;
753 }
754
755 // Combine current thread id, stream id and timestamp to uniquely identify image.
756 std::ostringstream tempOutputFile;
757 tempOutputFile << "HEIF-" << pthread_self() << "-"
758 << getStreamId() << "-" << timestamp;
759 inputFrame.fileFd = syscall(__NR_memfd_create, tempOutputFile.str().c_str(), MFD_CLOEXEC);
760 if (inputFrame.fileFd < 0) {
761 ALOGE("%s: Failed to create file %s. Error no is %d", __FUNCTION__,
762 tempOutputFile.str().c_str(), errno);
763 return NO_INIT;
764 }
765 inputFrame.muxer = new MediaMuxer(inputFrame.fileFd, MediaMuxer::OUTPUT_FORMAT_HEIF);
766 if (inputFrame.muxer == nullptr) {
767 ALOGE("%s: Failed to create MediaMuxer for file fd %d",
768 __FUNCTION__, inputFrame.fileFd);
769 return NO_INIT;
770 }
771
772 res = inputFrame.muxer->setOrientationHint(inputFrame.orientation);
773 if (res != OK) {
774 ALOGE("%s: Failed to setOrientationHint: %s (%d)", __FUNCTION__,
775 strerror(-res), res);
776 return res;
777 }
778 // Set encoder quality
779 {
780 sp<AMessage> qualityParams = new AMessage;
781 qualityParams->setInt32(PARAMETER_KEY_VIDEO_BITRATE, inputFrame.quality);
782 res = mCodec->setParameters(qualityParams);
783 if (res != OK) {
784 ALOGE("%s: Failed to set codec quality: %s (%d)",
785 __FUNCTION__, strerror(-res), res);
786 return res;
787 }
788 }
789
790 ssize_t trackId = inputFrame.muxer->addTrack(mFormat);
791 if (trackId < 0) {
792 ALOGE("%s: Failed to addTrack to the muxer: %zd", __FUNCTION__, trackId);
793 return NO_INIT;
794 }
795
796 inputFrame.trackIndex = trackId;
797 inputFrame.pendingOutputTiles = mNumOutputTiles;
798
799 res = inputFrame.muxer->start();
800 if (res != OK) {
801 ALOGE("%s: Failed to start MediaMuxer: %s (%d)",
802 __FUNCTION__, strerror(-res), res);
803 return res;
804 }
805
806 return OK;
807}
808
809status_t HeicCompositeStream::processAppSegment(nsecs_t timestamp, InputFrame &inputFrame) {
810 size_t app1Size = 0;
811 auto appSegmentSize = findAppSegmentsSize(inputFrame.appSegmentBuffer.data,
812 inputFrame.appSegmentBuffer.width * inputFrame.appSegmentBuffer.height,
813 &app1Size);
814 ALOGV("%s: appSegmentSize is %zu, width %d, height %d, app1Size %zu", __FUNCTION__,
815 appSegmentSize, inputFrame.appSegmentBuffer.width,
816 inputFrame.appSegmentBuffer.height, app1Size);
817 if (appSegmentSize == 0) {
818 ALOGE("%s: Failed to find JPEG APP segment size", __FUNCTION__);
819 return NO_INIT;
820 }
821
822 std::unique_ptr<ExifUtils> exifUtils(ExifUtils::create());
823 auto exifRes = exifUtils->initialize(inputFrame.appSegmentBuffer.data, app1Size);
824 if (!exifRes) {
825 ALOGE("%s: Failed to initialize ExifUtils object!", __FUNCTION__);
826 return BAD_VALUE;
827 }
828 //TODO: Use capture result metadata and static metadata to fill out the
829 //rest.
830 CameraMetadata dummyMeta;
831 exifRes = exifUtils->setFromMetadata(dummyMeta, mOutputWidth, mOutputHeight);
832 if (!exifRes) {
833 ALOGE("%s: Failed to set Exif tags using metadata and main image sizes", __FUNCTION__);
834 return BAD_VALUE;
835 }
836 exifRes = exifUtils->setOrientation(inputFrame.orientation);
837 if (!exifRes) {
838 ALOGE("%s: ExifUtils failed to set orientation", __FUNCTION__);
839 return BAD_VALUE;
840 }
841 exifRes = exifUtils->generateApp1();
842 if (!exifRes) {
843 ALOGE("%s: ExifUtils failed to generate APP1 segment", __FUNCTION__);
844 return BAD_VALUE;
845 }
846
847 unsigned int newApp1Length = exifUtils->getApp1Length();
848 const uint8_t *newApp1Segment = exifUtils->getApp1Buffer();
849
850 //Assemble the APP1 marker buffer required by MediaCodec
851 uint8_t kExifApp1Marker[] = {'E', 'x', 'i', 'f', 0xFF, 0xE1, 0x00, 0x00};
852 kExifApp1Marker[6] = static_cast<uint8_t>(newApp1Length >> 8);
853 kExifApp1Marker[7] = static_cast<uint8_t>(newApp1Length & 0xFF);
854 size_t appSegmentBufferSize = sizeof(kExifApp1Marker) +
855 appSegmentSize - app1Size + newApp1Length;
856 uint8_t* appSegmentBuffer = new uint8_t[appSegmentBufferSize];
857 memcpy(appSegmentBuffer, kExifApp1Marker, sizeof(kExifApp1Marker));
858 memcpy(appSegmentBuffer + sizeof(kExifApp1Marker), newApp1Segment, newApp1Length);
859 if (appSegmentSize - app1Size > 0) {
860 memcpy(appSegmentBuffer + sizeof(kExifApp1Marker) + newApp1Length,
861 inputFrame.appSegmentBuffer.data + app1Size, appSegmentSize - app1Size);
862 }
863
864 sp<ABuffer> aBuffer = new ABuffer(appSegmentBuffer, appSegmentBufferSize);
865 auto res = inputFrame.muxer->writeSampleData(aBuffer, inputFrame.trackIndex,
866 timestamp, MediaCodec::BUFFER_FLAG_MUXER_DATA);
867 delete[] appSegmentBuffer;
868
869 if (res != OK) {
870 ALOGE("%s: Failed to write JPEG APP segments to muxer: %s (%d)",
871 __FUNCTION__, strerror(-res), res);
872 return res;
873 }
874 inputFrame.appSegmentWritten = true;
875
876 return OK;
877}
878
879status_t HeicCompositeStream::processCodecInputFrame(InputFrame &inputFrame) {
880 for (auto& inputBuffer : inputFrame.codecInputBuffers) {
881 sp<MediaCodecBuffer> buffer;
882 auto res = mCodec->getInputBuffer(inputBuffer.index, &buffer);
883 if (res != OK) {
884 ALOGE("%s: Error getting codec input buffer: %s (%d)", __FUNCTION__,
885 strerror(-res), res);
886 return res;
887 }
888
889 // Copy one tile from source to destination.
890 size_t tileX = inputBuffer.tileIndex % mGridCols;
891 size_t tileY = inputBuffer.tileIndex / mGridCols;
892 size_t top = mGridHeight * tileY;
893 size_t left = mGridWidth * tileX;
894 size_t width = (tileX == static_cast<size_t>(mGridCols) - 1) ?
895 mOutputWidth - tileX * mGridWidth : mGridWidth;
896 size_t height = (tileY == static_cast<size_t>(mGridRows) - 1) ?
897 mOutputHeight - tileY * mGridHeight : mGridHeight;
898 ALOGV("%s: inputBuffer tileIndex [%zu, %zu], top %zu, left %zu, width %zu, height %zu",
899 __FUNCTION__, tileX, tileY, top, left, width, height);
900
901 res = copyOneYuvTile(buffer, inputFrame.yuvBuffer, top, left, width, height);
902 if (res != OK) {
903 ALOGE("%s: Failed to copy YUV tile %s (%d)", __FUNCTION__,
904 strerror(-res), res);
905 return res;
906 }
907
908 res = mCodec->queueInputBuffer(inputBuffer.index, 0, buffer->capacity(),
909 inputBuffer.timeUs, 0, nullptr /*errorDetailMsg*/);
910 if (res != OK) {
911 ALOGE("%s: Failed to queueInputBuffer to Codec: %s (%d)",
912 __FUNCTION__, strerror(-res), res);
913 return res;
914 }
915 }
916
917 inputFrame.codecInputBuffers.clear();
918 return OK;
919}
920
921status_t HeicCompositeStream::processOneCodecOutputFrame(nsecs_t timestamp,
922 InputFrame &inputFrame) {
923 auto it = inputFrame.codecOutputBuffers.begin();
924 sp<MediaCodecBuffer> buffer;
925 status_t res = mCodec->getOutputBuffer(it->index, &buffer);
926 if (res != OK) {
927 ALOGE("%s: Error getting Heic codec output buffer at index %d: %s (%d)",
928 __FUNCTION__, it->index, strerror(-res), res);
929 return res;
930 }
931 if (buffer == nullptr) {
932 ALOGE("%s: Invalid Heic codec output buffer at index %d",
933 __FUNCTION__, it->index);
934 return BAD_VALUE;
935 }
936
937 sp<ABuffer> aBuffer = new ABuffer(buffer->data(), buffer->size());
938 res = inputFrame.muxer->writeSampleData(
939 aBuffer, inputFrame.trackIndex, timestamp, 0 /*flags*/);
940 if (res != OK) {
941 ALOGE("%s: Failed to write buffer index %d to muxer: %s (%d)",
942 __FUNCTION__, it->index, strerror(-res), res);
943 return res;
944 }
945
946 mCodec->releaseOutputBuffer(it->index);
947 if (inputFrame.pendingOutputTiles == 0) {
948 ALOGW("%s: Codec generated more tiles than expected!", __FUNCTION__);
949 } else {
950 inputFrame.pendingOutputTiles--;
951 }
952
953 inputFrame.codecOutputBuffers.erase(inputFrame.codecOutputBuffers.begin());
954 return OK;
955}
956
957status_t HeicCompositeStream::processCompletedInputFrame(nsecs_t timestamp,
958 InputFrame &inputFrame) {
959 sp<ANativeWindow> outputANW = mOutputSurface;
960 inputFrame.muxer->stop();
961
962 // Copy the content of the file to memory.
963 sp<GraphicBuffer> gb = GraphicBuffer::from(inputFrame.anb);
964 void* dstBuffer;
965 auto res = gb->lockAsync(GRALLOC_USAGE_SW_WRITE_OFTEN, &dstBuffer, inputFrame.fenceFd);
966 if (res != OK) {
967 ALOGE("%s: Error trying to lock output buffer fence: %s (%d)", __FUNCTION__,
968 strerror(-res), res);
969 return res;
970 }
971
972 off_t fSize = lseek(inputFrame.fileFd, 0, SEEK_END);
973 if (static_cast<size_t>(fSize) > mMaxHeicBufferSize - sizeof(CameraBlob)) {
974 ALOGE("%s: Error: MediaMuxer output size %ld is larger than buffer sizer %zu",
975 __FUNCTION__, fSize, mMaxHeicBufferSize - sizeof(CameraBlob));
976 return BAD_VALUE;
977 }
978
979 lseek(inputFrame.fileFd, 0, SEEK_SET);
980 ssize_t bytesRead = read(inputFrame.fileFd, dstBuffer, fSize);
981 if (bytesRead < fSize) {
982 ALOGE("%s: Only %zd of %ld bytes read", __FUNCTION__, bytesRead, fSize);
983 return BAD_VALUE;
984 }
985
986 close(inputFrame.fileFd);
987 inputFrame.fileFd = -1;
988
989 // Fill in HEIC header
990 uint8_t *header = static_cast<uint8_t*>(dstBuffer) + mMaxHeicBufferSize - sizeof(CameraBlob);
991 struct CameraBlob *blobHeader = (struct CameraBlob *)header;
992 // Must be in sync with CAMERA3_HEIC_BLOB_ID in android_media_Utils.cpp
993 blobHeader->blobId = static_cast<CameraBlobId>(0x00FE);
994 blobHeader->blobSize = fSize;
995
996 res = native_window_set_buffers_timestamp(mOutputSurface.get(), timestamp);
997 if (res != OK) {
998 ALOGE("%s: Stream %d: Error setting timestamp: %s (%d)",
999 __FUNCTION__, getStreamId(), strerror(-res), res);
1000 return res;
1001 }
1002
1003 res = outputANW->queueBuffer(mOutputSurface.get(), inputFrame.anb, /*fence*/ -1);
1004 if (res != OK) {
1005 ALOGE("%s: Failed to queueBuffer to Heic stream: %s (%d)", __FUNCTION__,
1006 strerror(-res), res);
1007 return res;
1008 }
1009 inputFrame.anb = nullptr;
1010
1011 return OK;
1012}
1013
1014
1015void HeicCompositeStream::releaseInputFrameLocked(InputFrame *inputFrame /*out*/) {
1016 if (inputFrame == nullptr) {
1017 return;
1018 }
1019
1020 if (inputFrame->appSegmentBuffer.data != nullptr) {
1021 mAppSegmentConsumer->unlockBuffer(inputFrame->appSegmentBuffer);
1022 inputFrame->appSegmentBuffer.data = nullptr;
1023 mAppSegmentBufferAcquired = false;
1024 }
1025
1026 while (!inputFrame->codecOutputBuffers.empty()) {
1027 auto it = inputFrame->codecOutputBuffers.begin();
1028 ALOGV("%s: releaseOutputBuffer index %d", __FUNCTION__, it->index);
1029 mCodec->releaseOutputBuffer(it->index);
1030 inputFrame->codecOutputBuffers.erase(it);
1031 }
1032
1033 if (inputFrame->yuvBuffer.data != nullptr) {
1034 mMainImageConsumer->unlockBuffer(inputFrame->yuvBuffer);
1035 inputFrame->yuvBuffer.data = nullptr;
1036 mYuvBufferAcquired = false;
1037 }
1038
1039 while (!inputFrame->codecInputBuffers.empty()) {
1040 auto it = inputFrame->codecInputBuffers.begin();
1041 inputFrame->codecInputBuffers.erase(it);
1042 }
1043
1044 if ((inputFrame->error || mErrorState) && !inputFrame->errorNotified) {
1045 notifyError(inputFrame->frameNumber);
1046 inputFrame->errorNotified = true;
1047 }
1048
1049 if (inputFrame->fileFd >= 0) {
1050 close(inputFrame->fileFd);
1051 inputFrame->fileFd = -1;
1052 }
1053
1054 if (inputFrame->anb != nullptr) {
1055 sp<ANativeWindow> outputANW = mOutputSurface;
1056 outputANW->cancelBuffer(mOutputSurface.get(), inputFrame->anb, /*fence*/ -1);
1057 inputFrame->anb = nullptr;
1058 }
1059}
1060
1061void HeicCompositeStream::releaseInputFramesLocked(int64_t currentTs) {
1062 auto it = mPendingInputFrames.begin();
1063 while (it != mPendingInputFrames.end()) {
1064 if (it->first <= currentTs) {
1065 releaseInputFrameLocked(&it->second);
1066 it = mPendingInputFrames.erase(it);
1067 } else {
1068 it++;
1069 }
1070 }
1071}
1072
1073status_t HeicCompositeStream::initializeCodec(uint32_t width, uint32_t height,
1074 const sp<CameraDeviceBase>& cameraDevice) {
1075 ALOGV("%s", __FUNCTION__);
1076
1077 bool useGrid = false;
1078 bool isSizeSupported = isSizeSupportedByHeifEncoder(width, height,
1079 &mUseHeic, &useGrid, nullptr);
1080 if (!isSizeSupported) {
1081 ALOGE("%s: Encoder doesnt' support size %u x %u!",
1082 __FUNCTION__, width, height);
1083 return BAD_VALUE;
1084 }
1085
1086 // Create Looper for MediaCodec.
1087 auto desiredMime = mUseHeic ? MIMETYPE_IMAGE_ANDROID_HEIC : MIMETYPE_VIDEO_HEVC;
1088 mCodecLooper = new ALooper;
1089 mCodecLooper->setName("Camera3-HeicComposite-MediaCodecLooper");
1090 status_t res = mCodecLooper->start(
1091 false, // runOnCallingThread
1092 false, // canCallJava
1093 PRIORITY_AUDIO);
1094 if (res != OK) {
1095 ALOGE("%s: Failed to start codec looper: %s (%d)",
1096 __FUNCTION__, strerror(-res), res);
1097 return NO_INIT;
1098 }
1099
1100 // Create HEIC/HEVC codec.
1101 mCodec = MediaCodec::CreateByType(mCodecLooper, desiredMime, true /*encoder*/);
1102 if (mCodec == nullptr) {
1103 ALOGE("%s: Failed to create codec for %s", __FUNCTION__, desiredMime);
1104 return NO_INIT;
1105 }
1106
1107 // Create Looper and handler for Codec callback.
1108 mCodecCallbackHandler = new CodecCallbackHandler(this);
1109 if (mCodecCallbackHandler == nullptr) {
1110 ALOGE("%s: Failed to create codec callback handler", __FUNCTION__);
1111 return NO_MEMORY;
1112 }
1113 mCallbackLooper = new ALooper;
1114 mCallbackLooper->setName("Camera3-HeicComposite-MediaCodecCallbackLooper");
1115 res = mCallbackLooper->start(
1116 false, // runOnCallingThread
1117 false, // canCallJava
1118 PRIORITY_AUDIO);
1119 if (res != OK) {
1120 ALOGE("%s: Failed to start media callback looper: %s (%d)",
1121 __FUNCTION__, strerror(-res), res);
1122 return NO_INIT;
1123 }
1124 mCallbackLooper->registerHandler(mCodecCallbackHandler);
1125
1126 mAsyncNotify = new AMessage(kWhatCallbackNotify, mCodecCallbackHandler);
1127 res = mCodec->setCallback(mAsyncNotify);
1128 if (res != OK) {
1129 ALOGE("%s: Failed to set MediaCodec callback: %s (%d)", __FUNCTION__,
1130 strerror(-res), res);
1131 return res;
1132 }
1133
1134 // Create output format and configure the Codec.
1135 sp<AMessage> outputFormat = new AMessage();
1136 outputFormat->setString(KEY_MIME, desiredMime);
1137 outputFormat->setInt32(KEY_BITRATE_MODE, BITRATE_MODE_CQ);
1138 outputFormat->setInt32(KEY_QUALITY, kDefaultJpegQuality);
1139 // Ask codec to skip timestamp check and encode all frames.
1140 outputFormat->setInt64("max-pts-gap-to-encoder", kNoFrameDropMaxPtsGap);
1141
1142 int32_t gridWidth, gridHeight, gridRows, gridCols;
1143 if (useGrid || mUseHeic) {
1144 gridWidth = HeicEncoderInfoManager::kGridWidth;
1145 gridHeight = HeicEncoderInfoManager::kGridHeight;
1146 gridRows = (height + gridHeight - 1)/gridHeight;
1147 gridCols = (width + gridWidth - 1)/gridWidth;
1148
1149 if (mUseHeic) {
1150 outputFormat->setInt32(KEY_TILE_WIDTH, gridWidth);
1151 outputFormat->setInt32(KEY_TILE_HEIGHT, gridHeight);
1152 outputFormat->setInt32(KEY_GRID_COLUMNS, gridCols);
1153 outputFormat->setInt32(KEY_GRID_ROWS, gridRows);
1154 }
1155
1156 } else {
1157 gridWidth = width;
1158 gridHeight = height;
1159 gridRows = 1;
1160 gridCols = 1;
1161 }
1162
1163 outputFormat->setInt32(KEY_WIDTH, !useGrid ? width : gridWidth);
1164 outputFormat->setInt32(KEY_HEIGHT, !useGrid ? height : gridHeight);
1165 outputFormat->setInt32(KEY_I_FRAME_INTERVAL, 0);
1166 outputFormat->setInt32(KEY_COLOR_FORMAT,
1167 useGrid ? COLOR_FormatYUV420Flexible : COLOR_FormatSurface);
1168 outputFormat->setInt32(KEY_FRAME_RATE, gridRows * gridCols);
1169 // This only serves as a hint to encoder when encoding is not real-time.
1170 outputFormat->setInt32(KEY_OPERATING_RATE, useGrid ? kGridOpRate : kNoGridOpRate);
1171
1172 res = mCodec->configure(outputFormat, nullptr /*nativeWindow*/,
1173 nullptr /*crypto*/, CONFIGURE_FLAG_ENCODE);
1174 if (res != OK) {
1175 ALOGE("%s: Failed to configure codec: %s (%d)", __FUNCTION__,
1176 strerror(-res), res);
1177 return res;
1178 }
1179
1180 mGridWidth = gridWidth;
1181 mGridHeight = gridHeight;
1182 mGridRows = gridRows;
1183 mGridCols = gridCols;
1184 mUseGrid = useGrid;
1185 mOutputWidth = width;
1186 mOutputHeight = height;
1187 mAppSegmentMaxSize = calcAppSegmentMaxSize(cameraDevice->info());
1188 mMaxHeicBufferSize = mOutputWidth * mOutputHeight * 3 / 2 + mAppSegmentMaxSize;
1189
1190 return OK;
1191}
1192
1193void HeicCompositeStream::deinitCodec() {
1194 ALOGV("%s", __FUNCTION__);
1195 if (mCodec != nullptr) {
1196 mCodec->stop();
1197 mCodec->release();
1198 mCodec.clear();
1199 }
1200
1201 if (mCodecLooper != nullptr) {
1202 mCodecLooper->stop();
1203 mCodecLooper.clear();
1204 }
1205
1206 if (mCallbackLooper != nullptr) {
1207 mCallbackLooper->stop();
1208 mCallbackLooper.clear();
1209 }
1210
1211 mAsyncNotify.clear();
1212 mFormat.clear();
1213}
1214
1215// Return the size of the complete list of app segment, 0 indicates failure
1216size_t HeicCompositeStream::findAppSegmentsSize(const uint8_t* appSegmentBuffer,
1217 size_t maxSize, size_t *app1SegmentSize) {
1218 if (appSegmentBuffer == nullptr || app1SegmentSize == nullptr) {
1219 ALOGE("%s: Invalid input appSegmentBuffer %p, app1SegmentSize %p",
1220 __FUNCTION__, appSegmentBuffer, app1SegmentSize);
1221 return 0;
1222 }
1223
1224 size_t expectedSize = 0;
1225 // First check for EXIF transport header at the end of the buffer
1226 const uint8_t *header = appSegmentBuffer + (maxSize - sizeof(struct CameraBlob));
1227 const struct CameraBlob *blob = (const struct CameraBlob*)(header);
1228 if (blob->blobId != CameraBlobId::JPEG_APP_SEGMENTS) {
1229 ALOGE("%s: Invalid EXIF blobId %hu", __FUNCTION__, blob->blobId);
1230 return 0;
1231 }
1232
1233 expectedSize = blob->blobSize;
1234 if (expectedSize == 0 || expectedSize > maxSize - sizeof(struct CameraBlob)) {
1235 ALOGE("%s: Invalid blobSize %zu.", __FUNCTION__, expectedSize);
1236 return 0;
1237 }
1238
1239 uint32_t totalSize = 0;
1240
1241 // Verify APP1 marker (mandatory)
1242 uint8_t app1Marker[] = {0xFF, 0xE1};
1243 if (memcmp(appSegmentBuffer, app1Marker, sizeof(app1Marker))) {
1244 ALOGE("%s: Invalid APP1 marker: %x, %x", __FUNCTION__,
1245 appSegmentBuffer[0], appSegmentBuffer[1]);
1246 return 0;
1247 }
1248 totalSize += sizeof(app1Marker);
1249
1250 uint16_t app1Size = (static_cast<uint16_t>(appSegmentBuffer[totalSize]) << 8) +
1251 appSegmentBuffer[totalSize+1];
1252 totalSize += app1Size;
1253
1254 ALOGV("%s: Expected APP segments size %zu, APP1 segment size %u",
1255 __FUNCTION__, expectedSize, app1Size);
1256 while (totalSize < expectedSize) {
1257 if (appSegmentBuffer[totalSize] != 0xFF ||
1258 appSegmentBuffer[totalSize+1] <= 0xE1 ||
1259 appSegmentBuffer[totalSize+1] > 0xEF) {
1260 // Invalid APPn marker
1261 ALOGE("%s: Invalid APPn marker: %x, %x", __FUNCTION__,
1262 appSegmentBuffer[totalSize], appSegmentBuffer[totalSize+1]);
1263 return 0;
1264 }
1265 totalSize += 2;
1266
1267 uint16_t appnSize = (static_cast<uint16_t>(appSegmentBuffer[totalSize]) << 8) +
1268 appSegmentBuffer[totalSize+1];
1269 totalSize += appnSize;
1270 }
1271
1272 if (totalSize != expectedSize) {
1273 ALOGE("%s: Invalid JPEG APP segments: totalSize %u vs expected size %zu",
1274 __FUNCTION__, totalSize, expectedSize);
1275 return 0;
1276 }
1277
1278 *app1SegmentSize = app1Size + sizeof(app1Marker);
1279 return expectedSize;
1280}
1281
1282int64_t HeicCompositeStream::findTimestampInNsLocked(int64_t timeInUs) {
1283 for (const auto& fn : mFrameNumberMap) {
1284 if (timeInUs == ns2us(fn.second)) {
1285 return fn.second;
1286 }
1287 }
1288 for (const auto& inputFrame : mPendingInputFrames) {
1289 if (timeInUs == ns2us(inputFrame.first)) {
1290 return inputFrame.first;
1291 }
1292 }
1293 return -1;
1294}
1295
1296status_t HeicCompositeStream::copyOneYuvTile(sp<MediaCodecBuffer>& codecBuffer,
1297 const CpuConsumer::LockedBuffer& yuvBuffer,
1298 size_t top, size_t left, size_t width, size_t height) {
1299 ATRACE_CALL();
1300
1301 // Get stride information for codecBuffer
1302 sp<ABuffer> imageData;
1303 if (!codecBuffer->meta()->findBuffer("image-data", &imageData)) {
1304 ALOGE("%s: Codec input buffer is not for image data!", __FUNCTION__);
1305 return BAD_VALUE;
1306 }
1307 if (imageData->size() != sizeof(MediaImage2)) {
1308 ALOGE("%s: Invalid codec input image size %zu, expected %zu",
1309 __FUNCTION__, imageData->size(), sizeof(MediaImage2));
1310 return BAD_VALUE;
1311 }
1312 MediaImage2* imageInfo = reinterpret_cast<MediaImage2*>(imageData->data());
1313 if (imageInfo->mType != MediaImage2::MEDIA_IMAGE_TYPE_YUV ||
1314 imageInfo->mBitDepth != 8 ||
1315 imageInfo->mBitDepthAllocated != 8 ||
1316 imageInfo->mNumPlanes != 3) {
1317 ALOGE("%s: Invalid codec input image info: mType %d, mBitDepth %d, "
1318 "mBitDepthAllocated %d, mNumPlanes %d!", __FUNCTION__,
1319 imageInfo->mType, imageInfo->mBitDepth,
1320 imageInfo->mBitDepthAllocated, imageInfo->mNumPlanes);
1321 return BAD_VALUE;
1322 }
1323
1324 ALOGV("%s: yuvBuffer chromaStep %d, chromaStride %d",
1325 __FUNCTION__, yuvBuffer.chromaStep, yuvBuffer.chromaStride);
1326 ALOGV("%s: U offset %u, V offset %u, U rowInc %d, V rowInc %d, U colInc %d, V colInc %d",
1327 __FUNCTION__, imageInfo->mPlane[MediaImage2::U].mOffset,
1328 imageInfo->mPlane[MediaImage2::V].mOffset,
1329 imageInfo->mPlane[MediaImage2::U].mRowInc,
1330 imageInfo->mPlane[MediaImage2::V].mRowInc,
1331 imageInfo->mPlane[MediaImage2::U].mColInc,
1332 imageInfo->mPlane[MediaImage2::V].mColInc);
1333
1334 // Y
1335 for (auto row = top; row < top+height; row++) {
1336 uint8_t *dst = codecBuffer->data() + imageInfo->mPlane[MediaImage2::Y].mOffset +
1337 imageInfo->mPlane[MediaImage2::Y].mRowInc * (row - top);
1338 memcpy(dst, yuvBuffer.data+row*yuvBuffer.stride+left, width);
1339 }
1340
1341 // U is Cb, V is Cr
1342 bool codecUPlaneFirst = imageInfo->mPlane[MediaImage2::V].mOffset >
1343 imageInfo->mPlane[MediaImage2::U].mOffset;
1344 uint32_t codecUvOffsetDiff = codecUPlaneFirst ?
1345 imageInfo->mPlane[MediaImage2::V].mOffset - imageInfo->mPlane[MediaImage2::U].mOffset :
1346 imageInfo->mPlane[MediaImage2::U].mOffset - imageInfo->mPlane[MediaImage2::V].mOffset;
1347 bool isCodecUvSemiplannar = (codecUvOffsetDiff == 1) &&
1348 (imageInfo->mPlane[MediaImage2::U].mRowInc ==
1349 imageInfo->mPlane[MediaImage2::V].mRowInc) &&
1350 (imageInfo->mPlane[MediaImage2::U].mColInc == 2) &&
1351 (imageInfo->mPlane[MediaImage2::V].mColInc == 2);
1352 bool isCodecUvPlannar =
1353 ((codecUPlaneFirst && codecUvOffsetDiff >=
1354 imageInfo->mPlane[MediaImage2::U].mRowInc * imageInfo->mHeight/2) ||
1355 ((!codecUPlaneFirst && codecUvOffsetDiff >=
1356 imageInfo->mPlane[MediaImage2::V].mRowInc * imageInfo->mHeight/2))) &&
1357 imageInfo->mPlane[MediaImage2::U].mColInc == 1 &&
1358 imageInfo->mPlane[MediaImage2::V].mColInc == 1;
1359 bool cameraUPlaneFirst = yuvBuffer.dataCr > yuvBuffer.dataCb;
1360
1361 if (isCodecUvSemiplannar && yuvBuffer.chromaStep == 2 &&
1362 (codecUPlaneFirst == cameraUPlaneFirst)) {
1363 // UV semiplannar
1364 // The chrome plane could be either Cb first, or Cr first. Take the
1365 // smaller address.
1366 uint8_t *src = std::min(yuvBuffer.dataCb, yuvBuffer.dataCr);
1367 MediaImage2::PlaneIndex dstPlane = codecUvOffsetDiff > 0 ? MediaImage2::U : MediaImage2::V;
1368 for (auto row = top/2; row < (top+height)/2; row++) {
1369 uint8_t *dst = codecBuffer->data() + imageInfo->mPlane[dstPlane].mOffset +
1370 imageInfo->mPlane[dstPlane].mRowInc * (row - top/2);
1371 memcpy(dst, src+row*yuvBuffer.chromaStride+left, width);
1372 }
1373 } else if (isCodecUvPlannar && yuvBuffer.chromaStep == 1) {
1374 // U plane
1375 for (auto row = top/2; row < (top+height)/2; row++) {
1376 uint8_t *dst = codecBuffer->data() + imageInfo->mPlane[MediaImage2::U].mOffset +
1377 imageInfo->mPlane[MediaImage2::U].mRowInc * (row - top/2);
1378 memcpy(dst, yuvBuffer.dataCb+row*yuvBuffer.chromaStride+left/2, width/2);
1379 }
1380
1381 // V plane
1382 for (auto row = top/2; row < (top+height)/2; row++) {
1383 uint8_t *dst = codecBuffer->data() + imageInfo->mPlane[MediaImage2::V].mOffset +
1384 imageInfo->mPlane[MediaImage2::V].mRowInc * (row - top/2);
1385 memcpy(dst, yuvBuffer.dataCr+row*yuvBuffer.chromaStride+left/2, width/2);
1386 }
1387 } else {
1388 // Convert between semiplannar and plannar
1389 uint8_t *dst = codecBuffer->data();
1390 for (auto row = top/2; row < (top+height)/2; row++) {
1391 for (auto col = left/2; col < (left+width)/2; col++) {
1392 // U/Cb
1393 int32_t dstIndex = imageInfo->mPlane[MediaImage2::U].mOffset +
1394 imageInfo->mPlane[MediaImage2::U].mRowInc * (row - top/2) +
1395 imageInfo->mPlane[MediaImage2::U].mColInc * (col - left/2);
1396 int32_t srcIndex = row * yuvBuffer.chromaStride + yuvBuffer.chromaStep * col;
1397 dst[dstIndex] = yuvBuffer.dataCb[srcIndex];
1398
1399 // V/Cr
1400 dstIndex = imageInfo->mPlane[MediaImage2::V].mOffset +
1401 imageInfo->mPlane[MediaImage2::V].mRowInc * (row - top/2) +
1402 imageInfo->mPlane[MediaImage2::V].mColInc * (col - left/2);
1403 srcIndex = row * yuvBuffer.chromaStride + yuvBuffer.chromaStep * col;
1404 dst[dstIndex] = yuvBuffer.dataCr[srcIndex];
1405 }
1406 }
1407 }
1408 return OK;
1409}
1410
1411size_t HeicCompositeStream::calcAppSegmentMaxSize(const CameraMetadata& info) {
1412 camera_metadata_ro_entry_t entry = info.find(ANDROID_HEIC_INFO_MAX_JPEG_APP_SEGMENTS_COUNT);
1413 size_t maxAppsSegment = 1;
1414 if (entry.count > 0) {
1415 maxAppsSegment = entry.data.u8[0] < 1 ? 1 :
1416 entry.data.u8[0] > 16 ? 16 : entry.data.u8[0];
1417 }
1418 return maxAppsSegment * (2 + 0xFFFF) + sizeof(struct CameraBlob);
1419}
1420
1421bool HeicCompositeStream::threadLoop() {
1422 int64_t currentTs = INT64_MAX;
1423 bool newInputAvailable = false;
1424
1425 {
1426 Mutex::Autolock l(mMutex);
1427 if (mErrorState) {
1428 // In case we landed in error state, return any pending buffers and
1429 // halt all further processing.
1430 compilePendingInputLocked();
1431 releaseInputFramesLocked(currentTs);
1432 return false;
1433 }
1434
1435
1436 while (!newInputAvailable) {
1437 compilePendingInputLocked();
1438 newInputAvailable = getNextReadyInputLocked(&currentTs);
1439
1440 if (!newInputAvailable) {
1441 auto failingFrameNumber = getNextFailingInputLocked(&currentTs);
1442 if (failingFrameNumber >= 0) {
1443 // We cannot erase 'mPendingInputFrames[currentTs]' at this point because it is
1444 // possible for two internal stream buffers to fail. In such scenario the
1445 // composite stream should notify the client about a stream buffer error only
1446 // once and this information is kept within 'errorNotified'.
1447 // Any present failed input frames will be removed on a subsequent call to
1448 // 'releaseInputFramesLocked()'.
1449 releaseInputFrameLocked(&mPendingInputFrames[currentTs]);
1450 currentTs = INT64_MAX;
1451 }
1452
1453 auto ret = mInputReadyCondition.waitRelative(mMutex, kWaitDuration);
1454 if (ret == TIMED_OUT) {
1455 return true;
1456 } else if (ret != OK) {
1457 ALOGE("%s: Timed wait on condition failed: %s (%d)", __FUNCTION__,
1458 strerror(-ret), ret);
1459 return false;
1460 }
1461 }
1462 }
1463 }
1464
1465 auto res = processInputFrame(currentTs, mPendingInputFrames[currentTs]);
1466 Mutex::Autolock l(mMutex);
1467 if (res != OK) {
1468 ALOGE("%s: Failed processing frame with timestamp: %" PRIu64 ": %s (%d)",
1469 __FUNCTION__, currentTs, strerror(-res), res);
1470 mPendingInputFrames[currentTs].error = true;
1471 }
1472
1473 if (mPendingInputFrames[currentTs].error ||
1474 (mPendingInputFrames[currentTs].appSegmentWritten &&
1475 mPendingInputFrames[currentTs].pendingOutputTiles == 0)) {
1476 releaseInputFramesLocked(currentTs);
1477 }
1478
1479 return true;
1480}
1481
1482bool HeicCompositeStream::onStreamBufferError(const CaptureResultExtras& resultExtras) {
1483 bool res = false;
1484 // Buffer errors concerning internal composite streams should not be directly visible to
1485 // camera clients. They must only receive a single buffer error with the public composite
1486 // stream id.
1487 if ((resultExtras.errorStreamId == mAppSegmentStreamId) ||
1488 (resultExtras.errorStreamId == mMainImageStreamId)) {
1489 flagAnErrorFrameNumber(resultExtras.frameNumber);
1490 res = true;
1491 }
1492
1493 return res;
1494}
1495
1496void HeicCompositeStream::CodecCallbackHandler::onMessageReceived(const sp<AMessage> &msg) {
1497 sp<HeicCompositeStream> parent = mParent.promote();
1498 if (parent == nullptr) return;
1499
1500 switch (msg->what()) {
1501 case kWhatCallbackNotify: {
1502 int32_t cbID;
1503 if (!msg->findInt32("callbackID", &cbID)) {
1504 ALOGE("kWhatCallbackNotify: callbackID is expected.");
1505 break;
1506 }
1507
1508 ALOGV("kWhatCallbackNotify: cbID = %d", cbID);
1509
1510 switch (cbID) {
1511 case MediaCodec::CB_INPUT_AVAILABLE: {
1512 int32_t index;
1513 if (!msg->findInt32("index", &index)) {
1514 ALOGE("CB_INPUT_AVAILABLE: index is expected.");
1515 break;
1516 }
1517 parent->onHeicInputFrameAvailable(index);
1518 break;
1519 }
1520
1521 case MediaCodec::CB_OUTPUT_AVAILABLE: {
1522 int32_t index;
1523 size_t offset;
1524 size_t size;
1525 int64_t timeUs;
1526 int32_t flags;
1527
1528 if (!msg->findInt32("index", &index)) {
1529 ALOGE("CB_OUTPUT_AVAILABLE: index is expected.");
1530 break;
1531 }
1532 if (!msg->findSize("offset", &offset)) {
1533 ALOGE("CB_OUTPUT_AVAILABLE: offset is expected.");
1534 break;
1535 }
1536 if (!msg->findSize("size", &size)) {
1537 ALOGE("CB_OUTPUT_AVAILABLE: size is expected.");
1538 break;
1539 }
1540 if (!msg->findInt64("timeUs", &timeUs)) {
1541 ALOGE("CB_OUTPUT_AVAILABLE: timeUs is expected.");
1542 break;
1543 }
1544 if (!msg->findInt32("flags", &flags)) {
1545 ALOGE("CB_OUTPUT_AVAILABLE: flags is expected.");
1546 break;
1547 }
1548
1549 CodecOutputBufferInfo bufferInfo = {
1550 index,
1551 (int32_t)offset,
1552 (int32_t)size,
1553 timeUs,
1554 (uint32_t)flags};
1555
1556 parent->onHeicOutputFrameAvailable(bufferInfo);
1557 break;
1558 }
1559
1560 case MediaCodec::CB_OUTPUT_FORMAT_CHANGED: {
1561 sp<AMessage> format;
1562 if (!msg->findMessage("format", &format)) {
1563 ALOGE("CB_OUTPUT_FORMAT_CHANGED: format is expected.");
1564 break;
1565 }
1566
1567 parent->onHeicFormatChanged(format);
1568 break;
1569 }
1570
1571 case MediaCodec::CB_ERROR: {
1572 status_t err;
1573 int32_t actionCode;
1574 AString detail;
1575 if (!msg->findInt32("err", &err)) {
1576 ALOGE("CB_ERROR: err is expected.");
1577 break;
1578 }
1579 if (!msg->findInt32("action", &actionCode)) {
1580 ALOGE("CB_ERROR: action is expected.");
1581 break;
1582 }
1583 msg->findString("detail", &detail);
1584 ALOGE("Codec reported error(0x%x), actionCode(%d), detail(%s)",
1585 err, actionCode, detail.c_str());
1586
1587 parent->onHeicCodecError();
1588 break;
1589 }
1590
1591 default: {
1592 ALOGE("kWhatCallbackNotify: callbackID(%d) is unexpected.", cbID);
1593 break;
1594 }
1595 }
1596 break;
1597 }
1598
1599 default:
1600 ALOGE("shouldn't be here");
1601 break;
1602 }
1603}
1604
1605}; // namespace camera3
1606}; // namespace android