blob: 7c3c6b78e63d543917e907ca802b2f8c3303ce70 [file] [log] [blame]
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001/*
Shuzhen Wangc28189a2017-11-27 23:05:10 -08002 * Copyright (C) 2013-2018 The Android Open Source Project
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003 *
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-Device"
18#define ATRACE_TAG ATRACE_TAG_CAMERA
19//#define LOG_NDEBUG 0
20//#define LOG_NNDEBUG 0 // Per-frame verbose logging
21
22#ifdef LOG_NNDEBUG
23#define ALOGVV(...) ALOGV(__VA_ARGS__)
24#else
25#define ALOGVV(...) ((void)0)
26#endif
27
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -070028// Convenience macro for transient errors
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080029#define CLOGE(fmt, ...) ALOGE("Camera %s: %s: " fmt, mId.string(), __FUNCTION__, \
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -070030 ##__VA_ARGS__)
31
Yin-Chia Yeh99fd0972019-06-27 14:22:44 -070032#define CLOGW(fmt, ...) ALOGW("Camera %s: %s: " fmt, mId.string(), __FUNCTION__, \
33 ##__VA_ARGS__)
34
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -070035// Convenience macros for transitioning to the error state
36#define SET_ERR(fmt, ...) setErrorState( \
37 "%s: " fmt, __FUNCTION__, \
38 ##__VA_ARGS__)
39#define SET_ERR_L(fmt, ...) setErrorStateLocked( \
40 "%s: " fmt, __FUNCTION__, \
41 ##__VA_ARGS__)
42
Colin Crosse5729fa2014-03-21 15:04:25 -070043#include <inttypes.h>
44
Shuzhen Wang5c22c152017-12-31 17:12:25 -080045#include <utility>
46
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080047#include <utils/Log.h>
48#include <utils/Trace.h>
49#include <utils/Timers.h>
Zhijun He90f7c372016-08-16 16:19:43 -070050#include <cutils/properties.h>
Eino-Ville Talvala7b82efe2013-07-25 17:12:35 -070051
Cliff Wuc2ad9c82021-04-21 00:58:58 +080052#include <android/hardware/camera/device/3.7/ICameraInjectionSession.h>
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -080053#include <android/hardware/camera2/ICameraDeviceUser.h>
54
Igor Murashkinff3e31d2013-10-23 16:40:06 -070055#include "utils/CameraTraces.h"
Eino-Ville Talvalaf99498e2015-09-25 16:52:55 -070056#include "mediautils/SchedulingPolicyService.h"
Eino-Ville Talvala7b82efe2013-07-25 17:12:35 -070057#include "device3/Camera3Device.h"
58#include "device3/Camera3OutputStream.h"
59#include "device3/Camera3InputStream.h"
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -040060#include "device3/Camera3FakeStream.h"
Shuzhen Wang0129d522016-10-30 22:43:41 -070061#include "device3/Camera3SharedOutputStream.h"
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -070062#include "CameraService.h"
Jayant Chowdhary12361932018-08-27 14:46:13 -070063#include "utils/CameraThreadState.h"
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -080064#include "utils/SessionConfigurationUtils.h"
Jayant Chowdharyd4776262020-06-23 23:45:57 -070065#include "utils/TraceHFR.h"
Shuzhen Wang316781a2020-08-18 18:11:01 -070066#include "utils/CameraServiceProxyWrapper.h"
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -080067
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -080068#include <algorithm>
Yin-Chia Yeh84be5782019-03-01 11:47:02 -080069#include <tuple>
70
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -080071using namespace android::camera3;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080072using namespace android::hardware::camera;
73using namespace android::hardware::camera::device::V3_2;
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -080074using android::hardware::camera::metadata::V3_6::CameraMetadataEnumAndroidSensorPixelMode;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080075
76namespace android {
77
Shuzhen Wangd4abdf72021-05-28 11:22:50 -070078Camera3Device::Camera3Device(const String8 &id, bool overrideForPerfClass):
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080079 mId(id),
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -080080 mOperatingMode(NO_MODE),
Eino-Ville Talvala9a179412015-06-09 13:15:16 -070081 mIsConstrainedHighSpeedConfiguration(false),
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -070082 mStatus(STATUS_UNINITIALIZED),
Ruben Brunk183f0562015-08-12 12:55:02 -070083 mStatusWaiters(0),
Zhijun He204e3292014-07-14 17:09:23 -070084 mUsePartialResult(false),
85 mNumPartialResults(1),
Shuzhen Wangc28dccc2016-02-11 23:48:46 -080086 mTimestampOffset(0),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -070087 mNextResultFrameNumber(0),
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -070088 mNextReprocessResultFrameNumber(0),
Shuzhen Wang5ee99842019-04-12 11:55:48 -070089 mNextZslStillResultFrameNumber(0),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -070090 mNextShutterFrameNumber(0),
Chien-Yu Chen3df11ce2015-09-30 14:13:30 -070091 mNextReprocessShutterFrameNumber(0),
Shuzhen Wang5ee99842019-04-12 11:55:48 -070092 mNextZslStillShutterFrameNumber(0),
Emilian Peev71c73a22017-03-21 16:35:51 +000093 mListener(NULL),
Emilian Peev811d2952018-05-25 11:08:40 +010094 mVendorTagId(CAMERA_METADATA_INVALID_VENDOR_ID),
Shuzhen Wang268a1362018-10-16 16:32:59 -070095 mLastTemplateId(-1),
Shuzhen Wangd4abdf72021-05-28 11:22:50 -070096 mNeedFixupMonochromeTags(false),
97 mOverrideForPerfClass(overrideForPerfClass)
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080098{
99 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800100 ALOGV("%s: Created device for camera %s", __FUNCTION__, mId.string());
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800101}
102
103Camera3Device::~Camera3Device()
104{
105 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800106 ALOGV("%s: Tearing down for camera id %s", __FUNCTION__, mId.string());
Yin-Chia Yehc5248132018-08-15 12:19:20 -0700107 disconnectImpl();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800108}
109
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800110const String8& Camera3Device::getId() const {
Igor Murashkin71381052013-03-04 14:53:08 -0800111 return mId;
112}
113
Emilian Peevbd8c5032018-02-14 23:05:40 +0000114status_t Camera3Device::initialize(sp<CameraProviderManager> manager, const String8& monitorTags) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800115 ATRACE_CALL();
116 Mutex::Autolock il(mInterfaceLock);
117 Mutex::Autolock l(mLock);
118
119 ALOGV("%s: Initializing HIDL device for camera %s", __FUNCTION__, mId.string());
120 if (mStatus != STATUS_UNINITIALIZED) {
121 CLOGE("Already initialized!");
122 return INVALID_OPERATION;
123 }
124 if (manager == nullptr) return INVALID_OPERATION;
125
126 sp<ICameraDeviceSession> session;
127 ATRACE_BEGIN("CameraHal::openSession");
Steven Moreland5ff9c912017-03-09 23:13:00 -0800128 status_t res = manager->openSession(mId.string(), this,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800129 /*out*/ &session);
130 ATRACE_END();
131 if (res != OK) {
132 SET_ERR_L("Could not open camera session: %s (%d)", strerror(-res), res);
133 return res;
134 }
135
Shuzhen Wangd4abdf72021-05-28 11:22:50 -0700136 res = manager->getCameraCharacteristics(mId.string(), mOverrideForPerfClass, &mDeviceInfo);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800137 if (res != OK) {
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700138 SET_ERR_L("Could not retrieve camera characteristics: %s (%d)", strerror(-res), res);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800139 session->close();
140 return res;
141 }
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800142 mSupportNativeZoomRatio = manager->supportNativeZoomRatio(mId.string());
Yin-Chia Yeh52778d42016-12-22 18:20:43 -0800143
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700144 std::vector<std::string> physicalCameraIds;
Shuzhen Wang03d8cc12018-09-12 14:17:09 -0700145 bool isLogical = manager->isLogicalCamera(mId.string(), &physicalCameraIds);
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700146 if (isLogical) {
147 for (auto& physicalId : physicalCameraIds) {
Shuzhen Wangd4abdf72021-05-28 11:22:50 -0700148 // Do not override characteristics for physical cameras
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -0700149 res = manager->getCameraCharacteristics(
Shuzhen Wangd4abdf72021-05-28 11:22:50 -0700150 physicalId, /*overrideForPerfClass*/false, &mPhysicalDeviceInfoMap[physicalId]);
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700151 if (res != OK) {
152 SET_ERR_L("Could not retrieve camera %s characteristics: %s (%d)",
153 physicalId.c_str(), strerror(-res), res);
154 session->close();
155 return res;
156 }
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -0700157
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800158 bool usePrecorrectArray =
159 DistortionMapper::isDistortionSupported(mPhysicalDeviceInfoMap[physicalId]);
160 if (usePrecorrectArray) {
161 res = mDistortionMappers[physicalId].setupStaticInfo(
162 mPhysicalDeviceInfoMap[physicalId]);
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -0700163 if (res != OK) {
164 SET_ERR_L("Unable to read camera %s's calibration fields for distortion "
165 "correction", physicalId.c_str());
166 session->close();
167 return res;
168 }
169 }
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800170
Shuzhen Wang1c834da2019-12-18 11:17:03 -0800171 mZoomRatioMappers[physicalId] = ZoomRatioMapper(
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800172 &mPhysicalDeviceInfoMap[physicalId],
173 mSupportNativeZoomRatio, usePrecorrectArray);
Jayant Chowdhary9255ce02021-07-15 11:18:17 -0700174
175 if (SessionConfigurationUtils::isUltraHighResolutionSensor(
176 mPhysicalDeviceInfoMap[physicalId])) {
177 mUHRCropAndMeteringRegionMappers[physicalId] =
178 UHRCropAndMeteringRegionMapper(mPhysicalDeviceInfoMap[physicalId],
179 usePrecorrectArray);
180 }
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700181 }
182 }
183
Yifan Hongf79b5542017-04-11 14:44:25 -0700184 std::shared_ptr<RequestMetadataQueue> queue;
Yifan Honga640c5a2017-04-12 16:30:31 -0700185 auto requestQueueRet = session->getCaptureRequestMetadataQueue(
186 [&queue](const auto& descriptor) {
187 queue = std::make_shared<RequestMetadataQueue>(descriptor);
188 if (!queue->isValid() || queue->availableToWrite() <= 0) {
189 ALOGE("HAL returns empty request metadata fmq, not use it");
190 queue = nullptr;
191 // don't use the queue onwards.
192 }
193 });
194 if (!requestQueueRet.isOk()) {
195 ALOGE("Transaction error when getting request metadata fmq: %s, not use it",
196 requestQueueRet.description().c_str());
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -0700197 return DEAD_OBJECT;
Yifan Hongf79b5542017-04-11 14:44:25 -0700198 }
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700199
200 std::unique_ptr<ResultMetadataQueue>& resQueue = mResultMetadataQueue;
Yifan Honga640c5a2017-04-12 16:30:31 -0700201 auto resultQueueRet = session->getCaptureResultMetadataQueue(
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700202 [&resQueue](const auto& descriptor) {
203 resQueue = std::make_unique<ResultMetadataQueue>(descriptor);
204 if (!resQueue->isValid() || resQueue->availableToWrite() <= 0) {
Yifan Honga640c5a2017-04-12 16:30:31 -0700205 ALOGE("HAL returns empty result metadata fmq, not use it");
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700206 resQueue = nullptr;
207 // Don't use the resQueue onwards.
Yifan Honga640c5a2017-04-12 16:30:31 -0700208 }
209 });
210 if (!resultQueueRet.isOk()) {
211 ALOGE("Transaction error when getting result metadata queue from camera session: %s",
212 resultQueueRet.description().c_str());
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -0700213 return DEAD_OBJECT;
Yifan Honga640c5a2017-04-12 16:30:31 -0700214 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -0700215 IF_ALOGV() {
216 session->interfaceChain([](
217 ::android::hardware::hidl_vec<::android::hardware::hidl_string> interfaceChain) {
218 ALOGV("Session interface chain:");
Chih-Hung Hsieh3ef324d2018-12-11 11:48:12 -0800219 for (const auto& iface : interfaceChain) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -0700220 ALOGV(" %s", iface.c_str());
221 }
222 });
223 }
Yifan Hongf79b5542017-04-11 14:44:25 -0700224
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -0800225 camera_metadata_entry bufMgrMode =
226 mDeviceInfo.find(ANDROID_INFO_SUPPORTED_BUFFER_MANAGEMENT_VERSION);
227 if (bufMgrMode.count > 0) {
228 mUseHalBufManager = (bufMgrMode.data.u8[0] ==
229 ANDROID_INFO_SUPPORTED_BUFFER_MANAGEMENT_VERSION_HIDL_DEVICE_3_5);
230 }
231
Yin-Chia Yehb978c382019-10-30 00:22:37 -0700232 camera_metadata_entry_t capabilities = mDeviceInfo.find(ANDROID_REQUEST_AVAILABLE_CAPABILITIES);
233 for (size_t i = 0; i < capabilities.count; i++) {
234 uint8_t capability = capabilities.data.u8[i];
235 if (capability == ANDROID_REQUEST_AVAILABLE_CAPABILITIES_OFFLINE_PROCESSING) {
236 mSupportOfflineProcessing = true;
237 }
238 }
239
240 mInterface = new HalInterface(session, queue, mUseHalBufManager, mSupportOfflineProcessing);
Emilian Peev71c73a22017-03-21 16:35:51 +0000241 std::string providerType;
242 mVendorTagId = manager->getProviderTagIdLocked(mId.string());
Emilian Peevbd8c5032018-02-14 23:05:40 +0000243 mTagMonitor.initialize(mVendorTagId);
244 if (!monitorTags.isEmpty()) {
245 mTagMonitor.parseTagsToMonitor(String8(monitorTags));
246 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800247
Shuzhen Wang268a1362018-10-16 16:32:59 -0700248 // Metadata tags needs fixup for monochrome camera device version less
249 // than 3.5.
250 hardware::hidl_version maxVersion{0,0};
251 res = manager->getHighestSupportedVersion(mId.string(), &maxVersion);
252 if (res != OK) {
253 ALOGE("%s: Error in getting camera device version id: %s (%d)",
254 __FUNCTION__, strerror(-res), res);
255 return res;
256 }
257 int deviceVersion = HARDWARE_DEVICE_API_VERSION(
258 maxVersion.get_major(), maxVersion.get_minor());
259
260 bool isMonochrome = false;
Yin-Chia Yehb978c382019-10-30 00:22:37 -0700261 for (size_t i = 0; i < capabilities.count; i++) {
262 uint8_t capability = capabilities.data.u8[i];
Shuzhen Wang268a1362018-10-16 16:32:59 -0700263 if (capability == ANDROID_REQUEST_AVAILABLE_CAPABILITIES_MONOCHROME) {
264 isMonochrome = true;
265 }
266 }
267 mNeedFixupMonochromeTags = (isMonochrome && deviceVersion < CAMERA_DEVICE_API_VERSION_3_5);
268
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800269 return initializeCommonLocked();
270}
271
272status_t Camera3Device::initializeCommonLocked() {
273
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700274 /** Start up status tracker thread */
275 mStatusTracker = new StatusTracker(this);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800276 status_t res = mStatusTracker->run(String8::format("C3Dev-%s-Status", mId.string()).string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700277 if (res != OK) {
278 SET_ERR_L("Unable to start status tracking thread: %s (%d)",
279 strerror(-res), res);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800280 mInterface->close();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700281 mStatusTracker.clear();
282 return res;
283 }
284
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -0700285 /** Register in-flight map to the status tracker */
Yin-Chia Yeh87b3ec02019-06-03 10:44:39 -0700286 mInFlightStatusId = mStatusTracker->addComponent("InflightRequests");
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -0700287
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -0700288 if (mUseHalBufManager) {
289 res = mRequestBufferSM.initialize(mStatusTracker);
290 if (res != OK) {
291 SET_ERR_L("Unable to start request buffer state machine: %s (%d)",
292 strerror(-res), res);
293 mInterface->close();
294 mStatusTracker.clear();
295 return res;
296 }
297 }
298
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -0800299 /** Create buffer manager */
300 mBufferManager = new Camera3BufferManager();
301
302 Vector<int32_t> sessionParamKeys;
303 camera_metadata_entry_t sessionKeysEntry = mDeviceInfo.find(
304 ANDROID_REQUEST_AVAILABLE_SESSION_KEYS);
305 if (sessionKeysEntry.count > 0) {
306 sessionParamKeys.insertArrayAt(sessionKeysEntry.data.i32, 0, sessionKeysEntry.count);
307 }
308
Eino-Ville Talvala1646c3c2021-07-29 13:48:40 -0700309 camera_metadata_entry_t availableTestPatternModes = mDeviceInfo.find(
310 ANDROID_SENSOR_AVAILABLE_TEST_PATTERN_MODES);
311 for (size_t i = 0; i < availableTestPatternModes.count; i++) {
312 if (availableTestPatternModes.data.i32[i] ==
313 ANDROID_SENSOR_TEST_PATTERN_MODE_SOLID_COLOR) {
314 mSupportCameraMute = true;
315 mSupportTestPatternSolidColor = true;
316 break;
317 } else if (availableTestPatternModes.data.i32[i] ==
318 ANDROID_SENSOR_TEST_PATTERN_MODE_BLACK) {
319 mSupportCameraMute = true;
320 mSupportTestPatternSolidColor = false;
321 }
322 }
323
Chien-Yu Chenab5135b2015-06-30 11:20:58 -0700324 /** Start up request queue thread */
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -0700325 mRequestThread = new RequestThread(
Eino-Ville Talvala1646c3c2021-07-29 13:48:40 -0700326 this, mStatusTracker, mInterface, sessionParamKeys,
327 mUseHalBufManager, mSupportCameraMute);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800328 res = mRequestThread->run(String8::format("C3Dev-%s-ReqQueue", mId.string()).string());
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800329 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700330 SET_ERR_L("Unable to start request queue thread: %s (%d)",
331 strerror(-res), res);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800332 mInterface->close();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800333 mRequestThread.clear();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800334 return res;
335 }
336
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -0700337 mPreparerThread = new PreparerThread();
338
Ruben Brunk183f0562015-08-12 12:55:02 -0700339 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800340 mNextStreamId = 0;
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -0400341 mFakeStreamId = NO_STREAM;
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -0700342 mNeedConfig = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700343 mPauseStateNotify = false;
Shuzhen Wang83bff122020-11-20 15:51:39 -0800344 mIsInputStreamMultiResolution = false;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800345
Shuzhen Wangc28dccc2016-02-11 23:48:46 -0800346 // Measure the clock domain offset between camera and video/hw_composer
347 camera_metadata_entry timestampSource =
348 mDeviceInfo.find(ANDROID_SENSOR_INFO_TIMESTAMP_SOURCE);
349 if (timestampSource.count > 0 && timestampSource.data.u8[0] ==
350 ANDROID_SENSOR_INFO_TIMESTAMP_SOURCE_REALTIME) {
351 mTimestampOffset = getMonoToBoottimeOffset();
352 }
353
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -0700354 // Will the HAL be sending in early partial result metadata?
Emilian Peev08dd2452017-04-06 16:55:14 +0100355 camera_metadata_entry partialResultsCount =
356 mDeviceInfo.find(ANDROID_REQUEST_PARTIAL_RESULT_COUNT);
357 if (partialResultsCount.count > 0) {
358 mNumPartialResults = partialResultsCount.data.i32[0];
359 mUsePartialResult = (mNumPartialResults > 1);
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -0700360 }
361
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800362 bool usePrecorrectArray = DistortionMapper::isDistortionSupported(mDeviceInfo);
363 if (usePrecorrectArray) {
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -0700364 res = mDistortionMappers[mId.c_str()].setupStaticInfo(mDeviceInfo);
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -0700365 if (res != OK) {
366 SET_ERR_L("Unable to read necessary calibration fields for distortion correction");
367 return res;
368 }
369 }
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800370
Shuzhen Wang1c834da2019-12-18 11:17:03 -0800371 mZoomRatioMappers[mId.c_str()] = ZoomRatioMapper(&mDeviceInfo,
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800372 mSupportNativeZoomRatio, usePrecorrectArray);
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800373
Jayant Chowdhary9255ce02021-07-15 11:18:17 -0700374 if (SessionConfigurationUtils::isUltraHighResolutionSensor(mDeviceInfo)) {
375 mUHRCropAndMeteringRegionMappers[mId.c_str()] =
376 UHRCropAndMeteringRegionMapper(mDeviceInfo, usePrecorrectArray);
377 }
378
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -0800379 if (RotateAndCropMapper::isNeeded(&mDeviceInfo)) {
380 mRotateAndCropMappers.emplace(mId.c_str(), &mDeviceInfo);
381 }
382
Cliff Wuc2ad9c82021-04-21 00:58:58 +0800383 mInjectionMethods = new Camera3DeviceInjectionMethods(this);
384
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800385 return OK;
386}
387
388status_t Camera3Device::disconnect() {
Yin-Chia Yehc5248132018-08-15 12:19:20 -0700389 return disconnectImpl();
390}
391
392status_t Camera3Device::disconnectImpl() {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800393 ATRACE_CALL();
Yin-Chia Yehe1c80632016-08-08 14:48:05 -0700394 ALOGI("%s: E", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800395
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700396 status_t res = OK;
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700397 std::vector<wp<Camera3StreamInterface>> streams;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700398 {
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800399 Mutex::Autolock il(mInterfaceLock);
400 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
401 {
402 Mutex::Autolock l(mLock);
403 if (mStatus == STATUS_UNINITIALIZED) return res;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700404
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800405 if (mStatus == STATUS_ACTIVE ||
406 (mStatus == STATUS_ERROR && mRequestThread != NULL)) {
407 res = mRequestThread->clearRepeatingRequests();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700408 if (res != OK) {
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800409 SET_ERR_L("Can't stop streaming");
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700410 // Continue to close device even in case of error
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800411 } else {
412 res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
413 if (res != OK) {
414 SET_ERR_L("Timeout waiting for HAL to drain (% " PRIi64 " ns)",
415 maxExpectedDuration);
416 // Continue to close device even in case of error
417 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700418 }
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700419 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800420
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800421 if (mStatus == STATUS_ERROR) {
422 CLOGE("Shutting down in an error state");
423 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700424
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800425 if (mStatusTracker != NULL) {
426 mStatusTracker->requestExit();
427 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700428
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800429 if (mRequestThread != NULL) {
430 mRequestThread->requestExit();
431 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700432
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800433 streams.reserve(mOutputStreams.size() + (mInputStream != nullptr ? 1 : 0));
434 for (size_t i = 0; i < mOutputStreams.size(); i++) {
435 streams.push_back(mOutputStreams[i]);
436 }
437 if (mInputStream != nullptr) {
438 streams.push_back(mInputStream);
439 }
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700440 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700441 }
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800442 // Joining done without holding mLock and mInterfaceLock, otherwise deadlocks may ensue
443 // as the threads try to access parent state (b/143513518)
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700444 if (mRequestThread != NULL && mStatus != STATUS_ERROR) {
445 // HAL may be in a bad state, so waiting for request thread
446 // (which may be stuck in the HAL processCaptureRequest call)
447 // could be dangerous.
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800448 // give up mInterfaceLock here and then lock it again. Could this lead
449 // to other deadlocks
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700450 mRequestThread->join();
451 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700452 {
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800453 Mutex::Autolock il(mInterfaceLock);
454 if (mStatusTracker != NULL) {
455 mStatusTracker->join();
456 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800457
Cliff Wuc2ad9c82021-04-21 00:58:58 +0800458 if (mInjectionMethods->isInjecting()) {
459 mInjectionMethods->stopInjection();
460 }
461
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800462 HalInterface* interface;
463 {
464 Mutex::Autolock l(mLock);
465 mRequestThread.clear();
466 Mutex::Autolock stLock(mTrackerLock);
467 mStatusTracker.clear();
468 interface = mInterface.get();
469 }
Eino-Ville Talvalaefff1c42015-08-28 16:27:27 -0700470
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800471 // Call close without internal mutex held, as the HAL close may need to
472 // wait on assorted callbacks,etc, to complete before it can return.
473 interface->close();
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700474
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800475 flushInflightRequests();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800476
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800477 {
478 Mutex::Autolock l(mLock);
479 mInterface->clear();
480 mOutputStreams.clear();
481 mInputStream.clear();
482 mDeletedStreams.clear();
483 mBufferManager.clear();
484 internalUpdateStatusLocked(STATUS_UNINITIALIZED);
485 }
486
487 for (auto& weakStream : streams) {
488 sp<Camera3StreamInterface> stream = weakStream.promote();
489 if (stream != nullptr) {
490 ALOGE("%s: Stream %d leaked! strong reference (%d)!",
491 __FUNCTION__, stream->getId(), stream->getStrongCount() - 1);
492 }
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700493 }
494 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -0700495 ALOGI("%s: X", __FUNCTION__);
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700496 return res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800497}
498
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700499// For dumping/debugging only -
500// try to acquire a lock a few times, eventually give up to proceed with
501// debug/dump operations
502bool Camera3Device::tryLockSpinRightRound(Mutex& lock) {
503 bool gotLock = false;
504 for (size_t i = 0; i < kDumpLockAttempts; ++i) {
505 if (lock.tryLock() == NO_ERROR) {
506 gotLock = true;
507 break;
508 } else {
509 usleep(kDumpSleepDuration);
510 }
511 }
512 return gotLock;
513}
514
Shuzhen Wangc28dccc2016-02-11 23:48:46 -0800515nsecs_t Camera3Device::getMonoToBoottimeOffset() {
516 // try three times to get the clock offset, choose the one
517 // with the minimum gap in measurements.
518 const int tries = 3;
519 nsecs_t bestGap, measured;
520 for (int i = 0; i < tries; ++i) {
521 const nsecs_t tmono = systemTime(SYSTEM_TIME_MONOTONIC);
522 const nsecs_t tbase = systemTime(SYSTEM_TIME_BOOTTIME);
523 const nsecs_t tmono2 = systemTime(SYSTEM_TIME_MONOTONIC);
524 const nsecs_t gap = tmono2 - tmono;
525 if (i == 0 || gap < bestGap) {
526 bestGap = gap;
527 measured = tbase - ((tmono + tmono2) >> 1);
528 }
529 }
530 return measured;
531}
532
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800533hardware::graphics::common::V1_0::PixelFormat Camera3Device::mapToPixelFormat(
534 int frameworkFormat) {
535 return (hardware::graphics::common::V1_0::PixelFormat) frameworkFormat;
536}
537
538DataspaceFlags Camera3Device::mapToHidlDataspace(
539 android_dataspace dataSpace) {
540 return dataSpace;
541}
542
Chia-I Wu67a0c0e2017-04-06 13:37:01 -0700543BufferUsageFlags Camera3Device::mapToConsumerUsage(
Emilian Peev050f5dc2017-05-18 14:43:56 +0100544 uint64_t usage) {
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -0700545 return usage;
546}
547
Emilian Peevf4816702020-04-03 15:44:51 -0700548StreamRotation Camera3Device::mapToStreamRotation(camera_stream_rotation_t rotation) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800549 switch (rotation) {
Emilian Peevf4816702020-04-03 15:44:51 -0700550 case CAMERA_STREAM_ROTATION_0:
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800551 return StreamRotation::ROTATION_0;
Emilian Peevf4816702020-04-03 15:44:51 -0700552 case CAMERA_STREAM_ROTATION_90:
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800553 return StreamRotation::ROTATION_90;
Emilian Peevf4816702020-04-03 15:44:51 -0700554 case CAMERA_STREAM_ROTATION_180:
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800555 return StreamRotation::ROTATION_180;
Emilian Peevf4816702020-04-03 15:44:51 -0700556 case CAMERA_STREAM_ROTATION_270:
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800557 return StreamRotation::ROTATION_270;
558 }
559 ALOGE("%s: Unknown stream rotation %d", __FUNCTION__, rotation);
560 return StreamRotation::ROTATION_0;
561}
562
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800563status_t Camera3Device::mapToStreamConfigurationMode(
Emilian Peevf4816702020-04-03 15:44:51 -0700564 camera_stream_configuration_mode_t operationMode, StreamConfigurationMode *mode) {
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800565 if (mode == nullptr) return BAD_VALUE;
Emilian Peevf4816702020-04-03 15:44:51 -0700566 if (operationMode < CAMERA_VENDOR_STREAM_CONFIGURATION_MODE_START) {
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800567 switch(operationMode) {
Emilian Peevf4816702020-04-03 15:44:51 -0700568 case CAMERA_STREAM_CONFIGURATION_NORMAL_MODE:
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800569 *mode = StreamConfigurationMode::NORMAL_MODE;
570 break;
Emilian Peevf4816702020-04-03 15:44:51 -0700571 case CAMERA_STREAM_CONFIGURATION_CONSTRAINED_HIGH_SPEED_MODE:
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800572 *mode = StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE;
573 break;
574 default:
575 ALOGE("%s: Unknown stream configuration mode %d", __FUNCTION__, operationMode);
576 return BAD_VALUE;
577 }
578 } else {
579 *mode = static_cast<StreamConfigurationMode>(operationMode);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800580 }
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800581 return OK;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800582}
583
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800584int Camera3Device::mapToFrameworkFormat(
585 hardware::graphics::common::V1_0::PixelFormat pixelFormat) {
586 return static_cast<uint32_t>(pixelFormat);
587}
588
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -0700589android_dataspace Camera3Device::mapToFrameworkDataspace(
590 DataspaceFlags dataSpace) {
591 return static_cast<android_dataspace>(dataSpace);
592}
593
Emilian Peev050f5dc2017-05-18 14:43:56 +0100594uint64_t Camera3Device::mapConsumerToFrameworkUsage(
Chia-I Wu67a0c0e2017-04-06 13:37:01 -0700595 BufferUsageFlags usage) {
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -0700596 return usage;
597}
598
Emilian Peev050f5dc2017-05-18 14:43:56 +0100599uint64_t Camera3Device::mapProducerToFrameworkUsage(
Chia-I Wu67a0c0e2017-04-06 13:37:01 -0700600 BufferUsageFlags usage) {
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -0700601 return usage;
602}
603
Zhijun Hef7da0962014-04-24 13:27:56 -0700604ssize_t Camera3Device::getJpegBufferSize(uint32_t width, uint32_t height) const {
Jayant Chowdharycd3d36b2021-07-10 10:53:53 -0700605 // Get max jpeg size (area-wise) for default sensor pixel mode
606 camera3::Size maxDefaultJpegResolution =
607 SessionConfigurationUtils::getMaxJpegResolution(mDeviceInfo,
608 /*isUltraHighResolutionSensor*/false);
609 // Get max jpeg size (area-wise) for max resolution sensor pixel mode / 0 if
610 // not ultra high res sensor
611 camera3::Size uhrMaxJpegResolution =
612 SessionConfigurationUtils::getMaxJpegResolution(mDeviceInfo,
613 /*isUltraHighResolution*/true);
614 if (maxDefaultJpegResolution.width == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800615 ALOGE("%s: Camera %s: Can't find valid available jpeg sizes in static metadata!",
616 __FUNCTION__, mId.string());
Zhijun Hef7da0962014-04-24 13:27:56 -0700617 return BAD_VALUE;
618 }
Jayant Chowdharycd3d36b2021-07-10 10:53:53 -0700619 bool useMaxSensorPixelModeThreshold = false;
620 if (uhrMaxJpegResolution.width != 0 &&
621 width * height > maxDefaultJpegResolution.width * maxDefaultJpegResolution.height) {
622 // Use the ultra high res max jpeg size and max jpeg buffer size
623 useMaxSensorPixelModeThreshold = true;
624 }
Zhijun Hef7da0962014-04-24 13:27:56 -0700625
Zhijun Hef7da0962014-04-24 13:27:56 -0700626 // Get max jpeg buffer size
627 ssize_t maxJpegBufferSize = 0;
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700628 camera_metadata_ro_entry jpegBufMaxSize = mDeviceInfo.find(ANDROID_JPEG_MAX_SIZE);
629 if (jpegBufMaxSize.count == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800630 ALOGE("%s: Camera %s: Can't find maximum JPEG size in static metadata!", __FUNCTION__,
631 mId.string());
Zhijun Hef7da0962014-04-24 13:27:56 -0700632 return BAD_VALUE;
633 }
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700634 maxJpegBufferSize = jpegBufMaxSize.data.i32[0];
Jayant Chowdharycd3d36b2021-07-10 10:53:53 -0700635
636 camera3::Size chosenMaxJpegResolution = maxDefaultJpegResolution;
637 if (useMaxSensorPixelModeThreshold) {
638 maxJpegBufferSize =
639 SessionConfigurationUtils::getUHRMaxJpegBufferSize(uhrMaxJpegResolution,
640 maxDefaultJpegResolution, maxJpegBufferSize);
641 chosenMaxJpegResolution = uhrMaxJpegResolution;
642 }
Yin-Chia Yeh0c4e56d2015-01-09 15:21:27 -0800643 assert(kMinJpegBufferSize < maxJpegBufferSize);
Zhijun Hef7da0962014-04-24 13:27:56 -0700644
645 // Calculate final jpeg buffer size for the given resolution.
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700646 float scaleFactor = ((float) (width * height)) /
Jayant Chowdharycd3d36b2021-07-10 10:53:53 -0700647 (chosenMaxJpegResolution.width * chosenMaxJpegResolution.height);
Yin-Chia Yeh0c4e56d2015-01-09 15:21:27 -0800648 ssize_t jpegBufferSize = scaleFactor * (maxJpegBufferSize - kMinJpegBufferSize) +
649 kMinJpegBufferSize;
Zhijun Hef7da0962014-04-24 13:27:56 -0700650 if (jpegBufferSize > maxJpegBufferSize) {
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -0800651 ALOGI("%s: jpeg buffer size calculated is > maxJpeg bufferSize(%zd), clamping",
652 __FUNCTION__, maxJpegBufferSize);
Zhijun Hef7da0962014-04-24 13:27:56 -0700653 jpegBufferSize = maxJpegBufferSize;
Zhijun Hef7da0962014-04-24 13:27:56 -0700654 }
Zhijun Hef7da0962014-04-24 13:27:56 -0700655 return jpegBufferSize;
656}
657
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700658ssize_t Camera3Device::getPointCloudBufferSize() const {
659 const int FLOATS_PER_POINT=4;
660 camera_metadata_ro_entry maxPointCount = mDeviceInfo.find(ANDROID_DEPTH_MAX_DEPTH_SAMPLES);
661 if (maxPointCount.count == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800662 ALOGE("%s: Camera %s: Can't find maximum depth point cloud size in static metadata!",
663 __FUNCTION__, mId.string());
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700664 return BAD_VALUE;
665 }
666 ssize_t maxBytesForPointCloud = sizeof(android_depth_points) +
667 maxPointCount.data.i32[0] * sizeof(float) * FLOATS_PER_POINT;
668 return maxBytesForPointCloud;
669}
670
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -0800671ssize_t Camera3Device::getRawOpaqueBufferSize(int32_t width, int32_t height,
672 bool maxResolution) const {
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800673 const int PER_CONFIGURATION_SIZE = 3;
674 const int WIDTH_OFFSET = 0;
675 const int HEIGHT_OFFSET = 1;
676 const int SIZE_OFFSET = 2;
677 camera_metadata_ro_entry rawOpaqueSizes =
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -0800678 mDeviceInfo.find(
679 camera3::SessionConfigurationUtils::getAppropriateModeTag(
680 ANDROID_SENSOR_OPAQUE_RAW_SIZE,
681 maxResolution));
Aurimas Liutikasbc57b122016-02-16 09:59:16 -0800682 size_t count = rawOpaqueSizes.count;
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800683 if (count == 0 || (count % PER_CONFIGURATION_SIZE)) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800684 ALOGE("%s: Camera %s: bad opaque RAW size static metadata length(%zu)!",
685 __FUNCTION__, mId.string(), count);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800686 return BAD_VALUE;
687 }
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700688
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800689 for (size_t i = 0; i < count; i += PER_CONFIGURATION_SIZE) {
690 if (width == rawOpaqueSizes.data.i32[i + WIDTH_OFFSET] &&
691 height == rawOpaqueSizes.data.i32[i + HEIGHT_OFFSET]) {
692 return rawOpaqueSizes.data.i32[i + SIZE_OFFSET];
693 }
694 }
695
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800696 ALOGE("%s: Camera %s: cannot find size for %dx%d opaque RAW image!",
697 __FUNCTION__, mId.string(), width, height);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800698 return BAD_VALUE;
699}
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700700
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800701status_t Camera3Device::dump(int fd, const Vector<String16> &args) {
702 ATRACE_CALL();
703 (void)args;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700704
705 // Try to lock, but continue in case of failure (to avoid blocking in
706 // deadlocks)
707 bool gotInterfaceLock = tryLockSpinRightRound(mInterfaceLock);
708 bool gotLock = tryLockSpinRightRound(mLock);
709
710 ALOGW_IF(!gotInterfaceLock,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800711 "Camera %s: %s: Unable to lock interface lock, proceeding anyway",
712 mId.string(), __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700713 ALOGW_IF(!gotLock,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800714 "Camera %s: %s: Unable to lock main lock, proceeding anyway",
715 mId.string(), __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700716
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800717 bool dumpTemplates = false;
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700718
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800719 String16 templatesOption("-t");
720 int n = args.size();
721 for (int i = 0; i < n; i++) {
722 if (args[i] == templatesOption) {
723 dumpTemplates = true;
724 }
Emilian Peevbd8c5032018-02-14 23:05:40 +0000725 if (args[i] == TagMonitor::kMonitorOption) {
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700726 if (i + 1 < n) {
727 String8 monitorTags = String8(args[i + 1]);
728 if (monitorTags == "off") {
729 mTagMonitor.disableMonitoring();
730 } else {
731 mTagMonitor.parseTagsToMonitor(monitorTags);
732 }
733 } else {
734 mTagMonitor.disableMonitoring();
735 }
736 }
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800737 }
738
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800739 String8 lines;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800740
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800741 const char *status =
742 mStatus == STATUS_ERROR ? "ERROR" :
743 mStatus == STATUS_UNINITIALIZED ? "UNINITIALIZED" :
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700744 mStatus == STATUS_UNCONFIGURED ? "UNCONFIGURED" :
745 mStatus == STATUS_CONFIGURED ? "CONFIGURED" :
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800746 mStatus == STATUS_ACTIVE ? "ACTIVE" :
747 "Unknown";
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700748
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800749 lines.appendFormat(" Device status: %s\n", status);
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700750 if (mStatus == STATUS_ERROR) {
751 lines.appendFormat(" Error cause: %s\n", mErrorCause.string());
752 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800753 lines.appendFormat(" Stream configuration:\n");
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800754 const char *mode =
755 mOperatingMode == static_cast<int>(StreamConfigurationMode::NORMAL_MODE) ? "NORMAL" :
756 mOperatingMode == static_cast<int>(
757 StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE) ? "CONSTRAINED_HIGH_SPEED" :
758 "CUSTOM";
759 lines.appendFormat(" Operation mode: %s (%d) \n", mode, mOperatingMode);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800760
761 if (mInputStream != NULL) {
762 write(fd, lines.string(), lines.size());
763 mInputStream->dump(fd, args);
764 } else {
765 lines.appendFormat(" No input stream.\n");
766 write(fd, lines.string(), lines.size());
767 }
768 for (size_t i = 0; i < mOutputStreams.size(); i++) {
769 mOutputStreams[i]->dump(fd,args);
770 }
771
Zhijun He431503c2016-03-07 17:30:16 -0800772 if (mBufferManager != NULL) {
773 lines = String8(" Camera3 Buffer Manager:\n");
774 write(fd, lines.string(), lines.size());
775 mBufferManager->dump(fd, args);
776 }
Zhijun He125684a2015-12-26 15:07:30 -0800777
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700778 lines = String8(" In-flight requests:\n");
Emilian Peeva6138c52021-06-24 12:52:38 -0700779 if (mInFlightLock.try_lock()) {
780 if (mInFlightMap.size() == 0) {
781 lines.append(" None\n");
782 } else {
783 for (size_t i = 0; i < mInFlightMap.size(); i++) {
784 InFlightRequest r = mInFlightMap.valueAt(i);
785 lines.appendFormat(" Frame %d | Timestamp: %" PRId64 ", metadata"
786 " arrived: %s, buffers left: %d\n", mInFlightMap.keyAt(i),
787 r.shutterTimestamp, r.haveResultMetadata ? "true" : "false",
788 r.numBuffersLeft);
789 }
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700790 }
Emilian Peeva6138c52021-06-24 12:52:38 -0700791 mInFlightLock.unlock();
792 } else {
793 lines.append(" Failed to acquire In-flight lock!\n");
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700794 }
795 write(fd, lines.string(), lines.size());
796
Shuzhen Wang686f6442017-06-20 16:16:04 -0700797 if (mRequestThread != NULL) {
798 mRequestThread->dumpCaptureRequestLatency(fd,
799 " ProcessCaptureRequest latency histogram:");
800 }
801
Igor Murashkin1e479c02013-09-06 16:55:14 -0700802 {
803 lines = String8(" Last request sent:\n");
804 write(fd, lines.string(), lines.size());
805
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700806 CameraMetadata lastRequest = getLatestRequestLocked();
Igor Murashkin1e479c02013-09-06 16:55:14 -0700807 lastRequest.dump(fd, /*verbosity*/2, /*indentation*/6);
808 }
809
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800810 if (dumpTemplates) {
Emilian Peevf4816702020-04-03 15:44:51 -0700811 const char *templateNames[CAMERA_TEMPLATE_COUNT] = {
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800812 "TEMPLATE_PREVIEW",
813 "TEMPLATE_STILL_CAPTURE",
814 "TEMPLATE_VIDEO_RECORD",
815 "TEMPLATE_VIDEO_SNAPSHOT",
816 "TEMPLATE_ZERO_SHUTTER_LAG",
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -0800817 "TEMPLATE_MANUAL",
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800818 };
819
Emilian Peevf4816702020-04-03 15:44:51 -0700820 for (int i = 1; i < CAMERA_TEMPLATE_COUNT; i++) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800821 camera_metadata_t *templateRequest = nullptr;
822 mInterface->constructDefaultRequestSettings(
Emilian Peevf4816702020-04-03 15:44:51 -0700823 (camera_request_template_t) i, &templateRequest);
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800824 lines = String8::format(" HAL Request %s:\n", templateNames[i-1]);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800825 if (templateRequest == nullptr) {
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800826 lines.append(" Not supported\n");
827 write(fd, lines.string(), lines.size());
828 } else {
829 write(fd, lines.string(), lines.size());
830 dump_indented_camera_metadata(templateRequest,
831 fd, /*verbosity*/2, /*indentation*/8);
832 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800833 free_camera_metadata(templateRequest);
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800834 }
835 }
836
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700837 mTagMonitor.dumpMonitoredMetadata(fd);
838
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800839 if (mInterface->valid()) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -0800840 lines = String8(" HAL device dump:\n");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800841 write(fd, lines.string(), lines.size());
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800842 mInterface->dump(fd);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800843 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800844
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700845 if (gotLock) mLock.unlock();
846 if (gotInterfaceLock) mInterfaceLock.unlock();
847
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800848 return OK;
849}
850
Emilian Peevfaa4bde2020-01-23 12:19:37 -0800851const CameraMetadata& Camera3Device::infoPhysical(const String8& physicalId) const {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800852 ALOGVV("%s: E", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800853 if (CC_UNLIKELY(mStatus == STATUS_UNINITIALIZED ||
854 mStatus == STATUS_ERROR)) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700855 ALOGW("%s: Access to static info %s!", __FUNCTION__,
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800856 mStatus == STATUS_ERROR ?
857 "when in error state" : "before init");
858 }
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700859 if (physicalId.isEmpty()) {
860 return mDeviceInfo;
861 } else {
862 std::string id(physicalId.c_str());
863 if (mPhysicalDeviceInfoMap.find(id) != mPhysicalDeviceInfoMap.end()) {
864 return mPhysicalDeviceInfoMap.at(id);
865 } else {
866 ALOGE("%s: Invalid physical camera id %s", __FUNCTION__, physicalId.c_str());
867 return mDeviceInfo;
868 }
869 }
870}
871
872const CameraMetadata& Camera3Device::info() const {
873 String8 emptyId;
Emilian Peevfaa4bde2020-01-23 12:19:37 -0800874 return infoPhysical(emptyId);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800875}
876
Jianing Wei90e59c92014-03-12 18:29:36 -0700877status_t Camera3Device::checkStatusOkToCaptureLocked() {
878 switch (mStatus) {
879 case STATUS_ERROR:
880 CLOGE("Device has encountered a serious error");
881 return INVALID_OPERATION;
882 case STATUS_UNINITIALIZED:
883 CLOGE("Device not initialized");
884 return INVALID_OPERATION;
885 case STATUS_UNCONFIGURED:
886 case STATUS_CONFIGURED:
887 case STATUS_ACTIVE:
888 // OK
889 break;
890 default:
891 SET_ERR_L("Unexpected status: %d", mStatus);
892 return INVALID_OPERATION;
893 }
894 return OK;
895}
896
897status_t Camera3Device::convertMetadataListToRequestListLocked(
Emilian Peevaebbe412018-01-15 13:53:24 +0000898 const List<const PhysicalCameraSettingsList> &metadataList,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700899 const std::list<const SurfaceMap> &surfaceMaps,
Shuzhen Wang316781a2020-08-18 18:11:01 -0700900 bool repeating, nsecs_t requestTimeNs,
Shuzhen Wang9d066012016-09-30 11:30:20 -0700901 RequestList *requestList) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700902 if (requestList == NULL) {
903 CLOGE("requestList cannot be NULL.");
904 return BAD_VALUE;
905 }
906
Jianing Weicb0652e2014-03-12 18:29:36 -0700907 int32_t burstId = 0;
Emilian Peevaebbe412018-01-15 13:53:24 +0000908 List<const PhysicalCameraSettingsList>::const_iterator metadataIt = metadataList.begin();
Shuzhen Wang0129d522016-10-30 22:43:41 -0700909 std::list<const SurfaceMap>::const_iterator surfaceMapIt = surfaceMaps.begin();
910 for (; metadataIt != metadataList.end() && surfaceMapIt != surfaceMaps.end();
911 ++metadataIt, ++surfaceMapIt) {
912 sp<CaptureRequest> newRequest = setUpRequestLocked(*metadataIt, *surfaceMapIt);
Jianing Wei90e59c92014-03-12 18:29:36 -0700913 if (newRequest == 0) {
914 CLOGE("Can't create capture request");
915 return BAD_VALUE;
916 }
Jianing Weicb0652e2014-03-12 18:29:36 -0700917
Shuzhen Wang9d066012016-09-30 11:30:20 -0700918 newRequest->mRepeating = repeating;
Shuzhen Wang316781a2020-08-18 18:11:01 -0700919 newRequest->mRequestTimeNs = requestTimeNs;
Shuzhen Wang9d066012016-09-30 11:30:20 -0700920
Jianing Weicb0652e2014-03-12 18:29:36 -0700921 // Setup burst Id and request Id
922 newRequest->mResultExtras.burstId = burstId++;
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -0800923 auto requestIdEntry = metadataIt->begin()->metadata.find(ANDROID_REQUEST_ID);
924 if (requestIdEntry.count == 0) {
Jianing Weicb0652e2014-03-12 18:29:36 -0700925 CLOGE("RequestID does not exist in metadata");
926 return BAD_VALUE;
927 }
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -0800928 newRequest->mResultExtras.requestId = requestIdEntry.data.i32[0];
Jianing Weicb0652e2014-03-12 18:29:36 -0700929
Jianing Wei90e59c92014-03-12 18:29:36 -0700930 requestList->push_back(newRequest);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700931
932 ALOGV("%s: requestId = %" PRId32, __FUNCTION__, newRequest->mResultExtras.requestId);
Jianing Wei90e59c92014-03-12 18:29:36 -0700933 }
Shuzhen Wang0129d522016-10-30 22:43:41 -0700934 if (metadataIt != metadataList.end() || surfaceMapIt != surfaceMaps.end()) {
935 ALOGE("%s: metadataList and surfaceMaps are not the same size!", __FUNCTION__);
936 return BAD_VALUE;
937 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -0700938
939 // Setup batch size if this is a high speed video recording request.
940 if (mIsConstrainedHighSpeedConfiguration && requestList->size() > 0) {
941 auto firstRequest = requestList->begin();
942 for (auto& outputStream : (*firstRequest)->mOutputStreams) {
943 if (outputStream->isVideoStream()) {
944 (*firstRequest)->mBatchSize = requestList->size();
Yin-Chia Yeh14ef48d2020-02-10 15:06:37 -0800945 outputStream->setBatchSize(requestList->size());
Chien-Yu Chen85a64552015-08-28 15:46:12 -0700946 break;
947 }
948 }
949 }
950
Jianing Wei90e59c92014-03-12 18:29:36 -0700951 return OK;
952}
953
Yin-Chia Yeh7e5a2042019-02-06 16:01:06 -0800954status_t Camera3Device::capture(CameraMetadata &request, int64_t* lastFrameNumber) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800955 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800956
Emilian Peevaebbe412018-01-15 13:53:24 +0000957 List<const PhysicalCameraSettingsList> requestsList;
Shuzhen Wang0129d522016-10-30 22:43:41 -0700958 std::list<const SurfaceMap> surfaceMaps;
Emilian Peevaebbe412018-01-15 13:53:24 +0000959 convertToRequestList(requestsList, surfaceMaps, request);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700960
Yin-Chia Yeh7e5a2042019-02-06 16:01:06 -0800961 return captureList(requestsList, surfaceMaps, lastFrameNumber);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700962}
963
Emilian Peevaebbe412018-01-15 13:53:24 +0000964void Camera3Device::convertToRequestList(List<const PhysicalCameraSettingsList>& requestsList,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700965 std::list<const SurfaceMap>& surfaceMaps,
966 const CameraMetadata& request) {
Emilian Peevaebbe412018-01-15 13:53:24 +0000967 PhysicalCameraSettingsList requestList;
968 requestList.push_back({std::string(getId().string()), request});
969 requestsList.push_back(requestList);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700970
971 SurfaceMap surfaceMap;
972 camera_metadata_ro_entry streams = request.find(ANDROID_REQUEST_OUTPUT_STREAMS);
973 // With no surface list passed in, stream and surface will have 1-to-1
974 // mapping. So the surface index is 0 for each stream in the surfaceMap.
975 for (size_t i = 0; i < streams.count; i++) {
976 surfaceMap[streams.data.i32[i]].push_back(0);
977 }
978 surfaceMaps.push_back(surfaceMap);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800979}
980
Jianing Wei90e59c92014-03-12 18:29:36 -0700981status_t Camera3Device::submitRequestsHelper(
Emilian Peevaebbe412018-01-15 13:53:24 +0000982 const List<const PhysicalCameraSettingsList> &requests,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700983 const std::list<const SurfaceMap> &surfaceMaps,
984 bool repeating,
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700985 /*out*/
986 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700987 ATRACE_CALL();
Shuzhen Wang316781a2020-08-18 18:11:01 -0700988 nsecs_t requestTimeNs = systemTime();
989
Jianing Wei90e59c92014-03-12 18:29:36 -0700990 Mutex::Autolock il(mInterfaceLock);
991 Mutex::Autolock l(mLock);
992
993 status_t res = checkStatusOkToCaptureLocked();
994 if (res != OK) {
995 // error logged by previous call
996 return res;
997 }
998
999 RequestList requestList;
1000
Shuzhen Wang0129d522016-10-30 22:43:41 -07001001 res = convertMetadataListToRequestListLocked(requests, surfaceMaps,
Shuzhen Wang316781a2020-08-18 18:11:01 -07001002 repeating, requestTimeNs, /*out*/&requestList);
Jianing Wei90e59c92014-03-12 18:29:36 -07001003 if (res != OK) {
1004 // error logged by previous call
1005 return res;
1006 }
1007
1008 if (repeating) {
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07001009 res = mRequestThread->setRepeatingRequests(requestList, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -07001010 } else {
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07001011 res = mRequestThread->queueRequestList(requestList, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -07001012 }
1013
1014 if (res == OK) {
1015 waitUntilStateThenRelock(/*active*/true, kActiveTimeout);
1016 if (res != OK) {
1017 SET_ERR_L("Can't transition to active in %f seconds!",
1018 kActiveTimeout/1e9);
1019 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001020 ALOGV("Camera %s: Capture request %" PRId32 " enqueued", mId.string(),
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07001021 (*(requestList.begin()))->mResultExtras.requestId);
Jianing Wei90e59c92014-03-12 18:29:36 -07001022 } else {
1023 CLOGE("Cannot queue request. Impossible.");
1024 return BAD_VALUE;
1025 }
1026
1027 return res;
1028}
1029
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001030hardware::Return<void> Camera3Device::requestStreamBuffers(
1031 const hardware::hidl_vec<hardware::camera::device::V3_5::BufferRequest>& bufReqs,
1032 requestStreamBuffers_cb _hidl_cb) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001033 RequestBufferStates states {
Shuzhen Wang316781a2020-08-18 18:11:01 -07001034 mId, mRequestBufferInterfaceLock, mUseHalBufManager, mOutputStreams, mSessionStatsBuilder,
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001035 *this, *mInterface, *this};
1036 camera3::requestStreamBuffers(states, bufReqs, _hidl_cb);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001037 return hardware::Void();
1038}
1039
1040hardware::Return<void> Camera3Device::returnStreamBuffers(
1041 const hardware::hidl_vec<hardware::camera::device::V3_2::StreamBuffer>& buffers) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001042 ReturnBufferStates states {
Shuzhen Wang316781a2020-08-18 18:11:01 -07001043 mId, mUseHalBufManager, mOutputStreams, mSessionStatsBuilder, *mInterface};
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001044 camera3::returnStreamBuffers(states, buffers);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001045 return hardware::Void();
1046}
1047
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001048hardware::Return<void> Camera3Device::processCaptureResult_3_4(
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001049 const hardware::hidl_vec<
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001050 hardware::camera::device::V3_4::CaptureResult>& results) {
Yin-Chia Yeh657c1872017-07-18 18:09:57 -07001051 // Ideally we should grab mLock, but that can lead to deadlock, and
1052 // it's not super important to get up to date value of mStatus for this
1053 // warning print, hence skipping the lock here
1054 if (mStatus == STATUS_ERROR) {
1055 // Per API contract, HAL should act as closed after device error
1056 // But mStatus can be set to error by framework as well, so just log
1057 // a warning here.
1058 ALOGW("%s: received capture result in error state.", __FUNCTION__);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07001059 }
Yifan Honga640c5a2017-04-12 16:30:31 -07001060
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001061 sp<NotificationListener> listener;
1062 {
1063 std::lock_guard<std::mutex> l(mOutputLock);
1064 listener = mListener.promote();
1065 }
1066
Yifan Honga640c5a2017-04-12 16:30:31 -07001067 if (mProcessCaptureResultLock.tryLock() != OK) {
1068 // This should never happen; it indicates a wrong client implementation
1069 // that doesn't follow the contract. But, we can be tolerant here.
1070 ALOGE("%s: callback overlapped! waiting 1s...",
1071 __FUNCTION__);
1072 if (mProcessCaptureResultLock.timedLock(1000000000 /* 1s */) != OK) {
1073 ALOGE("%s: cannot acquire lock in 1s, dropping results",
1074 __FUNCTION__);
1075 // really don't know what to do, so bail out.
1076 return hardware::Void();
1077 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001078 }
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001079 CaptureOutputStates states {
1080 mId,
Shuzhen Wangb7b42652020-05-07 11:59:02 -07001081 mInFlightLock, mLastCompletedRegularFrameNumber,
1082 mLastCompletedReprocessFrameNumber, mLastCompletedZslFrameNumber,
1083 mInFlightMap, mOutputLock, mResultQueue, mResultSignal,
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001084 mNextShutterFrameNumber,
1085 mNextReprocessShutterFrameNumber, mNextZslStillShutterFrameNumber,
1086 mNextResultFrameNumber,
1087 mNextReprocessResultFrameNumber, mNextZslStillResultFrameNumber,
1088 mUseHalBufManager, mUsePartialResult, mNeedFixupMonochromeTags,
1089 mNumPartialResults, mVendorTagId, mDeviceInfo, mPhysicalDeviceInfoMap,
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08001090 mResultMetadataQueue, mDistortionMappers, mZoomRatioMappers, mRotateAndCropMappers,
Shuzhen Wang316781a2020-08-18 18:11:01 -07001091 mTagMonitor, mInputStream, mOutputStreams, mSessionStatsBuilder, listener, *this, *this,
1092 *mInterface
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001093 };
1094
Yifan Honga640c5a2017-04-12 16:30:31 -07001095 for (const auto& result : results) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001096 processOneCaptureResultLocked(states, result.v3_2, result.physicalCameraMetadata);
Yifan Honga640c5a2017-04-12 16:30:31 -07001097 }
1098 mProcessCaptureResultLock.unlock();
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001099 return hardware::Void();
1100}
1101
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001102// Only one processCaptureResult should be called at a time, so
1103// the locks won't block. The locks are present here simply to enforce this.
1104hardware::Return<void> Camera3Device::processCaptureResult(
1105 const hardware::hidl_vec<
1106 hardware::camera::device::V3_2::CaptureResult>& results) {
1107 hardware::hidl_vec<hardware::camera::device::V3_4::PhysicalCameraMetadata> noPhysMetadata;
1108
1109 // Ideally we should grab mLock, but that can lead to deadlock, and
1110 // it's not super important to get up to date value of mStatus for this
1111 // warning print, hence skipping the lock here
1112 if (mStatus == STATUS_ERROR) {
1113 // Per API contract, HAL should act as closed after device error
1114 // But mStatus can be set to error by framework as well, so just log
1115 // a warning here.
1116 ALOGW("%s: received capture result in error state.", __FUNCTION__);
1117 }
1118
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001119 sp<NotificationListener> listener;
1120 {
1121 std::lock_guard<std::mutex> l(mOutputLock);
1122 listener = mListener.promote();
1123 }
1124
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001125 if (mProcessCaptureResultLock.tryLock() != OK) {
1126 // This should never happen; it indicates a wrong client implementation
1127 // that doesn't follow the contract. But, we can be tolerant here.
1128 ALOGE("%s: callback overlapped! waiting 1s...",
1129 __FUNCTION__);
1130 if (mProcessCaptureResultLock.timedLock(1000000000 /* 1s */) != OK) {
1131 ALOGE("%s: cannot acquire lock in 1s, dropping results",
1132 __FUNCTION__);
1133 // really don't know what to do, so bail out.
1134 return hardware::Void();
1135 }
1136 }
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001137
1138 CaptureOutputStates states {
1139 mId,
Shuzhen Wangb7b42652020-05-07 11:59:02 -07001140 mInFlightLock, mLastCompletedRegularFrameNumber,
1141 mLastCompletedReprocessFrameNumber, mLastCompletedZslFrameNumber,
1142 mInFlightMap, mOutputLock, mResultQueue, mResultSignal,
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001143 mNextShutterFrameNumber,
1144 mNextReprocessShutterFrameNumber, mNextZslStillShutterFrameNumber,
1145 mNextResultFrameNumber,
1146 mNextReprocessResultFrameNumber, mNextZslStillResultFrameNumber,
1147 mUseHalBufManager, mUsePartialResult, mNeedFixupMonochromeTags,
1148 mNumPartialResults, mVendorTagId, mDeviceInfo, mPhysicalDeviceInfoMap,
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08001149 mResultMetadataQueue, mDistortionMappers, mZoomRatioMappers, mRotateAndCropMappers,
Shuzhen Wang316781a2020-08-18 18:11:01 -07001150 mTagMonitor, mInputStream, mOutputStreams, mSessionStatsBuilder, listener, *this, *this,
1151 *mInterface
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001152 };
1153
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001154 for (const auto& result : results) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001155 processOneCaptureResultLocked(states, result, noPhysMetadata);
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001156 }
1157 mProcessCaptureResultLock.unlock();
1158 return hardware::Void();
1159}
1160
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001161hardware::Return<void> Camera3Device::notify(
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001162 const hardware::hidl_vec<hardware::camera::device::V3_2::NotifyMsg>& msgs) {
Yin-Chia Yeh657c1872017-07-18 18:09:57 -07001163 // Ideally we should grab mLock, but that can lead to deadlock, and
1164 // it's not super important to get up to date value of mStatus for this
1165 // warning print, hence skipping the lock here
1166 if (mStatus == STATUS_ERROR) {
1167 // Per API contract, HAL should act as closed after device error
1168 // But mStatus can be set to error by framework as well, so just log
1169 // a warning here.
1170 ALOGW("%s: received notify message in error state.", __FUNCTION__);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07001171 }
Yin-Chia Yeh657c1872017-07-18 18:09:57 -07001172
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001173 sp<NotificationListener> listener;
1174 {
1175 std::lock_guard<std::mutex> l(mOutputLock);
1176 listener = mListener.promote();
1177 }
1178
1179 CaptureOutputStates states {
1180 mId,
Shuzhen Wangb7b42652020-05-07 11:59:02 -07001181 mInFlightLock, mLastCompletedRegularFrameNumber,
1182 mLastCompletedReprocessFrameNumber, mLastCompletedZslFrameNumber,
1183 mInFlightMap, mOutputLock, mResultQueue, mResultSignal,
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001184 mNextShutterFrameNumber,
1185 mNextReprocessShutterFrameNumber, mNextZslStillShutterFrameNumber,
1186 mNextResultFrameNumber,
1187 mNextReprocessResultFrameNumber, mNextZslStillResultFrameNumber,
1188 mUseHalBufManager, mUsePartialResult, mNeedFixupMonochromeTags,
1189 mNumPartialResults, mVendorTagId, mDeviceInfo, mPhysicalDeviceInfoMap,
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08001190 mResultMetadataQueue, mDistortionMappers, mZoomRatioMappers, mRotateAndCropMappers,
Shuzhen Wang316781a2020-08-18 18:11:01 -07001191 mTagMonitor, mInputStream, mOutputStreams, mSessionStatsBuilder, listener, *this, *this,
1192 *mInterface
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001193 };
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001194 for (const auto& msg : msgs) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001195 camera3::notify(states, msg);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001196 }
1197 return hardware::Void();
1198}
1199
Emilian Peevaebbe412018-01-15 13:53:24 +00001200status_t Camera3Device::captureList(const List<const PhysicalCameraSettingsList> &requestsList,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001201 const std::list<const SurfaceMap> &surfaceMaps,
Jianing Weicb0652e2014-03-12 18:29:36 -07001202 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -07001203 ATRACE_CALL();
1204
Emilian Peevaebbe412018-01-15 13:53:24 +00001205 return submitRequestsHelper(requestsList, surfaceMaps, /*repeating*/false, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -07001206}
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001207
Jianing Weicb0652e2014-03-12 18:29:36 -07001208status_t Camera3Device::setStreamingRequest(const CameraMetadata &request,
1209 int64_t* /*lastFrameNumber*/) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001210 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001211
Emilian Peevaebbe412018-01-15 13:53:24 +00001212 List<const PhysicalCameraSettingsList> requestsList;
Shuzhen Wang0129d522016-10-30 22:43:41 -07001213 std::list<const SurfaceMap> surfaceMaps;
Emilian Peevaebbe412018-01-15 13:53:24 +00001214 convertToRequestList(requestsList, surfaceMaps, request);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001215
Emilian Peevaebbe412018-01-15 13:53:24 +00001216 return setStreamingRequestList(requestsList, /*surfaceMap*/surfaceMaps,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001217 /*lastFrameNumber*/NULL);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001218}
1219
Emilian Peevaebbe412018-01-15 13:53:24 +00001220status_t Camera3Device::setStreamingRequestList(
1221 const List<const PhysicalCameraSettingsList> &requestsList,
1222 const std::list<const SurfaceMap> &surfaceMaps, int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -07001223 ATRACE_CALL();
1224
Emilian Peevaebbe412018-01-15 13:53:24 +00001225 return submitRequestsHelper(requestsList, surfaceMaps, /*repeating*/true, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -07001226}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001227
1228sp<Camera3Device::CaptureRequest> Camera3Device::setUpRequestLocked(
Emilian Peevaebbe412018-01-15 13:53:24 +00001229 const PhysicalCameraSettingsList &request, const SurfaceMap &surfaceMap) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001230 status_t res;
1231
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001232 if (mStatus == STATUS_UNCONFIGURED || mNeedConfig) {
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08001233 // This point should only be reached via API1 (API2 must explicitly call configureStreams)
1234 // so unilaterally select normal operating mode.
Emilian Peevaebbe412018-01-15 13:53:24 +00001235 res = filterParamsAndConfigureLocked(request.begin()->metadata,
Emilian Peevf4816702020-04-03 15:44:51 -07001236 CAMERA_STREAM_CONFIGURATION_NORMAL_MODE);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001237 // Stream configuration failed. Client might try other configuraitons.
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001238 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001239 CLOGE("Can't set up streams: %s (%d)", strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001240 return NULL;
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001241 } else if (mStatus == STATUS_UNCONFIGURED) {
1242 // Stream configuration successfully configure to empty stream configuration.
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001243 CLOGE("No streams configured");
1244 return NULL;
1245 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001246 }
1247
Shuzhen Wang0129d522016-10-30 22:43:41 -07001248 sp<CaptureRequest> newRequest = createCaptureRequest(request, surfaceMap);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001249 return newRequest;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001250}
1251
Jianing Weicb0652e2014-03-12 18:29:36 -07001252status_t Camera3Device::clearStreamingRequest(int64_t *lastFrameNumber) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001253 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001254 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001255 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001256
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001257 switch (mStatus) {
1258 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001259 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001260 return INVALID_OPERATION;
1261 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001262 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001263 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001264 case STATUS_UNCONFIGURED:
1265 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001266 case STATUS_ACTIVE:
1267 // OK
1268 break;
1269 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001270 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001271 return INVALID_OPERATION;
1272 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001273 ALOGV("Camera %s: Clearing repeating request", mId.string());
Jianing Weicb0652e2014-03-12 18:29:36 -07001274
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07001275 return mRequestThread->clearRepeatingRequests(lastFrameNumber);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001276}
1277
1278status_t Camera3Device::waitUntilRequestReceived(int32_t requestId, nsecs_t timeout) {
1279 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001280 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001281
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001282 return mRequestThread->waitUntilRequestProcessed(requestId, timeout);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001283}
1284
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001285status_t Camera3Device::createInputStream(
Shuzhen Wang83bff122020-11-20 15:51:39 -08001286 uint32_t width, uint32_t height, int format, bool isMultiResolution, int *id) {
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001287 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001288 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001289 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001290 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001291 ALOGV("Camera %s: Creating new input stream %d: %d x %d, format %d",
1292 mId.string(), mNextStreamId, width, height, format);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001293
1294 status_t res;
1295 bool wasActive = false;
1296
1297 switch (mStatus) {
1298 case STATUS_ERROR:
1299 ALOGE("%s: Device has encountered a serious error", __FUNCTION__);
1300 return INVALID_OPERATION;
1301 case STATUS_UNINITIALIZED:
1302 ALOGE("%s: Device not initialized", __FUNCTION__);
1303 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001304 case STATUS_UNCONFIGURED:
1305 case STATUS_CONFIGURED:
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001306 // OK
1307 break;
1308 case STATUS_ACTIVE:
1309 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001310 res = internalPauseAndWaitLocked(maxExpectedDuration);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001311 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001312 SET_ERR_L("Can't pause captures to reconfigure streams!");
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001313 return res;
1314 }
1315 wasActive = true;
1316 break;
1317 default:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001318 SET_ERR_L("%s: Unexpected status: %d", mStatus);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001319 return INVALID_OPERATION;
1320 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001321 assert(mStatus != STATUS_ACTIVE);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001322
1323 if (mInputStream != 0) {
1324 ALOGE("%s: Cannot create more than 1 input stream", __FUNCTION__);
1325 return INVALID_OPERATION;
1326 }
1327
1328 sp<Camera3InputStream> newStream = new Camera3InputStream(mNextStreamId,
1329 width, height, format);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001330 newStream->setStatusTracker(mStatusTracker);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001331
1332 mInputStream = newStream;
Shuzhen Wang83bff122020-11-20 15:51:39 -08001333 mIsInputStreamMultiResolution = isMultiResolution;
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001334
1335 *id = mNextStreamId++;
1336
1337 // Continue captures if active at start
1338 if (wasActive) {
1339 ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001340 // Reuse current operating mode and session parameters for new stream config
1341 res = configureStreamsLocked(mOperatingMode, mSessionParams);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001342 if (res != OK) {
1343 ALOGE("%s: Can't reconfigure device for new stream %d: %s (%d)",
1344 __FUNCTION__, mNextStreamId, strerror(-res), res);
1345 return res;
1346 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001347 internalResumeLocked();
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001348 }
1349
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001350 ALOGV("Camera %s: Created input stream", mId.string());
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001351 return OK;
1352}
1353
Eino-Ville Talvala727d1722015-06-09 13:44:19 -07001354status_t Camera3Device::createStream(sp<Surface> consumer,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001355 uint32_t width, uint32_t height, int format,
Emilian Peevf4816702020-04-03 15:44:51 -07001356 android_dataspace dataSpace, camera_stream_rotation_t rotation, int *id,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001357 const String8& physicalCameraId,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001358 const std::unordered_set<int32_t> &sensorPixelModesUsed,
1359 std::vector<int> *surfaceIds, int streamSetId, bool isShared, bool isMultiResolution,
1360 uint64_t consumerUsage) {
Shuzhen Wang0129d522016-10-30 22:43:41 -07001361 ATRACE_CALL();
1362
1363 if (consumer == nullptr) {
1364 ALOGE("%s: consumer must not be null", __FUNCTION__);
1365 return BAD_VALUE;
1366 }
1367
1368 std::vector<sp<Surface>> consumers;
1369 consumers.push_back(consumer);
1370
1371 return createStream(consumers, /*hasDeferredConsumer*/ false, width, height,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001372 format, dataSpace, rotation, id, physicalCameraId, sensorPixelModesUsed, surfaceIds,
1373 streamSetId, isShared, isMultiResolution, consumerUsage);
1374}
1375
1376static bool isRawFormat(int format) {
1377 switch (format) {
1378 case HAL_PIXEL_FORMAT_RAW16:
1379 case HAL_PIXEL_FORMAT_RAW12:
1380 case HAL_PIXEL_FORMAT_RAW10:
1381 case HAL_PIXEL_FORMAT_RAW_OPAQUE:
1382 return true;
1383 default:
1384 return false;
1385 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001386}
1387
1388status_t Camera3Device::createStream(const std::vector<sp<Surface>>& consumers,
1389 bool hasDeferredConsumer, uint32_t width, uint32_t height, int format,
Emilian Peevf4816702020-04-03 15:44:51 -07001390 android_dataspace dataSpace, camera_stream_rotation_t rotation, int *id,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001391 const String8& physicalCameraId, const std::unordered_set<int32_t> &sensorPixelModesUsed,
Shuzhen Wang83bff122020-11-20 15:51:39 -08001392 std::vector<int> *surfaceIds, int streamSetId, bool isShared, bool isMultiResolution,
1393 uint64_t consumerUsage) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001394 ATRACE_CALL();
Emilian Peev40ead602017-09-26 15:46:36 +01001395
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001396 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001397 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001398 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001399 ALOGV("Camera %s: Creating new stream %d: %d x %d, format %d, dataspace %d rotation %d"
Shuzhen Wang83bff122020-11-20 15:51:39 -08001400 " consumer usage %" PRIu64 ", isShared %d, physicalCameraId %s, isMultiResolution %d",
1401 mId.string(), mNextStreamId, width, height, format, dataSpace, rotation,
1402 consumerUsage, isShared, physicalCameraId.string(), isMultiResolution);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001403
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001404 status_t res;
1405 bool wasActive = false;
1406
1407 switch (mStatus) {
1408 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001409 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001410 return INVALID_OPERATION;
1411 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001412 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001413 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001414 case STATUS_UNCONFIGURED:
1415 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001416 // OK
1417 break;
1418 case STATUS_ACTIVE:
1419 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001420 res = internalPauseAndWaitLocked(maxExpectedDuration);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001421 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001422 SET_ERR_L("Can't pause captures to reconfigure streams!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001423 return res;
1424 }
1425 wasActive = true;
1426 break;
1427 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001428 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001429 return INVALID_OPERATION;
1430 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001431 assert(mStatus != STATUS_ACTIVE);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001432
1433 sp<Camera3OutputStream> newStream;
Zhijun He5d677d12016-05-29 16:52:39 -07001434
Shuzhen Wang0129d522016-10-30 22:43:41 -07001435 if (consumers.size() == 0 && !hasDeferredConsumer) {
1436 ALOGE("%s: Number of consumers cannot be smaller than 1", __FUNCTION__);
1437 return BAD_VALUE;
1438 }
Zhijun He5d677d12016-05-29 16:52:39 -07001439
Shuzhen Wang0129d522016-10-30 22:43:41 -07001440 if (hasDeferredConsumer && format != HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
Zhijun He5d677d12016-05-29 16:52:39 -07001441 ALOGE("Deferred consumer stream creation only support IMPLEMENTATION_DEFINED format");
1442 return BAD_VALUE;
1443 }
1444
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001445 if (isRawFormat(format) && sensorPixelModesUsed.size() > 1) {
1446 // We can't use one stream with a raw format in both sensor pixel modes since its going to
1447 // be found in only one sensor pixel mode.
1448 ALOGE("%s: RAW opaque stream cannot be used with > 1 sensor pixel modes", __FUNCTION__);
1449 return BAD_VALUE;
1450 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001451 if (format == HAL_PIXEL_FORMAT_BLOB) {
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -07001452 ssize_t blobBufferSize;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001453 if (dataSpace == HAL_DATASPACE_DEPTH) {
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -07001454 blobBufferSize = getPointCloudBufferSize();
1455 if (blobBufferSize <= 0) {
1456 SET_ERR_L("Invalid point cloud buffer size %zd", blobBufferSize);
1457 return BAD_VALUE;
1458 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001459 } else if (dataSpace == static_cast<android_dataspace>(HAL_DATASPACE_JPEG_APP_SEGMENTS)) {
1460 blobBufferSize = width * height;
1461 } else {
1462 blobBufferSize = getJpegBufferSize(width, height);
1463 if (blobBufferSize <= 0) {
1464 SET_ERR_L("Invalid jpeg buffer size %zd", blobBufferSize);
1465 return BAD_VALUE;
1466 }
Zhijun Hef7da0962014-04-24 13:27:56 -07001467 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001468 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001469 width, height, blobBufferSize, format, dataSpace, rotation,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001470 mTimestampOffset, physicalCameraId, sensorPixelModesUsed, streamSetId,
1471 isMultiResolution);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -08001472 } else if (format == HAL_PIXEL_FORMAT_RAW_OPAQUE) {
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001473 bool maxResolution =
1474 sensorPixelModesUsed.find(ANDROID_SENSOR_PIXEL_MODE_MAXIMUM_RESOLUTION) !=
1475 sensorPixelModesUsed.end();
1476 ssize_t rawOpaqueBufferSize = getRawOpaqueBufferSize(width, height, maxResolution);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -08001477 if (rawOpaqueBufferSize <= 0) {
1478 SET_ERR_L("Invalid RAW opaque buffer size %zd", rawOpaqueBufferSize);
1479 return BAD_VALUE;
1480 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001481 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001482 width, height, rawOpaqueBufferSize, format, dataSpace, rotation,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001483 mTimestampOffset, physicalCameraId, sensorPixelModesUsed, streamSetId,
1484 isMultiResolution);
Shuzhen Wang758c2152017-01-10 18:26:18 -08001485 } else if (isShared) {
1486 newStream = new Camera3SharedOutputStream(mNextStreamId, consumers,
1487 width, height, format, consumerUsage, dataSpace, rotation,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001488 mTimestampOffset, physicalCameraId, sensorPixelModesUsed, streamSetId,
1489 mUseHalBufManager);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001490 } else if (consumers.size() == 0 && hasDeferredConsumer) {
Zhijun He5d677d12016-05-29 16:52:39 -07001491 newStream = new Camera3OutputStream(mNextStreamId,
1492 width, height, format, consumerUsage, dataSpace, rotation,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001493 mTimestampOffset, physicalCameraId, sensorPixelModesUsed, streamSetId,
1494 isMultiResolution);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001495 } else {
Shuzhen Wang0129d522016-10-30 22:43:41 -07001496 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001497 width, height, format, dataSpace, rotation,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001498 mTimestampOffset, physicalCameraId, sensorPixelModesUsed, streamSetId,
1499 isMultiResolution);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001500 }
Emilian Peev40ead602017-09-26 15:46:36 +01001501
1502 size_t consumerCount = consumers.size();
1503 for (size_t i = 0; i < consumerCount; i++) {
1504 int id = newStream->getSurfaceId(consumers[i]);
1505 if (id < 0) {
1506 SET_ERR_L("Invalid surface id");
1507 return BAD_VALUE;
1508 }
1509 if (surfaceIds != nullptr) {
1510 surfaceIds->push_back(id);
1511 }
1512 }
1513
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001514 newStream->setStatusTracker(mStatusTracker);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001515
Emilian Peev08dd2452017-04-06 16:55:14 +01001516 newStream->setBufferManager(mBufferManager);
Zhijun He125684a2015-12-26 15:07:30 -08001517
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08001518 newStream->setImageDumpMask(mImageDumpMask);
1519
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001520 res = mOutputStreams.add(mNextStreamId, newStream);
1521 if (res < 0) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001522 SET_ERR_L("Can't add new stream to set: %s (%d)", strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001523 return res;
1524 }
1525
Shuzhen Wang316781a2020-08-18 18:11:01 -07001526 mSessionStatsBuilder.addStream(mNextStreamId);
1527
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001528 *id = mNextStreamId++;
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07001529 mNeedConfig = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001530
1531 // Continue captures if active at start
1532 if (wasActive) {
1533 ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001534 // Reuse current operating mode and session parameters for new stream config
1535 res = configureStreamsLocked(mOperatingMode, mSessionParams);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001536 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001537 CLOGE("Can't reconfigure device for new stream %d: %s (%d)",
1538 mNextStreamId, strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001539 return res;
1540 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001541 internalResumeLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001542 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001543 ALOGV("Camera %s: Created new stream", mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001544 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001545}
1546
Emilian Peev710c1422017-08-30 11:19:38 +01001547status_t Camera3Device::getStreamInfo(int id, StreamInfo *streamInfo) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001548 ATRACE_CALL();
Emilian Peev710c1422017-08-30 11:19:38 +01001549 if (nullptr == streamInfo) {
1550 return BAD_VALUE;
1551 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001552 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001553 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001554
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001555 switch (mStatus) {
1556 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001557 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001558 return INVALID_OPERATION;
1559 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001560 CLOGE("Device not initialized!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001561 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001562 case STATUS_UNCONFIGURED:
1563 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001564 case STATUS_ACTIVE:
1565 // OK
1566 break;
1567 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001568 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001569 return INVALID_OPERATION;
1570 }
1571
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001572 sp<Camera3StreamInterface> stream = mOutputStreams.get(id);
1573 if (stream == nullptr) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001574 CLOGE("Stream %d is unknown", id);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001575 return BAD_VALUE;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001576 }
1577
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001578 streamInfo->width = stream->getWidth();
1579 streamInfo->height = stream->getHeight();
1580 streamInfo->format = stream->getFormat();
1581 streamInfo->dataSpace = stream->getDataSpace();
1582 streamInfo->formatOverridden = stream->isFormatOverridden();
1583 streamInfo->originalFormat = stream->getOriginalFormat();
1584 streamInfo->dataSpaceOverridden = stream->isDataSpaceOverridden();
1585 streamInfo->originalDataSpace = stream->getOriginalDataSpace();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001586 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001587}
1588
1589status_t Camera3Device::setStreamTransform(int id,
1590 int transform) {
1591 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001592 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001593 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001594
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001595 switch (mStatus) {
1596 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001597 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001598 return INVALID_OPERATION;
1599 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001600 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001601 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001602 case STATUS_UNCONFIGURED:
1603 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001604 case STATUS_ACTIVE:
1605 // OK
1606 break;
1607 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001608 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001609 return INVALID_OPERATION;
1610 }
1611
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001612 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(id);
1613 if (stream == nullptr) {
1614 CLOGE("Stream %d does not exist", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001615 return BAD_VALUE;
1616 }
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001617 return stream->setTransform(transform);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001618}
1619
1620status_t Camera3Device::deleteStream(int id) {
1621 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001622 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001623 Mutex::Autolock l(mLock);
1624 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001625
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001626 ALOGV("%s: Camera %s: Deleting stream %d", __FUNCTION__, mId.string(), id);
Igor Murashkine2172be2013-05-28 15:31:39 -07001627
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001628 // CameraDevice semantics require device to already be idle before
1629 // deleteStream is called, unlike for createStream.
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001630 if (mStatus == STATUS_ACTIVE) {
Yin-Chia Yeh693047d2018-03-08 12:14:19 -08001631 ALOGW("%s: Camera %s: Device not idle", __FUNCTION__, mId.string());
Igor Murashkin52827132013-05-13 14:53:44 -07001632 return -EBUSY;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001633 }
1634
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07001635 if (mStatus == STATUS_ERROR) {
1636 ALOGW("%s: Camera %s: deleteStream not allowed in ERROR state",
1637 __FUNCTION__, mId.string());
1638 return -EBUSY;
1639 }
1640
Igor Murashkin2fba5842013-04-22 14:03:54 -07001641 sp<Camera3StreamInterface> deletedStream;
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001642 sp<Camera3StreamInterface> stream = mOutputStreams.get(id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001643 if (mInputStream != NULL && id == mInputStream->getId()) {
1644 deletedStream = mInputStream;
1645 mInputStream.clear();
1646 } else {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001647 if (stream == nullptr) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001648 CLOGE("Stream %d does not exist", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001649 return BAD_VALUE;
1650 }
Shuzhen Wang316781a2020-08-18 18:11:01 -07001651 mSessionStatsBuilder.removeStream(id);
Zhijun He5f446352014-01-22 09:49:33 -08001652 }
1653
1654 // Delete output stream or the output part of a bi-directional stream.
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001655 if (stream != nullptr) {
1656 deletedStream = stream;
1657 mOutputStreams.remove(id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001658 }
1659
1660 // Free up the stream endpoint so that it can be used by some other stream
1661 res = deletedStream->disconnect();
1662 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001663 SET_ERR_L("Can't disconnect deleted stream %d", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001664 // fall through since we want to still list the stream as deleted.
1665 }
1666 mDeletedStreams.add(deletedStream);
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07001667 mNeedConfig = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001668
1669 return res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001670}
1671
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001672status_t Camera3Device::configureStreams(const CameraMetadata& sessionParams, int operatingMode) {
Igor Murashkine2d167e2014-08-19 16:19:59 -07001673 ATRACE_CALL();
1674 ALOGV("%s: E", __FUNCTION__);
1675
1676 Mutex::Autolock il(mInterfaceLock);
1677 Mutex::Autolock l(mLock);
Chien-Yu Chen17338fc2015-06-18 16:30:12 -07001678
Emilian Peev811d2952018-05-25 11:08:40 +01001679 // In case the client doesn't include any session parameter, try a
1680 // speculative configuration using the values from the last cached
1681 // default request.
1682 if (sessionParams.isEmpty() &&
Emilian Peevf4816702020-04-03 15:44:51 -07001683 ((mLastTemplateId > 0) && (mLastTemplateId < CAMERA_TEMPLATE_COUNT)) &&
Emilian Peev811d2952018-05-25 11:08:40 +01001684 (!mRequestTemplateCache[mLastTemplateId].isEmpty())) {
1685 ALOGV("%s: Speculative session param configuration with template id: %d", __func__,
1686 mLastTemplateId);
1687 return filterParamsAndConfigureLocked(mRequestTemplateCache[mLastTemplateId],
1688 operatingMode);
1689 }
1690
Emilian Peevac3ce6c2017-12-12 15:27:02 +00001691 return filterParamsAndConfigureLocked(sessionParams, operatingMode);
1692}
1693
1694status_t Camera3Device::filterParamsAndConfigureLocked(const CameraMetadata& sessionParams,
1695 int operatingMode) {
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001696 //Filter out any incoming session parameters
1697 const CameraMetadata params(sessionParams);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001698 camera_metadata_entry_t availableSessionKeys = mDeviceInfo.find(
1699 ANDROID_REQUEST_AVAILABLE_SESSION_KEYS);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00001700 CameraMetadata filteredParams(availableSessionKeys.count);
1701 camera_metadata_t *meta = const_cast<camera_metadata_t *>(
1702 filteredParams.getAndLock());
1703 set_camera_metadata_vendor_id(meta, mVendorTagId);
1704 filteredParams.unlock(meta);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001705 if (availableSessionKeys.count > 0) {
1706 for (size_t i = 0; i < availableSessionKeys.count; i++) {
1707 camera_metadata_ro_entry entry = params.find(
1708 availableSessionKeys.data.i32[i]);
1709 if (entry.count > 0) {
1710 filteredParams.update(entry);
1711 }
1712 }
1713 }
1714
1715 return configureStreamsLocked(operatingMode, filteredParams);
Igor Murashkine2d167e2014-08-19 16:19:59 -07001716}
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001717
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07001718status_t Camera3Device::getInputBufferProducer(
1719 sp<IGraphicBufferProducer> *producer) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07001720 ATRACE_CALL();
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07001721 Mutex::Autolock il(mInterfaceLock);
1722 Mutex::Autolock l(mLock);
1723
1724 if (producer == NULL) {
1725 return BAD_VALUE;
1726 } else if (mInputStream == NULL) {
1727 return INVALID_OPERATION;
1728 }
1729
1730 return mInputStream->getInputBufferProducer(producer);
1731}
1732
Emilian Peevf4816702020-04-03 15:44:51 -07001733status_t Camera3Device::createDefaultRequest(camera_request_template_t templateId,
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001734 CameraMetadata *request) {
1735 ATRACE_CALL();
Alex Rayfe7e0c62013-05-30 00:12:13 -07001736 ALOGV("%s: for template %d", __FUNCTION__, templateId);
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08001737
Emilian Peevf4816702020-04-03 15:44:51 -07001738 if (templateId <= 0 || templateId >= CAMERA_TEMPLATE_COUNT) {
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08001739 android_errorWriteWithInfoLog(CameraService::SN_EVENT_LOG_ID, "26866110",
Jayant Chowdhary12361932018-08-27 14:46:13 -07001740 CameraThreadState::getCallingUid(), nullptr, 0);
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08001741 return BAD_VALUE;
1742 }
1743
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001744 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001745
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001746 {
1747 Mutex::Autolock l(mLock);
1748 switch (mStatus) {
1749 case STATUS_ERROR:
1750 CLOGE("Device has encountered a serious error");
1751 return INVALID_OPERATION;
1752 case STATUS_UNINITIALIZED:
1753 CLOGE("Device is not initialized!");
1754 return INVALID_OPERATION;
1755 case STATUS_UNCONFIGURED:
1756 case STATUS_CONFIGURED:
1757 case STATUS_ACTIVE:
1758 // OK
1759 break;
1760 default:
1761 SET_ERR_L("Unexpected status: %d", mStatus);
1762 return INVALID_OPERATION;
1763 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001764
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001765 if (!mRequestTemplateCache[templateId].isEmpty()) {
1766 *request = mRequestTemplateCache[templateId];
Emilian Peev811d2952018-05-25 11:08:40 +01001767 mLastTemplateId = templateId;
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001768 return OK;
1769 }
Zhijun Hea1530f12014-09-14 12:44:20 -07001770 }
1771
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001772 camera_metadata_t *rawRequest;
1773 status_t res = mInterface->constructDefaultRequestSettings(
Emilian Peevf4816702020-04-03 15:44:51 -07001774 (camera_request_template_t) templateId, &rawRequest);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001775
1776 {
1777 Mutex::Autolock l(mLock);
1778 if (res == BAD_VALUE) {
1779 ALOGI("%s: template %d is not supported on this camera device",
1780 __FUNCTION__, templateId);
1781 return res;
1782 } else if (res != OK) {
1783 CLOGE("Unable to construct request template %d: %s (%d)",
1784 templateId, strerror(-res), res);
1785 return res;
1786 }
1787
1788 set_camera_metadata_vendor_id(rawRequest, mVendorTagId);
1789 mRequestTemplateCache[templateId].acquire(rawRequest);
1790
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08001791 // Override the template request with zoomRatioMapper
1792 res = mZoomRatioMappers[mId.c_str()].initZoomRatioInTemplate(
1793 &mRequestTemplateCache[templateId]);
1794 if (res != OK) {
1795 CLOGE("Failed to update zoom ratio for template %d: %s (%d)",
1796 templateId, strerror(-res), res);
1797 return res;
1798 }
1799
Shuzhen Wangd25dc972020-03-24 17:11:43 -07001800 // Fill in JPEG_QUALITY if not available
1801 if (!mRequestTemplateCache[templateId].exists(ANDROID_JPEG_QUALITY)) {
1802 static const uint8_t kDefaultJpegQuality = 95;
1803 mRequestTemplateCache[templateId].update(ANDROID_JPEG_QUALITY,
1804 &kDefaultJpegQuality, 1);
1805 }
1806
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001807 *request = mRequestTemplateCache[templateId];
Emilian Peev811d2952018-05-25 11:08:40 +01001808 mLastTemplateId = templateId;
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001809 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001810 return OK;
1811}
1812
1813status_t Camera3Device::waitUntilDrained() {
1814 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001815 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001816 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001817 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001818
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001819 return waitUntilDrainedLocked(maxExpectedDuration);
Zhijun He69a37482014-03-23 18:44:49 -07001820}
1821
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001822status_t Camera3Device::waitUntilDrainedLocked(nsecs_t maxExpectedDuration) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001823 switch (mStatus) {
1824 case STATUS_UNINITIALIZED:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001825 case STATUS_UNCONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001826 ALOGV("%s: Already idle", __FUNCTION__);
1827 return OK;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001828 case STATUS_CONFIGURED:
1829 // To avoid race conditions, check with tracker to be sure
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001830 case STATUS_ERROR:
1831 case STATUS_ACTIVE:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001832 // Need to verify shut down
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001833 break;
1834 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001835 SET_ERR_L("Unexpected status: %d",mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001836 return INVALID_OPERATION;
1837 }
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07001838 ALOGV("%s: Camera %s: Waiting until idle (%" PRIi64 "ns)", __FUNCTION__, mId.string(),
1839 maxExpectedDuration);
1840 status_t res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
Eino-Ville Talvala9c8a0912014-09-14 14:52:19 -07001841 if (res != OK) {
Yin-Chia Yeh87b3ec02019-06-03 10:44:39 -07001842 mStatusTracker->dumpActiveComponents();
Eino-Ville Talvala9c8a0912014-09-14 14:52:19 -07001843 SET_ERR_L("Error waiting for HAL to drain: %s (%d)", strerror(-res),
1844 res);
1845 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001846 return res;
1847}
1848
Ruben Brunk183f0562015-08-12 12:55:02 -07001849void Camera3Device::internalUpdateStatusLocked(Status status) {
1850 mStatus = status;
1851 mRecentStatusUpdates.add(mStatus);
1852 mStatusChanged.broadcast();
1853}
1854
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001855// Pause to reconfigure
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001856status_t Camera3Device::internalPauseAndWaitLocked(nsecs_t maxExpectedDuration) {
Emilian Peeve86358b2019-02-15 13:51:39 -08001857 if (mRequestThread.get() != nullptr) {
1858 mRequestThread->setPaused(true);
1859 } else {
1860 return NO_INIT;
1861 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001862
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07001863 ALOGV("%s: Camera %s: Internal wait until idle (% " PRIi64 " ns)", __FUNCTION__, mId.string(),
1864 maxExpectedDuration);
1865 status_t res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001866 if (res != OK) {
1867 SET_ERR_L("Can't idle device in %f seconds!",
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07001868 maxExpectedDuration/1e9);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001869 }
1870
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001871 return res;
1872}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001873
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001874// Resume after internalPauseAndWaitLocked
1875status_t Camera3Device::internalResumeLocked() {
1876 status_t res;
1877
1878 mRequestThread->setPaused(false);
1879
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08001880 ALOGV("%s: Camera %s: Internal wait until active (% " PRIi64 " ns)", __FUNCTION__, mId.string(),
1881 kActiveTimeout);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001882 res = waitUntilStateThenRelock(/*active*/ true, kActiveTimeout);
1883 if (res != OK) {
1884 SET_ERR_L("Can't transition to active in %f seconds!",
1885 kActiveTimeout/1e9);
1886 }
1887 mPauseStateNotify = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001888 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001889}
1890
Ruben Brunk183f0562015-08-12 12:55:02 -07001891status_t Camera3Device::waitUntilStateThenRelock(bool active, nsecs_t timeout) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001892 status_t res = OK;
Ruben Brunk183f0562015-08-12 12:55:02 -07001893
1894 size_t startIndex = 0;
1895 if (mStatusWaiters == 0) {
1896 // Clear the list of recent statuses if there are no existing threads waiting on updates to
1897 // this status list
1898 mRecentStatusUpdates.clear();
1899 } else {
1900 // If other threads are waiting on updates to this status list, set the position of the
1901 // first element that this list will check rather than clearing the list.
1902 startIndex = mRecentStatusUpdates.size();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001903 }
1904
Ruben Brunk183f0562015-08-12 12:55:02 -07001905 mStatusWaiters++;
1906
Yin-Chia Yehe52b8fa2020-07-28 00:17:58 -07001907 bool signalPipelineDrain = false;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07001908 if (!active && mUseHalBufManager) {
1909 auto streamIds = mOutputStreams.getStreamIds();
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08001910 if (mStatus == STATUS_ACTIVE) {
1911 mRequestThread->signalPipelineDrain(streamIds);
Yin-Chia Yehe52b8fa2020-07-28 00:17:58 -07001912 signalPipelineDrain = true;
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08001913 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07001914 mRequestBufferSM.onWaitUntilIdle();
1915 }
1916
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001917 bool stateSeen = false;
1918 do {
Ruben Brunk183f0562015-08-12 12:55:02 -07001919 if (active == (mStatus == STATUS_ACTIVE)) {
1920 // Desired state is current
1921 break;
1922 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001923
1924 res = mStatusChanged.waitRelative(mLock, timeout);
1925 if (res != OK) break;
1926
Ruben Brunk183f0562015-08-12 12:55:02 -07001927 // This is impossible, but if not, could result in subtle deadlocks and invalid state
1928 // transitions.
1929 LOG_ALWAYS_FATAL_IF(startIndex > mRecentStatusUpdates.size(),
1930 "%s: Skipping status updates in Camera3Device, may result in deadlock.",
1931 __FUNCTION__);
1932
1933 // Encountered desired state since we began waiting
1934 for (size_t i = startIndex; i < mRecentStatusUpdates.size(); i++) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001935 if (active == (mRecentStatusUpdates[i] == STATUS_ACTIVE) ) {
1936 stateSeen = true;
1937 break;
1938 }
1939 }
1940 } while (!stateSeen);
1941
Yin-Chia Yehe52b8fa2020-07-28 00:17:58 -07001942 if (signalPipelineDrain) {
1943 mRequestThread->resetPipelineDrain();
1944 }
1945
Ruben Brunk183f0562015-08-12 12:55:02 -07001946 mStatusWaiters--;
1947
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001948 return res;
1949}
1950
1951
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001952status_t Camera3Device::setNotifyCallback(wp<NotificationListener> listener) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001953 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001954 std::lock_guard<std::mutex> l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001955
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001956 if (listener != NULL && mListener != NULL) {
1957 ALOGW("%s: Replacing old callback listener", __FUNCTION__);
1958 }
1959 mListener = listener;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001960 mRequestThread->setNotificationListener(listener);
1961 mPreparerThread->setNotificationListener(listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001962
1963 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001964}
1965
Eino-Ville Talvala46910bd2013-07-18 19:15:17 -07001966bool Camera3Device::willNotify3A() {
1967 return false;
1968}
1969
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001970status_t Camera3Device::waitForNextFrame(nsecs_t timeout) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07001971 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001972 std::unique_lock<std::mutex> l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001973
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001974 while (mResultQueue.empty()) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001975 auto st = mResultSignal.wait_for(l, std::chrono::nanoseconds(timeout));
1976 if (st == std::cv_status::timeout) {
1977 return TIMED_OUT;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001978 }
1979 }
1980 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001981}
1982
Jianing Weicb0652e2014-03-12 18:29:36 -07001983status_t Camera3Device::getNextResult(CaptureResult *frame) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001984 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001985 std::lock_guard<std::mutex> l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001986
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001987 if (mResultQueue.empty()) {
1988 return NOT_ENOUGH_DATA;
1989 }
1990
Jianing Weicb0652e2014-03-12 18:29:36 -07001991 if (frame == NULL) {
1992 ALOGE("%s: argument cannot be NULL", __FUNCTION__);
1993 return BAD_VALUE;
1994 }
1995
1996 CaptureResult &result = *(mResultQueue.begin());
1997 frame->mResultExtras = result.mResultExtras;
1998 frame->mMetadata.acquire(result.mMetadata);
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001999 frame->mPhysicalMetadatas = std::move(result.mPhysicalMetadatas);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002000 mResultQueue.erase(mResultQueue.begin());
2001
2002 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002003}
2004
2005status_t Camera3Device::triggerAutofocus(uint32_t id) {
2006 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002007 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002008
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002009 ALOGV("%s: Triggering autofocus, id %d", __FUNCTION__, id);
2010 // Mix-in this trigger into the next request and only the next request.
2011 RequestTrigger trigger[] = {
2012 {
2013 ANDROID_CONTROL_AF_TRIGGER,
2014 ANDROID_CONTROL_AF_TRIGGER_START
2015 },
2016 {
2017 ANDROID_CONTROL_AF_TRIGGER_ID,
2018 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07002019 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002020 };
2021
2022 return mRequestThread->queueTrigger(trigger,
2023 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002024}
2025
2026status_t Camera3Device::triggerCancelAutofocus(uint32_t id) {
2027 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002028 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002029
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002030 ALOGV("%s: Triggering cancel autofocus, id %d", __FUNCTION__, id);
2031 // Mix-in this trigger into the next request and only the next request.
2032 RequestTrigger trigger[] = {
2033 {
2034 ANDROID_CONTROL_AF_TRIGGER,
2035 ANDROID_CONTROL_AF_TRIGGER_CANCEL
2036 },
2037 {
2038 ANDROID_CONTROL_AF_TRIGGER_ID,
2039 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07002040 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002041 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002042
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002043 return mRequestThread->queueTrigger(trigger,
2044 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002045}
2046
2047status_t Camera3Device::triggerPrecaptureMetering(uint32_t id) {
2048 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002049 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002050
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002051 ALOGV("%s: Triggering precapture metering, id %d", __FUNCTION__, id);
2052 // Mix-in this trigger into the next request and only the next request.
2053 RequestTrigger trigger[] = {
2054 {
2055 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER,
2056 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_START
2057 },
2058 {
2059 ANDROID_CONTROL_AE_PRECAPTURE_ID,
2060 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07002061 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002062 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002063
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002064 return mRequestThread->queueTrigger(trigger,
2065 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002066}
2067
Jianing Weicb0652e2014-03-12 18:29:36 -07002068status_t Camera3Device::flush(int64_t *frameNumber) {
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07002069 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002070 ALOGV("%s: Camera %s: Flushing all requests", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002071 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07002072
Zhijun He7ef20392014-04-21 16:04:17 -07002073 {
2074 Mutex::Autolock l(mLock);
Emilian Peeved2ebe42018-09-25 16:59:09 +01002075
2076 // b/116514106 "disconnect()" can get called twice for the same device. The
2077 // camera device will not be initialized during the second run.
2078 if (mStatus == STATUS_UNINITIALIZED) {
2079 return OK;
2080 }
2081
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002082 mRequestThread->clear(/*out*/frameNumber);
Shuzhen Wang316781a2020-08-18 18:11:01 -07002083
2084 // Stop session and stream counter
2085 mSessionStatsBuilder.stopCounter();
Zhijun He7ef20392014-04-21 16:04:17 -07002086 }
2087
Emilian Peev08dd2452017-04-06 16:55:14 +01002088 return mRequestThread->flush();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07002089}
2090
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002091status_t Camera3Device::prepare(int streamId) {
Ruben Brunkc78ac262015-08-13 17:58:46 -07002092 return prepare(camera3::Camera3StreamInterface::ALLOCATE_PIPELINE_MAX, streamId);
2093}
2094
2095status_t Camera3Device::prepare(int maxCount, int streamId) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002096 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002097 ALOGV("%s: Camera %s: Preparing stream %d", __FUNCTION__, mId.string(), streamId);
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07002098 Mutex::Autolock il(mInterfaceLock);
2099 Mutex::Autolock l(mLock);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002100
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002101 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
2102 if (stream == nullptr) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002103 CLOGE("Stream %d does not exist", streamId);
2104 return BAD_VALUE;
2105 }
2106
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002107 if (stream->isUnpreparable() || stream->hasOutstandingBuffers() ) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07002108 CLOGE("Stream %d has already been a request target", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002109 return BAD_VALUE;
2110 }
2111
2112 if (mRequestThread->isStreamPending(stream)) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07002113 CLOGE("Stream %d is already a target in a pending request", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002114 return BAD_VALUE;
2115 }
2116
Ruben Brunkc78ac262015-08-13 17:58:46 -07002117 return mPreparerThread->prepare(maxCount, stream);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002118}
2119
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002120status_t Camera3Device::tearDown(int streamId) {
2121 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002122 ALOGV("%s: Camera %s: Tearing down stream %d", __FUNCTION__, mId.string(), streamId);
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002123 Mutex::Autolock il(mInterfaceLock);
2124 Mutex::Autolock l(mLock);
2125
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002126 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
2127 if (stream == nullptr) {
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002128 CLOGE("Stream %d does not exist", streamId);
2129 return BAD_VALUE;
2130 }
2131
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002132 if (stream->hasOutstandingBuffers() || mRequestThread->isStreamPending(stream)) {
2133 CLOGE("Stream %d is a target of a in-progress request", streamId);
2134 return BAD_VALUE;
2135 }
2136
2137 return stream->tearDown();
2138}
2139
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002140status_t Camera3Device::addBufferListenerForStream(int streamId,
2141 wp<Camera3StreamBufferListener> listener) {
2142 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002143 ALOGV("%s: Camera %s: Adding buffer listener for stream %d", __FUNCTION__, mId.string(), streamId);
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002144 Mutex::Autolock il(mInterfaceLock);
2145 Mutex::Autolock l(mLock);
2146
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002147 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
2148 if (stream == nullptr) {
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002149 CLOGE("Stream %d does not exist", streamId);
2150 return BAD_VALUE;
2151 }
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002152 stream->addBufferListener(listener);
2153
2154 return OK;
2155}
2156
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002157/**
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002158 * Methods called by subclasses
2159 */
2160
2161void Camera3Device::notifyStatus(bool idle) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002162 ATRACE_CALL();
Shuzhen Wang316781a2020-08-18 18:11:01 -07002163 std::vector<int> streamIds;
2164 std::vector<hardware::CameraStreamStats> streamStats;
2165
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002166 {
2167 // Need mLock to safely update state and synchronize to current
2168 // state of methods in flight.
2169 Mutex::Autolock l(mLock);
2170 // We can get various system-idle notices from the status tracker
2171 // while starting up. Only care about them if we've actually sent
2172 // in some requests recently.
2173 if (mStatus != STATUS_ACTIVE && mStatus != STATUS_CONFIGURED) {
2174 return;
2175 }
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08002176 ALOGV("%s: Camera %s: Now %s, pauseState: %s", __FUNCTION__, mId.string(),
2177 idle ? "idle" : "active", mPauseStateNotify ? "true" : "false");
Ruben Brunk183f0562015-08-12 12:55:02 -07002178 internalUpdateStatusLocked(idle ? STATUS_CONFIGURED : STATUS_ACTIVE);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002179
2180 // Skip notifying listener if we're doing some user-transparent
2181 // state changes
2182 if (mPauseStateNotify) return;
Shuzhen Wang316781a2020-08-18 18:11:01 -07002183
2184 // Populate stream statistics in case of Idle
2185 if (idle) {
2186 for (size_t i = 0; i < mOutputStreams.size(); i++) {
2187 auto stream = mOutputStreams[i];
2188 if (stream.get() == nullptr) continue;
2189 streamIds.push_back(stream->getId());
2190 Camera3Stream* camera3Stream = Camera3Stream::cast(stream->asHalStream());
2191 int64_t usage = 0LL;
2192 if (camera3Stream != nullptr) {
2193 usage = camera3Stream->getUsage();
2194 }
2195 streamStats.emplace_back(stream->getWidth(), stream->getHeight(),
2196 stream->getFormat(), stream->getDataSpace(), usage,
2197 stream->getMaxHalBuffers(),
2198 stream->getMaxTotalBuffers() - stream->getMaxHalBuffers());
2199 }
2200 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002201 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002202
2203 sp<NotificationListener> listener;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002204 {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002205 std::lock_guard<std::mutex> l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002206 listener = mListener.promote();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002207 }
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07002208 status_t res = OK;
2209 if (listener != nullptr) {
2210 if (idle) {
2211 // Get session stats from the builder, and notify the listener.
2212 int64_t requestCount, resultErrorCount;
2213 bool deviceError;
2214 std::map<int, StreamStats> streamStatsMap;
2215 mSessionStatsBuilder.buildAndReset(&requestCount, &resultErrorCount,
2216 &deviceError, &streamStatsMap);
2217 for (size_t i = 0; i < streamIds.size(); i++) {
2218 int streamId = streamIds[i];
2219 auto stats = streamStatsMap.find(streamId);
2220 if (stats != streamStatsMap.end()) {
2221 streamStats[i].mRequestCount = stats->second.mRequestedFrameCount;
2222 streamStats[i].mErrorCount = stats->second.mDroppedFrameCount;
2223 streamStats[i].mStartLatencyMs = stats->second.mStartLatencyMs;
2224 streamStats[i].mHistogramType =
2225 hardware::CameraStreamStats::HISTOGRAM_TYPE_CAPTURE_LATENCY;
2226 streamStats[i].mHistogramBins.assign(
2227 stats->second.mCaptureLatencyBins.begin(),
2228 stats->second.mCaptureLatencyBins.end());
2229 streamStats[i].mHistogramCounts.assign(
2230 stats->second.mCaptureLatencyHistogram.begin(),
2231 stats->second.mCaptureLatencyHistogram.end());
2232 }
Shuzhen Wang316781a2020-08-18 18:11:01 -07002233 }
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07002234 listener->notifyIdle(requestCount, resultErrorCount, deviceError, streamStats);
2235 } else {
2236 res = listener->notifyActive();
Shuzhen Wang316781a2020-08-18 18:11:01 -07002237 }
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07002238 }
2239 if (res != OK) {
2240 SET_ERR("Camera access permission lost mid-operation: %s (%d)",
2241 strerror(-res), res);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002242 }
2243}
2244
Shuzhen Wang758c2152017-01-10 18:26:18 -08002245status_t Camera3Device::setConsumerSurfaces(int streamId,
Emilian Peev40ead602017-09-26 15:46:36 +01002246 const std::vector<sp<Surface>>& consumers, std::vector<int> *surfaceIds) {
Zhijun He5d677d12016-05-29 16:52:39 -07002247 ATRACE_CALL();
Shuzhen Wang758c2152017-01-10 18:26:18 -08002248 ALOGV("%s: Camera %s: set consumer surface for stream %d",
2249 __FUNCTION__, mId.string(), streamId);
Emilian Peev40ead602017-09-26 15:46:36 +01002250
2251 if (surfaceIds == nullptr) {
2252 return BAD_VALUE;
2253 }
2254
Zhijun He5d677d12016-05-29 16:52:39 -07002255 Mutex::Autolock il(mInterfaceLock);
2256 Mutex::Autolock l(mLock);
2257
Shuzhen Wang758c2152017-01-10 18:26:18 -08002258 if (consumers.size() == 0) {
2259 CLOGE("No consumer is passed!");
Zhijun He5d677d12016-05-29 16:52:39 -07002260 return BAD_VALUE;
2261 }
2262
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002263 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
2264 if (stream == nullptr) {
Zhijun He5d677d12016-05-29 16:52:39 -07002265 CLOGE("Stream %d is unknown", streamId);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002266 return BAD_VALUE;
Zhijun He5d677d12016-05-29 16:52:39 -07002267 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002268
2269 // isConsumerConfigurationDeferred will be off after setConsumers
2270 bool isDeferred = stream->isConsumerConfigurationDeferred();
Shuzhen Wang758c2152017-01-10 18:26:18 -08002271 status_t res = stream->setConsumers(consumers);
Zhijun He5d677d12016-05-29 16:52:39 -07002272 if (res != OK) {
2273 CLOGE("Stream %d set consumer failed (error %d %s) ", streamId, res, strerror(-res));
2274 return res;
2275 }
2276
Emilian Peev40ead602017-09-26 15:46:36 +01002277 for (auto &consumer : consumers) {
2278 int id = stream->getSurfaceId(consumer);
2279 if (id < 0) {
2280 CLOGE("Invalid surface id!");
2281 return BAD_VALUE;
2282 }
2283 surfaceIds->push_back(id);
2284 }
2285
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002286 if (isDeferred) {
Shuzhen Wang0129d522016-10-30 22:43:41 -07002287 if (!stream->isConfiguring()) {
2288 CLOGE("Stream %d was already fully configured.", streamId);
2289 return INVALID_OPERATION;
2290 }
Zhijun He5d677d12016-05-29 16:52:39 -07002291
Shuzhen Wang0129d522016-10-30 22:43:41 -07002292 res = stream->finishConfiguration();
2293 if (res != OK) {
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002294 // If finishConfiguration fails due to abandoned surface, do not set
2295 // device to error state.
2296 bool isSurfaceAbandoned =
2297 (res == NO_INIT || res == DEAD_OBJECT) && stream->isAbandoned();
2298 if (!isSurfaceAbandoned) {
2299 SET_ERR_L("Can't finish configuring output stream %d: %s (%d)",
2300 stream->getId(), strerror(-res), res);
2301 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07002302 return res;
2303 }
Zhijun He5d677d12016-05-29 16:52:39 -07002304 }
2305
2306 return OK;
2307}
2308
Emilian Peev40ead602017-09-26 15:46:36 +01002309status_t Camera3Device::updateStream(int streamId, const std::vector<sp<Surface>> &newSurfaces,
2310 const std::vector<OutputStreamInfo> &outputInfo,
2311 const std::vector<size_t> &removedSurfaceIds, KeyedVector<sp<Surface>, size_t> *outputMap) {
2312 Mutex::Autolock il(mInterfaceLock);
2313 Mutex::Autolock l(mLock);
2314
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002315 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
2316 if (stream == nullptr) {
Emilian Peev40ead602017-09-26 15:46:36 +01002317 CLOGE("Stream %d is unknown", streamId);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002318 return BAD_VALUE;
Emilian Peev40ead602017-09-26 15:46:36 +01002319 }
2320
2321 for (const auto &it : removedSurfaceIds) {
2322 if (mRequestThread->isOutputSurfacePending(streamId, it)) {
2323 CLOGE("Shared surface still part of a pending request!");
2324 return -EBUSY;
2325 }
2326 }
2327
Emilian Peev40ead602017-09-26 15:46:36 +01002328 status_t res = stream->updateStream(newSurfaces, outputInfo, removedSurfaceIds, outputMap);
2329 if (res != OK) {
2330 CLOGE("Stream %d failed to update stream (error %d %s) ",
2331 streamId, res, strerror(-res));
2332 if (res == UNKNOWN_ERROR) {
2333 SET_ERR_L("%s: Stream update failed to revert to previous output configuration!",
2334 __FUNCTION__);
2335 }
2336 return res;
2337 }
2338
2339 return res;
2340}
2341
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002342status_t Camera3Device::dropStreamBuffers(bool dropping, int streamId) {
2343 Mutex::Autolock il(mInterfaceLock);
2344 Mutex::Autolock l(mLock);
2345
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002346 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
2347 if (stream == nullptr) {
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002348 ALOGE("%s: Stream %d is not found.", __FUNCTION__, streamId);
2349 return BAD_VALUE;
2350 }
Shuzhen Wang316781a2020-08-18 18:11:01 -07002351
2352 if (dropping) {
2353 mSessionStatsBuilder.stopCounter(streamId);
2354 } else {
2355 mSessionStatsBuilder.startCounter(streamId);
2356 }
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002357 return stream->dropBuffers(dropping);
2358}
2359
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002360/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002361 * Camera3Device private methods
2362 */
2363
2364sp<Camera3Device::CaptureRequest> Camera3Device::createCaptureRequest(
Emilian Peevaebbe412018-01-15 13:53:24 +00002365 const PhysicalCameraSettingsList &request, const SurfaceMap &surfaceMap) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002366 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002367
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08002368 sp<CaptureRequest> newRequest = new CaptureRequest();
Emilian Peevaebbe412018-01-15 13:53:24 +00002369 newRequest->mSettingsList = request;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002370
2371 camera_metadata_entry_t inputStreams =
Emilian Peevaebbe412018-01-15 13:53:24 +00002372 newRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_INPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002373 if (inputStreams.count > 0) {
2374 if (mInputStream == NULL ||
Zhijun Hed1d64672013-09-06 15:00:01 -07002375 mInputStream->getId() != inputStreams.data.i32[0]) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002376 CLOGE("Request references unknown input stream %d",
2377 inputStreams.data.u8[0]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002378 return NULL;
2379 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002380
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002381 if (mInputStream->isConfiguring()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002382 SET_ERR_L("%s: input stream %d is not configured!",
2383 __FUNCTION__, mInputStream->getId());
2384 return NULL;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002385 }
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07002386 // Check if stream prepare is blocking requests.
2387 if (mInputStream->isBlockedByPrepare()) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002388 CLOGE("Request references an input stream that's being prepared!");
2389 return NULL;
2390 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002391
2392 newRequest->mInputStream = mInputStream;
Emilian Peevaebbe412018-01-15 13:53:24 +00002393 newRequest->mSettingsList.begin()->metadata.erase(ANDROID_REQUEST_INPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002394 }
2395
2396 camera_metadata_entry_t streams =
Emilian Peevaebbe412018-01-15 13:53:24 +00002397 newRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_OUTPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002398 if (streams.count == 0) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002399 CLOGE("Zero output streams specified!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002400 return NULL;
2401 }
2402
2403 for (size_t i = 0; i < streams.count; i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002404 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streams.data.i32[i]);
2405 if (stream == nullptr) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002406 CLOGE("Request references unknown stream %d",
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002407 streams.data.i32[i]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002408 return NULL;
2409 }
Zhijun He5d677d12016-05-29 16:52:39 -07002410 // It is illegal to include a deferred consumer output stream into a request
Shuzhen Wang0129d522016-10-30 22:43:41 -07002411 auto iter = surfaceMap.find(streams.data.i32[i]);
2412 if (iter != surfaceMap.end()) {
2413 const std::vector<size_t>& surfaces = iter->second;
2414 for (const auto& surface : surfaces) {
2415 if (stream->isConsumerConfigurationDeferred(surface)) {
2416 CLOGE("Stream %d surface %zu hasn't finished configuration yet "
2417 "due to deferred consumer", stream->getId(), surface);
2418 return NULL;
2419 }
2420 }
Yin-Chia Yeh0b287572018-10-15 12:38:13 -07002421 newRequest->mOutputSurfaces[streams.data.i32[i]] = surfaces;
Zhijun He5d677d12016-05-29 16:52:39 -07002422 }
2423
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002424 if (stream->isConfiguring()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002425 SET_ERR_L("%s: stream %d is not configured!", __FUNCTION__, stream->getId());
2426 return NULL;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002427 }
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07002428 // Check if stream prepare is blocking requests.
2429 if (stream->isBlockedByPrepare()) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002430 CLOGE("Request references an output stream that's being prepared!");
2431 return NULL;
2432 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002433
2434 newRequest->mOutputStreams.push(stream);
2435 }
Emilian Peevaebbe412018-01-15 13:53:24 +00002436 newRequest->mSettingsList.begin()->metadata.erase(ANDROID_REQUEST_OUTPUT_STREAMS);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07002437 newRequest->mBatchSize = 1;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002438
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08002439 auto rotateAndCropEntry =
2440 newRequest->mSettingsList.begin()->metadata.find(ANDROID_SCALER_ROTATE_AND_CROP);
2441 if (rotateAndCropEntry.count > 0 &&
2442 rotateAndCropEntry.data.u8[0] == ANDROID_SCALER_ROTATE_AND_CROP_AUTO) {
2443 newRequest->mRotateAndCropAuto = true;
2444 } else {
2445 newRequest->mRotateAndCropAuto = false;
2446 }
2447
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07002448 auto zoomRatioEntry =
2449 newRequest->mSettingsList.begin()->metadata.find(ANDROID_CONTROL_ZOOM_RATIO);
2450 if (zoomRatioEntry.count > 0 &&
2451 zoomRatioEntry.data.f[0] == 1.0f) {
2452 newRequest->mZoomRatioIs1x = true;
2453 } else {
2454 newRequest->mZoomRatioIs1x = false;
2455 }
2456
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08002457 if (mSupportCameraMute) {
2458 auto testPatternModeEntry =
2459 newRequest->mSettingsList.begin()->metadata.find(ANDROID_SENSOR_TEST_PATTERN_MODE);
2460 newRequest->mOriginalTestPatternMode = testPatternModeEntry.count > 0 ?
2461 testPatternModeEntry.data.i32[0] :
2462 ANDROID_SENSOR_TEST_PATTERN_MODE_OFF;
2463
2464 auto testPatternDataEntry =
2465 newRequest->mSettingsList.begin()->metadata.find(ANDROID_SENSOR_TEST_PATTERN_DATA);
Eino-Ville Talvalac2459842021-07-22 16:36:36 -07002466 if (testPatternDataEntry.count >= 4) {
2467 memcpy(newRequest->mOriginalTestPatternData, testPatternDataEntry.data.i32,
2468 sizeof(CaptureRequest::mOriginalTestPatternData));
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08002469 } else {
2470 newRequest->mOriginalTestPatternData[0] = 0;
2471 newRequest->mOriginalTestPatternData[1] = 0;
2472 newRequest->mOriginalTestPatternData[2] = 0;
2473 newRequest->mOriginalTestPatternData[3] = 0;
2474 }
2475 }
2476
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002477 return newRequest;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002478}
2479
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002480void Camera3Device::cancelStreamsConfigurationLocked() {
2481 int res = OK;
2482 if (mInputStream != NULL && mInputStream->isConfiguring()) {
2483 res = mInputStream->cancelConfiguration();
2484 if (res != OK) {
2485 CLOGE("Can't cancel configuring input stream %d: %s (%d)",
2486 mInputStream->getId(), strerror(-res), res);
2487 }
2488 }
2489
2490 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002491 sp<Camera3OutputStreamInterface> outputStream = mOutputStreams[i];
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002492 if (outputStream->isConfiguring()) {
2493 res = outputStream->cancelConfiguration();
2494 if (res != OK) {
2495 CLOGE("Can't cancel configuring output stream %d: %s (%d)",
2496 outputStream->getId(), strerror(-res), res);
2497 }
2498 }
2499 }
2500
2501 // Return state to that at start of call, so that future configures
2502 // properly clean things up
2503 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
2504 mNeedConfig = true;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002505
2506 res = mPreparerThread->resume();
2507 if (res != OK) {
2508 ALOGE("%s: Camera %s: Preparer thread failed to resume!", __FUNCTION__, mId.string());
2509 }
2510}
2511
Emilian Peev0d0191e2020-04-21 17:01:18 -07002512bool Camera3Device::checkAbandonedStreamsLocked() {
2513 if ((mInputStream.get() != nullptr) && (mInputStream->isAbandoned())) {
2514 return true;
2515 }
2516
2517 for (size_t i = 0; i < mOutputStreams.size(); i++) {
2518 auto stream = mOutputStreams[i];
2519 if ((stream.get() != nullptr) && (stream->isAbandoned())) {
2520 return true;
2521 }
2522 }
2523
2524 return false;
2525}
2526
Emilian Peev3bead5f2020-05-28 17:29:08 -07002527bool Camera3Device::reconfigureCamera(const CameraMetadata& sessionParams, int clientStatusId) {
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002528 ATRACE_CALL();
2529 bool ret = false;
2530
Shuzhen Wang316781a2020-08-18 18:11:01 -07002531 nsecs_t startTime = systemTime();
2532
Jayant Chowdhary646c31b2020-01-30 13:09:59 -08002533 Mutex::Autolock il(mInterfaceLock);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002534 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
2535
2536 Mutex::Autolock l(mLock);
Emilian Peev0d0191e2020-04-21 17:01:18 -07002537 if (checkAbandonedStreamsLocked()) {
2538 ALOGW("%s: Abandoned stream detected, session parameters can't be applied correctly!",
2539 __FUNCTION__);
2540 return true;
2541 }
2542
Emilian Peev3bead5f2020-05-28 17:29:08 -07002543 status_t rc = NO_ERROR;
2544 bool markClientActive = false;
2545 if (mStatus == STATUS_ACTIVE) {
2546 markClientActive = true;
2547 mPauseStateNotify = true;
2548 mStatusTracker->markComponentIdle(clientStatusId, Fence::NO_FENCE);
2549
2550 rc = internalPauseAndWaitLocked(maxExpectedDuration);
2551 }
2552
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002553 if (rc == NO_ERROR) {
2554 mNeedConfig = true;
2555 rc = configureStreamsLocked(mOperatingMode, sessionParams, /*notifyRequestThread*/ false);
2556 if (rc == NO_ERROR) {
2557 ret = true;
2558 mPauseStateNotify = false;
2559 //Moving to active state while holding 'mLock' is important.
2560 //There could be pending calls to 'create-/deleteStream' which
2561 //will trigger another stream configuration while the already
2562 //present streams end up with outstanding buffers that will
2563 //not get drained.
2564 internalUpdateStatusLocked(STATUS_ACTIVE);
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002565 } else if (rc == DEAD_OBJECT) {
2566 // DEAD_OBJECT can be returned if either the consumer surface is
2567 // abandoned, or the HAL has died.
2568 // - If the HAL has died, configureStreamsLocked call will set
2569 // device to error state,
2570 // - If surface is abandoned, we should not set device to error
2571 // state.
2572 ALOGE("Failed to re-configure camera due to abandoned surface");
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002573 } else {
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002574 SET_ERR_L("Failed to re-configure camera: %d", rc);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002575 }
2576 } else {
2577 ALOGE("%s: Failed to pause streaming: %d", __FUNCTION__, rc);
2578 }
2579
Shuzhen Wang316781a2020-08-18 18:11:01 -07002580 CameraServiceProxyWrapper::logStreamConfigured(mId, mOperatingMode, true /*internalReconfig*/,
2581 ns2ms(systemTime() - startTime));
2582
Emilian Peev3bead5f2020-05-28 17:29:08 -07002583 if (markClientActive) {
2584 mStatusTracker->markComponentActive(clientStatusId);
2585 }
2586
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002587 return ret;
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002588}
2589
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002590status_t Camera3Device::configureStreamsLocked(int operatingMode,
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002591 const CameraMetadata& sessionParams, bool notifyRequestThread) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002592 ATRACE_CALL();
2593 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002594
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002595 if (mStatus != STATUS_UNCONFIGURED && mStatus != STATUS_CONFIGURED) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002596 CLOGE("Not idle");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002597 return INVALID_OPERATION;
2598 }
2599
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08002600 if (operatingMode < 0) {
2601 CLOGE("Invalid operating mode: %d", operatingMode);
2602 return BAD_VALUE;
2603 }
2604
2605 bool isConstrainedHighSpeed =
2606 static_cast<int>(StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE) ==
2607 operatingMode;
2608
2609 if (mOperatingMode != operatingMode) {
2610 mNeedConfig = true;
2611 mIsConstrainedHighSpeedConfiguration = isConstrainedHighSpeed;
2612 mOperatingMode = operatingMode;
2613 }
2614
Shuzhen Wang0cf01cb2019-09-05 13:33:06 -07002615 // In case called from configureStreams, abort queued input buffers not belonging to
2616 // any pending requests.
2617 if (mInputStream != NULL && notifyRequestThread) {
2618 while (true) {
Emilian Peevf4816702020-04-03 15:44:51 -07002619 camera_stream_buffer_t inputBuffer;
Shuzhen Wang83bff122020-11-20 15:51:39 -08002620 camera3::Size inputBufferSize;
Shuzhen Wang0cf01cb2019-09-05 13:33:06 -07002621 status_t res = mInputStream->getInputBuffer(&inputBuffer,
Shuzhen Wang83bff122020-11-20 15:51:39 -08002622 &inputBufferSize, /*respectHalLimit*/ false);
Shuzhen Wang0cf01cb2019-09-05 13:33:06 -07002623 if (res != OK) {
2624 // Exhausted acquiring all input buffers.
2625 break;
2626 }
2627
Emilian Peevf4816702020-04-03 15:44:51 -07002628 inputBuffer.status = CAMERA_BUFFER_STATUS_ERROR;
Shuzhen Wang0cf01cb2019-09-05 13:33:06 -07002629 res = mInputStream->returnInputBuffer(inputBuffer);
2630 if (res != OK) {
2631 ALOGE("%s: %d: couldn't return input buffer while clearing input queue: "
2632 "%s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
2633 }
2634 }
2635 }
2636
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002637 if (!mNeedConfig) {
2638 ALOGV("%s: Skipping config, no stream changes", __FUNCTION__);
2639 return OK;
2640 }
2641
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002642 // Workaround for device HALv3.2 or older spec bug - zero streams requires
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002643 // adding a fake stream instead.
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002644 // TODO: Bug: 17321404 for fixing the HAL spec and removing this workaround.
2645 if (mOutputStreams.size() == 0) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002646 addFakeStreamLocked();
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002647 } else {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002648 tryRemoveFakeStreamLocked();
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002649 }
2650
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002651 // Start configuring the streams
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002652 ALOGV("%s: Camera %s: Starting stream configuration", __FUNCTION__, mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002653
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002654 mPreparerThread->pause();
2655
Emilian Peevf4816702020-04-03 15:44:51 -07002656 camera_stream_configuration config;
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -08002657 config.operation_mode = mOperatingMode;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002658 config.num_streams = (mInputStream != NULL) + mOutputStreams.size();
Shuzhen Wang83bff122020-11-20 15:51:39 -08002659 config.input_is_multi_resolution = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002660
Emilian Peevf4816702020-04-03 15:44:51 -07002661 Vector<camera3::camera_stream_t*> streams;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002662 streams.setCapacity(config.num_streams);
Emilian Peev192ee832018-01-31 14:46:47 +00002663 std::vector<uint32_t> bufferSizes(config.num_streams, 0);
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002664
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002665
2666 if (mInputStream != NULL) {
Emilian Peevf4816702020-04-03 15:44:51 -07002667 camera3::camera_stream_t *inputStream;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002668 inputStream = mInputStream->startConfiguration();
2669 if (inputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002670 CLOGE("Can't start input stream configuration");
2671 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002672 return INVALID_OPERATION;
2673 }
2674 streams.add(inputStream);
Shuzhen Wang83bff122020-11-20 15:51:39 -08002675
2676 config.input_is_multi_resolution = mIsInputStreamMultiResolution;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002677 }
2678
Shuzhen Wang99080502021-03-07 21:08:20 -08002679 mGroupIdPhysicalCameraMap.clear();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002680 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Igor Murashkin2fba5842013-04-22 14:03:54 -07002681
2682 // Don't configure bidi streams twice, nor add them twice to the list
2683 if (mOutputStreams[i].get() ==
2684 static_cast<Camera3StreamInterface*>(mInputStream.get())) {
2685
2686 config.num_streams--;
2687 continue;
2688 }
2689
Emilian Peevf4816702020-04-03 15:44:51 -07002690 camera3::camera_stream_t *outputStream;
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002691 outputStream = mOutputStreams[i]->startConfiguration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002692 if (outputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002693 CLOGE("Can't start output stream configuration");
2694 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002695 return INVALID_OPERATION;
2696 }
2697 streams.add(outputStream);
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002698
Shuzhen Wangb7ab1e42019-02-20 15:42:23 -08002699 if (outputStream->format == HAL_PIXEL_FORMAT_BLOB) {
Emilian Peev192ee832018-01-31 14:46:47 +00002700 size_t k = i + ((mInputStream != nullptr) ? 1 : 0); // Input stream if present should
2701 // always occupy the initial entry.
Shuzhen Wangb7ab1e42019-02-20 15:42:23 -08002702 if (outputStream->data_space == HAL_DATASPACE_V0_JFIF) {
2703 bufferSizes[k] = static_cast<uint32_t>(
2704 getJpegBufferSize(outputStream->width, outputStream->height));
2705 } else if (outputStream->data_space ==
2706 static_cast<android_dataspace>(HAL_DATASPACE_JPEG_APP_SEGMENTS)) {
2707 bufferSizes[k] = outputStream->width * outputStream->height;
2708 } else {
2709 ALOGW("%s: Blob dataSpace %d not supported",
2710 __FUNCTION__, outputStream->data_space);
2711 }
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002712 }
Shuzhen Wang99080502021-03-07 21:08:20 -08002713
2714 if (mOutputStreams[i]->isMultiResolution()) {
2715 int32_t streamGroupId = mOutputStreams[i]->getHalStreamGroupId();
2716 const String8& physicalCameraId = mOutputStreams[i]->getPhysicalCameraId();
2717 mGroupIdPhysicalCameraMap[streamGroupId].insert(physicalCameraId);
2718 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002719 }
2720
2721 config.streams = streams.editArray();
2722
2723 // Do the HAL configuration; will potentially touch stream
Shuzhen Wang92653952019-05-07 15:11:43 -07002724 // max_buffers, usage, and priv fields, as well as data_space and format
2725 // fields for IMPLEMENTATION_DEFINED formats.
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002726
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002727 const camera_metadata_t *sessionBuffer = sessionParams.getAndLock();
Emilian Peev192ee832018-01-31 14:46:47 +00002728 res = mInterface->configureStreams(sessionBuffer, &config, bufferSizes);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002729 sessionParams.unlock(sessionBuffer);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002730
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002731 if (res == BAD_VALUE) {
2732 // HAL rejected this set of streams as unsupported, clean up config
2733 // attempt and return to unconfigured state
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002734 CLOGE("Set of requested inputs/outputs not supported by HAL");
2735 cancelStreamsConfigurationLocked();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002736 return BAD_VALUE;
2737 } else if (res != OK) {
2738 // Some other kind of error from configure_streams - this is not
2739 // expected
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002740 SET_ERR_L("Unable to configure streams with HAL: %s (%d)",
2741 strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002742 return res;
2743 }
2744
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002745 // Finish all stream configuration immediately.
2746 // TODO: Try to relax this later back to lazy completion, which should be
2747 // faster
2748
Igor Murashkin073f8572013-05-02 14:59:28 -07002749 if (mInputStream != NULL && mInputStream->isConfiguring()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002750 bool streamReConfigured = false;
2751 res = mInputStream->finishConfiguration(&streamReConfigured);
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002752 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002753 CLOGE("Can't finish configuring input stream %d: %s (%d)",
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002754 mInputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002755 cancelStreamsConfigurationLocked();
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002756 if ((res == NO_INIT || res == DEAD_OBJECT) && mInputStream->isAbandoned()) {
2757 return DEAD_OBJECT;
2758 }
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002759 return BAD_VALUE;
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002760 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002761 if (streamReConfigured) {
2762 mInterface->onStreamReConfigured(mInputStream->getId());
2763 }
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002764 }
2765
2766 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002767 sp<Camera3OutputStreamInterface> outputStream = mOutputStreams[i];
Zhijun He5d677d12016-05-29 16:52:39 -07002768 if (outputStream->isConfiguring() && !outputStream->isConsumerConfigurationDeferred()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002769 bool streamReConfigured = false;
2770 res = outputStream->finishConfiguration(&streamReConfigured);
Igor Murashkin073f8572013-05-02 14:59:28 -07002771 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002772 CLOGE("Can't finish configuring output stream %d: %s (%d)",
Igor Murashkin073f8572013-05-02 14:59:28 -07002773 outputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002774 cancelStreamsConfigurationLocked();
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002775 if ((res == NO_INIT || res == DEAD_OBJECT) && outputStream->isAbandoned()) {
2776 return DEAD_OBJECT;
2777 }
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002778 return BAD_VALUE;
Igor Murashkin073f8572013-05-02 14:59:28 -07002779 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002780 if (streamReConfigured) {
2781 mInterface->onStreamReConfigured(outputStream->getId());
2782 }
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002783 }
2784 }
2785
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002786 // Request thread needs to know to avoid using repeat-last-settings protocol
2787 // across configure_streams() calls
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002788 if (notifyRequestThread) {
Shuzhen Wang99080502021-03-07 21:08:20 -08002789 mRequestThread->configurationComplete(mIsConstrainedHighSpeedConfiguration,
2790 sessionParams, mGroupIdPhysicalCameraMap);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002791 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002792
Zhijun He90f7c372016-08-16 16:19:43 -07002793 char value[PROPERTY_VALUE_MAX];
2794 property_get("camera.fifo.disable", value, "0");
2795 int32_t disableFifo = atoi(value);
2796 if (disableFifo != 1) {
2797 // Boost priority of request thread to SCHED_FIFO.
2798 pid_t requestThreadTid = mRequestThread->getTid();
2799 res = requestPriority(getpid(), requestThreadTid,
Mikhail Naganov83f04272017-02-07 10:45:09 -08002800 kRequestThreadPriority, /*isForApp*/ false, /*asynchronous*/ false);
Zhijun He90f7c372016-08-16 16:19:43 -07002801 if (res != OK) {
2802 ALOGW("Can't set realtime priority for request processing thread: %s (%d)",
2803 strerror(-res), res);
2804 } else {
2805 ALOGD("Set real time priority for request queue thread (tid %d)", requestThreadTid);
2806 }
Eino-Ville Talvalaf99498e2015-09-25 16:52:55 -07002807 }
2808
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002809 // Update device state
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002810 const camera_metadata_t *newSessionParams = sessionParams.getAndLock();
2811 const camera_metadata_t *currentSessionParams = mSessionParams.getAndLock();
2812 bool updateSessionParams = (newSessionParams != currentSessionParams) ? true : false;
2813 sessionParams.unlock(newSessionParams);
2814 mSessionParams.unlock(currentSessionParams);
2815 if (updateSessionParams) {
2816 mSessionParams = sessionParams;
2817 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002818
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002819 mNeedConfig = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002820
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002821 internalUpdateStatusLocked((mFakeStreamId == NO_STREAM) ?
Ruben Brunk183f0562015-08-12 12:55:02 -07002822 STATUS_CONFIGURED : STATUS_UNCONFIGURED);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002823
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002824 ALOGV("%s: Camera %s: Stream configuration complete", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002825
Zhijun He0a210512014-07-24 13:45:15 -07002826 // tear down the deleted streams after configure streams.
2827 mDeletedStreams.clear();
2828
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002829 auto rc = mPreparerThread->resume();
2830 if (rc != OK) {
2831 SET_ERR_L("%s: Camera %s: Preparer thread failed to resume!", __FUNCTION__, mId.string());
2832 return rc;
2833 }
2834
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002835 if (mFakeStreamId == NO_STREAM) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07002836 mRequestBufferSM.onStreamsConfigured();
2837 }
2838
Cliff Wu3b268182021-07-06 15:44:43 +08002839 // First call injectCamera() and then run configureStreamsLocked() case:
Cliff Wuc2ad9c82021-04-21 00:58:58 +08002840 // Since the streams configuration of the injection camera is based on the internal camera, we
Cliff Wu3b268182021-07-06 15:44:43 +08002841 // must wait until the internal camera configure streams before running the injection job to
Cliff Wuc2ad9c82021-04-21 00:58:58 +08002842 // configure the injection streams.
2843 if (mInjectionMethods->isInjecting()) {
Cliff Wu3b268182021-07-06 15:44:43 +08002844 ALOGD("%s: Injection camera %s: Start to configure streams.",
Cliff Wuc2ad9c82021-04-21 00:58:58 +08002845 __FUNCTION__, mInjectionMethods->getInjectedCamId().string());
2846 res = mInjectionMethods->injectCamera(config, bufferSizes);
2847 if (res != OK) {
2848 ALOGE("Can't finish inject camera process!");
2849 return res;
2850 }
Cliff Wu3b268182021-07-06 15:44:43 +08002851 } else {
2852 // First run configureStreamsLocked() and then call injectCamera() case:
2853 // If the stream configuration has been completed and camera deive is active, but the
2854 // injection camera has not been injected yet, we need to store the stream configuration of
2855 // the internal camera (because the stream configuration of the injection camera is based
2856 // on the internal camera). When injecting occurs later, this configuration can be used by
2857 // the injection camera.
2858 ALOGV("%s: The stream configuration is complete and the camera device is active, but the"
2859 " injection camera has not been injected yet.", __FUNCTION__);
2860 mInjectionMethods->storeInjectionConfig(config, bufferSizes);
Cliff Wuc2ad9c82021-04-21 00:58:58 +08002861 }
2862
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002863 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002864}
2865
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002866status_t Camera3Device::addFakeStreamLocked() {
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002867 ATRACE_CALL();
2868 status_t res;
2869
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002870 if (mFakeStreamId != NO_STREAM) {
2871 // Should never be adding a second fake stream when one is already
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002872 // active
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002873 SET_ERR_L("%s: Camera %s: A fake stream already exists!",
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002874 __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002875 return INVALID_OPERATION;
2876 }
2877
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002878 ALOGV("%s: Camera %s: Adding a fake stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002879
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002880 sp<Camera3OutputStreamInterface> fakeStream =
2881 new Camera3FakeStream(mNextStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002882
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002883 res = mOutputStreams.add(mNextStreamId, fakeStream);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002884 if (res < 0) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002885 SET_ERR_L("Can't add fake stream to set: %s (%d)", strerror(-res), res);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002886 return res;
2887 }
2888
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002889 mFakeStreamId = mNextStreamId;
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002890 mNextStreamId++;
2891
2892 return OK;
2893}
2894
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002895status_t Camera3Device::tryRemoveFakeStreamLocked() {
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002896 ATRACE_CALL();
2897 status_t res;
2898
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002899 if (mFakeStreamId == NO_STREAM) return OK;
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002900 if (mOutputStreams.size() == 1) return OK;
2901
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002902 ALOGV("%s: Camera %s: Removing the fake stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002903
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002904 // Ok, have a fake stream and there's at least one other output stream,
2905 // so remove the fake
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002906
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002907 sp<Camera3StreamInterface> deletedStream = mOutputStreams.get(mFakeStreamId);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002908 if (deletedStream == nullptr) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002909 SET_ERR_L("Fake stream %d does not appear to exist", mFakeStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002910 return INVALID_OPERATION;
2911 }
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002912 mOutputStreams.remove(mFakeStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002913
2914 // Free up the stream endpoint so that it can be used by some other stream
2915 res = deletedStream->disconnect();
2916 if (res != OK) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002917 SET_ERR_L("Can't disconnect deleted fake stream %d", mFakeStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002918 // fall through since we want to still list the stream as deleted.
2919 }
2920 mDeletedStreams.add(deletedStream);
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002921 mFakeStreamId = NO_STREAM;
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002922
2923 return res;
2924}
2925
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002926void Camera3Device::setErrorState(const char *fmt, ...) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002927 ATRACE_CALL();
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002928 Mutex::Autolock l(mLock);
2929 va_list args;
2930 va_start(args, fmt);
2931
2932 setErrorStateLockedV(fmt, args);
2933
2934 va_end(args);
2935}
2936
2937void Camera3Device::setErrorStateV(const char *fmt, va_list args) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002938 ATRACE_CALL();
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002939 Mutex::Autolock l(mLock);
2940 setErrorStateLockedV(fmt, args);
2941}
2942
2943void Camera3Device::setErrorStateLocked(const char *fmt, ...) {
2944 va_list args;
2945 va_start(args, fmt);
2946
2947 setErrorStateLockedV(fmt, args);
2948
2949 va_end(args);
2950}
2951
2952void Camera3Device::setErrorStateLockedV(const char *fmt, va_list args) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002953 // Print out all error messages to log
2954 String8 errorCause = String8::formatV(fmt, args);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002955 ALOGE("Camera %s: %s", mId.string(), errorCause.string());
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002956
2957 // But only do error state transition steps for the first error
Zhijun Heb05eeae2013-06-06 13:51:22 -07002958 if (mStatus == STATUS_ERROR || mStatus == STATUS_UNINITIALIZED) return;
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002959
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002960 mErrorCause = errorCause;
2961
Yin-Chia Yeh3d145ae2017-07-27 12:47:03 -07002962 if (mRequestThread != nullptr) {
2963 mRequestThread->setPaused(true);
2964 }
Ruben Brunk183f0562015-08-12 12:55:02 -07002965 internalUpdateStatusLocked(STATUS_ERROR);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002966
2967 // Notify upstream about a device error
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002968 sp<NotificationListener> listener = mListener.promote();
2969 if (listener != NULL) {
2970 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002971 CaptureResultExtras());
Shuzhen Wang316781a2020-08-18 18:11:01 -07002972 mSessionStatsBuilder.onDeviceError();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002973 }
2974
2975 // Save stack trace. View by dumping it later.
2976 CameraTraces::saveTrace();
2977 // TODO: consider adding errorCause and client pid/procname
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002978}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002979
2980/**
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002981 * In-flight request management
2982 */
2983
Jianing Weicb0652e2014-03-12 18:29:36 -07002984status_t Camera3Device::registerInFlight(uint32_t frameNumber,
Chien-Yu Chend196d612015-06-22 19:49:01 -07002985 int32_t numBuffers, CaptureResultExtras resultExtras, bool hasInput,
Shuzhen Wang5c22c152017-12-31 17:12:25 -08002986 bool hasAppCallback, nsecs_t maxExpectedDuration,
Shuzhen Wang99080502021-03-07 21:08:20 -08002987 const std::set<std::set<String8>>& physicalCameraIds,
2988 bool isStillCapture, bool isZslCapture, bool rotateAndCropAuto,
2989 const std::set<std::string>& cameraIdsWithZoom,
Shuzhen Wang316781a2020-08-18 18:11:01 -07002990 const SurfaceMap& outputSurfaces, nsecs_t requestTimeNs) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002991 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002992 std::lock_guard<std::mutex> l(mInFlightLock);
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002993
2994 ssize_t res;
Chien-Yu Chend196d612015-06-22 19:49:01 -07002995 res = mInFlightMap.add(frameNumber, InFlightRequest(numBuffers, resultExtras, hasInput,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07002996 hasAppCallback, maxExpectedDuration, physicalCameraIds, isStillCapture, isZslCapture,
Shuzhen Wang316781a2020-08-18 18:11:01 -07002997 rotateAndCropAuto, cameraIdsWithZoom, requestTimeNs, outputSurfaces));
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002998 if (res < 0) return res;
2999
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07003000 if (mInFlightMap.size() == 1) {
Emilian Peev26d975d2018-07-05 14:52:57 +01003001 // Hold a separate dedicated tracker lock to prevent race with disconnect and also
3002 // avoid a deadlock during reprocess requests.
3003 Mutex::Autolock l(mTrackerLock);
Yin-Chia Yeh38dfde52017-06-27 17:13:33 -07003004 if (mStatusTracker != nullptr) {
3005 mStatusTracker->markComponentActive(mInFlightStatusId);
3006 }
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07003007 }
3008
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003009 mExpectedInflightDuration += maxExpectedDuration;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003010 return OK;
3011}
3012
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003013void Camera3Device::onInflightEntryRemovedLocked(nsecs_t duration) {
Shuzhen Wangcadb3302016-11-04 14:17:56 -07003014 // Indicate idle inFlightMap to the status tracker
3015 if (mInFlightMap.size() == 0) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07003016 mRequestBufferSM.onInflightMapEmpty();
Emilian Peev26d975d2018-07-05 14:52:57 +01003017 // Hold a separate dedicated tracker lock to prevent race with disconnect and also
3018 // avoid a deadlock during reprocess requests.
3019 Mutex::Autolock l(mTrackerLock);
Yin-Chia Yeh38dfde52017-06-27 17:13:33 -07003020 if (mStatusTracker != nullptr) {
3021 mStatusTracker->markComponentIdle(mInFlightStatusId, Fence::NO_FENCE);
3022 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07003023 }
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003024 mExpectedInflightDuration -= duration;
Shuzhen Wangcadb3302016-11-04 14:17:56 -07003025}
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003026
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003027void Camera3Device::checkInflightMapLengthLocked() {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04003028 // Validation check - if we have too many in-flight frames with long total inflight duration,
Yin-Chia Yeh99fd0972019-06-27 14:22:44 -07003029 // something has likely gone wrong. This might still be legit only if application send in
3030 // a long burst of long exposure requests.
3031 if (mExpectedInflightDuration > kMinWarnInflightDuration) {
3032 if (!mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() > kInFlightWarnLimit) {
3033 CLOGW("In-flight list too large: %zu, total inflight duration %" PRIu64,
3034 mInFlightMap.size(), mExpectedInflightDuration);
3035 } else if (mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() >
3036 kInFlightWarnLimitHighSpeed) {
3037 CLOGW("In-flight list too large for high speed configuration: %zu,"
3038 "total inflight duration %" PRIu64,
3039 mInFlightMap.size(), mExpectedInflightDuration);
3040 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003041 }
3042}
3043
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003044void Camera3Device::onInflightMapFlushedLocked() {
3045 mExpectedInflightDuration = 0;
3046}
3047
3048void Camera3Device::removeInFlightMapEntryLocked(int idx) {
Jayant Chowdharyd4776262020-06-23 23:45:57 -07003049 ATRACE_HFR_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003050 nsecs_t duration = mInFlightMap.valueAt(idx).maxExpectedDuration;
3051 mInFlightMap.removeItemsAt(idx, 1);
3052
3053 onInflightEntryRemovedLocked(duration);
3054}
3055
3056
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003057void Camera3Device::flushInflightRequests() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003058 ATRACE_CALL();
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003059 sp<NotificationListener> listener;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003060 {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003061 std::lock_guard<std::mutex> l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003062 listener = mListener.promote();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003063 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003064
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003065 FlushInflightReqStates states {
3066 mId, mInFlightLock, mInFlightMap, mUseHalBufManager,
Shuzhen Wang316781a2020-08-18 18:11:01 -07003067 listener, *this, *mInterface, *this, mSessionStatsBuilder};
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003068
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003069 camera3::flushInflightRequests(states);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003070}
3071
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003072CameraMetadata Camera3Device::getLatestRequestLocked() {
Igor Murashkin1e479c02013-09-06 16:55:14 -07003073 ALOGV("%s", __FUNCTION__);
3074
Igor Murashkin1e479c02013-09-06 16:55:14 -07003075 CameraMetadata retVal;
3076
3077 if (mRequestThread != NULL) {
3078 retVal = mRequestThread->getLatestRequest();
3079 }
3080
Igor Murashkin1e479c02013-09-06 16:55:14 -07003081 return retVal;
3082}
3083
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07003084void Camera3Device::monitorMetadata(TagMonitor::eventSource source,
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003085 int64_t frameNumber, nsecs_t timestamp, const CameraMetadata& metadata,
Jayant Chowdharycd277cd2021-08-11 15:48:40 -07003086 const std::unordered_map<std::string, CameraMetadata>& physicalMetadata,
3087 const std::set<int32_t> &outputStreamIds, int32_t inputStreamId) {
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003088
3089 mTagMonitor.monitorMetadata(source, frameNumber, timestamp, metadata,
Jayant Chowdharycd277cd2021-08-11 15:48:40 -07003090 physicalMetadata, outputStreamIds, inputStreamId);
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07003091}
3092
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003093/**
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003094 * HalInterface inner class methods
3095 */
3096
Yifan Hongf79b5542017-04-11 14:44:25 -07003097Camera3Device::HalInterface::HalInterface(
3098 sp<ICameraDeviceSession> &session,
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003099 std::shared_ptr<RequestMetadataQueue> queue,
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003100 bool useHalBufManager, bool supportOfflineProcessing) :
Yifan Hongf79b5542017-04-11 14:44:25 -07003101 mHidlSession(session),
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003102 mRequestMetadataQueue(queue),
Emilian Peev4ec17882019-01-24 17:16:58 -08003103 mUseHalBufManager(useHalBufManager),
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003104 mIsReconfigurationQuerySupported(true),
3105 mSupportOfflineProcessing(supportOfflineProcessing) {
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003106 // Check with hardware service manager if we can downcast these interfaces
3107 // Somewhat expensive, so cache the results at startup
Shuzhen Wang83bff122020-11-20 15:51:39 -08003108 auto castResult_3_7 = device::V3_7::ICameraDeviceSession::castFrom(mHidlSession);
3109 if (castResult_3_7.isOk()) {
3110 mHidlSession_3_7 = castResult_3_7;
3111 }
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003112 auto castResult_3_6 = device::V3_6::ICameraDeviceSession::castFrom(mHidlSession);
3113 if (castResult_3_6.isOk()) {
3114 mHidlSession_3_6 = castResult_3_6;
3115 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003116 auto castResult_3_5 = device::V3_5::ICameraDeviceSession::castFrom(mHidlSession);
3117 if (castResult_3_5.isOk()) {
3118 mHidlSession_3_5 = castResult_3_5;
3119 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003120 auto castResult_3_4 = device::V3_4::ICameraDeviceSession::castFrom(mHidlSession);
3121 if (castResult_3_4.isOk()) {
3122 mHidlSession_3_4 = castResult_3_4;
3123 }
3124 auto castResult_3_3 = device::V3_3::ICameraDeviceSession::castFrom(mHidlSession);
3125 if (castResult_3_3.isOk()) {
3126 mHidlSession_3_3 = castResult_3_3;
3127 }
3128}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003129
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003130Camera3Device::HalInterface::HalInterface() :
3131 mUseHalBufManager(false),
3132 mSupportOfflineProcessing(false) {}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003133
3134Camera3Device::HalInterface::HalInterface(const HalInterface& other) :
Yifan Hongf79b5542017-04-11 14:44:25 -07003135 mHidlSession(other.mHidlSession),
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003136 mRequestMetadataQueue(other.mRequestMetadataQueue),
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003137 mUseHalBufManager(other.mUseHalBufManager),
3138 mSupportOfflineProcessing(other.mSupportOfflineProcessing) {}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003139
3140bool Camera3Device::HalInterface::valid() {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003141 return (mHidlSession != nullptr);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003142}
3143
3144void Camera3Device::HalInterface::clear() {
Shuzhen Wang83bff122020-11-20 15:51:39 -08003145 mHidlSession_3_7.clear();
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003146 mHidlSession_3_6.clear();
Emilian Peev644a3e12018-11-23 13:52:39 +00003147 mHidlSession_3_5.clear();
Emilian Peev9e740b02018-01-30 18:28:03 +00003148 mHidlSession_3_4.clear();
3149 mHidlSession_3_3.clear();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003150 mHidlSession.clear();
3151}
3152
3153status_t Camera3Device::HalInterface::constructDefaultRequestSettings(
Emilian Peevf4816702020-04-03 15:44:51 -07003154 camera_request_template_t templateId,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003155 /*out*/ camera_metadata_t **requestTemplate) {
3156 ATRACE_NAME("CameraHal::constructDefaultRequestSettings");
3157 if (!valid()) return INVALID_OPERATION;
3158 status_t res = OK;
3159
Emilian Peev31abd0a2017-05-11 18:37:46 +01003160 common::V1_0::Status status;
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003161
3162 auto requestCallback = [&status, &requestTemplate]
Emilian Peev31abd0a2017-05-11 18:37:46 +01003163 (common::V1_0::Status s, const device::V3_2::CameraMetadata& request) {
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003164 status = s;
3165 if (status == common::V1_0::Status::OK) {
3166 const camera_metadata *r =
3167 reinterpret_cast<const camera_metadata_t*>(request.data());
3168 size_t expectedSize = request.size();
3169 int ret = validate_camera_metadata_structure(r, &expectedSize);
3170 if (ret == OK || ret == CAMERA_METADATA_VALIDATION_SHIFTED) {
3171 *requestTemplate = clone_camera_metadata(r);
3172 if (*requestTemplate == nullptr) {
3173 ALOGE("%s: Unable to clone camera metadata received from HAL",
3174 __FUNCTION__);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003175 status = common::V1_0::Status::INTERNAL_ERROR;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003176 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003177 } else {
3178 ALOGE("%s: Malformed camera metadata received from HAL", __FUNCTION__);
3179 status = common::V1_0::Status::INTERNAL_ERROR;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003180 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003181 }
3182 };
3183 hardware::Return<void> err;
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003184 RequestTemplate id;
3185 switch (templateId) {
Emilian Peevf4816702020-04-03 15:44:51 -07003186 case CAMERA_TEMPLATE_PREVIEW:
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003187 id = RequestTemplate::PREVIEW;
3188 break;
Emilian Peevf4816702020-04-03 15:44:51 -07003189 case CAMERA_TEMPLATE_STILL_CAPTURE:
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003190 id = RequestTemplate::STILL_CAPTURE;
3191 break;
Emilian Peevf4816702020-04-03 15:44:51 -07003192 case CAMERA_TEMPLATE_VIDEO_RECORD:
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003193 id = RequestTemplate::VIDEO_RECORD;
3194 break;
Emilian Peevf4816702020-04-03 15:44:51 -07003195 case CAMERA_TEMPLATE_VIDEO_SNAPSHOT:
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003196 id = RequestTemplate::VIDEO_SNAPSHOT;
3197 break;
Emilian Peevf4816702020-04-03 15:44:51 -07003198 case CAMERA_TEMPLATE_ZERO_SHUTTER_LAG:
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003199 id = RequestTemplate::ZERO_SHUTTER_LAG;
3200 break;
Emilian Peevf4816702020-04-03 15:44:51 -07003201 case CAMERA_TEMPLATE_MANUAL:
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003202 id = RequestTemplate::MANUAL;
3203 break;
3204 default:
3205 // Unknown template ID, or this HAL is too old to support it
3206 return BAD_VALUE;
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003207 }
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003208 err = mHidlSession->constructDefaultRequestSettings(id, requestCallback);
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003209
Emilian Peev31abd0a2017-05-11 18:37:46 +01003210 if (!err.isOk()) {
3211 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3212 res = DEAD_OBJECT;
3213 } else {
3214 res = CameraProviderManager::mapToStatusT(status);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003215 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003216
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003217 return res;
3218}
3219
Emilian Peev4ec17882019-01-24 17:16:58 -08003220bool Camera3Device::HalInterface::isReconfigurationRequired(CameraMetadata& oldSessionParams,
3221 CameraMetadata& newSessionParams) {
3222 // We do reconfiguration by default;
3223 bool ret = true;
3224 if ((mHidlSession_3_5 != nullptr) && mIsReconfigurationQuerySupported) {
3225 android::hardware::hidl_vec<uint8_t> oldParams, newParams;
3226 camera_metadata_t* oldSessioMeta = const_cast<camera_metadata_t*>(
3227 oldSessionParams.getAndLock());
3228 camera_metadata_t* newSessioMeta = const_cast<camera_metadata_t*>(
3229 newSessionParams.getAndLock());
3230 oldParams.setToExternal(reinterpret_cast<uint8_t*>(oldSessioMeta),
3231 get_camera_metadata_size(oldSessioMeta));
3232 newParams.setToExternal(reinterpret_cast<uint8_t*>(newSessioMeta),
3233 get_camera_metadata_size(newSessioMeta));
3234 hardware::camera::common::V1_0::Status callStatus;
3235 bool required;
3236 auto hidlCb = [&callStatus, &required] (hardware::camera::common::V1_0::Status s,
3237 bool requiredFlag) {
3238 callStatus = s;
3239 required = requiredFlag;
3240 };
3241 auto err = mHidlSession_3_5->isReconfigurationRequired(oldParams, newParams, hidlCb);
3242 oldSessionParams.unlock(oldSessioMeta);
3243 newSessionParams.unlock(newSessioMeta);
3244 if (err.isOk()) {
3245 switch (callStatus) {
3246 case hardware::camera::common::V1_0::Status::OK:
3247 ret = required;
3248 break;
3249 case hardware::camera::common::V1_0::Status::METHOD_NOT_SUPPORTED:
3250 mIsReconfigurationQuerySupported = false;
3251 ret = true;
3252 break;
3253 default:
3254 ALOGV("%s: Reconfiguration query failed: %d", __FUNCTION__, callStatus);
3255 ret = true;
3256 }
3257 } else {
3258 ALOGE("%s: Unexpected binder error: %s", __FUNCTION__, err.description().c_str());
3259 ret = true;
3260 }
3261 }
3262
3263 return ret;
3264}
3265
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003266status_t Camera3Device::HalInterface::configureStreams(const camera_metadata_t *sessionParams,
Emilian Peevf4816702020-04-03 15:44:51 -07003267 camera_stream_configuration *config, const std::vector<uint32_t>& bufferSizes) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003268 ATRACE_NAME("CameraHal::configureStreams");
3269 if (!valid()) return INVALID_OPERATION;
3270 status_t res = OK;
3271
Shuzhen Wang83bff122020-11-20 15:51:39 -08003272 if (config->input_is_multi_resolution && mHidlSession_3_7 == nullptr) {
3273 ALOGE("%s: Camera device doesn't support multi-resolution input stream", __FUNCTION__);
3274 return BAD_VALUE;
3275 }
3276
Emilian Peev31abd0a2017-05-11 18:37:46 +01003277 // Convert stream config to HIDL
3278 std::set<int> activeStreams;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003279 device::V3_2::StreamConfiguration requestedConfiguration3_2;
3280 device::V3_4::StreamConfiguration requestedConfiguration3_4;
Shuzhen Wang83bff122020-11-20 15:51:39 -08003281 device::V3_7::StreamConfiguration requestedConfiguration3_7;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003282 requestedConfiguration3_2.streams.resize(config->num_streams);
3283 requestedConfiguration3_4.streams.resize(config->num_streams);
Shuzhen Wang83bff122020-11-20 15:51:39 -08003284 requestedConfiguration3_7.streams.resize(config->num_streams);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003285 for (size_t i = 0; i < config->num_streams; i++) {
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003286 device::V3_2::Stream &dst3_2 = requestedConfiguration3_2.streams[i];
3287 device::V3_4::Stream &dst3_4 = requestedConfiguration3_4.streams[i];
Shuzhen Wang83bff122020-11-20 15:51:39 -08003288 device::V3_7::Stream &dst3_7 = requestedConfiguration3_7.streams[i];
Emilian Peevf4816702020-04-03 15:44:51 -07003289 camera3::camera_stream_t *src = config->streams[i];
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003290
Emilian Peev31abd0a2017-05-11 18:37:46 +01003291 Camera3Stream* cam3stream = Camera3Stream::cast(src);
3292 cam3stream->setBufferFreedListener(this);
3293 int streamId = cam3stream->getId();
3294 StreamType streamType;
3295 switch (src->stream_type) {
Emilian Peevf4816702020-04-03 15:44:51 -07003296 case CAMERA_STREAM_OUTPUT:
Emilian Peev31abd0a2017-05-11 18:37:46 +01003297 streamType = StreamType::OUTPUT;
3298 break;
Emilian Peevf4816702020-04-03 15:44:51 -07003299 case CAMERA_STREAM_INPUT:
Emilian Peev31abd0a2017-05-11 18:37:46 +01003300 streamType = StreamType::INPUT;
3301 break;
3302 default:
3303 ALOGE("%s: Stream %d: Unsupported stream type %d",
3304 __FUNCTION__, streamId, config->streams[i]->stream_type);
3305 return BAD_VALUE;
3306 }
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003307 dst3_2.id = streamId;
3308 dst3_2.streamType = streamType;
3309 dst3_2.width = src->width;
3310 dst3_2.height = src->height;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003311 dst3_2.usage = mapToConsumerUsage(cam3stream->getUsage());
Emilian Peevf4816702020-04-03 15:44:51 -07003312 dst3_2.rotation = mapToStreamRotation((camera_stream_rotation_t) src->rotation);
Shuzhen Wang92653952019-05-07 15:11:43 -07003313 // For HidlSession version 3.5 or newer, the format and dataSpace sent
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08003314 // to HAL are original, not the overridden ones.
Shuzhen Wang92653952019-05-07 15:11:43 -07003315 if (mHidlSession_3_5 != nullptr) {
3316 dst3_2.format = mapToPixelFormat(cam3stream->isFormatOverridden() ?
3317 cam3stream->getOriginalFormat() : src->format);
3318 dst3_2.dataSpace = mapToHidlDataspace(cam3stream->isDataSpaceOverridden() ?
3319 cam3stream->getOriginalDataSpace() : src->data_space);
3320 } else {
3321 dst3_2.format = mapToPixelFormat(src->format);
3322 dst3_2.dataSpace = mapToHidlDataspace(src->data_space);
3323 }
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003324 dst3_4.v3_2 = dst3_2;
Emilian Peev192ee832018-01-31 14:46:47 +00003325 dst3_4.bufferSize = bufferSizes[i];
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003326 if (src->physical_camera_id != nullptr) {
3327 dst3_4.physicalCameraId = src->physical_camera_id;
3328 }
Shuzhen Wang83bff122020-11-20 15:51:39 -08003329 dst3_7.v3_4 = dst3_4;
3330 dst3_7.groupId = cam3stream->getHalStreamGroupId();
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08003331 dst3_7.sensorPixelModesUsed.resize(src->sensor_pixel_modes_used.size());
3332 size_t j = 0;
3333 for (int mode : src->sensor_pixel_modes_used) {
3334 dst3_7.sensorPixelModesUsed[j++] =
3335 static_cast<CameraMetadataEnumAndroidSensorPixelMode>(mode);
3336 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003337 activeStreams.insert(streamId);
3338 // Create Buffer ID map if necessary
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003339 mBufferRecords.tryCreateBufferCache(streamId);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003340 }
3341 // remove BufferIdMap for deleted streams
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003342 mBufferRecords.removeInactiveBufferCaches(activeStreams);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003343
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003344 StreamConfigurationMode operationMode;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003345 res = mapToStreamConfigurationMode(
Emilian Peevf4816702020-04-03 15:44:51 -07003346 (camera_stream_configuration_mode_t) config->operation_mode,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003347 /*out*/ &operationMode);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003348 if (res != OK) {
3349 return res;
3350 }
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003351 requestedConfiguration3_2.operationMode = operationMode;
3352 requestedConfiguration3_4.operationMode = operationMode;
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08003353 requestedConfiguration3_7.operationMode = operationMode;
3354 size_t sessionParamSize = get_camera_metadata_size(sessionParams);
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003355 requestedConfiguration3_4.sessionParams.setToExternal(
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003356 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(sessionParams)),
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08003357 sessionParamSize);
Shuzhen Wang83bff122020-11-20 15:51:39 -08003358 requestedConfiguration3_7.operationMode = operationMode;
3359 requestedConfiguration3_7.sessionParams.setToExternal(
3360 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(sessionParams)),
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08003361 sessionParamSize);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003362
Emilian Peev31abd0a2017-05-11 18:37:46 +01003363 // Invoke configureStreams
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003364 device::V3_3::HalStreamConfiguration finalConfiguration;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003365 device::V3_4::HalStreamConfiguration finalConfiguration3_4;
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003366 device::V3_6::HalStreamConfiguration finalConfiguration3_6;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003367 common::V1_0::Status status;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003368
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003369 auto configStream34Cb = [&status, &finalConfiguration3_4]
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003370 (common::V1_0::Status s, const device::V3_4::HalStreamConfiguration& halConfiguration) {
3371 finalConfiguration3_4 = halConfiguration;
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003372 status = s;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003373 };
3374
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003375 auto configStream36Cb = [&status, &finalConfiguration3_6]
3376 (common::V1_0::Status s, const device::V3_6::HalStreamConfiguration& halConfiguration) {
3377 finalConfiguration3_6 = halConfiguration;
3378 status = s;
3379 };
3380
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003381 auto postprocConfigStream34 = [&finalConfiguration, &finalConfiguration3_4]
3382 (hardware::Return<void>& err) -> status_t {
3383 if (!err.isOk()) {
3384 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3385 return DEAD_OBJECT;
3386 }
3387 finalConfiguration.streams.resize(finalConfiguration3_4.streams.size());
3388 for (size_t i = 0; i < finalConfiguration3_4.streams.size(); i++) {
3389 finalConfiguration.streams[i] = finalConfiguration3_4.streams[i].v3_3;
3390 }
3391 return OK;
3392 };
3393
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003394 auto postprocConfigStream36 = [&finalConfiguration, &finalConfiguration3_6]
3395 (hardware::Return<void>& err) -> status_t {
3396 if (!err.isOk()) {
3397 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3398 return DEAD_OBJECT;
3399 }
3400 finalConfiguration.streams.resize(finalConfiguration3_6.streams.size());
3401 for (size_t i = 0; i < finalConfiguration3_6.streams.size(); i++) {
3402 finalConfiguration.streams[i] = finalConfiguration3_6.streams[i].v3_4.v3_3;
3403 }
3404 return OK;
3405 };
3406
Shuzhen Wang92653952019-05-07 15:11:43 -07003407 // See which version of HAL we have
Shuzhen Wang83bff122020-11-20 15:51:39 -08003408 if (mHidlSession_3_7 != nullptr) {
3409 ALOGV("%s: v3.7 device found", __FUNCTION__);
3410 requestedConfiguration3_7.streamConfigCounter = mNextStreamConfigCounter++;
3411 requestedConfiguration3_7.multiResolutionInputImage = config->input_is_multi_resolution;
3412 auto err = mHidlSession_3_7->configureStreams_3_7(
3413 requestedConfiguration3_7, configStream36Cb);
3414 res = postprocConfigStream36(err);
3415 if (res != OK) {
3416 return res;
3417 }
3418 } else if (mHidlSession_3_6 != nullptr) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003419 ALOGV("%s: v3.6 device found", __FUNCTION__);
3420 device::V3_5::StreamConfiguration requestedConfiguration3_5;
3421 requestedConfiguration3_5.v3_4 = requestedConfiguration3_4;
3422 requestedConfiguration3_5.streamConfigCounter = mNextStreamConfigCounter++;
3423 auto err = mHidlSession_3_6->configureStreams_3_6(
3424 requestedConfiguration3_5, configStream36Cb);
3425 res = postprocConfigStream36(err);
3426 if (res != OK) {
3427 return res;
3428 }
3429 } else if (mHidlSession_3_5 != nullptr) {
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003430 ALOGV("%s: v3.5 device found", __FUNCTION__);
3431 device::V3_5::StreamConfiguration requestedConfiguration3_5;
3432 requestedConfiguration3_5.v3_4 = requestedConfiguration3_4;
3433 requestedConfiguration3_5.streamConfigCounter = mNextStreamConfigCounter++;
3434 auto err = mHidlSession_3_5->configureStreams_3_5(
3435 requestedConfiguration3_5, configStream34Cb);
3436 res = postprocConfigStream34(err);
3437 if (res != OK) {
3438 return res;
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003439 }
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003440 } else if (mHidlSession_3_4 != nullptr) {
3441 // We do; use v3.4 for the call
3442 ALOGV("%s: v3.4 device found", __FUNCTION__);
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003443 auto err = mHidlSession_3_4->configureStreams_3_4(
3444 requestedConfiguration3_4, configStream34Cb);
3445 res = postprocConfigStream34(err);
3446 if (res != OK) {
3447 return res;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003448 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003449 } else if (mHidlSession_3_3 != nullptr) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003450 // We do; use v3.3 for the call
3451 ALOGV("%s: v3.3 device found", __FUNCTION__);
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003452 auto err = mHidlSession_3_3->configureStreams_3_3(requestedConfiguration3_2,
Emilian Peev31abd0a2017-05-11 18:37:46 +01003453 [&status, &finalConfiguration]
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003454 (common::V1_0::Status s, const device::V3_3::HalStreamConfiguration& halConfiguration) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003455 finalConfiguration = halConfiguration;
3456 status = s;
3457 });
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003458 if (!err.isOk()) {
3459 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3460 return DEAD_OBJECT;
3461 }
3462 } else {
3463 // We don't; use v3.2 call and construct a v3.3 HalStreamConfiguration
3464 ALOGV("%s: v3.2 device found", __FUNCTION__);
3465 HalStreamConfiguration finalConfiguration_3_2;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003466 auto err = mHidlSession->configureStreams(requestedConfiguration3_2,
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003467 [&status, &finalConfiguration_3_2]
3468 (common::V1_0::Status s, const HalStreamConfiguration& halConfiguration) {
3469 finalConfiguration_3_2 = halConfiguration;
3470 status = s;
3471 });
3472 if (!err.isOk()) {
3473 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3474 return DEAD_OBJECT;
3475 }
3476 finalConfiguration.streams.resize(finalConfiguration_3_2.streams.size());
3477 for (size_t i = 0; i < finalConfiguration_3_2.streams.size(); i++) {
3478 finalConfiguration.streams[i].v3_2 = finalConfiguration_3_2.streams[i];
3479 finalConfiguration.streams[i].overrideDataSpace =
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003480 requestedConfiguration3_2.streams[i].dataSpace;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003481 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003482 }
3483
3484 if (status != common::V1_0::Status::OK ) {
3485 return CameraProviderManager::mapToStatusT(status);
3486 }
3487
3488 // And convert output stream configuration from HIDL
3489
3490 for (size_t i = 0; i < config->num_streams; i++) {
Emilian Peevf4816702020-04-03 15:44:51 -07003491 camera3::camera_stream_t *dst = config->streams[i];
Emilian Peev31abd0a2017-05-11 18:37:46 +01003492 int streamId = Camera3Stream::cast(dst)->getId();
3493
3494 // Start scan at i, with the assumption that the stream order matches
3495 size_t realIdx = i;
3496 bool found = false;
Eino-Ville Talvala370875f2019-04-12 12:40:27 -07003497 size_t halStreamCount = finalConfiguration.streams.size();
3498 for (size_t idx = 0; idx < halStreamCount; idx++) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003499 if (finalConfiguration.streams[realIdx].v3_2.id == streamId) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003500 found = true;
3501 break;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003502 }
Eino-Ville Talvala370875f2019-04-12 12:40:27 -07003503 realIdx = (realIdx >= halStreamCount - 1) ? 0 : realIdx + 1;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003504 }
3505 if (!found) {
3506 ALOGE("%s: Stream %d not found in stream configuration response from HAL",
3507 __FUNCTION__, streamId);
3508 return INVALID_OPERATION;
3509 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003510 device::V3_3::HalStream &src = finalConfiguration.streams[realIdx];
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003511 device::V3_6::HalStream &src_36 = finalConfiguration3_6.streams[realIdx];
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003512
Emilian Peev710c1422017-08-30 11:19:38 +01003513 Camera3Stream* dstStream = Camera3Stream::cast(dst);
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003514 int overrideFormat = mapToFrameworkFormat(src.v3_2.overrideFormat);
3515 android_dataspace overrideDataSpace = mapToFrameworkDataspace(src.overrideDataSpace);
3516
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003517 if (mHidlSession_3_6 != nullptr) {
3518 dstStream->setOfflineProcessingSupport(src_36.supportOffline);
3519 }
3520
Yin-Chia Yeh90667662019-07-01 15:45:00 -07003521 if (dstStream->getOriginalFormat() != HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
Shuzhen Wang92653952019-05-07 15:11:43 -07003522 dstStream->setFormatOverride(false);
3523 dstStream->setDataSpaceOverride(false);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003524 if (dst->format != overrideFormat) {
3525 ALOGE("%s: Stream %d: Format override not allowed for format 0x%x", __FUNCTION__,
3526 streamId, dst->format);
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003527 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003528 if (dst->data_space != overrideDataSpace) {
3529 ALOGE("%s: Stream %d: DataSpace override not allowed for format 0x%x", __FUNCTION__,
3530 streamId, dst->format);
3531 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003532 } else {
Shuzhen Wang92653952019-05-07 15:11:43 -07003533 bool needFormatOverride =
3534 requestedConfiguration3_2.streams[i].format != src.v3_2.overrideFormat;
3535 bool needDataspaceOverride =
3536 requestedConfiguration3_2.streams[i].dataSpace != src.overrideDataSpace;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003537 // Override allowed with IMPLEMENTATION_DEFINED
Shuzhen Wang92653952019-05-07 15:11:43 -07003538 dstStream->setFormatOverride(needFormatOverride);
3539 dstStream->setDataSpaceOverride(needDataspaceOverride);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003540 dst->format = overrideFormat;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003541 dst->data_space = overrideDataSpace;
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003542 }
3543
Emilian Peevf4816702020-04-03 15:44:51 -07003544 if (dst->stream_type == CAMERA_STREAM_INPUT) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003545 if (src.v3_2.producerUsage != 0) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003546 ALOGE("%s: Stream %d: INPUT streams must have 0 for producer usage",
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003547 __FUNCTION__, streamId);
3548 return INVALID_OPERATION;
3549 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003550 dstStream->setUsage(
3551 mapConsumerToFrameworkUsage(src.v3_2.consumerUsage));
Emilian Peev31abd0a2017-05-11 18:37:46 +01003552 } else {
3553 // OUTPUT
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003554 if (src.v3_2.consumerUsage != 0) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003555 ALOGE("%s: Stream %d: OUTPUT streams must have 0 for consumer usage",
3556 __FUNCTION__, streamId);
3557 return INVALID_OPERATION;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003558 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003559 dstStream->setUsage(
3560 mapProducerToFrameworkUsage(src.v3_2.producerUsage));
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003561 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003562 dst->max_buffers = src.v3_2.maxBuffers;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003563 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003564
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003565 return res;
3566}
3567
Cliff Wuc2ad9c82021-04-21 00:58:58 +08003568status_t Camera3Device::HalInterface::configureInjectedStreams(
3569 const camera_metadata_t* sessionParams, camera_stream_configuration* config,
3570 const std::vector<uint32_t>& bufferSizes,
3571 const CameraMetadata& cameraCharacteristics) {
3572 ATRACE_NAME("InjectionCameraHal::configureStreams");
3573 if (!valid()) return INVALID_OPERATION;
3574 status_t res = OK;
3575
3576 if (config->input_is_multi_resolution) {
3577 ALOGE("%s: Injection camera device doesn't support multi-resolution input "
3578 "stream", __FUNCTION__);
3579 return BAD_VALUE;
3580 }
3581
3582 // Convert stream config to HIDL
3583 std::set<int> activeStreams;
3584 device::V3_2::StreamConfiguration requestedConfiguration3_2;
3585 device::V3_4::StreamConfiguration requestedConfiguration3_4;
3586 device::V3_7::StreamConfiguration requestedConfiguration3_7;
3587 requestedConfiguration3_2.streams.resize(config->num_streams);
3588 requestedConfiguration3_4.streams.resize(config->num_streams);
3589 requestedConfiguration3_7.streams.resize(config->num_streams);
3590 for (size_t i = 0; i < config->num_streams; i++) {
3591 device::V3_2::Stream& dst3_2 = requestedConfiguration3_2.streams[i];
3592 device::V3_4::Stream& dst3_4 = requestedConfiguration3_4.streams[i];
3593 device::V3_7::Stream& dst3_7 = requestedConfiguration3_7.streams[i];
3594 camera3::camera_stream_t* src = config->streams[i];
3595
3596 Camera3Stream* cam3stream = Camera3Stream::cast(src);
3597 cam3stream->setBufferFreedListener(this);
3598 int streamId = cam3stream->getId();
3599 StreamType streamType;
3600 switch (src->stream_type) {
3601 case CAMERA_STREAM_OUTPUT:
3602 streamType = StreamType::OUTPUT;
3603 break;
3604 case CAMERA_STREAM_INPUT:
3605 streamType = StreamType::INPUT;
3606 break;
3607 default:
3608 ALOGE("%s: Stream %d: Unsupported stream type %d", __FUNCTION__,
3609 streamId, config->streams[i]->stream_type);
3610 return BAD_VALUE;
3611 }
3612 dst3_2.id = streamId;
3613 dst3_2.streamType = streamType;
3614 dst3_2.width = src->width;
3615 dst3_2.height = src->height;
3616 dst3_2.usage = mapToConsumerUsage(cam3stream->getUsage());
3617 dst3_2.rotation =
3618 mapToStreamRotation((camera_stream_rotation_t)src->rotation);
3619 // For HidlSession version 3.5 or newer, the format and dataSpace sent
3620 // to HAL are original, not the overridden ones.
3621 if (mHidlSession_3_5 != nullptr) {
3622 dst3_2.format = mapToPixelFormat(cam3stream->isFormatOverridden()
3623 ? cam3stream->getOriginalFormat()
3624 : src->format);
3625 dst3_2.dataSpace =
3626 mapToHidlDataspace(cam3stream->isDataSpaceOverridden()
3627 ? cam3stream->getOriginalDataSpace()
3628 : src->data_space);
3629 } else {
3630 dst3_2.format = mapToPixelFormat(src->format);
3631 dst3_2.dataSpace = mapToHidlDataspace(src->data_space);
3632 }
3633 dst3_4.v3_2 = dst3_2;
3634 dst3_4.bufferSize = bufferSizes[i];
3635 if (src->physical_camera_id != nullptr) {
3636 dst3_4.physicalCameraId = src->physical_camera_id;
3637 }
3638 dst3_7.v3_4 = dst3_4;
3639 dst3_7.groupId = cam3stream->getHalStreamGroupId();
3640 dst3_7.sensorPixelModesUsed.resize(src->sensor_pixel_modes_used.size());
3641 size_t j = 0;
3642 for (int mode : src->sensor_pixel_modes_used) {
3643 dst3_7.sensorPixelModesUsed[j++] =
3644 static_cast<CameraMetadataEnumAndroidSensorPixelMode>(mode);
3645 }
3646 activeStreams.insert(streamId);
3647 // Create Buffer ID map if necessary
3648 mBufferRecords.tryCreateBufferCache(streamId);
3649 }
3650 // remove BufferIdMap for deleted streams
3651 mBufferRecords.removeInactiveBufferCaches(activeStreams);
3652
3653 StreamConfigurationMode operationMode;
3654 res = mapToStreamConfigurationMode(
3655 (camera_stream_configuration_mode_t)config->operation_mode,
3656 /*out*/ &operationMode);
3657 if (res != OK) {
3658 return res;
3659 }
3660 requestedConfiguration3_7.operationMode = operationMode;
3661 size_t sessionParamSize = get_camera_metadata_size(sessionParams);
3662 requestedConfiguration3_7.operationMode = operationMode;
3663 requestedConfiguration3_7.sessionParams.setToExternal(
3664 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(sessionParams)),
3665 sessionParamSize);
3666
3667 // See which version of HAL we have
3668 if (mHidlSession_3_7 != nullptr) {
3669 requestedConfiguration3_7.streamConfigCounter = mNextStreamConfigCounter++;
3670 requestedConfiguration3_7.multiResolutionInputImage =
3671 config->input_is_multi_resolution;
3672
3673 const camera_metadata_t* rawMetadata = cameraCharacteristics.getAndLock();
3674 ::android::hardware::camera::device::V3_2::CameraMetadata hidlChars = {};
3675 hidlChars.setToExternal(
3676 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(rawMetadata)),
3677 get_camera_metadata_size(rawMetadata));
3678 cameraCharacteristics.unlock(rawMetadata);
3679
3680 sp<hardware::camera::device::V3_7::ICameraInjectionSession>
3681 hidlInjectionSession_3_7;
3682 auto castInjectionResult_3_7 =
3683 device::V3_7::ICameraInjectionSession::castFrom(mHidlSession_3_7);
3684 if (castInjectionResult_3_7.isOk()) {
3685 hidlInjectionSession_3_7 = castInjectionResult_3_7;
3686 } else {
3687 ALOGE("%s: Transaction error: %s", __FUNCTION__,
3688 castInjectionResult_3_7.description().c_str());
3689 return DEAD_OBJECT;
3690 }
3691
3692 auto err = hidlInjectionSession_3_7->configureInjectionStreams(
3693 requestedConfiguration3_7, hidlChars);
3694 if (!err.isOk()) {
3695 ALOGE("%s: Transaction error: %s", __FUNCTION__,
3696 err.description().c_str());
3697 return DEAD_OBJECT;
3698 }
3699 } else {
3700 ALOGE("%s: mHidlSession_3_7 does not exist, the lowest version of injection "
3701 "session is 3.7", __FUNCTION__);
3702 return DEAD_OBJECT;
3703 }
3704
3705 return res;
3706}
3707
Emilian Peevf4816702020-04-03 15:44:51 -07003708status_t Camera3Device::HalInterface::wrapAsHidlRequest(camera_capture_request_t* request,
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003709 /*out*/device::V3_2::CaptureRequest* captureRequest,
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003710 /*out*/std::vector<native_handle_t*>* handlesCreated,
3711 /*out*/std::vector<std::pair<int32_t, int32_t>>* inflightBuffers) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003712 ATRACE_CALL();
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003713 if (captureRequest == nullptr || handlesCreated == nullptr || inflightBuffers == nullptr) {
3714 ALOGE("%s: captureRequest (%p), handlesCreated (%p), and inflightBuffers(%p) "
3715 "must not be null", __FUNCTION__, captureRequest, handlesCreated, inflightBuffers);
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003716 return BAD_VALUE;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003717 }
3718
3719 captureRequest->frameNumber = request->frame_number;
Yifan Hongf79b5542017-04-11 14:44:25 -07003720
3721 captureRequest->fmqSettingsSize = 0;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003722
3723 {
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003724 if (request->input_buffer != nullptr) {
3725 int32_t streamId = Camera3Stream::cast(request->input_buffer->stream)->getId();
3726 buffer_handle_t buf = *(request->input_buffer->buffer);
3727 auto pair = getBufferId(buf, streamId);
3728 bool isNewBuffer = pair.first;
3729 uint64_t bufferId = pair.second;
3730 captureRequest->inputBuffer.streamId = streamId;
3731 captureRequest->inputBuffer.bufferId = bufferId;
3732 captureRequest->inputBuffer.buffer = (isNewBuffer) ? buf : nullptr;
3733 captureRequest->inputBuffer.status = BufferStatus::OK;
3734 native_handle_t *acquireFence = nullptr;
3735 if (request->input_buffer->acquire_fence != -1) {
3736 acquireFence = native_handle_create(1,0);
3737 acquireFence->data[0] = request->input_buffer->acquire_fence;
3738 handlesCreated->push_back(acquireFence);
3739 }
3740 captureRequest->inputBuffer.acquireFence = acquireFence;
3741 captureRequest->inputBuffer.releaseFence = nullptr;
3742
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003743 mBufferRecords.pushInflightBuffer(captureRequest->frameNumber, streamId,
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003744 request->input_buffer->buffer);
3745 inflightBuffers->push_back(std::make_pair(captureRequest->frameNumber, streamId));
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003746 } else {
3747 captureRequest->inputBuffer.streamId = -1;
3748 captureRequest->inputBuffer.bufferId = BUFFER_ID_NO_BUFFER;
3749 }
3750
3751 captureRequest->outputBuffers.resize(request->num_output_buffers);
3752 for (size_t i = 0; i < request->num_output_buffers; i++) {
Emilian Peevf4816702020-04-03 15:44:51 -07003753 const camera_stream_buffer_t *src = request->output_buffers + i;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003754 StreamBuffer &dst = captureRequest->outputBuffers[i];
3755 int32_t streamId = Camera3Stream::cast(src->stream)->getId();
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003756 if (src->buffer != nullptr) {
3757 buffer_handle_t buf = *(src->buffer);
3758 auto pair = getBufferId(buf, streamId);
3759 bool isNewBuffer = pair.first;
3760 dst.bufferId = pair.second;
3761 dst.buffer = isNewBuffer ? buf : nullptr;
3762 native_handle_t *acquireFence = nullptr;
3763 if (src->acquire_fence != -1) {
3764 acquireFence = native_handle_create(1,0);
3765 acquireFence->data[0] = src->acquire_fence;
3766 handlesCreated->push_back(acquireFence);
3767 }
3768 dst.acquireFence = acquireFence;
3769 } else if (mUseHalBufManager) {
3770 // HAL buffer management path
3771 dst.bufferId = BUFFER_ID_NO_BUFFER;
3772 dst.buffer = nullptr;
3773 dst.acquireFence = nullptr;
3774 } else {
3775 ALOGE("%s: cannot send a null buffer in capture request!", __FUNCTION__);
3776 return BAD_VALUE;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003777 }
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003778 dst.streamId = streamId;
3779 dst.status = BufferStatus::OK;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003780 dst.releaseFence = nullptr;
3781
Yin-Chia Yeh5f840f82019-03-05 11:59:04 -08003782 // Output buffers are empty when using HAL buffer manager
3783 if (!mUseHalBufManager) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003784 mBufferRecords.pushInflightBuffer(
3785 captureRequest->frameNumber, streamId, src->buffer);
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003786 inflightBuffers->push_back(std::make_pair(captureRequest->frameNumber, streamId));
Yin-Chia Yeh5f840f82019-03-05 11:59:04 -08003787 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003788 }
3789 }
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003790 return OK;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003791}
3792
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003793void Camera3Device::HalInterface::cleanupNativeHandles(
3794 std::vector<native_handle_t*> *handles, bool closeFd) {
3795 if (handles == nullptr) {
3796 return;
3797 }
3798 if (closeFd) {
3799 for (auto& handle : *handles) {
3800 native_handle_close(handle);
3801 }
3802 }
3803 for (auto& handle : *handles) {
3804 native_handle_delete(handle);
3805 }
3806 handles->clear();
3807 return;
3808}
3809
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003810status_t Camera3Device::HalInterface::processBatchCaptureRequests(
Emilian Peevf4816702020-04-03 15:44:51 -07003811 std::vector<camera_capture_request_t*>& requests,/*out*/uint32_t* numRequestProcessed) {
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003812 ATRACE_NAME("CameraHal::processBatchCaptureRequests");
3813 if (!valid()) return INVALID_OPERATION;
3814
Emilian Peevaebbe412018-01-15 13:53:24 +00003815 sp<device::V3_4::ICameraDeviceSession> hidlSession_3_4;
Shuzhen Wang83bff122020-11-20 15:51:39 -08003816 sp<device::V3_7::ICameraDeviceSession> hidlSession_3_7;
3817 auto castResult_3_7 = device::V3_7::ICameraDeviceSession::castFrom(mHidlSession);
3818 if (castResult_3_7.isOk()) {
3819 hidlSession_3_7 = castResult_3_7;
3820 }
Emilian Peevaebbe412018-01-15 13:53:24 +00003821 auto castResult_3_4 = device::V3_4::ICameraDeviceSession::castFrom(mHidlSession);
3822 if (castResult_3_4.isOk()) {
3823 hidlSession_3_4 = castResult_3_4;
3824 }
3825
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003826 hardware::hidl_vec<device::V3_2::CaptureRequest> captureRequests;
Emilian Peevaebbe412018-01-15 13:53:24 +00003827 hardware::hidl_vec<device::V3_4::CaptureRequest> captureRequests_3_4;
Shuzhen Wang83bff122020-11-20 15:51:39 -08003828 hardware::hidl_vec<device::V3_7::CaptureRequest> captureRequests_3_7;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003829 size_t batchSize = requests.size();
Shuzhen Wang83bff122020-11-20 15:51:39 -08003830 if (hidlSession_3_7 != nullptr) {
3831 captureRequests_3_7.resize(batchSize);
3832 } else if (hidlSession_3_4 != nullptr) {
Emilian Peevaebbe412018-01-15 13:53:24 +00003833 captureRequests_3_4.resize(batchSize);
3834 } else {
3835 captureRequests.resize(batchSize);
3836 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003837 std::vector<native_handle_t*> handlesCreated;
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003838 std::vector<std::pair<int32_t, int32_t>> inflightBuffers;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003839
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003840 status_t res = OK;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003841 for (size_t i = 0; i < batchSize; i++) {
Shuzhen Wang83bff122020-11-20 15:51:39 -08003842 if (hidlSession_3_7 != nullptr) {
3843 res = wrapAsHidlRequest(requests[i], /*out*/&captureRequests_3_7[i].v3_4.v3_2,
3844 /*out*/&handlesCreated, /*out*/&inflightBuffers);
3845 } else if (hidlSession_3_4 != nullptr) {
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003846 res = wrapAsHidlRequest(requests[i], /*out*/&captureRequests_3_4[i].v3_2,
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003847 /*out*/&handlesCreated, /*out*/&inflightBuffers);
Emilian Peevaebbe412018-01-15 13:53:24 +00003848 } else {
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003849 res = wrapAsHidlRequest(requests[i], /*out*/&captureRequests[i],
3850 /*out*/&handlesCreated, /*out*/&inflightBuffers);
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003851 }
3852 if (res != OK) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003853 mBufferRecords.popInflightBuffers(inflightBuffers);
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003854 cleanupNativeHandles(&handlesCreated);
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003855 return res;
Emilian Peevaebbe412018-01-15 13:53:24 +00003856 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003857 }
3858
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003859 std::vector<device::V3_2::BufferCache> cachesToRemove;
3860 {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003861 std::lock_guard<std::mutex> lock(mFreedBuffersLock);
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003862 for (auto& pair : mFreedBuffers) {
3863 // The stream might have been removed since onBufferFreed
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003864 if (mBufferRecords.isStreamCached(pair.first)) {
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003865 cachesToRemove.push_back({pair.first, pair.second});
3866 }
3867 }
3868 mFreedBuffers.clear();
3869 }
3870
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003871 common::V1_0::Status status = common::V1_0::Status::INTERNAL_ERROR;
3872 *numRequestProcessed = 0;
Yifan Hongf79b5542017-04-11 14:44:25 -07003873
3874 // Write metadata to FMQ.
3875 for (size_t i = 0; i < batchSize; i++) {
Emilian Peevf4816702020-04-03 15:44:51 -07003876 camera_capture_request_t* request = requests[i];
Emilian Peevaebbe412018-01-15 13:53:24 +00003877 device::V3_2::CaptureRequest* captureRequest;
Shuzhen Wang83bff122020-11-20 15:51:39 -08003878 if (hidlSession_3_7 != nullptr) {
3879 captureRequest = &captureRequests_3_7[i].v3_4.v3_2;
3880 } else if (hidlSession_3_4 != nullptr) {
Emilian Peevaebbe412018-01-15 13:53:24 +00003881 captureRequest = &captureRequests_3_4[i].v3_2;
3882 } else {
3883 captureRequest = &captureRequests[i];
3884 }
Yifan Hongf79b5542017-04-11 14:44:25 -07003885
3886 if (request->settings != nullptr) {
3887 size_t settingsSize = get_camera_metadata_size(request->settings);
3888 if (mRequestMetadataQueue != nullptr && mRequestMetadataQueue->write(
3889 reinterpret_cast<const uint8_t*>(request->settings), settingsSize)) {
3890 captureRequest->settings.resize(0);
3891 captureRequest->fmqSettingsSize = settingsSize;
3892 } else {
3893 if (mRequestMetadataQueue != nullptr) {
3894 ALOGW("%s: couldn't utilize fmq, fallback to hwbinder", __FUNCTION__);
3895 }
3896 captureRequest->settings.setToExternal(
3897 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(request->settings)),
3898 get_camera_metadata_size(request->settings));
3899 captureRequest->fmqSettingsSize = 0u;
3900 }
3901 } else {
3902 // A null request settings maps to a size-0 CameraMetadata
3903 captureRequest->settings.resize(0);
3904 captureRequest->fmqSettingsSize = 0u;
3905 }
Emilian Peevaebbe412018-01-15 13:53:24 +00003906
Shuzhen Wang83bff122020-11-20 15:51:39 -08003907 // hidl session 3.7 specific handling.
3908 if (hidlSession_3_7 != nullptr) {
3909 captureRequests_3_7[i].inputWidth = request->input_width;
3910 captureRequests_3_7[i].inputHeight = request->input_height;
3911 }
3912
3913 // hidl session 3.7 and 3.4 specific handling.
3914 if (hidlSession_3_7 != nullptr || hidlSession_3_4 != nullptr) {
3915 hardware::hidl_vec<device::V3_4::PhysicalCameraSetting>& physicalCameraSettings =
3916 (hidlSession_3_7 != nullptr) ?
3917 captureRequests_3_7[i].v3_4.physicalCameraSettings :
3918 captureRequests_3_4[i].physicalCameraSettings;
3919 physicalCameraSettings.resize(request->num_physcam_settings);
Emilian Peevaebbe412018-01-15 13:53:24 +00003920 for (size_t j = 0; j < request->num_physcam_settings; j++) {
Emilian Peev00420d22018-02-05 21:33:13 +00003921 if (request->physcam_settings != nullptr) {
3922 size_t settingsSize = get_camera_metadata_size(request->physcam_settings[j]);
3923 if (mRequestMetadataQueue != nullptr && mRequestMetadataQueue->write(
3924 reinterpret_cast<const uint8_t*>(request->physcam_settings[j]),
3925 settingsSize)) {
Shuzhen Wang83bff122020-11-20 15:51:39 -08003926 physicalCameraSettings[j].settings.resize(0);
3927 physicalCameraSettings[j].fmqSettingsSize = settingsSize;
Emilian Peev00420d22018-02-05 21:33:13 +00003928 } else {
3929 if (mRequestMetadataQueue != nullptr) {
3930 ALOGW("%s: couldn't utilize fmq, fallback to hwbinder", __FUNCTION__);
3931 }
Shuzhen Wang83bff122020-11-20 15:51:39 -08003932 physicalCameraSettings[j].settings.setToExternal(
Emilian Peev00420d22018-02-05 21:33:13 +00003933 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(
3934 request->physcam_settings[j])),
3935 get_camera_metadata_size(request->physcam_settings[j]));
Shuzhen Wang83bff122020-11-20 15:51:39 -08003936 physicalCameraSettings[j].fmqSettingsSize = 0u;
Emilian Peevaebbe412018-01-15 13:53:24 +00003937 }
Emilian Peev00420d22018-02-05 21:33:13 +00003938 } else {
Yin-Chia Yeha2849702021-03-10 10:11:33 -08003939 physicalCameraSettings[j].fmqSettingsSize = 0u;
3940 physicalCameraSettings[j].settings.resize(0);
Emilian Peevaebbe412018-01-15 13:53:24 +00003941 }
Shuzhen Wang83bff122020-11-20 15:51:39 -08003942 physicalCameraSettings[j].physicalCameraId = request->physcam_id[j];
Emilian Peevaebbe412018-01-15 13:53:24 +00003943 }
3944 }
Yifan Hongf79b5542017-04-11 14:44:25 -07003945 }
Emilian Peevaebbe412018-01-15 13:53:24 +00003946
3947 hardware::details::return_status err;
Jayant Chowdharyc8d581e2018-07-16 14:46:23 -07003948 auto resultCallback =
3949 [&status, &numRequestProcessed] (auto s, uint32_t n) {
3950 status = s;
3951 *numRequestProcessed = n;
3952 };
Shuzhen Wang83bff122020-11-20 15:51:39 -08003953 if (hidlSession_3_7 != nullptr) {
3954 err = hidlSession_3_7->processCaptureRequest_3_7(captureRequests_3_7, cachesToRemove,
3955 resultCallback);
3956 } else if (hidlSession_3_4 != nullptr) {
Emilian Peevaebbe412018-01-15 13:53:24 +00003957 err = hidlSession_3_4->processCaptureRequest_3_4(captureRequests_3_4, cachesToRemove,
Jayant Chowdharyc8d581e2018-07-16 14:46:23 -07003958 resultCallback);
Emilian Peevaebbe412018-01-15 13:53:24 +00003959 } else {
3960 err = mHidlSession->processCaptureRequest(captureRequests, cachesToRemove,
Jayant Chowdharyc8d581e2018-07-16 14:46:23 -07003961 resultCallback);
Emilian Peevaebbe412018-01-15 13:53:24 +00003962 }
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -07003963 if (!err.isOk()) {
3964 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003965 status = common::V1_0::Status::CAMERA_DISCONNECTED;
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -07003966 }
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003967
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003968 if (status == common::V1_0::Status::OK && *numRequestProcessed != batchSize) {
3969 ALOGE("%s: processCaptureRequest returns OK but processed %d/%zu requests",
3970 __FUNCTION__, *numRequestProcessed, batchSize);
3971 status = common::V1_0::Status::INTERNAL_ERROR;
3972 }
3973
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003974 res = CameraProviderManager::mapToStatusT(status);
3975 if (res == OK) {
3976 if (mHidlSession->isRemote()) {
3977 // Only close acquire fence FDs when the HIDL transaction succeeds (so the FDs have been
3978 // sent to camera HAL processes)
3979 cleanupNativeHandles(&handlesCreated, /*closeFd*/true);
3980 } else {
3981 // In passthrough mode the FDs are now owned by HAL
3982 cleanupNativeHandles(&handlesCreated);
3983 }
3984 } else {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003985 mBufferRecords.popInflightBuffers(inflightBuffers);
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003986 cleanupNativeHandles(&handlesCreated);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003987 }
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003988 return res;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003989}
3990
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003991status_t Camera3Device::HalInterface::flush() {
3992 ATRACE_NAME("CameraHal::flush");
3993 if (!valid()) return INVALID_OPERATION;
3994 status_t res = OK;
3995
Emilian Peev31abd0a2017-05-11 18:37:46 +01003996 auto err = mHidlSession->flush();
3997 if (!err.isOk()) {
3998 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3999 res = DEAD_OBJECT;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004000 } else {
Emilian Peev31abd0a2017-05-11 18:37:46 +01004001 res = CameraProviderManager::mapToStatusT(err);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004002 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01004003
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004004 return res;
4005}
4006
Emilian Peev31abd0a2017-05-11 18:37:46 +01004007status_t Camera3Device::HalInterface::dump(int /*fd*/) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004008 ATRACE_NAME("CameraHal::dump");
4009 if (!valid()) return INVALID_OPERATION;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004010
Emilian Peev31abd0a2017-05-11 18:37:46 +01004011 // Handled by CameraProviderManager::dump
4012
4013 return OK;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004014}
4015
4016status_t Camera3Device::HalInterface::close() {
4017 ATRACE_NAME("CameraHal::close()");
4018 if (!valid()) return INVALID_OPERATION;
4019 status_t res = OK;
4020
Emilian Peev31abd0a2017-05-11 18:37:46 +01004021 auto err = mHidlSession->close();
4022 // Interface will be dead shortly anyway, so don't log errors
4023 if (!err.isOk()) {
4024 res = DEAD_OBJECT;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004025 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01004026
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004027 return res;
4028}
4029
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004030void Camera3Device::HalInterface::signalPipelineDrain(const std::vector<int>& streamIds) {
4031 ATRACE_NAME("CameraHal::signalPipelineDrain");
4032 if (!valid() || mHidlSession_3_5 == nullptr) {
4033 ALOGE("%s called on invalid camera!", __FUNCTION__);
4034 return;
4035 }
4036
Yin-Chia Yehc300a072019-02-13 14:56:57 -08004037 auto err = mHidlSession_3_5->signalStreamFlush(streamIds, mNextStreamConfigCounter - 1);
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004038 if (!err.isOk()) {
4039 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
4040 return;
4041 }
4042}
4043
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004044status_t Camera3Device::HalInterface::switchToOffline(
4045 const std::vector<int32_t>& streamsToKeep,
4046 /*out*/hardware::camera::device::V3_6::CameraOfflineSessionInfo* offlineSessionInfo,
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004047 /*out*/sp<hardware::camera::device::V3_6::ICameraOfflineSession>* offlineSession,
4048 /*out*/camera3::BufferRecords* bufferRecords) {
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004049 ATRACE_NAME("CameraHal::switchToOffline");
4050 if (!valid() || mHidlSession_3_6 == nullptr) {
4051 ALOGE("%s called on invalid camera!", __FUNCTION__);
4052 return INVALID_OPERATION;
4053 }
4054
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004055 if (offlineSessionInfo == nullptr || offlineSession == nullptr || bufferRecords == nullptr) {
4056 ALOGE("%s: output arguments must not be null!", __FUNCTION__);
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004057 return INVALID_OPERATION;
4058 }
4059
4060 common::V1_0::Status status = common::V1_0::Status::INTERNAL_ERROR;
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004061 auto resultCallback =
4062 [&status, &offlineSessionInfo, &offlineSession] (auto s, auto info, auto session) {
4063 status = s;
4064 *offlineSessionInfo = info;
4065 *offlineSession = session;
4066 };
4067 auto err = mHidlSession_3_6->switchToOffline(streamsToKeep, resultCallback);
4068
4069 if (!err.isOk()) {
4070 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
4071 return DEAD_OBJECT;
4072 }
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004073
4074 status_t ret = CameraProviderManager::mapToStatusT(status);
4075 if (ret != OK) {
4076 return ret;
4077 }
4078
4079 // TODO: assert no ongoing requestBuffer/returnBuffer call here
4080 // TODO: update RequestBufferStateMachine to block requestBuffer/returnBuffer once HAL
4081 // returns from switchToOffline.
4082
4083
4084 // Validate buffer caches
4085 std::vector<int32_t> streams;
4086 streams.reserve(offlineSessionInfo->offlineStreams.size());
4087 for (auto offlineStream : offlineSessionInfo->offlineStreams) {
4088 int32_t id = offlineStream.id;
4089 streams.push_back(id);
4090 // Verify buffer caches
4091 std::vector<uint64_t> bufIds(offlineStream.circulatingBufferIds.begin(),
4092 offlineStream.circulatingBufferIds.end());
4093 if (!verifyBufferIds(id, bufIds)) {
4094 ALOGE("%s: stream ID %d buffer cache records mismatch!", __FUNCTION__, id);
4095 return UNKNOWN_ERROR;
4096 }
4097 }
4098
4099 // Move buffer records
4100 bufferRecords->takeBufferCaches(mBufferRecords, streams);
4101 bufferRecords->takeInflightBufferMap(mBufferRecords);
4102 bufferRecords->takeRequestedBufferMap(mBufferRecords);
4103 return ret;
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004104}
4105
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07004106void Camera3Device::HalInterface::getInflightBufferKeys(
4107 std::vector<std::pair<int32_t, int32_t>>* out) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004108 mBufferRecords.getInflightBufferKeys(out);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07004109 return;
4110}
4111
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08004112void Camera3Device::HalInterface::getInflightRequestBufferKeys(
4113 std::vector<uint64_t>* out) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004114 mBufferRecords.getInflightRequestBufferKeys(out);
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08004115 return;
4116}
4117
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004118bool Camera3Device::HalInterface::verifyBufferIds(
4119 int32_t streamId, std::vector<uint64_t>& bufIds) {
4120 return mBufferRecords.verifyBufferIds(streamId, bufIds);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004121}
4122
4123status_t Camera3Device::HalInterface::popInflightBuffer(
Yin-Chia Yehf4650602017-01-10 13:13:39 -08004124 int32_t frameNumber, int32_t streamId,
4125 /*out*/ buffer_handle_t **buffer) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004126 return mBufferRecords.popInflightBuffer(frameNumber, streamId, buffer);
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07004127}
4128
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004129status_t Camera3Device::HalInterface::pushInflightRequestBuffer(
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08004130 uint64_t bufferId, buffer_handle_t* buf, int32_t streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004131 return mBufferRecords.pushInflightRequestBuffer(bufferId, buf, streamId);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004132}
4133
4134// Find and pop a buffer_handle_t based on bufferId
4135status_t Camera3Device::HalInterface::popInflightRequestBuffer(
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08004136 uint64_t bufferId,
4137 /*out*/ buffer_handle_t** buffer,
4138 /*optional out*/ int32_t* streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004139 return mBufferRecords.popInflightRequestBuffer(bufferId, buffer, streamId);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004140}
4141
Yin-Chia Yeh77327052017-01-09 18:23:07 -08004142std::pair<bool, uint64_t> Camera3Device::HalInterface::getBufferId(
4143 const buffer_handle_t& buf, int streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004144 return mBufferRecords.getBufferId(buf, streamId);
Yin-Chia Yeh77327052017-01-09 18:23:07 -08004145}
4146
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07004147void Camera3Device::HalInterface::onBufferFreed(
4148 int streamId, const native_handle_t* handle) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004149 uint32_t bufferId = mBufferRecords.removeOneBufferCache(streamId, handle);
4150 std::lock_guard<std::mutex> lock(mFreedBuffersLock);
4151 if (bufferId != BUFFER_ID_NO_BUFFER) {
4152 mFreedBuffers.push_back(std::make_pair(streamId, bufferId));
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07004153 }
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07004154}
4155
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07004156void Camera3Device::HalInterface::onStreamReConfigured(int streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004157 std::vector<uint64_t> bufIds = mBufferRecords.clearBufferCaches(streamId);
4158 std::lock_guard<std::mutex> lock(mFreedBuffersLock);
4159 for (auto bufferId : bufIds) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07004160 mFreedBuffers.push_back(std::make_pair(streamId, bufferId));
4161 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07004162}
4163
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004164/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004165 * RequestThread inner class methods
4166 */
4167
4168Camera3Device::RequestThread::RequestThread(wp<Camera3Device> parent,
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004169 sp<StatusTracker> statusTracker,
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004170 sp<HalInterface> interface, const Vector<int32_t>& sessionParamKeys,
Eino-Ville Talvala1646c3c2021-07-29 13:48:40 -07004171 bool useHalBufManager,
4172 bool supportCameraMute) :
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004173 Thread(/*canCallJava*/false),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004174 mParent(parent),
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004175 mStatusTracker(statusTracker),
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004176 mInterface(interface),
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07004177 mListener(nullptr),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004178 mId(getId(parent)),
Shuzhen Wang316781a2020-08-18 18:11:01 -07004179 mFirstRepeating(false),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004180 mReconfigured(false),
4181 mDoPause(false),
4182 mPaused(true),
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004183 mNotifyPipelineDrain(false),
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004184 mFrameNumber(0),
Jianing Weicb0652e2014-03-12 18:29:36 -07004185 mLatestRequestId(NAME_NOT_FOUND),
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07004186 mCurrentAfTriggerId(0),
4187 mCurrentPreCaptureTriggerId(0),
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004188 mRotateAndCropOverride(ANDROID_SCALER_ROTATE_AND_CROP_NONE),
Eino-Ville Talvala11afe4f2021-05-27 14:45:31 -07004189 mCameraMute(ANDROID_SENSOR_TEST_PATTERN_MODE_OFF),
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004190 mCameraMuteChanged(false),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004191 mRepeatingLastFrameNumber(
4192 hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES),
Shuzhen Wang686f6442017-06-20 16:16:04 -07004193 mPrepareVideoStream(false),
Emilian Peeva14b4dd2018-05-15 11:00:31 +01004194 mConstrainedMode(false),
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004195 mRequestLatency(kRequestLatencyBinSize),
4196 mSessionParamKeys(sessionParamKeys),
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004197 mLatestSessionParams(sessionParamKeys.size()),
Eino-Ville Talvala1646c3c2021-07-29 13:48:40 -07004198 mUseHalBufManager(useHalBufManager),
4199 mSupportCameraMute(supportCameraMute){
Yin-Chia Yeh87b3ec02019-06-03 10:44:39 -07004200 mStatusId = statusTracker->addComponent("RequestThread");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004201}
4202
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004203Camera3Device::RequestThread::~RequestThread() {}
4204
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004205void Camera3Device::RequestThread::setNotificationListener(
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004206 wp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004207 ATRACE_CALL();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004208 Mutex::Autolock l(mRequestLock);
4209 mListener = listener;
4210}
4211
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004212void Camera3Device::RequestThread::configurationComplete(bool isConstrainedHighSpeed,
Shuzhen Wang99080502021-03-07 21:08:20 -08004213 const CameraMetadata& sessionParams,
4214 const std::map<int32_t, std::set<String8>>& groupIdPhysicalCameraMap) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004215 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004216 Mutex::Autolock l(mRequestLock);
4217 mReconfigured = true;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004218 mLatestSessionParams = sessionParams;
Shuzhen Wang99080502021-03-07 21:08:20 -08004219 mGroupIdPhysicalCameraMap = groupIdPhysicalCameraMap;
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07004220 // Prepare video stream for high speed recording.
4221 mPrepareVideoStream = isConstrainedHighSpeed;
Emilian Peeva14b4dd2018-05-15 11:00:31 +01004222 mConstrainedMode = isConstrainedHighSpeed;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004223}
4224
Jianing Wei90e59c92014-03-12 18:29:36 -07004225status_t Camera3Device::RequestThread::queueRequestList(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004226 List<sp<CaptureRequest> > &requests,
4227 /*out*/
4228 int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004229 ATRACE_CALL();
Jianing Wei90e59c92014-03-12 18:29:36 -07004230 Mutex::Autolock l(mRequestLock);
4231 for (List<sp<CaptureRequest> >::iterator it = requests.begin(); it != requests.end();
4232 ++it) {
4233 mRequestQueue.push_back(*it);
4234 }
4235
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004236 if (lastFrameNumber != NULL) {
4237 *lastFrameNumber = mFrameNumber + mRequestQueue.size() - 1;
4238 ALOGV("%s: requestId %d, mFrameNumber %" PRId32 ", lastFrameNumber %" PRId64 ".",
4239 __FUNCTION__, (*(requests.begin()))->mResultExtras.requestId, mFrameNumber,
4240 *lastFrameNumber);
4241 }
Jianing Weicb0652e2014-03-12 18:29:36 -07004242
Jianing Wei90e59c92014-03-12 18:29:36 -07004243 unpauseForNewRequests();
4244
4245 return OK;
4246}
4247
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004248
4249status_t Camera3Device::RequestThread::queueTrigger(
4250 RequestTrigger trigger[],
4251 size_t count) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004252 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004253 Mutex::Autolock l(mTriggerMutex);
4254 status_t ret;
4255
4256 for (size_t i = 0; i < count; ++i) {
4257 ret = queueTriggerLocked(trigger[i]);
4258
4259 if (ret != OK) {
4260 return ret;
4261 }
4262 }
4263
4264 return OK;
4265}
4266
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004267const String8& Camera3Device::RequestThread::getId(const wp<Camera3Device> &device) {
4268 static String8 deadId("<DeadDevice>");
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004269 sp<Camera3Device> d = device.promote();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004270 if (d != nullptr) return d->mId;
4271 return deadId;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004272}
4273
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004274status_t Camera3Device::RequestThread::queueTriggerLocked(
4275 RequestTrigger trigger) {
4276
4277 uint32_t tag = trigger.metadataTag;
4278 ssize_t index = mTriggerMap.indexOfKey(tag);
4279
4280 switch (trigger.getTagType()) {
4281 case TYPE_BYTE:
4282 // fall-through
4283 case TYPE_INT32:
4284 break;
4285 default:
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004286 ALOGE("%s: Type not supported: 0x%x", __FUNCTION__,
4287 trigger.getTagType());
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004288 return INVALID_OPERATION;
4289 }
4290
4291 /**
4292 * Collect only the latest trigger, since we only have 1 field
4293 * in the request settings per trigger tag, and can't send more than 1
4294 * trigger per request.
4295 */
4296 if (index != NAME_NOT_FOUND) {
4297 mTriggerMap.editValueAt(index) = trigger;
4298 } else {
4299 mTriggerMap.add(tag, trigger);
4300 }
4301
4302 return OK;
4303}
4304
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004305status_t Camera3Device::RequestThread::setRepeatingRequests(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004306 const RequestList &requests,
4307 /*out*/
4308 int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004309 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004310 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004311 if (lastFrameNumber != NULL) {
4312 *lastFrameNumber = mRepeatingLastFrameNumber;
4313 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004314 mRepeatingRequests.clear();
Shuzhen Wang316781a2020-08-18 18:11:01 -07004315 mFirstRepeating = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004316 mRepeatingRequests.insert(mRepeatingRequests.begin(),
4317 requests.begin(), requests.end());
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004318
4319 unpauseForNewRequests();
4320
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004321 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004322 return OK;
4323}
4324
Chih-Hung Hsieh8b0b9712016-08-09 14:25:53 -07004325bool Camera3Device::RequestThread::isRepeatingRequestLocked(const sp<CaptureRequest>& requestIn) {
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07004326 if (mRepeatingRequests.empty()) {
4327 return false;
4328 }
4329 int32_t requestId = requestIn->mResultExtras.requestId;
4330 const RequestList &repeatRequests = mRepeatingRequests;
4331 // All repeating requests are guaranteed to have same id so only check first quest
4332 const sp<CaptureRequest> firstRequest = *repeatRequests.begin();
4333 return (firstRequest->mResultExtras.requestId == requestId);
4334}
4335
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004336status_t Camera3Device::RequestThread::clearRepeatingRequests(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004337 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004338 Mutex::Autolock l(mRequestLock);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004339 return clearRepeatingRequestsLocked(lastFrameNumber);
4340
4341}
4342
4343status_t Camera3Device::RequestThread::clearRepeatingRequestsLocked(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004344 mRepeatingRequests.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004345 if (lastFrameNumber != NULL) {
4346 *lastFrameNumber = mRepeatingLastFrameNumber;
4347 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004348 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004349 return OK;
4350}
4351
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004352status_t Camera3Device::RequestThread::clear(
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004353 /*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004354 ATRACE_CALL();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004355 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004356 ALOGV("RequestThread::%s:", __FUNCTION__);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004357
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004358 mRepeatingRequests.clear();
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07004359
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004360 // Send errors for all requests pending in the request queue, including
4361 // pending repeating requests
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004362 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004363 if (listener != NULL) {
4364 for (RequestList::iterator it = mRequestQueue.begin();
4365 it != mRequestQueue.end(); ++it) {
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004366 // Abort the input buffers for reprocess requests.
4367 if ((*it)->mInputStream != NULL) {
Emilian Peevf4816702020-04-03 15:44:51 -07004368 camera_stream_buffer_t inputBuffer;
Shuzhen Wang83bff122020-11-20 15:51:39 -08004369 camera3::Size inputBufferSize;
Eino-Ville Talvalaba435252017-06-21 16:07:25 -07004370 status_t res = (*it)->mInputStream->getInputBuffer(&inputBuffer,
Shuzhen Wang83bff122020-11-20 15:51:39 -08004371 &inputBufferSize, /*respectHalLimit*/ false);
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004372 if (res != OK) {
4373 ALOGW("%s: %d: couldn't get input buffer while clearing the request "
4374 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
4375 } else {
Emilian Peevf4816702020-04-03 15:44:51 -07004376 inputBuffer.status = CAMERA_BUFFER_STATUS_ERROR;
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004377 res = (*it)->mInputStream->returnInputBuffer(inputBuffer);
4378 if (res != OK) {
4379 ALOGE("%s: %d: couldn't return input buffer while clearing the request "
4380 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
4381 }
4382 }
4383 }
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004384 // Set the frame number this request would have had, if it
4385 // had been submitted; this frame number will not be reused.
4386 // The requestId and burstId fields were set when the request was
4387 // submitted originally (in convertMetadataListToRequestListLocked)
4388 (*it)->mResultExtras.frameNumber = mFrameNumber++;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004389 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004390 (*it)->mResultExtras);
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07004391 }
4392 }
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004393 mRequestQueue.clear();
Jinguang Dongb26e7a02016-11-14 16:04:02 +08004394
4395 Mutex::Autolock al(mTriggerMutex);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004396 mTriggerMap.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004397 if (lastFrameNumber != NULL) {
4398 *lastFrameNumber = mRepeatingLastFrameNumber;
4399 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004400 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Emilian Peev8dae54c2019-12-02 15:17:17 -08004401 mRequestSignal.signal();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004402 return OK;
4403}
4404
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004405status_t Camera3Device::RequestThread::flush() {
4406 ATRACE_CALL();
4407 Mutex::Autolock l(mFlushLock);
4408
Emilian Peev08dd2452017-04-06 16:55:14 +01004409 return mInterface->flush();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004410}
4411
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004412void Camera3Device::RequestThread::setPaused(bool paused) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004413 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004414 Mutex::Autolock l(mPauseLock);
4415 mDoPause = paused;
4416 mDoPauseSignal.signal();
4417}
4418
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004419status_t Camera3Device::RequestThread::waitUntilRequestProcessed(
4420 int32_t requestId, nsecs_t timeout) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004421 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004422 Mutex::Autolock l(mLatestRequestMutex);
4423 status_t res;
4424 while (mLatestRequestId != requestId) {
4425 nsecs_t startTime = systemTime();
4426
4427 res = mLatestRequestSignal.waitRelative(mLatestRequestMutex, timeout);
4428 if (res != OK) return res;
4429
4430 timeout -= (systemTime() - startTime);
4431 }
4432
4433 return OK;
4434}
4435
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004436void Camera3Device::RequestThread::requestExit() {
4437 // Call parent to set up shutdown
4438 Thread::requestExit();
4439 // The exit from any possible waits
4440 mDoPauseSignal.signal();
4441 mRequestSignal.signal();
Shuzhen Wang686f6442017-06-20 16:16:04 -07004442
4443 mRequestLatency.log("ProcessCaptureRequest latency histogram");
4444 mRequestLatency.reset();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004445}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004446
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004447void Camera3Device::RequestThread::checkAndStopRepeatingRequest() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004448 ATRACE_CALL();
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07004449 bool surfaceAbandoned = false;
4450 int64_t lastFrameNumber = 0;
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004451 sp<NotificationListener> listener;
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07004452 {
4453 Mutex::Autolock l(mRequestLock);
4454 // Check all streams needed by repeating requests are still valid. Otherwise, stop
4455 // repeating requests.
4456 for (const auto& request : mRepeatingRequests) {
4457 for (const auto& s : request->mOutputStreams) {
4458 if (s->isAbandoned()) {
4459 surfaceAbandoned = true;
4460 clearRepeatingRequestsLocked(&lastFrameNumber);
4461 break;
4462 }
4463 }
4464 if (surfaceAbandoned) {
4465 break;
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004466 }
4467 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004468 listener = mListener.promote();
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004469 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004470
4471 if (listener != NULL && surfaceAbandoned) {
4472 listener->notifyRepeatingRequestError(lastFrameNumber);
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07004473 }
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004474}
4475
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004476bool Camera3Device::RequestThread::sendRequestsBatch() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004477 ATRACE_CALL();
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004478 status_t res;
4479 size_t batchSize = mNextRequests.size();
Emilian Peevf4816702020-04-03 15:44:51 -07004480 std::vector<camera_capture_request_t*> requests(batchSize);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004481 uint32_t numRequestProcessed = 0;
4482 for (size_t i = 0; i < batchSize; i++) {
4483 requests[i] = &mNextRequests.editItemAt(i).halRequest;
Yin-Chia Yeh885691c2018-05-01 15:54:24 -07004484 ATRACE_ASYNC_BEGIN("frame capture", mNextRequests[i].halRequest.frame_number);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004485 }
4486
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004487 res = mInterface->processBatchCaptureRequests(requests, &numRequestProcessed);
4488
4489 bool triggerRemoveFailed = false;
4490 NextRequest& triggerFailedRequest = mNextRequests.editItemAt(0);
4491 for (size_t i = 0; i < numRequestProcessed; i++) {
4492 NextRequest& nextRequest = mNextRequests.editItemAt(i);
4493 nextRequest.submitted = true;
4494
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004495 updateNextRequest(nextRequest);
Emilian Peevaebbe412018-01-15 13:53:24 +00004496
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004497 if (!triggerRemoveFailed) {
4498 // Remove any previously queued triggers (after unlock)
4499 status_t removeTriggerRes = removeTriggers(mPrevRequest);
4500 if (removeTriggerRes != OK) {
4501 triggerRemoveFailed = true;
4502 triggerFailedRequest = nextRequest;
4503 }
4504 }
4505 }
4506
4507 if (triggerRemoveFailed) {
4508 SET_ERR("RequestThread: Unable to remove triggers "
4509 "(capture request %d, HAL device: %s (%d)",
4510 triggerFailedRequest.halRequest.frame_number, strerror(-res), res);
4511 cleanUpFailedRequests(/*sendRequestError*/ false);
4512 return false;
4513 }
4514
4515 if (res != OK) {
4516 // Should only get a failure here for malformed requests or device-level
4517 // errors, so consider all errors fatal. Bad metadata failures should
4518 // come through notify.
4519 SET_ERR("RequestThread: Unable to submit capture request %d to HAL device: %s (%d)",
4520 mNextRequests[numRequestProcessed].halRequest.frame_number,
4521 strerror(-res), res);
4522 cleanUpFailedRequests(/*sendRequestError*/ false);
4523 return false;
4524 }
4525 return true;
4526}
4527
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07004528nsecs_t Camera3Device::RequestThread::calculateMaxExpectedDuration(const camera_metadata_t *request) {
4529 nsecs_t maxExpectedDuration = kDefaultExpectedDuration;
4530 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
4531 find_camera_metadata_ro_entry(request,
4532 ANDROID_CONTROL_AE_MODE,
4533 &e);
4534 if (e.count == 0) return maxExpectedDuration;
4535
4536 switch (e.data.u8[0]) {
4537 case ANDROID_CONTROL_AE_MODE_OFF:
4538 find_camera_metadata_ro_entry(request,
4539 ANDROID_SENSOR_EXPOSURE_TIME,
4540 &e);
4541 if (e.count > 0) {
4542 maxExpectedDuration = e.data.i64[0];
4543 }
4544 find_camera_metadata_ro_entry(request,
4545 ANDROID_SENSOR_FRAME_DURATION,
4546 &e);
4547 if (e.count > 0) {
4548 maxExpectedDuration = std::max(e.data.i64[0], maxExpectedDuration);
4549 }
4550 break;
4551 default:
4552 find_camera_metadata_ro_entry(request,
4553 ANDROID_CONTROL_AE_TARGET_FPS_RANGE,
4554 &e);
4555 if (e.count > 1) {
4556 maxExpectedDuration = 1e9 / e.data.u8[0];
4557 }
4558 break;
4559 }
4560
4561 return maxExpectedDuration;
4562}
4563
Emilian Peeva14b4dd2018-05-15 11:00:31 +01004564bool Camera3Device::RequestThread::skipHFRTargetFPSUpdate(int32_t tag,
4565 const camera_metadata_ro_entry_t& newEntry, const camera_metadata_entry_t& currentEntry) {
4566 if (mConstrainedMode && (ANDROID_CONTROL_AE_TARGET_FPS_RANGE == tag) &&
4567 (newEntry.count == currentEntry.count) && (currentEntry.count == 2) &&
4568 (currentEntry.data.i32[1] == newEntry.data.i32[1])) {
4569 return true;
4570 }
4571
4572 return false;
4573}
4574
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004575void Camera3Device::RequestThread::updateNextRequest(NextRequest& nextRequest) {
4576 // Update the latest request sent to HAL
Shuzhen Wang83bff122020-11-20 15:51:39 -08004577 camera_capture_request_t& halRequest = nextRequest.halRequest;
4578 if (halRequest.settings != NULL) { // Don't update if they were unchanged
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004579 Mutex::Autolock al(mLatestRequestMutex);
4580
Shuzhen Wang83bff122020-11-20 15:51:39 -08004581 camera_metadata_t* cloned = clone_camera_metadata(halRequest.settings);
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004582 mLatestRequest.acquire(cloned);
4583
4584 mLatestPhysicalRequest.clear();
Shuzhen Wang83bff122020-11-20 15:51:39 -08004585 for (uint32_t i = 0; i < halRequest.num_physcam_settings; i++) {
4586 cloned = clone_camera_metadata(halRequest.physcam_settings[i]);
4587 mLatestPhysicalRequest.emplace(halRequest.physcam_id[i],
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004588 CameraMetadata(cloned));
4589 }
4590
4591 sp<Camera3Device> parent = mParent.promote();
4592 if (parent != NULL) {
Jayant Chowdharycd277cd2021-08-11 15:48:40 -07004593 std::set<int32_t> outputStreamIds;
4594 for (size_t i = 0; i < halRequest.num_output_buffers; i++) {
4595 const camera_stream_buffer_t *src = halRequest.output_buffers + i;
4596 int32_t streamId = Camera3Stream::cast(src->stream)->getId();
4597 outputStreamIds.emplace(streamId);
4598 }
4599 int32_t inputStreamId = -1;
4600 if (halRequest.input_buffer != nullptr) {
4601 inputStreamId = Camera3Stream::cast(halRequest.input_buffer->stream)->getId();
4602 }
4603
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004604 parent->monitorMetadata(TagMonitor::REQUEST,
Shuzhen Wang83bff122020-11-20 15:51:39 -08004605 halRequest.frame_number,
Jayant Chowdharycd277cd2021-08-11 15:48:40 -07004606 0, mLatestRequest, mLatestPhysicalRequest, outputStreamIds, inputStreamId);
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004607 }
4608 }
4609
Shuzhen Wang83bff122020-11-20 15:51:39 -08004610 if (halRequest.settings != NULL) {
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004611 nextRequest.captureRequest->mSettingsList.begin()->metadata.unlock(
Shuzhen Wang83bff122020-11-20 15:51:39 -08004612 halRequest.settings);
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004613 }
4614
Shuzhen Wang83bff122020-11-20 15:51:39 -08004615 cleanupPhysicalSettings(nextRequest.captureRequest, &halRequest);
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004616}
4617
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004618bool Camera3Device::RequestThread::updateSessionParameters(const CameraMetadata& settings) {
4619 ATRACE_CALL();
4620 bool updatesDetected = false;
4621
Emilian Peev4ec17882019-01-24 17:16:58 -08004622 CameraMetadata updatedParams(mLatestSessionParams);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004623 for (auto tag : mSessionParamKeys) {
4624 camera_metadata_ro_entry entry = settings.find(tag);
Emilian Peev4ec17882019-01-24 17:16:58 -08004625 camera_metadata_entry lastEntry = updatedParams.find(tag);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004626
4627 if (entry.count > 0) {
4628 bool isDifferent = false;
4629 if (lastEntry.count > 0) {
4630 // Have a last value, compare to see if changed
4631 if (lastEntry.type == entry.type &&
4632 lastEntry.count == entry.count) {
4633 // Same type and count, compare values
4634 size_t bytesPerValue = camera_metadata_type_size[lastEntry.type];
4635 size_t entryBytes = bytesPerValue * lastEntry.count;
4636 int cmp = memcmp(entry.data.u8, lastEntry.data.u8, entryBytes);
4637 if (cmp != 0) {
4638 isDifferent = true;
4639 }
4640 } else {
4641 // Count or type has changed
4642 isDifferent = true;
4643 }
4644 } else {
4645 // No last entry, so always consider to be different
4646 isDifferent = true;
4647 }
4648
4649 if (isDifferent) {
4650 ALOGV("%s: Session parameter tag id %d changed", __FUNCTION__, tag);
Emilian Peeva14b4dd2018-05-15 11:00:31 +01004651 if (!skipHFRTargetFPSUpdate(tag, entry, lastEntry)) {
4652 updatesDetected = true;
4653 }
Emilian Peev4ec17882019-01-24 17:16:58 -08004654 updatedParams.update(entry);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004655 }
4656 } else if (lastEntry.count > 0) {
4657 // Value has been removed
4658 ALOGV("%s: Session parameter tag id %d removed", __FUNCTION__, tag);
Emilian Peev4ec17882019-01-24 17:16:58 -08004659 updatedParams.erase(tag);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004660 updatesDetected = true;
4661 }
4662 }
4663
Emilian Peev4ec17882019-01-24 17:16:58 -08004664 bool reconfigureRequired;
4665 if (updatesDetected) {
4666 reconfigureRequired = mInterface->isReconfigurationRequired(mLatestSessionParams,
4667 updatedParams);
4668 mLatestSessionParams = updatedParams;
4669 } else {
4670 reconfigureRequired = false;
4671 }
4672
4673 return reconfigureRequired;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004674}
4675
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004676bool Camera3Device::RequestThread::threadLoop() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004677 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004678 status_t res;
Jayant Chowdhary37eca242019-11-18 08:55:56 -08004679 // Any function called from threadLoop() must not hold mInterfaceLock since
4680 // it could lead to deadlocks (disconnect() -> hold mInterfaceMutex -> wait for request thread
4681 // to finish -> request thread waits on mInterfaceMutex) http://b/143513518
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004682
4683 // Handle paused state.
4684 if (waitIfPaused()) {
4685 return true;
4686 }
4687
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004688 // Wait for the next batch of requests.
4689 waitForNextRequestBatch();
4690 if (mNextRequests.size() == 0) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004691 return true;
4692 }
4693
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004694 // Get the latest request ID, if any
4695 int latestRequestId;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004696 camera_metadata_entry_t requestIdEntry = mNextRequests[mNextRequests.size() - 1].
Emilian Peevaebbe412018-01-15 13:53:24 +00004697 captureRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_ID);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004698 if (requestIdEntry.count > 0) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004699 latestRequestId = requestIdEntry.data.i32[0];
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004700 } else {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004701 ALOGW("%s: Did not have android.request.id set in the request.", __FUNCTION__);
4702 latestRequestId = NAME_NOT_FOUND;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004703 }
4704
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004705 // 'mNextRequests' will at this point contain either a set of HFR batched requests
4706 // or a single request from streaming or burst. In either case the first element
4707 // should contain the latest camera settings that we need to check for any session
4708 // parameter updates.
Emilian Peevaebbe412018-01-15 13:53:24 +00004709 if (updateSessionParameters(mNextRequests[0].captureRequest->mSettingsList.begin()->metadata)) {
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004710 res = OK;
4711
4712 //Input stream buffers are already acquired at this point so an input stream
4713 //will not be able to move to idle state unless we force it.
4714 if (mNextRequests[0].captureRequest->mInputStream != nullptr) {
4715 res = mNextRequests[0].captureRequest->mInputStream->forceToIdle();
4716 if (res != OK) {
4717 ALOGE("%s: Failed to force idle input stream: %d", __FUNCTION__, res);
4718 cleanUpFailedRequests(/*sendRequestError*/ false);
4719 return false;
4720 }
4721 }
4722
4723 if (res == OK) {
Emilian Peev3bead5f2020-05-28 17:29:08 -07004724 sp<Camera3Device> parent = mParent.promote();
4725 if (parent != nullptr) {
4726 mReconfigured |= parent->reconfigureCamera(mLatestSessionParams, mStatusId);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004727 }
Emilian Peev3bead5f2020-05-28 17:29:08 -07004728 setPaused(false);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004729
4730 if (mNextRequests[0].captureRequest->mInputStream != nullptr) {
4731 mNextRequests[0].captureRequest->mInputStream->restoreConfiguredState();
4732 if (res != OK) {
4733 ALOGE("%s: Failed to restore configured input stream: %d", __FUNCTION__, res);
4734 cleanUpFailedRequests(/*sendRequestError*/ false);
4735 return false;
4736 }
4737 }
4738 }
4739 }
4740
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004741 // Prepare a batch of HAL requests and output buffers.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004742 res = prepareHalRequests();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004743 if (res == TIMED_OUT) {
4744 // Not a fatal error if getting output buffers time out.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004745 cleanUpFailedRequests(/*sendRequestError*/ true);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004746 // Check if any stream is abandoned.
4747 checkAndStopRepeatingRequest();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004748 return true;
4749 } else if (res != OK) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004750 cleanUpFailedRequests(/*sendRequestError*/ false);
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004751 return false;
4752 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004753
Zhijun Hecc27e112013-10-03 16:12:43 -07004754 // Inform waitUntilRequestProcessed thread of a new request ID
4755 {
4756 Mutex::Autolock al(mLatestRequestMutex);
4757
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004758 mLatestRequestId = latestRequestId;
Zhijun Hecc27e112013-10-03 16:12:43 -07004759 mLatestRequestSignal.signal();
4760 }
4761
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004762 // Submit a batch of requests to HAL.
4763 // Use flush lock only when submitting multilple requests in a batch.
4764 // TODO: The problem with flush lock is flush() will be blocked by process_capture_request()
4765 // which may take a long time to finish so synchronizing flush() and
4766 // process_capture_request() defeats the purpose of cancelling requests ASAP with flush().
4767 // For now, only synchronize for high speed recording and we should figure something out for
4768 // removing the synchronization.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004769 bool useFlushLock = mNextRequests.size() > 1;
Eino-Ville Talvala17a61ad2013-06-03 16:53:32 -07004770
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004771 if (useFlushLock) {
4772 mFlushLock.lock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004773 }
4774
Zhijun Hef0645c12016-08-02 00:58:11 -07004775 ALOGVV("%s: %d: submitting %zu requests in a batch.", __FUNCTION__, __LINE__,
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004776 mNextRequests.size());
Igor Murashkin1e479c02013-09-06 16:55:14 -07004777
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08004778 sp<Camera3Device> parent = mParent.promote();
4779 if (parent != nullptr) {
4780 parent->mRequestBufferSM.onSubmittingRequest();
4781 }
4782
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004783 bool submitRequestSuccess = false;
Shuzhen Wang686f6442017-06-20 16:16:04 -07004784 nsecs_t tRequestStart = systemTime(SYSTEM_TIME_MONOTONIC);
Yin-Chia Yeh11648852019-05-16 10:42:54 -07004785 submitRequestSuccess = sendRequestsBatch();
4786
Shuzhen Wang686f6442017-06-20 16:16:04 -07004787 nsecs_t tRequestEnd = systemTime(SYSTEM_TIME_MONOTONIC);
4788 mRequestLatency.add(tRequestStart, tRequestEnd);
Igor Murashkin1e479c02013-09-06 16:55:14 -07004789
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004790 if (useFlushLock) {
4791 mFlushLock.unlock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004792 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004793
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004794 // Unset as current request
4795 {
4796 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004797 mNextRequests.clear();
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004798 }
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004799 mRequestSubmittedSignal.signal();
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004800
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004801 return submitRequestSuccess;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004802}
4803
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004804status_t Camera3Device::RequestThread::prepareHalRequests() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004805 ATRACE_CALL();
4806
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07004807 bool batchedRequest = mNextRequests[0].captureRequest->mBatchSize > 1;
Shuzhen Wang4a472662017-02-26 23:29:04 -08004808 for (size_t i = 0; i < mNextRequests.size(); i++) {
4809 auto& nextRequest = mNextRequests.editItemAt(i);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004810 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
Emilian Peevf4816702020-04-03 15:44:51 -07004811 camera_capture_request_t* halRequest = &nextRequest.halRequest;
4812 Vector<camera_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004813
4814 // Prepare a request to HAL
4815 halRequest->frame_number = captureRequest->mResultExtras.frameNumber;
4816
4817 // Insert any queued triggers (before metadata is locked)
4818 status_t res = insertTriggers(captureRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004819 if (res < 0) {
4820 SET_ERR("RequestThread: Unable to insert triggers "
4821 "(capture request %d, HAL device: %s (%d)",
4822 halRequest->frame_number, strerror(-res), res);
4823 return INVALID_OPERATION;
4824 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07004825
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004826 int triggerCount = res;
4827 bool triggersMixedIn = (triggerCount > 0 || mPrevTriggers > 0);
4828 mPrevTriggers = triggerCount;
4829
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004830 bool rotateAndCropChanged = overrideAutoRotateAndCrop(captureRequest);
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004831 bool testPatternChanged = overrideTestPattern(captureRequest);
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004832
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004833 // If the request is the same as last, or we had triggers now or last time or
4834 // changing overrides this time
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004835 bool newRequest =
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004836 (mPrevRequest != captureRequest || triggersMixedIn ||
4837 rotateAndCropChanged || testPatternChanged) &&
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07004838 // Request settings are all the same within one batch, so only treat the first
4839 // request in a batch as new
Zhijun He54c36822018-07-18 09:33:39 -07004840 !(batchedRequest && i > 0);
Emilian Peev00420d22018-02-05 21:33:13 +00004841 if (newRequest) {
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08004842 std::set<std::string> cameraIdsWithZoom;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004843 /**
4844 * HAL workaround:
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004845 * Insert a fake trigger ID if a trigger is set but no trigger ID is
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004846 */
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004847 res = addFakeTriggerIds(captureRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004848 if (res != OK) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004849 SET_ERR("RequestThread: Unable to insert fake trigger IDs "
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004850 "(capture request %d, HAL device: %s (%d)",
4851 halRequest->frame_number, strerror(-res), res);
4852 return INVALID_OPERATION;
4853 }
4854
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07004855 {
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07004856 sp<Camera3Device> parent = mParent.promote();
4857 if (parent != nullptr) {
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -07004858 List<PhysicalCameraSettings>::iterator it;
4859 for (it = captureRequest->mSettingsList.begin();
4860 it != captureRequest->mSettingsList.end(); it++) {
Jayant Chowdhary9255ce02021-07-15 11:18:17 -07004861 if (parent->mUHRCropAndMeteringRegionMappers.find(it->cameraId) ==
4862 parent->mUHRCropAndMeteringRegionMappers.end()) {
4863 continue;
4864 }
4865
4866 if (!captureRequest->mUHRCropAndMeteringRegionsUpdated) {
4867 res = parent->mUHRCropAndMeteringRegionMappers[it->cameraId].
4868 updateCaptureRequest(&(it->metadata));
4869 if (res != OK) {
4870 SET_ERR("RequestThread: Unable to correct capture requests "
4871 "for scaler crop region and metering regions for request "
4872 "%d: %s (%d)", halRequest->frame_number, strerror(-res),
4873 res);
4874 return INVALID_OPERATION;
4875 }
4876 captureRequest->mUHRCropAndMeteringRegionsUpdated = true;
4877 }
4878 }
4879
4880 // Correct metadata regions for distortion correction if enabled
4881 for (it = captureRequest->mSettingsList.begin();
4882 it != captureRequest->mSettingsList.end(); it++) {
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -07004883 if (parent->mDistortionMappers.find(it->cameraId) ==
4884 parent->mDistortionMappers.end()) {
4885 continue;
4886 }
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07004887
4888 if (!captureRequest->mDistortionCorrectionUpdated) {
4889 res = parent->mDistortionMappers[it->cameraId].correctCaptureRequest(
4890 &(it->metadata));
4891 if (res != OK) {
4892 SET_ERR("RequestThread: Unable to correct capture requests "
4893 "for lens distortion for request %d: %s (%d)",
4894 halRequest->frame_number, strerror(-res), res);
4895 return INVALID_OPERATION;
4896 }
4897 captureRequest->mDistortionCorrectionUpdated = true;
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -07004898 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07004899 }
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08004900
4901 for (it = captureRequest->mSettingsList.begin();
4902 it != captureRequest->mSettingsList.end(); it++) {
4903 if (parent->mZoomRatioMappers.find(it->cameraId) ==
4904 parent->mZoomRatioMappers.end()) {
4905 continue;
4906 }
4907
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07004908 if (!captureRequest->mZoomRatioIs1x) {
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08004909 cameraIdsWithZoom.insert(it->cameraId);
4910 }
4911
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07004912 if (!captureRequest->mZoomRatioUpdated) {
4913 res = parent->mZoomRatioMappers[it->cameraId].updateCaptureRequest(
4914 &(it->metadata));
4915 if (res != OK) {
4916 SET_ERR("RequestThread: Unable to correct capture requests "
4917 "for zoom ratio for request %d: %s (%d)",
4918 halRequest->frame_number, strerror(-res), res);
4919 return INVALID_OPERATION;
4920 }
4921 captureRequest->mZoomRatioUpdated = true;
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08004922 }
4923 }
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07004924 if (captureRequest->mRotateAndCropAuto &&
4925 !captureRequest->mRotationAndCropUpdated) {
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004926 for (it = captureRequest->mSettingsList.begin();
4927 it != captureRequest->mSettingsList.end(); it++) {
4928 auto mapper = parent->mRotateAndCropMappers.find(it->cameraId);
4929 if (mapper != parent->mRotateAndCropMappers.end()) {
4930 res = mapper->second.updateCaptureRequest(&(it->metadata));
4931 if (res != OK) {
4932 SET_ERR("RequestThread: Unable to correct capture requests "
4933 "for rotate-and-crop for request %d: %s (%d)",
4934 halRequest->frame_number, strerror(-res), res);
4935 return INVALID_OPERATION;
4936 }
4937 }
4938 }
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07004939 captureRequest->mRotationAndCropUpdated = true;
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004940 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07004941 }
4942 }
4943
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004944 /**
4945 * The request should be presorted so accesses in HAL
4946 * are O(logn). Sidenote, sorting a sorted metadata is nop.
4947 */
Emilian Peevaebbe412018-01-15 13:53:24 +00004948 captureRequest->mSettingsList.begin()->metadata.sort();
4949 halRequest->settings = captureRequest->mSettingsList.begin()->metadata.getAndLock();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004950 mPrevRequest = captureRequest;
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08004951 mPrevCameraIdsWithZoom = cameraIdsWithZoom;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004952 ALOGVV("%s: Request settings are NEW", __FUNCTION__);
4953
4954 IF_ALOGV() {
4955 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
4956 find_camera_metadata_ro_entry(
4957 halRequest->settings,
4958 ANDROID_CONTROL_AF_TRIGGER,
4959 &e
4960 );
4961 if (e.count > 0) {
4962 ALOGV("%s: Request (frame num %d) had AF trigger 0x%x",
4963 __FUNCTION__,
4964 halRequest->frame_number,
4965 e.data.u8[0]);
4966 }
4967 }
4968 } else {
4969 // leave request.settings NULL to indicate 'reuse latest given'
4970 ALOGVV("%s: Request settings are REUSED",
4971 __FUNCTION__);
4972 }
4973
Emilian Peevaebbe412018-01-15 13:53:24 +00004974 if (captureRequest->mSettingsList.size() > 1) {
4975 halRequest->num_physcam_settings = captureRequest->mSettingsList.size() - 1;
4976 halRequest->physcam_id = new const char* [halRequest->num_physcam_settings];
Emilian Peev00420d22018-02-05 21:33:13 +00004977 if (newRequest) {
4978 halRequest->physcam_settings =
4979 new const camera_metadata* [halRequest->num_physcam_settings];
4980 } else {
4981 halRequest->physcam_settings = nullptr;
4982 }
Emilian Peevaebbe412018-01-15 13:53:24 +00004983 auto it = ++captureRequest->mSettingsList.begin();
4984 size_t i = 0;
4985 for (; it != captureRequest->mSettingsList.end(); it++, i++) {
4986 halRequest->physcam_id[i] = it->cameraId.c_str();
Emilian Peev00420d22018-02-05 21:33:13 +00004987 if (newRequest) {
4988 it->metadata.sort();
4989 halRequest->physcam_settings[i] = it->metadata.getAndLock();
4990 }
Emilian Peevaebbe412018-01-15 13:53:24 +00004991 }
4992 }
4993
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004994 uint32_t totalNumBuffers = 0;
4995
4996 // Fill in buffers
4997 if (captureRequest->mInputStream != NULL) {
4998 halRequest->input_buffer = &captureRequest->mInputBuffer;
Shuzhen Wang83bff122020-11-20 15:51:39 -08004999
5000 halRequest->input_width = captureRequest->mInputBufferSize.width;
5001 halRequest->input_height = captureRequest->mInputBufferSize.height;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005002 totalNumBuffers += 1;
5003 } else {
5004 halRequest->input_buffer = NULL;
5005 }
5006
Emilian Peevf4816702020-04-03 15:44:51 -07005007 outputBuffers->insertAt(camera_stream_buffer_t(), 0,
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005008 captureRequest->mOutputStreams.size());
5009 halRequest->output_buffers = outputBuffers->array();
Shuzhen Wang99080502021-03-07 21:08:20 -08005010 std::set<std::set<String8>> requestedPhysicalCameras;
Yin-Chia Yehb3a80b12018-09-04 12:13:05 -07005011
5012 sp<Camera3Device> parent = mParent.promote();
5013 if (parent == NULL) {
5014 // Should not happen, and nowhere to send errors to, so just log it
5015 CLOGE("RequestThread: Parent is gone");
5016 return INVALID_OPERATION;
5017 }
5018 nsecs_t waitDuration = kBaseGetBufferWait + parent->getExpectedInFlightDuration();
5019
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005020 SurfaceMap uniqueSurfaceIdMap;
Shuzhen Wang4a472662017-02-26 23:29:04 -08005021 for (size_t j = 0; j < captureRequest->mOutputStreams.size(); j++) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005022 sp<Camera3OutputStreamInterface> outputStream =
5023 captureRequest->mOutputStreams.editItemAt(j);
5024 int streamId = outputStream->getId();
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07005025
5026 // Prepare video buffers for high speed recording on the first video request.
5027 if (mPrepareVideoStream && outputStream->isVideoStream()) {
5028 // Only try to prepare video stream on the first video request.
5029 mPrepareVideoStream = false;
5030
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07005031 res = outputStream->startPrepare(Camera3StreamInterface::ALLOCATE_PIPELINE_MAX,
5032 false /*blockRequest*/);
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07005033 while (res == NOT_ENOUGH_DATA) {
5034 res = outputStream->prepareNextBuffer();
5035 }
5036 if (res != OK) {
5037 ALOGW("%s: Preparing video buffers for high speed failed: %s (%d)",
5038 __FUNCTION__, strerror(-res), res);
5039 outputStream->cancelPrepare();
5040 }
5041 }
5042
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005043 std::vector<size_t> uniqueSurfaceIds;
5044 res = outputStream->getUniqueSurfaceIds(
5045 captureRequest->mOutputSurfaces[streamId],
5046 &uniqueSurfaceIds);
5047 // INVALID_OPERATION is normal output for streams not supporting surfaceIds
5048 if (res != OK && res != INVALID_OPERATION) {
5049 ALOGE("%s: failed to query stream %d unique surface IDs",
5050 __FUNCTION__, streamId);
5051 return res;
5052 }
5053 if (res == OK) {
5054 uniqueSurfaceIdMap.insert({streamId, std::move(uniqueSurfaceIds)});
5055 }
5056
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07005057 if (mUseHalBufManager) {
Yin-Chia Yeh110342b2018-11-19 11:47:46 -08005058 if (outputStream->isAbandoned()) {
Yin-Chia Yeha1b56c82019-03-27 15:50:39 -07005059 ALOGV("%s: stream %d is abandoned, skipping request", __FUNCTION__, streamId);
Yin-Chia Yeh110342b2018-11-19 11:47:46 -08005060 return TIMED_OUT;
5061 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07005062 // HAL will request buffer through requestStreamBuffer API
Emilian Peevf4816702020-04-03 15:44:51 -07005063 camera_stream_buffer_t& buffer = outputBuffers->editItemAt(j);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07005064 buffer.stream = outputStream->asHalStream();
5065 buffer.buffer = nullptr;
Emilian Peevf4816702020-04-03 15:44:51 -07005066 buffer.status = CAMERA_BUFFER_STATUS_OK;
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07005067 buffer.acquire_fence = -1;
5068 buffer.release_fence = -1;
Emilian Peevf0348ae2021-01-13 13:39:45 -08005069 // Mark the output stream as unpreparable to block clients from calling
5070 // 'prepare' after this request reaches CameraHal and before the respective
5071 // buffers are requested.
5072 outputStream->markUnpreparable();
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07005073 } else {
5074 res = outputStream->getBuffer(&outputBuffers->editItemAt(j),
5075 waitDuration,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005076 captureRequest->mOutputSurfaces[streamId]);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07005077 if (res != OK) {
5078 // Can't get output buffer from gralloc queue - this could be due to
5079 // abandoned queue or other consumer misbehavior, so not a fatal
5080 // error
Yin-Chia Yeha1b56c82019-03-27 15:50:39 -07005081 ALOGV("RequestThread: Can't get output buffer, skipping request:"
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07005082 " %s (%d)", strerror(-res), res);
5083
5084 return TIMED_OUT;
5085 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005086 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08005087
5088 {
5089 sp<Camera3Device> parent = mParent.promote();
5090 if (parent != nullptr) {
5091 const String8& streamCameraId = outputStream->getPhysicalCameraId();
5092 for (const auto& settings : captureRequest->mSettingsList) {
5093 if ((streamCameraId.isEmpty() &&
5094 parent->getId() == settings.cameraId.c_str()) ||
5095 streamCameraId == settings.cameraId.c_str()) {
5096 outputStream->fireBufferRequestForFrameNumber(
5097 captureRequest->mResultExtras.frameNumber,
5098 settings.metadata);
5099 }
5100 }
5101 }
5102 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07005103
Shuzhen Wang5c22c152017-12-31 17:12:25 -08005104 String8 physicalCameraId = outputStream->getPhysicalCameraId();
Shuzhen Wang99080502021-03-07 21:08:20 -08005105 int32_t streamGroupId = outputStream->getHalStreamGroupId();
5106 if (streamGroupId != -1 && mGroupIdPhysicalCameraMap.count(streamGroupId) == 1) {
5107 requestedPhysicalCameras.insert(mGroupIdPhysicalCameraMap[streamGroupId]);
5108 } else if (!physicalCameraId.isEmpty()) {
5109 requestedPhysicalCameras.insert(std::set<String8>({physicalCameraId}));
Shuzhen Wang5c22c152017-12-31 17:12:25 -08005110 }
5111 halRequest->num_output_buffers++;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005112 }
5113 totalNumBuffers += halRequest->num_output_buffers;
5114
5115 // Log request in the in-flight queue
Shuzhen Wang4a472662017-02-26 23:29:04 -08005116 // If this request list is for constrained high speed recording (not
5117 // preview), and the current request is not the last one in the batch,
5118 // do not send callback to the app.
5119 bool hasCallback = true;
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07005120 if (batchedRequest && i != mNextRequests.size()-1) {
Shuzhen Wang4a472662017-02-26 23:29:04 -08005121 hasCallback = false;
5122 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01005123 bool isStillCapture = false;
Shuzhen Wang26abaf42018-08-28 15:41:20 -07005124 bool isZslCapture = false;
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08005125 const camera_metadata_t* settings = halRequest->settings;
5126 bool shouldUnlockSettings = false;
5127 if (settings == nullptr) {
5128 shouldUnlockSettings = true;
5129 settings = captureRequest->mSettingsList.begin()->metadata.getAndLock();
5130 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01005131 if (!mNextRequests[0].captureRequest->mSettingsList.begin()->metadata.isEmpty()) {
5132 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08005133 find_camera_metadata_ro_entry(settings, ANDROID_CONTROL_CAPTURE_INTENT, &e);
Emilian Peev9dd21f42018-08-03 13:39:29 +01005134 if ((e.count > 0) && (e.data.u8[0] == ANDROID_CONTROL_CAPTURE_INTENT_STILL_CAPTURE)) {
5135 isStillCapture = true;
5136 ATRACE_ASYNC_BEGIN("still capture", mNextRequests[i].halRequest.frame_number);
5137 }
Shuzhen Wang26abaf42018-08-28 15:41:20 -07005138
Emilian Peevaf8416e2021-02-04 17:52:43 -08005139 e = camera_metadata_ro_entry_t();
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08005140 find_camera_metadata_ro_entry(settings, ANDROID_CONTROL_ENABLE_ZSL, &e);
Shuzhen Wang26abaf42018-08-28 15:41:20 -07005141 if ((e.count > 0) && (e.data.u8[0] == ANDROID_CONTROL_ENABLE_ZSL_TRUE)) {
5142 isZslCapture = true;
5143 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01005144 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005145 res = parent->registerInFlight(halRequest->frame_number,
5146 totalNumBuffers, captureRequest->mResultExtras,
5147 /*hasInput*/halRequest->input_buffer != NULL,
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07005148 hasCallback,
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08005149 calculateMaxExpectedDuration(settings),
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005150 requestedPhysicalCameras, isStillCapture, isZslCapture,
5151 captureRequest->mRotateAndCropAuto, mPrevCameraIdsWithZoom,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005152 (mUseHalBufManager) ? uniqueSurfaceIdMap :
Shuzhen Wang316781a2020-08-18 18:11:01 -07005153 SurfaceMap{}, captureRequest->mRequestTimeNs);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005154 ALOGVV("%s: registered in flight requestId = %" PRId32 ", frameNumber = %" PRId64
5155 ", burstId = %" PRId32 ".",
5156 __FUNCTION__,
5157 captureRequest->mResultExtras.requestId, captureRequest->mResultExtras.frameNumber,
5158 captureRequest->mResultExtras.burstId);
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08005159
5160 if (shouldUnlockSettings) {
5161 captureRequest->mSettingsList.begin()->metadata.unlock(settings);
5162 }
5163
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005164 if (res != OK) {
5165 SET_ERR("RequestThread: Unable to register new in-flight request:"
5166 " %s (%d)", strerror(-res), res);
5167 return INVALID_OPERATION;
5168 }
5169 }
5170
5171 return OK;
5172}
5173
Igor Murashkin1e479c02013-09-06 16:55:14 -07005174CameraMetadata Camera3Device::RequestThread::getLatestRequest() const {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005175 ATRACE_CALL();
Igor Murashkin1e479c02013-09-06 16:55:14 -07005176 Mutex::Autolock al(mLatestRequestMutex);
5177
5178 ALOGV("RequestThread::%s", __FUNCTION__);
5179
5180 return mLatestRequest;
5181}
5182
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005183bool Camera3Device::RequestThread::isStreamPending(
5184 sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005185 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005186 Mutex::Autolock l(mRequestLock);
5187
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005188 for (const auto& nextRequest : mNextRequests) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005189 if (!nextRequest.submitted) {
5190 for (const auto& s : nextRequest.captureRequest->mOutputStreams) {
5191 if (stream == s) return true;
5192 }
5193 if (stream == nextRequest.captureRequest->mInputStream) return true;
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07005194 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07005195 }
5196
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005197 for (const auto& request : mRequestQueue) {
5198 for (const auto& s : request->mOutputStreams) {
5199 if (stream == s) return true;
5200 }
5201 if (stream == request->mInputStream) return true;
5202 }
5203
5204 for (const auto& request : mRepeatingRequests) {
5205 for (const auto& s : request->mOutputStreams) {
5206 if (stream == s) return true;
5207 }
5208 if (stream == request->mInputStream) return true;
5209 }
5210
5211 return false;
5212}
Jianing Weicb0652e2014-03-12 18:29:36 -07005213
Emilian Peev40ead602017-09-26 15:46:36 +01005214bool Camera3Device::RequestThread::isOutputSurfacePending(int streamId, size_t surfaceId) {
5215 ATRACE_CALL();
5216 Mutex::Autolock l(mRequestLock);
5217
5218 for (const auto& nextRequest : mNextRequests) {
5219 for (const auto& s : nextRequest.captureRequest->mOutputSurfaces) {
5220 if (s.first == streamId) {
5221 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
5222 if (it != s.second.end()) {
5223 return true;
5224 }
5225 }
5226 }
5227 }
5228
5229 for (const auto& request : mRequestQueue) {
5230 for (const auto& s : request->mOutputSurfaces) {
5231 if (s.first == streamId) {
5232 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
5233 if (it != s.second.end()) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005234 return true;
Emilian Peev40ead602017-09-26 15:46:36 +01005235 }
5236 }
5237 }
5238 }
5239
5240 for (const auto& request : mRepeatingRequests) {
5241 for (const auto& s : request->mOutputSurfaces) {
5242 if (s.first == streamId) {
5243 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
5244 if (it != s.second.end()) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005245 return true;
Emilian Peev40ead602017-09-26 15:46:36 +01005246 }
5247 }
5248 }
5249 }
5250
5251 return false;
5252}
5253
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07005254void Camera3Device::RequestThread::signalPipelineDrain(const std::vector<int>& streamIds) {
5255 if (!mUseHalBufManager) {
5256 ALOGE("%s called for camera device not supporting HAL buffer management", __FUNCTION__);
5257 return;
5258 }
5259
5260 Mutex::Autolock pl(mPauseLock);
5261 if (mPaused) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005262 mInterface->signalPipelineDrain(streamIds);
5263 return;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07005264 }
5265 // If request thread is still busy, wait until paused then notify HAL
5266 mNotifyPipelineDrain = true;
5267 mStreamIdsToBeDrained = streamIds;
5268}
5269
Yin-Chia Yehe52b8fa2020-07-28 00:17:58 -07005270void Camera3Device::RequestThread::resetPipelineDrain() {
5271 Mutex::Autolock pl(mPauseLock);
5272 mNotifyPipelineDrain = false;
5273 mStreamIdsToBeDrained.clear();
5274}
5275
Emilian Peevc0fe54c2020-03-11 14:05:07 -07005276void Camera3Device::RequestThread::clearPreviousRequest() {
5277 Mutex::Autolock l(mRequestLock);
5278 mPrevRequest.clear();
5279}
5280
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005281status_t Camera3Device::RequestThread::switchToOffline(
5282 const std::vector<int32_t>& streamsToKeep,
5283 /*out*/hardware::camera::device::V3_6::CameraOfflineSessionInfo* offlineSessionInfo,
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005284 /*out*/sp<hardware::camera::device::V3_6::ICameraOfflineSession>* offlineSession,
5285 /*out*/camera3::BufferRecords* bufferRecords) {
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005286 Mutex::Autolock l(mRequestLock);
5287 clearRepeatingRequestsLocked(/*lastFrameNumber*/nullptr);
5288
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005289 // Wait until request thread is fully stopped
5290 // TBD: check if request thread is being paused by other APIs (shouldn't be)
5291
5292 // We could also check for mRepeatingRequests.empty(), but the API interface
5293 // is serialized by Camera3Device::mInterfaceLock so no one should be able to submit any
5294 // new requests during the call; hence skip that check.
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005295 bool queueEmpty = mNextRequests.empty() && mRequestQueue.empty();
5296 while (!queueEmpty) {
5297 status_t res = mRequestSubmittedSignal.waitRelative(mRequestLock, kRequestSubmitTimeout);
5298 if (res == TIMED_OUT) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005299 ALOGE("%s: request thread failed to submit one request within timeout!", __FUNCTION__);
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005300 return res;
5301 } else if (res != OK) {
5302 ALOGE("%s: request thread failed to submit a request: %s (%d)!",
5303 __FUNCTION__, strerror(-res), res);
5304 return res;
5305 }
5306 queueEmpty = mNextRequests.empty() && mRequestQueue.empty();
5307 }
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005308
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005309 return mInterface->switchToOffline(
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005310 streamsToKeep, offlineSessionInfo, offlineSession, bufferRecords);
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005311}
5312
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005313status_t Camera3Device::RequestThread::setRotateAndCropAutoBehavior(
5314 camera_metadata_enum_android_scaler_rotate_and_crop_t rotateAndCropValue) {
5315 ATRACE_CALL();
5316 Mutex::Autolock l(mTriggerMutex);
5317 if (rotateAndCropValue == ANDROID_SCALER_ROTATE_AND_CROP_AUTO) {
5318 return BAD_VALUE;
5319 }
5320 mRotateAndCropOverride = rotateAndCropValue;
5321 return OK;
5322}
5323
Eino-Ville Talvala11afe4f2021-05-27 14:45:31 -07005324status_t Camera3Device::RequestThread::setCameraMute(int32_t muteMode) {
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005325 ATRACE_CALL();
5326 Mutex::Autolock l(mTriggerMutex);
Eino-Ville Talvala11afe4f2021-05-27 14:45:31 -07005327 if (muteMode != mCameraMute) {
5328 mCameraMute = muteMode;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005329 mCameraMuteChanged = true;
5330 }
5331 return OK;
5332}
5333
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07005334nsecs_t Camera3Device::getExpectedInFlightDuration() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005335 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005336 std::lock_guard<std::mutex> l(mInFlightLock);
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07005337 return mExpectedInflightDuration > kMinInflightDuration ?
5338 mExpectedInflightDuration : kMinInflightDuration;
5339}
5340
Emilian Peevaebbe412018-01-15 13:53:24 +00005341void Camera3Device::RequestThread::cleanupPhysicalSettings(sp<CaptureRequest> request,
Emilian Peevf4816702020-04-03 15:44:51 -07005342 camera_capture_request_t *halRequest) {
Emilian Peevaebbe412018-01-15 13:53:24 +00005343 if ((request == nullptr) || (halRequest == nullptr)) {
5344 ALOGE("%s: Invalid request!", __FUNCTION__);
5345 return;
5346 }
5347
5348 if (halRequest->num_physcam_settings > 0) {
5349 if (halRequest->physcam_id != nullptr) {
5350 delete [] halRequest->physcam_id;
5351 halRequest->physcam_id = nullptr;
5352 }
5353 if (halRequest->physcam_settings != nullptr) {
5354 auto it = ++(request->mSettingsList.begin());
5355 size_t i = 0;
5356 for (; it != request->mSettingsList.end(); it++, i++) {
5357 it->metadata.unlock(halRequest->physcam_settings[i]);
5358 }
5359 delete [] halRequest->physcam_settings;
5360 halRequest->physcam_settings = nullptr;
5361 }
5362 }
5363}
5364
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005365void Camera3Device::RequestThread::cleanUpFailedRequests(bool sendRequestError) {
5366 if (mNextRequests.empty()) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005367 return;
5368 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005369
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005370 for (auto& nextRequest : mNextRequests) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005371 // Skip the ones that have been submitted successfully.
5372 if (nextRequest.submitted) {
5373 continue;
5374 }
5375
5376 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
Emilian Peevf4816702020-04-03 15:44:51 -07005377 camera_capture_request_t* halRequest = &nextRequest.halRequest;
5378 Vector<camera_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005379
5380 if (halRequest->settings != NULL) {
Emilian Peevaebbe412018-01-15 13:53:24 +00005381 captureRequest->mSettingsList.begin()->metadata.unlock(halRequest->settings);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005382 }
5383
Emilian Peevaebbe412018-01-15 13:53:24 +00005384 cleanupPhysicalSettings(captureRequest, halRequest);
5385
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005386 if (captureRequest->mInputStream != NULL) {
Emilian Peevf4816702020-04-03 15:44:51 -07005387 captureRequest->mInputBuffer.status = CAMERA_BUFFER_STATUS_ERROR;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005388 captureRequest->mInputStream->returnInputBuffer(captureRequest->mInputBuffer);
5389 }
5390
Yin-Chia Yeh21cb47b2019-01-18 15:08:17 -08005391 // No output buffer can be returned when using HAL buffer manager
5392 if (!mUseHalBufManager) {
5393 for (size_t i = 0; i < halRequest->num_output_buffers; i++) {
5394 //Buffers that failed processing could still have
5395 //valid acquire fence.
5396 int acquireFence = (*outputBuffers)[i].acquire_fence;
5397 if (0 <= acquireFence) {
5398 close(acquireFence);
5399 outputBuffers->editItemAt(i).acquire_fence = -1;
5400 }
Emilian Peevf4816702020-04-03 15:44:51 -07005401 outputBuffers->editItemAt(i).status = CAMERA_BUFFER_STATUS_ERROR;
Yin-Chia Yeh21cb47b2019-01-18 15:08:17 -08005402 captureRequest->mOutputStreams.editItemAt(i)->returnBuffer((*outputBuffers)[i], 0,
5403 /*timestampIncreasing*/true, std::vector<size_t> (),
5404 captureRequest->mResultExtras.frameNumber);
Emilian Peevc58cf4c2017-05-11 17:23:41 +01005405 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005406 }
5407
5408 if (sendRequestError) {
5409 Mutex::Autolock l(mRequestLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005410 sp<NotificationListener> listener = mListener.promote();
5411 if (listener != NULL) {
5412 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08005413 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005414 captureRequest->mResultExtras);
5415 }
5416 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07005417
5418 // Remove yet-to-be submitted inflight request from inflightMap
5419 {
5420 sp<Camera3Device> parent = mParent.promote();
5421 if (parent != NULL) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005422 std::lock_guard<std::mutex> l(parent->mInFlightLock);
Shuzhen Wangcadb3302016-11-04 14:17:56 -07005423 ssize_t idx = parent->mInFlightMap.indexOfKey(captureRequest->mResultExtras.frameNumber);
5424 if (idx >= 0) {
5425 ALOGV("%s: Remove inflight request from queue: frameNumber %" PRId64,
5426 __FUNCTION__, captureRequest->mResultExtras.frameNumber);
5427 parent->removeInFlightMapEntryLocked(idx);
5428 }
5429 }
5430 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005431 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07005432
5433 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005434 mNextRequests.clear();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005435}
5436
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005437void Camera3Device::RequestThread::waitForNextRequestBatch() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005438 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005439 // Optimized a bit for the simple steady-state case (single repeating
5440 // request), to avoid putting that request in the queue temporarily.
5441 Mutex::Autolock l(mRequestLock);
5442
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005443 assert(mNextRequests.empty());
5444
5445 NextRequest nextRequest;
5446 nextRequest.captureRequest = waitForNextRequestLocked();
5447 if (nextRequest.captureRequest == nullptr) {
5448 return;
5449 }
5450
Emilian Peevf4816702020-04-03 15:44:51 -07005451 nextRequest.halRequest = camera_capture_request_t();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005452 nextRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005453 mNextRequests.add(nextRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005454
5455 // Wait for additional requests
5456 const size_t batchSize = nextRequest.captureRequest->mBatchSize;
5457
5458 for (size_t i = 1; i < batchSize; i++) {
5459 NextRequest additionalRequest;
5460 additionalRequest.captureRequest = waitForNextRequestLocked();
5461 if (additionalRequest.captureRequest == nullptr) {
5462 break;
5463 }
5464
Emilian Peevf4816702020-04-03 15:44:51 -07005465 additionalRequest.halRequest = camera_capture_request_t();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005466 additionalRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005467 mNextRequests.add(additionalRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005468 }
5469
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005470 if (mNextRequests.size() < batchSize) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08005471 ALOGE("RequestThread: only get %zu out of %zu requests. Skipping requests.",
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005472 mNextRequests.size(), batchSize);
5473 cleanUpFailedRequests(/*sendRequestError*/true);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005474 }
5475
5476 return;
5477}
5478
5479sp<Camera3Device::CaptureRequest>
5480 Camera3Device::RequestThread::waitForNextRequestLocked() {
5481 status_t res;
5482 sp<CaptureRequest> nextRequest;
5483
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005484 while (mRequestQueue.empty()) {
5485 if (!mRepeatingRequests.empty()) {
5486 // Always atomically enqueue all requests in a repeating request
5487 // list. Guarantees a complete in-sequence set of captures to
5488 // application.
5489 const RequestList &requests = mRepeatingRequests;
Shuzhen Wang316781a2020-08-18 18:11:01 -07005490 if (mFirstRepeating) {
5491 mFirstRepeating = false;
5492 } else {
5493 for (auto& request : requests) {
5494 // For repeating requests, override timestamp request using
5495 // the time a request is inserted into the request queue,
5496 // because the original repeating request will have an old
5497 // fixed timestamp.
5498 request->mRequestTimeNs = systemTime();
5499 }
5500 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005501 RequestList::const_iterator firstRequest =
5502 requests.begin();
5503 nextRequest = *firstRequest;
5504 mRequestQueue.insert(mRequestQueue.end(),
5505 ++firstRequest,
5506 requests.end());
5507 // No need to wait any longer
Jianing Weicb0652e2014-03-12 18:29:36 -07005508
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005509 mRepeatingLastFrameNumber = mFrameNumber + requests.size() - 1;
Jianing Weicb0652e2014-03-12 18:29:36 -07005510
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005511 break;
5512 }
5513
5514 res = mRequestSignal.waitRelative(mRequestLock, kRequestTimeout);
5515
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005516 if ((mRequestQueue.empty() && mRepeatingRequests.empty()) ||
5517 exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005518 Mutex::Autolock pl(mPauseLock);
5519 if (mPaused == false) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005520 ALOGV("%s: RequestThread: Going idle", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005521 mPaused = true;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07005522 if (mNotifyPipelineDrain) {
5523 mInterface->signalPipelineDrain(mStreamIdsToBeDrained);
5524 mNotifyPipelineDrain = false;
5525 mStreamIdsToBeDrained.clear();
5526 }
Yin-Chia Yehc300a072019-02-13 14:56:57 -08005527 // Let the tracker know
5528 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5529 if (statusTracker != 0) {
5530 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
5531 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005532 sp<Camera3Device> parent = mParent.promote();
5533 if (parent != nullptr) {
5534 parent->mRequestBufferSM.onRequestThreadPaused();
5535 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005536 }
5537 // Stop waiting for now and let thread management happen
5538 return NULL;
5539 }
5540 }
5541
5542 if (nextRequest == NULL) {
5543 // Don't have a repeating request already in hand, so queue
5544 // must have an entry now.
5545 RequestList::iterator firstRequest =
5546 mRequestQueue.begin();
5547 nextRequest = *firstRequest;
5548 mRequestQueue.erase(firstRequest);
Shuzhen Wang9d066012016-09-30 11:30:20 -07005549 if (mRequestQueue.empty() && !nextRequest->mRepeating) {
5550 sp<NotificationListener> listener = mListener.promote();
5551 if (listener != NULL) {
5552 listener->notifyRequestQueueEmpty();
5553 }
5554 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005555 }
5556
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005557 // In case we've been unpaused by setPaused clearing mDoPause, need to
5558 // update internal pause state (capture/setRepeatingRequest unpause
5559 // directly).
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005560 Mutex::Autolock pl(mPauseLock);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005561 if (mPaused) {
5562 ALOGV("%s: RequestThread: Unpaused", __FUNCTION__);
5563 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5564 if (statusTracker != 0) {
5565 statusTracker->markComponentActive(mStatusId);
5566 }
5567 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005568 mPaused = false;
5569
5570 // Check if we've reconfigured since last time, and reset the preview
5571 // request if so. Can't use 'NULL request == repeat' across configure calls.
5572 if (mReconfigured) {
5573 mPrevRequest.clear();
5574 mReconfigured = false;
5575 }
5576
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005577 if (nextRequest != NULL) {
5578 nextRequest->mResultExtras.frameNumber = mFrameNumber++;
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07005579 nextRequest->mResultExtras.afTriggerId = mCurrentAfTriggerId;
5580 nextRequest->mResultExtras.precaptureTriggerId = mCurrentPreCaptureTriggerId;
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07005581
5582 // Since RequestThread::clear() removes buffers from the input stream,
5583 // get the right buffer here before unlocking mRequestLock
5584 if (nextRequest->mInputStream != NULL) {
Shuzhen Wang83bff122020-11-20 15:51:39 -08005585 res = nextRequest->mInputStream->getInputBuffer(&nextRequest->mInputBuffer,
5586 &nextRequest->mInputBufferSize);
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07005587 if (res != OK) {
5588 // Can't get input buffer from gralloc queue - this could be due to
5589 // disconnected queue or other producer misbehavior, so not a fatal
5590 // error
5591 ALOGE("%s: Can't get input buffer, skipping request:"
5592 " %s (%d)", __FUNCTION__, strerror(-res), res);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005593
5594 sp<NotificationListener> listener = mListener.promote();
5595 if (listener != NULL) {
5596 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08005597 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07005598 nextRequest->mResultExtras);
5599 }
5600 return NULL;
5601 }
5602 }
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005603 }
Chien-Yu Chend196d612015-06-22 19:49:01 -07005604
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005605 return nextRequest;
5606}
5607
5608bool Camera3Device::RequestThread::waitIfPaused() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005609 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005610 status_t res;
5611 Mutex::Autolock l(mPauseLock);
5612 while (mDoPause) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005613 if (mPaused == false) {
5614 mPaused = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005615 ALOGV("%s: RequestThread: Paused", __FUNCTION__);
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07005616 if (mNotifyPipelineDrain) {
5617 mInterface->signalPipelineDrain(mStreamIdsToBeDrained);
5618 mNotifyPipelineDrain = false;
5619 mStreamIdsToBeDrained.clear();
5620 }
Yin-Chia Yehc300a072019-02-13 14:56:57 -08005621 // Let the tracker know
5622 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5623 if (statusTracker != 0) {
5624 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
5625 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005626 sp<Camera3Device> parent = mParent.promote();
5627 if (parent != nullptr) {
5628 parent->mRequestBufferSM.onRequestThreadPaused();
5629 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005630 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005631
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005632 res = mDoPauseSignal.waitRelative(mPauseLock, kRequestTimeout);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005633 if (res == TIMED_OUT || exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005634 return true;
5635 }
5636 }
5637 // We don't set mPaused to false here, because waitForNextRequest needs
5638 // to further manage the paused state in case of starvation.
5639 return false;
5640}
5641
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005642void Camera3Device::RequestThread::unpauseForNewRequests() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005643 ATRACE_CALL();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005644 // With work to do, mark thread as unpaused.
5645 // If paused by request (setPaused), don't resume, to avoid
5646 // extra signaling/waiting overhead to waitUntilPaused
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005647 mRequestSignal.signal();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005648 Mutex::Autolock p(mPauseLock);
5649 if (!mDoPause) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005650 ALOGV("%s: RequestThread: Going active", __FUNCTION__);
5651 if (mPaused) {
5652 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5653 if (statusTracker != 0) {
5654 statusTracker->markComponentActive(mStatusId);
5655 }
5656 }
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005657 mPaused = false;
5658 }
5659}
5660
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07005661void Camera3Device::RequestThread::setErrorState(const char *fmt, ...) {
5662 sp<Camera3Device> parent = mParent.promote();
5663 if (parent != NULL) {
5664 va_list args;
5665 va_start(args, fmt);
5666
5667 parent->setErrorStateV(fmt, args);
5668
5669 va_end(args);
5670 }
5671}
5672
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005673status_t Camera3Device::RequestThread::insertTriggers(
5674 const sp<CaptureRequest> &request) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005675 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005676 Mutex::Autolock al(mTriggerMutex);
5677
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07005678 sp<Camera3Device> parent = mParent.promote();
5679 if (parent == NULL) {
5680 CLOGE("RequestThread: Parent is gone");
5681 return DEAD_OBJECT;
5682 }
5683
Emilian Peevaebbe412018-01-15 13:53:24 +00005684 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005685 size_t count = mTriggerMap.size();
5686
5687 for (size_t i = 0; i < count; ++i) {
5688 RequestTrigger trigger = mTriggerMap.valueAt(i);
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005689 uint32_t tag = trigger.metadataTag;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07005690
5691 if (tag == ANDROID_CONTROL_AF_TRIGGER_ID || tag == ANDROID_CONTROL_AE_PRECAPTURE_ID) {
5692 bool isAeTrigger = (trigger.metadataTag == ANDROID_CONTROL_AE_PRECAPTURE_ID);
5693 uint32_t triggerId = static_cast<uint32_t>(trigger.entryValue);
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07005694 if (isAeTrigger) {
5695 request->mResultExtras.precaptureTriggerId = triggerId;
5696 mCurrentPreCaptureTriggerId = triggerId;
5697 } else {
5698 request->mResultExtras.afTriggerId = triggerId;
5699 mCurrentAfTriggerId = triggerId;
5700 }
Emilian Peev7e25e5e2017-04-07 15:48:49 +01005701 continue;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07005702 }
5703
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005704 camera_metadata_entry entry = metadata.find(tag);
5705
5706 if (entry.count > 0) {
5707 /**
5708 * Already has an entry for this trigger in the request.
5709 * Rewrite it with our requested trigger value.
5710 */
5711 RequestTrigger oldTrigger = trigger;
5712
5713 oldTrigger.entryValue = entry.data.u8[0];
5714
5715 mTriggerReplacedMap.add(tag, oldTrigger);
5716 } else {
5717 /**
5718 * More typical, no trigger entry, so we just add it
5719 */
5720 mTriggerRemovedMap.add(tag, trigger);
5721 }
5722
5723 status_t res;
5724
5725 switch (trigger.getTagType()) {
5726 case TYPE_BYTE: {
5727 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
5728 res = metadata.update(tag,
5729 &entryValue,
5730 /*count*/1);
5731 break;
5732 }
5733 case TYPE_INT32:
5734 res = metadata.update(tag,
5735 &trigger.entryValue,
5736 /*count*/1);
5737 break;
5738 default:
5739 ALOGE("%s: Type not supported: 0x%x",
5740 __FUNCTION__,
5741 trigger.getTagType());
5742 return INVALID_OPERATION;
5743 }
5744
5745 if (res != OK) {
5746 ALOGE("%s: Failed to update request metadata with trigger tag %s"
5747 ", value %d", __FUNCTION__, trigger.getTagName(),
5748 trigger.entryValue);
5749 return res;
5750 }
5751
5752 ALOGV("%s: Mixed in trigger %s, value %d", __FUNCTION__,
5753 trigger.getTagName(),
5754 trigger.entryValue);
5755 }
5756
5757 mTriggerMap.clear();
5758
5759 return count;
5760}
5761
5762status_t Camera3Device::RequestThread::removeTriggers(
5763 const sp<CaptureRequest> &request) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005764 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005765 Mutex::Autolock al(mTriggerMutex);
5766
Emilian Peevaebbe412018-01-15 13:53:24 +00005767 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005768
5769 /**
5770 * Replace all old entries with their old values.
5771 */
5772 for (size_t i = 0; i < mTriggerReplacedMap.size(); ++i) {
5773 RequestTrigger trigger = mTriggerReplacedMap.valueAt(i);
5774
5775 status_t res;
5776
5777 uint32_t tag = trigger.metadataTag;
5778 switch (trigger.getTagType()) {
5779 case TYPE_BYTE: {
5780 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
5781 res = metadata.update(tag,
5782 &entryValue,
5783 /*count*/1);
5784 break;
5785 }
5786 case TYPE_INT32:
5787 res = metadata.update(tag,
5788 &trigger.entryValue,
5789 /*count*/1);
5790 break;
5791 default:
5792 ALOGE("%s: Type not supported: 0x%x",
5793 __FUNCTION__,
5794 trigger.getTagType());
5795 return INVALID_OPERATION;
5796 }
5797
5798 if (res != OK) {
5799 ALOGE("%s: Failed to restore request metadata with trigger tag %s"
5800 ", trigger value %d", __FUNCTION__,
5801 trigger.getTagName(), trigger.entryValue);
5802 return res;
5803 }
5804 }
5805 mTriggerReplacedMap.clear();
5806
5807 /**
5808 * Remove all new entries.
5809 */
5810 for (size_t i = 0; i < mTriggerRemovedMap.size(); ++i) {
5811 RequestTrigger trigger = mTriggerRemovedMap.valueAt(i);
5812 status_t res = metadata.erase(trigger.metadataTag);
5813
5814 if (res != OK) {
5815 ALOGE("%s: Failed to erase metadata with trigger tag %s"
5816 ", trigger value %d", __FUNCTION__,
5817 trigger.getTagName(), trigger.entryValue);
5818 return res;
5819 }
5820 }
5821 mTriggerRemovedMap.clear();
5822
5823 return OK;
5824}
5825
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04005826status_t Camera3Device::RequestThread::addFakeTriggerIds(
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005827 const sp<CaptureRequest> &request) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08005828 // Trigger ID 0 had special meaning in the HAL2 spec, so avoid it here
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04005829 static const int32_t fakeTriggerId = 1;
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005830 status_t res;
5831
Emilian Peevaebbe412018-01-15 13:53:24 +00005832 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005833
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04005834 // If AF trigger is active, insert a fake AF trigger ID if none already
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005835 // exists
5836 camera_metadata_entry afTrigger = metadata.find(ANDROID_CONTROL_AF_TRIGGER);
5837 camera_metadata_entry afId = metadata.find(ANDROID_CONTROL_AF_TRIGGER_ID);
5838 if (afTrigger.count > 0 &&
5839 afTrigger.data.u8[0] != ANDROID_CONTROL_AF_TRIGGER_IDLE &&
5840 afId.count == 0) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04005841 res = metadata.update(ANDROID_CONTROL_AF_TRIGGER_ID, &fakeTriggerId, 1);
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005842 if (res != OK) return res;
5843 }
5844
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04005845 // If AE precapture trigger is active, insert a fake precapture trigger ID
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005846 // if none already exists
5847 camera_metadata_entry pcTrigger =
5848 metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER);
5849 camera_metadata_entry pcId = metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_ID);
5850 if (pcTrigger.count > 0 &&
5851 pcTrigger.data.u8[0] != ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_IDLE &&
5852 pcId.count == 0) {
5853 res = metadata.update(ANDROID_CONTROL_AE_PRECAPTURE_ID,
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04005854 &fakeTriggerId, 1);
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005855 if (res != OK) return res;
5856 }
5857
5858 return OK;
5859}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005860
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005861bool Camera3Device::RequestThread::overrideAutoRotateAndCrop(
5862 const sp<CaptureRequest> &request) {
5863 ATRACE_CALL();
5864
5865 if (request->mRotateAndCropAuto) {
5866 Mutex::Autolock l(mTriggerMutex);
5867 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
5868
5869 auto rotateAndCropEntry = metadata.find(ANDROID_SCALER_ROTATE_AND_CROP);
5870 if (rotateAndCropEntry.count > 0) {
5871 if (rotateAndCropEntry.data.u8[0] == mRotateAndCropOverride) {
5872 return false;
5873 } else {
5874 rotateAndCropEntry.data.u8[0] = mRotateAndCropOverride;
5875 return true;
5876 }
5877 } else {
5878 uint8_t rotateAndCrop_u8 = mRotateAndCropOverride;
5879 metadata.update(ANDROID_SCALER_ROTATE_AND_CROP,
5880 &rotateAndCrop_u8, 1);
5881 return true;
5882 }
5883 }
5884 return false;
5885}
5886
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005887bool Camera3Device::RequestThread::overrideTestPattern(
5888 const sp<CaptureRequest> &request) {
5889 ATRACE_CALL();
5890
Eino-Ville Talvala1646c3c2021-07-29 13:48:40 -07005891 if (!mSupportCameraMute) return false;
Eino-Ville Talvalac2459842021-07-22 16:36:36 -07005892
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005893 Mutex::Autolock l(mTriggerMutex);
5894
5895 bool changed = false;
5896
5897 int32_t testPatternMode = request->mOriginalTestPatternMode;
5898 int32_t testPatternData[4] = {
5899 request->mOriginalTestPatternData[0],
5900 request->mOriginalTestPatternData[1],
5901 request->mOriginalTestPatternData[2],
5902 request->mOriginalTestPatternData[3]
5903 };
5904
Eino-Ville Talvala11afe4f2021-05-27 14:45:31 -07005905 if (mCameraMute != ANDROID_SENSOR_TEST_PATTERN_MODE_OFF) {
5906 testPatternMode = mCameraMute;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005907 testPatternData[0] = 0;
5908 testPatternData[1] = 0;
5909 testPatternData[2] = 0;
5910 testPatternData[3] = 0;
5911 }
5912
5913 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
5914
5915 auto testPatternEntry = metadata.find(ANDROID_SENSOR_TEST_PATTERN_MODE);
5916 if (testPatternEntry.count > 0) {
5917 if (testPatternEntry.data.i32[0] != testPatternMode) {
5918 testPatternEntry.data.i32[0] = testPatternMode;
5919 changed = true;
5920 }
5921 } else {
5922 metadata.update(ANDROID_SENSOR_TEST_PATTERN_MODE,
5923 &testPatternMode, 1);
5924 changed = true;
5925 }
5926
5927 auto testPatternColor = metadata.find(ANDROID_SENSOR_TEST_PATTERN_DATA);
Eino-Ville Talvalac2459842021-07-22 16:36:36 -07005928 if (testPatternColor.count >= 4) {
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005929 for (size_t i = 0; i < 4; i++) {
Eino-Ville Talvalac2459842021-07-22 16:36:36 -07005930 if (testPatternColor.data.i32[i] != testPatternData[i]) {
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005931 testPatternColor.data.i32[i] = testPatternData[i];
5932 changed = true;
5933 }
5934 }
5935 } else {
5936 metadata.update(ANDROID_SENSOR_TEST_PATTERN_DATA,
Eino-Ville Talvalac2459842021-07-22 16:36:36 -07005937 testPatternData, 4);
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005938 changed = true;
5939 }
5940
5941 return changed;
5942}
5943
Cliff Wuc2ad9c82021-04-21 00:58:58 +08005944status_t Camera3Device::RequestThread::setHalInterface(
5945 sp<HalInterface> newHalInterface) {
5946 if (newHalInterface.get() == nullptr) {
5947 ALOGE("%s: The newHalInterface does not exist!", __FUNCTION__);
5948 return DEAD_OBJECT;
5949 }
5950
5951 mInterface = newHalInterface;
5952
5953 return OK;
5954}
5955
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005956/**
5957 * PreparerThread inner class methods
5958 */
5959
5960Camera3Device::PreparerThread::PreparerThread() :
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07005961 Thread(/*canCallJava*/false), mListener(nullptr),
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005962 mActive(false), mCancelNow(false), mCurrentMaxCount(0), mCurrentPrepareComplete(false) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005963}
5964
5965Camera3Device::PreparerThread::~PreparerThread() {
5966 Thread::requestExitAndWait();
5967 if (mCurrentStream != nullptr) {
5968 mCurrentStream->cancelPrepare();
5969 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
5970 mCurrentStream.clear();
5971 }
5972 clear();
5973}
5974
Ruben Brunkc78ac262015-08-13 17:58:46 -07005975status_t Camera3Device::PreparerThread::prepare(int maxCount, sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005976 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005977 status_t res;
5978
5979 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005980 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005981
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07005982 res = stream->startPrepare(maxCount, true /*blockRequest*/);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005983 if (res == OK) {
5984 // No preparation needed, fire listener right off
5985 ALOGV("%s: Stream %d already prepared", __FUNCTION__, stream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005986 if (listener != NULL) {
5987 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005988 }
5989 return OK;
5990 } else if (res != NOT_ENOUGH_DATA) {
5991 return res;
5992 }
5993
5994 // Need to prepare, start up thread if necessary
5995 if (!mActive) {
5996 // mRunning will change to false before the thread fully shuts down, so wait to be sure it
5997 // isn't running
5998 Thread::requestExitAndWait();
5999 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
6000 if (res != OK) {
6001 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__, res, strerror(-res));
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006002 if (listener != NULL) {
6003 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006004 }
6005 return res;
6006 }
6007 mCancelNow = false;
6008 mActive = true;
6009 ALOGV("%s: Preparer stream started", __FUNCTION__);
6010 }
6011
6012 // queue up the work
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006013 mPendingStreams.emplace(maxCount, stream);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006014 ALOGV("%s: Stream %d queued for preparing", __FUNCTION__, stream->getId());
6015
6016 return OK;
6017}
6018
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006019void Camera3Device::PreparerThread::pause() {
6020 ATRACE_CALL();
6021
6022 Mutex::Autolock l(mLock);
6023
6024 std::unordered_map<int, sp<camera3::Camera3StreamInterface> > pendingStreams;
6025 pendingStreams.insert(mPendingStreams.begin(), mPendingStreams.end());
6026 sp<camera3::Camera3StreamInterface> currentStream = mCurrentStream;
6027 int currentMaxCount = mCurrentMaxCount;
6028 mPendingStreams.clear();
6029 mCancelNow = true;
6030 while (mActive) {
6031 auto res = mThreadActiveSignal.waitRelative(mLock, kActiveTimeout);
6032 if (res == TIMED_OUT) {
6033 ALOGE("%s: Timed out waiting on prepare thread!", __FUNCTION__);
6034 return;
6035 } else if (res != OK) {
6036 ALOGE("%s: Encountered an error: %d waiting on prepare thread!", __FUNCTION__, res);
6037 return;
6038 }
6039 }
6040
6041 //Check whether the prepare thread was able to complete the current
6042 //stream. In case work is still pending emplace it along with the rest
6043 //of the streams in the pending list.
6044 if (currentStream != nullptr) {
6045 if (!mCurrentPrepareComplete) {
6046 pendingStreams.emplace(currentMaxCount, currentStream);
6047 }
6048 }
6049
6050 mPendingStreams.insert(pendingStreams.begin(), pendingStreams.end());
6051 for (const auto& it : mPendingStreams) {
6052 it.second->cancelPrepare();
6053 }
6054}
6055
6056status_t Camera3Device::PreparerThread::resume() {
6057 ATRACE_CALL();
6058 status_t res;
6059
6060 Mutex::Autolock l(mLock);
6061 sp<NotificationListener> listener = mListener.promote();
6062
6063 if (mActive) {
6064 ALOGE("%s: Trying to resume an already active prepare thread!", __FUNCTION__);
6065 return NO_INIT;
6066 }
6067
6068 auto it = mPendingStreams.begin();
6069 for (; it != mPendingStreams.end();) {
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07006070 res = it->second->startPrepare(it->first, true /*blockRequest*/);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006071 if (res == OK) {
6072 if (listener != NULL) {
6073 listener->notifyPrepared(it->second->getId());
6074 }
6075 it = mPendingStreams.erase(it);
6076 } else if (res != NOT_ENOUGH_DATA) {
6077 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__,
6078 res, strerror(-res));
6079 it = mPendingStreams.erase(it);
6080 } else {
6081 it++;
6082 }
6083 }
6084
6085 if (mPendingStreams.empty()) {
6086 return OK;
6087 }
6088
6089 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
6090 if (res != OK) {
6091 ALOGE("%s: Unable to start preparer stream: %d (%s)",
6092 __FUNCTION__, res, strerror(-res));
6093 return res;
6094 }
6095 mCancelNow = false;
6096 mActive = true;
6097 ALOGV("%s: Preparer stream started", __FUNCTION__);
6098
6099 return OK;
6100}
6101
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006102status_t Camera3Device::PreparerThread::clear() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07006103 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006104 Mutex::Autolock l(mLock);
6105
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006106 for (const auto& it : mPendingStreams) {
6107 it.second->cancelPrepare();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006108 }
6109 mPendingStreams.clear();
6110 mCancelNow = true;
6111
6112 return OK;
6113}
6114
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006115void Camera3Device::PreparerThread::setNotificationListener(wp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07006116 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006117 Mutex::Autolock l(mLock);
6118 mListener = listener;
6119}
6120
6121bool Camera3Device::PreparerThread::threadLoop() {
6122 status_t res;
6123 {
6124 Mutex::Autolock l(mLock);
6125 if (mCurrentStream == nullptr) {
6126 // End thread if done with work
6127 if (mPendingStreams.empty()) {
6128 ALOGV("%s: Preparer stream out of work", __FUNCTION__);
6129 // threadLoop _must not_ re-acquire mLock after it sets mActive to false; would
6130 // cause deadlock with prepare()'s requestExitAndWait triggered by !mActive.
6131 mActive = false;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006132 mThreadActiveSignal.signal();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006133 return false;
6134 }
6135
6136 // Get next stream to prepare
6137 auto it = mPendingStreams.begin();
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006138 mCurrentStream = it->second;
6139 mCurrentMaxCount = it->first;
6140 mCurrentPrepareComplete = false;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006141 mPendingStreams.erase(it);
6142 ATRACE_ASYNC_BEGIN("stream prepare", mCurrentStream->getId());
6143 ALOGV("%s: Preparing stream %d", __FUNCTION__, mCurrentStream->getId());
6144 } else if (mCancelNow) {
6145 mCurrentStream->cancelPrepare();
6146 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
6147 ALOGV("%s: Cancelling stream %d prepare", __FUNCTION__, mCurrentStream->getId());
6148 mCurrentStream.clear();
6149 mCancelNow = false;
6150 return true;
6151 }
6152 }
6153
6154 res = mCurrentStream->prepareNextBuffer();
6155 if (res == NOT_ENOUGH_DATA) return true;
6156 if (res != OK) {
6157 // Something bad happened; try to recover by cancelling prepare and
6158 // signalling listener anyway
6159 ALOGE("%s: Stream %d returned error %d (%s) during prepare", __FUNCTION__,
6160 mCurrentStream->getId(), res, strerror(-res));
6161 mCurrentStream->cancelPrepare();
6162 }
6163
6164 // This stream has finished, notify listener
6165 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006166 sp<NotificationListener> listener = mListener.promote();
6167 if (listener != NULL) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006168 ALOGV("%s: Stream %d prepare done, signaling listener", __FUNCTION__,
6169 mCurrentStream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006170 listener->notifyPrepared(mCurrentStream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006171 }
6172
6173 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
6174 mCurrentStream.clear();
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006175 mCurrentPrepareComplete = true;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006176
6177 return true;
6178}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07006179
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006180status_t Camera3Device::RequestBufferStateMachine::initialize(
6181 sp<camera3::StatusTracker> statusTracker) {
6182 if (statusTracker == nullptr) {
6183 ALOGE("%s: statusTracker is null", __FUNCTION__);
6184 return BAD_VALUE;
6185 }
6186
6187 std::lock_guard<std::mutex> lock(mLock);
6188 mStatusTracker = statusTracker;
Yin-Chia Yeh87b3ec02019-06-03 10:44:39 -07006189 mRequestBufferStatusId = statusTracker->addComponent("BufferRequestSM");
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006190 return OK;
6191}
6192
6193bool Camera3Device::RequestBufferStateMachine::startRequestBuffer() {
6194 std::lock_guard<std::mutex> lock(mLock);
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08006195 if (mStatus == RB_STATUS_READY || mStatus == RB_STATUS_PENDING_STOP) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006196 mRequestBufferOngoing = true;
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08006197 notifyTrackerLocked(/*active*/true);
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006198 return true;
6199 }
6200 return false;
6201}
6202
6203void Camera3Device::RequestBufferStateMachine::endRequestBuffer() {
6204 std::lock_guard<std::mutex> lock(mLock);
6205 if (!mRequestBufferOngoing) {
6206 ALOGE("%s called without a successful startRequestBuffer call first!", __FUNCTION__);
6207 return;
6208 }
6209 mRequestBufferOngoing = false;
6210 if (mStatus == RB_STATUS_PENDING_STOP) {
6211 checkSwitchToStopLocked();
6212 }
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08006213 notifyTrackerLocked(/*active*/false);
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006214}
6215
6216void Camera3Device::RequestBufferStateMachine::onStreamsConfigured() {
6217 std::lock_guard<std::mutex> lock(mLock);
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006218 mSwitchedToOffline = false;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006219 mStatus = RB_STATUS_READY;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006220 return;
6221}
6222
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08006223void Camera3Device::RequestBufferStateMachine::onSubmittingRequest() {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006224 std::lock_guard<std::mutex> lock(mLock);
6225 mRequestThreadPaused = false;
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08006226 // inflight map register actually happens in prepareHalRequest now, but it is close enough
6227 // approximation.
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006228 mInflightMapEmpty = false;
6229 if (mStatus == RB_STATUS_STOPPED) {
6230 mStatus = RB_STATUS_READY;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006231 }
6232 return;
6233}
6234
6235void Camera3Device::RequestBufferStateMachine::onRequestThreadPaused() {
6236 std::lock_guard<std::mutex> lock(mLock);
6237 mRequestThreadPaused = true;
6238 if (mStatus == RB_STATUS_PENDING_STOP) {
6239 checkSwitchToStopLocked();
6240 }
6241 return;
6242}
6243
6244void Camera3Device::RequestBufferStateMachine::onInflightMapEmpty() {
6245 std::lock_guard<std::mutex> lock(mLock);
6246 mInflightMapEmpty = true;
6247 if (mStatus == RB_STATUS_PENDING_STOP) {
6248 checkSwitchToStopLocked();
6249 }
6250 return;
6251}
6252
6253void Camera3Device::RequestBufferStateMachine::onWaitUntilIdle() {
6254 std::lock_guard<std::mutex> lock(mLock);
6255 if (!checkSwitchToStopLocked()) {
6256 mStatus = RB_STATUS_PENDING_STOP;
6257 }
6258 return;
6259}
6260
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006261bool Camera3Device::RequestBufferStateMachine::onSwitchToOfflineSuccess() {
6262 std::lock_guard<std::mutex> lock(mLock);
6263 if (mRequestBufferOngoing) {
6264 ALOGE("%s: HAL must not be requesting buffer after HAL returns switchToOffline!",
6265 __FUNCTION__);
6266 return false;
6267 }
6268 mSwitchedToOffline = true;
6269 mInflightMapEmpty = true;
6270 mRequestThreadPaused = true;
6271 mStatus = RB_STATUS_STOPPED;
6272 return true;
6273}
6274
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006275void Camera3Device::RequestBufferStateMachine::notifyTrackerLocked(bool active) {
6276 sp<StatusTracker> statusTracker = mStatusTracker.promote();
6277 if (statusTracker != nullptr) {
6278 if (active) {
6279 statusTracker->markComponentActive(mRequestBufferStatusId);
6280 } else {
6281 statusTracker->markComponentIdle(mRequestBufferStatusId, Fence::NO_FENCE);
6282 }
6283 }
6284}
6285
6286bool Camera3Device::RequestBufferStateMachine::checkSwitchToStopLocked() {
6287 if (mInflightMapEmpty && mRequestThreadPaused && !mRequestBufferOngoing) {
6288 mStatus = RB_STATUS_STOPPED;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006289 return true;
6290 }
6291 return false;
6292}
6293
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006294bool Camera3Device::startRequestBuffer() {
6295 return mRequestBufferSM.startRequestBuffer();
6296}
Shuzhen Wang268a1362018-10-16 16:32:59 -07006297
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006298void Camera3Device::endRequestBuffer() {
6299 mRequestBufferSM.endRequestBuffer();
6300}
Shuzhen Wang268a1362018-10-16 16:32:59 -07006301
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006302nsecs_t Camera3Device::getWaitDuration() {
6303 return kBaseGetBufferWait + getExpectedInFlightDuration();
6304}
Shuzhen Wang268a1362018-10-16 16:32:59 -07006305
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006306void Camera3Device::getInflightBufferKeys(std::vector<std::pair<int32_t, int32_t>>* out) {
6307 mInterface->getInflightBufferKeys(out);
6308}
Shuzhen Wang268a1362018-10-16 16:32:59 -07006309
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006310void Camera3Device::getInflightRequestBufferKeys(std::vector<uint64_t>* out) {
6311 mInterface->getInflightRequestBufferKeys(out);
6312}
Shuzhen Wang268a1362018-10-16 16:32:59 -07006313
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006314std::vector<sp<Camera3StreamInterface>> Camera3Device::getAllStreams() {
6315 std::vector<sp<Camera3StreamInterface>> ret;
6316 bool hasInputStream = mInputStream != nullptr;
6317 ret.reserve(mOutputStreams.size() + mDeletedStreams.size() + ((hasInputStream) ? 1 : 0));
6318 if (hasInputStream) {
6319 ret.push_back(mInputStream);
Shuzhen Wang268a1362018-10-16 16:32:59 -07006320 }
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006321 for (size_t i = 0; i < mOutputStreams.size(); i++) {
6322 ret.push_back(mOutputStreams[i]);
6323 }
6324 for (size_t i = 0; i < mDeletedStreams.size(); i++) {
6325 ret.push_back(mDeletedStreams[i]);
6326 }
6327 return ret;
Shuzhen Wang268a1362018-10-16 16:32:59 -07006328}
6329
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006330status_t Camera3Device::switchToOffline(
6331 const std::vector<int32_t>& streamsToKeep,
6332 /*out*/ sp<CameraOfflineSessionBase>* session) {
6333 ATRACE_CALL();
6334 if (session == nullptr) {
6335 ALOGE("%s: session must not be null", __FUNCTION__);
6336 return BAD_VALUE;
6337 }
6338
6339 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006340
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006341 bool hasInputStream = mInputStream != nullptr;
6342 int32_t inputStreamId = hasInputStream ? mInputStream->getId() : -1;
6343 bool inputStreamSupportsOffline = hasInputStream ?
6344 mInputStream->getOfflineProcessingSupport() : false;
6345 auto outputStreamIds = mOutputStreams.getStreamIds();
6346 auto streamIds = outputStreamIds;
6347 if (hasInputStream) {
6348 streamIds.push_back(mInputStream->getId());
6349 }
6350
6351 // Check all streams in streamsToKeep supports offline mode
6352 for (auto id : streamsToKeep) {
6353 if (std::find(streamIds.begin(), streamIds.end(), id) == streamIds.end()) {
6354 ALOGE("%s: Unknown stream ID %d", __FUNCTION__, id);
6355 return BAD_VALUE;
6356 } else if (id == inputStreamId) {
6357 if (!inputStreamSupportsOffline) {
6358 ALOGE("%s: input stream %d cannot be switched to offline",
6359 __FUNCTION__, id);
6360 return BAD_VALUE;
6361 }
6362 } else {
6363 sp<camera3::Camera3OutputStreamInterface> stream = mOutputStreams.get(id);
6364 if (!stream->getOfflineProcessingSupport()) {
6365 ALOGE("%s: output stream %d cannot be switched to offline",
6366 __FUNCTION__, id);
6367 return BAD_VALUE;
6368 }
6369 }
6370 }
6371
6372 // TODO: block surface sharing and surface group streams until we can support them
6373
6374 // Stop repeating request, wait until all remaining requests are submitted, then call into
6375 // HAL switchToOffline
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006376 hardware::camera::device::V3_6::CameraOfflineSessionInfo offlineSessionInfo;
6377 sp<hardware::camera::device::V3_6::ICameraOfflineSession> offlineSession;
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006378 camera3::BufferRecords bufferRecords;
6379 status_t ret = mRequestThread->switchToOffline(
6380 streamsToKeep, &offlineSessionInfo, &offlineSession, &bufferRecords);
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006381
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006382 if (ret != OK) {
6383 SET_ERR("Switch to offline failed: %s (%d)", strerror(-ret), ret);
6384 return ret;
6385 }
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006386
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006387 bool succ = mRequestBufferSM.onSwitchToOfflineSuccess();
6388 if (!succ) {
6389 SET_ERR("HAL must not be calling requestStreamBuffers call");
6390 // TODO: block ALL callbacks from HAL till app configured new streams?
6391 return UNKNOWN_ERROR;
6392 }
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006393
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006394 // Verify offlineSessionInfo
6395 std::vector<int32_t> offlineStreamIds;
6396 offlineStreamIds.reserve(offlineSessionInfo.offlineStreams.size());
6397 for (auto offlineStream : offlineSessionInfo.offlineStreams) {
6398 // verify stream IDs
6399 int32_t id = offlineStream.id;
6400 if (std::find(streamIds.begin(), streamIds.end(), id) == streamIds.end()) {
6401 SET_ERR("stream ID %d not found!", id);
6402 return UNKNOWN_ERROR;
6403 }
6404
6405 // When not using HAL buf manager, only allow streams requested by app to be preserved
6406 if (!mUseHalBufManager) {
6407 if (std::find(streamsToKeep.begin(), streamsToKeep.end(), id) == streamsToKeep.end()) {
6408 SET_ERR("stream ID %d must not be switched to offline!", id);
6409 return UNKNOWN_ERROR;
6410 }
6411 }
6412
6413 offlineStreamIds.push_back(id);
6414 sp<Camera3StreamInterface> stream = (id == inputStreamId) ?
6415 static_cast<sp<Camera3StreamInterface>>(mInputStream) :
6416 static_cast<sp<Camera3StreamInterface>>(mOutputStreams.get(id));
6417 // Verify number of outstanding buffers
6418 if (stream->getOutstandingBuffersCount() != offlineStream.numOutstandingBuffers) {
6419 SET_ERR("Offline stream %d # of remaining buffer mismatch: (%zu,%d) (service/HAL)",
6420 id, stream->getOutstandingBuffersCount(), offlineStream.numOutstandingBuffers);
6421 return UNKNOWN_ERROR;
6422 }
6423 }
6424
6425 // Verify all streams to be deleted don't have any outstanding buffers
6426 if (hasInputStream && std::find(offlineStreamIds.begin(), offlineStreamIds.end(),
6427 inputStreamId) == offlineStreamIds.end()) {
6428 if (mInputStream->hasOutstandingBuffers()) {
6429 SET_ERR("Input stream %d still has %zu outstanding buffer!",
6430 inputStreamId, mInputStream->getOutstandingBuffersCount());
6431 return UNKNOWN_ERROR;
6432 }
6433 }
6434
6435 for (const auto& outStreamId : outputStreamIds) {
6436 if (std::find(offlineStreamIds.begin(), offlineStreamIds.end(),
6437 outStreamId) == offlineStreamIds.end()) {
6438 auto outStream = mOutputStreams.get(outStreamId);
6439 if (outStream->hasOutstandingBuffers()) {
6440 SET_ERR("Output stream %d still has %zu outstanding buffer!",
6441 outStreamId, outStream->getOutstandingBuffersCount());
6442 return UNKNOWN_ERROR;
6443 }
6444 }
6445 }
6446
6447 InFlightRequestMap offlineReqs;
6448 // Verify inflight requests and their pending buffers
6449 {
6450 std::lock_guard<std::mutex> l(mInFlightLock);
6451 for (auto offlineReq : offlineSessionInfo.offlineRequests) {
6452 int idx = mInFlightMap.indexOfKey(offlineReq.frameNumber);
6453 if (idx == NAME_NOT_FOUND) {
6454 SET_ERR("Offline request frame number %d not found!", offlineReq.frameNumber);
6455 return UNKNOWN_ERROR;
6456 }
6457
6458 const auto& inflightReq = mInFlightMap.valueAt(idx);
6459 // TODO: check specific stream IDs
6460 size_t numBuffersLeft = static_cast<size_t>(inflightReq.numBuffersLeft);
6461 if (numBuffersLeft != offlineReq.pendingStreams.size()) {
6462 SET_ERR("Offline request # of remaining buffer mismatch: (%d,%d) (service/HAL)",
6463 inflightReq.numBuffersLeft, offlineReq.pendingStreams.size());
6464 return UNKNOWN_ERROR;
6465 }
6466 offlineReqs.add(offlineReq.frameNumber, inflightReq);
6467 }
6468 }
6469
6470 // Create Camera3OfflineSession and transfer object ownership
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006471 // (streams, inflight requests, buffer caches)
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006472 camera3::StreamSet offlineStreamSet;
6473 sp<camera3::Camera3Stream> inputStream;
6474 for (auto offlineStream : offlineSessionInfo.offlineStreams) {
6475 int32_t id = offlineStream.id;
6476 if (mInputStream != nullptr && id == mInputStream->getId()) {
6477 inputStream = mInputStream;
6478 } else {
6479 offlineStreamSet.add(id, mOutputStreams.get(id));
6480 }
6481 }
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006482
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006483 // TODO: check if we need to lock before copying states
6484 // though technically no other thread should be talking to Camera3Device at this point
6485 Camera3OfflineStates offlineStates(
6486 mTagMonitor, mVendorTagId, mUseHalBufManager, mNeedFixupMonochromeTags,
Shuzhen Wangb7b42652020-05-07 11:59:02 -07006487 mUsePartialResult, mNumPartialResults, mLastCompletedRegularFrameNumber,
6488 mLastCompletedReprocessFrameNumber, mLastCompletedZslFrameNumber,
6489 mNextResultFrameNumber, mNextReprocessResultFrameNumber,
6490 mNextZslStillResultFrameNumber, mNextShutterFrameNumber,
6491 mNextReprocessShutterFrameNumber, mNextZslStillShutterFrameNumber,
6492 mDeviceInfo, mPhysicalDeviceInfoMap, mDistortionMappers,
6493 mZoomRatioMappers, mRotateAndCropMappers);
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006494
6495 *session = new Camera3OfflineSession(mId, inputStream, offlineStreamSet,
6496 std::move(bufferRecords), offlineReqs, offlineStates, offlineSession);
6497
6498 // Delete all streams that has been transferred to offline session
6499 Mutex::Autolock l(mLock);
6500 for (auto offlineStream : offlineSessionInfo.offlineStreams) {
6501 int32_t id = offlineStream.id;
6502 if (mInputStream != nullptr && id == mInputStream->getId()) {
6503 mInputStream.clear();
6504 } else {
6505 mOutputStreams.remove(id);
6506 }
6507 }
6508
6509 // disconnect all other streams and switch to UNCONFIGURED state
6510 if (mInputStream != nullptr) {
6511 ret = mInputStream->disconnect();
6512 if (ret != OK) {
6513 SET_ERR_L("disconnect input stream failed!");
6514 return UNKNOWN_ERROR;
6515 }
6516 }
6517
6518 for (auto streamId : mOutputStreams.getStreamIds()) {
6519 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
6520 ret = stream->disconnect();
6521 if (ret != OK) {
6522 SET_ERR_L("disconnect output stream %d failed!", streamId);
6523 return UNKNOWN_ERROR;
6524 }
6525 }
6526
6527 mInputStream.clear();
6528 mOutputStreams.clear();
6529 mNeedConfig = true;
6530 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
6531 mOperatingMode = NO_MODE;
6532 mIsConstrainedHighSpeedConfiguration = false;
Emilian Peevc0fe54c2020-03-11 14:05:07 -07006533 mRequestThread->clearPreviousRequest();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006534
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006535 return OK;
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006536 // TO be done by CameraDeviceClient/Camera3OfflineSession
6537 // register the offline client to camera service
6538 // Setup result passthing threads etc
6539 // Initialize offline session so HAL can start sending callback to it (result Fmq)
6540 // TODO: check how many onIdle callback will be sent
6541 // Java side to make sure the CameraCaptureSession is properly closed
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006542}
6543
Emilian Peevcc0b7952020-01-07 13:54:47 -08006544void Camera3Device::getOfflineStreamIds(std::vector<int> *offlineStreamIds) {
6545 ATRACE_CALL();
6546
6547 if (offlineStreamIds == nullptr) {
6548 return;
6549 }
6550
6551 Mutex::Autolock il(mInterfaceLock);
6552
6553 auto streamIds = mOutputStreams.getStreamIds();
6554 bool hasInputStream = mInputStream != nullptr;
6555 if (hasInputStream && mInputStream->getOfflineProcessingSupport()) {
6556 offlineStreamIds->push_back(mInputStream->getId());
6557 }
6558
6559 for (const auto & streamId : streamIds) {
6560 sp<camera3::Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
6561 // Streams that use the camera buffer manager are currently not supported in
6562 // offline mode
6563 if (stream->getOfflineProcessingSupport() &&
6564 (stream->getStreamSetId() == CAMERA3_STREAM_SET_ID_INVALID)) {
6565 offlineStreamIds->push_back(streamId);
6566 }
6567 }
6568}
6569
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08006570status_t Camera3Device::setRotateAndCropAutoBehavior(
6571 camera_metadata_enum_android_scaler_rotate_and_crop_t rotateAndCropValue) {
6572 ATRACE_CALL();
6573 Mutex::Autolock il(mInterfaceLock);
6574 Mutex::Autolock l(mLock);
6575 if (mRequestThread == nullptr) {
6576 return INVALID_OPERATION;
6577 }
6578 return mRequestThread->setRotateAndCropAutoBehavior(rotateAndCropValue);
6579}
6580
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08006581bool Camera3Device::supportsCameraMute() {
6582 Mutex::Autolock il(mInterfaceLock);
6583 Mutex::Autolock l(mLock);
6584
6585 return mSupportCameraMute;
6586}
6587
6588status_t Camera3Device::setCameraMute(bool enabled) {
6589 ATRACE_CALL();
6590 Mutex::Autolock il(mInterfaceLock);
6591 Mutex::Autolock l(mLock);
6592
6593 if (mRequestThread == nullptr || !mSupportCameraMute) {
6594 return INVALID_OPERATION;
6595 }
Eino-Ville Talvala11afe4f2021-05-27 14:45:31 -07006596 int32_t muteMode =
6597 !enabled ? ANDROID_SENSOR_TEST_PATTERN_MODE_OFF :
6598 mSupportTestPatternSolidColor ? ANDROID_SENSOR_TEST_PATTERN_MODE_SOLID_COLOR :
6599 ANDROID_SENSOR_TEST_PATTERN_MODE_BLACK;
6600 return mRequestThread->setCameraMute(muteMode);
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08006601}
6602
Cliff Wuc2ad9c82021-04-21 00:58:58 +08006603status_t Camera3Device::injectCamera(const String8& injectedCamId,
6604 sp<CameraProviderManager> manager) {
6605 ALOGI("%s Injection camera: injectedCamId = %s", __FUNCTION__, injectedCamId.string());
6606 ATRACE_CALL();
6607 Mutex::Autolock il(mInterfaceLock);
Cliff Wu3b268182021-07-06 15:44:43 +08006608 // When the camera device is active, injectCamera() and stopInjection() will call
6609 // internalPauseAndWaitLocked() and internalResumeLocked(), and then they will call
6610 // mStatusChanged.waitRelative(mLock, timeout) of waitUntilStateThenRelock(). But
6611 // mStatusChanged.waitRelative(mLock, timeout)'s parameter: mutex "mLock" must be in the locked
6612 // state, so we need to add "Mutex::Autolock l(mLock)" to lock the "mLock" before calling
6613 // waitUntilStateThenRelock().
6614 Mutex::Autolock l(mLock);
Cliff Wuc2ad9c82021-04-21 00:58:58 +08006615
6616 status_t res = NO_ERROR;
6617 if (mInjectionMethods->isInjecting()) {
6618 if (injectedCamId == mInjectionMethods->getInjectedCamId()) {
6619 return OK;
6620 } else {
6621 res = mInjectionMethods->stopInjection();
6622 if (res != OK) {
6623 ALOGE("%s: Failed to stop the injection camera! ret != NO_ERROR: %d",
6624 __FUNCTION__, res);
6625 return res;
6626 }
6627 }
6628 }
6629
6630 res = mInjectionMethods->injectionInitialize(injectedCamId, manager, this);
6631 if (res != OK) {
6632 ALOGE("%s: Failed to initialize the injection camera! ret != NO_ERROR: %d",
6633 __FUNCTION__, res);
6634 return res;
6635 }
6636
Cliff Wuc2ad9c82021-04-21 00:58:58 +08006637 // When the second display of android is cast to the remote device, and the opened camera is
6638 // also cast to the second display, in this case, because the camera has configured the streams
6639 // at this time, we can directly call injectCamera() to replace the internal camera with
6640 // injection camera.
Cliff Wu3b268182021-07-06 15:44:43 +08006641 if (mInjectionMethods->isStreamConfigCompleteButNotInjected()) {
6642 ALOGD("%s: The opened camera is directly cast to the remote device.", __FUNCTION__);
6643
6644 camera3::camera_stream_configuration injectionConfig;
6645 std::vector<uint32_t> injectionBufferSizes;
6646 mInjectionMethods->getInjectionConfig(&injectionConfig, &injectionBufferSizes);
6647 if (mOperatingMode < 0 || injectionConfig.num_streams <= 0
6648 || injectionBufferSizes.size() <= 0) {
6649 ALOGE("Failed to inject camera due to abandoned configuration! "
6650 "mOperatingMode: %d injectionConfig.num_streams: %d "
6651 "injectionBufferSizes.size(): %zu", mOperatingMode,
6652 injectionConfig.num_streams, injectionBufferSizes.size());
6653 return DEAD_OBJECT;
6654 }
6655
Cliff Wuc2ad9c82021-04-21 00:58:58 +08006656 res = mInjectionMethods->injectCamera(
6657 injectionConfig, injectionBufferSizes);
6658 if (res != OK) {
6659 ALOGE("Can't finish inject camera process!");
6660 return res;
6661 }
6662 }
6663
6664 return OK;
6665}
6666
6667status_t Camera3Device::stopInjection() {
6668 ALOGI("%s: Injection camera: stopInjection", __FUNCTION__);
6669 Mutex::Autolock il(mInterfaceLock);
Cliff Wu3b268182021-07-06 15:44:43 +08006670 Mutex::Autolock l(mLock);
Cliff Wuc2ad9c82021-04-21 00:58:58 +08006671 return mInjectionMethods->stopInjection();
6672}
6673
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08006674}; // namespace android