blob: 0feded269491a46b9ecbe1a2f429db353d004c1d [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
Susmitha Gummallae911f2e2020-11-23 09:57:03 -080019#define ALIGN(x, mask) ( ((x) + (mask) - 1) & ~((mask) - 1) )
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -080020//#define LOG_NDEBUG 0
21
22#include <linux/memfd.h>
23#include <pthread.h>
24#include <sys/syscall.h>
25
Jayant Chowdharyc67af1b2022-04-07 18:05:04 +000026#include <aidl/android/hardware/camera/device/CameraBlob.h>
27#include <aidl/android/hardware/camera/device/CameraBlobId.h>
Shuzhen Wang219c2992019-02-15 17:24:28 -080028#include <libyuv.h>
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -080029#include <gui/Surface.h>
30#include <utils/Log.h>
31#include <utils/Trace.h>
32
Marco Nelissen13aa1a42019-09-27 10:21:55 -070033#include <mediadrm/ICrypto.h>
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -080034#include <media/MediaCodecBuffer.h>
35#include <media/stagefright/foundation/ABuffer.h>
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -080036#include <media/stagefright/foundation/MediaDefs.h>
37#include <media/stagefright/MediaCodecConstants.h>
38
39#include "common/CameraDeviceBase.h"
40#include "utils/ExifUtils.h"
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -080041#include "utils/SessionConfigurationUtils.h"
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -080042#include "HeicEncoderInfoManager.h"
43#include "HeicCompositeStream.h"
44
Jayant Chowdharyc67af1b2022-04-07 18:05:04 +000045using aidl::android::hardware::camera::device::CameraBlob;
46using aidl::android::hardware::camera::device::CameraBlobId;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -080047
48namespace android {
49namespace camera3 {
50
Shuzhen Wange8675782019-12-05 09:12:14 -080051HeicCompositeStream::HeicCompositeStream(sp<CameraDeviceBase> device,
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -080052 wp<hardware::camera2::ICameraDeviceCallbacks> cb) :
53 CompositeStream(device, cb),
54 mUseHeic(false),
55 mNumOutputTiles(1),
56 mOutputWidth(0),
57 mOutputHeight(0),
58 mMaxHeicBufferSize(0),
59 mGridWidth(HeicEncoderInfoManager::kGridWidth),
60 mGridHeight(HeicEncoderInfoManager::kGridHeight),
61 mGridRows(1),
62 mGridCols(1),
63 mUseGrid(false),
64 mAppSegmentStreamId(-1),
65 mAppSegmentSurfaceId(-1),
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -080066 mMainImageStreamId(-1),
67 mMainImageSurfaceId(-1),
68 mYuvBufferAcquired(false),
69 mProducerListener(new ProducerListener()),
Shuzhen Wang3d00ee52019-09-25 14:19:28 -070070 mDequeuedOutputBufferCnt(0),
71 mCodecOutputCounter(0),
Shuzhen Wang62f49ed2019-09-04 14:07:53 -070072 mQuality(-1),
Shuzhen Wange8675782019-12-05 09:12:14 -080073 mGridTimestampUs(0),
74 mStatusId(StatusTracker::NO_STATUS_ID) {
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -080075}
76
77HeicCompositeStream::~HeicCompositeStream() {
78 // Call deinitCodec in case stream hasn't been deleted yet to avoid any
79 // memory/resource leak.
80 deinitCodec();
81
82 mInputAppSegmentBuffers.clear();
83 mCodecOutputBuffers.clear();
84
85 mAppSegmentStreamId = -1;
86 mAppSegmentSurfaceId = -1;
87 mAppSegmentConsumer.clear();
88 mAppSegmentSurface.clear();
89
90 mMainImageStreamId = -1;
91 mMainImageSurfaceId = -1;
92 mMainImageConsumer.clear();
93 mMainImageSurface.clear();
94}
95
96bool HeicCompositeStream::isHeicCompositeStream(const sp<Surface> &surface) {
97 ANativeWindow *anw = surface.get();
98 status_t err;
99 int format;
100 if ((err = anw->query(anw, NATIVE_WINDOW_FORMAT, &format)) != OK) {
101 String8 msg = String8::format("Failed to query Surface format: %s (%d)", strerror(-err),
102 err);
103 ALOGE("%s: %s", __FUNCTION__, msg.string());
104 return false;
105 }
106
107 int dataspace;
108 if ((err = anw->query(anw, NATIVE_WINDOW_DEFAULT_DATASPACE, &dataspace)) != OK) {
109 String8 msg = String8::format("Failed to query Surface dataspace: %s (%d)", strerror(-err),
110 err);
111 ALOGE("%s: %s", __FUNCTION__, msg.string());
112 return false;
113 }
114
115 return ((format == HAL_PIXEL_FORMAT_BLOB) && (dataspace == HAL_DATASPACE_HEIF));
116}
117
118status_t HeicCompositeStream::createInternalStreams(const std::vector<sp<Surface>>& consumers,
119 bool /*hasDeferredConsumer*/, uint32_t width, uint32_t height, int format,
Emilian Peevf4816702020-04-03 15:44:51 -0700120 camera_stream_rotation_t rotation, int *id, const String8& physicalCameraId,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -0800121 const std::unordered_set<int32_t> &sensorPixelModesUsed,
122 std::vector<int> *surfaceIds,
123 int /*streamSetId*/, bool /*isShared*/) {
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800124
125 sp<CameraDeviceBase> device = mDevice.promote();
126 if (!device.get()) {
127 ALOGE("%s: Invalid camera device!", __FUNCTION__);
128 return NO_INIT;
129 }
130
131 status_t res = initializeCodec(width, height, device);
132 if (res != OK) {
133 ALOGE("%s: Failed to initialize HEIC/HEVC codec: %s (%d)",
134 __FUNCTION__, strerror(-res), res);
135 return NO_INIT;
136 }
137
138 sp<IGraphicBufferProducer> producer;
139 sp<IGraphicBufferConsumer> consumer;
140 BufferQueue::createBufferQueue(&producer, &consumer);
Michael Gonzalezb5986a32019-10-09 15:38:17 -0700141 mAppSegmentConsumer = new CpuConsumer(consumer, kMaxAcquiredAppSegment);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800142 mAppSegmentConsumer->setFrameAvailableListener(this);
143 mAppSegmentConsumer->setName(String8("Camera3-HeicComposite-AppSegmentStream"));
144 mAppSegmentSurface = new Surface(producer);
145
Shuzhen Wange7f4b462019-02-12 08:43:07 -0800146 mStaticInfo = device->info();
147
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800148 res = device->createStream(mAppSegmentSurface, mAppSegmentMaxSize, 1, format,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -0800149 kAppSegmentDataSpace, rotation, &mAppSegmentStreamId, physicalCameraId,
150 sensorPixelModesUsed,surfaceIds);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800151 if (res == OK) {
152 mAppSegmentSurfaceId = (*surfaceIds)[0];
153 } else {
154 ALOGE("%s: Failed to create JPEG App segment stream: %s (%d)", __FUNCTION__,
155 strerror(-res), res);
156 return res;
157 }
158
159 if (!mUseGrid) {
160 res = mCodec->createInputSurface(&producer);
161 if (res != OK) {
162 ALOGE("%s: Failed to create input surface for Heic codec: %s (%d)",
163 __FUNCTION__, strerror(-res), res);
164 return res;
165 }
166 } else {
167 BufferQueue::createBufferQueue(&producer, &consumer);
168 mMainImageConsumer = new CpuConsumer(consumer, 1);
169 mMainImageConsumer->setFrameAvailableListener(this);
170 mMainImageConsumer->setName(String8("Camera3-HeicComposite-HevcInputYUVStream"));
171 }
172 mMainImageSurface = new Surface(producer);
173
174 res = mCodec->start();
175 if (res != OK) {
176 ALOGE("%s: Failed to start codec: %s (%d)", __FUNCTION__,
177 strerror(-res), res);
178 return res;
179 }
180
181 std::vector<int> sourceSurfaceId;
182 //Use YUV_888 format if framework tiling is needed.
183 int srcStreamFmt = mUseGrid ? HAL_PIXEL_FORMAT_YCbCr_420_888 :
184 HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED;
185 res = device->createStream(mMainImageSurface, width, height, srcStreamFmt, kHeifDataSpace,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -0800186 rotation, id, physicalCameraId, sensorPixelModesUsed, &sourceSurfaceId);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800187 if (res == OK) {
188 mMainImageSurfaceId = sourceSurfaceId[0];
189 mMainImageStreamId = *id;
190 } else {
191 ALOGE("%s: Failed to create main image stream: %s (%d)", __FUNCTION__,
192 strerror(-res), res);
193 return res;
194 }
195
196 mOutputSurface = consumers[0];
Shuzhen Wange8675782019-12-05 09:12:14 -0800197 res = registerCompositeStreamListener(mMainImageStreamId);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800198 if (res != OK) {
Shuzhen Wange8675782019-12-05 09:12:14 -0800199 ALOGE("%s: Failed to register HAL main image stream: %s (%d)", __FUNCTION__,
200 strerror(-res), res);
201 return res;
202 }
203
204 res = registerCompositeStreamListener(mAppSegmentStreamId);
205 if (res != OK) {
206 ALOGE("%s: Failed to register HAL app segment stream: %s (%d)", __FUNCTION__,
207 strerror(-res), res);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800208 return res;
209 }
210
Shuzhen Wang219c2992019-02-15 17:24:28 -0800211 initCopyRowFunction(width);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800212 return res;
213}
214
215status_t HeicCompositeStream::deleteInternalStreams() {
216 requestExit();
217 auto res = join();
218 if (res != OK) {
219 ALOGE("%s: Failed to join with the main processing thread: %s (%d)", __FUNCTION__,
220 strerror(-res), res);
221 }
222
223 deinitCodec();
224
225 if (mAppSegmentStreamId >= 0) {
Emilian Peevc0fe54c2020-03-11 14:05:07 -0700226 // Camera devices may not be valid after switching to offline mode.
227 // In this case, all offline streams including internal composite streams
228 // are managed and released by the offline session.
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800229 sp<CameraDeviceBase> device = mDevice.promote();
Emilian Peevc0fe54c2020-03-11 14:05:07 -0700230 if (device.get() != nullptr) {
231 res = device->deleteStream(mAppSegmentStreamId);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800232 }
233
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800234 mAppSegmentStreamId = -1;
235 }
236
Shuzhen Wang2c545042019-02-07 10:27:35 -0800237 if (mOutputSurface != nullptr) {
238 mOutputSurface->disconnect(NATIVE_WINDOW_API_CAMERA);
239 mOutputSurface.clear();
240 }
Shuzhen Wange8675782019-12-05 09:12:14 -0800241
242 sp<StatusTracker> statusTracker = mStatusTracker.promote();
243 if (statusTracker != nullptr && mStatusId != StatusTracker::NO_STATUS_ID) {
244 statusTracker->removeComponent(mStatusId);
245 mStatusId = StatusTracker::NO_STATUS_ID;
246 }
247
248 if (mPendingInputFrames.size() > 0) {
249 ALOGW("%s: mPendingInputFrames has %zu stale entries",
250 __FUNCTION__, mPendingInputFrames.size());
251 mPendingInputFrames.clear();
252 }
253
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800254 return res;
255}
256
257void HeicCompositeStream::onBufferReleased(const BufferInfo& bufferInfo) {
258 Mutex::Autolock l(mMutex);
259
260 if (bufferInfo.mError) return;
261
Shuzhen Wange8675782019-12-05 09:12:14 -0800262 if (bufferInfo.mStreamId == mMainImageStreamId) {
263 mMainImageFrameNumbers.push(bufferInfo.mFrameNumber);
264 mCodecOutputBufferFrameNumbers.push(bufferInfo.mFrameNumber);
265 ALOGV("%s: [%" PRId64 "]: Adding main image frame number (%zu frame numbers in total)",
266 __FUNCTION__, bufferInfo.mFrameNumber, mMainImageFrameNumbers.size());
267 } else if (bufferInfo.mStreamId == mAppSegmentStreamId) {
268 mAppSegmentFrameNumbers.push(bufferInfo.mFrameNumber);
269 ALOGV("%s: [%" PRId64 "]: Adding app segment frame number (%zu frame numbers in total)",
270 __FUNCTION__, bufferInfo.mFrameNumber, mAppSegmentFrameNumbers.size());
271 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800272}
273
274// We need to get the settings early to handle the case where the codec output
275// arrives earlier than result metadata.
276void HeicCompositeStream::onBufferRequestForFrameNumber(uint64_t frameNumber, int streamId,
277 const CameraMetadata& settings) {
278 ATRACE_ASYNC_BEGIN("HEIC capture", frameNumber);
279
280 Mutex::Autolock l(mMutex);
281 if (mErrorState || (streamId != getStreamId())) {
282 return;
283 }
284
285 mPendingCaptureResults.emplace(frameNumber, CameraMetadata());
286
287 camera_metadata_ro_entry entry;
288
289 int32_t orientation = 0;
290 entry = settings.find(ANDROID_JPEG_ORIENTATION);
291 if (entry.count == 1) {
292 orientation = entry.data.i32[0];
293 }
294
295 int32_t quality = kDefaultJpegQuality;
296 entry = settings.find(ANDROID_JPEG_QUALITY);
297 if (entry.count == 1) {
298 quality = entry.data.i32[0];
299 }
300
Shuzhen Wange8675782019-12-05 09:12:14 -0800301 mSettingsByFrameNumber[frameNumber] = {orientation, quality};
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800302}
303
304void HeicCompositeStream::onFrameAvailable(const BufferItem& item) {
305 if (item.mDataSpace == static_cast<android_dataspace>(kAppSegmentDataSpace)) {
306 ALOGV("%s: JPEG APP segments buffer with ts: %" PRIu64 " ms. arrived!",
307 __func__, ns2ms(item.mTimestamp));
308
309 Mutex::Autolock l(mMutex);
310 if (!mErrorState) {
311 mInputAppSegmentBuffers.push_back(item.mTimestamp);
312 mInputReadyCondition.signal();
313 }
314 } else if (item.mDataSpace == kHeifDataSpace) {
315 ALOGV("%s: YUV_888 buffer with ts: %" PRIu64 " ms. arrived!",
316 __func__, ns2ms(item.mTimestamp));
317
318 Mutex::Autolock l(mMutex);
319 if (!mUseGrid) {
320 ALOGE("%s: YUV_888 internal stream is only supported for HEVC tiling",
321 __FUNCTION__);
322 return;
323 }
324 if (!mErrorState) {
325 mInputYuvBuffers.push_back(item.mTimestamp);
326 mInputReadyCondition.signal();
327 }
328 } else {
329 ALOGE("%s: Unexpected data space: 0x%x", __FUNCTION__, item.mDataSpace);
330 }
331}
332
333status_t HeicCompositeStream::getCompositeStreamInfo(const OutputStreamInfo &streamInfo,
334 const CameraMetadata& ch, std::vector<OutputStreamInfo>* compositeOutput /*out*/) {
335 if (compositeOutput == nullptr) {
336 return BAD_VALUE;
337 }
338
339 compositeOutput->clear();
340
341 bool useGrid, useHeic;
342 bool isSizeSupported = isSizeSupportedByHeifEncoder(
343 streamInfo.width, streamInfo.height, &useHeic, &useGrid, nullptr);
344 if (!isSizeSupported) {
345 // Size is not supported by either encoder.
346 return OK;
347 }
348
349 compositeOutput->insert(compositeOutput->end(), 2, streamInfo);
350
351 // JPEG APPS segments Blob stream info
352 (*compositeOutput)[0].width = calcAppSegmentMaxSize(ch);
353 (*compositeOutput)[0].height = 1;
354 (*compositeOutput)[0].format = HAL_PIXEL_FORMAT_BLOB;
355 (*compositeOutput)[0].dataSpace = kAppSegmentDataSpace;
356 (*compositeOutput)[0].consumerUsage = GRALLOC_USAGE_SW_READ_OFTEN;
357
358 // YUV/IMPLEMENTATION_DEFINED stream info
359 (*compositeOutput)[1].width = streamInfo.width;
360 (*compositeOutput)[1].height = streamInfo.height;
361 (*compositeOutput)[1].format = useGrid ? HAL_PIXEL_FORMAT_YCbCr_420_888 :
362 HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED;
363 (*compositeOutput)[1].dataSpace = kHeifDataSpace;
364 (*compositeOutput)[1].consumerUsage = useHeic ? GRALLOC_USAGE_HW_IMAGE_ENCODER :
365 useGrid ? GRALLOC_USAGE_SW_READ_OFTEN : GRALLOC_USAGE_HW_VIDEO_ENCODER;
366
367 return NO_ERROR;
368}
369
370bool HeicCompositeStream::isSizeSupportedByHeifEncoder(int32_t width, int32_t height,
Chong Zhang688abaa2019-05-17 16:32:23 -0700371 bool* useHeic, bool* useGrid, int64_t* stall, AString* hevcName) {
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800372 static HeicEncoderInfoManager& heicManager = HeicEncoderInfoManager::getInstance();
Chong Zhang688abaa2019-05-17 16:32:23 -0700373 return heicManager.isSizeSupported(width, height, useHeic, useGrid, stall, hevcName);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800374}
375
376bool HeicCompositeStream::isInMemoryTempFileSupported() {
377 int memfd = syscall(__NR_memfd_create, "HEIF-try-memfd", MFD_CLOEXEC);
378 if (memfd == -1) {
379 if (errno != ENOSYS) {
380 ALOGE("%s: Failed to create tmpfs file. errno %d", __FUNCTION__, errno);
381 }
382 return false;
383 }
384 close(memfd);
385 return true;
386}
387
388void HeicCompositeStream::onHeicOutputFrameAvailable(
389 const CodecOutputBufferInfo& outputBufferInfo) {
390 Mutex::Autolock l(mMutex);
391
392 ALOGV("%s: index %d, offset %d, size %d, time %" PRId64 ", flags 0x%x",
393 __FUNCTION__, outputBufferInfo.index, outputBufferInfo.offset,
394 outputBufferInfo.size, outputBufferInfo.timeUs, outputBufferInfo.flags);
395
396 if (!mErrorState) {
397 if ((outputBufferInfo.size > 0) &&
398 ((outputBufferInfo.flags & MediaCodec::BUFFER_FLAG_CODECCONFIG) == 0)) {
399 mCodecOutputBuffers.push_back(outputBufferInfo);
400 mInputReadyCondition.signal();
401 } else {
Shuzhen Wang3d00ee52019-09-25 14:19:28 -0700402 ALOGV("%s: Releasing output buffer: size %d flags: 0x%x ", __FUNCTION__,
403 outputBufferInfo.size, outputBufferInfo.flags);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800404 mCodec->releaseOutputBuffer(outputBufferInfo.index);
405 }
406 } else {
407 mCodec->releaseOutputBuffer(outputBufferInfo.index);
408 }
409}
410
411void HeicCompositeStream::onHeicInputFrameAvailable(int32_t index) {
412 Mutex::Autolock l(mMutex);
413
414 if (!mUseGrid) {
415 ALOGE("%s: Codec YUV input mode must only be used for Hevc tiling mode", __FUNCTION__);
416 return;
417 }
418
419 mCodecInputBuffers.push_back(index);
420 mInputReadyCondition.signal();
421}
422
423void HeicCompositeStream::onHeicFormatChanged(sp<AMessage>& newFormat) {
424 if (newFormat == nullptr) {
425 ALOGE("%s: newFormat must not be null!", __FUNCTION__);
426 return;
427 }
428
429 Mutex::Autolock l(mMutex);
430
431 AString mime;
432 AString mimeHeic(MIMETYPE_IMAGE_ANDROID_HEIC);
433 newFormat->findString(KEY_MIME, &mime);
434 if (mime != mimeHeic) {
435 // For HEVC codec, below keys need to be filled out or overwritten so that the
436 // muxer can handle them as HEIC output image.
437 newFormat->setString(KEY_MIME, mimeHeic);
438 newFormat->setInt32(KEY_WIDTH, mOutputWidth);
439 newFormat->setInt32(KEY_HEIGHT, mOutputHeight);
Shuzhen Wang1403d952023-07-31 20:42:19 +0000440 }
441
442 if (mUseGrid || mUseHeic) {
443 int32_t gridRows, gridCols, tileWidth, tileHeight;
444 if (newFormat->findInt32(KEY_GRID_ROWS, &gridRows) &&
445 newFormat->findInt32(KEY_GRID_COLUMNS, &gridCols) &&
446 newFormat->findInt32(KEY_TILE_WIDTH, &tileWidth) &&
447 newFormat->findInt32(KEY_TILE_HEIGHT, &tileHeight)) {
448 mGridWidth = tileWidth;
449 mGridHeight = tileHeight;
450 mGridRows = gridRows;
451 mGridCols = gridCols;
452 } else {
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800453 newFormat->setInt32(KEY_TILE_WIDTH, mGridWidth);
454 newFormat->setInt32(KEY_TILE_HEIGHT, mGridHeight);
455 newFormat->setInt32(KEY_GRID_ROWS, mGridRows);
456 newFormat->setInt32(KEY_GRID_COLUMNS, mGridCols);
Shuzhen Wang1403d952023-07-31 20:42:19 +0000457 }
458 int32_t left, top, right, bottom;
459 if (newFormat->findRect("crop", &left, &top, &right, &bottom)) {
460 newFormat->setRect("crop", 0, 0, mOutputWidth - 1, mOutputHeight - 1);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800461 }
462 }
463 newFormat->setInt32(KEY_IS_DEFAULT, 1 /*isPrimary*/);
464
465 int32_t gridRows, gridCols;
466 if (newFormat->findInt32(KEY_GRID_ROWS, &gridRows) &&
467 newFormat->findInt32(KEY_GRID_COLUMNS, &gridCols)) {
468 mNumOutputTiles = gridRows * gridCols;
469 } else {
470 mNumOutputTiles = 1;
471 }
472
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800473 mFormat = newFormat;
Shuzhen Wang3d00ee52019-09-25 14:19:28 -0700474
475 ALOGV("%s: mNumOutputTiles is %zu", __FUNCTION__, mNumOutputTiles);
476 mInputReadyCondition.signal();
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800477}
478
479void HeicCompositeStream::onHeicCodecError() {
480 Mutex::Autolock l(mMutex);
481 mErrorState = true;
482}
483
484status_t HeicCompositeStream::configureStream() {
485 if (isRunning()) {
486 // Processing thread is already running, nothing more to do.
487 return NO_ERROR;
488 }
489
490 if (mOutputSurface.get() == nullptr) {
491 ALOGE("%s: No valid output surface set!", __FUNCTION__);
492 return NO_INIT;
493 }
494
495 auto res = mOutputSurface->connect(NATIVE_WINDOW_API_CAMERA, mProducerListener);
496 if (res != OK) {
497 ALOGE("%s: Unable to connect to native window for stream %d",
498 __FUNCTION__, mMainImageStreamId);
499 return res;
500 }
501
502 if ((res = native_window_set_buffers_format(mOutputSurface.get(), HAL_PIXEL_FORMAT_BLOB))
503 != OK) {
504 ALOGE("%s: Unable to configure stream buffer format for stream %d", __FUNCTION__,
505 mMainImageStreamId);
506 return res;
507 }
508
509 ANativeWindow *anwConsumer = mOutputSurface.get();
510 int maxConsumerBuffers;
511 if ((res = anwConsumer->query(anwConsumer, NATIVE_WINDOW_MIN_UNDEQUEUED_BUFFERS,
512 &maxConsumerBuffers)) != OK) {
513 ALOGE("%s: Unable to query consumer undequeued"
514 " buffer count for stream %d", __FUNCTION__, mMainImageStreamId);
515 return res;
516 }
517
518 // Cannot use SourceSurface buffer count since it could be codec's 512*512 tile
519 // buffer count.
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800520 if ((res = native_window_set_buffer_count(
Shuzhen Wang3d00ee52019-09-25 14:19:28 -0700521 anwConsumer, kMaxOutputSurfaceProducerCount + maxConsumerBuffers)) != OK) {
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800522 ALOGE("%s: Unable to set buffer count for stream %d", __FUNCTION__, mMainImageStreamId);
523 return res;
524 }
525
526 if ((res = native_window_set_buffers_dimensions(anwConsumer, mMaxHeicBufferSize, 1)) != OK) {
527 ALOGE("%s: Unable to set buffer dimension %zu x 1 for stream %d: %s (%d)",
528 __FUNCTION__, mMaxHeicBufferSize, mMainImageStreamId, strerror(-res), res);
529 return res;
530 }
531
Shuzhen Wange8675782019-12-05 09:12:14 -0800532 sp<camera3::StatusTracker> statusTracker = mStatusTracker.promote();
533 if (statusTracker != nullptr) {
Yin-Chia Yeh87b3ec02019-06-03 10:44:39 -0700534 std::string name = std::string("HeicStream ") + std::to_string(getStreamId());
535 mStatusId = statusTracker->addComponent(name);
Shuzhen Wange8675782019-12-05 09:12:14 -0800536 }
537
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800538 run("HeicCompositeStreamProc");
539
540 return NO_ERROR;
541}
542
543status_t HeicCompositeStream::insertGbp(SurfaceMap* /*out*/outSurfaceMap,
544 Vector<int32_t>* /*out*/outputStreamIds, int32_t* /*out*/currentStreamId) {
545 if (outSurfaceMap->find(mAppSegmentStreamId) == outSurfaceMap->end()) {
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800546 outputStreamIds->push_back(mAppSegmentStreamId);
547 }
548 (*outSurfaceMap)[mAppSegmentStreamId].push_back(mAppSegmentSurfaceId);
549
550 if (outSurfaceMap->find(mMainImageStreamId) == outSurfaceMap->end()) {
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800551 outputStreamIds->push_back(mMainImageStreamId);
552 }
553 (*outSurfaceMap)[mMainImageStreamId].push_back(mMainImageSurfaceId);
554
555 if (currentStreamId != nullptr) {
556 *currentStreamId = mMainImageStreamId;
557 }
558
559 return NO_ERROR;
560}
561
Emilian Peev4697b642019-11-19 17:11:14 -0800562status_t HeicCompositeStream::insertCompositeStreamIds(
563 std::vector<int32_t>* compositeStreamIds /*out*/) {
564 if (compositeStreamIds == nullptr) {
565 return BAD_VALUE;
566 }
567
568 compositeStreamIds->push_back(mAppSegmentStreamId);
569 compositeStreamIds->push_back(mMainImageStreamId);
570
571 return OK;
572}
573
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800574void HeicCompositeStream::onShutter(const CaptureResultExtras& resultExtras, nsecs_t timestamp) {
575 Mutex::Autolock l(mMutex);
576 if (mErrorState) {
577 return;
578 }
579
580 if (mSettingsByFrameNumber.find(resultExtras.frameNumber) != mSettingsByFrameNumber.end()) {
Shuzhen Wange8675782019-12-05 09:12:14 -0800581 ALOGV("%s: [%" PRId64 "]: timestamp %" PRId64 ", requestId %d", __FUNCTION__,
582 resultExtras.frameNumber, timestamp, resultExtras.requestId);
583 mSettingsByFrameNumber[resultExtras.frameNumber].shutterNotified = true;
584 mSettingsByFrameNumber[resultExtras.frameNumber].timestamp = timestamp;
585 mSettingsByFrameNumber[resultExtras.frameNumber].requestId = resultExtras.requestId;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800586 mInputReadyCondition.signal();
587 }
588}
589
590void HeicCompositeStream::compilePendingInputLocked() {
Shuzhen Wange8675782019-12-05 09:12:14 -0800591 auto i = mSettingsByFrameNumber.begin();
592 while (i != mSettingsByFrameNumber.end()) {
593 if (i->second.shutterNotified) {
594 mPendingInputFrames[i->first].orientation = i->second.orientation;
595 mPendingInputFrames[i->first].quality = i->second.quality;
596 mPendingInputFrames[i->first].timestamp = i->second.timestamp;
597 mPendingInputFrames[i->first].requestId = i->second.requestId;
598 ALOGV("%s: [%" PRId64 "]: timestamp is %" PRId64, __FUNCTION__,
599 i->first, i->second.timestamp);
600 i = mSettingsByFrameNumber.erase(i);
Shuzhen Wang62f49ed2019-09-04 14:07:53 -0700601
Shuzhen Wange8675782019-12-05 09:12:14 -0800602 // Set encoder quality if no inflight encoding
603 if (mPendingInputFrames.size() == 1) {
604 sp<StatusTracker> statusTracker = mStatusTracker.promote();
605 if (statusTracker != nullptr) {
606 statusTracker->markComponentActive(mStatusId);
607 ALOGV("%s: Mark component as active", __FUNCTION__);
608 }
609
610 int32_t newQuality = mPendingInputFrames.begin()->second.quality;
611 updateCodecQualityLocked(newQuality);
612 }
613 } else {
614 i++;
Shuzhen Wang62f49ed2019-09-04 14:07:53 -0700615 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800616 }
617
Shuzhen Wange8675782019-12-05 09:12:14 -0800618 while (!mInputAppSegmentBuffers.empty() && mAppSegmentFrameNumbers.size() > 0) {
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800619 CpuConsumer::LockedBuffer imgBuffer;
620 auto it = mInputAppSegmentBuffers.begin();
621 auto res = mAppSegmentConsumer->lockNextBuffer(&imgBuffer);
622 if (res == NOT_ENOUGH_DATA) {
Michael Gonzalezb5986a32019-10-09 15:38:17 -0700623 // Can not lock any more buffers.
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800624 break;
625 } else if ((res != OK) || (*it != imgBuffer.timestamp)) {
626 if (res != OK) {
627 ALOGE("%s: Error locking JPEG_APP_SEGMENTS image buffer: %s (%d)", __FUNCTION__,
628 strerror(-res), res);
629 } else {
630 ALOGE("%s: Expecting JPEG_APP_SEGMENTS buffer with time stamp: %" PRId64
631 " received buffer with time stamp: %" PRId64, __FUNCTION__,
632 *it, imgBuffer.timestamp);
Michael Gonzalezb5986a32019-10-09 15:38:17 -0700633 mAppSegmentConsumer->unlockBuffer(imgBuffer);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800634 }
635 mPendingInputFrames[*it].error = true;
636 mInputAppSegmentBuffers.erase(it);
637 continue;
638 }
639
Shuzhen Wange8675782019-12-05 09:12:14 -0800640 if (mPendingInputFrames.find(mAppSegmentFrameNumbers.front()) == mPendingInputFrames.end()) {
641 ALOGE("%s: mPendingInputFrames doesn't contain frameNumber %" PRId64, __FUNCTION__,
642 mAppSegmentFrameNumbers.front());
Shuzhen Wang991b7b62020-06-17 11:39:11 -0700643 mInputAppSegmentBuffers.erase(it);
644 mAppSegmentFrameNumbers.pop();
Shuzhen Wange8675782019-12-05 09:12:14 -0800645 continue;
646 }
647
648 int64_t frameNumber = mAppSegmentFrameNumbers.front();
649 // If mPendingInputFrames doesn't contain the expected frame number, the captured
650 // input app segment frame must have been dropped via a buffer error. Simply
651 // return the buffer to the buffer queue.
652 if ((mPendingInputFrames.find(frameNumber) == mPendingInputFrames.end()) ||
653 (mPendingInputFrames[frameNumber].error)) {
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800654 mAppSegmentConsumer->unlockBuffer(imgBuffer);
655 } else {
Shuzhen Wange8675782019-12-05 09:12:14 -0800656 mPendingInputFrames[frameNumber].appSegmentBuffer = imgBuffer;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800657 }
658 mInputAppSegmentBuffers.erase(it);
Shuzhen Wange8675782019-12-05 09:12:14 -0800659 mAppSegmentFrameNumbers.pop();
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800660 }
661
Shuzhen Wange8675782019-12-05 09:12:14 -0800662 while (!mInputYuvBuffers.empty() && !mYuvBufferAcquired && mMainImageFrameNumbers.size() > 0) {
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800663 CpuConsumer::LockedBuffer imgBuffer;
664 auto it = mInputYuvBuffers.begin();
665 auto res = mMainImageConsumer->lockNextBuffer(&imgBuffer);
666 if (res == NOT_ENOUGH_DATA) {
Michael Gonzalezb5986a32019-10-09 15:38:17 -0700667 // Can not lock any more buffers.
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800668 break;
669 } else if (res != OK) {
670 ALOGE("%s: Error locking YUV_888 image buffer: %s (%d)", __FUNCTION__,
671 strerror(-res), res);
672 mPendingInputFrames[*it].error = true;
673 mInputYuvBuffers.erase(it);
674 continue;
675 } else if (*it != imgBuffer.timestamp) {
676 ALOGW("%s: Expecting YUV_888 buffer with time stamp: %" PRId64 " received buffer with "
677 "time stamp: %" PRId64, __FUNCTION__, *it, imgBuffer.timestamp);
678 mPendingInputFrames[*it].error = true;
679 mInputYuvBuffers.erase(it);
680 continue;
681 }
682
Shuzhen Wange8675782019-12-05 09:12:14 -0800683 if (mPendingInputFrames.find(mMainImageFrameNumbers.front()) == mPendingInputFrames.end()) {
684 ALOGE("%s: mPendingInputFrames doesn't contain frameNumber %" PRId64, __FUNCTION__,
685 mMainImageFrameNumbers.front());
686 mInputYuvBuffers.erase(it);
Shuzhen Wang991b7b62020-06-17 11:39:11 -0700687 mMainImageFrameNumbers.pop();
Shuzhen Wange8675782019-12-05 09:12:14 -0800688 continue;
689 }
690
691 int64_t frameNumber = mMainImageFrameNumbers.front();
692 // If mPendingInputFrames doesn't contain the expected frame number, the captured
693 // input main image must have been dropped via a buffer error. Simply
694 // return the buffer to the buffer queue.
695 if ((mPendingInputFrames.find(frameNumber) == mPendingInputFrames.end()) ||
696 (mPendingInputFrames[frameNumber].error)) {
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800697 mMainImageConsumer->unlockBuffer(imgBuffer);
698 } else {
Shuzhen Wange8675782019-12-05 09:12:14 -0800699 mPendingInputFrames[frameNumber].yuvBuffer = imgBuffer;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800700 mYuvBufferAcquired = true;
701 }
702 mInputYuvBuffers.erase(it);
Shuzhen Wange8675782019-12-05 09:12:14 -0800703 mMainImageFrameNumbers.pop();
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800704 }
705
706 while (!mCodecOutputBuffers.empty()) {
707 auto it = mCodecOutputBuffers.begin();
Shuzhen Wange8675782019-12-05 09:12:14 -0800708 // Assume encoder input to output is FIFO, use a queue to look up
709 // frameNumber when handling codec outputs.
710 int64_t bufferFrameNumber = -1;
711 if (mCodecOutputBufferFrameNumbers.empty()) {
712 ALOGV("%s: Failed to find buffer frameNumber for codec output buffer!", __FUNCTION__);
Michael Gonzalez5c103f22019-10-08 14:30:32 -0700713 break;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800714 } else {
Shuzhen Wange8675782019-12-05 09:12:14 -0800715 // Direct mapping between camera frame number and codec timestamp (in us).
716 bufferFrameNumber = mCodecOutputBufferFrameNumbers.front();
Shuzhen Wang3d00ee52019-09-25 14:19:28 -0700717 mCodecOutputCounter++;
718 if (mCodecOutputCounter == mNumOutputTiles) {
Shuzhen Wange8675782019-12-05 09:12:14 -0800719 mCodecOutputBufferFrameNumbers.pop();
Shuzhen Wang3d00ee52019-09-25 14:19:28 -0700720 mCodecOutputCounter = 0;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800721 }
722
Shuzhen Wange8675782019-12-05 09:12:14 -0800723 mPendingInputFrames[bufferFrameNumber].codecOutputBuffers.push_back(*it);
724 ALOGV("%s: [%" PRId64 "]: Pushing codecOutputBuffers (frameNumber %" PRId64 ")",
725 __FUNCTION__, bufferFrameNumber, it->timeUs);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800726 }
727 mCodecOutputBuffers.erase(it);
728 }
729
Shuzhen Wange7f4b462019-02-12 08:43:07 -0800730 while (!mCaptureResults.empty()) {
731 auto it = mCaptureResults.begin();
Shuzhen Wange8675782019-12-05 09:12:14 -0800732 // Negative frame number indicates that something went wrong during the capture result
Shuzhen Wange7f4b462019-02-12 08:43:07 -0800733 // collection process.
Shuzhen Wange8675782019-12-05 09:12:14 -0800734 int64_t frameNumber = std::get<0>(it->second);
735 if (it->first >= 0 &&
736 mPendingInputFrames.find(frameNumber) != mPendingInputFrames.end()) {
737 if (mPendingInputFrames[frameNumber].timestamp == it->first) {
738 mPendingInputFrames[frameNumber].result =
Shuzhen Wange7f4b462019-02-12 08:43:07 -0800739 std::make_unique<CameraMetadata>(std::get<1>(it->second));
740 } else {
741 ALOGE("%s: Capture result frameNumber/timestamp mapping changed between "
Shuzhen Wange8675782019-12-05 09:12:14 -0800742 "shutter and capture result! before: %" PRId64 ", after: %" PRId64,
743 __FUNCTION__, mPendingInputFrames[frameNumber].timestamp,
744 it->first);
Shuzhen Wange7f4b462019-02-12 08:43:07 -0800745 }
746 }
747 mCaptureResults.erase(it);
748 }
749
750 // mErrorFrameNumbers stores frame number of dropped buffers.
751 auto it = mErrorFrameNumbers.begin();
752 while (it != mErrorFrameNumbers.end()) {
Shuzhen Wange8675782019-12-05 09:12:14 -0800753 if (mPendingInputFrames.find(*it) != mPendingInputFrames.end()) {
754 mPendingInputFrames[*it].error = true;
Shuzhen Wange7f4b462019-02-12 08:43:07 -0800755 } else {
Shuzhen Wange8675782019-12-05 09:12:14 -0800756 //Error callback is guaranteed to arrive after shutter notify, which
757 //results in mPendingInputFrames being populated.
Shuzhen Wange7f4b462019-02-12 08:43:07 -0800758 ALOGW("%s: Not able to find failing input with frame number: %" PRId64, __FUNCTION__,
759 *it);
Shuzhen Wange7f4b462019-02-12 08:43:07 -0800760 }
Shuzhen Wange8675782019-12-05 09:12:14 -0800761 it = mErrorFrameNumbers.erase(it);
762 }
763
764 // mExifErrorFrameNumbers stores the frame number of dropped APP_SEGMENT buffers
765 it = mExifErrorFrameNumbers.begin();
766 while (it != mExifErrorFrameNumbers.end()) {
767 if (mPendingInputFrames.find(*it) != mPendingInputFrames.end()) {
768 mPendingInputFrames[*it].exifError = true;
769 }
770 it = mExifErrorFrameNumbers.erase(it);
Shuzhen Wange7f4b462019-02-12 08:43:07 -0800771 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800772
773 // Distribute codec input buffers to be filled out from YUV output
774 for (auto it = mPendingInputFrames.begin();
775 it != mPendingInputFrames.end() && mCodecInputBuffers.size() > 0; it++) {
776 InputFrame& inputFrame(it->second);
777 if (inputFrame.codecInputCounter < mGridRows * mGridCols) {
778 // Available input tiles that are required for the current input
779 // image.
780 size_t newInputTiles = std::min(mCodecInputBuffers.size(),
781 mGridRows * mGridCols - inputFrame.codecInputCounter);
782 for (size_t i = 0; i < newInputTiles; i++) {
783 CodecInputBufferInfo inputInfo =
784 { mCodecInputBuffers[0], mGridTimestampUs++, inputFrame.codecInputCounter };
785 inputFrame.codecInputBuffers.push_back(inputInfo);
786
787 mCodecInputBuffers.erase(mCodecInputBuffers.begin());
788 inputFrame.codecInputCounter++;
789 }
790 break;
791 }
792 }
793}
794
Shuzhen Wange8675782019-12-05 09:12:14 -0800795bool HeicCompositeStream::getNextReadyInputLocked(int64_t *frameNumber /*out*/) {
796 if (frameNumber == nullptr) {
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800797 return false;
798 }
799
800 bool newInputAvailable = false;
Shuzhen Wang3d00ee52019-09-25 14:19:28 -0700801 for (auto& it : mPendingInputFrames) {
802 // New input is considered to be available only if:
803 // 1. input buffers are ready, or
804 // 2. App segment and muxer is created, or
805 // 3. A codec output tile is ready, and an output buffer is available.
806 // This makes sure that muxer gets created only when an output tile is
807 // generated, because right now we only handle 1 HEIC output buffer at a
808 // time (max dequeued buffer count is 1).
Shuzhen Wange8675782019-12-05 09:12:14 -0800809 bool appSegmentReady =
810 (it.second.appSegmentBuffer.data != nullptr || it.second.exifError) &&
Shuzhen Wang3d00ee52019-09-25 14:19:28 -0700811 !it.second.appSegmentWritten && it.second.result != nullptr &&
812 it.second.muxer != nullptr;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800813 bool codecOutputReady = !it.second.codecOutputBuffers.empty();
814 bool codecInputReady = (it.second.yuvBuffer.data != nullptr) &&
815 (!it.second.codecInputBuffers.empty());
Shuzhen Wang3d00ee52019-09-25 14:19:28 -0700816 bool hasOutputBuffer = it.second.muxer != nullptr ||
817 (mDequeuedOutputBufferCnt < kMaxOutputSurfaceProducerCount);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800818 if ((!it.second.error) &&
Shuzhen Wang3d00ee52019-09-25 14:19:28 -0700819 (appSegmentReady || (codecOutputReady && hasOutputBuffer) || codecInputReady)) {
Shuzhen Wange8675782019-12-05 09:12:14 -0800820 *frameNumber = it.first;
Shuzhen Wang3d00ee52019-09-25 14:19:28 -0700821 if (it.second.format == nullptr && mFormat != nullptr) {
822 it.second.format = mFormat->dup();
823 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800824 newInputAvailable = true;
825 break;
826 }
827 }
828
829 return newInputAvailable;
830}
831
Shuzhen Wange8675782019-12-05 09:12:14 -0800832int64_t HeicCompositeStream::getNextFailingInputLocked() {
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800833 int64_t res = -1;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800834
835 for (const auto& it : mPendingInputFrames) {
Shuzhen Wange8675782019-12-05 09:12:14 -0800836 if (it.second.error) {
837 res = it.first;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800838 break;
839 }
840 }
841
842 return res;
843}
844
Shuzhen Wange8675782019-12-05 09:12:14 -0800845status_t HeicCompositeStream::processInputFrame(int64_t frameNumber,
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800846 InputFrame &inputFrame) {
847 ATRACE_CALL();
848 status_t res = OK;
849
Shuzhen Wange8675782019-12-05 09:12:14 -0800850 bool appSegmentReady =
851 (inputFrame.appSegmentBuffer.data != nullptr || inputFrame.exifError) &&
Shuzhen Wang3d00ee52019-09-25 14:19:28 -0700852 !inputFrame.appSegmentWritten && inputFrame.result != nullptr &&
853 inputFrame.muxer != nullptr;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800854 bool codecOutputReady = inputFrame.codecOutputBuffers.size() > 0;
855 bool codecInputReady = inputFrame.yuvBuffer.data != nullptr &&
Shuzhen Wang3d00ee52019-09-25 14:19:28 -0700856 !inputFrame.codecInputBuffers.empty();
857 bool hasOutputBuffer = inputFrame.muxer != nullptr ||
858 (mDequeuedOutputBufferCnt < kMaxOutputSurfaceProducerCount);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800859
Shuzhen Wang3d00ee52019-09-25 14:19:28 -0700860 ALOGV("%s: [%" PRId64 "]: appSegmentReady %d, codecOutputReady %d, codecInputReady %d,"
Shuzhen Wange8675782019-12-05 09:12:14 -0800861 " dequeuedOutputBuffer %d, timestamp %" PRId64, __FUNCTION__, frameNumber,
862 appSegmentReady, codecOutputReady, codecInputReady, mDequeuedOutputBufferCnt,
863 inputFrame.timestamp);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800864
865 // Handle inputs for Hevc tiling
866 if (codecInputReady) {
867 res = processCodecInputFrame(inputFrame);
868 if (res != OK) {
869 ALOGE("%s: Failed to process codec input frame: %s (%d)", __FUNCTION__,
870 strerror(-res), res);
871 return res;
872 }
873 }
874
Shuzhen Wang3d00ee52019-09-25 14:19:28 -0700875 if (!(codecOutputReady && hasOutputBuffer) && !appSegmentReady) {
876 return OK;
877 }
878
879 // Initialize and start muxer if not yet done so. In this case,
880 // codecOutputReady must be true. Otherwise, appSegmentReady is guaranteed
881 // to be false, and the function must have returned early.
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800882 if (inputFrame.muxer == nullptr) {
Shuzhen Wange8675782019-12-05 09:12:14 -0800883 res = startMuxerForInputFrame(frameNumber, inputFrame);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800884 if (res != OK) {
885 ALOGE("%s: Failed to create and start muxer: %s (%d)", __FUNCTION__,
886 strerror(-res), res);
887 return res;
888 }
889 }
890
891 // Write JPEG APP segments data to the muxer.
Shuzhen Wang3d00ee52019-09-25 14:19:28 -0700892 if (appSegmentReady) {
Shuzhen Wange8675782019-12-05 09:12:14 -0800893 res = processAppSegment(frameNumber, inputFrame);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800894 if (res != OK) {
895 ALOGE("%s: Failed to process JPEG APP segments: %s (%d)", __FUNCTION__,
896 strerror(-res), res);
897 return res;
898 }
899 }
900
901 // Write media codec bitstream buffers to muxer.
902 while (!inputFrame.codecOutputBuffers.empty()) {
Shuzhen Wange8675782019-12-05 09:12:14 -0800903 res = processOneCodecOutputFrame(frameNumber, inputFrame);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800904 if (res != OK) {
905 ALOGE("%s: Failed to process codec output frame: %s (%d)", __FUNCTION__,
906 strerror(-res), res);
907 return res;
908 }
909 }
910
Michael Gonzalezb5986a32019-10-09 15:38:17 -0700911 if (inputFrame.pendingOutputTiles == 0) {
912 if (inputFrame.appSegmentWritten) {
Shuzhen Wange8675782019-12-05 09:12:14 -0800913 res = processCompletedInputFrame(frameNumber, inputFrame);
Michael Gonzalezb5986a32019-10-09 15:38:17 -0700914 if (res != OK) {
915 ALOGE("%s: Failed to process completed input frame: %s (%d)", __FUNCTION__,
916 strerror(-res), res);
917 return res;
918 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800919 }
920 }
921
922 return res;
923}
924
Shuzhen Wange8675782019-12-05 09:12:14 -0800925status_t HeicCompositeStream::startMuxerForInputFrame(int64_t frameNumber, InputFrame &inputFrame) {
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800926 sp<ANativeWindow> outputANW = mOutputSurface;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800927
928 auto res = outputANW->dequeueBuffer(mOutputSurface.get(), &inputFrame.anb, &inputFrame.fenceFd);
929 if (res != OK) {
930 ALOGE("%s: Error retrieving output buffer: %s (%d)", __FUNCTION__, strerror(-res),
931 res);
932 return res;
933 }
Shuzhen Wang3d00ee52019-09-25 14:19:28 -0700934 mDequeuedOutputBufferCnt++;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800935
936 // Combine current thread id, stream id and timestamp to uniquely identify image.
937 std::ostringstream tempOutputFile;
938 tempOutputFile << "HEIF-" << pthread_self() << "-"
Shuzhen Wange8675782019-12-05 09:12:14 -0800939 << getStreamId() << "-" << frameNumber;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800940 inputFrame.fileFd = syscall(__NR_memfd_create, tempOutputFile.str().c_str(), MFD_CLOEXEC);
941 if (inputFrame.fileFd < 0) {
942 ALOGE("%s: Failed to create file %s. Error no is %d", __FUNCTION__,
943 tempOutputFile.str().c_str(), errno);
944 return NO_INIT;
945 }
Manisha Jajoo022b52f2021-10-09 00:51:42 +0530946 inputFrame.muxer = MediaMuxer::create(inputFrame.fileFd, MediaMuxer::OUTPUT_FORMAT_HEIF);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800947 if (inputFrame.muxer == nullptr) {
948 ALOGE("%s: Failed to create MediaMuxer for file fd %d",
949 __FUNCTION__, inputFrame.fileFd);
950 return NO_INIT;
951 }
952
953 res = inputFrame.muxer->setOrientationHint(inputFrame.orientation);
954 if (res != OK) {
955 ALOGE("%s: Failed to setOrientationHint: %s (%d)", __FUNCTION__,
956 strerror(-res), res);
957 return res;
958 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800959
Shuzhen Wang3d00ee52019-09-25 14:19:28 -0700960 ssize_t trackId = inputFrame.muxer->addTrack(inputFrame.format);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800961 if (trackId < 0) {
962 ALOGE("%s: Failed to addTrack to the muxer: %zd", __FUNCTION__, trackId);
963 return NO_INIT;
964 }
965
966 inputFrame.trackIndex = trackId;
967 inputFrame.pendingOutputTiles = mNumOutputTiles;
968
969 res = inputFrame.muxer->start();
970 if (res != OK) {
971 ALOGE("%s: Failed to start MediaMuxer: %s (%d)",
972 __FUNCTION__, strerror(-res), res);
973 return res;
974 }
975
Shuzhen Wang3d00ee52019-09-25 14:19:28 -0700976 ALOGV("%s: [%" PRId64 "]: Muxer started for inputFrame", __FUNCTION__,
Shuzhen Wange8675782019-12-05 09:12:14 -0800977 frameNumber);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800978 return OK;
979}
980
Shuzhen Wange8675782019-12-05 09:12:14 -0800981status_t HeicCompositeStream::processAppSegment(int64_t frameNumber, InputFrame &inputFrame) {
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800982 size_t app1Size = 0;
Shuzhen Wange8675782019-12-05 09:12:14 -0800983 size_t appSegmentSize = 0;
984 if (!inputFrame.exifError) {
985 appSegmentSize = findAppSegmentsSize(inputFrame.appSegmentBuffer.data,
986 inputFrame.appSegmentBuffer.width * inputFrame.appSegmentBuffer.height,
987 &app1Size);
988 if (appSegmentSize == 0) {
989 ALOGE("%s: Failed to find JPEG APP segment size", __FUNCTION__);
990 return NO_INIT;
991 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800992 }
993
994 std::unique_ptr<ExifUtils> exifUtils(ExifUtils::create());
Shuzhen Wange8675782019-12-05 09:12:14 -0800995 auto exifRes = inputFrame.exifError ?
996 exifUtils->initializeEmpty() :
997 exifUtils->initialize(inputFrame.appSegmentBuffer.data, app1Size);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800998 if (!exifRes) {
999 ALOGE("%s: Failed to initialize ExifUtils object!", __FUNCTION__);
1000 return BAD_VALUE;
1001 }
Shuzhen Wange7f4b462019-02-12 08:43:07 -08001002 exifRes = exifUtils->setFromMetadata(*inputFrame.result, mStaticInfo,
1003 mOutputWidth, mOutputHeight);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001004 if (!exifRes) {
1005 ALOGE("%s: Failed to set Exif tags using metadata and main image sizes", __FUNCTION__);
1006 return BAD_VALUE;
1007 }
1008 exifRes = exifUtils->setOrientation(inputFrame.orientation);
1009 if (!exifRes) {
1010 ALOGE("%s: ExifUtils failed to set orientation", __FUNCTION__);
1011 return BAD_VALUE;
1012 }
1013 exifRes = exifUtils->generateApp1();
1014 if (!exifRes) {
1015 ALOGE("%s: ExifUtils failed to generate APP1 segment", __FUNCTION__);
1016 return BAD_VALUE;
1017 }
1018
1019 unsigned int newApp1Length = exifUtils->getApp1Length();
1020 const uint8_t *newApp1Segment = exifUtils->getApp1Buffer();
1021
1022 //Assemble the APP1 marker buffer required by MediaCodec
1023 uint8_t kExifApp1Marker[] = {'E', 'x', 'i', 'f', 0xFF, 0xE1, 0x00, 0x00};
1024 kExifApp1Marker[6] = static_cast<uint8_t>(newApp1Length >> 8);
1025 kExifApp1Marker[7] = static_cast<uint8_t>(newApp1Length & 0xFF);
1026 size_t appSegmentBufferSize = sizeof(kExifApp1Marker) +
1027 appSegmentSize - app1Size + newApp1Length;
1028 uint8_t* appSegmentBuffer = new uint8_t[appSegmentBufferSize];
1029 memcpy(appSegmentBuffer, kExifApp1Marker, sizeof(kExifApp1Marker));
1030 memcpy(appSegmentBuffer + sizeof(kExifApp1Marker), newApp1Segment, newApp1Length);
1031 if (appSegmentSize - app1Size > 0) {
1032 memcpy(appSegmentBuffer + sizeof(kExifApp1Marker) + newApp1Length,
1033 inputFrame.appSegmentBuffer.data + app1Size, appSegmentSize - app1Size);
1034 }
1035
1036 sp<ABuffer> aBuffer = new ABuffer(appSegmentBuffer, appSegmentBufferSize);
1037 auto res = inputFrame.muxer->writeSampleData(aBuffer, inputFrame.trackIndex,
Shuzhen Wange8675782019-12-05 09:12:14 -08001038 inputFrame.timestamp, MediaCodec::BUFFER_FLAG_MUXER_DATA);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001039 delete[] appSegmentBuffer;
1040
1041 if (res != OK) {
1042 ALOGE("%s: Failed to write JPEG APP segments to muxer: %s (%d)",
1043 __FUNCTION__, strerror(-res), res);
1044 return res;
1045 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001046
Shuzhen Wang3d00ee52019-09-25 14:19:28 -07001047 ALOGV("%s: [%" PRId64 "]: appSegmentSize is %zu, width %d, height %d, app1Size %zu",
Shuzhen Wange8675782019-12-05 09:12:14 -08001048 __FUNCTION__, frameNumber, appSegmentSize, inputFrame.appSegmentBuffer.width,
Shuzhen Wang3d00ee52019-09-25 14:19:28 -07001049 inputFrame.appSegmentBuffer.height, app1Size);
Michael Gonzalezb5986a32019-10-09 15:38:17 -07001050
1051 inputFrame.appSegmentWritten = true;
1052 // Release the buffer now so any pending input app segments can be processed
1053 mAppSegmentConsumer->unlockBuffer(inputFrame.appSegmentBuffer);
1054 inputFrame.appSegmentBuffer.data = nullptr;
Shuzhen Wange8675782019-12-05 09:12:14 -08001055 inputFrame.exifError = false;
Michael Gonzalezb5986a32019-10-09 15:38:17 -07001056
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001057 return OK;
1058}
1059
1060status_t HeicCompositeStream::processCodecInputFrame(InputFrame &inputFrame) {
1061 for (auto& inputBuffer : inputFrame.codecInputBuffers) {
1062 sp<MediaCodecBuffer> buffer;
1063 auto res = mCodec->getInputBuffer(inputBuffer.index, &buffer);
1064 if (res != OK) {
1065 ALOGE("%s: Error getting codec input buffer: %s (%d)", __FUNCTION__,
1066 strerror(-res), res);
1067 return res;
1068 }
1069
1070 // Copy one tile from source to destination.
1071 size_t tileX = inputBuffer.tileIndex % mGridCols;
1072 size_t tileY = inputBuffer.tileIndex / mGridCols;
1073 size_t top = mGridHeight * tileY;
1074 size_t left = mGridWidth * tileX;
1075 size_t width = (tileX == static_cast<size_t>(mGridCols) - 1) ?
1076 mOutputWidth - tileX * mGridWidth : mGridWidth;
1077 size_t height = (tileY == static_cast<size_t>(mGridRows) - 1) ?
1078 mOutputHeight - tileY * mGridHeight : mGridHeight;
Shuzhen Wang3d00ee52019-09-25 14:19:28 -07001079 ALOGV("%s: inputBuffer tileIndex [%zu, %zu], top %zu, left %zu, width %zu, height %zu,"
1080 " timeUs %" PRId64, __FUNCTION__, tileX, tileY, top, left, width, height,
1081 inputBuffer.timeUs);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001082
1083 res = copyOneYuvTile(buffer, inputFrame.yuvBuffer, top, left, width, height);
1084 if (res != OK) {
1085 ALOGE("%s: Failed to copy YUV tile %s (%d)", __FUNCTION__,
1086 strerror(-res), res);
1087 return res;
1088 }
1089
1090 res = mCodec->queueInputBuffer(inputBuffer.index, 0, buffer->capacity(),
1091 inputBuffer.timeUs, 0, nullptr /*errorDetailMsg*/);
1092 if (res != OK) {
1093 ALOGE("%s: Failed to queueInputBuffer to Codec: %s (%d)",
1094 __FUNCTION__, strerror(-res), res);
1095 return res;
1096 }
1097 }
1098
1099 inputFrame.codecInputBuffers.clear();
1100 return OK;
1101}
1102
Shuzhen Wange8675782019-12-05 09:12:14 -08001103status_t HeicCompositeStream::processOneCodecOutputFrame(int64_t frameNumber,
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001104 InputFrame &inputFrame) {
1105 auto it = inputFrame.codecOutputBuffers.begin();
1106 sp<MediaCodecBuffer> buffer;
1107 status_t res = mCodec->getOutputBuffer(it->index, &buffer);
1108 if (res != OK) {
1109 ALOGE("%s: Error getting Heic codec output buffer at index %d: %s (%d)",
1110 __FUNCTION__, it->index, strerror(-res), res);
1111 return res;
1112 }
1113 if (buffer == nullptr) {
1114 ALOGE("%s: Invalid Heic codec output buffer at index %d",
1115 __FUNCTION__, it->index);
1116 return BAD_VALUE;
1117 }
1118
1119 sp<ABuffer> aBuffer = new ABuffer(buffer->data(), buffer->size());
1120 res = inputFrame.muxer->writeSampleData(
Shuzhen Wange8675782019-12-05 09:12:14 -08001121 aBuffer, inputFrame.trackIndex, inputFrame.timestamp, 0 /*flags*/);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001122 if (res != OK) {
1123 ALOGE("%s: Failed to write buffer index %d to muxer: %s (%d)",
1124 __FUNCTION__, it->index, strerror(-res), res);
1125 return res;
1126 }
1127
1128 mCodec->releaseOutputBuffer(it->index);
1129 if (inputFrame.pendingOutputTiles == 0) {
1130 ALOGW("%s: Codec generated more tiles than expected!", __FUNCTION__);
1131 } else {
1132 inputFrame.pendingOutputTiles--;
1133 }
1134
1135 inputFrame.codecOutputBuffers.erase(inputFrame.codecOutputBuffers.begin());
Shuzhen Wang3d00ee52019-09-25 14:19:28 -07001136
1137 ALOGV("%s: [%" PRId64 "]: Output buffer index %d",
Shuzhen Wange8675782019-12-05 09:12:14 -08001138 __FUNCTION__, frameNumber, it->index);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001139 return OK;
1140}
1141
Shuzhen Wange8675782019-12-05 09:12:14 -08001142status_t HeicCompositeStream::processCompletedInputFrame(int64_t frameNumber,
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001143 InputFrame &inputFrame) {
1144 sp<ANativeWindow> outputANW = mOutputSurface;
1145 inputFrame.muxer->stop();
1146
1147 // Copy the content of the file to memory.
1148 sp<GraphicBuffer> gb = GraphicBuffer::from(inputFrame.anb);
1149 void* dstBuffer;
Shuzhen Wangc87315d2022-03-17 00:11:20 +00001150 GraphicBufferLocker gbLocker(gb);
1151 auto res = gbLocker.lockAsync(&dstBuffer, inputFrame.fenceFd);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001152 if (res != OK) {
1153 ALOGE("%s: Error trying to lock output buffer fence: %s (%d)", __FUNCTION__,
1154 strerror(-res), res);
1155 return res;
1156 }
1157
1158 off_t fSize = lseek(inputFrame.fileFd, 0, SEEK_END);
1159 if (static_cast<size_t>(fSize) > mMaxHeicBufferSize - sizeof(CameraBlob)) {
1160 ALOGE("%s: Error: MediaMuxer output size %ld is larger than buffer sizer %zu",
1161 __FUNCTION__, fSize, mMaxHeicBufferSize - sizeof(CameraBlob));
1162 return BAD_VALUE;
1163 }
1164
1165 lseek(inputFrame.fileFd, 0, SEEK_SET);
1166 ssize_t bytesRead = read(inputFrame.fileFd, dstBuffer, fSize);
1167 if (bytesRead < fSize) {
1168 ALOGE("%s: Only %zd of %ld bytes read", __FUNCTION__, bytesRead, fSize);
1169 return BAD_VALUE;
1170 }
1171
1172 close(inputFrame.fileFd);
1173 inputFrame.fileFd = -1;
1174
1175 // Fill in HEIC header
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001176 // Must be in sync with CAMERA3_HEIC_BLOB_ID in android_media_Utils.cpp
Shuzhen Wangdc519092022-12-02 12:29:04 -08001177 uint8_t *header = static_cast<uint8_t*>(dstBuffer) + mMaxHeicBufferSize - sizeof(CameraBlob);
1178 CameraBlob blobHeader = {
1179 .blobId = static_cast<CameraBlobId>(0x00FE),
1180 .blobSizeBytes = static_cast<int32_t>(fSize)
1181 };
1182 memcpy(header, &blobHeader, sizeof(CameraBlob));
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001183
Shuzhen Wange8675782019-12-05 09:12:14 -08001184 res = native_window_set_buffers_timestamp(mOutputSurface.get(), inputFrame.timestamp);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001185 if (res != OK) {
1186 ALOGE("%s: Stream %d: Error setting timestamp: %s (%d)",
1187 __FUNCTION__, getStreamId(), strerror(-res), res);
1188 return res;
1189 }
1190
1191 res = outputANW->queueBuffer(mOutputSurface.get(), inputFrame.anb, /*fence*/ -1);
1192 if (res != OK) {
1193 ALOGE("%s: Failed to queueBuffer to Heic stream: %s (%d)", __FUNCTION__,
1194 strerror(-res), res);
1195 return res;
1196 }
1197 inputFrame.anb = nullptr;
Shuzhen Wang3d00ee52019-09-25 14:19:28 -07001198 mDequeuedOutputBufferCnt--;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001199
Shuzhen Wange8675782019-12-05 09:12:14 -08001200 ALOGV("%s: [%" PRId64 "]", __FUNCTION__, frameNumber);
1201 ATRACE_ASYNC_END("HEIC capture", frameNumber);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001202 return OK;
1203}
1204
1205
Shuzhen Wange8675782019-12-05 09:12:14 -08001206void HeicCompositeStream::releaseInputFrameLocked(int64_t frameNumber,
1207 InputFrame *inputFrame /*out*/) {
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001208 if (inputFrame == nullptr) {
1209 return;
1210 }
1211
1212 if (inputFrame->appSegmentBuffer.data != nullptr) {
1213 mAppSegmentConsumer->unlockBuffer(inputFrame->appSegmentBuffer);
1214 inputFrame->appSegmentBuffer.data = nullptr;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001215 }
1216
1217 while (!inputFrame->codecOutputBuffers.empty()) {
1218 auto it = inputFrame->codecOutputBuffers.begin();
1219 ALOGV("%s: releaseOutputBuffer index %d", __FUNCTION__, it->index);
1220 mCodec->releaseOutputBuffer(it->index);
1221 inputFrame->codecOutputBuffers.erase(it);
1222 }
1223
1224 if (inputFrame->yuvBuffer.data != nullptr) {
1225 mMainImageConsumer->unlockBuffer(inputFrame->yuvBuffer);
1226 inputFrame->yuvBuffer.data = nullptr;
1227 mYuvBufferAcquired = false;
1228 }
1229
1230 while (!inputFrame->codecInputBuffers.empty()) {
1231 auto it = inputFrame->codecInputBuffers.begin();
1232 inputFrame->codecInputBuffers.erase(it);
1233 }
1234
Shuzhen Wange8675782019-12-05 09:12:14 -08001235 if (inputFrame->error || mErrorState) {
1236 ALOGV("%s: notifyError called for frameNumber %" PRId64, __FUNCTION__, frameNumber);
1237 notifyError(frameNumber, inputFrame->requestId);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001238 }
1239
1240 if (inputFrame->fileFd >= 0) {
1241 close(inputFrame->fileFd);
1242 inputFrame->fileFd = -1;
1243 }
1244
1245 if (inputFrame->anb != nullptr) {
1246 sp<ANativeWindow> outputANW = mOutputSurface;
1247 outputANW->cancelBuffer(mOutputSurface.get(), inputFrame->anb, /*fence*/ -1);
1248 inputFrame->anb = nullptr;
Shuzhen Wange8675782019-12-05 09:12:14 -08001249
1250 mDequeuedOutputBufferCnt--;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001251 }
1252}
1253
Michael Gonzalezb5986a32019-10-09 15:38:17 -07001254void HeicCompositeStream::releaseInputFramesLocked() {
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001255 auto it = mPendingInputFrames.begin();
Shuzhen Wang62f49ed2019-09-04 14:07:53 -07001256 bool inputFrameDone = false;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001257 while (it != mPendingInputFrames.end()) {
Michael Gonzalezb5986a32019-10-09 15:38:17 -07001258 auto& inputFrame = it->second;
1259 if (inputFrame.error ||
Shuzhen Wange8675782019-12-05 09:12:14 -08001260 (inputFrame.appSegmentWritten && inputFrame.pendingOutputTiles == 0)) {
1261 releaseInputFrameLocked(it->first, &inputFrame);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001262 it = mPendingInputFrames.erase(it);
Shuzhen Wang62f49ed2019-09-04 14:07:53 -07001263 inputFrameDone = true;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001264 } else {
1265 it++;
1266 }
1267 }
Shuzhen Wang62f49ed2019-09-04 14:07:53 -07001268
1269 // Update codec quality based on first upcoming input frame.
1270 // Note that when encoding is in surface mode, currently there is no
1271 // way for camera service to synchronize quality setting on a per-frame
1272 // basis: we don't get notification when codec is ready to consume a new
1273 // input frame. So we update codec quality on a best-effort basis.
1274 if (inputFrameDone) {
1275 auto firstPendingFrame = mPendingInputFrames.begin();
1276 if (firstPendingFrame != mPendingInputFrames.end()) {
1277 updateCodecQualityLocked(firstPendingFrame->second.quality);
Shuzhen Wange8675782019-12-05 09:12:14 -08001278 } else {
1279 markTrackerIdle();
Shuzhen Wang62f49ed2019-09-04 14:07:53 -07001280 }
1281 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001282}
1283
1284status_t HeicCompositeStream::initializeCodec(uint32_t width, uint32_t height,
1285 const sp<CameraDeviceBase>& cameraDevice) {
1286 ALOGV("%s", __FUNCTION__);
1287
1288 bool useGrid = false;
Chong Zhang688abaa2019-05-17 16:32:23 -07001289 AString hevcName;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001290 bool isSizeSupported = isSizeSupportedByHeifEncoder(width, height,
Chong Zhang688abaa2019-05-17 16:32:23 -07001291 &mUseHeic, &useGrid, nullptr, &hevcName);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001292 if (!isSizeSupported) {
1293 ALOGE("%s: Encoder doesnt' support size %u x %u!",
1294 __FUNCTION__, width, height);
1295 return BAD_VALUE;
1296 }
1297
1298 // Create Looper for MediaCodec.
1299 auto desiredMime = mUseHeic ? MIMETYPE_IMAGE_ANDROID_HEIC : MIMETYPE_VIDEO_HEVC;
1300 mCodecLooper = new ALooper;
1301 mCodecLooper->setName("Camera3-HeicComposite-MediaCodecLooper");
1302 status_t res = mCodecLooper->start(
1303 false, // runOnCallingThread
1304 false, // canCallJava
1305 PRIORITY_AUDIO);
1306 if (res != OK) {
1307 ALOGE("%s: Failed to start codec looper: %s (%d)",
1308 __FUNCTION__, strerror(-res), res);
1309 return NO_INIT;
1310 }
1311
1312 // Create HEIC/HEVC codec.
Chong Zhang688abaa2019-05-17 16:32:23 -07001313 if (mUseHeic) {
1314 mCodec = MediaCodec::CreateByType(mCodecLooper, desiredMime, true /*encoder*/);
1315 } else {
1316 mCodec = MediaCodec::CreateByComponentName(mCodecLooper, hevcName);
1317 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001318 if (mCodec == nullptr) {
1319 ALOGE("%s: Failed to create codec for %s", __FUNCTION__, desiredMime);
1320 return NO_INIT;
1321 }
1322
1323 // Create Looper and handler for Codec callback.
1324 mCodecCallbackHandler = new CodecCallbackHandler(this);
1325 if (mCodecCallbackHandler == nullptr) {
1326 ALOGE("%s: Failed to create codec callback handler", __FUNCTION__);
1327 return NO_MEMORY;
1328 }
1329 mCallbackLooper = new ALooper;
1330 mCallbackLooper->setName("Camera3-HeicComposite-MediaCodecCallbackLooper");
1331 res = mCallbackLooper->start(
1332 false, // runOnCallingThread
1333 false, // canCallJava
1334 PRIORITY_AUDIO);
1335 if (res != OK) {
1336 ALOGE("%s: Failed to start media callback looper: %s (%d)",
1337 __FUNCTION__, strerror(-res), res);
1338 return NO_INIT;
1339 }
1340 mCallbackLooper->registerHandler(mCodecCallbackHandler);
1341
1342 mAsyncNotify = new AMessage(kWhatCallbackNotify, mCodecCallbackHandler);
1343 res = mCodec->setCallback(mAsyncNotify);
1344 if (res != OK) {
1345 ALOGE("%s: Failed to set MediaCodec callback: %s (%d)", __FUNCTION__,
1346 strerror(-res), res);
1347 return res;
1348 }
1349
1350 // Create output format and configure the Codec.
1351 sp<AMessage> outputFormat = new AMessage();
1352 outputFormat->setString(KEY_MIME, desiredMime);
1353 outputFormat->setInt32(KEY_BITRATE_MODE, BITRATE_MODE_CQ);
1354 outputFormat->setInt32(KEY_QUALITY, kDefaultJpegQuality);
1355 // Ask codec to skip timestamp check and encode all frames.
Chong Zhang70bfcec2019-03-18 12:52:28 -07001356 outputFormat->setInt64(KEY_MAX_PTS_GAP_TO_ENCODER, kNoFrameDropMaxPtsGap);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001357
1358 int32_t gridWidth, gridHeight, gridRows, gridCols;
1359 if (useGrid || mUseHeic) {
1360 gridWidth = HeicEncoderInfoManager::kGridWidth;
1361 gridHeight = HeicEncoderInfoManager::kGridHeight;
1362 gridRows = (height + gridHeight - 1)/gridHeight;
1363 gridCols = (width + gridWidth - 1)/gridWidth;
1364
1365 if (mUseHeic) {
1366 outputFormat->setInt32(KEY_TILE_WIDTH, gridWidth);
1367 outputFormat->setInt32(KEY_TILE_HEIGHT, gridHeight);
1368 outputFormat->setInt32(KEY_GRID_COLUMNS, gridCols);
1369 outputFormat->setInt32(KEY_GRID_ROWS, gridRows);
1370 }
1371
1372 } else {
1373 gridWidth = width;
1374 gridHeight = height;
1375 gridRows = 1;
1376 gridCols = 1;
1377 }
1378
1379 outputFormat->setInt32(KEY_WIDTH, !useGrid ? width : gridWidth);
1380 outputFormat->setInt32(KEY_HEIGHT, !useGrid ? height : gridHeight);
1381 outputFormat->setInt32(KEY_I_FRAME_INTERVAL, 0);
1382 outputFormat->setInt32(KEY_COLOR_FORMAT,
1383 useGrid ? COLOR_FormatYUV420Flexible : COLOR_FormatSurface);
Shuzhen Wang0ca81522019-08-30 14:15:16 -07001384 outputFormat->setInt32(KEY_FRAME_RATE, useGrid ? gridRows * gridCols : kNoGridOpRate);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001385 // This only serves as a hint to encoder when encoding is not real-time.
1386 outputFormat->setInt32(KEY_OPERATING_RATE, useGrid ? kGridOpRate : kNoGridOpRate);
1387
1388 res = mCodec->configure(outputFormat, nullptr /*nativeWindow*/,
1389 nullptr /*crypto*/, CONFIGURE_FLAG_ENCODE);
1390 if (res != OK) {
1391 ALOGE("%s: Failed to configure codec: %s (%d)", __FUNCTION__,
1392 strerror(-res), res);
1393 return res;
1394 }
1395
1396 mGridWidth = gridWidth;
1397 mGridHeight = gridHeight;
1398 mGridRows = gridRows;
1399 mGridCols = gridCols;
1400 mUseGrid = useGrid;
1401 mOutputWidth = width;
1402 mOutputHeight = height;
1403 mAppSegmentMaxSize = calcAppSegmentMaxSize(cameraDevice->info());
Susmitha Gummallae911f2e2020-11-23 09:57:03 -08001404 mMaxHeicBufferSize =
1405 ALIGN(mOutputWidth, HeicEncoderInfoManager::kGridWidth) *
1406 ALIGN(mOutputHeight, HeicEncoderInfoManager::kGridHeight) * 3 / 2 + mAppSegmentMaxSize;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001407
1408 return OK;
1409}
1410
1411void HeicCompositeStream::deinitCodec() {
1412 ALOGV("%s", __FUNCTION__);
1413 if (mCodec != nullptr) {
1414 mCodec->stop();
1415 mCodec->release();
1416 mCodec.clear();
1417 }
1418
1419 if (mCodecLooper != nullptr) {
1420 mCodecLooper->stop();
1421 mCodecLooper.clear();
1422 }
1423
1424 if (mCallbackLooper != nullptr) {
1425 mCallbackLooper->stop();
1426 mCallbackLooper.clear();
1427 }
1428
1429 mAsyncNotify.clear();
1430 mFormat.clear();
1431}
1432
1433// Return the size of the complete list of app segment, 0 indicates failure
1434size_t HeicCompositeStream::findAppSegmentsSize(const uint8_t* appSegmentBuffer,
1435 size_t maxSize, size_t *app1SegmentSize) {
1436 if (appSegmentBuffer == nullptr || app1SegmentSize == nullptr) {
1437 ALOGE("%s: Invalid input appSegmentBuffer %p, app1SegmentSize %p",
1438 __FUNCTION__, appSegmentBuffer, app1SegmentSize);
1439 return 0;
1440 }
1441
1442 size_t expectedSize = 0;
1443 // First check for EXIF transport header at the end of the buffer
Jayant Chowdharyc67af1b2022-04-07 18:05:04 +00001444 const uint8_t *header = appSegmentBuffer + (maxSize - sizeof(CameraBlob));
1445 const CameraBlob *blob = (const CameraBlob*)(header);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001446 if (blob->blobId != CameraBlobId::JPEG_APP_SEGMENTS) {
Jayant Chowdharyc67af1b2022-04-07 18:05:04 +00001447 ALOGE("%s: Invalid EXIF blobId %d", __FUNCTION__, blob->blobId);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001448 return 0;
1449 }
1450
Jayant Chowdharyc67af1b2022-04-07 18:05:04 +00001451 expectedSize = blob->blobSizeBytes;
1452 if (expectedSize == 0 || expectedSize > maxSize - sizeof(CameraBlob)) {
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001453 ALOGE("%s: Invalid blobSize %zu.", __FUNCTION__, expectedSize);
1454 return 0;
1455 }
1456
1457 uint32_t totalSize = 0;
1458
1459 // Verify APP1 marker (mandatory)
1460 uint8_t app1Marker[] = {0xFF, 0xE1};
1461 if (memcmp(appSegmentBuffer, app1Marker, sizeof(app1Marker))) {
1462 ALOGE("%s: Invalid APP1 marker: %x, %x", __FUNCTION__,
1463 appSegmentBuffer[0], appSegmentBuffer[1]);
1464 return 0;
1465 }
1466 totalSize += sizeof(app1Marker);
1467
1468 uint16_t app1Size = (static_cast<uint16_t>(appSegmentBuffer[totalSize]) << 8) +
1469 appSegmentBuffer[totalSize+1];
1470 totalSize += app1Size;
1471
1472 ALOGV("%s: Expected APP segments size %zu, APP1 segment size %u",
1473 __FUNCTION__, expectedSize, app1Size);
1474 while (totalSize < expectedSize) {
1475 if (appSegmentBuffer[totalSize] != 0xFF ||
1476 appSegmentBuffer[totalSize+1] <= 0xE1 ||
1477 appSegmentBuffer[totalSize+1] > 0xEF) {
1478 // Invalid APPn marker
1479 ALOGE("%s: Invalid APPn marker: %x, %x", __FUNCTION__,
1480 appSegmentBuffer[totalSize], appSegmentBuffer[totalSize+1]);
1481 return 0;
1482 }
1483 totalSize += 2;
1484
1485 uint16_t appnSize = (static_cast<uint16_t>(appSegmentBuffer[totalSize]) << 8) +
1486 appSegmentBuffer[totalSize+1];
1487 totalSize += appnSize;
1488 }
1489
1490 if (totalSize != expectedSize) {
1491 ALOGE("%s: Invalid JPEG APP segments: totalSize %u vs expected size %zu",
1492 __FUNCTION__, totalSize, expectedSize);
1493 return 0;
1494 }
1495
1496 *app1SegmentSize = app1Size + sizeof(app1Marker);
1497 return expectedSize;
1498}
1499
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001500status_t HeicCompositeStream::copyOneYuvTile(sp<MediaCodecBuffer>& codecBuffer,
1501 const CpuConsumer::LockedBuffer& yuvBuffer,
1502 size_t top, size_t left, size_t width, size_t height) {
1503 ATRACE_CALL();
1504
1505 // Get stride information for codecBuffer
1506 sp<ABuffer> imageData;
1507 if (!codecBuffer->meta()->findBuffer("image-data", &imageData)) {
1508 ALOGE("%s: Codec input buffer is not for image data!", __FUNCTION__);
1509 return BAD_VALUE;
1510 }
1511 if (imageData->size() != sizeof(MediaImage2)) {
1512 ALOGE("%s: Invalid codec input image size %zu, expected %zu",
1513 __FUNCTION__, imageData->size(), sizeof(MediaImage2));
1514 return BAD_VALUE;
1515 }
1516 MediaImage2* imageInfo = reinterpret_cast<MediaImage2*>(imageData->data());
1517 if (imageInfo->mType != MediaImage2::MEDIA_IMAGE_TYPE_YUV ||
1518 imageInfo->mBitDepth != 8 ||
1519 imageInfo->mBitDepthAllocated != 8 ||
1520 imageInfo->mNumPlanes != 3) {
1521 ALOGE("%s: Invalid codec input image info: mType %d, mBitDepth %d, "
1522 "mBitDepthAllocated %d, mNumPlanes %d!", __FUNCTION__,
1523 imageInfo->mType, imageInfo->mBitDepth,
1524 imageInfo->mBitDepthAllocated, imageInfo->mNumPlanes);
1525 return BAD_VALUE;
1526 }
1527
1528 ALOGV("%s: yuvBuffer chromaStep %d, chromaStride %d",
1529 __FUNCTION__, yuvBuffer.chromaStep, yuvBuffer.chromaStride);
1530 ALOGV("%s: U offset %u, V offset %u, U rowInc %d, V rowInc %d, U colInc %d, V colInc %d",
1531 __FUNCTION__, imageInfo->mPlane[MediaImage2::U].mOffset,
1532 imageInfo->mPlane[MediaImage2::V].mOffset,
1533 imageInfo->mPlane[MediaImage2::U].mRowInc,
1534 imageInfo->mPlane[MediaImage2::V].mRowInc,
1535 imageInfo->mPlane[MediaImage2::U].mColInc,
1536 imageInfo->mPlane[MediaImage2::V].mColInc);
1537
1538 // Y
1539 for (auto row = top; row < top+height; row++) {
1540 uint8_t *dst = codecBuffer->data() + imageInfo->mPlane[MediaImage2::Y].mOffset +
1541 imageInfo->mPlane[MediaImage2::Y].mRowInc * (row - top);
Shuzhen Wang219c2992019-02-15 17:24:28 -08001542 mFnCopyRow(yuvBuffer.data+row*yuvBuffer.stride+left, dst, width);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001543 }
1544
1545 // U is Cb, V is Cr
1546 bool codecUPlaneFirst = imageInfo->mPlane[MediaImage2::V].mOffset >
1547 imageInfo->mPlane[MediaImage2::U].mOffset;
1548 uint32_t codecUvOffsetDiff = codecUPlaneFirst ?
1549 imageInfo->mPlane[MediaImage2::V].mOffset - imageInfo->mPlane[MediaImage2::U].mOffset :
1550 imageInfo->mPlane[MediaImage2::U].mOffset - imageInfo->mPlane[MediaImage2::V].mOffset;
1551 bool isCodecUvSemiplannar = (codecUvOffsetDiff == 1) &&
1552 (imageInfo->mPlane[MediaImage2::U].mRowInc ==
1553 imageInfo->mPlane[MediaImage2::V].mRowInc) &&
1554 (imageInfo->mPlane[MediaImage2::U].mColInc == 2) &&
1555 (imageInfo->mPlane[MediaImage2::V].mColInc == 2);
1556 bool isCodecUvPlannar =
1557 ((codecUPlaneFirst && codecUvOffsetDiff >=
1558 imageInfo->mPlane[MediaImage2::U].mRowInc * imageInfo->mHeight/2) ||
1559 ((!codecUPlaneFirst && codecUvOffsetDiff >=
1560 imageInfo->mPlane[MediaImage2::V].mRowInc * imageInfo->mHeight/2))) &&
1561 imageInfo->mPlane[MediaImage2::U].mColInc == 1 &&
1562 imageInfo->mPlane[MediaImage2::V].mColInc == 1;
1563 bool cameraUPlaneFirst = yuvBuffer.dataCr > yuvBuffer.dataCb;
1564
1565 if (isCodecUvSemiplannar && yuvBuffer.chromaStep == 2 &&
1566 (codecUPlaneFirst == cameraUPlaneFirst)) {
1567 // UV semiplannar
1568 // The chrome plane could be either Cb first, or Cr first. Take the
1569 // smaller address.
1570 uint8_t *src = std::min(yuvBuffer.dataCb, yuvBuffer.dataCr);
1571 MediaImage2::PlaneIndex dstPlane = codecUvOffsetDiff > 0 ? MediaImage2::U : MediaImage2::V;
1572 for (auto row = top/2; row < (top+height)/2; row++) {
1573 uint8_t *dst = codecBuffer->data() + imageInfo->mPlane[dstPlane].mOffset +
1574 imageInfo->mPlane[dstPlane].mRowInc * (row - top/2);
Shuzhen Wang219c2992019-02-15 17:24:28 -08001575 mFnCopyRow(src+row*yuvBuffer.chromaStride+left, dst, width);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001576 }
1577 } else if (isCodecUvPlannar && yuvBuffer.chromaStep == 1) {
1578 // U plane
1579 for (auto row = top/2; row < (top+height)/2; row++) {
1580 uint8_t *dst = codecBuffer->data() + imageInfo->mPlane[MediaImage2::U].mOffset +
1581 imageInfo->mPlane[MediaImage2::U].mRowInc * (row - top/2);
Shuzhen Wang219c2992019-02-15 17:24:28 -08001582 mFnCopyRow(yuvBuffer.dataCb+row*yuvBuffer.chromaStride+left/2, dst, width/2);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001583 }
1584
1585 // V plane
1586 for (auto row = top/2; row < (top+height)/2; row++) {
1587 uint8_t *dst = codecBuffer->data() + imageInfo->mPlane[MediaImage2::V].mOffset +
1588 imageInfo->mPlane[MediaImage2::V].mRowInc * (row - top/2);
Shuzhen Wang219c2992019-02-15 17:24:28 -08001589 mFnCopyRow(yuvBuffer.dataCr+row*yuvBuffer.chromaStride+left/2, dst, width/2);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001590 }
1591 } else {
Shuzhen Wang219c2992019-02-15 17:24:28 -08001592 // Convert between semiplannar and plannar, or when UV orders are
1593 // different.
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001594 uint8_t *dst = codecBuffer->data();
1595 for (auto row = top/2; row < (top+height)/2; row++) {
1596 for (auto col = left/2; col < (left+width)/2; col++) {
1597 // U/Cb
1598 int32_t dstIndex = imageInfo->mPlane[MediaImage2::U].mOffset +
1599 imageInfo->mPlane[MediaImage2::U].mRowInc * (row - top/2) +
1600 imageInfo->mPlane[MediaImage2::U].mColInc * (col - left/2);
1601 int32_t srcIndex = row * yuvBuffer.chromaStride + yuvBuffer.chromaStep * col;
1602 dst[dstIndex] = yuvBuffer.dataCb[srcIndex];
1603
1604 // V/Cr
1605 dstIndex = imageInfo->mPlane[MediaImage2::V].mOffset +
1606 imageInfo->mPlane[MediaImage2::V].mRowInc * (row - top/2) +
1607 imageInfo->mPlane[MediaImage2::V].mColInc * (col - left/2);
1608 srcIndex = row * yuvBuffer.chromaStride + yuvBuffer.chromaStep * col;
1609 dst[dstIndex] = yuvBuffer.dataCr[srcIndex];
1610 }
1611 }
1612 }
1613 return OK;
1614}
1615
Colin Cross14900c92023-01-13 14:50:17 -08001616void HeicCompositeStream::initCopyRowFunction([[maybe_unused]] int32_t width)
Shuzhen Wang219c2992019-02-15 17:24:28 -08001617{
1618 using namespace libyuv;
1619
1620 mFnCopyRow = CopyRow_C;
1621#if defined(HAS_COPYROW_SSE2)
1622 if (TestCpuFlag(kCpuHasSSE2)) {
1623 mFnCopyRow = IS_ALIGNED(width, 32) ? CopyRow_SSE2 : CopyRow_Any_SSE2;
1624 }
1625#endif
1626#if defined(HAS_COPYROW_AVX)
1627 if (TestCpuFlag(kCpuHasAVX)) {
1628 mFnCopyRow = IS_ALIGNED(width, 64) ? CopyRow_AVX : CopyRow_Any_AVX;
1629 }
1630#endif
1631#if defined(HAS_COPYROW_ERMS)
1632 if (TestCpuFlag(kCpuHasERMS)) {
1633 mFnCopyRow = CopyRow_ERMS;
1634 }
1635#endif
1636#if defined(HAS_COPYROW_NEON)
1637 if (TestCpuFlag(kCpuHasNEON)) {
1638 mFnCopyRow = IS_ALIGNED(width, 32) ? CopyRow_NEON : CopyRow_Any_NEON;
1639 }
1640#endif
1641#if defined(HAS_COPYROW_MIPS)
1642 if (TestCpuFlag(kCpuHasMIPS)) {
1643 mFnCopyRow = CopyRow_MIPS;
1644 }
1645#endif
1646}
1647
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001648size_t HeicCompositeStream::calcAppSegmentMaxSize(const CameraMetadata& info) {
1649 camera_metadata_ro_entry_t entry = info.find(ANDROID_HEIC_INFO_MAX_JPEG_APP_SEGMENTS_COUNT);
1650 size_t maxAppsSegment = 1;
1651 if (entry.count > 0) {
1652 maxAppsSegment = entry.data.u8[0] < 1 ? 1 :
1653 entry.data.u8[0] > 16 ? 16 : entry.data.u8[0];
1654 }
Jayant Chowdharyc67af1b2022-04-07 18:05:04 +00001655 return maxAppsSegment * (2 + 0xFFFF) + sizeof(CameraBlob);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001656}
1657
Shuzhen Wang62f49ed2019-09-04 14:07:53 -07001658void HeicCompositeStream::updateCodecQualityLocked(int32_t quality) {
1659 if (quality != mQuality) {
1660 sp<AMessage> qualityParams = new AMessage;
1661 qualityParams->setInt32(PARAMETER_KEY_VIDEO_BITRATE, quality);
1662 status_t res = mCodec->setParameters(qualityParams);
1663 if (res != OK) {
1664 ALOGE("%s: Failed to set codec quality: %s (%d)",
1665 __FUNCTION__, strerror(-res), res);
1666 } else {
1667 mQuality = quality;
1668 }
1669 }
1670}
1671
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001672bool HeicCompositeStream::threadLoop() {
Shuzhen Wange8675782019-12-05 09:12:14 -08001673 int64_t frameNumber = -1;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001674 bool newInputAvailable = false;
1675
1676 {
1677 Mutex::Autolock l(mMutex);
1678 if (mErrorState) {
1679 // In case we landed in error state, return any pending buffers and
1680 // halt all further processing.
1681 compilePendingInputLocked();
Michael Gonzalezb5986a32019-10-09 15:38:17 -07001682 releaseInputFramesLocked();
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001683 return false;
1684 }
1685
1686
1687 while (!newInputAvailable) {
1688 compilePendingInputLocked();
Shuzhen Wange8675782019-12-05 09:12:14 -08001689 newInputAvailable = getNextReadyInputLocked(&frameNumber);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001690
1691 if (!newInputAvailable) {
Shuzhen Wange8675782019-12-05 09:12:14 -08001692 auto failingFrameNumber = getNextFailingInputLocked();
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001693 if (failingFrameNumber >= 0) {
Shuzhen Wange8675782019-12-05 09:12:14 -08001694 releaseInputFrameLocked(failingFrameNumber,
1695 &mPendingInputFrames[failingFrameNumber]);
1696
1697 // It's okay to remove the entry from mPendingInputFrames
1698 // because:
1699 // 1. Only one internal stream (main input) is critical in
1700 // backing the output stream.
1701 // 2. If captureResult/appSegment arrives after the entry is
1702 // removed, they are simply skipped.
1703 mPendingInputFrames.erase(failingFrameNumber);
1704 if (mPendingInputFrames.size() == 0) {
1705 markTrackerIdle();
1706 }
1707 return true;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001708 }
1709
1710 auto ret = mInputReadyCondition.waitRelative(mMutex, kWaitDuration);
1711 if (ret == TIMED_OUT) {
1712 return true;
1713 } else if (ret != OK) {
1714 ALOGE("%s: Timed wait on condition failed: %s (%d)", __FUNCTION__,
1715 strerror(-ret), ret);
1716 return false;
1717 }
1718 }
1719 }
1720 }
1721
Shuzhen Wange8675782019-12-05 09:12:14 -08001722 auto res = processInputFrame(frameNumber, mPendingInputFrames[frameNumber]);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001723 Mutex::Autolock l(mMutex);
1724 if (res != OK) {
Shuzhen Wange8675782019-12-05 09:12:14 -08001725 ALOGE("%s: Failed processing frame with timestamp: %" PRIu64 ", frameNumber: %"
1726 PRId64 ": %s (%d)", __FUNCTION__, mPendingInputFrames[frameNumber].timestamp,
1727 frameNumber, strerror(-res), res);
1728 mPendingInputFrames[frameNumber].error = true;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001729 }
1730
Michael Gonzalezb5986a32019-10-09 15:38:17 -07001731 releaseInputFramesLocked();
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001732
1733 return true;
1734}
1735
Shuzhen Wange8675782019-12-05 09:12:14 -08001736void HeicCompositeStream::flagAnExifErrorFrameNumber(int64_t frameNumber) {
1737 Mutex::Autolock l(mMutex);
1738 mExifErrorFrameNumbers.emplace(frameNumber);
1739 mInputReadyCondition.signal();
1740}
1741
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001742bool HeicCompositeStream::onStreamBufferError(const CaptureResultExtras& resultExtras) {
1743 bool res = false;
Shuzhen Wange8675782019-12-05 09:12:14 -08001744 int64_t frameNumber = resultExtras.frameNumber;
1745
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001746 // Buffer errors concerning internal composite streams should not be directly visible to
1747 // camera clients. They must only receive a single buffer error with the public composite
1748 // stream id.
Shuzhen Wange8675782019-12-05 09:12:14 -08001749 if (resultExtras.errorStreamId == mAppSegmentStreamId) {
1750 ALOGV("%s: APP_SEGMENT frameNumber: %" PRId64, __FUNCTION__, frameNumber);
1751 flagAnExifErrorFrameNumber(frameNumber);
1752 res = true;
1753 } else if (resultExtras.errorStreamId == mMainImageStreamId) {
1754 ALOGV("%s: YUV frameNumber: %" PRId64, __FUNCTION__, frameNumber);
1755 flagAnErrorFrameNumber(frameNumber);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001756 res = true;
1757 }
1758
1759 return res;
1760}
1761
Shuzhen Wange7f4b462019-02-12 08:43:07 -08001762void HeicCompositeStream::onResultError(const CaptureResultExtras& resultExtras) {
1763 // For result error, since the APPS_SEGMENT buffer already contains EXIF,
1764 // simply skip using the capture result metadata to override EXIF.
1765 Mutex::Autolock l(mMutex);
1766
1767 int64_t timestamp = -1;
Shuzhen Wange8675782019-12-05 09:12:14 -08001768 for (const auto& fn : mSettingsByFrameNumber) {
Shuzhen Wange7f4b462019-02-12 08:43:07 -08001769 if (fn.first == resultExtras.frameNumber) {
Shuzhen Wange8675782019-12-05 09:12:14 -08001770 timestamp = fn.second.timestamp;
Shuzhen Wange7f4b462019-02-12 08:43:07 -08001771 break;
1772 }
1773 }
1774 if (timestamp == -1) {
1775 for (const auto& inputFrame : mPendingInputFrames) {
Shuzhen Wange8675782019-12-05 09:12:14 -08001776 if (inputFrame.first == resultExtras.frameNumber) {
1777 timestamp = inputFrame.second.timestamp;
Shuzhen Wange7f4b462019-02-12 08:43:07 -08001778 break;
1779 }
1780 }
1781 }
1782
1783 if (timestamp == -1) {
1784 ALOGE("%s: Failed to find shutter timestamp for result error!", __FUNCTION__);
1785 return;
1786 }
1787
1788 mCaptureResults.emplace(timestamp, std::make_tuple(resultExtras.frameNumber, CameraMetadata()));
Shuzhen Wange8675782019-12-05 09:12:14 -08001789 ALOGV("%s: timestamp %" PRId64 ", frameNumber %" PRId64, __FUNCTION__,
1790 timestamp, resultExtras.frameNumber);
Shuzhen Wange7f4b462019-02-12 08:43:07 -08001791 mInputReadyCondition.signal();
1792}
1793
Shuzhen Wange8675782019-12-05 09:12:14 -08001794void HeicCompositeStream::onRequestError(const CaptureResultExtras& resultExtras) {
1795 auto frameNumber = resultExtras.frameNumber;
1796 ALOGV("%s: frameNumber: %" PRId64, __FUNCTION__, frameNumber);
1797 Mutex::Autolock l(mMutex);
1798 auto numRequests = mSettingsByFrameNumber.erase(frameNumber);
1799 if (numRequests == 0) {
1800 // Pending request has been populated into mPendingInputFrames
1801 mErrorFrameNumbers.emplace(frameNumber);
1802 mInputReadyCondition.signal();
1803 } else {
1804 // REQUEST_ERROR was received without onShutter.
1805 }
1806}
1807
1808void HeicCompositeStream::markTrackerIdle() {
1809 sp<StatusTracker> statusTracker = mStatusTracker.promote();
1810 if (statusTracker != nullptr) {
1811 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
1812 ALOGV("%s: Mark component as idle", __FUNCTION__);
1813 }
1814}
1815
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001816void HeicCompositeStream::CodecCallbackHandler::onMessageReceived(const sp<AMessage> &msg) {
1817 sp<HeicCompositeStream> parent = mParent.promote();
1818 if (parent == nullptr) return;
1819
1820 switch (msg->what()) {
1821 case kWhatCallbackNotify: {
1822 int32_t cbID;
1823 if (!msg->findInt32("callbackID", &cbID)) {
1824 ALOGE("kWhatCallbackNotify: callbackID is expected.");
1825 break;
1826 }
1827
1828 ALOGV("kWhatCallbackNotify: cbID = %d", cbID);
1829
1830 switch (cbID) {
1831 case MediaCodec::CB_INPUT_AVAILABLE: {
1832 int32_t index;
1833 if (!msg->findInt32("index", &index)) {
1834 ALOGE("CB_INPUT_AVAILABLE: index is expected.");
1835 break;
1836 }
1837 parent->onHeicInputFrameAvailable(index);
1838 break;
1839 }
1840
1841 case MediaCodec::CB_OUTPUT_AVAILABLE: {
1842 int32_t index;
1843 size_t offset;
1844 size_t size;
1845 int64_t timeUs;
1846 int32_t flags;
1847
1848 if (!msg->findInt32("index", &index)) {
1849 ALOGE("CB_OUTPUT_AVAILABLE: index is expected.");
1850 break;
1851 }
1852 if (!msg->findSize("offset", &offset)) {
1853 ALOGE("CB_OUTPUT_AVAILABLE: offset is expected.");
1854 break;
1855 }
1856 if (!msg->findSize("size", &size)) {
1857 ALOGE("CB_OUTPUT_AVAILABLE: size is expected.");
1858 break;
1859 }
1860 if (!msg->findInt64("timeUs", &timeUs)) {
1861 ALOGE("CB_OUTPUT_AVAILABLE: timeUs is expected.");
1862 break;
1863 }
1864 if (!msg->findInt32("flags", &flags)) {
1865 ALOGE("CB_OUTPUT_AVAILABLE: flags is expected.");
1866 break;
1867 }
1868
1869 CodecOutputBufferInfo bufferInfo = {
1870 index,
1871 (int32_t)offset,
1872 (int32_t)size,
1873 timeUs,
1874 (uint32_t)flags};
1875
1876 parent->onHeicOutputFrameAvailable(bufferInfo);
1877 break;
1878 }
1879
1880 case MediaCodec::CB_OUTPUT_FORMAT_CHANGED: {
1881 sp<AMessage> format;
1882 if (!msg->findMessage("format", &format)) {
1883 ALOGE("CB_OUTPUT_FORMAT_CHANGED: format is expected.");
1884 break;
1885 }
Chong Zhang860eff12019-09-16 16:15:00 -07001886 // Here format is MediaCodec's internal copy of output format.
1887 // Make a copy since onHeicFormatChanged() might modify it.
1888 sp<AMessage> formatCopy;
1889 if (format != nullptr) {
1890 formatCopy = format->dup();
1891 }
1892 parent->onHeicFormatChanged(formatCopy);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001893 break;
1894 }
1895
1896 case MediaCodec::CB_ERROR: {
1897 status_t err;
1898 int32_t actionCode;
1899 AString detail;
1900 if (!msg->findInt32("err", &err)) {
1901 ALOGE("CB_ERROR: err is expected.");
1902 break;
1903 }
1904 if (!msg->findInt32("action", &actionCode)) {
1905 ALOGE("CB_ERROR: action is expected.");
1906 break;
1907 }
1908 msg->findString("detail", &detail);
1909 ALOGE("Codec reported error(0x%x), actionCode(%d), detail(%s)",
1910 err, actionCode, detail.c_str());
1911
1912 parent->onHeicCodecError();
1913 break;
1914 }
1915
1916 default: {
1917 ALOGE("kWhatCallbackNotify: callbackID(%d) is unexpected.", cbID);
1918 break;
1919 }
1920 }
1921 break;
1922 }
1923
1924 default:
1925 ALOGE("shouldn't be here");
1926 break;
1927 }
1928}
1929
1930}; // namespace camera3
1931}; // namespace android