blob: 294a9082b2ddb8ab8bb959ac72cb1e38feea8440 [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,
Syed Haqc8a536d2023-05-09 12:14:52 -0700123 int /*streamSetId*/, bool /*isShared*/, int32_t colorSpace,
Shuzhen Wangbce53db2022-12-03 00:38:20 +0000124 int64_t /*dynamicProfile*/, int64_t /*streamUseCase*/, bool useReadoutTimestamp) {
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800125 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,
Shuzhen Wangbce53db2022-12-03 00:38:20 +0000150 sensorPixelModesUsed, surfaceIds, camera3::CAMERA3_STREAM_SET_ID_INVALID,
151 /*isShared*/false, /*isMultiResolution*/false,
152 /*consumerUsage*/0, ANDROID_REQUEST_AVAILABLE_DYNAMIC_RANGE_PROFILES_MAP_STANDARD,
153 ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_DEFAULT,
154 OutputConfiguration::TIMESTAMP_BASE_DEFAULT,
155 OutputConfiguration::MIRROR_MODE_AUTO,
Syed Haqc8a536d2023-05-09 12:14:52 -0700156 colorSpace,
Shuzhen Wangbce53db2022-12-03 00:38:20 +0000157 useReadoutTimestamp);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800158 if (res == OK) {
159 mAppSegmentSurfaceId = (*surfaceIds)[0];
160 } else {
161 ALOGE("%s: Failed to create JPEG App segment stream: %s (%d)", __FUNCTION__,
162 strerror(-res), res);
163 return res;
164 }
165
166 if (!mUseGrid) {
167 res = mCodec->createInputSurface(&producer);
168 if (res != OK) {
169 ALOGE("%s: Failed to create input surface for Heic codec: %s (%d)",
170 __FUNCTION__, strerror(-res), res);
171 return res;
172 }
173 } else {
174 BufferQueue::createBufferQueue(&producer, &consumer);
175 mMainImageConsumer = new CpuConsumer(consumer, 1);
176 mMainImageConsumer->setFrameAvailableListener(this);
177 mMainImageConsumer->setName(String8("Camera3-HeicComposite-HevcInputYUVStream"));
178 }
179 mMainImageSurface = new Surface(producer);
180
181 res = mCodec->start();
182 if (res != OK) {
183 ALOGE("%s: Failed to start codec: %s (%d)", __FUNCTION__,
184 strerror(-res), res);
185 return res;
186 }
187
188 std::vector<int> sourceSurfaceId;
189 //Use YUV_888 format if framework tiling is needed.
190 int srcStreamFmt = mUseGrid ? HAL_PIXEL_FORMAT_YCbCr_420_888 :
191 HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED;
192 res = device->createStream(mMainImageSurface, width, height, srcStreamFmt, kHeifDataSpace,
Shuzhen Wangbce53db2022-12-03 00:38:20 +0000193 rotation, id, physicalCameraId, sensorPixelModesUsed, &sourceSurfaceId,
194 camera3::CAMERA3_STREAM_SET_ID_INVALID, /*isShared*/false, /*isMultiResolution*/false,
195 /*consumerUsage*/0, ANDROID_REQUEST_AVAILABLE_DYNAMIC_RANGE_PROFILES_MAP_STANDARD,
196 ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_DEFAULT,
197 OutputConfiguration::TIMESTAMP_BASE_DEFAULT,
198 OutputConfiguration::MIRROR_MODE_AUTO,
Syed Haqc8a536d2023-05-09 12:14:52 -0700199 colorSpace,
Shuzhen Wangbce53db2022-12-03 00:38:20 +0000200 useReadoutTimestamp);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800201 if (res == OK) {
202 mMainImageSurfaceId = sourceSurfaceId[0];
203 mMainImageStreamId = *id;
204 } else {
205 ALOGE("%s: Failed to create main image stream: %s (%d)", __FUNCTION__,
206 strerror(-res), res);
207 return res;
208 }
209
210 mOutputSurface = consumers[0];
Shuzhen Wange8675782019-12-05 09:12:14 -0800211 res = registerCompositeStreamListener(mMainImageStreamId);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800212 if (res != OK) {
Shuzhen Wange8675782019-12-05 09:12:14 -0800213 ALOGE("%s: Failed to register HAL main image stream: %s (%d)", __FUNCTION__,
214 strerror(-res), res);
215 return res;
216 }
217
218 res = registerCompositeStreamListener(mAppSegmentStreamId);
219 if (res != OK) {
220 ALOGE("%s: Failed to register HAL app segment stream: %s (%d)", __FUNCTION__,
221 strerror(-res), res);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800222 return res;
223 }
224
Shuzhen Wang219c2992019-02-15 17:24:28 -0800225 initCopyRowFunction(width);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800226 return res;
227}
228
229status_t HeicCompositeStream::deleteInternalStreams() {
230 requestExit();
231 auto res = join();
232 if (res != OK) {
233 ALOGE("%s: Failed to join with the main processing thread: %s (%d)", __FUNCTION__,
234 strerror(-res), res);
235 }
236
237 deinitCodec();
238
239 if (mAppSegmentStreamId >= 0) {
Emilian Peevc0fe54c2020-03-11 14:05:07 -0700240 // Camera devices may not be valid after switching to offline mode.
241 // In this case, all offline streams including internal composite streams
242 // are managed and released by the offline session.
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800243 sp<CameraDeviceBase> device = mDevice.promote();
Emilian Peevc0fe54c2020-03-11 14:05:07 -0700244 if (device.get() != nullptr) {
245 res = device->deleteStream(mAppSegmentStreamId);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800246 }
247
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800248 mAppSegmentStreamId = -1;
249 }
250
Shuzhen Wang2c545042019-02-07 10:27:35 -0800251 if (mOutputSurface != nullptr) {
252 mOutputSurface->disconnect(NATIVE_WINDOW_API_CAMERA);
253 mOutputSurface.clear();
254 }
Shuzhen Wange8675782019-12-05 09:12:14 -0800255
256 sp<StatusTracker> statusTracker = mStatusTracker.promote();
257 if (statusTracker != nullptr && mStatusId != StatusTracker::NO_STATUS_ID) {
258 statusTracker->removeComponent(mStatusId);
259 mStatusId = StatusTracker::NO_STATUS_ID;
260 }
261
262 if (mPendingInputFrames.size() > 0) {
263 ALOGW("%s: mPendingInputFrames has %zu stale entries",
264 __FUNCTION__, mPendingInputFrames.size());
265 mPendingInputFrames.clear();
266 }
267
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800268 return res;
269}
270
271void HeicCompositeStream::onBufferReleased(const BufferInfo& bufferInfo) {
272 Mutex::Autolock l(mMutex);
273
274 if (bufferInfo.mError) return;
275
Shuzhen Wange8675782019-12-05 09:12:14 -0800276 if (bufferInfo.mStreamId == mMainImageStreamId) {
277 mMainImageFrameNumbers.push(bufferInfo.mFrameNumber);
278 mCodecOutputBufferFrameNumbers.push(bufferInfo.mFrameNumber);
279 ALOGV("%s: [%" PRId64 "]: Adding main image frame number (%zu frame numbers in total)",
280 __FUNCTION__, bufferInfo.mFrameNumber, mMainImageFrameNumbers.size());
281 } else if (bufferInfo.mStreamId == mAppSegmentStreamId) {
282 mAppSegmentFrameNumbers.push(bufferInfo.mFrameNumber);
283 ALOGV("%s: [%" PRId64 "]: Adding app segment frame number (%zu frame numbers in total)",
284 __FUNCTION__, bufferInfo.mFrameNumber, mAppSegmentFrameNumbers.size());
285 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800286}
287
288// We need to get the settings early to handle the case where the codec output
289// arrives earlier than result metadata.
290void HeicCompositeStream::onBufferRequestForFrameNumber(uint64_t frameNumber, int streamId,
291 const CameraMetadata& settings) {
292 ATRACE_ASYNC_BEGIN("HEIC capture", frameNumber);
293
294 Mutex::Autolock l(mMutex);
295 if (mErrorState || (streamId != getStreamId())) {
296 return;
297 }
298
299 mPendingCaptureResults.emplace(frameNumber, CameraMetadata());
300
301 camera_metadata_ro_entry entry;
302
303 int32_t orientation = 0;
304 entry = settings.find(ANDROID_JPEG_ORIENTATION);
305 if (entry.count == 1) {
306 orientation = entry.data.i32[0];
307 }
308
309 int32_t quality = kDefaultJpegQuality;
310 entry = settings.find(ANDROID_JPEG_QUALITY);
311 if (entry.count == 1) {
312 quality = entry.data.i32[0];
313 }
314
Shuzhen Wange8675782019-12-05 09:12:14 -0800315 mSettingsByFrameNumber[frameNumber] = {orientation, quality};
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800316}
317
318void HeicCompositeStream::onFrameAvailable(const BufferItem& item) {
319 if (item.mDataSpace == static_cast<android_dataspace>(kAppSegmentDataSpace)) {
320 ALOGV("%s: JPEG APP segments buffer with ts: %" PRIu64 " ms. arrived!",
321 __func__, ns2ms(item.mTimestamp));
322
323 Mutex::Autolock l(mMutex);
324 if (!mErrorState) {
325 mInputAppSegmentBuffers.push_back(item.mTimestamp);
326 mInputReadyCondition.signal();
327 }
328 } else if (item.mDataSpace == kHeifDataSpace) {
329 ALOGV("%s: YUV_888 buffer with ts: %" PRIu64 " ms. arrived!",
330 __func__, ns2ms(item.mTimestamp));
331
332 Mutex::Autolock l(mMutex);
333 if (!mUseGrid) {
334 ALOGE("%s: YUV_888 internal stream is only supported for HEVC tiling",
335 __FUNCTION__);
336 return;
337 }
338 if (!mErrorState) {
339 mInputYuvBuffers.push_back(item.mTimestamp);
340 mInputReadyCondition.signal();
341 }
342 } else {
343 ALOGE("%s: Unexpected data space: 0x%x", __FUNCTION__, item.mDataSpace);
344 }
345}
346
347status_t HeicCompositeStream::getCompositeStreamInfo(const OutputStreamInfo &streamInfo,
348 const CameraMetadata& ch, std::vector<OutputStreamInfo>* compositeOutput /*out*/) {
349 if (compositeOutput == nullptr) {
350 return BAD_VALUE;
351 }
352
353 compositeOutput->clear();
354
355 bool useGrid, useHeic;
356 bool isSizeSupported = isSizeSupportedByHeifEncoder(
357 streamInfo.width, streamInfo.height, &useHeic, &useGrid, nullptr);
358 if (!isSizeSupported) {
359 // Size is not supported by either encoder.
360 return OK;
361 }
362
363 compositeOutput->insert(compositeOutput->end(), 2, streamInfo);
364
365 // JPEG APPS segments Blob stream info
366 (*compositeOutput)[0].width = calcAppSegmentMaxSize(ch);
367 (*compositeOutput)[0].height = 1;
368 (*compositeOutput)[0].format = HAL_PIXEL_FORMAT_BLOB;
369 (*compositeOutput)[0].dataSpace = kAppSegmentDataSpace;
370 (*compositeOutput)[0].consumerUsage = GRALLOC_USAGE_SW_READ_OFTEN;
371
372 // YUV/IMPLEMENTATION_DEFINED stream info
373 (*compositeOutput)[1].width = streamInfo.width;
374 (*compositeOutput)[1].height = streamInfo.height;
375 (*compositeOutput)[1].format = useGrid ? HAL_PIXEL_FORMAT_YCbCr_420_888 :
376 HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED;
377 (*compositeOutput)[1].dataSpace = kHeifDataSpace;
378 (*compositeOutput)[1].consumerUsage = useHeic ? GRALLOC_USAGE_HW_IMAGE_ENCODER :
379 useGrid ? GRALLOC_USAGE_SW_READ_OFTEN : GRALLOC_USAGE_HW_VIDEO_ENCODER;
380
381 return NO_ERROR;
382}
383
384bool HeicCompositeStream::isSizeSupportedByHeifEncoder(int32_t width, int32_t height,
Chong Zhang688abaa2019-05-17 16:32:23 -0700385 bool* useHeic, bool* useGrid, int64_t* stall, AString* hevcName) {
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800386 static HeicEncoderInfoManager& heicManager = HeicEncoderInfoManager::getInstance();
Chong Zhang688abaa2019-05-17 16:32:23 -0700387 return heicManager.isSizeSupported(width, height, useHeic, useGrid, stall, hevcName);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800388}
389
390bool HeicCompositeStream::isInMemoryTempFileSupported() {
391 int memfd = syscall(__NR_memfd_create, "HEIF-try-memfd", MFD_CLOEXEC);
392 if (memfd == -1) {
393 if (errno != ENOSYS) {
394 ALOGE("%s: Failed to create tmpfs file. errno %d", __FUNCTION__, errno);
395 }
396 return false;
397 }
398 close(memfd);
399 return true;
400}
401
402void HeicCompositeStream::onHeicOutputFrameAvailable(
403 const CodecOutputBufferInfo& outputBufferInfo) {
404 Mutex::Autolock l(mMutex);
405
406 ALOGV("%s: index %d, offset %d, size %d, time %" PRId64 ", flags 0x%x",
407 __FUNCTION__, outputBufferInfo.index, outputBufferInfo.offset,
408 outputBufferInfo.size, outputBufferInfo.timeUs, outputBufferInfo.flags);
409
410 if (!mErrorState) {
411 if ((outputBufferInfo.size > 0) &&
412 ((outputBufferInfo.flags & MediaCodec::BUFFER_FLAG_CODECCONFIG) == 0)) {
413 mCodecOutputBuffers.push_back(outputBufferInfo);
414 mInputReadyCondition.signal();
415 } else {
Shuzhen Wang3d00ee52019-09-25 14:19:28 -0700416 ALOGV("%s: Releasing output buffer: size %d flags: 0x%x ", __FUNCTION__,
417 outputBufferInfo.size, outputBufferInfo.flags);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800418 mCodec->releaseOutputBuffer(outputBufferInfo.index);
419 }
420 } else {
421 mCodec->releaseOutputBuffer(outputBufferInfo.index);
422 }
423}
424
425void HeicCompositeStream::onHeicInputFrameAvailable(int32_t index) {
426 Mutex::Autolock l(mMutex);
427
428 if (!mUseGrid) {
429 ALOGE("%s: Codec YUV input mode must only be used for Hevc tiling mode", __FUNCTION__);
430 return;
431 }
432
433 mCodecInputBuffers.push_back(index);
434 mInputReadyCondition.signal();
435}
436
437void HeicCompositeStream::onHeicFormatChanged(sp<AMessage>& newFormat) {
438 if (newFormat == nullptr) {
439 ALOGE("%s: newFormat must not be null!", __FUNCTION__);
440 return;
441 }
442
443 Mutex::Autolock l(mMutex);
444
445 AString mime;
446 AString mimeHeic(MIMETYPE_IMAGE_ANDROID_HEIC);
447 newFormat->findString(KEY_MIME, &mime);
448 if (mime != mimeHeic) {
449 // For HEVC codec, below keys need to be filled out or overwritten so that the
450 // muxer can handle them as HEIC output image.
451 newFormat->setString(KEY_MIME, mimeHeic);
452 newFormat->setInt32(KEY_WIDTH, mOutputWidth);
453 newFormat->setInt32(KEY_HEIGHT, mOutputHeight);
Shuzhen Wang1403d952023-07-31 20:42:19 +0000454 }
455
456 if (mUseGrid || mUseHeic) {
457 int32_t gridRows, gridCols, tileWidth, tileHeight;
458 if (newFormat->findInt32(KEY_GRID_ROWS, &gridRows) &&
459 newFormat->findInt32(KEY_GRID_COLUMNS, &gridCols) &&
460 newFormat->findInt32(KEY_TILE_WIDTH, &tileWidth) &&
461 newFormat->findInt32(KEY_TILE_HEIGHT, &tileHeight)) {
462 mGridWidth = tileWidth;
463 mGridHeight = tileHeight;
464 mGridRows = gridRows;
465 mGridCols = gridCols;
466 } else {
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800467 newFormat->setInt32(KEY_TILE_WIDTH, mGridWidth);
468 newFormat->setInt32(KEY_TILE_HEIGHT, mGridHeight);
469 newFormat->setInt32(KEY_GRID_ROWS, mGridRows);
470 newFormat->setInt32(KEY_GRID_COLUMNS, mGridCols);
Shuzhen Wang1403d952023-07-31 20:42:19 +0000471 }
472 int32_t left, top, right, bottom;
473 if (newFormat->findRect("crop", &left, &top, &right, &bottom)) {
474 newFormat->setRect("crop", 0, 0, mOutputWidth - 1, mOutputHeight - 1);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800475 }
476 }
477 newFormat->setInt32(KEY_IS_DEFAULT, 1 /*isPrimary*/);
478
479 int32_t gridRows, gridCols;
480 if (newFormat->findInt32(KEY_GRID_ROWS, &gridRows) &&
481 newFormat->findInt32(KEY_GRID_COLUMNS, &gridCols)) {
482 mNumOutputTiles = gridRows * gridCols;
483 } else {
484 mNumOutputTiles = 1;
485 }
486
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800487 mFormat = newFormat;
Shuzhen Wang3d00ee52019-09-25 14:19:28 -0700488
489 ALOGV("%s: mNumOutputTiles is %zu", __FUNCTION__, mNumOutputTiles);
490 mInputReadyCondition.signal();
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800491}
492
493void HeicCompositeStream::onHeicCodecError() {
494 Mutex::Autolock l(mMutex);
495 mErrorState = true;
496}
497
498status_t HeicCompositeStream::configureStream() {
499 if (isRunning()) {
500 // Processing thread is already running, nothing more to do.
501 return NO_ERROR;
502 }
503
504 if (mOutputSurface.get() == nullptr) {
505 ALOGE("%s: No valid output surface set!", __FUNCTION__);
506 return NO_INIT;
507 }
508
509 auto res = mOutputSurface->connect(NATIVE_WINDOW_API_CAMERA, mProducerListener);
510 if (res != OK) {
511 ALOGE("%s: Unable to connect to native window for stream %d",
512 __FUNCTION__, mMainImageStreamId);
513 return res;
514 }
515
516 if ((res = native_window_set_buffers_format(mOutputSurface.get(), HAL_PIXEL_FORMAT_BLOB))
517 != OK) {
518 ALOGE("%s: Unable to configure stream buffer format for stream %d", __FUNCTION__,
519 mMainImageStreamId);
520 return res;
521 }
522
523 ANativeWindow *anwConsumer = mOutputSurface.get();
524 int maxConsumerBuffers;
525 if ((res = anwConsumer->query(anwConsumer, NATIVE_WINDOW_MIN_UNDEQUEUED_BUFFERS,
526 &maxConsumerBuffers)) != OK) {
527 ALOGE("%s: Unable to query consumer undequeued"
528 " buffer count for stream %d", __FUNCTION__, mMainImageStreamId);
529 return res;
530 }
531
532 // Cannot use SourceSurface buffer count since it could be codec's 512*512 tile
533 // buffer count.
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800534 if ((res = native_window_set_buffer_count(
Shuzhen Wang3d00ee52019-09-25 14:19:28 -0700535 anwConsumer, kMaxOutputSurfaceProducerCount + maxConsumerBuffers)) != OK) {
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800536 ALOGE("%s: Unable to set buffer count for stream %d", __FUNCTION__, mMainImageStreamId);
537 return res;
538 }
539
540 if ((res = native_window_set_buffers_dimensions(anwConsumer, mMaxHeicBufferSize, 1)) != OK) {
541 ALOGE("%s: Unable to set buffer dimension %zu x 1 for stream %d: %s (%d)",
542 __FUNCTION__, mMaxHeicBufferSize, mMainImageStreamId, strerror(-res), res);
543 return res;
544 }
545
Shuzhen Wange8675782019-12-05 09:12:14 -0800546 sp<camera3::StatusTracker> statusTracker = mStatusTracker.promote();
547 if (statusTracker != nullptr) {
Yin-Chia Yeh87b3ec02019-06-03 10:44:39 -0700548 std::string name = std::string("HeicStream ") + std::to_string(getStreamId());
549 mStatusId = statusTracker->addComponent(name);
Shuzhen Wange8675782019-12-05 09:12:14 -0800550 }
551
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800552 run("HeicCompositeStreamProc");
553
554 return NO_ERROR;
555}
556
557status_t HeicCompositeStream::insertGbp(SurfaceMap* /*out*/outSurfaceMap,
558 Vector<int32_t>* /*out*/outputStreamIds, int32_t* /*out*/currentStreamId) {
559 if (outSurfaceMap->find(mAppSegmentStreamId) == outSurfaceMap->end()) {
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800560 outputStreamIds->push_back(mAppSegmentStreamId);
561 }
562 (*outSurfaceMap)[mAppSegmentStreamId].push_back(mAppSegmentSurfaceId);
563
564 if (outSurfaceMap->find(mMainImageStreamId) == outSurfaceMap->end()) {
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800565 outputStreamIds->push_back(mMainImageStreamId);
566 }
567 (*outSurfaceMap)[mMainImageStreamId].push_back(mMainImageSurfaceId);
568
569 if (currentStreamId != nullptr) {
570 *currentStreamId = mMainImageStreamId;
571 }
572
573 return NO_ERROR;
574}
575
Emilian Peev4697b642019-11-19 17:11:14 -0800576status_t HeicCompositeStream::insertCompositeStreamIds(
577 std::vector<int32_t>* compositeStreamIds /*out*/) {
578 if (compositeStreamIds == nullptr) {
579 return BAD_VALUE;
580 }
581
582 compositeStreamIds->push_back(mAppSegmentStreamId);
583 compositeStreamIds->push_back(mMainImageStreamId);
584
585 return OK;
586}
587
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800588void HeicCompositeStream::onShutter(const CaptureResultExtras& resultExtras, nsecs_t timestamp) {
589 Mutex::Autolock l(mMutex);
590 if (mErrorState) {
591 return;
592 }
593
594 if (mSettingsByFrameNumber.find(resultExtras.frameNumber) != mSettingsByFrameNumber.end()) {
Shuzhen Wange8675782019-12-05 09:12:14 -0800595 ALOGV("%s: [%" PRId64 "]: timestamp %" PRId64 ", requestId %d", __FUNCTION__,
596 resultExtras.frameNumber, timestamp, resultExtras.requestId);
597 mSettingsByFrameNumber[resultExtras.frameNumber].shutterNotified = true;
598 mSettingsByFrameNumber[resultExtras.frameNumber].timestamp = timestamp;
599 mSettingsByFrameNumber[resultExtras.frameNumber].requestId = resultExtras.requestId;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800600 mInputReadyCondition.signal();
601 }
602}
603
604void HeicCompositeStream::compilePendingInputLocked() {
Shuzhen Wange8675782019-12-05 09:12:14 -0800605 auto i = mSettingsByFrameNumber.begin();
606 while (i != mSettingsByFrameNumber.end()) {
607 if (i->second.shutterNotified) {
608 mPendingInputFrames[i->first].orientation = i->second.orientation;
609 mPendingInputFrames[i->first].quality = i->second.quality;
610 mPendingInputFrames[i->first].timestamp = i->second.timestamp;
611 mPendingInputFrames[i->first].requestId = i->second.requestId;
612 ALOGV("%s: [%" PRId64 "]: timestamp is %" PRId64, __FUNCTION__,
613 i->first, i->second.timestamp);
614 i = mSettingsByFrameNumber.erase(i);
Shuzhen Wang62f49ed2019-09-04 14:07:53 -0700615
Shuzhen Wange8675782019-12-05 09:12:14 -0800616 // Set encoder quality if no inflight encoding
617 if (mPendingInputFrames.size() == 1) {
618 sp<StatusTracker> statusTracker = mStatusTracker.promote();
619 if (statusTracker != nullptr) {
620 statusTracker->markComponentActive(mStatusId);
621 ALOGV("%s: Mark component as active", __FUNCTION__);
622 }
623
624 int32_t newQuality = mPendingInputFrames.begin()->second.quality;
625 updateCodecQualityLocked(newQuality);
626 }
627 } else {
628 i++;
Shuzhen Wang62f49ed2019-09-04 14:07:53 -0700629 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800630 }
631
Shuzhen Wange8675782019-12-05 09:12:14 -0800632 while (!mInputAppSegmentBuffers.empty() && mAppSegmentFrameNumbers.size() > 0) {
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800633 CpuConsumer::LockedBuffer imgBuffer;
634 auto it = mInputAppSegmentBuffers.begin();
635 auto res = mAppSegmentConsumer->lockNextBuffer(&imgBuffer);
636 if (res == NOT_ENOUGH_DATA) {
Michael Gonzalezb5986a32019-10-09 15:38:17 -0700637 // Can not lock any more buffers.
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800638 break;
639 } else if ((res != OK) || (*it != imgBuffer.timestamp)) {
640 if (res != OK) {
641 ALOGE("%s: Error locking JPEG_APP_SEGMENTS image buffer: %s (%d)", __FUNCTION__,
642 strerror(-res), res);
643 } else {
644 ALOGE("%s: Expecting JPEG_APP_SEGMENTS buffer with time stamp: %" PRId64
645 " received buffer with time stamp: %" PRId64, __FUNCTION__,
646 *it, imgBuffer.timestamp);
Michael Gonzalezb5986a32019-10-09 15:38:17 -0700647 mAppSegmentConsumer->unlockBuffer(imgBuffer);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800648 }
649 mPendingInputFrames[*it].error = true;
650 mInputAppSegmentBuffers.erase(it);
651 continue;
652 }
653
Shuzhen Wange8675782019-12-05 09:12:14 -0800654 if (mPendingInputFrames.find(mAppSegmentFrameNumbers.front()) == mPendingInputFrames.end()) {
655 ALOGE("%s: mPendingInputFrames doesn't contain frameNumber %" PRId64, __FUNCTION__,
656 mAppSegmentFrameNumbers.front());
Shuzhen Wang991b7b62020-06-17 11:39:11 -0700657 mInputAppSegmentBuffers.erase(it);
658 mAppSegmentFrameNumbers.pop();
Shuzhen Wange8675782019-12-05 09:12:14 -0800659 continue;
660 }
661
662 int64_t frameNumber = mAppSegmentFrameNumbers.front();
663 // If mPendingInputFrames doesn't contain the expected frame number, the captured
664 // input app segment frame must have been dropped via a buffer error. Simply
665 // return the buffer to the buffer queue.
666 if ((mPendingInputFrames.find(frameNumber) == mPendingInputFrames.end()) ||
667 (mPendingInputFrames[frameNumber].error)) {
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800668 mAppSegmentConsumer->unlockBuffer(imgBuffer);
669 } else {
Shuzhen Wange8675782019-12-05 09:12:14 -0800670 mPendingInputFrames[frameNumber].appSegmentBuffer = imgBuffer;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800671 }
672 mInputAppSegmentBuffers.erase(it);
Shuzhen Wange8675782019-12-05 09:12:14 -0800673 mAppSegmentFrameNumbers.pop();
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800674 }
675
Shuzhen Wange8675782019-12-05 09:12:14 -0800676 while (!mInputYuvBuffers.empty() && !mYuvBufferAcquired && mMainImageFrameNumbers.size() > 0) {
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800677 CpuConsumer::LockedBuffer imgBuffer;
678 auto it = mInputYuvBuffers.begin();
679 auto res = mMainImageConsumer->lockNextBuffer(&imgBuffer);
680 if (res == NOT_ENOUGH_DATA) {
Michael Gonzalezb5986a32019-10-09 15:38:17 -0700681 // Can not lock any more buffers.
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800682 break;
683 } else if (res != OK) {
684 ALOGE("%s: Error locking YUV_888 image buffer: %s (%d)", __FUNCTION__,
685 strerror(-res), res);
686 mPendingInputFrames[*it].error = true;
687 mInputYuvBuffers.erase(it);
688 continue;
689 } else if (*it != imgBuffer.timestamp) {
690 ALOGW("%s: Expecting YUV_888 buffer with time stamp: %" PRId64 " received buffer with "
691 "time stamp: %" PRId64, __FUNCTION__, *it, imgBuffer.timestamp);
692 mPendingInputFrames[*it].error = true;
693 mInputYuvBuffers.erase(it);
694 continue;
695 }
696
Shuzhen Wange8675782019-12-05 09:12:14 -0800697 if (mPendingInputFrames.find(mMainImageFrameNumbers.front()) == mPendingInputFrames.end()) {
698 ALOGE("%s: mPendingInputFrames doesn't contain frameNumber %" PRId64, __FUNCTION__,
699 mMainImageFrameNumbers.front());
700 mInputYuvBuffers.erase(it);
Shuzhen Wang991b7b62020-06-17 11:39:11 -0700701 mMainImageFrameNumbers.pop();
Shuzhen Wange8675782019-12-05 09:12:14 -0800702 continue;
703 }
704
705 int64_t frameNumber = mMainImageFrameNumbers.front();
706 // If mPendingInputFrames doesn't contain the expected frame number, the captured
707 // input main image must have been dropped via a buffer error. Simply
708 // return the buffer to the buffer queue.
709 if ((mPendingInputFrames.find(frameNumber) == mPendingInputFrames.end()) ||
710 (mPendingInputFrames[frameNumber].error)) {
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800711 mMainImageConsumer->unlockBuffer(imgBuffer);
712 } else {
Shuzhen Wange8675782019-12-05 09:12:14 -0800713 mPendingInputFrames[frameNumber].yuvBuffer = imgBuffer;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800714 mYuvBufferAcquired = true;
715 }
716 mInputYuvBuffers.erase(it);
Shuzhen Wange8675782019-12-05 09:12:14 -0800717 mMainImageFrameNumbers.pop();
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800718 }
719
720 while (!mCodecOutputBuffers.empty()) {
721 auto it = mCodecOutputBuffers.begin();
Shuzhen Wange8675782019-12-05 09:12:14 -0800722 // Assume encoder input to output is FIFO, use a queue to look up
723 // frameNumber when handling codec outputs.
724 int64_t bufferFrameNumber = -1;
725 if (mCodecOutputBufferFrameNumbers.empty()) {
726 ALOGV("%s: Failed to find buffer frameNumber for codec output buffer!", __FUNCTION__);
Michael Gonzalez5c103f22019-10-08 14:30:32 -0700727 break;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800728 } else {
Shuzhen Wange8675782019-12-05 09:12:14 -0800729 // Direct mapping between camera frame number and codec timestamp (in us).
730 bufferFrameNumber = mCodecOutputBufferFrameNumbers.front();
Shuzhen Wang3d00ee52019-09-25 14:19:28 -0700731 mCodecOutputCounter++;
732 if (mCodecOutputCounter == mNumOutputTiles) {
Shuzhen Wange8675782019-12-05 09:12:14 -0800733 mCodecOutputBufferFrameNumbers.pop();
Shuzhen Wang3d00ee52019-09-25 14:19:28 -0700734 mCodecOutputCounter = 0;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800735 }
736
Shuzhen Wange8675782019-12-05 09:12:14 -0800737 mPendingInputFrames[bufferFrameNumber].codecOutputBuffers.push_back(*it);
738 ALOGV("%s: [%" PRId64 "]: Pushing codecOutputBuffers (frameNumber %" PRId64 ")",
739 __FUNCTION__, bufferFrameNumber, it->timeUs);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800740 }
741 mCodecOutputBuffers.erase(it);
742 }
743
Shuzhen Wange7f4b462019-02-12 08:43:07 -0800744 while (!mCaptureResults.empty()) {
745 auto it = mCaptureResults.begin();
Shuzhen Wange8675782019-12-05 09:12:14 -0800746 // Negative frame number indicates that something went wrong during the capture result
Shuzhen Wange7f4b462019-02-12 08:43:07 -0800747 // collection process.
Shuzhen Wange8675782019-12-05 09:12:14 -0800748 int64_t frameNumber = std::get<0>(it->second);
749 if (it->first >= 0 &&
750 mPendingInputFrames.find(frameNumber) != mPendingInputFrames.end()) {
751 if (mPendingInputFrames[frameNumber].timestamp == it->first) {
752 mPendingInputFrames[frameNumber].result =
Shuzhen Wange7f4b462019-02-12 08:43:07 -0800753 std::make_unique<CameraMetadata>(std::get<1>(it->second));
754 } else {
755 ALOGE("%s: Capture result frameNumber/timestamp mapping changed between "
Shuzhen Wange8675782019-12-05 09:12:14 -0800756 "shutter and capture result! before: %" PRId64 ", after: %" PRId64,
757 __FUNCTION__, mPendingInputFrames[frameNumber].timestamp,
758 it->first);
Shuzhen Wange7f4b462019-02-12 08:43:07 -0800759 }
760 }
761 mCaptureResults.erase(it);
762 }
763
764 // mErrorFrameNumbers stores frame number of dropped buffers.
765 auto it = mErrorFrameNumbers.begin();
766 while (it != mErrorFrameNumbers.end()) {
Shuzhen Wange8675782019-12-05 09:12:14 -0800767 if (mPendingInputFrames.find(*it) != mPendingInputFrames.end()) {
768 mPendingInputFrames[*it].error = true;
Shuzhen Wange7f4b462019-02-12 08:43:07 -0800769 } else {
Shuzhen Wange8675782019-12-05 09:12:14 -0800770 //Error callback is guaranteed to arrive after shutter notify, which
771 //results in mPendingInputFrames being populated.
Shuzhen Wange7f4b462019-02-12 08:43:07 -0800772 ALOGW("%s: Not able to find failing input with frame number: %" PRId64, __FUNCTION__,
773 *it);
Shuzhen Wange7f4b462019-02-12 08:43:07 -0800774 }
Shuzhen Wange8675782019-12-05 09:12:14 -0800775 it = mErrorFrameNumbers.erase(it);
776 }
777
778 // mExifErrorFrameNumbers stores the frame number of dropped APP_SEGMENT buffers
779 it = mExifErrorFrameNumbers.begin();
780 while (it != mExifErrorFrameNumbers.end()) {
781 if (mPendingInputFrames.find(*it) != mPendingInputFrames.end()) {
782 mPendingInputFrames[*it].exifError = true;
783 }
784 it = mExifErrorFrameNumbers.erase(it);
Shuzhen Wange7f4b462019-02-12 08:43:07 -0800785 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800786
787 // Distribute codec input buffers to be filled out from YUV output
788 for (auto it = mPendingInputFrames.begin();
789 it != mPendingInputFrames.end() && mCodecInputBuffers.size() > 0; it++) {
790 InputFrame& inputFrame(it->second);
791 if (inputFrame.codecInputCounter < mGridRows * mGridCols) {
792 // Available input tiles that are required for the current input
793 // image.
794 size_t newInputTiles = std::min(mCodecInputBuffers.size(),
795 mGridRows * mGridCols - inputFrame.codecInputCounter);
796 for (size_t i = 0; i < newInputTiles; i++) {
797 CodecInputBufferInfo inputInfo =
798 { mCodecInputBuffers[0], mGridTimestampUs++, inputFrame.codecInputCounter };
799 inputFrame.codecInputBuffers.push_back(inputInfo);
800
801 mCodecInputBuffers.erase(mCodecInputBuffers.begin());
802 inputFrame.codecInputCounter++;
803 }
804 break;
805 }
806 }
807}
808
Shuzhen Wange8675782019-12-05 09:12:14 -0800809bool HeicCompositeStream::getNextReadyInputLocked(int64_t *frameNumber /*out*/) {
810 if (frameNumber == nullptr) {
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800811 return false;
812 }
813
814 bool newInputAvailable = false;
Shuzhen Wang3d00ee52019-09-25 14:19:28 -0700815 for (auto& it : mPendingInputFrames) {
816 // New input is considered to be available only if:
817 // 1. input buffers are ready, or
818 // 2. App segment and muxer is created, or
819 // 3. A codec output tile is ready, and an output buffer is available.
820 // This makes sure that muxer gets created only when an output tile is
821 // generated, because right now we only handle 1 HEIC output buffer at a
822 // time (max dequeued buffer count is 1).
Shuzhen Wange8675782019-12-05 09:12:14 -0800823 bool appSegmentReady =
824 (it.second.appSegmentBuffer.data != nullptr || it.second.exifError) &&
Shuzhen Wang3d00ee52019-09-25 14:19:28 -0700825 !it.second.appSegmentWritten && it.second.result != nullptr &&
826 it.second.muxer != nullptr;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800827 bool codecOutputReady = !it.second.codecOutputBuffers.empty();
828 bool codecInputReady = (it.second.yuvBuffer.data != nullptr) &&
829 (!it.second.codecInputBuffers.empty());
Shuzhen Wang3d00ee52019-09-25 14:19:28 -0700830 bool hasOutputBuffer = it.second.muxer != nullptr ||
831 (mDequeuedOutputBufferCnt < kMaxOutputSurfaceProducerCount);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800832 if ((!it.second.error) &&
Shuzhen Wang3d00ee52019-09-25 14:19:28 -0700833 (appSegmentReady || (codecOutputReady && hasOutputBuffer) || codecInputReady)) {
Shuzhen Wange8675782019-12-05 09:12:14 -0800834 *frameNumber = it.first;
Shuzhen Wang3d00ee52019-09-25 14:19:28 -0700835 if (it.second.format == nullptr && mFormat != nullptr) {
836 it.second.format = mFormat->dup();
837 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800838 newInputAvailable = true;
839 break;
840 }
841 }
842
843 return newInputAvailable;
844}
845
Shuzhen Wange8675782019-12-05 09:12:14 -0800846int64_t HeicCompositeStream::getNextFailingInputLocked() {
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800847 int64_t res = -1;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800848
849 for (const auto& it : mPendingInputFrames) {
Shuzhen Wange8675782019-12-05 09:12:14 -0800850 if (it.second.error) {
851 res = it.first;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800852 break;
853 }
854 }
855
856 return res;
857}
858
Shuzhen Wange8675782019-12-05 09:12:14 -0800859status_t HeicCompositeStream::processInputFrame(int64_t frameNumber,
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800860 InputFrame &inputFrame) {
861 ATRACE_CALL();
862 status_t res = OK;
863
Shuzhen Wange8675782019-12-05 09:12:14 -0800864 bool appSegmentReady =
865 (inputFrame.appSegmentBuffer.data != nullptr || inputFrame.exifError) &&
Shuzhen Wang3d00ee52019-09-25 14:19:28 -0700866 !inputFrame.appSegmentWritten && inputFrame.result != nullptr &&
867 inputFrame.muxer != nullptr;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800868 bool codecOutputReady = inputFrame.codecOutputBuffers.size() > 0;
869 bool codecInputReady = inputFrame.yuvBuffer.data != nullptr &&
Shuzhen Wang3d00ee52019-09-25 14:19:28 -0700870 !inputFrame.codecInputBuffers.empty();
871 bool hasOutputBuffer = inputFrame.muxer != nullptr ||
872 (mDequeuedOutputBufferCnt < kMaxOutputSurfaceProducerCount);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800873
Shuzhen Wang3d00ee52019-09-25 14:19:28 -0700874 ALOGV("%s: [%" PRId64 "]: appSegmentReady %d, codecOutputReady %d, codecInputReady %d,"
Shuzhen Wange8675782019-12-05 09:12:14 -0800875 " dequeuedOutputBuffer %d, timestamp %" PRId64, __FUNCTION__, frameNumber,
876 appSegmentReady, codecOutputReady, codecInputReady, mDequeuedOutputBufferCnt,
877 inputFrame.timestamp);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800878
879 // Handle inputs for Hevc tiling
880 if (codecInputReady) {
881 res = processCodecInputFrame(inputFrame);
882 if (res != OK) {
883 ALOGE("%s: Failed to process codec input frame: %s (%d)", __FUNCTION__,
884 strerror(-res), res);
885 return res;
886 }
887 }
888
Shuzhen Wang3d00ee52019-09-25 14:19:28 -0700889 if (!(codecOutputReady && hasOutputBuffer) && !appSegmentReady) {
890 return OK;
891 }
892
893 // Initialize and start muxer if not yet done so. In this case,
894 // codecOutputReady must be true. Otherwise, appSegmentReady is guaranteed
895 // to be false, and the function must have returned early.
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800896 if (inputFrame.muxer == nullptr) {
Shuzhen Wange8675782019-12-05 09:12:14 -0800897 res = startMuxerForInputFrame(frameNumber, inputFrame);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800898 if (res != OK) {
899 ALOGE("%s: Failed to create and start muxer: %s (%d)", __FUNCTION__,
900 strerror(-res), res);
901 return res;
902 }
903 }
904
905 // Write JPEG APP segments data to the muxer.
Shuzhen Wang3d00ee52019-09-25 14:19:28 -0700906 if (appSegmentReady) {
Shuzhen Wange8675782019-12-05 09:12:14 -0800907 res = processAppSegment(frameNumber, inputFrame);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800908 if (res != OK) {
909 ALOGE("%s: Failed to process JPEG APP segments: %s (%d)", __FUNCTION__,
910 strerror(-res), res);
911 return res;
912 }
913 }
914
915 // Write media codec bitstream buffers to muxer.
916 while (!inputFrame.codecOutputBuffers.empty()) {
Shuzhen Wange8675782019-12-05 09:12:14 -0800917 res = processOneCodecOutputFrame(frameNumber, inputFrame);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800918 if (res != OK) {
919 ALOGE("%s: Failed to process codec output frame: %s (%d)", __FUNCTION__,
920 strerror(-res), res);
921 return res;
922 }
923 }
924
Michael Gonzalezb5986a32019-10-09 15:38:17 -0700925 if (inputFrame.pendingOutputTiles == 0) {
926 if (inputFrame.appSegmentWritten) {
Shuzhen Wange8675782019-12-05 09:12:14 -0800927 res = processCompletedInputFrame(frameNumber, inputFrame);
Michael Gonzalezb5986a32019-10-09 15:38:17 -0700928 if (res != OK) {
929 ALOGE("%s: Failed to process completed input frame: %s (%d)", __FUNCTION__,
930 strerror(-res), res);
931 return res;
932 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800933 }
934 }
935
936 return res;
937}
938
Shuzhen Wange8675782019-12-05 09:12:14 -0800939status_t HeicCompositeStream::startMuxerForInputFrame(int64_t frameNumber, InputFrame &inputFrame) {
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800940 sp<ANativeWindow> outputANW = mOutputSurface;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800941
942 auto res = outputANW->dequeueBuffer(mOutputSurface.get(), &inputFrame.anb, &inputFrame.fenceFd);
943 if (res != OK) {
944 ALOGE("%s: Error retrieving output buffer: %s (%d)", __FUNCTION__, strerror(-res),
945 res);
946 return res;
947 }
Shuzhen Wang3d00ee52019-09-25 14:19:28 -0700948 mDequeuedOutputBufferCnt++;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800949
950 // Combine current thread id, stream id and timestamp to uniquely identify image.
951 std::ostringstream tempOutputFile;
952 tempOutputFile << "HEIF-" << pthread_self() << "-"
Shuzhen Wange8675782019-12-05 09:12:14 -0800953 << getStreamId() << "-" << frameNumber;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800954 inputFrame.fileFd = syscall(__NR_memfd_create, tempOutputFile.str().c_str(), MFD_CLOEXEC);
955 if (inputFrame.fileFd < 0) {
956 ALOGE("%s: Failed to create file %s. Error no is %d", __FUNCTION__,
957 tempOutputFile.str().c_str(), errno);
958 return NO_INIT;
959 }
Manisha Jajoo022b52f2021-10-09 00:51:42 +0530960 inputFrame.muxer = MediaMuxer::create(inputFrame.fileFd, MediaMuxer::OUTPUT_FORMAT_HEIF);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800961 if (inputFrame.muxer == nullptr) {
962 ALOGE("%s: Failed to create MediaMuxer for file fd %d",
963 __FUNCTION__, inputFrame.fileFd);
964 return NO_INIT;
965 }
966
967 res = inputFrame.muxer->setOrientationHint(inputFrame.orientation);
968 if (res != OK) {
969 ALOGE("%s: Failed to setOrientationHint: %s (%d)", __FUNCTION__,
970 strerror(-res), res);
971 return res;
972 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800973
Shuzhen Wang3d00ee52019-09-25 14:19:28 -0700974 ssize_t trackId = inputFrame.muxer->addTrack(inputFrame.format);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800975 if (trackId < 0) {
976 ALOGE("%s: Failed to addTrack to the muxer: %zd", __FUNCTION__, trackId);
977 return NO_INIT;
978 }
979
980 inputFrame.trackIndex = trackId;
981 inputFrame.pendingOutputTiles = mNumOutputTiles;
982
983 res = inputFrame.muxer->start();
984 if (res != OK) {
985 ALOGE("%s: Failed to start MediaMuxer: %s (%d)",
986 __FUNCTION__, strerror(-res), res);
987 return res;
988 }
989
Shuzhen Wang3d00ee52019-09-25 14:19:28 -0700990 ALOGV("%s: [%" PRId64 "]: Muxer started for inputFrame", __FUNCTION__,
Shuzhen Wange8675782019-12-05 09:12:14 -0800991 frameNumber);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800992 return OK;
993}
994
Shuzhen Wange8675782019-12-05 09:12:14 -0800995status_t HeicCompositeStream::processAppSegment(int64_t frameNumber, InputFrame &inputFrame) {
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800996 size_t app1Size = 0;
Shuzhen Wange8675782019-12-05 09:12:14 -0800997 size_t appSegmentSize = 0;
998 if (!inputFrame.exifError) {
999 appSegmentSize = findAppSegmentsSize(inputFrame.appSegmentBuffer.data,
1000 inputFrame.appSegmentBuffer.width * inputFrame.appSegmentBuffer.height,
1001 &app1Size);
1002 if (appSegmentSize == 0) {
1003 ALOGE("%s: Failed to find JPEG APP segment size", __FUNCTION__);
1004 return NO_INIT;
1005 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001006 }
1007
1008 std::unique_ptr<ExifUtils> exifUtils(ExifUtils::create());
Shuzhen Wange8675782019-12-05 09:12:14 -08001009 auto exifRes = inputFrame.exifError ?
1010 exifUtils->initializeEmpty() :
1011 exifUtils->initialize(inputFrame.appSegmentBuffer.data, app1Size);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001012 if (!exifRes) {
1013 ALOGE("%s: Failed to initialize ExifUtils object!", __FUNCTION__);
1014 return BAD_VALUE;
1015 }
Shuzhen Wange7f4b462019-02-12 08:43:07 -08001016 exifRes = exifUtils->setFromMetadata(*inputFrame.result, mStaticInfo,
1017 mOutputWidth, mOutputHeight);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001018 if (!exifRes) {
1019 ALOGE("%s: Failed to set Exif tags using metadata and main image sizes", __FUNCTION__);
1020 return BAD_VALUE;
1021 }
1022 exifRes = exifUtils->setOrientation(inputFrame.orientation);
1023 if (!exifRes) {
1024 ALOGE("%s: ExifUtils failed to set orientation", __FUNCTION__);
1025 return BAD_VALUE;
1026 }
1027 exifRes = exifUtils->generateApp1();
1028 if (!exifRes) {
1029 ALOGE("%s: ExifUtils failed to generate APP1 segment", __FUNCTION__);
1030 return BAD_VALUE;
1031 }
1032
1033 unsigned int newApp1Length = exifUtils->getApp1Length();
1034 const uint8_t *newApp1Segment = exifUtils->getApp1Buffer();
1035
1036 //Assemble the APP1 marker buffer required by MediaCodec
1037 uint8_t kExifApp1Marker[] = {'E', 'x', 'i', 'f', 0xFF, 0xE1, 0x00, 0x00};
1038 kExifApp1Marker[6] = static_cast<uint8_t>(newApp1Length >> 8);
1039 kExifApp1Marker[7] = static_cast<uint8_t>(newApp1Length & 0xFF);
1040 size_t appSegmentBufferSize = sizeof(kExifApp1Marker) +
1041 appSegmentSize - app1Size + newApp1Length;
1042 uint8_t* appSegmentBuffer = new uint8_t[appSegmentBufferSize];
1043 memcpy(appSegmentBuffer, kExifApp1Marker, sizeof(kExifApp1Marker));
1044 memcpy(appSegmentBuffer + sizeof(kExifApp1Marker), newApp1Segment, newApp1Length);
1045 if (appSegmentSize - app1Size > 0) {
1046 memcpy(appSegmentBuffer + sizeof(kExifApp1Marker) + newApp1Length,
1047 inputFrame.appSegmentBuffer.data + app1Size, appSegmentSize - app1Size);
1048 }
1049
1050 sp<ABuffer> aBuffer = new ABuffer(appSegmentBuffer, appSegmentBufferSize);
1051 auto res = inputFrame.muxer->writeSampleData(aBuffer, inputFrame.trackIndex,
Shuzhen Wange8675782019-12-05 09:12:14 -08001052 inputFrame.timestamp, MediaCodec::BUFFER_FLAG_MUXER_DATA);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001053 delete[] appSegmentBuffer;
1054
1055 if (res != OK) {
1056 ALOGE("%s: Failed to write JPEG APP segments to muxer: %s (%d)",
1057 __FUNCTION__, strerror(-res), res);
1058 return res;
1059 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001060
Shuzhen Wang3d00ee52019-09-25 14:19:28 -07001061 ALOGV("%s: [%" PRId64 "]: appSegmentSize is %zu, width %d, height %d, app1Size %zu",
Shuzhen Wange8675782019-12-05 09:12:14 -08001062 __FUNCTION__, frameNumber, appSegmentSize, inputFrame.appSegmentBuffer.width,
Shuzhen Wang3d00ee52019-09-25 14:19:28 -07001063 inputFrame.appSegmentBuffer.height, app1Size);
Michael Gonzalezb5986a32019-10-09 15:38:17 -07001064
1065 inputFrame.appSegmentWritten = true;
1066 // Release the buffer now so any pending input app segments can be processed
1067 mAppSegmentConsumer->unlockBuffer(inputFrame.appSegmentBuffer);
1068 inputFrame.appSegmentBuffer.data = nullptr;
Shuzhen Wange8675782019-12-05 09:12:14 -08001069 inputFrame.exifError = false;
Michael Gonzalezb5986a32019-10-09 15:38:17 -07001070
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001071 return OK;
1072}
1073
1074status_t HeicCompositeStream::processCodecInputFrame(InputFrame &inputFrame) {
1075 for (auto& inputBuffer : inputFrame.codecInputBuffers) {
1076 sp<MediaCodecBuffer> buffer;
1077 auto res = mCodec->getInputBuffer(inputBuffer.index, &buffer);
1078 if (res != OK) {
1079 ALOGE("%s: Error getting codec input buffer: %s (%d)", __FUNCTION__,
1080 strerror(-res), res);
1081 return res;
1082 }
1083
1084 // Copy one tile from source to destination.
1085 size_t tileX = inputBuffer.tileIndex % mGridCols;
1086 size_t tileY = inputBuffer.tileIndex / mGridCols;
1087 size_t top = mGridHeight * tileY;
1088 size_t left = mGridWidth * tileX;
1089 size_t width = (tileX == static_cast<size_t>(mGridCols) - 1) ?
1090 mOutputWidth - tileX * mGridWidth : mGridWidth;
1091 size_t height = (tileY == static_cast<size_t>(mGridRows) - 1) ?
1092 mOutputHeight - tileY * mGridHeight : mGridHeight;
Shuzhen Wang3d00ee52019-09-25 14:19:28 -07001093 ALOGV("%s: inputBuffer tileIndex [%zu, %zu], top %zu, left %zu, width %zu, height %zu,"
1094 " timeUs %" PRId64, __FUNCTION__, tileX, tileY, top, left, width, height,
1095 inputBuffer.timeUs);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001096
1097 res = copyOneYuvTile(buffer, inputFrame.yuvBuffer, top, left, width, height);
1098 if (res != OK) {
1099 ALOGE("%s: Failed to copy YUV tile %s (%d)", __FUNCTION__,
1100 strerror(-res), res);
1101 return res;
1102 }
1103
1104 res = mCodec->queueInputBuffer(inputBuffer.index, 0, buffer->capacity(),
1105 inputBuffer.timeUs, 0, nullptr /*errorDetailMsg*/);
1106 if (res != OK) {
1107 ALOGE("%s: Failed to queueInputBuffer to Codec: %s (%d)",
1108 __FUNCTION__, strerror(-res), res);
1109 return res;
1110 }
1111 }
1112
1113 inputFrame.codecInputBuffers.clear();
1114 return OK;
1115}
1116
Shuzhen Wange8675782019-12-05 09:12:14 -08001117status_t HeicCompositeStream::processOneCodecOutputFrame(int64_t frameNumber,
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001118 InputFrame &inputFrame) {
1119 auto it = inputFrame.codecOutputBuffers.begin();
1120 sp<MediaCodecBuffer> buffer;
1121 status_t res = mCodec->getOutputBuffer(it->index, &buffer);
1122 if (res != OK) {
1123 ALOGE("%s: Error getting Heic codec output buffer at index %d: %s (%d)",
1124 __FUNCTION__, it->index, strerror(-res), res);
1125 return res;
1126 }
1127 if (buffer == nullptr) {
1128 ALOGE("%s: Invalid Heic codec output buffer at index %d",
1129 __FUNCTION__, it->index);
1130 return BAD_VALUE;
1131 }
1132
1133 sp<ABuffer> aBuffer = new ABuffer(buffer->data(), buffer->size());
1134 res = inputFrame.muxer->writeSampleData(
Shuzhen Wange8675782019-12-05 09:12:14 -08001135 aBuffer, inputFrame.trackIndex, inputFrame.timestamp, 0 /*flags*/);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001136 if (res != OK) {
1137 ALOGE("%s: Failed to write buffer index %d to muxer: %s (%d)",
1138 __FUNCTION__, it->index, strerror(-res), res);
1139 return res;
1140 }
1141
1142 mCodec->releaseOutputBuffer(it->index);
1143 if (inputFrame.pendingOutputTiles == 0) {
1144 ALOGW("%s: Codec generated more tiles than expected!", __FUNCTION__);
1145 } else {
1146 inputFrame.pendingOutputTiles--;
1147 }
1148
1149 inputFrame.codecOutputBuffers.erase(inputFrame.codecOutputBuffers.begin());
Shuzhen Wang3d00ee52019-09-25 14:19:28 -07001150
1151 ALOGV("%s: [%" PRId64 "]: Output buffer index %d",
Shuzhen Wange8675782019-12-05 09:12:14 -08001152 __FUNCTION__, frameNumber, it->index);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001153 return OK;
1154}
1155
Shuzhen Wange8675782019-12-05 09:12:14 -08001156status_t HeicCompositeStream::processCompletedInputFrame(int64_t frameNumber,
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001157 InputFrame &inputFrame) {
1158 sp<ANativeWindow> outputANW = mOutputSurface;
1159 inputFrame.muxer->stop();
1160
1161 // Copy the content of the file to memory.
1162 sp<GraphicBuffer> gb = GraphicBuffer::from(inputFrame.anb);
1163 void* dstBuffer;
Shuzhen Wangc87315d2022-03-17 00:11:20 +00001164 GraphicBufferLocker gbLocker(gb);
1165 auto res = gbLocker.lockAsync(&dstBuffer, inputFrame.fenceFd);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001166 if (res != OK) {
1167 ALOGE("%s: Error trying to lock output buffer fence: %s (%d)", __FUNCTION__,
1168 strerror(-res), res);
1169 return res;
1170 }
1171
1172 off_t fSize = lseek(inputFrame.fileFd, 0, SEEK_END);
1173 if (static_cast<size_t>(fSize) > mMaxHeicBufferSize - sizeof(CameraBlob)) {
1174 ALOGE("%s: Error: MediaMuxer output size %ld is larger than buffer sizer %zu",
1175 __FUNCTION__, fSize, mMaxHeicBufferSize - sizeof(CameraBlob));
1176 return BAD_VALUE;
1177 }
1178
1179 lseek(inputFrame.fileFd, 0, SEEK_SET);
1180 ssize_t bytesRead = read(inputFrame.fileFd, dstBuffer, fSize);
1181 if (bytesRead < fSize) {
1182 ALOGE("%s: Only %zd of %ld bytes read", __FUNCTION__, bytesRead, fSize);
1183 return BAD_VALUE;
1184 }
1185
1186 close(inputFrame.fileFd);
1187 inputFrame.fileFd = -1;
1188
1189 // Fill in HEIC header
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001190 // Must be in sync with CAMERA3_HEIC_BLOB_ID in android_media_Utils.cpp
Shuzhen Wangdc519092022-12-02 12:29:04 -08001191 uint8_t *header = static_cast<uint8_t*>(dstBuffer) + mMaxHeicBufferSize - sizeof(CameraBlob);
1192 CameraBlob blobHeader = {
1193 .blobId = static_cast<CameraBlobId>(0x00FE),
1194 .blobSizeBytes = static_cast<int32_t>(fSize)
1195 };
1196 memcpy(header, &blobHeader, sizeof(CameraBlob));
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001197
Shuzhen Wange8675782019-12-05 09:12:14 -08001198 res = native_window_set_buffers_timestamp(mOutputSurface.get(), inputFrame.timestamp);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001199 if (res != OK) {
1200 ALOGE("%s: Stream %d: Error setting timestamp: %s (%d)",
1201 __FUNCTION__, getStreamId(), strerror(-res), res);
1202 return res;
1203 }
1204
1205 res = outputANW->queueBuffer(mOutputSurface.get(), inputFrame.anb, /*fence*/ -1);
1206 if (res != OK) {
1207 ALOGE("%s: Failed to queueBuffer to Heic stream: %s (%d)", __FUNCTION__,
1208 strerror(-res), res);
1209 return res;
1210 }
1211 inputFrame.anb = nullptr;
Shuzhen Wang3d00ee52019-09-25 14:19:28 -07001212 mDequeuedOutputBufferCnt--;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001213
Shuzhen Wange8675782019-12-05 09:12:14 -08001214 ALOGV("%s: [%" PRId64 "]", __FUNCTION__, frameNumber);
1215 ATRACE_ASYNC_END("HEIC capture", frameNumber);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001216 return OK;
1217}
1218
1219
Shuzhen Wange8675782019-12-05 09:12:14 -08001220void HeicCompositeStream::releaseInputFrameLocked(int64_t frameNumber,
1221 InputFrame *inputFrame /*out*/) {
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001222 if (inputFrame == nullptr) {
1223 return;
1224 }
1225
1226 if (inputFrame->appSegmentBuffer.data != nullptr) {
1227 mAppSegmentConsumer->unlockBuffer(inputFrame->appSegmentBuffer);
1228 inputFrame->appSegmentBuffer.data = nullptr;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001229 }
1230
1231 while (!inputFrame->codecOutputBuffers.empty()) {
1232 auto it = inputFrame->codecOutputBuffers.begin();
1233 ALOGV("%s: releaseOutputBuffer index %d", __FUNCTION__, it->index);
1234 mCodec->releaseOutputBuffer(it->index);
1235 inputFrame->codecOutputBuffers.erase(it);
1236 }
1237
1238 if (inputFrame->yuvBuffer.data != nullptr) {
1239 mMainImageConsumer->unlockBuffer(inputFrame->yuvBuffer);
1240 inputFrame->yuvBuffer.data = nullptr;
1241 mYuvBufferAcquired = false;
1242 }
1243
1244 while (!inputFrame->codecInputBuffers.empty()) {
1245 auto it = inputFrame->codecInputBuffers.begin();
1246 inputFrame->codecInputBuffers.erase(it);
1247 }
1248
Shuzhen Wange8675782019-12-05 09:12:14 -08001249 if (inputFrame->error || mErrorState) {
1250 ALOGV("%s: notifyError called for frameNumber %" PRId64, __FUNCTION__, frameNumber);
1251 notifyError(frameNumber, inputFrame->requestId);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001252 }
1253
1254 if (inputFrame->fileFd >= 0) {
1255 close(inputFrame->fileFd);
1256 inputFrame->fileFd = -1;
1257 }
1258
1259 if (inputFrame->anb != nullptr) {
1260 sp<ANativeWindow> outputANW = mOutputSurface;
1261 outputANW->cancelBuffer(mOutputSurface.get(), inputFrame->anb, /*fence*/ -1);
1262 inputFrame->anb = nullptr;
Shuzhen Wange8675782019-12-05 09:12:14 -08001263
1264 mDequeuedOutputBufferCnt--;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001265 }
1266}
1267
Michael Gonzalezb5986a32019-10-09 15:38:17 -07001268void HeicCompositeStream::releaseInputFramesLocked() {
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001269 auto it = mPendingInputFrames.begin();
Shuzhen Wang62f49ed2019-09-04 14:07:53 -07001270 bool inputFrameDone = false;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001271 while (it != mPendingInputFrames.end()) {
Michael Gonzalezb5986a32019-10-09 15:38:17 -07001272 auto& inputFrame = it->second;
1273 if (inputFrame.error ||
Shuzhen Wange8675782019-12-05 09:12:14 -08001274 (inputFrame.appSegmentWritten && inputFrame.pendingOutputTiles == 0)) {
1275 releaseInputFrameLocked(it->first, &inputFrame);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001276 it = mPendingInputFrames.erase(it);
Shuzhen Wang62f49ed2019-09-04 14:07:53 -07001277 inputFrameDone = true;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001278 } else {
1279 it++;
1280 }
1281 }
Shuzhen Wang62f49ed2019-09-04 14:07:53 -07001282
1283 // Update codec quality based on first upcoming input frame.
1284 // Note that when encoding is in surface mode, currently there is no
1285 // way for camera service to synchronize quality setting on a per-frame
1286 // basis: we don't get notification when codec is ready to consume a new
1287 // input frame. So we update codec quality on a best-effort basis.
1288 if (inputFrameDone) {
1289 auto firstPendingFrame = mPendingInputFrames.begin();
1290 if (firstPendingFrame != mPendingInputFrames.end()) {
1291 updateCodecQualityLocked(firstPendingFrame->second.quality);
Shuzhen Wange8675782019-12-05 09:12:14 -08001292 } else {
1293 markTrackerIdle();
Shuzhen Wang62f49ed2019-09-04 14:07:53 -07001294 }
1295 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001296}
1297
1298status_t HeicCompositeStream::initializeCodec(uint32_t width, uint32_t height,
1299 const sp<CameraDeviceBase>& cameraDevice) {
1300 ALOGV("%s", __FUNCTION__);
1301
1302 bool useGrid = false;
Chong Zhang688abaa2019-05-17 16:32:23 -07001303 AString hevcName;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001304 bool isSizeSupported = isSizeSupportedByHeifEncoder(width, height,
Chong Zhang688abaa2019-05-17 16:32:23 -07001305 &mUseHeic, &useGrid, nullptr, &hevcName);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001306 if (!isSizeSupported) {
1307 ALOGE("%s: Encoder doesnt' support size %u x %u!",
1308 __FUNCTION__, width, height);
1309 return BAD_VALUE;
1310 }
1311
1312 // Create Looper for MediaCodec.
1313 auto desiredMime = mUseHeic ? MIMETYPE_IMAGE_ANDROID_HEIC : MIMETYPE_VIDEO_HEVC;
1314 mCodecLooper = new ALooper;
1315 mCodecLooper->setName("Camera3-HeicComposite-MediaCodecLooper");
1316 status_t res = mCodecLooper->start(
1317 false, // runOnCallingThread
1318 false, // canCallJava
1319 PRIORITY_AUDIO);
1320 if (res != OK) {
1321 ALOGE("%s: Failed to start codec looper: %s (%d)",
1322 __FUNCTION__, strerror(-res), res);
1323 return NO_INIT;
1324 }
1325
1326 // Create HEIC/HEVC codec.
Chong Zhang688abaa2019-05-17 16:32:23 -07001327 if (mUseHeic) {
1328 mCodec = MediaCodec::CreateByType(mCodecLooper, desiredMime, true /*encoder*/);
1329 } else {
1330 mCodec = MediaCodec::CreateByComponentName(mCodecLooper, hevcName);
1331 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001332 if (mCodec == nullptr) {
1333 ALOGE("%s: Failed to create codec for %s", __FUNCTION__, desiredMime);
1334 return NO_INIT;
1335 }
1336
1337 // Create Looper and handler for Codec callback.
1338 mCodecCallbackHandler = new CodecCallbackHandler(this);
1339 if (mCodecCallbackHandler == nullptr) {
1340 ALOGE("%s: Failed to create codec callback handler", __FUNCTION__);
1341 return NO_MEMORY;
1342 }
1343 mCallbackLooper = new ALooper;
1344 mCallbackLooper->setName("Camera3-HeicComposite-MediaCodecCallbackLooper");
1345 res = mCallbackLooper->start(
1346 false, // runOnCallingThread
1347 false, // canCallJava
1348 PRIORITY_AUDIO);
1349 if (res != OK) {
1350 ALOGE("%s: Failed to start media callback looper: %s (%d)",
1351 __FUNCTION__, strerror(-res), res);
1352 return NO_INIT;
1353 }
1354 mCallbackLooper->registerHandler(mCodecCallbackHandler);
1355
1356 mAsyncNotify = new AMessage(kWhatCallbackNotify, mCodecCallbackHandler);
1357 res = mCodec->setCallback(mAsyncNotify);
1358 if (res != OK) {
1359 ALOGE("%s: Failed to set MediaCodec callback: %s (%d)", __FUNCTION__,
1360 strerror(-res), res);
1361 return res;
1362 }
1363
1364 // Create output format and configure the Codec.
1365 sp<AMessage> outputFormat = new AMessage();
1366 outputFormat->setString(KEY_MIME, desiredMime);
1367 outputFormat->setInt32(KEY_BITRATE_MODE, BITRATE_MODE_CQ);
1368 outputFormat->setInt32(KEY_QUALITY, kDefaultJpegQuality);
1369 // Ask codec to skip timestamp check and encode all frames.
Chong Zhang70bfcec2019-03-18 12:52:28 -07001370 outputFormat->setInt64(KEY_MAX_PTS_GAP_TO_ENCODER, kNoFrameDropMaxPtsGap);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001371
1372 int32_t gridWidth, gridHeight, gridRows, gridCols;
1373 if (useGrid || mUseHeic) {
1374 gridWidth = HeicEncoderInfoManager::kGridWidth;
1375 gridHeight = HeicEncoderInfoManager::kGridHeight;
1376 gridRows = (height + gridHeight - 1)/gridHeight;
1377 gridCols = (width + gridWidth - 1)/gridWidth;
1378
1379 if (mUseHeic) {
1380 outputFormat->setInt32(KEY_TILE_WIDTH, gridWidth);
1381 outputFormat->setInt32(KEY_TILE_HEIGHT, gridHeight);
1382 outputFormat->setInt32(KEY_GRID_COLUMNS, gridCols);
1383 outputFormat->setInt32(KEY_GRID_ROWS, gridRows);
1384 }
1385
1386 } else {
1387 gridWidth = width;
1388 gridHeight = height;
1389 gridRows = 1;
1390 gridCols = 1;
1391 }
1392
1393 outputFormat->setInt32(KEY_WIDTH, !useGrid ? width : gridWidth);
1394 outputFormat->setInt32(KEY_HEIGHT, !useGrid ? height : gridHeight);
1395 outputFormat->setInt32(KEY_I_FRAME_INTERVAL, 0);
1396 outputFormat->setInt32(KEY_COLOR_FORMAT,
1397 useGrid ? COLOR_FormatYUV420Flexible : COLOR_FormatSurface);
Shuzhen Wang0ca81522019-08-30 14:15:16 -07001398 outputFormat->setInt32(KEY_FRAME_RATE, useGrid ? gridRows * gridCols : kNoGridOpRate);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001399 // This only serves as a hint to encoder when encoding is not real-time.
1400 outputFormat->setInt32(KEY_OPERATING_RATE, useGrid ? kGridOpRate : kNoGridOpRate);
1401
1402 res = mCodec->configure(outputFormat, nullptr /*nativeWindow*/,
1403 nullptr /*crypto*/, CONFIGURE_FLAG_ENCODE);
1404 if (res != OK) {
1405 ALOGE("%s: Failed to configure codec: %s (%d)", __FUNCTION__,
1406 strerror(-res), res);
1407 return res;
1408 }
1409
1410 mGridWidth = gridWidth;
1411 mGridHeight = gridHeight;
1412 mGridRows = gridRows;
1413 mGridCols = gridCols;
1414 mUseGrid = useGrid;
1415 mOutputWidth = width;
1416 mOutputHeight = height;
1417 mAppSegmentMaxSize = calcAppSegmentMaxSize(cameraDevice->info());
Susmitha Gummallae911f2e2020-11-23 09:57:03 -08001418 mMaxHeicBufferSize =
1419 ALIGN(mOutputWidth, HeicEncoderInfoManager::kGridWidth) *
1420 ALIGN(mOutputHeight, HeicEncoderInfoManager::kGridHeight) * 3 / 2 + mAppSegmentMaxSize;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001421
1422 return OK;
1423}
1424
1425void HeicCompositeStream::deinitCodec() {
1426 ALOGV("%s", __FUNCTION__);
1427 if (mCodec != nullptr) {
1428 mCodec->stop();
1429 mCodec->release();
1430 mCodec.clear();
1431 }
1432
1433 if (mCodecLooper != nullptr) {
1434 mCodecLooper->stop();
1435 mCodecLooper.clear();
1436 }
1437
1438 if (mCallbackLooper != nullptr) {
1439 mCallbackLooper->stop();
1440 mCallbackLooper.clear();
1441 }
1442
1443 mAsyncNotify.clear();
1444 mFormat.clear();
1445}
1446
1447// Return the size of the complete list of app segment, 0 indicates failure
1448size_t HeicCompositeStream::findAppSegmentsSize(const uint8_t* appSegmentBuffer,
1449 size_t maxSize, size_t *app1SegmentSize) {
1450 if (appSegmentBuffer == nullptr || app1SegmentSize == nullptr) {
1451 ALOGE("%s: Invalid input appSegmentBuffer %p, app1SegmentSize %p",
1452 __FUNCTION__, appSegmentBuffer, app1SegmentSize);
1453 return 0;
1454 }
1455
1456 size_t expectedSize = 0;
1457 // First check for EXIF transport header at the end of the buffer
Jayant Chowdharyc67af1b2022-04-07 18:05:04 +00001458 const uint8_t *header = appSegmentBuffer + (maxSize - sizeof(CameraBlob));
1459 const CameraBlob *blob = (const CameraBlob*)(header);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001460 if (blob->blobId != CameraBlobId::JPEG_APP_SEGMENTS) {
Jayant Chowdharyc67af1b2022-04-07 18:05:04 +00001461 ALOGE("%s: Invalid EXIF blobId %d", __FUNCTION__, blob->blobId);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001462 return 0;
1463 }
1464
Jayant Chowdharyc67af1b2022-04-07 18:05:04 +00001465 expectedSize = blob->blobSizeBytes;
1466 if (expectedSize == 0 || expectedSize > maxSize - sizeof(CameraBlob)) {
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001467 ALOGE("%s: Invalid blobSize %zu.", __FUNCTION__, expectedSize);
1468 return 0;
1469 }
1470
1471 uint32_t totalSize = 0;
1472
1473 // Verify APP1 marker (mandatory)
1474 uint8_t app1Marker[] = {0xFF, 0xE1};
1475 if (memcmp(appSegmentBuffer, app1Marker, sizeof(app1Marker))) {
1476 ALOGE("%s: Invalid APP1 marker: %x, %x", __FUNCTION__,
1477 appSegmentBuffer[0], appSegmentBuffer[1]);
1478 return 0;
1479 }
1480 totalSize += sizeof(app1Marker);
1481
1482 uint16_t app1Size = (static_cast<uint16_t>(appSegmentBuffer[totalSize]) << 8) +
1483 appSegmentBuffer[totalSize+1];
1484 totalSize += app1Size;
1485
1486 ALOGV("%s: Expected APP segments size %zu, APP1 segment size %u",
1487 __FUNCTION__, expectedSize, app1Size);
1488 while (totalSize < expectedSize) {
1489 if (appSegmentBuffer[totalSize] != 0xFF ||
1490 appSegmentBuffer[totalSize+1] <= 0xE1 ||
1491 appSegmentBuffer[totalSize+1] > 0xEF) {
1492 // Invalid APPn marker
1493 ALOGE("%s: Invalid APPn marker: %x, %x", __FUNCTION__,
1494 appSegmentBuffer[totalSize], appSegmentBuffer[totalSize+1]);
1495 return 0;
1496 }
1497 totalSize += 2;
1498
1499 uint16_t appnSize = (static_cast<uint16_t>(appSegmentBuffer[totalSize]) << 8) +
1500 appSegmentBuffer[totalSize+1];
1501 totalSize += appnSize;
1502 }
1503
1504 if (totalSize != expectedSize) {
1505 ALOGE("%s: Invalid JPEG APP segments: totalSize %u vs expected size %zu",
1506 __FUNCTION__, totalSize, expectedSize);
1507 return 0;
1508 }
1509
1510 *app1SegmentSize = app1Size + sizeof(app1Marker);
1511 return expectedSize;
1512}
1513
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001514status_t HeicCompositeStream::copyOneYuvTile(sp<MediaCodecBuffer>& codecBuffer,
1515 const CpuConsumer::LockedBuffer& yuvBuffer,
1516 size_t top, size_t left, size_t width, size_t height) {
1517 ATRACE_CALL();
1518
1519 // Get stride information for codecBuffer
1520 sp<ABuffer> imageData;
1521 if (!codecBuffer->meta()->findBuffer("image-data", &imageData)) {
1522 ALOGE("%s: Codec input buffer is not for image data!", __FUNCTION__);
1523 return BAD_VALUE;
1524 }
1525 if (imageData->size() != sizeof(MediaImage2)) {
1526 ALOGE("%s: Invalid codec input image size %zu, expected %zu",
1527 __FUNCTION__, imageData->size(), sizeof(MediaImage2));
1528 return BAD_VALUE;
1529 }
1530 MediaImage2* imageInfo = reinterpret_cast<MediaImage2*>(imageData->data());
1531 if (imageInfo->mType != MediaImage2::MEDIA_IMAGE_TYPE_YUV ||
1532 imageInfo->mBitDepth != 8 ||
1533 imageInfo->mBitDepthAllocated != 8 ||
1534 imageInfo->mNumPlanes != 3) {
1535 ALOGE("%s: Invalid codec input image info: mType %d, mBitDepth %d, "
1536 "mBitDepthAllocated %d, mNumPlanes %d!", __FUNCTION__,
1537 imageInfo->mType, imageInfo->mBitDepth,
1538 imageInfo->mBitDepthAllocated, imageInfo->mNumPlanes);
1539 return BAD_VALUE;
1540 }
1541
1542 ALOGV("%s: yuvBuffer chromaStep %d, chromaStride %d",
1543 __FUNCTION__, yuvBuffer.chromaStep, yuvBuffer.chromaStride);
1544 ALOGV("%s: U offset %u, V offset %u, U rowInc %d, V rowInc %d, U colInc %d, V colInc %d",
1545 __FUNCTION__, imageInfo->mPlane[MediaImage2::U].mOffset,
1546 imageInfo->mPlane[MediaImage2::V].mOffset,
1547 imageInfo->mPlane[MediaImage2::U].mRowInc,
1548 imageInfo->mPlane[MediaImage2::V].mRowInc,
1549 imageInfo->mPlane[MediaImage2::U].mColInc,
1550 imageInfo->mPlane[MediaImage2::V].mColInc);
1551
1552 // Y
1553 for (auto row = top; row < top+height; row++) {
1554 uint8_t *dst = codecBuffer->data() + imageInfo->mPlane[MediaImage2::Y].mOffset +
1555 imageInfo->mPlane[MediaImage2::Y].mRowInc * (row - top);
Shuzhen Wang219c2992019-02-15 17:24:28 -08001556 mFnCopyRow(yuvBuffer.data+row*yuvBuffer.stride+left, dst, width);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001557 }
1558
1559 // U is Cb, V is Cr
1560 bool codecUPlaneFirst = imageInfo->mPlane[MediaImage2::V].mOffset >
1561 imageInfo->mPlane[MediaImage2::U].mOffset;
1562 uint32_t codecUvOffsetDiff = codecUPlaneFirst ?
1563 imageInfo->mPlane[MediaImage2::V].mOffset - imageInfo->mPlane[MediaImage2::U].mOffset :
1564 imageInfo->mPlane[MediaImage2::U].mOffset - imageInfo->mPlane[MediaImage2::V].mOffset;
1565 bool isCodecUvSemiplannar = (codecUvOffsetDiff == 1) &&
1566 (imageInfo->mPlane[MediaImage2::U].mRowInc ==
1567 imageInfo->mPlane[MediaImage2::V].mRowInc) &&
1568 (imageInfo->mPlane[MediaImage2::U].mColInc == 2) &&
1569 (imageInfo->mPlane[MediaImage2::V].mColInc == 2);
1570 bool isCodecUvPlannar =
1571 ((codecUPlaneFirst && codecUvOffsetDiff >=
1572 imageInfo->mPlane[MediaImage2::U].mRowInc * imageInfo->mHeight/2) ||
1573 ((!codecUPlaneFirst && codecUvOffsetDiff >=
1574 imageInfo->mPlane[MediaImage2::V].mRowInc * imageInfo->mHeight/2))) &&
1575 imageInfo->mPlane[MediaImage2::U].mColInc == 1 &&
1576 imageInfo->mPlane[MediaImage2::V].mColInc == 1;
1577 bool cameraUPlaneFirst = yuvBuffer.dataCr > yuvBuffer.dataCb;
1578
1579 if (isCodecUvSemiplannar && yuvBuffer.chromaStep == 2 &&
1580 (codecUPlaneFirst == cameraUPlaneFirst)) {
1581 // UV semiplannar
1582 // The chrome plane could be either Cb first, or Cr first. Take the
1583 // smaller address.
1584 uint8_t *src = std::min(yuvBuffer.dataCb, yuvBuffer.dataCr);
1585 MediaImage2::PlaneIndex dstPlane = codecUvOffsetDiff > 0 ? MediaImage2::U : MediaImage2::V;
1586 for (auto row = top/2; row < (top+height)/2; row++) {
1587 uint8_t *dst = codecBuffer->data() + imageInfo->mPlane[dstPlane].mOffset +
1588 imageInfo->mPlane[dstPlane].mRowInc * (row - top/2);
Shuzhen Wang219c2992019-02-15 17:24:28 -08001589 mFnCopyRow(src+row*yuvBuffer.chromaStride+left, dst, width);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001590 }
1591 } else if (isCodecUvPlannar && yuvBuffer.chromaStep == 1) {
1592 // U plane
1593 for (auto row = top/2; row < (top+height)/2; row++) {
1594 uint8_t *dst = codecBuffer->data() + imageInfo->mPlane[MediaImage2::U].mOffset +
1595 imageInfo->mPlane[MediaImage2::U].mRowInc * (row - top/2);
Shuzhen Wang219c2992019-02-15 17:24:28 -08001596 mFnCopyRow(yuvBuffer.dataCb+row*yuvBuffer.chromaStride+left/2, dst, width/2);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001597 }
1598
1599 // V plane
1600 for (auto row = top/2; row < (top+height)/2; row++) {
1601 uint8_t *dst = codecBuffer->data() + imageInfo->mPlane[MediaImage2::V].mOffset +
1602 imageInfo->mPlane[MediaImage2::V].mRowInc * (row - top/2);
Shuzhen Wang219c2992019-02-15 17:24:28 -08001603 mFnCopyRow(yuvBuffer.dataCr+row*yuvBuffer.chromaStride+left/2, dst, width/2);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001604 }
1605 } else {
Shuzhen Wang219c2992019-02-15 17:24:28 -08001606 // Convert between semiplannar and plannar, or when UV orders are
1607 // different.
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001608 uint8_t *dst = codecBuffer->data();
1609 for (auto row = top/2; row < (top+height)/2; row++) {
1610 for (auto col = left/2; col < (left+width)/2; col++) {
1611 // U/Cb
1612 int32_t dstIndex = imageInfo->mPlane[MediaImage2::U].mOffset +
1613 imageInfo->mPlane[MediaImage2::U].mRowInc * (row - top/2) +
1614 imageInfo->mPlane[MediaImage2::U].mColInc * (col - left/2);
1615 int32_t srcIndex = row * yuvBuffer.chromaStride + yuvBuffer.chromaStep * col;
1616 dst[dstIndex] = yuvBuffer.dataCb[srcIndex];
1617
1618 // V/Cr
1619 dstIndex = imageInfo->mPlane[MediaImage2::V].mOffset +
1620 imageInfo->mPlane[MediaImage2::V].mRowInc * (row - top/2) +
1621 imageInfo->mPlane[MediaImage2::V].mColInc * (col - left/2);
1622 srcIndex = row * yuvBuffer.chromaStride + yuvBuffer.chromaStep * col;
1623 dst[dstIndex] = yuvBuffer.dataCr[srcIndex];
1624 }
1625 }
1626 }
1627 return OK;
1628}
1629
Colin Cross14900c92023-01-13 14:50:17 -08001630void HeicCompositeStream::initCopyRowFunction([[maybe_unused]] int32_t width)
Shuzhen Wang219c2992019-02-15 17:24:28 -08001631{
1632 using namespace libyuv;
1633
1634 mFnCopyRow = CopyRow_C;
1635#if defined(HAS_COPYROW_SSE2)
1636 if (TestCpuFlag(kCpuHasSSE2)) {
1637 mFnCopyRow = IS_ALIGNED(width, 32) ? CopyRow_SSE2 : CopyRow_Any_SSE2;
1638 }
1639#endif
1640#if defined(HAS_COPYROW_AVX)
1641 if (TestCpuFlag(kCpuHasAVX)) {
1642 mFnCopyRow = IS_ALIGNED(width, 64) ? CopyRow_AVX : CopyRow_Any_AVX;
1643 }
1644#endif
1645#if defined(HAS_COPYROW_ERMS)
1646 if (TestCpuFlag(kCpuHasERMS)) {
1647 mFnCopyRow = CopyRow_ERMS;
1648 }
1649#endif
1650#if defined(HAS_COPYROW_NEON)
1651 if (TestCpuFlag(kCpuHasNEON)) {
1652 mFnCopyRow = IS_ALIGNED(width, 32) ? CopyRow_NEON : CopyRow_Any_NEON;
1653 }
1654#endif
1655#if defined(HAS_COPYROW_MIPS)
1656 if (TestCpuFlag(kCpuHasMIPS)) {
1657 mFnCopyRow = CopyRow_MIPS;
1658 }
1659#endif
1660}
1661
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001662size_t HeicCompositeStream::calcAppSegmentMaxSize(const CameraMetadata& info) {
1663 camera_metadata_ro_entry_t entry = info.find(ANDROID_HEIC_INFO_MAX_JPEG_APP_SEGMENTS_COUNT);
1664 size_t maxAppsSegment = 1;
1665 if (entry.count > 0) {
1666 maxAppsSegment = entry.data.u8[0] < 1 ? 1 :
1667 entry.data.u8[0] > 16 ? 16 : entry.data.u8[0];
1668 }
Jayant Chowdharyc67af1b2022-04-07 18:05:04 +00001669 return maxAppsSegment * (2 + 0xFFFF) + sizeof(CameraBlob);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001670}
1671
Shuzhen Wang62f49ed2019-09-04 14:07:53 -07001672void HeicCompositeStream::updateCodecQualityLocked(int32_t quality) {
1673 if (quality != mQuality) {
1674 sp<AMessage> qualityParams = new AMessage;
1675 qualityParams->setInt32(PARAMETER_KEY_VIDEO_BITRATE, quality);
1676 status_t res = mCodec->setParameters(qualityParams);
1677 if (res != OK) {
1678 ALOGE("%s: Failed to set codec quality: %s (%d)",
1679 __FUNCTION__, strerror(-res), res);
1680 } else {
1681 mQuality = quality;
1682 }
1683 }
1684}
1685
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001686bool HeicCompositeStream::threadLoop() {
Shuzhen Wange8675782019-12-05 09:12:14 -08001687 int64_t frameNumber = -1;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001688 bool newInputAvailable = false;
1689
1690 {
1691 Mutex::Autolock l(mMutex);
1692 if (mErrorState) {
1693 // In case we landed in error state, return any pending buffers and
1694 // halt all further processing.
1695 compilePendingInputLocked();
Michael Gonzalezb5986a32019-10-09 15:38:17 -07001696 releaseInputFramesLocked();
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001697 return false;
1698 }
1699
1700
1701 while (!newInputAvailable) {
1702 compilePendingInputLocked();
Shuzhen Wange8675782019-12-05 09:12:14 -08001703 newInputAvailable = getNextReadyInputLocked(&frameNumber);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001704
1705 if (!newInputAvailable) {
Shuzhen Wange8675782019-12-05 09:12:14 -08001706 auto failingFrameNumber = getNextFailingInputLocked();
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001707 if (failingFrameNumber >= 0) {
Shuzhen Wange8675782019-12-05 09:12:14 -08001708 releaseInputFrameLocked(failingFrameNumber,
1709 &mPendingInputFrames[failingFrameNumber]);
1710
1711 // It's okay to remove the entry from mPendingInputFrames
1712 // because:
1713 // 1. Only one internal stream (main input) is critical in
1714 // backing the output stream.
1715 // 2. If captureResult/appSegment arrives after the entry is
1716 // removed, they are simply skipped.
1717 mPendingInputFrames.erase(failingFrameNumber);
1718 if (mPendingInputFrames.size() == 0) {
1719 markTrackerIdle();
1720 }
1721 return true;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001722 }
1723
1724 auto ret = mInputReadyCondition.waitRelative(mMutex, kWaitDuration);
1725 if (ret == TIMED_OUT) {
1726 return true;
1727 } else if (ret != OK) {
1728 ALOGE("%s: Timed wait on condition failed: %s (%d)", __FUNCTION__,
1729 strerror(-ret), ret);
1730 return false;
1731 }
1732 }
1733 }
1734 }
1735
Shuzhen Wange8675782019-12-05 09:12:14 -08001736 auto res = processInputFrame(frameNumber, mPendingInputFrames[frameNumber]);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001737 Mutex::Autolock l(mMutex);
1738 if (res != OK) {
Shuzhen Wange8675782019-12-05 09:12:14 -08001739 ALOGE("%s: Failed processing frame with timestamp: %" PRIu64 ", frameNumber: %"
1740 PRId64 ": %s (%d)", __FUNCTION__, mPendingInputFrames[frameNumber].timestamp,
1741 frameNumber, strerror(-res), res);
1742 mPendingInputFrames[frameNumber].error = true;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001743 }
1744
Michael Gonzalezb5986a32019-10-09 15:38:17 -07001745 releaseInputFramesLocked();
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001746
1747 return true;
1748}
1749
Shuzhen Wange8675782019-12-05 09:12:14 -08001750void HeicCompositeStream::flagAnExifErrorFrameNumber(int64_t frameNumber) {
1751 Mutex::Autolock l(mMutex);
1752 mExifErrorFrameNumbers.emplace(frameNumber);
1753 mInputReadyCondition.signal();
1754}
1755
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001756bool HeicCompositeStream::onStreamBufferError(const CaptureResultExtras& resultExtras) {
1757 bool res = false;
Shuzhen Wange8675782019-12-05 09:12:14 -08001758 int64_t frameNumber = resultExtras.frameNumber;
1759
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001760 // Buffer errors concerning internal composite streams should not be directly visible to
1761 // camera clients. They must only receive a single buffer error with the public composite
1762 // stream id.
Shuzhen Wange8675782019-12-05 09:12:14 -08001763 if (resultExtras.errorStreamId == mAppSegmentStreamId) {
1764 ALOGV("%s: APP_SEGMENT frameNumber: %" PRId64, __FUNCTION__, frameNumber);
1765 flagAnExifErrorFrameNumber(frameNumber);
1766 res = true;
1767 } else if (resultExtras.errorStreamId == mMainImageStreamId) {
1768 ALOGV("%s: YUV frameNumber: %" PRId64, __FUNCTION__, frameNumber);
1769 flagAnErrorFrameNumber(frameNumber);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001770 res = true;
1771 }
1772
1773 return res;
1774}
1775
Shuzhen Wange7f4b462019-02-12 08:43:07 -08001776void HeicCompositeStream::onResultError(const CaptureResultExtras& resultExtras) {
1777 // For result error, since the APPS_SEGMENT buffer already contains EXIF,
1778 // simply skip using the capture result metadata to override EXIF.
1779 Mutex::Autolock l(mMutex);
1780
1781 int64_t timestamp = -1;
Shuzhen Wange8675782019-12-05 09:12:14 -08001782 for (const auto& fn : mSettingsByFrameNumber) {
Shuzhen Wange7f4b462019-02-12 08:43:07 -08001783 if (fn.first == resultExtras.frameNumber) {
Shuzhen Wange8675782019-12-05 09:12:14 -08001784 timestamp = fn.second.timestamp;
Shuzhen Wange7f4b462019-02-12 08:43:07 -08001785 break;
1786 }
1787 }
1788 if (timestamp == -1) {
1789 for (const auto& inputFrame : mPendingInputFrames) {
Shuzhen Wange8675782019-12-05 09:12:14 -08001790 if (inputFrame.first == resultExtras.frameNumber) {
1791 timestamp = inputFrame.second.timestamp;
Shuzhen Wange7f4b462019-02-12 08:43:07 -08001792 break;
1793 }
1794 }
1795 }
1796
1797 if (timestamp == -1) {
1798 ALOGE("%s: Failed to find shutter timestamp for result error!", __FUNCTION__);
1799 return;
1800 }
1801
1802 mCaptureResults.emplace(timestamp, std::make_tuple(resultExtras.frameNumber, CameraMetadata()));
Shuzhen Wange8675782019-12-05 09:12:14 -08001803 ALOGV("%s: timestamp %" PRId64 ", frameNumber %" PRId64, __FUNCTION__,
1804 timestamp, resultExtras.frameNumber);
Shuzhen Wange7f4b462019-02-12 08:43:07 -08001805 mInputReadyCondition.signal();
1806}
1807
Shuzhen Wange8675782019-12-05 09:12:14 -08001808void HeicCompositeStream::onRequestError(const CaptureResultExtras& resultExtras) {
1809 auto frameNumber = resultExtras.frameNumber;
1810 ALOGV("%s: frameNumber: %" PRId64, __FUNCTION__, frameNumber);
1811 Mutex::Autolock l(mMutex);
1812 auto numRequests = mSettingsByFrameNumber.erase(frameNumber);
1813 if (numRequests == 0) {
1814 // Pending request has been populated into mPendingInputFrames
1815 mErrorFrameNumbers.emplace(frameNumber);
1816 mInputReadyCondition.signal();
1817 } else {
1818 // REQUEST_ERROR was received without onShutter.
1819 }
1820}
1821
1822void HeicCompositeStream::markTrackerIdle() {
1823 sp<StatusTracker> statusTracker = mStatusTracker.promote();
1824 if (statusTracker != nullptr) {
1825 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
1826 ALOGV("%s: Mark component as idle", __FUNCTION__);
1827 }
1828}
1829
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001830void HeicCompositeStream::CodecCallbackHandler::onMessageReceived(const sp<AMessage> &msg) {
1831 sp<HeicCompositeStream> parent = mParent.promote();
1832 if (parent == nullptr) return;
1833
1834 switch (msg->what()) {
1835 case kWhatCallbackNotify: {
1836 int32_t cbID;
1837 if (!msg->findInt32("callbackID", &cbID)) {
1838 ALOGE("kWhatCallbackNotify: callbackID is expected.");
1839 break;
1840 }
1841
1842 ALOGV("kWhatCallbackNotify: cbID = %d", cbID);
1843
1844 switch (cbID) {
1845 case MediaCodec::CB_INPUT_AVAILABLE: {
1846 int32_t index;
1847 if (!msg->findInt32("index", &index)) {
1848 ALOGE("CB_INPUT_AVAILABLE: index is expected.");
1849 break;
1850 }
1851 parent->onHeicInputFrameAvailable(index);
1852 break;
1853 }
1854
1855 case MediaCodec::CB_OUTPUT_AVAILABLE: {
1856 int32_t index;
1857 size_t offset;
1858 size_t size;
1859 int64_t timeUs;
1860 int32_t flags;
1861
1862 if (!msg->findInt32("index", &index)) {
1863 ALOGE("CB_OUTPUT_AVAILABLE: index is expected.");
1864 break;
1865 }
1866 if (!msg->findSize("offset", &offset)) {
1867 ALOGE("CB_OUTPUT_AVAILABLE: offset is expected.");
1868 break;
1869 }
1870 if (!msg->findSize("size", &size)) {
1871 ALOGE("CB_OUTPUT_AVAILABLE: size is expected.");
1872 break;
1873 }
1874 if (!msg->findInt64("timeUs", &timeUs)) {
1875 ALOGE("CB_OUTPUT_AVAILABLE: timeUs is expected.");
1876 break;
1877 }
1878 if (!msg->findInt32("flags", &flags)) {
1879 ALOGE("CB_OUTPUT_AVAILABLE: flags is expected.");
1880 break;
1881 }
1882
1883 CodecOutputBufferInfo bufferInfo = {
1884 index,
1885 (int32_t)offset,
1886 (int32_t)size,
1887 timeUs,
1888 (uint32_t)flags};
1889
1890 parent->onHeicOutputFrameAvailable(bufferInfo);
1891 break;
1892 }
1893
1894 case MediaCodec::CB_OUTPUT_FORMAT_CHANGED: {
1895 sp<AMessage> format;
1896 if (!msg->findMessage("format", &format)) {
1897 ALOGE("CB_OUTPUT_FORMAT_CHANGED: format is expected.");
1898 break;
1899 }
Chong Zhang860eff12019-09-16 16:15:00 -07001900 // Here format is MediaCodec's internal copy of output format.
1901 // Make a copy since onHeicFormatChanged() might modify it.
1902 sp<AMessage> formatCopy;
1903 if (format != nullptr) {
1904 formatCopy = format->dup();
1905 }
1906 parent->onHeicFormatChanged(formatCopy);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001907 break;
1908 }
1909
1910 case MediaCodec::CB_ERROR: {
1911 status_t err;
1912 int32_t actionCode;
1913 AString detail;
1914 if (!msg->findInt32("err", &err)) {
1915 ALOGE("CB_ERROR: err is expected.");
1916 break;
1917 }
1918 if (!msg->findInt32("action", &actionCode)) {
1919 ALOGE("CB_ERROR: action is expected.");
1920 break;
1921 }
1922 msg->findString("detail", &detail);
1923 ALOGE("Codec reported error(0x%x), actionCode(%d), detail(%s)",
1924 err, actionCode, detail.c_str());
1925
1926 parent->onHeicCodecError();
1927 break;
1928 }
1929
1930 default: {
1931 ALOGE("kWhatCallbackNotify: callbackID(%d) is unexpected.", cbID);
1932 break;
1933 }
1934 }
1935 break;
1936 }
1937
1938 default:
1939 ALOGE("shouldn't be here");
1940 break;
1941 }
1942}
1943
1944}; // namespace camera3
1945}; // namespace android