blob: 873a914f33169043a4d1d64e5494012bbddf6894 [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
Emilian Peev5104fe92021-10-21 14:27:09 -070078Camera3Device::Camera3Device(const String8 &id, bool overrideForPerfClass, bool legacyClient):
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080079 mId(id),
Emilian Peev5104fe92021-10-21 14:27:09 -070080 mLegacyClient(legacyClient),
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -080081 mOperatingMode(NO_MODE),
Eino-Ville Talvala9a179412015-06-09 13:15:16 -070082 mIsConstrainedHighSpeedConfiguration(false),
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -070083 mStatus(STATUS_UNINITIALIZED),
Ruben Brunk183f0562015-08-12 12:55:02 -070084 mStatusWaiters(0),
Zhijun He204e3292014-07-14 17:09:23 -070085 mUsePartialResult(false),
86 mNumPartialResults(1),
Shuzhen Wangc28dccc2016-02-11 23:48:46 -080087 mTimestampOffset(0),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -070088 mNextResultFrameNumber(0),
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -070089 mNextReprocessResultFrameNumber(0),
Shuzhen Wang5ee99842019-04-12 11:55:48 -070090 mNextZslStillResultFrameNumber(0),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -070091 mNextShutterFrameNumber(0),
Chien-Yu Chen3df11ce2015-09-30 14:13:30 -070092 mNextReprocessShutterFrameNumber(0),
Shuzhen Wang5ee99842019-04-12 11:55:48 -070093 mNextZslStillShutterFrameNumber(0),
Emilian Peev71c73a22017-03-21 16:35:51 +000094 mListener(NULL),
Emilian Peev811d2952018-05-25 11:08:40 +010095 mVendorTagId(CAMERA_METADATA_INVALID_VENDOR_ID),
Shuzhen Wang268a1362018-10-16 16:32:59 -070096 mLastTemplateId(-1),
Shuzhen Wangd4abdf72021-05-28 11:22:50 -070097 mNeedFixupMonochromeTags(false),
98 mOverrideForPerfClass(overrideForPerfClass)
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080099{
100 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800101 ALOGV("%s: Created device for camera %s", __FUNCTION__, mId.string());
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800102}
103
104Camera3Device::~Camera3Device()
105{
106 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800107 ALOGV("%s: Tearing down for camera id %s", __FUNCTION__, mId.string());
Yin-Chia Yehc5248132018-08-15 12:19:20 -0700108 disconnectImpl();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800109}
110
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800111const String8& Camera3Device::getId() const {
Igor Murashkin71381052013-03-04 14:53:08 -0800112 return mId;
113}
114
Emilian Peevbd8c5032018-02-14 23:05:40 +0000115status_t Camera3Device::initialize(sp<CameraProviderManager> manager, const String8& monitorTags) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800116 ATRACE_CALL();
117 Mutex::Autolock il(mInterfaceLock);
118 Mutex::Autolock l(mLock);
119
120 ALOGV("%s: Initializing HIDL device for camera %s", __FUNCTION__, mId.string());
121 if (mStatus != STATUS_UNINITIALIZED) {
122 CLOGE("Already initialized!");
123 return INVALID_OPERATION;
124 }
125 if (manager == nullptr) return INVALID_OPERATION;
126
127 sp<ICameraDeviceSession> session;
128 ATRACE_BEGIN("CameraHal::openSession");
Steven Moreland5ff9c912017-03-09 23:13:00 -0800129 status_t res = manager->openSession(mId.string(), this,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800130 /*out*/ &session);
131 ATRACE_END();
132 if (res != OK) {
133 SET_ERR_L("Could not open camera session: %s (%d)", strerror(-res), res);
134 return res;
135 }
136
Shuzhen Wangd4abdf72021-05-28 11:22:50 -0700137 res = manager->getCameraCharacteristics(mId.string(), mOverrideForPerfClass, &mDeviceInfo);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800138 if (res != OK) {
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700139 SET_ERR_L("Could not retrieve camera characteristics: %s (%d)", strerror(-res), res);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800140 session->close();
141 return res;
142 }
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800143 mSupportNativeZoomRatio = manager->supportNativeZoomRatio(mId.string());
Yin-Chia Yeh52778d42016-12-22 18:20:43 -0800144
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700145 std::vector<std::string> physicalCameraIds;
Shuzhen Wang03d8cc12018-09-12 14:17:09 -0700146 bool isLogical = manager->isLogicalCamera(mId.string(), &physicalCameraIds);
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700147 if (isLogical) {
148 for (auto& physicalId : physicalCameraIds) {
Shuzhen Wangd4abdf72021-05-28 11:22:50 -0700149 // Do not override characteristics for physical cameras
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -0700150 res = manager->getCameraCharacteristics(
Shuzhen Wangd4abdf72021-05-28 11:22:50 -0700151 physicalId, /*overrideForPerfClass*/false, &mPhysicalDeviceInfoMap[physicalId]);
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700152 if (res != OK) {
153 SET_ERR_L("Could not retrieve camera %s characteristics: %s (%d)",
154 physicalId.c_str(), strerror(-res), res);
155 session->close();
156 return res;
157 }
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -0700158
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800159 bool usePrecorrectArray =
160 DistortionMapper::isDistortionSupported(mPhysicalDeviceInfoMap[physicalId]);
161 if (usePrecorrectArray) {
162 res = mDistortionMappers[physicalId].setupStaticInfo(
163 mPhysicalDeviceInfoMap[physicalId]);
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -0700164 if (res != OK) {
165 SET_ERR_L("Unable to read camera %s's calibration fields for distortion "
166 "correction", physicalId.c_str());
167 session->close();
168 return res;
169 }
170 }
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800171
Shuzhen Wang1c834da2019-12-18 11:17:03 -0800172 mZoomRatioMappers[physicalId] = ZoomRatioMapper(
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800173 &mPhysicalDeviceInfoMap[physicalId],
174 mSupportNativeZoomRatio, usePrecorrectArray);
Jayant Chowdhary9255ce02021-07-15 11:18:17 -0700175
176 if (SessionConfigurationUtils::isUltraHighResolutionSensor(
177 mPhysicalDeviceInfoMap[physicalId])) {
178 mUHRCropAndMeteringRegionMappers[physicalId] =
179 UHRCropAndMeteringRegionMapper(mPhysicalDeviceInfoMap[physicalId],
180 usePrecorrectArray);
181 }
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700182 }
183 }
184
Yifan Hongf79b5542017-04-11 14:44:25 -0700185 std::shared_ptr<RequestMetadataQueue> queue;
Yifan Honga640c5a2017-04-12 16:30:31 -0700186 auto requestQueueRet = session->getCaptureRequestMetadataQueue(
187 [&queue](const auto& descriptor) {
188 queue = std::make_shared<RequestMetadataQueue>(descriptor);
189 if (!queue->isValid() || queue->availableToWrite() <= 0) {
190 ALOGE("HAL returns empty request metadata fmq, not use it");
191 queue = nullptr;
192 // don't use the queue onwards.
193 }
194 });
195 if (!requestQueueRet.isOk()) {
196 ALOGE("Transaction error when getting request metadata fmq: %s, not use it",
197 requestQueueRet.description().c_str());
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -0700198 return DEAD_OBJECT;
Yifan Hongf79b5542017-04-11 14:44:25 -0700199 }
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700200
201 std::unique_ptr<ResultMetadataQueue>& resQueue = mResultMetadataQueue;
Yifan Honga640c5a2017-04-12 16:30:31 -0700202 auto resultQueueRet = session->getCaptureResultMetadataQueue(
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700203 [&resQueue](const auto& descriptor) {
204 resQueue = std::make_unique<ResultMetadataQueue>(descriptor);
205 if (!resQueue->isValid() || resQueue->availableToWrite() <= 0) {
Yifan Honga640c5a2017-04-12 16:30:31 -0700206 ALOGE("HAL returns empty result metadata fmq, not use it");
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700207 resQueue = nullptr;
208 // Don't use the resQueue onwards.
Yifan Honga640c5a2017-04-12 16:30:31 -0700209 }
210 });
211 if (!resultQueueRet.isOk()) {
212 ALOGE("Transaction error when getting result metadata queue from camera session: %s",
213 resultQueueRet.description().c_str());
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -0700214 return DEAD_OBJECT;
Yifan Honga640c5a2017-04-12 16:30:31 -0700215 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -0700216 IF_ALOGV() {
217 session->interfaceChain([](
218 ::android::hardware::hidl_vec<::android::hardware::hidl_string> interfaceChain) {
219 ALOGV("Session interface chain:");
Chih-Hung Hsieh3ef324d2018-12-11 11:48:12 -0800220 for (const auto& iface : interfaceChain) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -0700221 ALOGV(" %s", iface.c_str());
222 }
223 });
224 }
Yifan Hongf79b5542017-04-11 14:44:25 -0700225
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -0800226 camera_metadata_entry bufMgrMode =
227 mDeviceInfo.find(ANDROID_INFO_SUPPORTED_BUFFER_MANAGEMENT_VERSION);
228 if (bufMgrMode.count > 0) {
229 mUseHalBufManager = (bufMgrMode.data.u8[0] ==
230 ANDROID_INFO_SUPPORTED_BUFFER_MANAGEMENT_VERSION_HIDL_DEVICE_3_5);
231 }
232
Yin-Chia Yehb978c382019-10-30 00:22:37 -0700233 camera_metadata_entry_t capabilities = mDeviceInfo.find(ANDROID_REQUEST_AVAILABLE_CAPABILITIES);
234 for (size_t i = 0; i < capabilities.count; i++) {
235 uint8_t capability = capabilities.data.u8[i];
236 if (capability == ANDROID_REQUEST_AVAILABLE_CAPABILITIES_OFFLINE_PROCESSING) {
237 mSupportOfflineProcessing = true;
238 }
239 }
240
241 mInterface = new HalInterface(session, queue, mUseHalBufManager, mSupportOfflineProcessing);
Emilian Peev71c73a22017-03-21 16:35:51 +0000242 std::string providerType;
243 mVendorTagId = manager->getProviderTagIdLocked(mId.string());
Emilian Peevbd8c5032018-02-14 23:05:40 +0000244 mTagMonitor.initialize(mVendorTagId);
245 if (!monitorTags.isEmpty()) {
246 mTagMonitor.parseTagsToMonitor(String8(monitorTags));
247 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800248
Shuzhen Wang268a1362018-10-16 16:32:59 -0700249 // Metadata tags needs fixup for monochrome camera device version less
250 // than 3.5.
251 hardware::hidl_version maxVersion{0,0};
252 res = manager->getHighestSupportedVersion(mId.string(), &maxVersion);
253 if (res != OK) {
254 ALOGE("%s: Error in getting camera device version id: %s (%d)",
255 __FUNCTION__, strerror(-res), res);
256 return res;
257 }
258 int deviceVersion = HARDWARE_DEVICE_API_VERSION(
259 maxVersion.get_major(), maxVersion.get_minor());
260
261 bool isMonochrome = false;
Yin-Chia Yehb978c382019-10-30 00:22:37 -0700262 for (size_t i = 0; i < capabilities.count; i++) {
263 uint8_t capability = capabilities.data.u8[i];
Shuzhen Wang268a1362018-10-16 16:32:59 -0700264 if (capability == ANDROID_REQUEST_AVAILABLE_CAPABILITIES_MONOCHROME) {
265 isMonochrome = true;
266 }
267 }
268 mNeedFixupMonochromeTags = (isMonochrome && deviceVersion < CAMERA_DEVICE_API_VERSION_3_5);
269
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800270 return initializeCommonLocked();
271}
272
273status_t Camera3Device::initializeCommonLocked() {
274
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700275 /** Start up status tracker thread */
276 mStatusTracker = new StatusTracker(this);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800277 status_t res = mStatusTracker->run(String8::format("C3Dev-%s-Status", mId.string()).string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700278 if (res != OK) {
279 SET_ERR_L("Unable to start status tracking thread: %s (%d)",
280 strerror(-res), res);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800281 mInterface->close();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700282 mStatusTracker.clear();
283 return res;
284 }
285
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -0700286 /** Register in-flight map to the status tracker */
Yin-Chia Yeh87b3ec02019-06-03 10:44:39 -0700287 mInFlightStatusId = mStatusTracker->addComponent("InflightRequests");
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -0700288
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -0700289 if (mUseHalBufManager) {
290 res = mRequestBufferSM.initialize(mStatusTracker);
291 if (res != OK) {
292 SET_ERR_L("Unable to start request buffer state machine: %s (%d)",
293 strerror(-res), res);
294 mInterface->close();
295 mStatusTracker.clear();
296 return res;
297 }
298 }
299
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -0800300 /** Create buffer manager */
301 mBufferManager = new Camera3BufferManager();
302
303 Vector<int32_t> sessionParamKeys;
304 camera_metadata_entry_t sessionKeysEntry = mDeviceInfo.find(
305 ANDROID_REQUEST_AVAILABLE_SESSION_KEYS);
306 if (sessionKeysEntry.count > 0) {
307 sessionParamKeys.insertArrayAt(sessionKeysEntry.data.i32, 0, sessionKeysEntry.count);
308 }
309
Eino-Ville Talvala1646c3c2021-07-29 13:48:40 -0700310 camera_metadata_entry_t availableTestPatternModes = mDeviceInfo.find(
311 ANDROID_SENSOR_AVAILABLE_TEST_PATTERN_MODES);
312 for (size_t i = 0; i < availableTestPatternModes.count; i++) {
313 if (availableTestPatternModes.data.i32[i] ==
314 ANDROID_SENSOR_TEST_PATTERN_MODE_SOLID_COLOR) {
315 mSupportCameraMute = true;
316 mSupportTestPatternSolidColor = true;
317 break;
318 } else if (availableTestPatternModes.data.i32[i] ==
319 ANDROID_SENSOR_TEST_PATTERN_MODE_BLACK) {
320 mSupportCameraMute = true;
321 mSupportTestPatternSolidColor = false;
322 }
323 }
324
Chien-Yu Chenab5135b2015-06-30 11:20:58 -0700325 /** Start up request queue thread */
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -0700326 mRequestThread = new RequestThread(
Eino-Ville Talvala1646c3c2021-07-29 13:48:40 -0700327 this, mStatusTracker, mInterface, sessionParamKeys,
328 mUseHalBufManager, mSupportCameraMute);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800329 res = mRequestThread->run(String8::format("C3Dev-%s-ReqQueue", mId.string()).string());
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800330 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700331 SET_ERR_L("Unable to start request queue thread: %s (%d)",
332 strerror(-res), res);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800333 mInterface->close();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800334 mRequestThread.clear();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800335 return res;
336 }
337
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -0700338 mPreparerThread = new PreparerThread();
339
Ruben Brunk183f0562015-08-12 12:55:02 -0700340 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800341 mNextStreamId = 0;
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -0400342 mFakeStreamId = NO_STREAM;
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -0700343 mNeedConfig = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700344 mPauseStateNotify = false;
Shuzhen Wang83bff122020-11-20 15:51:39 -0800345 mIsInputStreamMultiResolution = false;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800346
Shuzhen Wangc28dccc2016-02-11 23:48:46 -0800347 // Measure the clock domain offset between camera and video/hw_composer
348 camera_metadata_entry timestampSource =
349 mDeviceInfo.find(ANDROID_SENSOR_INFO_TIMESTAMP_SOURCE);
350 if (timestampSource.count > 0 && timestampSource.data.u8[0] ==
351 ANDROID_SENSOR_INFO_TIMESTAMP_SOURCE_REALTIME) {
352 mTimestampOffset = getMonoToBoottimeOffset();
353 }
354
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -0700355 // Will the HAL be sending in early partial result metadata?
Emilian Peev08dd2452017-04-06 16:55:14 +0100356 camera_metadata_entry partialResultsCount =
357 mDeviceInfo.find(ANDROID_REQUEST_PARTIAL_RESULT_COUNT);
358 if (partialResultsCount.count > 0) {
359 mNumPartialResults = partialResultsCount.data.i32[0];
360 mUsePartialResult = (mNumPartialResults > 1);
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -0700361 }
362
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800363 bool usePrecorrectArray = DistortionMapper::isDistortionSupported(mDeviceInfo);
364 if (usePrecorrectArray) {
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -0700365 res = mDistortionMappers[mId.c_str()].setupStaticInfo(mDeviceInfo);
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -0700366 if (res != OK) {
367 SET_ERR_L("Unable to read necessary calibration fields for distortion correction");
368 return res;
369 }
370 }
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800371
Shuzhen Wang1c834da2019-12-18 11:17:03 -0800372 mZoomRatioMappers[mId.c_str()] = ZoomRatioMapper(&mDeviceInfo,
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800373 mSupportNativeZoomRatio, usePrecorrectArray);
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800374
Jayant Chowdhary9255ce02021-07-15 11:18:17 -0700375 if (SessionConfigurationUtils::isUltraHighResolutionSensor(mDeviceInfo)) {
376 mUHRCropAndMeteringRegionMappers[mId.c_str()] =
377 UHRCropAndMeteringRegionMapper(mDeviceInfo, usePrecorrectArray);
378 }
379
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -0800380 if (RotateAndCropMapper::isNeeded(&mDeviceInfo)) {
381 mRotateAndCropMappers.emplace(mId.c_str(), &mDeviceInfo);
382 }
383
Cliff Wuc2ad9c82021-04-21 00:58:58 +0800384 mInjectionMethods = new Camera3DeviceInjectionMethods(this);
385
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800386 return OK;
387}
388
389status_t Camera3Device::disconnect() {
Yin-Chia Yehc5248132018-08-15 12:19:20 -0700390 return disconnectImpl();
391}
392
393status_t Camera3Device::disconnectImpl() {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800394 ATRACE_CALL();
Yin-Chia Yehe1c80632016-08-08 14:48:05 -0700395 ALOGI("%s: E", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800396
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700397 status_t res = OK;
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700398 std::vector<wp<Camera3StreamInterface>> streams;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700399 {
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800400 Mutex::Autolock il(mInterfaceLock);
401 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
402 {
403 Mutex::Autolock l(mLock);
404 if (mStatus == STATUS_UNINITIALIZED) return res;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700405
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800406 if (mStatus == STATUS_ACTIVE ||
407 (mStatus == STATUS_ERROR && mRequestThread != NULL)) {
408 res = mRequestThread->clearRepeatingRequests();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700409 if (res != OK) {
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800410 SET_ERR_L("Can't stop streaming");
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700411 // Continue to close device even in case of error
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800412 } else {
413 res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
414 if (res != OK) {
415 SET_ERR_L("Timeout waiting for HAL to drain (% " PRIi64 " ns)",
416 maxExpectedDuration);
417 // Continue to close device even in case of error
418 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700419 }
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700420 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800421
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800422 if (mStatus == STATUS_ERROR) {
423 CLOGE("Shutting down in an error state");
424 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700425
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800426 if (mStatusTracker != NULL) {
427 mStatusTracker->requestExit();
428 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700429
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800430 if (mRequestThread != NULL) {
431 mRequestThread->requestExit();
432 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700433
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800434 streams.reserve(mOutputStreams.size() + (mInputStream != nullptr ? 1 : 0));
435 for (size_t i = 0; i < mOutputStreams.size(); i++) {
436 streams.push_back(mOutputStreams[i]);
437 }
438 if (mInputStream != nullptr) {
439 streams.push_back(mInputStream);
440 }
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700441 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700442 }
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800443 // Joining done without holding mLock and mInterfaceLock, otherwise deadlocks may ensue
444 // as the threads try to access parent state (b/143513518)
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700445 if (mRequestThread != NULL && mStatus != STATUS_ERROR) {
446 // HAL may be in a bad state, so waiting for request thread
447 // (which may be stuck in the HAL processCaptureRequest call)
448 // could be dangerous.
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800449 // give up mInterfaceLock here and then lock it again. Could this lead
450 // to other deadlocks
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700451 mRequestThread->join();
452 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700453 {
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800454 Mutex::Autolock il(mInterfaceLock);
455 if (mStatusTracker != NULL) {
456 mStatusTracker->join();
457 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800458
Cliff Wuc2ad9c82021-04-21 00:58:58 +0800459 if (mInjectionMethods->isInjecting()) {
460 mInjectionMethods->stopInjection();
461 }
462
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800463 HalInterface* interface;
464 {
465 Mutex::Autolock l(mLock);
466 mRequestThread.clear();
467 Mutex::Autolock stLock(mTrackerLock);
468 mStatusTracker.clear();
469 interface = mInterface.get();
470 }
Eino-Ville Talvalaefff1c42015-08-28 16:27:27 -0700471
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800472 // Call close without internal mutex held, as the HAL close may need to
473 // wait on assorted callbacks,etc, to complete before it can return.
474 interface->close();
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700475
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800476 flushInflightRequests();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800477
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800478 {
479 Mutex::Autolock l(mLock);
480 mInterface->clear();
481 mOutputStreams.clear();
482 mInputStream.clear();
483 mDeletedStreams.clear();
484 mBufferManager.clear();
485 internalUpdateStatusLocked(STATUS_UNINITIALIZED);
486 }
487
488 for (auto& weakStream : streams) {
489 sp<Camera3StreamInterface> stream = weakStream.promote();
490 if (stream != nullptr) {
491 ALOGE("%s: Stream %d leaked! strong reference (%d)!",
492 __FUNCTION__, stream->getId(), stream->getStrongCount() - 1);
493 }
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700494 }
495 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -0700496 ALOGI("%s: X", __FUNCTION__);
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700497 return res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800498}
499
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700500// For dumping/debugging only -
501// try to acquire a lock a few times, eventually give up to proceed with
502// debug/dump operations
503bool Camera3Device::tryLockSpinRightRound(Mutex& lock) {
504 bool gotLock = false;
505 for (size_t i = 0; i < kDumpLockAttempts; ++i) {
506 if (lock.tryLock() == NO_ERROR) {
507 gotLock = true;
508 break;
509 } else {
510 usleep(kDumpSleepDuration);
511 }
512 }
513 return gotLock;
514}
515
Shuzhen Wangc28dccc2016-02-11 23:48:46 -0800516nsecs_t Camera3Device::getMonoToBoottimeOffset() {
517 // try three times to get the clock offset, choose the one
518 // with the minimum gap in measurements.
519 const int tries = 3;
520 nsecs_t bestGap, measured;
521 for (int i = 0; i < tries; ++i) {
522 const nsecs_t tmono = systemTime(SYSTEM_TIME_MONOTONIC);
523 const nsecs_t tbase = systemTime(SYSTEM_TIME_BOOTTIME);
524 const nsecs_t tmono2 = systemTime(SYSTEM_TIME_MONOTONIC);
525 const nsecs_t gap = tmono2 - tmono;
526 if (i == 0 || gap < bestGap) {
527 bestGap = gap;
528 measured = tbase - ((tmono + tmono2) >> 1);
529 }
530 }
531 return measured;
532}
533
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800534hardware::graphics::common::V1_0::PixelFormat Camera3Device::mapToPixelFormat(
535 int frameworkFormat) {
536 return (hardware::graphics::common::V1_0::PixelFormat) frameworkFormat;
537}
538
539DataspaceFlags Camera3Device::mapToHidlDataspace(
540 android_dataspace dataSpace) {
541 return dataSpace;
542}
543
Chia-I Wu67a0c0e2017-04-06 13:37:01 -0700544BufferUsageFlags Camera3Device::mapToConsumerUsage(
Emilian Peev050f5dc2017-05-18 14:43:56 +0100545 uint64_t usage) {
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -0700546 return usage;
547}
548
Emilian Peevf4816702020-04-03 15:44:51 -0700549StreamRotation Camera3Device::mapToStreamRotation(camera_stream_rotation_t rotation) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800550 switch (rotation) {
Emilian Peevf4816702020-04-03 15:44:51 -0700551 case CAMERA_STREAM_ROTATION_0:
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800552 return StreamRotation::ROTATION_0;
Emilian Peevf4816702020-04-03 15:44:51 -0700553 case CAMERA_STREAM_ROTATION_90:
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800554 return StreamRotation::ROTATION_90;
Emilian Peevf4816702020-04-03 15:44:51 -0700555 case CAMERA_STREAM_ROTATION_180:
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800556 return StreamRotation::ROTATION_180;
Emilian Peevf4816702020-04-03 15:44:51 -0700557 case CAMERA_STREAM_ROTATION_270:
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800558 return StreamRotation::ROTATION_270;
559 }
560 ALOGE("%s: Unknown stream rotation %d", __FUNCTION__, rotation);
561 return StreamRotation::ROTATION_0;
562}
563
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800564status_t Camera3Device::mapToStreamConfigurationMode(
Emilian Peevf4816702020-04-03 15:44:51 -0700565 camera_stream_configuration_mode_t operationMode, StreamConfigurationMode *mode) {
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800566 if (mode == nullptr) return BAD_VALUE;
Emilian Peevf4816702020-04-03 15:44:51 -0700567 if (operationMode < CAMERA_VENDOR_STREAM_CONFIGURATION_MODE_START) {
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800568 switch(operationMode) {
Emilian Peevf4816702020-04-03 15:44:51 -0700569 case CAMERA_STREAM_CONFIGURATION_NORMAL_MODE:
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800570 *mode = StreamConfigurationMode::NORMAL_MODE;
571 break;
Emilian Peevf4816702020-04-03 15:44:51 -0700572 case CAMERA_STREAM_CONFIGURATION_CONSTRAINED_HIGH_SPEED_MODE:
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800573 *mode = StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE;
574 break;
575 default:
576 ALOGE("%s: Unknown stream configuration mode %d", __FUNCTION__, operationMode);
577 return BAD_VALUE;
578 }
579 } else {
580 *mode = static_cast<StreamConfigurationMode>(operationMode);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800581 }
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800582 return OK;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800583}
584
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800585int Camera3Device::mapToFrameworkFormat(
586 hardware::graphics::common::V1_0::PixelFormat pixelFormat) {
587 return static_cast<uint32_t>(pixelFormat);
588}
589
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -0700590android_dataspace Camera3Device::mapToFrameworkDataspace(
591 DataspaceFlags dataSpace) {
592 return static_cast<android_dataspace>(dataSpace);
593}
594
Emilian Peev050f5dc2017-05-18 14:43:56 +0100595uint64_t Camera3Device::mapConsumerToFrameworkUsage(
Chia-I Wu67a0c0e2017-04-06 13:37:01 -0700596 BufferUsageFlags usage) {
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -0700597 return usage;
598}
599
Emilian Peev050f5dc2017-05-18 14:43:56 +0100600uint64_t Camera3Device::mapProducerToFrameworkUsage(
Chia-I Wu67a0c0e2017-04-06 13:37:01 -0700601 BufferUsageFlags usage) {
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -0700602 return usage;
603}
604
Zhijun Hef7da0962014-04-24 13:27:56 -0700605ssize_t Camera3Device::getJpegBufferSize(uint32_t width, uint32_t height) const {
Jayant Chowdharycd3d36b2021-07-10 10:53:53 -0700606 // Get max jpeg size (area-wise) for default sensor pixel mode
607 camera3::Size maxDefaultJpegResolution =
608 SessionConfigurationUtils::getMaxJpegResolution(mDeviceInfo,
609 /*isUltraHighResolutionSensor*/false);
610 // Get max jpeg size (area-wise) for max resolution sensor pixel mode / 0 if
611 // not ultra high res sensor
612 camera3::Size uhrMaxJpegResolution =
613 SessionConfigurationUtils::getMaxJpegResolution(mDeviceInfo,
614 /*isUltraHighResolution*/true);
615 if (maxDefaultJpegResolution.width == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800616 ALOGE("%s: Camera %s: Can't find valid available jpeg sizes in static metadata!",
617 __FUNCTION__, mId.string());
Zhijun Hef7da0962014-04-24 13:27:56 -0700618 return BAD_VALUE;
619 }
Jayant Chowdharycd3d36b2021-07-10 10:53:53 -0700620 bool useMaxSensorPixelModeThreshold = false;
621 if (uhrMaxJpegResolution.width != 0 &&
622 width * height > maxDefaultJpegResolution.width * maxDefaultJpegResolution.height) {
623 // Use the ultra high res max jpeg size and max jpeg buffer size
624 useMaxSensorPixelModeThreshold = true;
625 }
Zhijun Hef7da0962014-04-24 13:27:56 -0700626
Zhijun Hef7da0962014-04-24 13:27:56 -0700627 // Get max jpeg buffer size
628 ssize_t maxJpegBufferSize = 0;
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700629 camera_metadata_ro_entry jpegBufMaxSize = mDeviceInfo.find(ANDROID_JPEG_MAX_SIZE);
630 if (jpegBufMaxSize.count == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800631 ALOGE("%s: Camera %s: Can't find maximum JPEG size in static metadata!", __FUNCTION__,
632 mId.string());
Zhijun Hef7da0962014-04-24 13:27:56 -0700633 return BAD_VALUE;
634 }
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700635 maxJpegBufferSize = jpegBufMaxSize.data.i32[0];
Jayant Chowdharycd3d36b2021-07-10 10:53:53 -0700636
637 camera3::Size chosenMaxJpegResolution = maxDefaultJpegResolution;
638 if (useMaxSensorPixelModeThreshold) {
639 maxJpegBufferSize =
640 SessionConfigurationUtils::getUHRMaxJpegBufferSize(uhrMaxJpegResolution,
641 maxDefaultJpegResolution, maxJpegBufferSize);
642 chosenMaxJpegResolution = uhrMaxJpegResolution;
643 }
Yin-Chia Yeh0c4e56d2015-01-09 15:21:27 -0800644 assert(kMinJpegBufferSize < maxJpegBufferSize);
Zhijun Hef7da0962014-04-24 13:27:56 -0700645
646 // Calculate final jpeg buffer size for the given resolution.
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700647 float scaleFactor = ((float) (width * height)) /
Jayant Chowdharycd3d36b2021-07-10 10:53:53 -0700648 (chosenMaxJpegResolution.width * chosenMaxJpegResolution.height);
Yin-Chia Yeh0c4e56d2015-01-09 15:21:27 -0800649 ssize_t jpegBufferSize = scaleFactor * (maxJpegBufferSize - kMinJpegBufferSize) +
650 kMinJpegBufferSize;
Zhijun Hef7da0962014-04-24 13:27:56 -0700651 if (jpegBufferSize > maxJpegBufferSize) {
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -0800652 ALOGI("%s: jpeg buffer size calculated is > maxJpeg bufferSize(%zd), clamping",
653 __FUNCTION__, maxJpegBufferSize);
Zhijun Hef7da0962014-04-24 13:27:56 -0700654 jpegBufferSize = maxJpegBufferSize;
Zhijun Hef7da0962014-04-24 13:27:56 -0700655 }
Zhijun Hef7da0962014-04-24 13:27:56 -0700656 return jpegBufferSize;
657}
658
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700659ssize_t Camera3Device::getPointCloudBufferSize() const {
660 const int FLOATS_PER_POINT=4;
661 camera_metadata_ro_entry maxPointCount = mDeviceInfo.find(ANDROID_DEPTH_MAX_DEPTH_SAMPLES);
662 if (maxPointCount.count == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800663 ALOGE("%s: Camera %s: Can't find maximum depth point cloud size in static metadata!",
664 __FUNCTION__, mId.string());
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700665 return BAD_VALUE;
666 }
667 ssize_t maxBytesForPointCloud = sizeof(android_depth_points) +
668 maxPointCount.data.i32[0] * sizeof(float) * FLOATS_PER_POINT;
669 return maxBytesForPointCloud;
670}
671
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -0800672ssize_t Camera3Device::getRawOpaqueBufferSize(int32_t width, int32_t height,
673 bool maxResolution) const {
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800674 const int PER_CONFIGURATION_SIZE = 3;
675 const int WIDTH_OFFSET = 0;
676 const int HEIGHT_OFFSET = 1;
677 const int SIZE_OFFSET = 2;
678 camera_metadata_ro_entry rawOpaqueSizes =
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -0800679 mDeviceInfo.find(
680 camera3::SessionConfigurationUtils::getAppropriateModeTag(
681 ANDROID_SENSOR_OPAQUE_RAW_SIZE,
682 maxResolution));
Aurimas Liutikasbc57b122016-02-16 09:59:16 -0800683 size_t count = rawOpaqueSizes.count;
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800684 if (count == 0 || (count % PER_CONFIGURATION_SIZE)) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800685 ALOGE("%s: Camera %s: bad opaque RAW size static metadata length(%zu)!",
686 __FUNCTION__, mId.string(), count);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800687 return BAD_VALUE;
688 }
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700689
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800690 for (size_t i = 0; i < count; i += PER_CONFIGURATION_SIZE) {
691 if (width == rawOpaqueSizes.data.i32[i + WIDTH_OFFSET] &&
692 height == rawOpaqueSizes.data.i32[i + HEIGHT_OFFSET]) {
693 return rawOpaqueSizes.data.i32[i + SIZE_OFFSET];
694 }
695 }
696
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800697 ALOGE("%s: Camera %s: cannot find size for %dx%d opaque RAW image!",
698 __FUNCTION__, mId.string(), width, height);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800699 return BAD_VALUE;
700}
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700701
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800702status_t Camera3Device::dump(int fd, const Vector<String16> &args) {
703 ATRACE_CALL();
704 (void)args;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700705
706 // Try to lock, but continue in case of failure (to avoid blocking in
707 // deadlocks)
708 bool gotInterfaceLock = tryLockSpinRightRound(mInterfaceLock);
709 bool gotLock = tryLockSpinRightRound(mLock);
710
711 ALOGW_IF(!gotInterfaceLock,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800712 "Camera %s: %s: Unable to lock interface lock, proceeding anyway",
713 mId.string(), __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700714 ALOGW_IF(!gotLock,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800715 "Camera %s: %s: Unable to lock main lock, proceeding anyway",
716 mId.string(), __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700717
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800718 bool dumpTemplates = false;
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700719
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800720 String16 templatesOption("-t");
721 int n = args.size();
722 for (int i = 0; i < n; i++) {
723 if (args[i] == templatesOption) {
724 dumpTemplates = true;
725 }
Emilian Peevbd8c5032018-02-14 23:05:40 +0000726 if (args[i] == TagMonitor::kMonitorOption) {
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700727 if (i + 1 < n) {
728 String8 monitorTags = String8(args[i + 1]);
729 if (monitorTags == "off") {
730 mTagMonitor.disableMonitoring();
731 } else {
732 mTagMonitor.parseTagsToMonitor(monitorTags);
733 }
734 } else {
735 mTagMonitor.disableMonitoring();
736 }
737 }
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800738 }
739
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800740 String8 lines;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800741
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800742 const char *status =
743 mStatus == STATUS_ERROR ? "ERROR" :
744 mStatus == STATUS_UNINITIALIZED ? "UNINITIALIZED" :
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700745 mStatus == STATUS_UNCONFIGURED ? "UNCONFIGURED" :
746 mStatus == STATUS_CONFIGURED ? "CONFIGURED" :
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800747 mStatus == STATUS_ACTIVE ? "ACTIVE" :
748 "Unknown";
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700749
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800750 lines.appendFormat(" Device status: %s\n", status);
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700751 if (mStatus == STATUS_ERROR) {
752 lines.appendFormat(" Error cause: %s\n", mErrorCause.string());
753 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800754 lines.appendFormat(" Stream configuration:\n");
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800755 const char *mode =
756 mOperatingMode == static_cast<int>(StreamConfigurationMode::NORMAL_MODE) ? "NORMAL" :
757 mOperatingMode == static_cast<int>(
758 StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE) ? "CONSTRAINED_HIGH_SPEED" :
759 "CUSTOM";
760 lines.appendFormat(" Operation mode: %s (%d) \n", mode, mOperatingMode);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800761
762 if (mInputStream != NULL) {
763 write(fd, lines.string(), lines.size());
764 mInputStream->dump(fd, args);
765 } else {
766 lines.appendFormat(" No input stream.\n");
767 write(fd, lines.string(), lines.size());
768 }
769 for (size_t i = 0; i < mOutputStreams.size(); i++) {
770 mOutputStreams[i]->dump(fd,args);
771 }
772
Zhijun He431503c2016-03-07 17:30:16 -0800773 if (mBufferManager != NULL) {
774 lines = String8(" Camera3 Buffer Manager:\n");
775 write(fd, lines.string(), lines.size());
776 mBufferManager->dump(fd, args);
777 }
Zhijun He125684a2015-12-26 15:07:30 -0800778
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700779 lines = String8(" In-flight requests:\n");
Emilian Peeva6138c52021-06-24 12:52:38 -0700780 if (mInFlightLock.try_lock()) {
781 if (mInFlightMap.size() == 0) {
782 lines.append(" None\n");
783 } else {
784 for (size_t i = 0; i < mInFlightMap.size(); i++) {
785 InFlightRequest r = mInFlightMap.valueAt(i);
786 lines.appendFormat(" Frame %d | Timestamp: %" PRId64 ", metadata"
787 " arrived: %s, buffers left: %d\n", mInFlightMap.keyAt(i),
788 r.shutterTimestamp, r.haveResultMetadata ? "true" : "false",
789 r.numBuffersLeft);
790 }
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700791 }
Emilian Peeva6138c52021-06-24 12:52:38 -0700792 mInFlightLock.unlock();
793 } else {
794 lines.append(" Failed to acquire In-flight lock!\n");
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700795 }
796 write(fd, lines.string(), lines.size());
797
Shuzhen Wang686f6442017-06-20 16:16:04 -0700798 if (mRequestThread != NULL) {
799 mRequestThread->dumpCaptureRequestLatency(fd,
800 " ProcessCaptureRequest latency histogram:");
801 }
802
Igor Murashkin1e479c02013-09-06 16:55:14 -0700803 {
804 lines = String8(" Last request sent:\n");
805 write(fd, lines.string(), lines.size());
806
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700807 CameraMetadata lastRequest = getLatestRequestLocked();
Igor Murashkin1e479c02013-09-06 16:55:14 -0700808 lastRequest.dump(fd, /*verbosity*/2, /*indentation*/6);
809 }
810
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800811 if (dumpTemplates) {
Emilian Peevf4816702020-04-03 15:44:51 -0700812 const char *templateNames[CAMERA_TEMPLATE_COUNT] = {
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800813 "TEMPLATE_PREVIEW",
814 "TEMPLATE_STILL_CAPTURE",
815 "TEMPLATE_VIDEO_RECORD",
816 "TEMPLATE_VIDEO_SNAPSHOT",
817 "TEMPLATE_ZERO_SHUTTER_LAG",
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -0800818 "TEMPLATE_MANUAL",
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800819 };
820
Emilian Peevf4816702020-04-03 15:44:51 -0700821 for (int i = 1; i < CAMERA_TEMPLATE_COUNT; i++) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800822 camera_metadata_t *templateRequest = nullptr;
823 mInterface->constructDefaultRequestSettings(
Emilian Peevf4816702020-04-03 15:44:51 -0700824 (camera_request_template_t) i, &templateRequest);
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800825 lines = String8::format(" HAL Request %s:\n", templateNames[i-1]);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800826 if (templateRequest == nullptr) {
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800827 lines.append(" Not supported\n");
828 write(fd, lines.string(), lines.size());
829 } else {
830 write(fd, lines.string(), lines.size());
831 dump_indented_camera_metadata(templateRequest,
832 fd, /*verbosity*/2, /*indentation*/8);
833 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800834 free_camera_metadata(templateRequest);
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800835 }
836 }
837
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700838 mTagMonitor.dumpMonitoredMetadata(fd);
839
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800840 if (mInterface->valid()) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -0800841 lines = String8(" HAL device dump:\n");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800842 write(fd, lines.string(), lines.size());
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800843 mInterface->dump(fd);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800844 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800845
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700846 if (gotLock) mLock.unlock();
847 if (gotInterfaceLock) mInterfaceLock.unlock();
848
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800849 return OK;
850}
851
Emilian Peevfaa4bde2020-01-23 12:19:37 -0800852const CameraMetadata& Camera3Device::infoPhysical(const String8& physicalId) const {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800853 ALOGVV("%s: E", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800854 if (CC_UNLIKELY(mStatus == STATUS_UNINITIALIZED ||
855 mStatus == STATUS_ERROR)) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700856 ALOGW("%s: Access to static info %s!", __FUNCTION__,
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800857 mStatus == STATUS_ERROR ?
858 "when in error state" : "before init");
859 }
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700860 if (physicalId.isEmpty()) {
861 return mDeviceInfo;
862 } else {
863 std::string id(physicalId.c_str());
864 if (mPhysicalDeviceInfoMap.find(id) != mPhysicalDeviceInfoMap.end()) {
865 return mPhysicalDeviceInfoMap.at(id);
866 } else {
867 ALOGE("%s: Invalid physical camera id %s", __FUNCTION__, physicalId.c_str());
868 return mDeviceInfo;
869 }
870 }
871}
872
873const CameraMetadata& Camera3Device::info() const {
874 String8 emptyId;
Emilian Peevfaa4bde2020-01-23 12:19:37 -0800875 return infoPhysical(emptyId);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800876}
877
Jianing Wei90e59c92014-03-12 18:29:36 -0700878status_t Camera3Device::checkStatusOkToCaptureLocked() {
879 switch (mStatus) {
880 case STATUS_ERROR:
881 CLOGE("Device has encountered a serious error");
882 return INVALID_OPERATION;
883 case STATUS_UNINITIALIZED:
884 CLOGE("Device not initialized");
885 return INVALID_OPERATION;
886 case STATUS_UNCONFIGURED:
887 case STATUS_CONFIGURED:
888 case STATUS_ACTIVE:
889 // OK
890 break;
891 default:
892 SET_ERR_L("Unexpected status: %d", mStatus);
893 return INVALID_OPERATION;
894 }
895 return OK;
896}
897
898status_t Camera3Device::convertMetadataListToRequestListLocked(
Emilian Peevaebbe412018-01-15 13:53:24 +0000899 const List<const PhysicalCameraSettingsList> &metadataList,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700900 const std::list<const SurfaceMap> &surfaceMaps,
Shuzhen Wang316781a2020-08-18 18:11:01 -0700901 bool repeating, nsecs_t requestTimeNs,
Shuzhen Wang9d066012016-09-30 11:30:20 -0700902 RequestList *requestList) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700903 if (requestList == NULL) {
904 CLOGE("requestList cannot be NULL.");
905 return BAD_VALUE;
906 }
907
Jianing Weicb0652e2014-03-12 18:29:36 -0700908 int32_t burstId = 0;
Emilian Peevaebbe412018-01-15 13:53:24 +0000909 List<const PhysicalCameraSettingsList>::const_iterator metadataIt = metadataList.begin();
Shuzhen Wang0129d522016-10-30 22:43:41 -0700910 std::list<const SurfaceMap>::const_iterator surfaceMapIt = surfaceMaps.begin();
911 for (; metadataIt != metadataList.end() && surfaceMapIt != surfaceMaps.end();
912 ++metadataIt, ++surfaceMapIt) {
913 sp<CaptureRequest> newRequest = setUpRequestLocked(*metadataIt, *surfaceMapIt);
Jianing Wei90e59c92014-03-12 18:29:36 -0700914 if (newRequest == 0) {
915 CLOGE("Can't create capture request");
916 return BAD_VALUE;
917 }
Jianing Weicb0652e2014-03-12 18:29:36 -0700918
Shuzhen Wang9d066012016-09-30 11:30:20 -0700919 newRequest->mRepeating = repeating;
Shuzhen Wang316781a2020-08-18 18:11:01 -0700920 newRequest->mRequestTimeNs = requestTimeNs;
Shuzhen Wang9d066012016-09-30 11:30:20 -0700921
Jianing Weicb0652e2014-03-12 18:29:36 -0700922 // Setup burst Id and request Id
923 newRequest->mResultExtras.burstId = burstId++;
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -0800924 auto requestIdEntry = metadataIt->begin()->metadata.find(ANDROID_REQUEST_ID);
925 if (requestIdEntry.count == 0) {
Jianing Weicb0652e2014-03-12 18:29:36 -0700926 CLOGE("RequestID does not exist in metadata");
927 return BAD_VALUE;
928 }
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -0800929 newRequest->mResultExtras.requestId = requestIdEntry.data.i32[0];
Jianing Weicb0652e2014-03-12 18:29:36 -0700930
Jianing Wei90e59c92014-03-12 18:29:36 -0700931 requestList->push_back(newRequest);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700932
933 ALOGV("%s: requestId = %" PRId32, __FUNCTION__, newRequest->mResultExtras.requestId);
Jianing Wei90e59c92014-03-12 18:29:36 -0700934 }
Shuzhen Wang0129d522016-10-30 22:43:41 -0700935 if (metadataIt != metadataList.end() || surfaceMapIt != surfaceMaps.end()) {
936 ALOGE("%s: metadataList and surfaceMaps are not the same size!", __FUNCTION__);
937 return BAD_VALUE;
938 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -0700939
940 // Setup batch size if this is a high speed video recording request.
941 if (mIsConstrainedHighSpeedConfiguration && requestList->size() > 0) {
942 auto firstRequest = requestList->begin();
943 for (auto& outputStream : (*firstRequest)->mOutputStreams) {
944 if (outputStream->isVideoStream()) {
945 (*firstRequest)->mBatchSize = requestList->size();
Yin-Chia Yeh14ef48d2020-02-10 15:06:37 -0800946 outputStream->setBatchSize(requestList->size());
Chien-Yu Chen85a64552015-08-28 15:46:12 -0700947 break;
948 }
949 }
950 }
951
Jianing Wei90e59c92014-03-12 18:29:36 -0700952 return OK;
953}
954
Yin-Chia Yeh7e5a2042019-02-06 16:01:06 -0800955status_t Camera3Device::capture(CameraMetadata &request, int64_t* lastFrameNumber) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800956 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800957
Emilian Peevaebbe412018-01-15 13:53:24 +0000958 List<const PhysicalCameraSettingsList> requestsList;
Shuzhen Wang0129d522016-10-30 22:43:41 -0700959 std::list<const SurfaceMap> surfaceMaps;
Emilian Peevaebbe412018-01-15 13:53:24 +0000960 convertToRequestList(requestsList, surfaceMaps, request);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700961
Yin-Chia Yeh7e5a2042019-02-06 16:01:06 -0800962 return captureList(requestsList, surfaceMaps, lastFrameNumber);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700963}
964
Emilian Peevaebbe412018-01-15 13:53:24 +0000965void Camera3Device::convertToRequestList(List<const PhysicalCameraSettingsList>& requestsList,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700966 std::list<const SurfaceMap>& surfaceMaps,
967 const CameraMetadata& request) {
Emilian Peevaebbe412018-01-15 13:53:24 +0000968 PhysicalCameraSettingsList requestList;
969 requestList.push_back({std::string(getId().string()), request});
970 requestsList.push_back(requestList);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700971
972 SurfaceMap surfaceMap;
973 camera_metadata_ro_entry streams = request.find(ANDROID_REQUEST_OUTPUT_STREAMS);
974 // With no surface list passed in, stream and surface will have 1-to-1
975 // mapping. So the surface index is 0 for each stream in the surfaceMap.
976 for (size_t i = 0; i < streams.count; i++) {
977 surfaceMap[streams.data.i32[i]].push_back(0);
978 }
979 surfaceMaps.push_back(surfaceMap);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800980}
981
Jianing Wei90e59c92014-03-12 18:29:36 -0700982status_t Camera3Device::submitRequestsHelper(
Emilian Peevaebbe412018-01-15 13:53:24 +0000983 const List<const PhysicalCameraSettingsList> &requests,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700984 const std::list<const SurfaceMap> &surfaceMaps,
985 bool repeating,
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700986 /*out*/
987 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700988 ATRACE_CALL();
Shuzhen Wang316781a2020-08-18 18:11:01 -0700989 nsecs_t requestTimeNs = systemTime();
990
Jianing Wei90e59c92014-03-12 18:29:36 -0700991 Mutex::Autolock il(mInterfaceLock);
992 Mutex::Autolock l(mLock);
993
994 status_t res = checkStatusOkToCaptureLocked();
995 if (res != OK) {
996 // error logged by previous call
997 return res;
998 }
999
1000 RequestList requestList;
1001
Shuzhen Wang0129d522016-10-30 22:43:41 -07001002 res = convertMetadataListToRequestListLocked(requests, surfaceMaps,
Shuzhen Wang316781a2020-08-18 18:11:01 -07001003 repeating, requestTimeNs, /*out*/&requestList);
Jianing Wei90e59c92014-03-12 18:29:36 -07001004 if (res != OK) {
1005 // error logged by previous call
1006 return res;
1007 }
1008
1009 if (repeating) {
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07001010 res = mRequestThread->setRepeatingRequests(requestList, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -07001011 } else {
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07001012 res = mRequestThread->queueRequestList(requestList, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -07001013 }
1014
1015 if (res == OK) {
1016 waitUntilStateThenRelock(/*active*/true, kActiveTimeout);
1017 if (res != OK) {
1018 SET_ERR_L("Can't transition to active in %f seconds!",
1019 kActiveTimeout/1e9);
1020 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001021 ALOGV("Camera %s: Capture request %" PRId32 " enqueued", mId.string(),
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07001022 (*(requestList.begin()))->mResultExtras.requestId);
Jianing Wei90e59c92014-03-12 18:29:36 -07001023 } else {
1024 CLOGE("Cannot queue request. Impossible.");
1025 return BAD_VALUE;
1026 }
1027
1028 return res;
1029}
1030
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001031hardware::Return<void> Camera3Device::requestStreamBuffers(
1032 const hardware::hidl_vec<hardware::camera::device::V3_5::BufferRequest>& bufReqs,
1033 requestStreamBuffers_cb _hidl_cb) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001034 RequestBufferStates states {
Shuzhen Wang316781a2020-08-18 18:11:01 -07001035 mId, mRequestBufferInterfaceLock, mUseHalBufManager, mOutputStreams, mSessionStatsBuilder,
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001036 *this, *mInterface, *this};
1037 camera3::requestStreamBuffers(states, bufReqs, _hidl_cb);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001038 return hardware::Void();
1039}
1040
1041hardware::Return<void> Camera3Device::returnStreamBuffers(
1042 const hardware::hidl_vec<hardware::camera::device::V3_2::StreamBuffer>& buffers) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001043 ReturnBufferStates states {
Shuzhen Wang316781a2020-08-18 18:11:01 -07001044 mId, mUseHalBufManager, mOutputStreams, mSessionStatsBuilder, *mInterface};
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001045 camera3::returnStreamBuffers(states, buffers);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001046 return hardware::Void();
1047}
1048
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001049hardware::Return<void> Camera3Device::processCaptureResult_3_4(
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001050 const hardware::hidl_vec<
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001051 hardware::camera::device::V3_4::CaptureResult>& results) {
Yin-Chia Yeh657c1872017-07-18 18:09:57 -07001052 // Ideally we should grab mLock, but that can lead to deadlock, and
1053 // it's not super important to get up to date value of mStatus for this
1054 // warning print, hence skipping the lock here
1055 if (mStatus == STATUS_ERROR) {
1056 // Per API contract, HAL should act as closed after device error
1057 // But mStatus can be set to error by framework as well, so just log
1058 // a warning here.
1059 ALOGW("%s: received capture result in error state.", __FUNCTION__);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07001060 }
Yifan Honga640c5a2017-04-12 16:30:31 -07001061
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001062 sp<NotificationListener> listener;
1063 {
1064 std::lock_guard<std::mutex> l(mOutputLock);
1065 listener = mListener.promote();
1066 }
1067
Yifan Honga640c5a2017-04-12 16:30:31 -07001068 if (mProcessCaptureResultLock.tryLock() != OK) {
1069 // This should never happen; it indicates a wrong client implementation
1070 // that doesn't follow the contract. But, we can be tolerant here.
1071 ALOGE("%s: callback overlapped! waiting 1s...",
1072 __FUNCTION__);
1073 if (mProcessCaptureResultLock.timedLock(1000000000 /* 1s */) != OK) {
1074 ALOGE("%s: cannot acquire lock in 1s, dropping results",
1075 __FUNCTION__);
1076 // really don't know what to do, so bail out.
1077 return hardware::Void();
1078 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001079 }
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001080 CaptureOutputStates states {
1081 mId,
Shuzhen Wangb7b42652020-05-07 11:59:02 -07001082 mInFlightLock, mLastCompletedRegularFrameNumber,
1083 mLastCompletedReprocessFrameNumber, mLastCompletedZslFrameNumber,
1084 mInFlightMap, mOutputLock, mResultQueue, mResultSignal,
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001085 mNextShutterFrameNumber,
1086 mNextReprocessShutterFrameNumber, mNextZslStillShutterFrameNumber,
1087 mNextResultFrameNumber,
1088 mNextReprocessResultFrameNumber, mNextZslStillResultFrameNumber,
1089 mUseHalBufManager, mUsePartialResult, mNeedFixupMonochromeTags,
1090 mNumPartialResults, mVendorTagId, mDeviceInfo, mPhysicalDeviceInfoMap,
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08001091 mResultMetadataQueue, mDistortionMappers, mZoomRatioMappers, mRotateAndCropMappers,
Shuzhen Wang316781a2020-08-18 18:11:01 -07001092 mTagMonitor, mInputStream, mOutputStreams, mSessionStatsBuilder, listener, *this, *this,
Emilian Peev5104fe92021-10-21 14:27:09 -07001093 *mInterface, mLegacyClient
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001094 };
1095
Yifan Honga640c5a2017-04-12 16:30:31 -07001096 for (const auto& result : results) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001097 processOneCaptureResultLocked(states, result.v3_2, result.physicalCameraMetadata);
Yifan Honga640c5a2017-04-12 16:30:31 -07001098 }
1099 mProcessCaptureResultLock.unlock();
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001100 return hardware::Void();
1101}
1102
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001103// Only one processCaptureResult should be called at a time, so
1104// the locks won't block. The locks are present here simply to enforce this.
1105hardware::Return<void> Camera3Device::processCaptureResult(
1106 const hardware::hidl_vec<
1107 hardware::camera::device::V3_2::CaptureResult>& results) {
1108 hardware::hidl_vec<hardware::camera::device::V3_4::PhysicalCameraMetadata> noPhysMetadata;
1109
1110 // Ideally we should grab mLock, but that can lead to deadlock, and
1111 // it's not super important to get up to date value of mStatus for this
1112 // warning print, hence skipping the lock here
1113 if (mStatus == STATUS_ERROR) {
1114 // Per API contract, HAL should act as closed after device error
1115 // But mStatus can be set to error by framework as well, so just log
1116 // a warning here.
1117 ALOGW("%s: received capture result in error state.", __FUNCTION__);
1118 }
1119
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001120 sp<NotificationListener> listener;
1121 {
1122 std::lock_guard<std::mutex> l(mOutputLock);
1123 listener = mListener.promote();
1124 }
1125
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001126 if (mProcessCaptureResultLock.tryLock() != OK) {
1127 // This should never happen; it indicates a wrong client implementation
1128 // that doesn't follow the contract. But, we can be tolerant here.
1129 ALOGE("%s: callback overlapped! waiting 1s...",
1130 __FUNCTION__);
1131 if (mProcessCaptureResultLock.timedLock(1000000000 /* 1s */) != OK) {
1132 ALOGE("%s: cannot acquire lock in 1s, dropping results",
1133 __FUNCTION__);
1134 // really don't know what to do, so bail out.
1135 return hardware::Void();
1136 }
1137 }
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001138
1139 CaptureOutputStates states {
1140 mId,
Shuzhen Wangb7b42652020-05-07 11:59:02 -07001141 mInFlightLock, mLastCompletedRegularFrameNumber,
1142 mLastCompletedReprocessFrameNumber, mLastCompletedZslFrameNumber,
1143 mInFlightMap, mOutputLock, mResultQueue, mResultSignal,
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001144 mNextShutterFrameNumber,
1145 mNextReprocessShutterFrameNumber, mNextZslStillShutterFrameNumber,
1146 mNextResultFrameNumber,
1147 mNextReprocessResultFrameNumber, mNextZslStillResultFrameNumber,
1148 mUseHalBufManager, mUsePartialResult, mNeedFixupMonochromeTags,
1149 mNumPartialResults, mVendorTagId, mDeviceInfo, mPhysicalDeviceInfoMap,
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08001150 mResultMetadataQueue, mDistortionMappers, mZoomRatioMappers, mRotateAndCropMappers,
Shuzhen Wang316781a2020-08-18 18:11:01 -07001151 mTagMonitor, mInputStream, mOutputStreams, mSessionStatsBuilder, listener, *this, *this,
Emilian Peev5104fe92021-10-21 14:27:09 -07001152 *mInterface, mLegacyClient
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001153 };
1154
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001155 for (const auto& result : results) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001156 processOneCaptureResultLocked(states, result, noPhysMetadata);
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001157 }
1158 mProcessCaptureResultLock.unlock();
1159 return hardware::Void();
1160}
1161
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001162hardware::Return<void> Camera3Device::notify(
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001163 const hardware::hidl_vec<hardware::camera::device::V3_2::NotifyMsg>& msgs) {
Yin-Chia Yeh657c1872017-07-18 18:09:57 -07001164 // Ideally we should grab mLock, but that can lead to deadlock, and
1165 // it's not super important to get up to date value of mStatus for this
1166 // warning print, hence skipping the lock here
1167 if (mStatus == STATUS_ERROR) {
1168 // Per API contract, HAL should act as closed after device error
1169 // But mStatus can be set to error by framework as well, so just log
1170 // a warning here.
1171 ALOGW("%s: received notify message in error state.", __FUNCTION__);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07001172 }
Yin-Chia Yeh657c1872017-07-18 18:09:57 -07001173
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001174 sp<NotificationListener> listener;
1175 {
1176 std::lock_guard<std::mutex> l(mOutputLock);
1177 listener = mListener.promote();
1178 }
1179
1180 CaptureOutputStates states {
1181 mId,
Shuzhen Wangb7b42652020-05-07 11:59:02 -07001182 mInFlightLock, mLastCompletedRegularFrameNumber,
1183 mLastCompletedReprocessFrameNumber, mLastCompletedZslFrameNumber,
1184 mInFlightMap, mOutputLock, mResultQueue, mResultSignal,
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001185 mNextShutterFrameNumber,
1186 mNextReprocessShutterFrameNumber, mNextZslStillShutterFrameNumber,
1187 mNextResultFrameNumber,
1188 mNextReprocessResultFrameNumber, mNextZslStillResultFrameNumber,
1189 mUseHalBufManager, mUsePartialResult, mNeedFixupMonochromeTags,
1190 mNumPartialResults, mVendorTagId, mDeviceInfo, mPhysicalDeviceInfoMap,
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08001191 mResultMetadataQueue, mDistortionMappers, mZoomRatioMappers, mRotateAndCropMappers,
Shuzhen Wang316781a2020-08-18 18:11:01 -07001192 mTagMonitor, mInputStream, mOutputStreams, mSessionStatsBuilder, listener, *this, *this,
Emilian Peev5104fe92021-10-21 14:27:09 -07001193 *mInterface, mLegacyClient
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001194 };
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001195 for (const auto& msg : msgs) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001196 camera3::notify(states, msg);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001197 }
1198 return hardware::Void();
1199}
1200
Emilian Peevaebbe412018-01-15 13:53:24 +00001201status_t Camera3Device::captureList(const List<const PhysicalCameraSettingsList> &requestsList,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001202 const std::list<const SurfaceMap> &surfaceMaps,
Jianing Weicb0652e2014-03-12 18:29:36 -07001203 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -07001204 ATRACE_CALL();
1205
Emilian Peevaebbe412018-01-15 13:53:24 +00001206 return submitRequestsHelper(requestsList, surfaceMaps, /*repeating*/false, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -07001207}
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001208
Jianing Weicb0652e2014-03-12 18:29:36 -07001209status_t Camera3Device::setStreamingRequest(const CameraMetadata &request,
1210 int64_t* /*lastFrameNumber*/) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001211 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001212
Emilian Peevaebbe412018-01-15 13:53:24 +00001213 List<const PhysicalCameraSettingsList> requestsList;
Shuzhen Wang0129d522016-10-30 22:43:41 -07001214 std::list<const SurfaceMap> surfaceMaps;
Emilian Peevaebbe412018-01-15 13:53:24 +00001215 convertToRequestList(requestsList, surfaceMaps, request);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001216
Emilian Peevaebbe412018-01-15 13:53:24 +00001217 return setStreamingRequestList(requestsList, /*surfaceMap*/surfaceMaps,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001218 /*lastFrameNumber*/NULL);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001219}
1220
Emilian Peevaebbe412018-01-15 13:53:24 +00001221status_t Camera3Device::setStreamingRequestList(
1222 const List<const PhysicalCameraSettingsList> &requestsList,
1223 const std::list<const SurfaceMap> &surfaceMaps, int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -07001224 ATRACE_CALL();
1225
Emilian Peevaebbe412018-01-15 13:53:24 +00001226 return submitRequestsHelper(requestsList, surfaceMaps, /*repeating*/true, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -07001227}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001228
1229sp<Camera3Device::CaptureRequest> Camera3Device::setUpRequestLocked(
Emilian Peevaebbe412018-01-15 13:53:24 +00001230 const PhysicalCameraSettingsList &request, const SurfaceMap &surfaceMap) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001231 status_t res;
1232
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001233 if (mStatus == STATUS_UNCONFIGURED || mNeedConfig) {
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08001234 // This point should only be reached via API1 (API2 must explicitly call configureStreams)
1235 // so unilaterally select normal operating mode.
Emilian Peevaebbe412018-01-15 13:53:24 +00001236 res = filterParamsAndConfigureLocked(request.begin()->metadata,
Emilian Peevf4816702020-04-03 15:44:51 -07001237 CAMERA_STREAM_CONFIGURATION_NORMAL_MODE);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001238 // Stream configuration failed. Client might try other configuraitons.
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001239 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001240 CLOGE("Can't set up streams: %s (%d)", strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001241 return NULL;
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001242 } else if (mStatus == STATUS_UNCONFIGURED) {
1243 // Stream configuration successfully configure to empty stream configuration.
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001244 CLOGE("No streams configured");
1245 return NULL;
1246 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001247 }
1248
Shuzhen Wang0129d522016-10-30 22:43:41 -07001249 sp<CaptureRequest> newRequest = createCaptureRequest(request, surfaceMap);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001250 return newRequest;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001251}
1252
Jianing Weicb0652e2014-03-12 18:29:36 -07001253status_t Camera3Device::clearStreamingRequest(int64_t *lastFrameNumber) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001254 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001255 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001256 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001257
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001258 switch (mStatus) {
1259 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001260 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001261 return INVALID_OPERATION;
1262 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001263 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001264 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001265 case STATUS_UNCONFIGURED:
1266 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001267 case STATUS_ACTIVE:
1268 // OK
1269 break;
1270 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001271 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001272 return INVALID_OPERATION;
1273 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001274 ALOGV("Camera %s: Clearing repeating request", mId.string());
Jianing Weicb0652e2014-03-12 18:29:36 -07001275
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07001276 return mRequestThread->clearRepeatingRequests(lastFrameNumber);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001277}
1278
1279status_t Camera3Device::waitUntilRequestReceived(int32_t requestId, nsecs_t timeout) {
1280 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001281 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001282
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001283 return mRequestThread->waitUntilRequestProcessed(requestId, timeout);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001284}
1285
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001286status_t Camera3Device::createInputStream(
Shuzhen Wang83bff122020-11-20 15:51:39 -08001287 uint32_t width, uint32_t height, int format, bool isMultiResolution, int *id) {
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001288 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001289 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001290 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001291 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001292 ALOGV("Camera %s: Creating new input stream %d: %d x %d, format %d",
1293 mId.string(), mNextStreamId, width, height, format);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001294
1295 status_t res;
1296 bool wasActive = false;
1297
1298 switch (mStatus) {
1299 case STATUS_ERROR:
1300 ALOGE("%s: Device has encountered a serious error", __FUNCTION__);
1301 return INVALID_OPERATION;
1302 case STATUS_UNINITIALIZED:
1303 ALOGE("%s: Device not initialized", __FUNCTION__);
1304 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001305 case STATUS_UNCONFIGURED:
1306 case STATUS_CONFIGURED:
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001307 // OK
1308 break;
1309 case STATUS_ACTIVE:
1310 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001311 res = internalPauseAndWaitLocked(maxExpectedDuration);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001312 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001313 SET_ERR_L("Can't pause captures to reconfigure streams!");
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001314 return res;
1315 }
1316 wasActive = true;
1317 break;
1318 default:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001319 SET_ERR_L("%s: Unexpected status: %d", mStatus);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001320 return INVALID_OPERATION;
1321 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001322 assert(mStatus != STATUS_ACTIVE);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001323
1324 if (mInputStream != 0) {
1325 ALOGE("%s: Cannot create more than 1 input stream", __FUNCTION__);
1326 return INVALID_OPERATION;
1327 }
1328
1329 sp<Camera3InputStream> newStream = new Camera3InputStream(mNextStreamId,
1330 width, height, format);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001331 newStream->setStatusTracker(mStatusTracker);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001332
1333 mInputStream = newStream;
Shuzhen Wang83bff122020-11-20 15:51:39 -08001334 mIsInputStreamMultiResolution = isMultiResolution;
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001335
1336 *id = mNextStreamId++;
1337
1338 // Continue captures if active at start
1339 if (wasActive) {
1340 ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001341 // Reuse current operating mode and session parameters for new stream config
1342 res = configureStreamsLocked(mOperatingMode, mSessionParams);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001343 if (res != OK) {
1344 ALOGE("%s: Can't reconfigure device for new stream %d: %s (%d)",
1345 __FUNCTION__, mNextStreamId, strerror(-res), res);
1346 return res;
1347 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001348 internalResumeLocked();
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001349 }
1350
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001351 ALOGV("Camera %s: Created input stream", mId.string());
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001352 return OK;
1353}
1354
Eino-Ville Talvala727d1722015-06-09 13:44:19 -07001355status_t Camera3Device::createStream(sp<Surface> consumer,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001356 uint32_t width, uint32_t height, int format,
Emilian Peevf4816702020-04-03 15:44:51 -07001357 android_dataspace dataSpace, camera_stream_rotation_t rotation, int *id,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001358 const String8& physicalCameraId,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001359 const std::unordered_set<int32_t> &sensorPixelModesUsed,
1360 std::vector<int> *surfaceIds, int streamSetId, bool isShared, bool isMultiResolution,
1361 uint64_t consumerUsage) {
Shuzhen Wang0129d522016-10-30 22:43:41 -07001362 ATRACE_CALL();
1363
1364 if (consumer == nullptr) {
1365 ALOGE("%s: consumer must not be null", __FUNCTION__);
1366 return BAD_VALUE;
1367 }
1368
1369 std::vector<sp<Surface>> consumers;
1370 consumers.push_back(consumer);
1371
1372 return createStream(consumers, /*hasDeferredConsumer*/ false, width, height,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001373 format, dataSpace, rotation, id, physicalCameraId, sensorPixelModesUsed, surfaceIds,
1374 streamSetId, isShared, isMultiResolution, consumerUsage);
1375}
1376
1377static bool isRawFormat(int format) {
1378 switch (format) {
1379 case HAL_PIXEL_FORMAT_RAW16:
1380 case HAL_PIXEL_FORMAT_RAW12:
1381 case HAL_PIXEL_FORMAT_RAW10:
1382 case HAL_PIXEL_FORMAT_RAW_OPAQUE:
1383 return true;
1384 default:
1385 return false;
1386 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001387}
1388
1389status_t Camera3Device::createStream(const std::vector<sp<Surface>>& consumers,
1390 bool hasDeferredConsumer, uint32_t width, uint32_t height, int format,
Emilian Peevf4816702020-04-03 15:44:51 -07001391 android_dataspace dataSpace, camera_stream_rotation_t rotation, int *id,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001392 const String8& physicalCameraId, const std::unordered_set<int32_t> &sensorPixelModesUsed,
Shuzhen Wang83bff122020-11-20 15:51:39 -08001393 std::vector<int> *surfaceIds, int streamSetId, bool isShared, bool isMultiResolution,
1394 uint64_t consumerUsage) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001395 ATRACE_CALL();
Emilian Peev40ead602017-09-26 15:46:36 +01001396
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001397 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001398 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001399 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001400 ALOGV("Camera %s: Creating new stream %d: %d x %d, format %d, dataspace %d rotation %d"
Shuzhen Wang83bff122020-11-20 15:51:39 -08001401 " consumer usage %" PRIu64 ", isShared %d, physicalCameraId %s, isMultiResolution %d",
1402 mId.string(), mNextStreamId, width, height, format, dataSpace, rotation,
1403 consumerUsage, isShared, physicalCameraId.string(), isMultiResolution);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001404
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001405 status_t res;
1406 bool wasActive = false;
1407
1408 switch (mStatus) {
1409 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001410 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001411 return INVALID_OPERATION;
1412 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001413 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001414 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001415 case STATUS_UNCONFIGURED:
1416 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001417 // OK
1418 break;
1419 case STATUS_ACTIVE:
1420 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001421 res = internalPauseAndWaitLocked(maxExpectedDuration);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001422 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001423 SET_ERR_L("Can't pause captures to reconfigure streams!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001424 return res;
1425 }
1426 wasActive = true;
1427 break;
1428 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001429 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001430 return INVALID_OPERATION;
1431 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001432 assert(mStatus != STATUS_ACTIVE);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001433
1434 sp<Camera3OutputStream> newStream;
Zhijun He5d677d12016-05-29 16:52:39 -07001435
Shuzhen Wang0129d522016-10-30 22:43:41 -07001436 if (consumers.size() == 0 && !hasDeferredConsumer) {
1437 ALOGE("%s: Number of consumers cannot be smaller than 1", __FUNCTION__);
1438 return BAD_VALUE;
1439 }
Zhijun He5d677d12016-05-29 16:52:39 -07001440
Shuzhen Wang0129d522016-10-30 22:43:41 -07001441 if (hasDeferredConsumer && format != HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
Zhijun He5d677d12016-05-29 16:52:39 -07001442 ALOGE("Deferred consumer stream creation only support IMPLEMENTATION_DEFINED format");
1443 return BAD_VALUE;
1444 }
1445
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001446 if (isRawFormat(format) && sensorPixelModesUsed.size() > 1) {
1447 // We can't use one stream with a raw format in both sensor pixel modes since its going to
1448 // be found in only one sensor pixel mode.
1449 ALOGE("%s: RAW opaque stream cannot be used with > 1 sensor pixel modes", __FUNCTION__);
1450 return BAD_VALUE;
1451 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001452 if (format == HAL_PIXEL_FORMAT_BLOB) {
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -07001453 ssize_t blobBufferSize;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001454 if (dataSpace == HAL_DATASPACE_DEPTH) {
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -07001455 blobBufferSize = getPointCloudBufferSize();
1456 if (blobBufferSize <= 0) {
1457 SET_ERR_L("Invalid point cloud buffer size %zd", blobBufferSize);
1458 return BAD_VALUE;
1459 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001460 } else if (dataSpace == static_cast<android_dataspace>(HAL_DATASPACE_JPEG_APP_SEGMENTS)) {
1461 blobBufferSize = width * height;
1462 } else {
1463 blobBufferSize = getJpegBufferSize(width, height);
1464 if (blobBufferSize <= 0) {
1465 SET_ERR_L("Invalid jpeg buffer size %zd", blobBufferSize);
1466 return BAD_VALUE;
1467 }
Zhijun Hef7da0962014-04-24 13:27:56 -07001468 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001469 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001470 width, height, blobBufferSize, format, dataSpace, rotation,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001471 mTimestampOffset, physicalCameraId, sensorPixelModesUsed, streamSetId,
1472 isMultiResolution);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -08001473 } else if (format == HAL_PIXEL_FORMAT_RAW_OPAQUE) {
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001474 bool maxResolution =
1475 sensorPixelModesUsed.find(ANDROID_SENSOR_PIXEL_MODE_MAXIMUM_RESOLUTION) !=
1476 sensorPixelModesUsed.end();
1477 ssize_t rawOpaqueBufferSize = getRawOpaqueBufferSize(width, height, maxResolution);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -08001478 if (rawOpaqueBufferSize <= 0) {
1479 SET_ERR_L("Invalid RAW opaque buffer size %zd", rawOpaqueBufferSize);
1480 return BAD_VALUE;
1481 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001482 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001483 width, height, rawOpaqueBufferSize, format, dataSpace, rotation,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001484 mTimestampOffset, physicalCameraId, sensorPixelModesUsed, streamSetId,
1485 isMultiResolution);
Shuzhen Wang758c2152017-01-10 18:26:18 -08001486 } else if (isShared) {
1487 newStream = new Camera3SharedOutputStream(mNextStreamId, consumers,
1488 width, height, format, consumerUsage, dataSpace, rotation,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001489 mTimestampOffset, physicalCameraId, sensorPixelModesUsed, streamSetId,
1490 mUseHalBufManager);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001491 } else if (consumers.size() == 0 && hasDeferredConsumer) {
Zhijun He5d677d12016-05-29 16:52:39 -07001492 newStream = new Camera3OutputStream(mNextStreamId,
1493 width, height, format, consumerUsage, dataSpace, rotation,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001494 mTimestampOffset, physicalCameraId, sensorPixelModesUsed, streamSetId,
1495 isMultiResolution);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001496 } else {
Shuzhen Wang0129d522016-10-30 22:43:41 -07001497 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001498 width, height, format, dataSpace, rotation,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001499 mTimestampOffset, physicalCameraId, sensorPixelModesUsed, streamSetId,
1500 isMultiResolution);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001501 }
Emilian Peev40ead602017-09-26 15:46:36 +01001502
1503 size_t consumerCount = consumers.size();
1504 for (size_t i = 0; i < consumerCount; i++) {
1505 int id = newStream->getSurfaceId(consumers[i]);
1506 if (id < 0) {
1507 SET_ERR_L("Invalid surface id");
1508 return BAD_VALUE;
1509 }
1510 if (surfaceIds != nullptr) {
1511 surfaceIds->push_back(id);
1512 }
1513 }
1514
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001515 newStream->setStatusTracker(mStatusTracker);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001516
Emilian Peev08dd2452017-04-06 16:55:14 +01001517 newStream->setBufferManager(mBufferManager);
Zhijun He125684a2015-12-26 15:07:30 -08001518
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08001519 newStream->setImageDumpMask(mImageDumpMask);
1520
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001521 res = mOutputStreams.add(mNextStreamId, newStream);
1522 if (res < 0) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001523 SET_ERR_L("Can't add new stream to set: %s (%d)", strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001524 return res;
1525 }
1526
Shuzhen Wang316781a2020-08-18 18:11:01 -07001527 mSessionStatsBuilder.addStream(mNextStreamId);
1528
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001529 *id = mNextStreamId++;
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07001530 mNeedConfig = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001531
1532 // Continue captures if active at start
1533 if (wasActive) {
1534 ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001535 // Reuse current operating mode and session parameters for new stream config
1536 res = configureStreamsLocked(mOperatingMode, mSessionParams);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001537 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001538 CLOGE("Can't reconfigure device for new stream %d: %s (%d)",
1539 mNextStreamId, strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001540 return res;
1541 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001542 internalResumeLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001543 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001544 ALOGV("Camera %s: Created new stream", mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001545 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001546}
1547
Emilian Peev710c1422017-08-30 11:19:38 +01001548status_t Camera3Device::getStreamInfo(int id, StreamInfo *streamInfo) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001549 ATRACE_CALL();
Emilian Peev710c1422017-08-30 11:19:38 +01001550 if (nullptr == streamInfo) {
1551 return BAD_VALUE;
1552 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001553 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001554 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001555
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001556 switch (mStatus) {
1557 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001558 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001559 return INVALID_OPERATION;
1560 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001561 CLOGE("Device not initialized!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001562 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001563 case STATUS_UNCONFIGURED:
1564 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001565 case STATUS_ACTIVE:
1566 // OK
1567 break;
1568 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001569 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001570 return INVALID_OPERATION;
1571 }
1572
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001573 sp<Camera3StreamInterface> stream = mOutputStreams.get(id);
1574 if (stream == nullptr) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001575 CLOGE("Stream %d is unknown", id);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001576 return BAD_VALUE;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001577 }
1578
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001579 streamInfo->width = stream->getWidth();
1580 streamInfo->height = stream->getHeight();
1581 streamInfo->format = stream->getFormat();
1582 streamInfo->dataSpace = stream->getDataSpace();
1583 streamInfo->formatOverridden = stream->isFormatOverridden();
1584 streamInfo->originalFormat = stream->getOriginalFormat();
1585 streamInfo->dataSpaceOverridden = stream->isDataSpaceOverridden();
1586 streamInfo->originalDataSpace = stream->getOriginalDataSpace();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001587 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001588}
1589
1590status_t Camera3Device::setStreamTransform(int id,
1591 int transform) {
1592 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001593 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001594 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001595
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001596 switch (mStatus) {
1597 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001598 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001599 return INVALID_OPERATION;
1600 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001601 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001602 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001603 case STATUS_UNCONFIGURED:
1604 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001605 case STATUS_ACTIVE:
1606 // OK
1607 break;
1608 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001609 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001610 return INVALID_OPERATION;
1611 }
1612
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001613 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(id);
1614 if (stream == nullptr) {
1615 CLOGE("Stream %d does not exist", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001616 return BAD_VALUE;
1617 }
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001618 return stream->setTransform(transform);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001619}
1620
1621status_t Camera3Device::deleteStream(int id) {
1622 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001623 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001624 Mutex::Autolock l(mLock);
1625 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001626
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001627 ALOGV("%s: Camera %s: Deleting stream %d", __FUNCTION__, mId.string(), id);
Igor Murashkine2172be2013-05-28 15:31:39 -07001628
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001629 // CameraDevice semantics require device to already be idle before
1630 // deleteStream is called, unlike for createStream.
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001631 if (mStatus == STATUS_ACTIVE) {
Yin-Chia Yeh693047d2018-03-08 12:14:19 -08001632 ALOGW("%s: Camera %s: Device not idle", __FUNCTION__, mId.string());
Igor Murashkin52827132013-05-13 14:53:44 -07001633 return -EBUSY;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001634 }
1635
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07001636 if (mStatus == STATUS_ERROR) {
1637 ALOGW("%s: Camera %s: deleteStream not allowed in ERROR state",
1638 __FUNCTION__, mId.string());
1639 return -EBUSY;
1640 }
1641
Igor Murashkin2fba5842013-04-22 14:03:54 -07001642 sp<Camera3StreamInterface> deletedStream;
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001643 sp<Camera3StreamInterface> stream = mOutputStreams.get(id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001644 if (mInputStream != NULL && id == mInputStream->getId()) {
1645 deletedStream = mInputStream;
1646 mInputStream.clear();
1647 } else {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001648 if (stream == nullptr) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001649 CLOGE("Stream %d does not exist", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001650 return BAD_VALUE;
1651 }
Shuzhen Wang316781a2020-08-18 18:11:01 -07001652 mSessionStatsBuilder.removeStream(id);
Zhijun He5f446352014-01-22 09:49:33 -08001653 }
1654
1655 // Delete output stream or the output part of a bi-directional stream.
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001656 if (stream != nullptr) {
1657 deletedStream = stream;
1658 mOutputStreams.remove(id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001659 }
1660
1661 // Free up the stream endpoint so that it can be used by some other stream
1662 res = deletedStream->disconnect();
1663 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001664 SET_ERR_L("Can't disconnect deleted stream %d", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001665 // fall through since we want to still list the stream as deleted.
1666 }
1667 mDeletedStreams.add(deletedStream);
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07001668 mNeedConfig = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001669
1670 return res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001671}
1672
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001673status_t Camera3Device::configureStreams(const CameraMetadata& sessionParams, int operatingMode) {
Igor Murashkine2d167e2014-08-19 16:19:59 -07001674 ATRACE_CALL();
1675 ALOGV("%s: E", __FUNCTION__);
1676
1677 Mutex::Autolock il(mInterfaceLock);
1678 Mutex::Autolock l(mLock);
Chien-Yu Chen17338fc2015-06-18 16:30:12 -07001679
Emilian Peev811d2952018-05-25 11:08:40 +01001680 // In case the client doesn't include any session parameter, try a
1681 // speculative configuration using the values from the last cached
1682 // default request.
1683 if (sessionParams.isEmpty() &&
Emilian Peevf4816702020-04-03 15:44:51 -07001684 ((mLastTemplateId > 0) && (mLastTemplateId < CAMERA_TEMPLATE_COUNT)) &&
Emilian Peev811d2952018-05-25 11:08:40 +01001685 (!mRequestTemplateCache[mLastTemplateId].isEmpty())) {
1686 ALOGV("%s: Speculative session param configuration with template id: %d", __func__,
1687 mLastTemplateId);
1688 return filterParamsAndConfigureLocked(mRequestTemplateCache[mLastTemplateId],
1689 operatingMode);
1690 }
1691
Emilian Peevac3ce6c2017-12-12 15:27:02 +00001692 return filterParamsAndConfigureLocked(sessionParams, operatingMode);
1693}
1694
1695status_t Camera3Device::filterParamsAndConfigureLocked(const CameraMetadata& sessionParams,
1696 int operatingMode) {
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001697 //Filter out any incoming session parameters
1698 const CameraMetadata params(sessionParams);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001699 camera_metadata_entry_t availableSessionKeys = mDeviceInfo.find(
1700 ANDROID_REQUEST_AVAILABLE_SESSION_KEYS);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00001701 CameraMetadata filteredParams(availableSessionKeys.count);
1702 camera_metadata_t *meta = const_cast<camera_metadata_t *>(
1703 filteredParams.getAndLock());
1704 set_camera_metadata_vendor_id(meta, mVendorTagId);
1705 filteredParams.unlock(meta);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001706 if (availableSessionKeys.count > 0) {
1707 for (size_t i = 0; i < availableSessionKeys.count; i++) {
1708 camera_metadata_ro_entry entry = params.find(
1709 availableSessionKeys.data.i32[i]);
1710 if (entry.count > 0) {
1711 filteredParams.update(entry);
1712 }
1713 }
1714 }
1715
1716 return configureStreamsLocked(operatingMode, filteredParams);
Igor Murashkine2d167e2014-08-19 16:19:59 -07001717}
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001718
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07001719status_t Camera3Device::getInputBufferProducer(
1720 sp<IGraphicBufferProducer> *producer) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07001721 ATRACE_CALL();
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07001722 Mutex::Autolock il(mInterfaceLock);
1723 Mutex::Autolock l(mLock);
1724
1725 if (producer == NULL) {
1726 return BAD_VALUE;
1727 } else if (mInputStream == NULL) {
1728 return INVALID_OPERATION;
1729 }
1730
1731 return mInputStream->getInputBufferProducer(producer);
1732}
1733
Emilian Peevf4816702020-04-03 15:44:51 -07001734status_t Camera3Device::createDefaultRequest(camera_request_template_t templateId,
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001735 CameraMetadata *request) {
1736 ATRACE_CALL();
Alex Rayfe7e0c62013-05-30 00:12:13 -07001737 ALOGV("%s: for template %d", __FUNCTION__, templateId);
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08001738
Emilian Peevf4816702020-04-03 15:44:51 -07001739 if (templateId <= 0 || templateId >= CAMERA_TEMPLATE_COUNT) {
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08001740 android_errorWriteWithInfoLog(CameraService::SN_EVENT_LOG_ID, "26866110",
Jayant Chowdhary12361932018-08-27 14:46:13 -07001741 CameraThreadState::getCallingUid(), nullptr, 0);
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08001742 return BAD_VALUE;
1743 }
1744
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001745 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001746
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001747 {
1748 Mutex::Autolock l(mLock);
1749 switch (mStatus) {
1750 case STATUS_ERROR:
1751 CLOGE("Device has encountered a serious error");
1752 return INVALID_OPERATION;
1753 case STATUS_UNINITIALIZED:
1754 CLOGE("Device is not initialized!");
1755 return INVALID_OPERATION;
1756 case STATUS_UNCONFIGURED:
1757 case STATUS_CONFIGURED:
1758 case STATUS_ACTIVE:
1759 // OK
1760 break;
1761 default:
1762 SET_ERR_L("Unexpected status: %d", mStatus);
1763 return INVALID_OPERATION;
1764 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001765
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001766 if (!mRequestTemplateCache[templateId].isEmpty()) {
1767 *request = mRequestTemplateCache[templateId];
Emilian Peev811d2952018-05-25 11:08:40 +01001768 mLastTemplateId = templateId;
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001769 return OK;
1770 }
Zhijun Hea1530f12014-09-14 12:44:20 -07001771 }
1772
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001773 camera_metadata_t *rawRequest;
1774 status_t res = mInterface->constructDefaultRequestSettings(
Emilian Peevf4816702020-04-03 15:44:51 -07001775 (camera_request_template_t) templateId, &rawRequest);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001776
1777 {
1778 Mutex::Autolock l(mLock);
1779 if (res == BAD_VALUE) {
1780 ALOGI("%s: template %d is not supported on this camera device",
1781 __FUNCTION__, templateId);
1782 return res;
1783 } else if (res != OK) {
1784 CLOGE("Unable to construct request template %d: %s (%d)",
1785 templateId, strerror(-res), res);
1786 return res;
1787 }
1788
1789 set_camera_metadata_vendor_id(rawRequest, mVendorTagId);
1790 mRequestTemplateCache[templateId].acquire(rawRequest);
1791
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08001792 // Override the template request with zoomRatioMapper
1793 res = mZoomRatioMappers[mId.c_str()].initZoomRatioInTemplate(
1794 &mRequestTemplateCache[templateId]);
1795 if (res != OK) {
1796 CLOGE("Failed to update zoom ratio for template %d: %s (%d)",
1797 templateId, strerror(-res), res);
1798 return res;
1799 }
1800
Shuzhen Wangd25dc972020-03-24 17:11:43 -07001801 // Fill in JPEG_QUALITY if not available
1802 if (!mRequestTemplateCache[templateId].exists(ANDROID_JPEG_QUALITY)) {
1803 static const uint8_t kDefaultJpegQuality = 95;
1804 mRequestTemplateCache[templateId].update(ANDROID_JPEG_QUALITY,
1805 &kDefaultJpegQuality, 1);
1806 }
1807
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001808 *request = mRequestTemplateCache[templateId];
Emilian Peev811d2952018-05-25 11:08:40 +01001809 mLastTemplateId = templateId;
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001810 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001811 return OK;
1812}
1813
1814status_t Camera3Device::waitUntilDrained() {
1815 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001816 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001817 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001818 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001819
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001820 return waitUntilDrainedLocked(maxExpectedDuration);
Zhijun He69a37482014-03-23 18:44:49 -07001821}
1822
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001823status_t Camera3Device::waitUntilDrainedLocked(nsecs_t maxExpectedDuration) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001824 switch (mStatus) {
1825 case STATUS_UNINITIALIZED:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001826 case STATUS_UNCONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001827 ALOGV("%s: Already idle", __FUNCTION__);
1828 return OK;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001829 case STATUS_CONFIGURED:
1830 // To avoid race conditions, check with tracker to be sure
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001831 case STATUS_ERROR:
1832 case STATUS_ACTIVE:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001833 // Need to verify shut down
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001834 break;
1835 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001836 SET_ERR_L("Unexpected status: %d",mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001837 return INVALID_OPERATION;
1838 }
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07001839 ALOGV("%s: Camera %s: Waiting until idle (%" PRIi64 "ns)", __FUNCTION__, mId.string(),
1840 maxExpectedDuration);
1841 status_t res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
Eino-Ville Talvala9c8a0912014-09-14 14:52:19 -07001842 if (res != OK) {
Yin-Chia Yeh87b3ec02019-06-03 10:44:39 -07001843 mStatusTracker->dumpActiveComponents();
Eino-Ville Talvala9c8a0912014-09-14 14:52:19 -07001844 SET_ERR_L("Error waiting for HAL to drain: %s (%d)", strerror(-res),
1845 res);
1846 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001847 return res;
1848}
1849
Ruben Brunk183f0562015-08-12 12:55:02 -07001850void Camera3Device::internalUpdateStatusLocked(Status status) {
1851 mStatus = status;
1852 mRecentStatusUpdates.add(mStatus);
1853 mStatusChanged.broadcast();
1854}
1855
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001856// Pause to reconfigure
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001857status_t Camera3Device::internalPauseAndWaitLocked(nsecs_t maxExpectedDuration) {
Emilian Peeve86358b2019-02-15 13:51:39 -08001858 if (mRequestThread.get() != nullptr) {
1859 mRequestThread->setPaused(true);
1860 } else {
1861 return NO_INIT;
1862 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001863
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07001864 ALOGV("%s: Camera %s: Internal wait until idle (% " PRIi64 " ns)", __FUNCTION__, mId.string(),
1865 maxExpectedDuration);
1866 status_t res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001867 if (res != OK) {
1868 SET_ERR_L("Can't idle device in %f seconds!",
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07001869 maxExpectedDuration/1e9);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001870 }
1871
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001872 return res;
1873}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001874
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001875// Resume after internalPauseAndWaitLocked
1876status_t Camera3Device::internalResumeLocked() {
1877 status_t res;
1878
1879 mRequestThread->setPaused(false);
1880
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08001881 ALOGV("%s: Camera %s: Internal wait until active (% " PRIi64 " ns)", __FUNCTION__, mId.string(),
1882 kActiveTimeout);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001883 res = waitUntilStateThenRelock(/*active*/ true, kActiveTimeout);
1884 if (res != OK) {
1885 SET_ERR_L("Can't transition to active in %f seconds!",
1886 kActiveTimeout/1e9);
1887 }
1888 mPauseStateNotify = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001889 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001890}
1891
Ruben Brunk183f0562015-08-12 12:55:02 -07001892status_t Camera3Device::waitUntilStateThenRelock(bool active, nsecs_t timeout) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001893 status_t res = OK;
Ruben Brunk183f0562015-08-12 12:55:02 -07001894
1895 size_t startIndex = 0;
1896 if (mStatusWaiters == 0) {
1897 // Clear the list of recent statuses if there are no existing threads waiting on updates to
1898 // this status list
1899 mRecentStatusUpdates.clear();
1900 } else {
1901 // If other threads are waiting on updates to this status list, set the position of the
1902 // first element that this list will check rather than clearing the list.
1903 startIndex = mRecentStatusUpdates.size();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001904 }
1905
Ruben Brunk183f0562015-08-12 12:55:02 -07001906 mStatusWaiters++;
1907
Yin-Chia Yehe52b8fa2020-07-28 00:17:58 -07001908 bool signalPipelineDrain = false;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07001909 if (!active && mUseHalBufManager) {
1910 auto streamIds = mOutputStreams.getStreamIds();
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08001911 if (mStatus == STATUS_ACTIVE) {
1912 mRequestThread->signalPipelineDrain(streamIds);
Yin-Chia Yehe52b8fa2020-07-28 00:17:58 -07001913 signalPipelineDrain = true;
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08001914 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07001915 mRequestBufferSM.onWaitUntilIdle();
1916 }
1917
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001918 bool stateSeen = false;
1919 do {
Ruben Brunk183f0562015-08-12 12:55:02 -07001920 if (active == (mStatus == STATUS_ACTIVE)) {
1921 // Desired state is current
1922 break;
1923 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001924
1925 res = mStatusChanged.waitRelative(mLock, timeout);
1926 if (res != OK) break;
1927
Ruben Brunk183f0562015-08-12 12:55:02 -07001928 // This is impossible, but if not, could result in subtle deadlocks and invalid state
1929 // transitions.
1930 LOG_ALWAYS_FATAL_IF(startIndex > mRecentStatusUpdates.size(),
1931 "%s: Skipping status updates in Camera3Device, may result in deadlock.",
1932 __FUNCTION__);
1933
1934 // Encountered desired state since we began waiting
1935 for (size_t i = startIndex; i < mRecentStatusUpdates.size(); i++) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001936 if (active == (mRecentStatusUpdates[i] == STATUS_ACTIVE) ) {
1937 stateSeen = true;
1938 break;
1939 }
1940 }
1941 } while (!stateSeen);
1942
Yin-Chia Yehe52b8fa2020-07-28 00:17:58 -07001943 if (signalPipelineDrain) {
1944 mRequestThread->resetPipelineDrain();
1945 }
1946
Ruben Brunk183f0562015-08-12 12:55:02 -07001947 mStatusWaiters--;
1948
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001949 return res;
1950}
1951
1952
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001953status_t Camera3Device::setNotifyCallback(wp<NotificationListener> listener) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001954 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001955 std::lock_guard<std::mutex> l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001956
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001957 if (listener != NULL && mListener != NULL) {
1958 ALOGW("%s: Replacing old callback listener", __FUNCTION__);
1959 }
1960 mListener = listener;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001961 mRequestThread->setNotificationListener(listener);
1962 mPreparerThread->setNotificationListener(listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001963
1964 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001965}
1966
Eino-Ville Talvala46910bd2013-07-18 19:15:17 -07001967bool Camera3Device::willNotify3A() {
1968 return false;
1969}
1970
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001971status_t Camera3Device::waitForNextFrame(nsecs_t timeout) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07001972 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001973 std::unique_lock<std::mutex> l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001974
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001975 while (mResultQueue.empty()) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001976 auto st = mResultSignal.wait_for(l, std::chrono::nanoseconds(timeout));
1977 if (st == std::cv_status::timeout) {
1978 return TIMED_OUT;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001979 }
1980 }
1981 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001982}
1983
Jianing Weicb0652e2014-03-12 18:29:36 -07001984status_t Camera3Device::getNextResult(CaptureResult *frame) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001985 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001986 std::lock_guard<std::mutex> l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001987
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001988 if (mResultQueue.empty()) {
1989 return NOT_ENOUGH_DATA;
1990 }
1991
Jianing Weicb0652e2014-03-12 18:29:36 -07001992 if (frame == NULL) {
1993 ALOGE("%s: argument cannot be NULL", __FUNCTION__);
1994 return BAD_VALUE;
1995 }
1996
1997 CaptureResult &result = *(mResultQueue.begin());
1998 frame->mResultExtras = result.mResultExtras;
1999 frame->mMetadata.acquire(result.mMetadata);
Shuzhen Wang5c22c152017-12-31 17:12:25 -08002000 frame->mPhysicalMetadatas = std::move(result.mPhysicalMetadatas);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002001 mResultQueue.erase(mResultQueue.begin());
2002
2003 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002004}
2005
2006status_t Camera3Device::triggerAutofocus(uint32_t id) {
2007 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002008 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002009
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002010 ALOGV("%s: Triggering autofocus, id %d", __FUNCTION__, id);
2011 // Mix-in this trigger into the next request and only the next request.
2012 RequestTrigger trigger[] = {
2013 {
2014 ANDROID_CONTROL_AF_TRIGGER,
2015 ANDROID_CONTROL_AF_TRIGGER_START
2016 },
2017 {
2018 ANDROID_CONTROL_AF_TRIGGER_ID,
2019 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07002020 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002021 };
2022
2023 return mRequestThread->queueTrigger(trigger,
2024 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002025}
2026
2027status_t Camera3Device::triggerCancelAutofocus(uint32_t id) {
2028 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002029 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002030
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002031 ALOGV("%s: Triggering cancel autofocus, id %d", __FUNCTION__, id);
2032 // Mix-in this trigger into the next request and only the next request.
2033 RequestTrigger trigger[] = {
2034 {
2035 ANDROID_CONTROL_AF_TRIGGER,
2036 ANDROID_CONTROL_AF_TRIGGER_CANCEL
2037 },
2038 {
2039 ANDROID_CONTROL_AF_TRIGGER_ID,
2040 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07002041 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002042 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002043
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002044 return mRequestThread->queueTrigger(trigger,
2045 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002046}
2047
2048status_t Camera3Device::triggerPrecaptureMetering(uint32_t id) {
2049 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002050 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002051
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002052 ALOGV("%s: Triggering precapture metering, id %d", __FUNCTION__, id);
2053 // Mix-in this trigger into the next request and only the next request.
2054 RequestTrigger trigger[] = {
2055 {
2056 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER,
2057 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_START
2058 },
2059 {
2060 ANDROID_CONTROL_AE_PRECAPTURE_ID,
2061 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07002062 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002063 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002064
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002065 return mRequestThread->queueTrigger(trigger,
2066 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002067}
2068
Jianing Weicb0652e2014-03-12 18:29:36 -07002069status_t Camera3Device::flush(int64_t *frameNumber) {
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07002070 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002071 ALOGV("%s: Camera %s: Flushing all requests", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002072 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07002073
Zhijun He7ef20392014-04-21 16:04:17 -07002074 {
2075 Mutex::Autolock l(mLock);
Emilian Peeved2ebe42018-09-25 16:59:09 +01002076
2077 // b/116514106 "disconnect()" can get called twice for the same device. The
2078 // camera device will not be initialized during the second run.
2079 if (mStatus == STATUS_UNINITIALIZED) {
2080 return OK;
2081 }
2082
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002083 mRequestThread->clear(/*out*/frameNumber);
Shuzhen Wang316781a2020-08-18 18:11:01 -07002084
2085 // Stop session and stream counter
2086 mSessionStatsBuilder.stopCounter();
Zhijun He7ef20392014-04-21 16:04:17 -07002087 }
2088
Emilian Peev08dd2452017-04-06 16:55:14 +01002089 return mRequestThread->flush();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07002090}
2091
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002092status_t Camera3Device::prepare(int streamId) {
Ruben Brunkc78ac262015-08-13 17:58:46 -07002093 return prepare(camera3::Camera3StreamInterface::ALLOCATE_PIPELINE_MAX, streamId);
2094}
2095
2096status_t Camera3Device::prepare(int maxCount, int streamId) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002097 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002098 ALOGV("%s: Camera %s: Preparing stream %d", __FUNCTION__, mId.string(), streamId);
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07002099 Mutex::Autolock il(mInterfaceLock);
2100 Mutex::Autolock l(mLock);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002101
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002102 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
2103 if (stream == nullptr) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002104 CLOGE("Stream %d does not exist", streamId);
2105 return BAD_VALUE;
2106 }
2107
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002108 if (stream->isUnpreparable() || stream->hasOutstandingBuffers() ) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07002109 CLOGE("Stream %d has already been a request target", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002110 return BAD_VALUE;
2111 }
2112
2113 if (mRequestThread->isStreamPending(stream)) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07002114 CLOGE("Stream %d is already a target in a pending request", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002115 return BAD_VALUE;
2116 }
2117
Ruben Brunkc78ac262015-08-13 17:58:46 -07002118 return mPreparerThread->prepare(maxCount, stream);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002119}
2120
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002121status_t Camera3Device::tearDown(int streamId) {
2122 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002123 ALOGV("%s: Camera %s: Tearing down stream %d", __FUNCTION__, mId.string(), streamId);
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002124 Mutex::Autolock il(mInterfaceLock);
2125 Mutex::Autolock l(mLock);
2126
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002127 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
2128 if (stream == nullptr) {
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002129 CLOGE("Stream %d does not exist", streamId);
2130 return BAD_VALUE;
2131 }
2132
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002133 if (stream->hasOutstandingBuffers() || mRequestThread->isStreamPending(stream)) {
2134 CLOGE("Stream %d is a target of a in-progress request", streamId);
2135 return BAD_VALUE;
2136 }
2137
2138 return stream->tearDown();
2139}
2140
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002141status_t Camera3Device::addBufferListenerForStream(int streamId,
2142 wp<Camera3StreamBufferListener> listener) {
2143 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002144 ALOGV("%s: Camera %s: Adding buffer listener for stream %d", __FUNCTION__, mId.string(), streamId);
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002145 Mutex::Autolock il(mInterfaceLock);
2146 Mutex::Autolock l(mLock);
2147
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002148 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
2149 if (stream == nullptr) {
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002150 CLOGE("Stream %d does not exist", streamId);
2151 return BAD_VALUE;
2152 }
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002153 stream->addBufferListener(listener);
2154
2155 return OK;
2156}
2157
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002158/**
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002159 * Methods called by subclasses
2160 */
2161
2162void Camera3Device::notifyStatus(bool idle) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002163 ATRACE_CALL();
Shuzhen Wang316781a2020-08-18 18:11:01 -07002164 std::vector<int> streamIds;
2165 std::vector<hardware::CameraStreamStats> streamStats;
2166
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002167 {
2168 // Need mLock to safely update state and synchronize to current
2169 // state of methods in flight.
2170 Mutex::Autolock l(mLock);
2171 // We can get various system-idle notices from the status tracker
2172 // while starting up. Only care about them if we've actually sent
2173 // in some requests recently.
2174 if (mStatus != STATUS_ACTIVE && mStatus != STATUS_CONFIGURED) {
2175 return;
2176 }
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08002177 ALOGV("%s: Camera %s: Now %s, pauseState: %s", __FUNCTION__, mId.string(),
2178 idle ? "idle" : "active", mPauseStateNotify ? "true" : "false");
Ruben Brunk183f0562015-08-12 12:55:02 -07002179 internalUpdateStatusLocked(idle ? STATUS_CONFIGURED : STATUS_ACTIVE);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002180
2181 // Skip notifying listener if we're doing some user-transparent
2182 // state changes
2183 if (mPauseStateNotify) return;
Shuzhen Wang316781a2020-08-18 18:11:01 -07002184
2185 // Populate stream statistics in case of Idle
2186 if (idle) {
2187 for (size_t i = 0; i < mOutputStreams.size(); i++) {
2188 auto stream = mOutputStreams[i];
2189 if (stream.get() == nullptr) continue;
2190 streamIds.push_back(stream->getId());
2191 Camera3Stream* camera3Stream = Camera3Stream::cast(stream->asHalStream());
2192 int64_t usage = 0LL;
2193 if (camera3Stream != nullptr) {
2194 usage = camera3Stream->getUsage();
2195 }
2196 streamStats.emplace_back(stream->getWidth(), stream->getHeight(),
2197 stream->getFormat(), stream->getDataSpace(), usage,
2198 stream->getMaxHalBuffers(),
2199 stream->getMaxTotalBuffers() - stream->getMaxHalBuffers());
2200 }
2201 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002202 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002203
2204 sp<NotificationListener> listener;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002205 {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002206 std::lock_guard<std::mutex> l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002207 listener = mListener.promote();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002208 }
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07002209 status_t res = OK;
2210 if (listener != nullptr) {
2211 if (idle) {
2212 // Get session stats from the builder, and notify the listener.
2213 int64_t requestCount, resultErrorCount;
2214 bool deviceError;
2215 std::map<int, StreamStats> streamStatsMap;
2216 mSessionStatsBuilder.buildAndReset(&requestCount, &resultErrorCount,
2217 &deviceError, &streamStatsMap);
2218 for (size_t i = 0; i < streamIds.size(); i++) {
2219 int streamId = streamIds[i];
2220 auto stats = streamStatsMap.find(streamId);
2221 if (stats != streamStatsMap.end()) {
2222 streamStats[i].mRequestCount = stats->second.mRequestedFrameCount;
2223 streamStats[i].mErrorCount = stats->second.mDroppedFrameCount;
2224 streamStats[i].mStartLatencyMs = stats->second.mStartLatencyMs;
2225 streamStats[i].mHistogramType =
2226 hardware::CameraStreamStats::HISTOGRAM_TYPE_CAPTURE_LATENCY;
2227 streamStats[i].mHistogramBins.assign(
2228 stats->second.mCaptureLatencyBins.begin(),
2229 stats->second.mCaptureLatencyBins.end());
2230 streamStats[i].mHistogramCounts.assign(
2231 stats->second.mCaptureLatencyHistogram.begin(),
2232 stats->second.mCaptureLatencyHistogram.end());
2233 }
Shuzhen Wang316781a2020-08-18 18:11:01 -07002234 }
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07002235 listener->notifyIdle(requestCount, resultErrorCount, deviceError, streamStats);
2236 } else {
2237 res = listener->notifyActive();
Shuzhen Wang316781a2020-08-18 18:11:01 -07002238 }
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07002239 }
2240 if (res != OK) {
2241 SET_ERR("Camera access permission lost mid-operation: %s (%d)",
2242 strerror(-res), res);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002243 }
2244}
2245
Shuzhen Wang758c2152017-01-10 18:26:18 -08002246status_t Camera3Device::setConsumerSurfaces(int streamId,
Emilian Peev40ead602017-09-26 15:46:36 +01002247 const std::vector<sp<Surface>>& consumers, std::vector<int> *surfaceIds) {
Zhijun He5d677d12016-05-29 16:52:39 -07002248 ATRACE_CALL();
Shuzhen Wang758c2152017-01-10 18:26:18 -08002249 ALOGV("%s: Camera %s: set consumer surface for stream %d",
2250 __FUNCTION__, mId.string(), streamId);
Emilian Peev40ead602017-09-26 15:46:36 +01002251
2252 if (surfaceIds == nullptr) {
2253 return BAD_VALUE;
2254 }
2255
Zhijun He5d677d12016-05-29 16:52:39 -07002256 Mutex::Autolock il(mInterfaceLock);
2257 Mutex::Autolock l(mLock);
2258
Shuzhen Wang758c2152017-01-10 18:26:18 -08002259 if (consumers.size() == 0) {
2260 CLOGE("No consumer is passed!");
Zhijun He5d677d12016-05-29 16:52:39 -07002261 return BAD_VALUE;
2262 }
2263
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002264 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
2265 if (stream == nullptr) {
Zhijun He5d677d12016-05-29 16:52:39 -07002266 CLOGE("Stream %d is unknown", streamId);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002267 return BAD_VALUE;
Zhijun He5d677d12016-05-29 16:52:39 -07002268 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002269
2270 // isConsumerConfigurationDeferred will be off after setConsumers
2271 bool isDeferred = stream->isConsumerConfigurationDeferred();
Shuzhen Wang758c2152017-01-10 18:26:18 -08002272 status_t res = stream->setConsumers(consumers);
Zhijun He5d677d12016-05-29 16:52:39 -07002273 if (res != OK) {
2274 CLOGE("Stream %d set consumer failed (error %d %s) ", streamId, res, strerror(-res));
2275 return res;
2276 }
2277
Emilian Peev40ead602017-09-26 15:46:36 +01002278 for (auto &consumer : consumers) {
2279 int id = stream->getSurfaceId(consumer);
2280 if (id < 0) {
2281 CLOGE("Invalid surface id!");
2282 return BAD_VALUE;
2283 }
2284 surfaceIds->push_back(id);
2285 }
2286
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002287 if (isDeferred) {
Shuzhen Wang0129d522016-10-30 22:43:41 -07002288 if (!stream->isConfiguring()) {
2289 CLOGE("Stream %d was already fully configured.", streamId);
2290 return INVALID_OPERATION;
2291 }
Zhijun He5d677d12016-05-29 16:52:39 -07002292
Shuzhen Wang0129d522016-10-30 22:43:41 -07002293 res = stream->finishConfiguration();
2294 if (res != OK) {
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002295 // If finishConfiguration fails due to abandoned surface, do not set
2296 // device to error state.
2297 bool isSurfaceAbandoned =
2298 (res == NO_INIT || res == DEAD_OBJECT) && stream->isAbandoned();
2299 if (!isSurfaceAbandoned) {
2300 SET_ERR_L("Can't finish configuring output stream %d: %s (%d)",
2301 stream->getId(), strerror(-res), res);
2302 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07002303 return res;
2304 }
Zhijun He5d677d12016-05-29 16:52:39 -07002305 }
2306
2307 return OK;
2308}
2309
Emilian Peev40ead602017-09-26 15:46:36 +01002310status_t Camera3Device::updateStream(int streamId, const std::vector<sp<Surface>> &newSurfaces,
2311 const std::vector<OutputStreamInfo> &outputInfo,
2312 const std::vector<size_t> &removedSurfaceIds, KeyedVector<sp<Surface>, size_t> *outputMap) {
2313 Mutex::Autolock il(mInterfaceLock);
2314 Mutex::Autolock l(mLock);
2315
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002316 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
2317 if (stream == nullptr) {
Emilian Peev40ead602017-09-26 15:46:36 +01002318 CLOGE("Stream %d is unknown", streamId);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002319 return BAD_VALUE;
Emilian Peev40ead602017-09-26 15:46:36 +01002320 }
2321
2322 for (const auto &it : removedSurfaceIds) {
2323 if (mRequestThread->isOutputSurfacePending(streamId, it)) {
2324 CLOGE("Shared surface still part of a pending request!");
2325 return -EBUSY;
2326 }
2327 }
2328
Emilian Peev40ead602017-09-26 15:46:36 +01002329 status_t res = stream->updateStream(newSurfaces, outputInfo, removedSurfaceIds, outputMap);
2330 if (res != OK) {
2331 CLOGE("Stream %d failed to update stream (error %d %s) ",
2332 streamId, res, strerror(-res));
2333 if (res == UNKNOWN_ERROR) {
2334 SET_ERR_L("%s: Stream update failed to revert to previous output configuration!",
2335 __FUNCTION__);
2336 }
2337 return res;
2338 }
2339
2340 return res;
2341}
2342
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002343status_t Camera3Device::dropStreamBuffers(bool dropping, int streamId) {
2344 Mutex::Autolock il(mInterfaceLock);
2345 Mutex::Autolock l(mLock);
2346
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002347 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
2348 if (stream == nullptr) {
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002349 ALOGE("%s: Stream %d is not found.", __FUNCTION__, streamId);
2350 return BAD_VALUE;
2351 }
Shuzhen Wang316781a2020-08-18 18:11:01 -07002352
2353 if (dropping) {
2354 mSessionStatsBuilder.stopCounter(streamId);
2355 } else {
2356 mSessionStatsBuilder.startCounter(streamId);
2357 }
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002358 return stream->dropBuffers(dropping);
2359}
2360
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002361/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002362 * Camera3Device private methods
2363 */
2364
2365sp<Camera3Device::CaptureRequest> Camera3Device::createCaptureRequest(
Emilian Peevaebbe412018-01-15 13:53:24 +00002366 const PhysicalCameraSettingsList &request, const SurfaceMap &surfaceMap) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002367 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002368
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08002369 sp<CaptureRequest> newRequest = new CaptureRequest();
Emilian Peevaebbe412018-01-15 13:53:24 +00002370 newRequest->mSettingsList = request;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002371
2372 camera_metadata_entry_t inputStreams =
Emilian Peevaebbe412018-01-15 13:53:24 +00002373 newRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_INPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002374 if (inputStreams.count > 0) {
2375 if (mInputStream == NULL ||
Zhijun Hed1d64672013-09-06 15:00:01 -07002376 mInputStream->getId() != inputStreams.data.i32[0]) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002377 CLOGE("Request references unknown input stream %d",
2378 inputStreams.data.u8[0]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002379 return NULL;
2380 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002381
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002382 if (mInputStream->isConfiguring()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002383 SET_ERR_L("%s: input stream %d is not configured!",
2384 __FUNCTION__, mInputStream->getId());
2385 return NULL;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002386 }
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07002387 // Check if stream prepare is blocking requests.
2388 if (mInputStream->isBlockedByPrepare()) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002389 CLOGE("Request references an input stream that's being prepared!");
2390 return NULL;
2391 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002392
2393 newRequest->mInputStream = mInputStream;
Emilian Peevaebbe412018-01-15 13:53:24 +00002394 newRequest->mSettingsList.begin()->metadata.erase(ANDROID_REQUEST_INPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002395 }
2396
2397 camera_metadata_entry_t streams =
Emilian Peevaebbe412018-01-15 13:53:24 +00002398 newRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_OUTPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002399 if (streams.count == 0) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002400 CLOGE("Zero output streams specified!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002401 return NULL;
2402 }
2403
2404 for (size_t i = 0; i < streams.count; i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002405 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streams.data.i32[i]);
2406 if (stream == nullptr) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002407 CLOGE("Request references unknown stream %d",
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002408 streams.data.i32[i]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002409 return NULL;
2410 }
Zhijun He5d677d12016-05-29 16:52:39 -07002411 // It is illegal to include a deferred consumer output stream into a request
Shuzhen Wang0129d522016-10-30 22:43:41 -07002412 auto iter = surfaceMap.find(streams.data.i32[i]);
2413 if (iter != surfaceMap.end()) {
2414 const std::vector<size_t>& surfaces = iter->second;
2415 for (const auto& surface : surfaces) {
2416 if (stream->isConsumerConfigurationDeferred(surface)) {
2417 CLOGE("Stream %d surface %zu hasn't finished configuration yet "
2418 "due to deferred consumer", stream->getId(), surface);
2419 return NULL;
2420 }
2421 }
Yin-Chia Yeh0b287572018-10-15 12:38:13 -07002422 newRequest->mOutputSurfaces[streams.data.i32[i]] = surfaces;
Zhijun He5d677d12016-05-29 16:52:39 -07002423 }
2424
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002425 if (stream->isConfiguring()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002426 SET_ERR_L("%s: stream %d is not configured!", __FUNCTION__, stream->getId());
2427 return NULL;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002428 }
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07002429 // Check if stream prepare is blocking requests.
2430 if (stream->isBlockedByPrepare()) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002431 CLOGE("Request references an output stream that's being prepared!");
2432 return NULL;
2433 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002434
2435 newRequest->mOutputStreams.push(stream);
2436 }
Emilian Peevaebbe412018-01-15 13:53:24 +00002437 newRequest->mSettingsList.begin()->metadata.erase(ANDROID_REQUEST_OUTPUT_STREAMS);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07002438 newRequest->mBatchSize = 1;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002439
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08002440 auto rotateAndCropEntry =
2441 newRequest->mSettingsList.begin()->metadata.find(ANDROID_SCALER_ROTATE_AND_CROP);
2442 if (rotateAndCropEntry.count > 0 &&
2443 rotateAndCropEntry.data.u8[0] == ANDROID_SCALER_ROTATE_AND_CROP_AUTO) {
2444 newRequest->mRotateAndCropAuto = true;
2445 } else {
2446 newRequest->mRotateAndCropAuto = false;
2447 }
2448
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07002449 auto zoomRatioEntry =
2450 newRequest->mSettingsList.begin()->metadata.find(ANDROID_CONTROL_ZOOM_RATIO);
2451 if (zoomRatioEntry.count > 0 &&
2452 zoomRatioEntry.data.f[0] == 1.0f) {
2453 newRequest->mZoomRatioIs1x = true;
2454 } else {
2455 newRequest->mZoomRatioIs1x = false;
2456 }
2457
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08002458 if (mSupportCameraMute) {
2459 auto testPatternModeEntry =
2460 newRequest->mSettingsList.begin()->metadata.find(ANDROID_SENSOR_TEST_PATTERN_MODE);
2461 newRequest->mOriginalTestPatternMode = testPatternModeEntry.count > 0 ?
2462 testPatternModeEntry.data.i32[0] :
2463 ANDROID_SENSOR_TEST_PATTERN_MODE_OFF;
2464
2465 auto testPatternDataEntry =
2466 newRequest->mSettingsList.begin()->metadata.find(ANDROID_SENSOR_TEST_PATTERN_DATA);
Eino-Ville Talvalac2459842021-07-22 16:36:36 -07002467 if (testPatternDataEntry.count >= 4) {
2468 memcpy(newRequest->mOriginalTestPatternData, testPatternDataEntry.data.i32,
2469 sizeof(CaptureRequest::mOriginalTestPatternData));
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08002470 } else {
2471 newRequest->mOriginalTestPatternData[0] = 0;
2472 newRequest->mOriginalTestPatternData[1] = 0;
2473 newRequest->mOriginalTestPatternData[2] = 0;
2474 newRequest->mOriginalTestPatternData[3] = 0;
2475 }
2476 }
2477
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002478 return newRequest;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002479}
2480
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002481void Camera3Device::cancelStreamsConfigurationLocked() {
2482 int res = OK;
2483 if (mInputStream != NULL && mInputStream->isConfiguring()) {
2484 res = mInputStream->cancelConfiguration();
2485 if (res != OK) {
2486 CLOGE("Can't cancel configuring input stream %d: %s (%d)",
2487 mInputStream->getId(), strerror(-res), res);
2488 }
2489 }
2490
2491 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002492 sp<Camera3OutputStreamInterface> outputStream = mOutputStreams[i];
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002493 if (outputStream->isConfiguring()) {
2494 res = outputStream->cancelConfiguration();
2495 if (res != OK) {
2496 CLOGE("Can't cancel configuring output stream %d: %s (%d)",
2497 outputStream->getId(), strerror(-res), res);
2498 }
2499 }
2500 }
2501
2502 // Return state to that at start of call, so that future configures
2503 // properly clean things up
2504 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
2505 mNeedConfig = true;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002506
2507 res = mPreparerThread->resume();
2508 if (res != OK) {
2509 ALOGE("%s: Camera %s: Preparer thread failed to resume!", __FUNCTION__, mId.string());
2510 }
2511}
2512
Emilian Peev0d0191e2020-04-21 17:01:18 -07002513bool Camera3Device::checkAbandonedStreamsLocked() {
2514 if ((mInputStream.get() != nullptr) && (mInputStream->isAbandoned())) {
2515 return true;
2516 }
2517
2518 for (size_t i = 0; i < mOutputStreams.size(); i++) {
2519 auto stream = mOutputStreams[i];
2520 if ((stream.get() != nullptr) && (stream->isAbandoned())) {
2521 return true;
2522 }
2523 }
2524
2525 return false;
2526}
2527
Emilian Peev3bead5f2020-05-28 17:29:08 -07002528bool Camera3Device::reconfigureCamera(const CameraMetadata& sessionParams, int clientStatusId) {
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002529 ATRACE_CALL();
2530 bool ret = false;
2531
Shuzhen Wang316781a2020-08-18 18:11:01 -07002532 nsecs_t startTime = systemTime();
2533
Jayant Chowdhary646c31b2020-01-30 13:09:59 -08002534 Mutex::Autolock il(mInterfaceLock);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002535 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
2536
2537 Mutex::Autolock l(mLock);
Emilian Peev0d0191e2020-04-21 17:01:18 -07002538 if (checkAbandonedStreamsLocked()) {
2539 ALOGW("%s: Abandoned stream detected, session parameters can't be applied correctly!",
2540 __FUNCTION__);
2541 return true;
2542 }
2543
Emilian Peev3bead5f2020-05-28 17:29:08 -07002544 status_t rc = NO_ERROR;
2545 bool markClientActive = false;
2546 if (mStatus == STATUS_ACTIVE) {
2547 markClientActive = true;
2548 mPauseStateNotify = true;
2549 mStatusTracker->markComponentIdle(clientStatusId, Fence::NO_FENCE);
2550
2551 rc = internalPauseAndWaitLocked(maxExpectedDuration);
2552 }
2553
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002554 if (rc == NO_ERROR) {
2555 mNeedConfig = true;
2556 rc = configureStreamsLocked(mOperatingMode, sessionParams, /*notifyRequestThread*/ false);
2557 if (rc == NO_ERROR) {
2558 ret = true;
2559 mPauseStateNotify = false;
2560 //Moving to active state while holding 'mLock' is important.
2561 //There could be pending calls to 'create-/deleteStream' which
2562 //will trigger another stream configuration while the already
2563 //present streams end up with outstanding buffers that will
2564 //not get drained.
2565 internalUpdateStatusLocked(STATUS_ACTIVE);
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002566 } else if (rc == DEAD_OBJECT) {
2567 // DEAD_OBJECT can be returned if either the consumer surface is
2568 // abandoned, or the HAL has died.
2569 // - If the HAL has died, configureStreamsLocked call will set
2570 // device to error state,
2571 // - If surface is abandoned, we should not set device to error
2572 // state.
2573 ALOGE("Failed to re-configure camera due to abandoned surface");
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002574 } else {
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002575 SET_ERR_L("Failed to re-configure camera: %d", rc);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002576 }
2577 } else {
2578 ALOGE("%s: Failed to pause streaming: %d", __FUNCTION__, rc);
2579 }
2580
Shuzhen Wang316781a2020-08-18 18:11:01 -07002581 CameraServiceProxyWrapper::logStreamConfigured(mId, mOperatingMode, true /*internalReconfig*/,
2582 ns2ms(systemTime() - startTime));
2583
Emilian Peev3bead5f2020-05-28 17:29:08 -07002584 if (markClientActive) {
2585 mStatusTracker->markComponentActive(clientStatusId);
2586 }
2587
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002588 return ret;
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002589}
2590
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002591status_t Camera3Device::configureStreamsLocked(int operatingMode,
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002592 const CameraMetadata& sessionParams, bool notifyRequestThread) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002593 ATRACE_CALL();
2594 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002595
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002596 if (mStatus != STATUS_UNCONFIGURED && mStatus != STATUS_CONFIGURED) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002597 CLOGE("Not idle");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002598 return INVALID_OPERATION;
2599 }
2600
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08002601 if (operatingMode < 0) {
2602 CLOGE("Invalid operating mode: %d", operatingMode);
2603 return BAD_VALUE;
2604 }
2605
2606 bool isConstrainedHighSpeed =
2607 static_cast<int>(StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE) ==
2608 operatingMode;
2609
2610 if (mOperatingMode != operatingMode) {
2611 mNeedConfig = true;
2612 mIsConstrainedHighSpeedConfiguration = isConstrainedHighSpeed;
2613 mOperatingMode = operatingMode;
2614 }
2615
Shuzhen Wang0cf01cb2019-09-05 13:33:06 -07002616 // In case called from configureStreams, abort queued input buffers not belonging to
2617 // any pending requests.
2618 if (mInputStream != NULL && notifyRequestThread) {
2619 while (true) {
Emilian Peevf4816702020-04-03 15:44:51 -07002620 camera_stream_buffer_t inputBuffer;
Shuzhen Wang83bff122020-11-20 15:51:39 -08002621 camera3::Size inputBufferSize;
Shuzhen Wang0cf01cb2019-09-05 13:33:06 -07002622 status_t res = mInputStream->getInputBuffer(&inputBuffer,
Shuzhen Wang83bff122020-11-20 15:51:39 -08002623 &inputBufferSize, /*respectHalLimit*/ false);
Shuzhen Wang0cf01cb2019-09-05 13:33:06 -07002624 if (res != OK) {
2625 // Exhausted acquiring all input buffers.
2626 break;
2627 }
2628
Emilian Peevf4816702020-04-03 15:44:51 -07002629 inputBuffer.status = CAMERA_BUFFER_STATUS_ERROR;
Shuzhen Wang0cf01cb2019-09-05 13:33:06 -07002630 res = mInputStream->returnInputBuffer(inputBuffer);
2631 if (res != OK) {
2632 ALOGE("%s: %d: couldn't return input buffer while clearing input queue: "
2633 "%s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
2634 }
2635 }
2636 }
2637
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002638 if (!mNeedConfig) {
2639 ALOGV("%s: Skipping config, no stream changes", __FUNCTION__);
2640 return OK;
2641 }
2642
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002643 // Workaround for device HALv3.2 or older spec bug - zero streams requires
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002644 // adding a fake stream instead.
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002645 // TODO: Bug: 17321404 for fixing the HAL spec and removing this workaround.
2646 if (mOutputStreams.size() == 0) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002647 addFakeStreamLocked();
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002648 } else {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002649 tryRemoveFakeStreamLocked();
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002650 }
2651
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002652 // Start configuring the streams
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002653 ALOGV("%s: Camera %s: Starting stream configuration", __FUNCTION__, mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002654
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002655 mPreparerThread->pause();
2656
Emilian Peevf4816702020-04-03 15:44:51 -07002657 camera_stream_configuration config;
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -08002658 config.operation_mode = mOperatingMode;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002659 config.num_streams = (mInputStream != NULL) + mOutputStreams.size();
Shuzhen Wang83bff122020-11-20 15:51:39 -08002660 config.input_is_multi_resolution = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002661
Emilian Peevf4816702020-04-03 15:44:51 -07002662 Vector<camera3::camera_stream_t*> streams;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002663 streams.setCapacity(config.num_streams);
Emilian Peev192ee832018-01-31 14:46:47 +00002664 std::vector<uint32_t> bufferSizes(config.num_streams, 0);
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002665
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002666
2667 if (mInputStream != NULL) {
Emilian Peevf4816702020-04-03 15:44:51 -07002668 camera3::camera_stream_t *inputStream;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002669 inputStream = mInputStream->startConfiguration();
2670 if (inputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002671 CLOGE("Can't start input stream configuration");
2672 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002673 return INVALID_OPERATION;
2674 }
2675 streams.add(inputStream);
Shuzhen Wang83bff122020-11-20 15:51:39 -08002676
2677 config.input_is_multi_resolution = mIsInputStreamMultiResolution;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002678 }
2679
Shuzhen Wang99080502021-03-07 21:08:20 -08002680 mGroupIdPhysicalCameraMap.clear();
Emilian Peeve23f1d92021-09-20 14:56:01 -07002681 bool composerSurfacePresent = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002682 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Igor Murashkin2fba5842013-04-22 14:03:54 -07002683
2684 // Don't configure bidi streams twice, nor add them twice to the list
2685 if (mOutputStreams[i].get() ==
2686 static_cast<Camera3StreamInterface*>(mInputStream.get())) {
2687
2688 config.num_streams--;
2689 continue;
2690 }
2691
Emilian Peevf4816702020-04-03 15:44:51 -07002692 camera3::camera_stream_t *outputStream;
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002693 outputStream = mOutputStreams[i]->startConfiguration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002694 if (outputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002695 CLOGE("Can't start output stream configuration");
2696 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002697 return INVALID_OPERATION;
2698 }
2699 streams.add(outputStream);
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002700
Shuzhen Wangb7ab1e42019-02-20 15:42:23 -08002701 if (outputStream->format == HAL_PIXEL_FORMAT_BLOB) {
Emilian Peev192ee832018-01-31 14:46:47 +00002702 size_t k = i + ((mInputStream != nullptr) ? 1 : 0); // Input stream if present should
2703 // always occupy the initial entry.
Shuzhen Wangb7ab1e42019-02-20 15:42:23 -08002704 if (outputStream->data_space == HAL_DATASPACE_V0_JFIF) {
2705 bufferSizes[k] = static_cast<uint32_t>(
2706 getJpegBufferSize(outputStream->width, outputStream->height));
2707 } else if (outputStream->data_space ==
2708 static_cast<android_dataspace>(HAL_DATASPACE_JPEG_APP_SEGMENTS)) {
2709 bufferSizes[k] = outputStream->width * outputStream->height;
2710 } else {
2711 ALOGW("%s: Blob dataSpace %d not supported",
2712 __FUNCTION__, outputStream->data_space);
2713 }
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002714 }
Shuzhen Wang99080502021-03-07 21:08:20 -08002715
2716 if (mOutputStreams[i]->isMultiResolution()) {
2717 int32_t streamGroupId = mOutputStreams[i]->getHalStreamGroupId();
2718 const String8& physicalCameraId = mOutputStreams[i]->getPhysicalCameraId();
2719 mGroupIdPhysicalCameraMap[streamGroupId].insert(physicalCameraId);
2720 }
Emilian Peeve23f1d92021-09-20 14:56:01 -07002721
2722 if (outputStream->usage & GraphicBuffer::USAGE_HW_COMPOSER) {
2723 composerSurfacePresent = true;
2724 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002725 }
2726
2727 config.streams = streams.editArray();
2728
2729 // Do the HAL configuration; will potentially touch stream
Shuzhen Wang92653952019-05-07 15:11:43 -07002730 // max_buffers, usage, and priv fields, as well as data_space and format
2731 // fields for IMPLEMENTATION_DEFINED formats.
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002732
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002733 const camera_metadata_t *sessionBuffer = sessionParams.getAndLock();
Emilian Peev192ee832018-01-31 14:46:47 +00002734 res = mInterface->configureStreams(sessionBuffer, &config, bufferSizes);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002735 sessionParams.unlock(sessionBuffer);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002736
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002737 if (res == BAD_VALUE) {
2738 // HAL rejected this set of streams as unsupported, clean up config
2739 // attempt and return to unconfigured state
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002740 CLOGE("Set of requested inputs/outputs not supported by HAL");
2741 cancelStreamsConfigurationLocked();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002742 return BAD_VALUE;
2743 } else if (res != OK) {
2744 // Some other kind of error from configure_streams - this is not
2745 // expected
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002746 SET_ERR_L("Unable to configure streams with HAL: %s (%d)",
2747 strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002748 return res;
2749 }
2750
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002751 // Finish all stream configuration immediately.
2752 // TODO: Try to relax this later back to lazy completion, which should be
2753 // faster
2754
Igor Murashkin073f8572013-05-02 14:59:28 -07002755 if (mInputStream != NULL && mInputStream->isConfiguring()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002756 bool streamReConfigured = false;
2757 res = mInputStream->finishConfiguration(&streamReConfigured);
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002758 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002759 CLOGE("Can't finish configuring input stream %d: %s (%d)",
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002760 mInputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002761 cancelStreamsConfigurationLocked();
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002762 if ((res == NO_INIT || res == DEAD_OBJECT) && mInputStream->isAbandoned()) {
2763 return DEAD_OBJECT;
2764 }
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002765 return BAD_VALUE;
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002766 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002767 if (streamReConfigured) {
2768 mInterface->onStreamReConfigured(mInputStream->getId());
2769 }
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002770 }
2771
2772 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002773 sp<Camera3OutputStreamInterface> outputStream = mOutputStreams[i];
Zhijun He5d677d12016-05-29 16:52:39 -07002774 if (outputStream->isConfiguring() && !outputStream->isConsumerConfigurationDeferred()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002775 bool streamReConfigured = false;
2776 res = outputStream->finishConfiguration(&streamReConfigured);
Igor Murashkin073f8572013-05-02 14:59:28 -07002777 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002778 CLOGE("Can't finish configuring output stream %d: %s (%d)",
Igor Murashkin073f8572013-05-02 14:59:28 -07002779 outputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002780 cancelStreamsConfigurationLocked();
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002781 if ((res == NO_INIT || res == DEAD_OBJECT) && outputStream->isAbandoned()) {
2782 return DEAD_OBJECT;
2783 }
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002784 return BAD_VALUE;
Igor Murashkin073f8572013-05-02 14:59:28 -07002785 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002786 if (streamReConfigured) {
2787 mInterface->onStreamReConfigured(outputStream->getId());
2788 }
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002789 }
2790 }
2791
Emilian Peeve23f1d92021-09-20 14:56:01 -07002792 mRequestThread->setComposerSurface(composerSurfacePresent);
2793
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002794 // Request thread needs to know to avoid using repeat-last-settings protocol
2795 // across configure_streams() calls
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002796 if (notifyRequestThread) {
Shuzhen Wang99080502021-03-07 21:08:20 -08002797 mRequestThread->configurationComplete(mIsConstrainedHighSpeedConfiguration,
2798 sessionParams, mGroupIdPhysicalCameraMap);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002799 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002800
Zhijun He90f7c372016-08-16 16:19:43 -07002801 char value[PROPERTY_VALUE_MAX];
2802 property_get("camera.fifo.disable", value, "0");
2803 int32_t disableFifo = atoi(value);
2804 if (disableFifo != 1) {
2805 // Boost priority of request thread to SCHED_FIFO.
2806 pid_t requestThreadTid = mRequestThread->getTid();
2807 res = requestPriority(getpid(), requestThreadTid,
Mikhail Naganov83f04272017-02-07 10:45:09 -08002808 kRequestThreadPriority, /*isForApp*/ false, /*asynchronous*/ false);
Zhijun He90f7c372016-08-16 16:19:43 -07002809 if (res != OK) {
2810 ALOGW("Can't set realtime priority for request processing thread: %s (%d)",
2811 strerror(-res), res);
2812 } else {
2813 ALOGD("Set real time priority for request queue thread (tid %d)", requestThreadTid);
2814 }
Eino-Ville Talvalaf99498e2015-09-25 16:52:55 -07002815 }
2816
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002817 // Update device state
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002818 const camera_metadata_t *newSessionParams = sessionParams.getAndLock();
2819 const camera_metadata_t *currentSessionParams = mSessionParams.getAndLock();
2820 bool updateSessionParams = (newSessionParams != currentSessionParams) ? true : false;
2821 sessionParams.unlock(newSessionParams);
2822 mSessionParams.unlock(currentSessionParams);
2823 if (updateSessionParams) {
2824 mSessionParams = sessionParams;
2825 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002826
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002827 mNeedConfig = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002828
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002829 internalUpdateStatusLocked((mFakeStreamId == NO_STREAM) ?
Ruben Brunk183f0562015-08-12 12:55:02 -07002830 STATUS_CONFIGURED : STATUS_UNCONFIGURED);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002831
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002832 ALOGV("%s: Camera %s: Stream configuration complete", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002833
Zhijun He0a210512014-07-24 13:45:15 -07002834 // tear down the deleted streams after configure streams.
2835 mDeletedStreams.clear();
2836
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002837 auto rc = mPreparerThread->resume();
2838 if (rc != OK) {
2839 SET_ERR_L("%s: Camera %s: Preparer thread failed to resume!", __FUNCTION__, mId.string());
2840 return rc;
2841 }
2842
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002843 if (mFakeStreamId == NO_STREAM) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07002844 mRequestBufferSM.onStreamsConfigured();
2845 }
2846
Cliff Wuc2ad9c82021-04-21 00:58:58 +08002847 // Since the streams configuration of the injection camera is based on the internal camera, we
2848 // must wait until the internal camera configure streams before calling injectCamera() to
2849 // configure the injection streams.
2850 if (mInjectionMethods->isInjecting()) {
2851 ALOGV("%s: Injection camera %s: Start to configure streams.",
2852 __FUNCTION__, mInjectionMethods->getInjectedCamId().string());
2853 res = mInjectionMethods->injectCamera(config, bufferSizes);
2854 if (res != OK) {
2855 ALOGE("Can't finish inject camera process!");
2856 return res;
2857 }
2858 }
2859
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002860 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002861}
2862
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002863status_t Camera3Device::addFakeStreamLocked() {
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002864 ATRACE_CALL();
2865 status_t res;
2866
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002867 if (mFakeStreamId != NO_STREAM) {
2868 // Should never be adding a second fake stream when one is already
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002869 // active
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002870 SET_ERR_L("%s: Camera %s: A fake stream already exists!",
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002871 __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002872 return INVALID_OPERATION;
2873 }
2874
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002875 ALOGV("%s: Camera %s: Adding a fake stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002876
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002877 sp<Camera3OutputStreamInterface> fakeStream =
2878 new Camera3FakeStream(mNextStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002879
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002880 res = mOutputStreams.add(mNextStreamId, fakeStream);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002881 if (res < 0) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002882 SET_ERR_L("Can't add fake stream to set: %s (%d)", strerror(-res), res);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002883 return res;
2884 }
2885
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002886 mFakeStreamId = mNextStreamId;
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002887 mNextStreamId++;
2888
2889 return OK;
2890}
2891
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002892status_t Camera3Device::tryRemoveFakeStreamLocked() {
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002893 ATRACE_CALL();
2894 status_t res;
2895
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002896 if (mFakeStreamId == NO_STREAM) return OK;
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002897 if (mOutputStreams.size() == 1) return OK;
2898
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002899 ALOGV("%s: Camera %s: Removing the fake stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002900
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002901 // Ok, have a fake stream and there's at least one other output stream,
2902 // so remove the fake
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002903
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002904 sp<Camera3StreamInterface> deletedStream = mOutputStreams.get(mFakeStreamId);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002905 if (deletedStream == nullptr) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002906 SET_ERR_L("Fake stream %d does not appear to exist", mFakeStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002907 return INVALID_OPERATION;
2908 }
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002909 mOutputStreams.remove(mFakeStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002910
2911 // Free up the stream endpoint so that it can be used by some other stream
2912 res = deletedStream->disconnect();
2913 if (res != OK) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002914 SET_ERR_L("Can't disconnect deleted fake stream %d", mFakeStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002915 // fall through since we want to still list the stream as deleted.
2916 }
2917 mDeletedStreams.add(deletedStream);
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002918 mFakeStreamId = NO_STREAM;
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002919
2920 return res;
2921}
2922
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002923void Camera3Device::setErrorState(const char *fmt, ...) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002924 ATRACE_CALL();
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002925 Mutex::Autolock l(mLock);
2926 va_list args;
2927 va_start(args, fmt);
2928
2929 setErrorStateLockedV(fmt, args);
2930
2931 va_end(args);
2932}
2933
2934void Camera3Device::setErrorStateV(const char *fmt, va_list args) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002935 ATRACE_CALL();
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002936 Mutex::Autolock l(mLock);
2937 setErrorStateLockedV(fmt, args);
2938}
2939
2940void Camera3Device::setErrorStateLocked(const char *fmt, ...) {
2941 va_list args;
2942 va_start(args, fmt);
2943
2944 setErrorStateLockedV(fmt, args);
2945
2946 va_end(args);
2947}
2948
2949void Camera3Device::setErrorStateLockedV(const char *fmt, va_list args) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002950 // Print out all error messages to log
2951 String8 errorCause = String8::formatV(fmt, args);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002952 ALOGE("Camera %s: %s", mId.string(), errorCause.string());
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002953
2954 // But only do error state transition steps for the first error
Zhijun Heb05eeae2013-06-06 13:51:22 -07002955 if (mStatus == STATUS_ERROR || mStatus == STATUS_UNINITIALIZED) return;
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002956
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002957 mErrorCause = errorCause;
2958
Yin-Chia Yeh3d145ae2017-07-27 12:47:03 -07002959 if (mRequestThread != nullptr) {
2960 mRequestThread->setPaused(true);
2961 }
Ruben Brunk183f0562015-08-12 12:55:02 -07002962 internalUpdateStatusLocked(STATUS_ERROR);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002963
2964 // Notify upstream about a device error
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002965 sp<NotificationListener> listener = mListener.promote();
2966 if (listener != NULL) {
2967 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002968 CaptureResultExtras());
Shuzhen Wang316781a2020-08-18 18:11:01 -07002969 mSessionStatsBuilder.onDeviceError();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002970 }
2971
2972 // Save stack trace. View by dumping it later.
2973 CameraTraces::saveTrace();
2974 // TODO: consider adding errorCause and client pid/procname
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002975}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002976
2977/**
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002978 * In-flight request management
2979 */
2980
Jianing Weicb0652e2014-03-12 18:29:36 -07002981status_t Camera3Device::registerInFlight(uint32_t frameNumber,
Chien-Yu Chend196d612015-06-22 19:49:01 -07002982 int32_t numBuffers, CaptureResultExtras resultExtras, bool hasInput,
Shuzhen Wang5c22c152017-12-31 17:12:25 -08002983 bool hasAppCallback, nsecs_t maxExpectedDuration,
Shuzhen Wang99080502021-03-07 21:08:20 -08002984 const std::set<std::set<String8>>& physicalCameraIds,
2985 bool isStillCapture, bool isZslCapture, bool rotateAndCropAuto,
2986 const std::set<std::string>& cameraIdsWithZoom,
Shuzhen Wang316781a2020-08-18 18:11:01 -07002987 const SurfaceMap& outputSurfaces, nsecs_t requestTimeNs) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002988 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002989 std::lock_guard<std::mutex> l(mInFlightLock);
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002990
2991 ssize_t res;
Chien-Yu Chend196d612015-06-22 19:49:01 -07002992 res = mInFlightMap.add(frameNumber, InFlightRequest(numBuffers, resultExtras, hasInput,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07002993 hasAppCallback, maxExpectedDuration, physicalCameraIds, isStillCapture, isZslCapture,
Shuzhen Wang316781a2020-08-18 18:11:01 -07002994 rotateAndCropAuto, cameraIdsWithZoom, requestTimeNs, outputSurfaces));
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002995 if (res < 0) return res;
2996
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07002997 if (mInFlightMap.size() == 1) {
Emilian Peev26d975d2018-07-05 14:52:57 +01002998 // Hold a separate dedicated tracker lock to prevent race with disconnect and also
2999 // avoid a deadlock during reprocess requests.
3000 Mutex::Autolock l(mTrackerLock);
Yin-Chia Yeh38dfde52017-06-27 17:13:33 -07003001 if (mStatusTracker != nullptr) {
3002 mStatusTracker->markComponentActive(mInFlightStatusId);
3003 }
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07003004 }
3005
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003006 mExpectedInflightDuration += maxExpectedDuration;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003007 return OK;
3008}
3009
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003010void Camera3Device::onInflightEntryRemovedLocked(nsecs_t duration) {
Shuzhen Wangcadb3302016-11-04 14:17:56 -07003011 // Indicate idle inFlightMap to the status tracker
3012 if (mInFlightMap.size() == 0) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07003013 mRequestBufferSM.onInflightMapEmpty();
Emilian Peev26d975d2018-07-05 14:52:57 +01003014 // Hold a separate dedicated tracker lock to prevent race with disconnect and also
3015 // avoid a deadlock during reprocess requests.
3016 Mutex::Autolock l(mTrackerLock);
Yin-Chia Yeh38dfde52017-06-27 17:13:33 -07003017 if (mStatusTracker != nullptr) {
3018 mStatusTracker->markComponentIdle(mInFlightStatusId, Fence::NO_FENCE);
3019 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07003020 }
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003021 mExpectedInflightDuration -= duration;
Shuzhen Wangcadb3302016-11-04 14:17:56 -07003022}
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003023
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003024void Camera3Device::checkInflightMapLengthLocked() {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04003025 // Validation check - if we have too many in-flight frames with long total inflight duration,
Yin-Chia Yeh99fd0972019-06-27 14:22:44 -07003026 // something has likely gone wrong. This might still be legit only if application send in
3027 // a long burst of long exposure requests.
3028 if (mExpectedInflightDuration > kMinWarnInflightDuration) {
3029 if (!mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() > kInFlightWarnLimit) {
3030 CLOGW("In-flight list too large: %zu, total inflight duration %" PRIu64,
3031 mInFlightMap.size(), mExpectedInflightDuration);
3032 } else if (mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() >
3033 kInFlightWarnLimitHighSpeed) {
3034 CLOGW("In-flight list too large for high speed configuration: %zu,"
3035 "total inflight duration %" PRIu64,
3036 mInFlightMap.size(), mExpectedInflightDuration);
3037 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003038 }
3039}
3040
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003041void Camera3Device::onInflightMapFlushedLocked() {
3042 mExpectedInflightDuration = 0;
3043}
3044
3045void Camera3Device::removeInFlightMapEntryLocked(int idx) {
Jayant Chowdharyd4776262020-06-23 23:45:57 -07003046 ATRACE_HFR_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003047 nsecs_t duration = mInFlightMap.valueAt(idx).maxExpectedDuration;
3048 mInFlightMap.removeItemsAt(idx, 1);
3049
3050 onInflightEntryRemovedLocked(duration);
3051}
3052
3053
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003054void Camera3Device::flushInflightRequests() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003055 ATRACE_CALL();
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003056 sp<NotificationListener> listener;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003057 {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003058 std::lock_guard<std::mutex> l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003059 listener = mListener.promote();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003060 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003061
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003062 FlushInflightReqStates states {
3063 mId, mInFlightLock, mInFlightMap, mUseHalBufManager,
Shuzhen Wang316781a2020-08-18 18:11:01 -07003064 listener, *this, *mInterface, *this, mSessionStatsBuilder};
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003065
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003066 camera3::flushInflightRequests(states);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003067}
3068
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003069CameraMetadata Camera3Device::getLatestRequestLocked() {
Igor Murashkin1e479c02013-09-06 16:55:14 -07003070 ALOGV("%s", __FUNCTION__);
3071
Igor Murashkin1e479c02013-09-06 16:55:14 -07003072 CameraMetadata retVal;
3073
3074 if (mRequestThread != NULL) {
3075 retVal = mRequestThread->getLatestRequest();
3076 }
3077
Igor Murashkin1e479c02013-09-06 16:55:14 -07003078 return retVal;
3079}
3080
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07003081void Camera3Device::monitorMetadata(TagMonitor::eventSource source,
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003082 int64_t frameNumber, nsecs_t timestamp, const CameraMetadata& metadata,
3083 const std::unordered_map<std::string, CameraMetadata>& physicalMetadata) {
3084
3085 mTagMonitor.monitorMetadata(source, frameNumber, timestamp, metadata,
3086 physicalMetadata);
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07003087}
3088
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003089/**
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003090 * HalInterface inner class methods
3091 */
3092
Yifan Hongf79b5542017-04-11 14:44:25 -07003093Camera3Device::HalInterface::HalInterface(
3094 sp<ICameraDeviceSession> &session,
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003095 std::shared_ptr<RequestMetadataQueue> queue,
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003096 bool useHalBufManager, bool supportOfflineProcessing) :
Yifan Hongf79b5542017-04-11 14:44:25 -07003097 mHidlSession(session),
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003098 mRequestMetadataQueue(queue),
Emilian Peev4ec17882019-01-24 17:16:58 -08003099 mUseHalBufManager(useHalBufManager),
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003100 mIsReconfigurationQuerySupported(true),
3101 mSupportOfflineProcessing(supportOfflineProcessing) {
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003102 // Check with hardware service manager if we can downcast these interfaces
3103 // Somewhat expensive, so cache the results at startup
Shuzhen Wang83bff122020-11-20 15:51:39 -08003104 auto castResult_3_7 = device::V3_7::ICameraDeviceSession::castFrom(mHidlSession);
3105 if (castResult_3_7.isOk()) {
3106 mHidlSession_3_7 = castResult_3_7;
3107 }
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003108 auto castResult_3_6 = device::V3_6::ICameraDeviceSession::castFrom(mHidlSession);
3109 if (castResult_3_6.isOk()) {
3110 mHidlSession_3_6 = castResult_3_6;
3111 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003112 auto castResult_3_5 = device::V3_5::ICameraDeviceSession::castFrom(mHidlSession);
3113 if (castResult_3_5.isOk()) {
3114 mHidlSession_3_5 = castResult_3_5;
3115 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003116 auto castResult_3_4 = device::V3_4::ICameraDeviceSession::castFrom(mHidlSession);
3117 if (castResult_3_4.isOk()) {
3118 mHidlSession_3_4 = castResult_3_4;
3119 }
3120 auto castResult_3_3 = device::V3_3::ICameraDeviceSession::castFrom(mHidlSession);
3121 if (castResult_3_3.isOk()) {
3122 mHidlSession_3_3 = castResult_3_3;
3123 }
3124}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003125
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003126Camera3Device::HalInterface::HalInterface() :
3127 mUseHalBufManager(false),
3128 mSupportOfflineProcessing(false) {}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003129
3130Camera3Device::HalInterface::HalInterface(const HalInterface& other) :
Yifan Hongf79b5542017-04-11 14:44:25 -07003131 mHidlSession(other.mHidlSession),
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003132 mRequestMetadataQueue(other.mRequestMetadataQueue),
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003133 mUseHalBufManager(other.mUseHalBufManager),
3134 mSupportOfflineProcessing(other.mSupportOfflineProcessing) {}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003135
3136bool Camera3Device::HalInterface::valid() {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003137 return (mHidlSession != nullptr);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003138}
3139
3140void Camera3Device::HalInterface::clear() {
Shuzhen Wang83bff122020-11-20 15:51:39 -08003141 mHidlSession_3_7.clear();
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003142 mHidlSession_3_6.clear();
Emilian Peev644a3e12018-11-23 13:52:39 +00003143 mHidlSession_3_5.clear();
Emilian Peev9e740b02018-01-30 18:28:03 +00003144 mHidlSession_3_4.clear();
3145 mHidlSession_3_3.clear();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003146 mHidlSession.clear();
3147}
3148
3149status_t Camera3Device::HalInterface::constructDefaultRequestSettings(
Emilian Peevf4816702020-04-03 15:44:51 -07003150 camera_request_template_t templateId,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003151 /*out*/ camera_metadata_t **requestTemplate) {
3152 ATRACE_NAME("CameraHal::constructDefaultRequestSettings");
3153 if (!valid()) return INVALID_OPERATION;
3154 status_t res = OK;
3155
Emilian Peev31abd0a2017-05-11 18:37:46 +01003156 common::V1_0::Status status;
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003157
3158 auto requestCallback = [&status, &requestTemplate]
Emilian Peev31abd0a2017-05-11 18:37:46 +01003159 (common::V1_0::Status s, const device::V3_2::CameraMetadata& request) {
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003160 status = s;
3161 if (status == common::V1_0::Status::OK) {
3162 const camera_metadata *r =
3163 reinterpret_cast<const camera_metadata_t*>(request.data());
3164 size_t expectedSize = request.size();
3165 int ret = validate_camera_metadata_structure(r, &expectedSize);
3166 if (ret == OK || ret == CAMERA_METADATA_VALIDATION_SHIFTED) {
3167 *requestTemplate = clone_camera_metadata(r);
3168 if (*requestTemplate == nullptr) {
3169 ALOGE("%s: Unable to clone camera metadata received from HAL",
3170 __FUNCTION__);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003171 status = common::V1_0::Status::INTERNAL_ERROR;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003172 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003173 } else {
3174 ALOGE("%s: Malformed camera metadata received from HAL", __FUNCTION__);
3175 status = common::V1_0::Status::INTERNAL_ERROR;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003176 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003177 }
3178 };
3179 hardware::Return<void> err;
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003180 RequestTemplate id;
3181 switch (templateId) {
Emilian Peevf4816702020-04-03 15:44:51 -07003182 case CAMERA_TEMPLATE_PREVIEW:
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003183 id = RequestTemplate::PREVIEW;
3184 break;
Emilian Peevf4816702020-04-03 15:44:51 -07003185 case CAMERA_TEMPLATE_STILL_CAPTURE:
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003186 id = RequestTemplate::STILL_CAPTURE;
3187 break;
Emilian Peevf4816702020-04-03 15:44:51 -07003188 case CAMERA_TEMPLATE_VIDEO_RECORD:
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003189 id = RequestTemplate::VIDEO_RECORD;
3190 break;
Emilian Peevf4816702020-04-03 15:44:51 -07003191 case CAMERA_TEMPLATE_VIDEO_SNAPSHOT:
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003192 id = RequestTemplate::VIDEO_SNAPSHOT;
3193 break;
Emilian Peevf4816702020-04-03 15:44:51 -07003194 case CAMERA_TEMPLATE_ZERO_SHUTTER_LAG:
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003195 id = RequestTemplate::ZERO_SHUTTER_LAG;
3196 break;
Emilian Peevf4816702020-04-03 15:44:51 -07003197 case CAMERA_TEMPLATE_MANUAL:
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003198 id = RequestTemplate::MANUAL;
3199 break;
3200 default:
3201 // Unknown template ID, or this HAL is too old to support it
3202 return BAD_VALUE;
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003203 }
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003204 err = mHidlSession->constructDefaultRequestSettings(id, requestCallback);
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003205
Emilian Peev31abd0a2017-05-11 18:37:46 +01003206 if (!err.isOk()) {
3207 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3208 res = DEAD_OBJECT;
3209 } else {
3210 res = CameraProviderManager::mapToStatusT(status);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003211 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003212
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003213 return res;
3214}
3215
Emilian Peev4ec17882019-01-24 17:16:58 -08003216bool Camera3Device::HalInterface::isReconfigurationRequired(CameraMetadata& oldSessionParams,
3217 CameraMetadata& newSessionParams) {
3218 // We do reconfiguration by default;
3219 bool ret = true;
3220 if ((mHidlSession_3_5 != nullptr) && mIsReconfigurationQuerySupported) {
3221 android::hardware::hidl_vec<uint8_t> oldParams, newParams;
3222 camera_metadata_t* oldSessioMeta = const_cast<camera_metadata_t*>(
3223 oldSessionParams.getAndLock());
3224 camera_metadata_t* newSessioMeta = const_cast<camera_metadata_t*>(
3225 newSessionParams.getAndLock());
3226 oldParams.setToExternal(reinterpret_cast<uint8_t*>(oldSessioMeta),
3227 get_camera_metadata_size(oldSessioMeta));
3228 newParams.setToExternal(reinterpret_cast<uint8_t*>(newSessioMeta),
3229 get_camera_metadata_size(newSessioMeta));
3230 hardware::camera::common::V1_0::Status callStatus;
3231 bool required;
3232 auto hidlCb = [&callStatus, &required] (hardware::camera::common::V1_0::Status s,
3233 bool requiredFlag) {
3234 callStatus = s;
3235 required = requiredFlag;
3236 };
3237 auto err = mHidlSession_3_5->isReconfigurationRequired(oldParams, newParams, hidlCb);
3238 oldSessionParams.unlock(oldSessioMeta);
3239 newSessionParams.unlock(newSessioMeta);
3240 if (err.isOk()) {
3241 switch (callStatus) {
3242 case hardware::camera::common::V1_0::Status::OK:
3243 ret = required;
3244 break;
3245 case hardware::camera::common::V1_0::Status::METHOD_NOT_SUPPORTED:
3246 mIsReconfigurationQuerySupported = false;
3247 ret = true;
3248 break;
3249 default:
3250 ALOGV("%s: Reconfiguration query failed: %d", __FUNCTION__, callStatus);
3251 ret = true;
3252 }
3253 } else {
3254 ALOGE("%s: Unexpected binder error: %s", __FUNCTION__, err.description().c_str());
3255 ret = true;
3256 }
3257 }
3258
3259 return ret;
3260}
3261
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003262status_t Camera3Device::HalInterface::configureStreams(const camera_metadata_t *sessionParams,
Emilian Peevf4816702020-04-03 15:44:51 -07003263 camera_stream_configuration *config, const std::vector<uint32_t>& bufferSizes) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003264 ATRACE_NAME("CameraHal::configureStreams");
3265 if (!valid()) return INVALID_OPERATION;
3266 status_t res = OK;
3267
Shuzhen Wang83bff122020-11-20 15:51:39 -08003268 if (config->input_is_multi_resolution && mHidlSession_3_7 == nullptr) {
3269 ALOGE("%s: Camera device doesn't support multi-resolution input stream", __FUNCTION__);
3270 return BAD_VALUE;
3271 }
3272
Emilian Peev31abd0a2017-05-11 18:37:46 +01003273 // Convert stream config to HIDL
3274 std::set<int> activeStreams;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003275 device::V3_2::StreamConfiguration requestedConfiguration3_2;
3276 device::V3_4::StreamConfiguration requestedConfiguration3_4;
Shuzhen Wang83bff122020-11-20 15:51:39 -08003277 device::V3_7::StreamConfiguration requestedConfiguration3_7;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003278 requestedConfiguration3_2.streams.resize(config->num_streams);
3279 requestedConfiguration3_4.streams.resize(config->num_streams);
Shuzhen Wang83bff122020-11-20 15:51:39 -08003280 requestedConfiguration3_7.streams.resize(config->num_streams);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003281 for (size_t i = 0; i < config->num_streams; i++) {
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003282 device::V3_2::Stream &dst3_2 = requestedConfiguration3_2.streams[i];
3283 device::V3_4::Stream &dst3_4 = requestedConfiguration3_4.streams[i];
Shuzhen Wang83bff122020-11-20 15:51:39 -08003284 device::V3_7::Stream &dst3_7 = requestedConfiguration3_7.streams[i];
Emilian Peevf4816702020-04-03 15:44:51 -07003285 camera3::camera_stream_t *src = config->streams[i];
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003286
Emilian Peev31abd0a2017-05-11 18:37:46 +01003287 Camera3Stream* cam3stream = Camera3Stream::cast(src);
3288 cam3stream->setBufferFreedListener(this);
3289 int streamId = cam3stream->getId();
3290 StreamType streamType;
3291 switch (src->stream_type) {
Emilian Peevf4816702020-04-03 15:44:51 -07003292 case CAMERA_STREAM_OUTPUT:
Emilian Peev31abd0a2017-05-11 18:37:46 +01003293 streamType = StreamType::OUTPUT;
3294 break;
Emilian Peevf4816702020-04-03 15:44:51 -07003295 case CAMERA_STREAM_INPUT:
Emilian Peev31abd0a2017-05-11 18:37:46 +01003296 streamType = StreamType::INPUT;
3297 break;
3298 default:
3299 ALOGE("%s: Stream %d: Unsupported stream type %d",
3300 __FUNCTION__, streamId, config->streams[i]->stream_type);
3301 return BAD_VALUE;
3302 }
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003303 dst3_2.id = streamId;
3304 dst3_2.streamType = streamType;
3305 dst3_2.width = src->width;
3306 dst3_2.height = src->height;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003307 dst3_2.usage = mapToConsumerUsage(cam3stream->getUsage());
Emilian Peevf4816702020-04-03 15:44:51 -07003308 dst3_2.rotation = mapToStreamRotation((camera_stream_rotation_t) src->rotation);
Shuzhen Wang92653952019-05-07 15:11:43 -07003309 // For HidlSession version 3.5 or newer, the format and dataSpace sent
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08003310 // to HAL are original, not the overridden ones.
Shuzhen Wang92653952019-05-07 15:11:43 -07003311 if (mHidlSession_3_5 != nullptr) {
3312 dst3_2.format = mapToPixelFormat(cam3stream->isFormatOverridden() ?
3313 cam3stream->getOriginalFormat() : src->format);
3314 dst3_2.dataSpace = mapToHidlDataspace(cam3stream->isDataSpaceOverridden() ?
3315 cam3stream->getOriginalDataSpace() : src->data_space);
3316 } else {
3317 dst3_2.format = mapToPixelFormat(src->format);
3318 dst3_2.dataSpace = mapToHidlDataspace(src->data_space);
3319 }
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003320 dst3_4.v3_2 = dst3_2;
Emilian Peev192ee832018-01-31 14:46:47 +00003321 dst3_4.bufferSize = bufferSizes[i];
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003322 if (src->physical_camera_id != nullptr) {
3323 dst3_4.physicalCameraId = src->physical_camera_id;
3324 }
Shuzhen Wang83bff122020-11-20 15:51:39 -08003325 dst3_7.v3_4 = dst3_4;
3326 dst3_7.groupId = cam3stream->getHalStreamGroupId();
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08003327 dst3_7.sensorPixelModesUsed.resize(src->sensor_pixel_modes_used.size());
3328 size_t j = 0;
3329 for (int mode : src->sensor_pixel_modes_used) {
3330 dst3_7.sensorPixelModesUsed[j++] =
3331 static_cast<CameraMetadataEnumAndroidSensorPixelMode>(mode);
3332 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003333 activeStreams.insert(streamId);
3334 // Create Buffer ID map if necessary
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003335 mBufferRecords.tryCreateBufferCache(streamId);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003336 }
3337 // remove BufferIdMap for deleted streams
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003338 mBufferRecords.removeInactiveBufferCaches(activeStreams);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003339
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003340 StreamConfigurationMode operationMode;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003341 res = mapToStreamConfigurationMode(
Emilian Peevf4816702020-04-03 15:44:51 -07003342 (camera_stream_configuration_mode_t) config->operation_mode,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003343 /*out*/ &operationMode);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003344 if (res != OK) {
3345 return res;
3346 }
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003347 requestedConfiguration3_2.operationMode = operationMode;
3348 requestedConfiguration3_4.operationMode = operationMode;
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08003349 requestedConfiguration3_7.operationMode = operationMode;
3350 size_t sessionParamSize = get_camera_metadata_size(sessionParams);
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003351 requestedConfiguration3_4.sessionParams.setToExternal(
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003352 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(sessionParams)),
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08003353 sessionParamSize);
Shuzhen Wang83bff122020-11-20 15:51:39 -08003354 requestedConfiguration3_7.operationMode = operationMode;
3355 requestedConfiguration3_7.sessionParams.setToExternal(
3356 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(sessionParams)),
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08003357 sessionParamSize);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003358
Emilian Peev31abd0a2017-05-11 18:37:46 +01003359 // Invoke configureStreams
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003360 device::V3_3::HalStreamConfiguration finalConfiguration;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003361 device::V3_4::HalStreamConfiguration finalConfiguration3_4;
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003362 device::V3_6::HalStreamConfiguration finalConfiguration3_6;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003363 common::V1_0::Status status;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003364
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003365 auto configStream34Cb = [&status, &finalConfiguration3_4]
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003366 (common::V1_0::Status s, const device::V3_4::HalStreamConfiguration& halConfiguration) {
3367 finalConfiguration3_4 = halConfiguration;
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003368 status = s;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003369 };
3370
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003371 auto configStream36Cb = [&status, &finalConfiguration3_6]
3372 (common::V1_0::Status s, const device::V3_6::HalStreamConfiguration& halConfiguration) {
3373 finalConfiguration3_6 = halConfiguration;
3374 status = s;
3375 };
3376
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003377 auto postprocConfigStream34 = [&finalConfiguration, &finalConfiguration3_4]
3378 (hardware::Return<void>& err) -> status_t {
3379 if (!err.isOk()) {
3380 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3381 return DEAD_OBJECT;
3382 }
3383 finalConfiguration.streams.resize(finalConfiguration3_4.streams.size());
3384 for (size_t i = 0; i < finalConfiguration3_4.streams.size(); i++) {
3385 finalConfiguration.streams[i] = finalConfiguration3_4.streams[i].v3_3;
3386 }
3387 return OK;
3388 };
3389
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003390 auto postprocConfigStream36 = [&finalConfiguration, &finalConfiguration3_6]
3391 (hardware::Return<void>& err) -> status_t {
3392 if (!err.isOk()) {
3393 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3394 return DEAD_OBJECT;
3395 }
3396 finalConfiguration.streams.resize(finalConfiguration3_6.streams.size());
3397 for (size_t i = 0; i < finalConfiguration3_6.streams.size(); i++) {
3398 finalConfiguration.streams[i] = finalConfiguration3_6.streams[i].v3_4.v3_3;
3399 }
3400 return OK;
3401 };
3402
Shuzhen Wang92653952019-05-07 15:11:43 -07003403 // See which version of HAL we have
Shuzhen Wang83bff122020-11-20 15:51:39 -08003404 if (mHidlSession_3_7 != nullptr) {
3405 ALOGV("%s: v3.7 device found", __FUNCTION__);
3406 requestedConfiguration3_7.streamConfigCounter = mNextStreamConfigCounter++;
3407 requestedConfiguration3_7.multiResolutionInputImage = config->input_is_multi_resolution;
3408 auto err = mHidlSession_3_7->configureStreams_3_7(
3409 requestedConfiguration3_7, configStream36Cb);
3410 res = postprocConfigStream36(err);
3411 if (res != OK) {
3412 return res;
3413 }
3414 } else if (mHidlSession_3_6 != nullptr) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003415 ALOGV("%s: v3.6 device found", __FUNCTION__);
3416 device::V3_5::StreamConfiguration requestedConfiguration3_5;
3417 requestedConfiguration3_5.v3_4 = requestedConfiguration3_4;
3418 requestedConfiguration3_5.streamConfigCounter = mNextStreamConfigCounter++;
3419 auto err = mHidlSession_3_6->configureStreams_3_6(
3420 requestedConfiguration3_5, configStream36Cb);
3421 res = postprocConfigStream36(err);
3422 if (res != OK) {
3423 return res;
3424 }
3425 } else if (mHidlSession_3_5 != nullptr) {
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003426 ALOGV("%s: v3.5 device found", __FUNCTION__);
3427 device::V3_5::StreamConfiguration requestedConfiguration3_5;
3428 requestedConfiguration3_5.v3_4 = requestedConfiguration3_4;
3429 requestedConfiguration3_5.streamConfigCounter = mNextStreamConfigCounter++;
3430 auto err = mHidlSession_3_5->configureStreams_3_5(
3431 requestedConfiguration3_5, configStream34Cb);
3432 res = postprocConfigStream34(err);
3433 if (res != OK) {
3434 return res;
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003435 }
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003436 } else if (mHidlSession_3_4 != nullptr) {
3437 // We do; use v3.4 for the call
3438 ALOGV("%s: v3.4 device found", __FUNCTION__);
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003439 auto err = mHidlSession_3_4->configureStreams_3_4(
3440 requestedConfiguration3_4, configStream34Cb);
3441 res = postprocConfigStream34(err);
3442 if (res != OK) {
3443 return res;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003444 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003445 } else if (mHidlSession_3_3 != nullptr) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003446 // We do; use v3.3 for the call
3447 ALOGV("%s: v3.3 device found", __FUNCTION__);
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003448 auto err = mHidlSession_3_3->configureStreams_3_3(requestedConfiguration3_2,
Emilian Peev31abd0a2017-05-11 18:37:46 +01003449 [&status, &finalConfiguration]
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003450 (common::V1_0::Status s, const device::V3_3::HalStreamConfiguration& halConfiguration) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003451 finalConfiguration = halConfiguration;
3452 status = s;
3453 });
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003454 if (!err.isOk()) {
3455 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3456 return DEAD_OBJECT;
3457 }
3458 } else {
3459 // We don't; use v3.2 call and construct a v3.3 HalStreamConfiguration
3460 ALOGV("%s: v3.2 device found", __FUNCTION__);
3461 HalStreamConfiguration finalConfiguration_3_2;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003462 auto err = mHidlSession->configureStreams(requestedConfiguration3_2,
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003463 [&status, &finalConfiguration_3_2]
3464 (common::V1_0::Status s, const HalStreamConfiguration& halConfiguration) {
3465 finalConfiguration_3_2 = halConfiguration;
3466 status = s;
3467 });
3468 if (!err.isOk()) {
3469 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3470 return DEAD_OBJECT;
3471 }
3472 finalConfiguration.streams.resize(finalConfiguration_3_2.streams.size());
3473 for (size_t i = 0; i < finalConfiguration_3_2.streams.size(); i++) {
3474 finalConfiguration.streams[i].v3_2 = finalConfiguration_3_2.streams[i];
3475 finalConfiguration.streams[i].overrideDataSpace =
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003476 requestedConfiguration3_2.streams[i].dataSpace;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003477 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003478 }
3479
3480 if (status != common::V1_0::Status::OK ) {
3481 return CameraProviderManager::mapToStatusT(status);
3482 }
3483
3484 // And convert output stream configuration from HIDL
3485
3486 for (size_t i = 0; i < config->num_streams; i++) {
Emilian Peevf4816702020-04-03 15:44:51 -07003487 camera3::camera_stream_t *dst = config->streams[i];
Emilian Peev31abd0a2017-05-11 18:37:46 +01003488 int streamId = Camera3Stream::cast(dst)->getId();
3489
3490 // Start scan at i, with the assumption that the stream order matches
3491 size_t realIdx = i;
3492 bool found = false;
Eino-Ville Talvala370875f2019-04-12 12:40:27 -07003493 size_t halStreamCount = finalConfiguration.streams.size();
3494 for (size_t idx = 0; idx < halStreamCount; idx++) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003495 if (finalConfiguration.streams[realIdx].v3_2.id == streamId) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003496 found = true;
3497 break;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003498 }
Eino-Ville Talvala370875f2019-04-12 12:40:27 -07003499 realIdx = (realIdx >= halStreamCount - 1) ? 0 : realIdx + 1;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003500 }
3501 if (!found) {
3502 ALOGE("%s: Stream %d not found in stream configuration response from HAL",
3503 __FUNCTION__, streamId);
3504 return INVALID_OPERATION;
3505 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003506 device::V3_3::HalStream &src = finalConfiguration.streams[realIdx];
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003507 device::V3_6::HalStream &src_36 = finalConfiguration3_6.streams[realIdx];
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003508
Emilian Peev710c1422017-08-30 11:19:38 +01003509 Camera3Stream* dstStream = Camera3Stream::cast(dst);
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003510 int overrideFormat = mapToFrameworkFormat(src.v3_2.overrideFormat);
3511 android_dataspace overrideDataSpace = mapToFrameworkDataspace(src.overrideDataSpace);
3512
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003513 if (mHidlSession_3_6 != nullptr) {
3514 dstStream->setOfflineProcessingSupport(src_36.supportOffline);
3515 }
3516
Yin-Chia Yeh90667662019-07-01 15:45:00 -07003517 if (dstStream->getOriginalFormat() != HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
Shuzhen Wang92653952019-05-07 15:11:43 -07003518 dstStream->setFormatOverride(false);
3519 dstStream->setDataSpaceOverride(false);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003520 if (dst->format != overrideFormat) {
3521 ALOGE("%s: Stream %d: Format override not allowed for format 0x%x", __FUNCTION__,
3522 streamId, dst->format);
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003523 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003524 if (dst->data_space != overrideDataSpace) {
3525 ALOGE("%s: Stream %d: DataSpace override not allowed for format 0x%x", __FUNCTION__,
3526 streamId, dst->format);
3527 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003528 } else {
Shuzhen Wang92653952019-05-07 15:11:43 -07003529 bool needFormatOverride =
3530 requestedConfiguration3_2.streams[i].format != src.v3_2.overrideFormat;
3531 bool needDataspaceOverride =
3532 requestedConfiguration3_2.streams[i].dataSpace != src.overrideDataSpace;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003533 // Override allowed with IMPLEMENTATION_DEFINED
Shuzhen Wang92653952019-05-07 15:11:43 -07003534 dstStream->setFormatOverride(needFormatOverride);
3535 dstStream->setDataSpaceOverride(needDataspaceOverride);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003536 dst->format = overrideFormat;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003537 dst->data_space = overrideDataSpace;
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003538 }
3539
Emilian Peevf4816702020-04-03 15:44:51 -07003540 if (dst->stream_type == CAMERA_STREAM_INPUT) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003541 if (src.v3_2.producerUsage != 0) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003542 ALOGE("%s: Stream %d: INPUT streams must have 0 for producer usage",
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003543 __FUNCTION__, streamId);
3544 return INVALID_OPERATION;
3545 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003546 dstStream->setUsage(
3547 mapConsumerToFrameworkUsage(src.v3_2.consumerUsage));
Emilian Peev31abd0a2017-05-11 18:37:46 +01003548 } else {
3549 // OUTPUT
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003550 if (src.v3_2.consumerUsage != 0) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003551 ALOGE("%s: Stream %d: OUTPUT streams must have 0 for consumer usage",
3552 __FUNCTION__, streamId);
3553 return INVALID_OPERATION;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003554 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003555 dstStream->setUsage(
3556 mapProducerToFrameworkUsage(src.v3_2.producerUsage));
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003557 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003558 dst->max_buffers = src.v3_2.maxBuffers;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003559 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003560
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003561 return res;
3562}
3563
Cliff Wuc2ad9c82021-04-21 00:58:58 +08003564status_t Camera3Device::HalInterface::configureInjectedStreams(
3565 const camera_metadata_t* sessionParams, camera_stream_configuration* config,
3566 const std::vector<uint32_t>& bufferSizes,
3567 const CameraMetadata& cameraCharacteristics) {
3568 ATRACE_NAME("InjectionCameraHal::configureStreams");
3569 if (!valid()) return INVALID_OPERATION;
3570 status_t res = OK;
3571
3572 if (config->input_is_multi_resolution) {
3573 ALOGE("%s: Injection camera device doesn't support multi-resolution input "
3574 "stream", __FUNCTION__);
3575 return BAD_VALUE;
3576 }
3577
3578 // Convert stream config to HIDL
3579 std::set<int> activeStreams;
3580 device::V3_2::StreamConfiguration requestedConfiguration3_2;
3581 device::V3_4::StreamConfiguration requestedConfiguration3_4;
3582 device::V3_7::StreamConfiguration requestedConfiguration3_7;
3583 requestedConfiguration3_2.streams.resize(config->num_streams);
3584 requestedConfiguration3_4.streams.resize(config->num_streams);
3585 requestedConfiguration3_7.streams.resize(config->num_streams);
3586 for (size_t i = 0; i < config->num_streams; i++) {
3587 device::V3_2::Stream& dst3_2 = requestedConfiguration3_2.streams[i];
3588 device::V3_4::Stream& dst3_4 = requestedConfiguration3_4.streams[i];
3589 device::V3_7::Stream& dst3_7 = requestedConfiguration3_7.streams[i];
3590 camera3::camera_stream_t* src = config->streams[i];
3591
3592 Camera3Stream* cam3stream = Camera3Stream::cast(src);
3593 cam3stream->setBufferFreedListener(this);
3594 int streamId = cam3stream->getId();
3595 StreamType streamType;
3596 switch (src->stream_type) {
3597 case CAMERA_STREAM_OUTPUT:
3598 streamType = StreamType::OUTPUT;
3599 break;
3600 case CAMERA_STREAM_INPUT:
3601 streamType = StreamType::INPUT;
3602 break;
3603 default:
3604 ALOGE("%s: Stream %d: Unsupported stream type %d", __FUNCTION__,
3605 streamId, config->streams[i]->stream_type);
3606 return BAD_VALUE;
3607 }
3608 dst3_2.id = streamId;
3609 dst3_2.streamType = streamType;
3610 dst3_2.width = src->width;
3611 dst3_2.height = src->height;
3612 dst3_2.usage = mapToConsumerUsage(cam3stream->getUsage());
3613 dst3_2.rotation =
3614 mapToStreamRotation((camera_stream_rotation_t)src->rotation);
3615 // For HidlSession version 3.5 or newer, the format and dataSpace sent
3616 // to HAL are original, not the overridden ones.
3617 if (mHidlSession_3_5 != nullptr) {
3618 dst3_2.format = mapToPixelFormat(cam3stream->isFormatOverridden()
3619 ? cam3stream->getOriginalFormat()
3620 : src->format);
3621 dst3_2.dataSpace =
3622 mapToHidlDataspace(cam3stream->isDataSpaceOverridden()
3623 ? cam3stream->getOriginalDataSpace()
3624 : src->data_space);
3625 } else {
3626 dst3_2.format = mapToPixelFormat(src->format);
3627 dst3_2.dataSpace = mapToHidlDataspace(src->data_space);
3628 }
3629 dst3_4.v3_2 = dst3_2;
3630 dst3_4.bufferSize = bufferSizes[i];
3631 if (src->physical_camera_id != nullptr) {
3632 dst3_4.physicalCameraId = src->physical_camera_id;
3633 }
3634 dst3_7.v3_4 = dst3_4;
3635 dst3_7.groupId = cam3stream->getHalStreamGroupId();
3636 dst3_7.sensorPixelModesUsed.resize(src->sensor_pixel_modes_used.size());
3637 size_t j = 0;
3638 for (int mode : src->sensor_pixel_modes_used) {
3639 dst3_7.sensorPixelModesUsed[j++] =
3640 static_cast<CameraMetadataEnumAndroidSensorPixelMode>(mode);
3641 }
3642 activeStreams.insert(streamId);
3643 // Create Buffer ID map if necessary
3644 mBufferRecords.tryCreateBufferCache(streamId);
3645 }
3646 // remove BufferIdMap for deleted streams
3647 mBufferRecords.removeInactiveBufferCaches(activeStreams);
3648
3649 StreamConfigurationMode operationMode;
3650 res = mapToStreamConfigurationMode(
3651 (camera_stream_configuration_mode_t)config->operation_mode,
3652 /*out*/ &operationMode);
3653 if (res != OK) {
3654 return res;
3655 }
3656 requestedConfiguration3_7.operationMode = operationMode;
3657 size_t sessionParamSize = get_camera_metadata_size(sessionParams);
3658 requestedConfiguration3_7.operationMode = operationMode;
3659 requestedConfiguration3_7.sessionParams.setToExternal(
3660 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(sessionParams)),
3661 sessionParamSize);
3662
3663 // See which version of HAL we have
3664 if (mHidlSession_3_7 != nullptr) {
3665 requestedConfiguration3_7.streamConfigCounter = mNextStreamConfigCounter++;
3666 requestedConfiguration3_7.multiResolutionInputImage =
3667 config->input_is_multi_resolution;
3668
3669 const camera_metadata_t* rawMetadata = cameraCharacteristics.getAndLock();
3670 ::android::hardware::camera::device::V3_2::CameraMetadata hidlChars = {};
3671 hidlChars.setToExternal(
3672 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(rawMetadata)),
3673 get_camera_metadata_size(rawMetadata));
3674 cameraCharacteristics.unlock(rawMetadata);
3675
3676 sp<hardware::camera::device::V3_7::ICameraInjectionSession>
3677 hidlInjectionSession_3_7;
3678 auto castInjectionResult_3_7 =
3679 device::V3_7::ICameraInjectionSession::castFrom(mHidlSession_3_7);
3680 if (castInjectionResult_3_7.isOk()) {
3681 hidlInjectionSession_3_7 = castInjectionResult_3_7;
3682 } else {
3683 ALOGE("%s: Transaction error: %s", __FUNCTION__,
3684 castInjectionResult_3_7.description().c_str());
3685 return DEAD_OBJECT;
3686 }
3687
3688 auto err = hidlInjectionSession_3_7->configureInjectionStreams(
3689 requestedConfiguration3_7, hidlChars);
3690 if (!err.isOk()) {
3691 ALOGE("%s: Transaction error: %s", __FUNCTION__,
3692 err.description().c_str());
3693 return DEAD_OBJECT;
3694 }
3695 } else {
3696 ALOGE("%s: mHidlSession_3_7 does not exist, the lowest version of injection "
3697 "session is 3.7", __FUNCTION__);
3698 return DEAD_OBJECT;
3699 }
3700
3701 return res;
3702}
3703
Emilian Peevf4816702020-04-03 15:44:51 -07003704status_t Camera3Device::HalInterface::wrapAsHidlRequest(camera_capture_request_t* request,
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003705 /*out*/device::V3_2::CaptureRequest* captureRequest,
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003706 /*out*/std::vector<native_handle_t*>* handlesCreated,
3707 /*out*/std::vector<std::pair<int32_t, int32_t>>* inflightBuffers) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003708 ATRACE_CALL();
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003709 if (captureRequest == nullptr || handlesCreated == nullptr || inflightBuffers == nullptr) {
3710 ALOGE("%s: captureRequest (%p), handlesCreated (%p), and inflightBuffers(%p) "
3711 "must not be null", __FUNCTION__, captureRequest, handlesCreated, inflightBuffers);
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003712 return BAD_VALUE;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003713 }
3714
3715 captureRequest->frameNumber = request->frame_number;
Yifan Hongf79b5542017-04-11 14:44:25 -07003716
3717 captureRequest->fmqSettingsSize = 0;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003718
3719 {
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003720 if (request->input_buffer != nullptr) {
3721 int32_t streamId = Camera3Stream::cast(request->input_buffer->stream)->getId();
3722 buffer_handle_t buf = *(request->input_buffer->buffer);
3723 auto pair = getBufferId(buf, streamId);
3724 bool isNewBuffer = pair.first;
3725 uint64_t bufferId = pair.second;
3726 captureRequest->inputBuffer.streamId = streamId;
3727 captureRequest->inputBuffer.bufferId = bufferId;
3728 captureRequest->inputBuffer.buffer = (isNewBuffer) ? buf : nullptr;
3729 captureRequest->inputBuffer.status = BufferStatus::OK;
3730 native_handle_t *acquireFence = nullptr;
3731 if (request->input_buffer->acquire_fence != -1) {
3732 acquireFence = native_handle_create(1,0);
3733 acquireFence->data[0] = request->input_buffer->acquire_fence;
3734 handlesCreated->push_back(acquireFence);
3735 }
3736 captureRequest->inputBuffer.acquireFence = acquireFence;
3737 captureRequest->inputBuffer.releaseFence = nullptr;
3738
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003739 mBufferRecords.pushInflightBuffer(captureRequest->frameNumber, streamId,
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003740 request->input_buffer->buffer);
3741 inflightBuffers->push_back(std::make_pair(captureRequest->frameNumber, streamId));
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003742 } else {
3743 captureRequest->inputBuffer.streamId = -1;
3744 captureRequest->inputBuffer.bufferId = BUFFER_ID_NO_BUFFER;
3745 }
3746
3747 captureRequest->outputBuffers.resize(request->num_output_buffers);
3748 for (size_t i = 0; i < request->num_output_buffers; i++) {
Emilian Peevf4816702020-04-03 15:44:51 -07003749 const camera_stream_buffer_t *src = request->output_buffers + i;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003750 StreamBuffer &dst = captureRequest->outputBuffers[i];
3751 int32_t streamId = Camera3Stream::cast(src->stream)->getId();
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003752 if (src->buffer != nullptr) {
3753 buffer_handle_t buf = *(src->buffer);
3754 auto pair = getBufferId(buf, streamId);
3755 bool isNewBuffer = pair.first;
3756 dst.bufferId = pair.second;
3757 dst.buffer = isNewBuffer ? buf : nullptr;
3758 native_handle_t *acquireFence = nullptr;
3759 if (src->acquire_fence != -1) {
3760 acquireFence = native_handle_create(1,0);
3761 acquireFence->data[0] = src->acquire_fence;
3762 handlesCreated->push_back(acquireFence);
3763 }
3764 dst.acquireFence = acquireFence;
3765 } else if (mUseHalBufManager) {
3766 // HAL buffer management path
3767 dst.bufferId = BUFFER_ID_NO_BUFFER;
3768 dst.buffer = nullptr;
3769 dst.acquireFence = nullptr;
3770 } else {
3771 ALOGE("%s: cannot send a null buffer in capture request!", __FUNCTION__);
3772 return BAD_VALUE;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003773 }
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003774 dst.streamId = streamId;
3775 dst.status = BufferStatus::OK;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003776 dst.releaseFence = nullptr;
3777
Yin-Chia Yeh5f840f82019-03-05 11:59:04 -08003778 // Output buffers are empty when using HAL buffer manager
3779 if (!mUseHalBufManager) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003780 mBufferRecords.pushInflightBuffer(
3781 captureRequest->frameNumber, streamId, src->buffer);
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003782 inflightBuffers->push_back(std::make_pair(captureRequest->frameNumber, streamId));
Yin-Chia Yeh5f840f82019-03-05 11:59:04 -08003783 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003784 }
3785 }
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003786 return OK;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003787}
3788
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003789void Camera3Device::HalInterface::cleanupNativeHandles(
3790 std::vector<native_handle_t*> *handles, bool closeFd) {
3791 if (handles == nullptr) {
3792 return;
3793 }
3794 if (closeFd) {
3795 for (auto& handle : *handles) {
3796 native_handle_close(handle);
3797 }
3798 }
3799 for (auto& handle : *handles) {
3800 native_handle_delete(handle);
3801 }
3802 handles->clear();
3803 return;
3804}
3805
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003806status_t Camera3Device::HalInterface::processBatchCaptureRequests(
Emilian Peevf4816702020-04-03 15:44:51 -07003807 std::vector<camera_capture_request_t*>& requests,/*out*/uint32_t* numRequestProcessed) {
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003808 ATRACE_NAME("CameraHal::processBatchCaptureRequests");
3809 if (!valid()) return INVALID_OPERATION;
3810
Emilian Peevaebbe412018-01-15 13:53:24 +00003811 sp<device::V3_4::ICameraDeviceSession> hidlSession_3_4;
Shuzhen Wang83bff122020-11-20 15:51:39 -08003812 sp<device::V3_7::ICameraDeviceSession> hidlSession_3_7;
3813 auto castResult_3_7 = device::V3_7::ICameraDeviceSession::castFrom(mHidlSession);
3814 if (castResult_3_7.isOk()) {
3815 hidlSession_3_7 = castResult_3_7;
3816 }
Emilian Peevaebbe412018-01-15 13:53:24 +00003817 auto castResult_3_4 = device::V3_4::ICameraDeviceSession::castFrom(mHidlSession);
3818 if (castResult_3_4.isOk()) {
3819 hidlSession_3_4 = castResult_3_4;
3820 }
3821
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003822 hardware::hidl_vec<device::V3_2::CaptureRequest> captureRequests;
Emilian Peevaebbe412018-01-15 13:53:24 +00003823 hardware::hidl_vec<device::V3_4::CaptureRequest> captureRequests_3_4;
Shuzhen Wang83bff122020-11-20 15:51:39 -08003824 hardware::hidl_vec<device::V3_7::CaptureRequest> captureRequests_3_7;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003825 size_t batchSize = requests.size();
Shuzhen Wang83bff122020-11-20 15:51:39 -08003826 if (hidlSession_3_7 != nullptr) {
3827 captureRequests_3_7.resize(batchSize);
3828 } else if (hidlSession_3_4 != nullptr) {
Emilian Peevaebbe412018-01-15 13:53:24 +00003829 captureRequests_3_4.resize(batchSize);
3830 } else {
3831 captureRequests.resize(batchSize);
3832 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003833 std::vector<native_handle_t*> handlesCreated;
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003834 std::vector<std::pair<int32_t, int32_t>> inflightBuffers;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003835
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003836 status_t res = OK;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003837 for (size_t i = 0; i < batchSize; i++) {
Shuzhen Wang83bff122020-11-20 15:51:39 -08003838 if (hidlSession_3_7 != nullptr) {
3839 res = wrapAsHidlRequest(requests[i], /*out*/&captureRequests_3_7[i].v3_4.v3_2,
3840 /*out*/&handlesCreated, /*out*/&inflightBuffers);
3841 } else if (hidlSession_3_4 != nullptr) {
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003842 res = wrapAsHidlRequest(requests[i], /*out*/&captureRequests_3_4[i].v3_2,
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003843 /*out*/&handlesCreated, /*out*/&inflightBuffers);
Emilian Peevaebbe412018-01-15 13:53:24 +00003844 } else {
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003845 res = wrapAsHidlRequest(requests[i], /*out*/&captureRequests[i],
3846 /*out*/&handlesCreated, /*out*/&inflightBuffers);
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003847 }
3848 if (res != OK) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003849 mBufferRecords.popInflightBuffers(inflightBuffers);
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003850 cleanupNativeHandles(&handlesCreated);
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003851 return res;
Emilian Peevaebbe412018-01-15 13:53:24 +00003852 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003853 }
3854
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003855 std::vector<device::V3_2::BufferCache> cachesToRemove;
3856 {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003857 std::lock_guard<std::mutex> lock(mFreedBuffersLock);
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003858 for (auto& pair : mFreedBuffers) {
3859 // The stream might have been removed since onBufferFreed
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003860 if (mBufferRecords.isStreamCached(pair.first)) {
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003861 cachesToRemove.push_back({pair.first, pair.second});
3862 }
3863 }
3864 mFreedBuffers.clear();
3865 }
3866
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003867 common::V1_0::Status status = common::V1_0::Status::INTERNAL_ERROR;
3868 *numRequestProcessed = 0;
Yifan Hongf79b5542017-04-11 14:44:25 -07003869
3870 // Write metadata to FMQ.
3871 for (size_t i = 0; i < batchSize; i++) {
Emilian Peevf4816702020-04-03 15:44:51 -07003872 camera_capture_request_t* request = requests[i];
Emilian Peevaebbe412018-01-15 13:53:24 +00003873 device::V3_2::CaptureRequest* captureRequest;
Shuzhen Wang83bff122020-11-20 15:51:39 -08003874 if (hidlSession_3_7 != nullptr) {
3875 captureRequest = &captureRequests_3_7[i].v3_4.v3_2;
3876 } else if (hidlSession_3_4 != nullptr) {
Emilian Peevaebbe412018-01-15 13:53:24 +00003877 captureRequest = &captureRequests_3_4[i].v3_2;
3878 } else {
3879 captureRequest = &captureRequests[i];
3880 }
Yifan Hongf79b5542017-04-11 14:44:25 -07003881
3882 if (request->settings != nullptr) {
3883 size_t settingsSize = get_camera_metadata_size(request->settings);
3884 if (mRequestMetadataQueue != nullptr && mRequestMetadataQueue->write(
3885 reinterpret_cast<const uint8_t*>(request->settings), settingsSize)) {
3886 captureRequest->settings.resize(0);
3887 captureRequest->fmqSettingsSize = settingsSize;
3888 } else {
3889 if (mRequestMetadataQueue != nullptr) {
3890 ALOGW("%s: couldn't utilize fmq, fallback to hwbinder", __FUNCTION__);
3891 }
3892 captureRequest->settings.setToExternal(
3893 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(request->settings)),
3894 get_camera_metadata_size(request->settings));
3895 captureRequest->fmqSettingsSize = 0u;
3896 }
3897 } else {
3898 // A null request settings maps to a size-0 CameraMetadata
3899 captureRequest->settings.resize(0);
3900 captureRequest->fmqSettingsSize = 0u;
3901 }
Emilian Peevaebbe412018-01-15 13:53:24 +00003902
Shuzhen Wang83bff122020-11-20 15:51:39 -08003903 // hidl session 3.7 specific handling.
3904 if (hidlSession_3_7 != nullptr) {
3905 captureRequests_3_7[i].inputWidth = request->input_width;
3906 captureRequests_3_7[i].inputHeight = request->input_height;
3907 }
3908
3909 // hidl session 3.7 and 3.4 specific handling.
3910 if (hidlSession_3_7 != nullptr || hidlSession_3_4 != nullptr) {
3911 hardware::hidl_vec<device::V3_4::PhysicalCameraSetting>& physicalCameraSettings =
3912 (hidlSession_3_7 != nullptr) ?
3913 captureRequests_3_7[i].v3_4.physicalCameraSettings :
3914 captureRequests_3_4[i].physicalCameraSettings;
3915 physicalCameraSettings.resize(request->num_physcam_settings);
Emilian Peevaebbe412018-01-15 13:53:24 +00003916 for (size_t j = 0; j < request->num_physcam_settings; j++) {
Emilian Peev00420d22018-02-05 21:33:13 +00003917 if (request->physcam_settings != nullptr) {
3918 size_t settingsSize = get_camera_metadata_size(request->physcam_settings[j]);
3919 if (mRequestMetadataQueue != nullptr && mRequestMetadataQueue->write(
3920 reinterpret_cast<const uint8_t*>(request->physcam_settings[j]),
3921 settingsSize)) {
Shuzhen Wang83bff122020-11-20 15:51:39 -08003922 physicalCameraSettings[j].settings.resize(0);
3923 physicalCameraSettings[j].fmqSettingsSize = settingsSize;
Emilian Peev00420d22018-02-05 21:33:13 +00003924 } else {
3925 if (mRequestMetadataQueue != nullptr) {
3926 ALOGW("%s: couldn't utilize fmq, fallback to hwbinder", __FUNCTION__);
3927 }
Shuzhen Wang83bff122020-11-20 15:51:39 -08003928 physicalCameraSettings[j].settings.setToExternal(
Emilian Peev00420d22018-02-05 21:33:13 +00003929 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(
3930 request->physcam_settings[j])),
3931 get_camera_metadata_size(request->physcam_settings[j]));
Shuzhen Wang83bff122020-11-20 15:51:39 -08003932 physicalCameraSettings[j].fmqSettingsSize = 0u;
Emilian Peevaebbe412018-01-15 13:53:24 +00003933 }
Emilian Peev00420d22018-02-05 21:33:13 +00003934 } else {
Yin-Chia Yeha2849702021-03-10 10:11:33 -08003935 physicalCameraSettings[j].fmqSettingsSize = 0u;
3936 physicalCameraSettings[j].settings.resize(0);
Emilian Peevaebbe412018-01-15 13:53:24 +00003937 }
Shuzhen Wang83bff122020-11-20 15:51:39 -08003938 physicalCameraSettings[j].physicalCameraId = request->physcam_id[j];
Emilian Peevaebbe412018-01-15 13:53:24 +00003939 }
3940 }
Yifan Hongf79b5542017-04-11 14:44:25 -07003941 }
Emilian Peevaebbe412018-01-15 13:53:24 +00003942
3943 hardware::details::return_status err;
Jayant Chowdharyc8d581e2018-07-16 14:46:23 -07003944 auto resultCallback =
3945 [&status, &numRequestProcessed] (auto s, uint32_t n) {
3946 status = s;
3947 *numRequestProcessed = n;
3948 };
Shuzhen Wang83bff122020-11-20 15:51:39 -08003949 if (hidlSession_3_7 != nullptr) {
3950 err = hidlSession_3_7->processCaptureRequest_3_7(captureRequests_3_7, cachesToRemove,
3951 resultCallback);
3952 } else if (hidlSession_3_4 != nullptr) {
Emilian Peevaebbe412018-01-15 13:53:24 +00003953 err = hidlSession_3_4->processCaptureRequest_3_4(captureRequests_3_4, cachesToRemove,
Jayant Chowdharyc8d581e2018-07-16 14:46:23 -07003954 resultCallback);
Emilian Peevaebbe412018-01-15 13:53:24 +00003955 } else {
3956 err = mHidlSession->processCaptureRequest(captureRequests, cachesToRemove,
Jayant Chowdharyc8d581e2018-07-16 14:46:23 -07003957 resultCallback);
Emilian Peevaebbe412018-01-15 13:53:24 +00003958 }
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -07003959 if (!err.isOk()) {
3960 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003961 status = common::V1_0::Status::CAMERA_DISCONNECTED;
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -07003962 }
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003963
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003964 if (status == common::V1_0::Status::OK && *numRequestProcessed != batchSize) {
3965 ALOGE("%s: processCaptureRequest returns OK but processed %d/%zu requests",
3966 __FUNCTION__, *numRequestProcessed, batchSize);
3967 status = common::V1_0::Status::INTERNAL_ERROR;
3968 }
3969
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003970 res = CameraProviderManager::mapToStatusT(status);
3971 if (res == OK) {
3972 if (mHidlSession->isRemote()) {
3973 // Only close acquire fence FDs when the HIDL transaction succeeds (so the FDs have been
3974 // sent to camera HAL processes)
3975 cleanupNativeHandles(&handlesCreated, /*closeFd*/true);
3976 } else {
3977 // In passthrough mode the FDs are now owned by HAL
3978 cleanupNativeHandles(&handlesCreated);
3979 }
3980 } else {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003981 mBufferRecords.popInflightBuffers(inflightBuffers);
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003982 cleanupNativeHandles(&handlesCreated);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003983 }
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003984 return res;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003985}
3986
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003987status_t Camera3Device::HalInterface::flush() {
3988 ATRACE_NAME("CameraHal::flush");
3989 if (!valid()) return INVALID_OPERATION;
3990 status_t res = OK;
3991
Emilian Peev31abd0a2017-05-11 18:37:46 +01003992 auto err = mHidlSession->flush();
3993 if (!err.isOk()) {
3994 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3995 res = DEAD_OBJECT;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003996 } else {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003997 res = CameraProviderManager::mapToStatusT(err);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003998 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003999
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004000 return res;
4001}
4002
Emilian Peev31abd0a2017-05-11 18:37:46 +01004003status_t Camera3Device::HalInterface::dump(int /*fd*/) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004004 ATRACE_NAME("CameraHal::dump");
4005 if (!valid()) return INVALID_OPERATION;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004006
Emilian Peev31abd0a2017-05-11 18:37:46 +01004007 // Handled by CameraProviderManager::dump
4008
4009 return OK;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004010}
4011
4012status_t Camera3Device::HalInterface::close() {
4013 ATRACE_NAME("CameraHal::close()");
4014 if (!valid()) return INVALID_OPERATION;
4015 status_t res = OK;
4016
Emilian Peev31abd0a2017-05-11 18:37:46 +01004017 auto err = mHidlSession->close();
4018 // Interface will be dead shortly anyway, so don't log errors
4019 if (!err.isOk()) {
4020 res = DEAD_OBJECT;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004021 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01004022
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004023 return res;
4024}
4025
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004026void Camera3Device::HalInterface::signalPipelineDrain(const std::vector<int>& streamIds) {
4027 ATRACE_NAME("CameraHal::signalPipelineDrain");
4028 if (!valid() || mHidlSession_3_5 == nullptr) {
4029 ALOGE("%s called on invalid camera!", __FUNCTION__);
4030 return;
4031 }
4032
Yin-Chia Yehc300a072019-02-13 14:56:57 -08004033 auto err = mHidlSession_3_5->signalStreamFlush(streamIds, mNextStreamConfigCounter - 1);
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004034 if (!err.isOk()) {
4035 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
4036 return;
4037 }
4038}
4039
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004040status_t Camera3Device::HalInterface::switchToOffline(
4041 const std::vector<int32_t>& streamsToKeep,
4042 /*out*/hardware::camera::device::V3_6::CameraOfflineSessionInfo* offlineSessionInfo,
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004043 /*out*/sp<hardware::camera::device::V3_6::ICameraOfflineSession>* offlineSession,
4044 /*out*/camera3::BufferRecords* bufferRecords) {
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004045 ATRACE_NAME("CameraHal::switchToOffline");
4046 if (!valid() || mHidlSession_3_6 == nullptr) {
4047 ALOGE("%s called on invalid camera!", __FUNCTION__);
4048 return INVALID_OPERATION;
4049 }
4050
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004051 if (offlineSessionInfo == nullptr || offlineSession == nullptr || bufferRecords == nullptr) {
4052 ALOGE("%s: output arguments must not be null!", __FUNCTION__);
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004053 return INVALID_OPERATION;
4054 }
4055
4056 common::V1_0::Status status = common::V1_0::Status::INTERNAL_ERROR;
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004057 auto resultCallback =
4058 [&status, &offlineSessionInfo, &offlineSession] (auto s, auto info, auto session) {
4059 status = s;
4060 *offlineSessionInfo = info;
4061 *offlineSession = session;
4062 };
4063 auto err = mHidlSession_3_6->switchToOffline(streamsToKeep, resultCallback);
4064
4065 if (!err.isOk()) {
4066 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
4067 return DEAD_OBJECT;
4068 }
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004069
4070 status_t ret = CameraProviderManager::mapToStatusT(status);
4071 if (ret != OK) {
4072 return ret;
4073 }
4074
4075 // TODO: assert no ongoing requestBuffer/returnBuffer call here
4076 // TODO: update RequestBufferStateMachine to block requestBuffer/returnBuffer once HAL
4077 // returns from switchToOffline.
4078
4079
4080 // Validate buffer caches
4081 std::vector<int32_t> streams;
4082 streams.reserve(offlineSessionInfo->offlineStreams.size());
4083 for (auto offlineStream : offlineSessionInfo->offlineStreams) {
4084 int32_t id = offlineStream.id;
4085 streams.push_back(id);
4086 // Verify buffer caches
4087 std::vector<uint64_t> bufIds(offlineStream.circulatingBufferIds.begin(),
4088 offlineStream.circulatingBufferIds.end());
4089 if (!verifyBufferIds(id, bufIds)) {
4090 ALOGE("%s: stream ID %d buffer cache records mismatch!", __FUNCTION__, id);
4091 return UNKNOWN_ERROR;
4092 }
4093 }
4094
4095 // Move buffer records
4096 bufferRecords->takeBufferCaches(mBufferRecords, streams);
4097 bufferRecords->takeInflightBufferMap(mBufferRecords);
4098 bufferRecords->takeRequestedBufferMap(mBufferRecords);
4099 return ret;
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004100}
4101
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07004102void Camera3Device::HalInterface::getInflightBufferKeys(
4103 std::vector<std::pair<int32_t, int32_t>>* out) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004104 mBufferRecords.getInflightBufferKeys(out);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07004105 return;
4106}
4107
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08004108void Camera3Device::HalInterface::getInflightRequestBufferKeys(
4109 std::vector<uint64_t>* out) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004110 mBufferRecords.getInflightRequestBufferKeys(out);
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08004111 return;
4112}
4113
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004114bool Camera3Device::HalInterface::verifyBufferIds(
4115 int32_t streamId, std::vector<uint64_t>& bufIds) {
4116 return mBufferRecords.verifyBufferIds(streamId, bufIds);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004117}
4118
4119status_t Camera3Device::HalInterface::popInflightBuffer(
Yin-Chia Yehf4650602017-01-10 13:13:39 -08004120 int32_t frameNumber, int32_t streamId,
4121 /*out*/ buffer_handle_t **buffer) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004122 return mBufferRecords.popInflightBuffer(frameNumber, streamId, buffer);
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07004123}
4124
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004125status_t Camera3Device::HalInterface::pushInflightRequestBuffer(
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08004126 uint64_t bufferId, buffer_handle_t* buf, int32_t streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004127 return mBufferRecords.pushInflightRequestBuffer(bufferId, buf, streamId);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004128}
4129
4130// Find and pop a buffer_handle_t based on bufferId
4131status_t Camera3Device::HalInterface::popInflightRequestBuffer(
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08004132 uint64_t bufferId,
4133 /*out*/ buffer_handle_t** buffer,
4134 /*optional out*/ int32_t* streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004135 return mBufferRecords.popInflightRequestBuffer(bufferId, buffer, streamId);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004136}
4137
Yin-Chia Yeh77327052017-01-09 18:23:07 -08004138std::pair<bool, uint64_t> Camera3Device::HalInterface::getBufferId(
4139 const buffer_handle_t& buf, int streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004140 return mBufferRecords.getBufferId(buf, streamId);
Yin-Chia Yeh77327052017-01-09 18:23:07 -08004141}
4142
Shuzhen Wangcd5b1822021-09-07 11:52:48 -07004143uint64_t Camera3Device::HalInterface::removeOneBufferCache(int streamId,
4144 const native_handle_t* handle) {
4145 return mBufferRecords.removeOneBufferCache(streamId, handle);
4146}
4147
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07004148void Camera3Device::HalInterface::onBufferFreed(
4149 int streamId, const native_handle_t* handle) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004150 uint32_t bufferId = mBufferRecords.removeOneBufferCache(streamId, handle);
4151 std::lock_guard<std::mutex> lock(mFreedBuffersLock);
4152 if (bufferId != BUFFER_ID_NO_BUFFER) {
4153 mFreedBuffers.push_back(std::make_pair(streamId, bufferId));
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07004154 }
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07004155}
4156
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07004157void Camera3Device::HalInterface::onStreamReConfigured(int streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004158 std::vector<uint64_t> bufIds = mBufferRecords.clearBufferCaches(streamId);
4159 std::lock_guard<std::mutex> lock(mFreedBuffersLock);
4160 for (auto bufferId : bufIds) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07004161 mFreedBuffers.push_back(std::make_pair(streamId, bufferId));
4162 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07004163}
4164
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004165/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004166 * RequestThread inner class methods
4167 */
4168
4169Camera3Device::RequestThread::RequestThread(wp<Camera3Device> parent,
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004170 sp<StatusTracker> statusTracker,
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004171 sp<HalInterface> interface, const Vector<int32_t>& sessionParamKeys,
Eino-Ville Talvala1646c3c2021-07-29 13:48:40 -07004172 bool useHalBufManager,
4173 bool supportCameraMute) :
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004174 Thread(/*canCallJava*/false),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004175 mParent(parent),
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004176 mStatusTracker(statusTracker),
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004177 mInterface(interface),
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07004178 mListener(nullptr),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004179 mId(getId(parent)),
Shuzhen Wang316781a2020-08-18 18:11:01 -07004180 mFirstRepeating(false),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004181 mReconfigured(false),
4182 mDoPause(false),
4183 mPaused(true),
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004184 mNotifyPipelineDrain(false),
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004185 mFrameNumber(0),
Jianing Weicb0652e2014-03-12 18:29:36 -07004186 mLatestRequestId(NAME_NOT_FOUND),
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07004187 mCurrentAfTriggerId(0),
4188 mCurrentPreCaptureTriggerId(0),
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004189 mRotateAndCropOverride(ANDROID_SCALER_ROTATE_AND_CROP_NONE),
Emilian Peeve23f1d92021-09-20 14:56:01 -07004190 mComposerOutput(false),
Eino-Ville Talvala11afe4f2021-05-27 14:45:31 -07004191 mCameraMute(ANDROID_SENSOR_TEST_PATTERN_MODE_OFF),
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004192 mCameraMuteChanged(false),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004193 mRepeatingLastFrameNumber(
4194 hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES),
Shuzhen Wang686f6442017-06-20 16:16:04 -07004195 mPrepareVideoStream(false),
Emilian Peeva14b4dd2018-05-15 11:00:31 +01004196 mConstrainedMode(false),
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004197 mRequestLatency(kRequestLatencyBinSize),
4198 mSessionParamKeys(sessionParamKeys),
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004199 mLatestSessionParams(sessionParamKeys.size()),
Eino-Ville Talvala1646c3c2021-07-29 13:48:40 -07004200 mUseHalBufManager(useHalBufManager),
4201 mSupportCameraMute(supportCameraMute){
Yin-Chia Yeh87b3ec02019-06-03 10:44:39 -07004202 mStatusId = statusTracker->addComponent("RequestThread");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004203}
4204
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004205Camera3Device::RequestThread::~RequestThread() {}
4206
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004207void Camera3Device::RequestThread::setNotificationListener(
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004208 wp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004209 ATRACE_CALL();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004210 Mutex::Autolock l(mRequestLock);
4211 mListener = listener;
4212}
4213
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004214void Camera3Device::RequestThread::configurationComplete(bool isConstrainedHighSpeed,
Shuzhen Wang99080502021-03-07 21:08:20 -08004215 const CameraMetadata& sessionParams,
4216 const std::map<int32_t, std::set<String8>>& groupIdPhysicalCameraMap) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004217 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004218 Mutex::Autolock l(mRequestLock);
4219 mReconfigured = true;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004220 mLatestSessionParams = sessionParams;
Shuzhen Wang99080502021-03-07 21:08:20 -08004221 mGroupIdPhysicalCameraMap = groupIdPhysicalCameraMap;
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07004222 // Prepare video stream for high speed recording.
4223 mPrepareVideoStream = isConstrainedHighSpeed;
Emilian Peeva14b4dd2018-05-15 11:00:31 +01004224 mConstrainedMode = isConstrainedHighSpeed;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004225}
4226
Jianing Wei90e59c92014-03-12 18:29:36 -07004227status_t Camera3Device::RequestThread::queueRequestList(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004228 List<sp<CaptureRequest> > &requests,
4229 /*out*/
4230 int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004231 ATRACE_CALL();
Jianing Wei90e59c92014-03-12 18:29:36 -07004232 Mutex::Autolock l(mRequestLock);
4233 for (List<sp<CaptureRequest> >::iterator it = requests.begin(); it != requests.end();
4234 ++it) {
4235 mRequestQueue.push_back(*it);
4236 }
4237
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004238 if (lastFrameNumber != NULL) {
4239 *lastFrameNumber = mFrameNumber + mRequestQueue.size() - 1;
4240 ALOGV("%s: requestId %d, mFrameNumber %" PRId32 ", lastFrameNumber %" PRId64 ".",
4241 __FUNCTION__, (*(requests.begin()))->mResultExtras.requestId, mFrameNumber,
4242 *lastFrameNumber);
4243 }
Jianing Weicb0652e2014-03-12 18:29:36 -07004244
Jianing Wei90e59c92014-03-12 18:29:36 -07004245 unpauseForNewRequests();
4246
4247 return OK;
4248}
4249
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004250
4251status_t Camera3Device::RequestThread::queueTrigger(
4252 RequestTrigger trigger[],
4253 size_t count) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004254 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004255 Mutex::Autolock l(mTriggerMutex);
4256 status_t ret;
4257
4258 for (size_t i = 0; i < count; ++i) {
4259 ret = queueTriggerLocked(trigger[i]);
4260
4261 if (ret != OK) {
4262 return ret;
4263 }
4264 }
4265
4266 return OK;
4267}
4268
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004269const String8& Camera3Device::RequestThread::getId(const wp<Camera3Device> &device) {
4270 static String8 deadId("<DeadDevice>");
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004271 sp<Camera3Device> d = device.promote();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004272 if (d != nullptr) return d->mId;
4273 return deadId;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004274}
4275
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004276status_t Camera3Device::RequestThread::queueTriggerLocked(
4277 RequestTrigger trigger) {
4278
4279 uint32_t tag = trigger.metadataTag;
4280 ssize_t index = mTriggerMap.indexOfKey(tag);
4281
4282 switch (trigger.getTagType()) {
4283 case TYPE_BYTE:
4284 // fall-through
4285 case TYPE_INT32:
4286 break;
4287 default:
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004288 ALOGE("%s: Type not supported: 0x%x", __FUNCTION__,
4289 trigger.getTagType());
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004290 return INVALID_OPERATION;
4291 }
4292
4293 /**
4294 * Collect only the latest trigger, since we only have 1 field
4295 * in the request settings per trigger tag, and can't send more than 1
4296 * trigger per request.
4297 */
4298 if (index != NAME_NOT_FOUND) {
4299 mTriggerMap.editValueAt(index) = trigger;
4300 } else {
4301 mTriggerMap.add(tag, trigger);
4302 }
4303
4304 return OK;
4305}
4306
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004307status_t Camera3Device::RequestThread::setRepeatingRequests(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004308 const RequestList &requests,
4309 /*out*/
4310 int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004311 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004312 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004313 if (lastFrameNumber != NULL) {
4314 *lastFrameNumber = mRepeatingLastFrameNumber;
4315 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004316 mRepeatingRequests.clear();
Shuzhen Wang316781a2020-08-18 18:11:01 -07004317 mFirstRepeating = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004318 mRepeatingRequests.insert(mRepeatingRequests.begin(),
4319 requests.begin(), requests.end());
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004320
4321 unpauseForNewRequests();
4322
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004323 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004324 return OK;
4325}
4326
Chih-Hung Hsieh8b0b9712016-08-09 14:25:53 -07004327bool Camera3Device::RequestThread::isRepeatingRequestLocked(const sp<CaptureRequest>& requestIn) {
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07004328 if (mRepeatingRequests.empty()) {
4329 return false;
4330 }
4331 int32_t requestId = requestIn->mResultExtras.requestId;
4332 const RequestList &repeatRequests = mRepeatingRequests;
4333 // All repeating requests are guaranteed to have same id so only check first quest
4334 const sp<CaptureRequest> firstRequest = *repeatRequests.begin();
4335 return (firstRequest->mResultExtras.requestId == requestId);
4336}
4337
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004338status_t Camera3Device::RequestThread::clearRepeatingRequests(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004339 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004340 Mutex::Autolock l(mRequestLock);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004341 return clearRepeatingRequestsLocked(lastFrameNumber);
4342
4343}
4344
4345status_t Camera3Device::RequestThread::clearRepeatingRequestsLocked(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004346 mRepeatingRequests.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004347 if (lastFrameNumber != NULL) {
4348 *lastFrameNumber = mRepeatingLastFrameNumber;
4349 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004350 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004351 return OK;
4352}
4353
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004354status_t Camera3Device::RequestThread::clear(
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004355 /*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004356 ATRACE_CALL();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004357 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004358 ALOGV("RequestThread::%s:", __FUNCTION__);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004359
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004360 mRepeatingRequests.clear();
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07004361
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004362 // Send errors for all requests pending in the request queue, including
4363 // pending repeating requests
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004364 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004365 if (listener != NULL) {
4366 for (RequestList::iterator it = mRequestQueue.begin();
4367 it != mRequestQueue.end(); ++it) {
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004368 // Abort the input buffers for reprocess requests.
4369 if ((*it)->mInputStream != NULL) {
Emilian Peevf4816702020-04-03 15:44:51 -07004370 camera_stream_buffer_t inputBuffer;
Shuzhen Wang83bff122020-11-20 15:51:39 -08004371 camera3::Size inputBufferSize;
Eino-Ville Talvalaba435252017-06-21 16:07:25 -07004372 status_t res = (*it)->mInputStream->getInputBuffer(&inputBuffer,
Shuzhen Wang83bff122020-11-20 15:51:39 -08004373 &inputBufferSize, /*respectHalLimit*/ false);
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004374 if (res != OK) {
4375 ALOGW("%s: %d: couldn't get input buffer while clearing the request "
4376 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
4377 } else {
Emilian Peevf4816702020-04-03 15:44:51 -07004378 inputBuffer.status = CAMERA_BUFFER_STATUS_ERROR;
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004379 res = (*it)->mInputStream->returnInputBuffer(inputBuffer);
4380 if (res != OK) {
4381 ALOGE("%s: %d: couldn't return input buffer while clearing the request "
4382 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
4383 }
4384 }
4385 }
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004386 // Set the frame number this request would have had, if it
4387 // had been submitted; this frame number will not be reused.
4388 // The requestId and burstId fields were set when the request was
4389 // submitted originally (in convertMetadataListToRequestListLocked)
4390 (*it)->mResultExtras.frameNumber = mFrameNumber++;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004391 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004392 (*it)->mResultExtras);
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07004393 }
4394 }
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004395 mRequestQueue.clear();
Jinguang Dongb26e7a02016-11-14 16:04:02 +08004396
4397 Mutex::Autolock al(mTriggerMutex);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004398 mTriggerMap.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004399 if (lastFrameNumber != NULL) {
4400 *lastFrameNumber = mRepeatingLastFrameNumber;
4401 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004402 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Emilian Peev8dae54c2019-12-02 15:17:17 -08004403 mRequestSignal.signal();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004404 return OK;
4405}
4406
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004407status_t Camera3Device::RequestThread::flush() {
4408 ATRACE_CALL();
4409 Mutex::Autolock l(mFlushLock);
4410
Emilian Peev08dd2452017-04-06 16:55:14 +01004411 return mInterface->flush();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004412}
4413
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004414void Camera3Device::RequestThread::setPaused(bool paused) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004415 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004416 Mutex::Autolock l(mPauseLock);
4417 mDoPause = paused;
4418 mDoPauseSignal.signal();
4419}
4420
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004421status_t Camera3Device::RequestThread::waitUntilRequestProcessed(
4422 int32_t requestId, nsecs_t timeout) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004423 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004424 Mutex::Autolock l(mLatestRequestMutex);
4425 status_t res;
4426 while (mLatestRequestId != requestId) {
4427 nsecs_t startTime = systemTime();
4428
4429 res = mLatestRequestSignal.waitRelative(mLatestRequestMutex, timeout);
4430 if (res != OK) return res;
4431
4432 timeout -= (systemTime() - startTime);
4433 }
4434
4435 return OK;
4436}
4437
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004438void Camera3Device::RequestThread::requestExit() {
4439 // Call parent to set up shutdown
4440 Thread::requestExit();
4441 // The exit from any possible waits
4442 mDoPauseSignal.signal();
4443 mRequestSignal.signal();
Shuzhen Wang686f6442017-06-20 16:16:04 -07004444
4445 mRequestLatency.log("ProcessCaptureRequest latency histogram");
4446 mRequestLatency.reset();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004447}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004448
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004449void Camera3Device::RequestThread::checkAndStopRepeatingRequest() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004450 ATRACE_CALL();
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07004451 bool surfaceAbandoned = false;
4452 int64_t lastFrameNumber = 0;
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004453 sp<NotificationListener> listener;
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07004454 {
4455 Mutex::Autolock l(mRequestLock);
4456 // Check all streams needed by repeating requests are still valid. Otherwise, stop
4457 // repeating requests.
4458 for (const auto& request : mRepeatingRequests) {
4459 for (const auto& s : request->mOutputStreams) {
4460 if (s->isAbandoned()) {
4461 surfaceAbandoned = true;
4462 clearRepeatingRequestsLocked(&lastFrameNumber);
4463 break;
4464 }
4465 }
4466 if (surfaceAbandoned) {
4467 break;
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004468 }
4469 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004470 listener = mListener.promote();
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004471 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004472
4473 if (listener != NULL && surfaceAbandoned) {
4474 listener->notifyRepeatingRequestError(lastFrameNumber);
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07004475 }
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004476}
4477
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004478bool Camera3Device::RequestThread::sendRequestsBatch() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004479 ATRACE_CALL();
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004480 status_t res;
4481 size_t batchSize = mNextRequests.size();
Emilian Peevf4816702020-04-03 15:44:51 -07004482 std::vector<camera_capture_request_t*> requests(batchSize);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004483 uint32_t numRequestProcessed = 0;
4484 for (size_t i = 0; i < batchSize; i++) {
4485 requests[i] = &mNextRequests.editItemAt(i).halRequest;
Yin-Chia Yeh885691c2018-05-01 15:54:24 -07004486 ATRACE_ASYNC_BEGIN("frame capture", mNextRequests[i].halRequest.frame_number);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004487 }
4488
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004489 res = mInterface->processBatchCaptureRequests(requests, &numRequestProcessed);
4490
4491 bool triggerRemoveFailed = false;
4492 NextRequest& triggerFailedRequest = mNextRequests.editItemAt(0);
4493 for (size_t i = 0; i < numRequestProcessed; i++) {
4494 NextRequest& nextRequest = mNextRequests.editItemAt(i);
4495 nextRequest.submitted = true;
4496
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004497 updateNextRequest(nextRequest);
Emilian Peevaebbe412018-01-15 13:53:24 +00004498
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004499 if (!triggerRemoveFailed) {
4500 // Remove any previously queued triggers (after unlock)
4501 status_t removeTriggerRes = removeTriggers(mPrevRequest);
4502 if (removeTriggerRes != OK) {
4503 triggerRemoveFailed = true;
4504 triggerFailedRequest = nextRequest;
4505 }
4506 }
4507 }
4508
4509 if (triggerRemoveFailed) {
4510 SET_ERR("RequestThread: Unable to remove triggers "
4511 "(capture request %d, HAL device: %s (%d)",
4512 triggerFailedRequest.halRequest.frame_number, strerror(-res), res);
4513 cleanUpFailedRequests(/*sendRequestError*/ false);
4514 return false;
4515 }
4516
4517 if (res != OK) {
4518 // Should only get a failure here for malformed requests or device-level
4519 // errors, so consider all errors fatal. Bad metadata failures should
4520 // come through notify.
4521 SET_ERR("RequestThread: Unable to submit capture request %d to HAL device: %s (%d)",
4522 mNextRequests[numRequestProcessed].halRequest.frame_number,
4523 strerror(-res), res);
4524 cleanUpFailedRequests(/*sendRequestError*/ false);
4525 return false;
4526 }
4527 return true;
4528}
4529
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07004530nsecs_t Camera3Device::RequestThread::calculateMaxExpectedDuration(const camera_metadata_t *request) {
4531 nsecs_t maxExpectedDuration = kDefaultExpectedDuration;
4532 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
4533 find_camera_metadata_ro_entry(request,
4534 ANDROID_CONTROL_AE_MODE,
4535 &e);
4536 if (e.count == 0) return maxExpectedDuration;
4537
4538 switch (e.data.u8[0]) {
4539 case ANDROID_CONTROL_AE_MODE_OFF:
4540 find_camera_metadata_ro_entry(request,
4541 ANDROID_SENSOR_EXPOSURE_TIME,
4542 &e);
4543 if (e.count > 0) {
4544 maxExpectedDuration = e.data.i64[0];
4545 }
4546 find_camera_metadata_ro_entry(request,
4547 ANDROID_SENSOR_FRAME_DURATION,
4548 &e);
4549 if (e.count > 0) {
4550 maxExpectedDuration = std::max(e.data.i64[0], maxExpectedDuration);
4551 }
4552 break;
4553 default:
4554 find_camera_metadata_ro_entry(request,
4555 ANDROID_CONTROL_AE_TARGET_FPS_RANGE,
4556 &e);
4557 if (e.count > 1) {
4558 maxExpectedDuration = 1e9 / e.data.u8[0];
4559 }
4560 break;
4561 }
4562
4563 return maxExpectedDuration;
4564}
4565
Emilian Peeva14b4dd2018-05-15 11:00:31 +01004566bool Camera3Device::RequestThread::skipHFRTargetFPSUpdate(int32_t tag,
4567 const camera_metadata_ro_entry_t& newEntry, const camera_metadata_entry_t& currentEntry) {
4568 if (mConstrainedMode && (ANDROID_CONTROL_AE_TARGET_FPS_RANGE == tag) &&
4569 (newEntry.count == currentEntry.count) && (currentEntry.count == 2) &&
4570 (currentEntry.data.i32[1] == newEntry.data.i32[1])) {
4571 return true;
4572 }
4573
4574 return false;
4575}
4576
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004577void Camera3Device::RequestThread::updateNextRequest(NextRequest& nextRequest) {
4578 // Update the latest request sent to HAL
Shuzhen Wang83bff122020-11-20 15:51:39 -08004579 camera_capture_request_t& halRequest = nextRequest.halRequest;
4580 if (halRequest.settings != NULL) { // Don't update if they were unchanged
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004581 Mutex::Autolock al(mLatestRequestMutex);
4582
Shuzhen Wang83bff122020-11-20 15:51:39 -08004583 camera_metadata_t* cloned = clone_camera_metadata(halRequest.settings);
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004584 mLatestRequest.acquire(cloned);
4585
4586 mLatestPhysicalRequest.clear();
Shuzhen Wang83bff122020-11-20 15:51:39 -08004587 for (uint32_t i = 0; i < halRequest.num_physcam_settings; i++) {
4588 cloned = clone_camera_metadata(halRequest.physcam_settings[i]);
4589 mLatestPhysicalRequest.emplace(halRequest.physcam_id[i],
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004590 CameraMetadata(cloned));
4591 }
4592
4593 sp<Camera3Device> parent = mParent.promote();
4594 if (parent != NULL) {
4595 parent->monitorMetadata(TagMonitor::REQUEST,
Shuzhen Wang83bff122020-11-20 15:51:39 -08004596 halRequest.frame_number,
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004597 0, mLatestRequest, mLatestPhysicalRequest);
4598 }
4599 }
4600
Shuzhen Wang83bff122020-11-20 15:51:39 -08004601 if (halRequest.settings != NULL) {
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004602 nextRequest.captureRequest->mSettingsList.begin()->metadata.unlock(
Shuzhen Wang83bff122020-11-20 15:51:39 -08004603 halRequest.settings);
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004604 }
4605
Shuzhen Wang83bff122020-11-20 15:51:39 -08004606 cleanupPhysicalSettings(nextRequest.captureRequest, &halRequest);
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004607}
4608
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004609bool Camera3Device::RequestThread::updateSessionParameters(const CameraMetadata& settings) {
4610 ATRACE_CALL();
4611 bool updatesDetected = false;
4612
Emilian Peev4ec17882019-01-24 17:16:58 -08004613 CameraMetadata updatedParams(mLatestSessionParams);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004614 for (auto tag : mSessionParamKeys) {
4615 camera_metadata_ro_entry entry = settings.find(tag);
Emilian Peev4ec17882019-01-24 17:16:58 -08004616 camera_metadata_entry lastEntry = updatedParams.find(tag);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004617
4618 if (entry.count > 0) {
4619 bool isDifferent = false;
4620 if (lastEntry.count > 0) {
4621 // Have a last value, compare to see if changed
4622 if (lastEntry.type == entry.type &&
4623 lastEntry.count == entry.count) {
4624 // Same type and count, compare values
4625 size_t bytesPerValue = camera_metadata_type_size[lastEntry.type];
4626 size_t entryBytes = bytesPerValue * lastEntry.count;
4627 int cmp = memcmp(entry.data.u8, lastEntry.data.u8, entryBytes);
4628 if (cmp != 0) {
4629 isDifferent = true;
4630 }
4631 } else {
4632 // Count or type has changed
4633 isDifferent = true;
4634 }
4635 } else {
4636 // No last entry, so always consider to be different
4637 isDifferent = true;
4638 }
4639
4640 if (isDifferent) {
4641 ALOGV("%s: Session parameter tag id %d changed", __FUNCTION__, tag);
Emilian Peeva14b4dd2018-05-15 11:00:31 +01004642 if (!skipHFRTargetFPSUpdate(tag, entry, lastEntry)) {
4643 updatesDetected = true;
4644 }
Emilian Peev4ec17882019-01-24 17:16:58 -08004645 updatedParams.update(entry);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004646 }
4647 } else if (lastEntry.count > 0) {
4648 // Value has been removed
4649 ALOGV("%s: Session parameter tag id %d removed", __FUNCTION__, tag);
Emilian Peev4ec17882019-01-24 17:16:58 -08004650 updatedParams.erase(tag);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004651 updatesDetected = true;
4652 }
4653 }
4654
Emilian Peev4ec17882019-01-24 17:16:58 -08004655 bool reconfigureRequired;
4656 if (updatesDetected) {
4657 reconfigureRequired = mInterface->isReconfigurationRequired(mLatestSessionParams,
4658 updatedParams);
4659 mLatestSessionParams = updatedParams;
4660 } else {
4661 reconfigureRequired = false;
4662 }
4663
4664 return reconfigureRequired;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004665}
4666
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004667bool Camera3Device::RequestThread::threadLoop() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004668 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004669 status_t res;
Jayant Chowdhary37eca242019-11-18 08:55:56 -08004670 // Any function called from threadLoop() must not hold mInterfaceLock since
4671 // it could lead to deadlocks (disconnect() -> hold mInterfaceMutex -> wait for request thread
4672 // to finish -> request thread waits on mInterfaceMutex) http://b/143513518
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004673
4674 // Handle paused state.
4675 if (waitIfPaused()) {
4676 return true;
4677 }
4678
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004679 // Wait for the next batch of requests.
4680 waitForNextRequestBatch();
4681 if (mNextRequests.size() == 0) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004682 return true;
4683 }
4684
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004685 // Get the latest request ID, if any
4686 int latestRequestId;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004687 camera_metadata_entry_t requestIdEntry = mNextRequests[mNextRequests.size() - 1].
Emilian Peevaebbe412018-01-15 13:53:24 +00004688 captureRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_ID);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004689 if (requestIdEntry.count > 0) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004690 latestRequestId = requestIdEntry.data.i32[0];
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004691 } else {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004692 ALOGW("%s: Did not have android.request.id set in the request.", __FUNCTION__);
4693 latestRequestId = NAME_NOT_FOUND;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004694 }
4695
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004696 // 'mNextRequests' will at this point contain either a set of HFR batched requests
4697 // or a single request from streaming or burst. In either case the first element
4698 // should contain the latest camera settings that we need to check for any session
4699 // parameter updates.
Emilian Peevaebbe412018-01-15 13:53:24 +00004700 if (updateSessionParameters(mNextRequests[0].captureRequest->mSettingsList.begin()->metadata)) {
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004701 res = OK;
4702
4703 //Input stream buffers are already acquired at this point so an input stream
4704 //will not be able to move to idle state unless we force it.
4705 if (mNextRequests[0].captureRequest->mInputStream != nullptr) {
4706 res = mNextRequests[0].captureRequest->mInputStream->forceToIdle();
4707 if (res != OK) {
4708 ALOGE("%s: Failed to force idle input stream: %d", __FUNCTION__, res);
4709 cleanUpFailedRequests(/*sendRequestError*/ false);
4710 return false;
4711 }
4712 }
4713
4714 if (res == OK) {
Emilian Peev3bead5f2020-05-28 17:29:08 -07004715 sp<Camera3Device> parent = mParent.promote();
4716 if (parent != nullptr) {
4717 mReconfigured |= parent->reconfigureCamera(mLatestSessionParams, mStatusId);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004718 }
Emilian Peev3bead5f2020-05-28 17:29:08 -07004719 setPaused(false);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004720
4721 if (mNextRequests[0].captureRequest->mInputStream != nullptr) {
4722 mNextRequests[0].captureRequest->mInputStream->restoreConfiguredState();
4723 if (res != OK) {
4724 ALOGE("%s: Failed to restore configured input stream: %d", __FUNCTION__, res);
4725 cleanUpFailedRequests(/*sendRequestError*/ false);
4726 return false;
4727 }
4728 }
4729 }
4730 }
4731
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004732 // Prepare a batch of HAL requests and output buffers.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004733 res = prepareHalRequests();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004734 if (res == TIMED_OUT) {
4735 // Not a fatal error if getting output buffers time out.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004736 cleanUpFailedRequests(/*sendRequestError*/ true);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004737 // Check if any stream is abandoned.
4738 checkAndStopRepeatingRequest();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004739 return true;
4740 } else if (res != OK) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004741 cleanUpFailedRequests(/*sendRequestError*/ false);
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004742 return false;
4743 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004744
Zhijun Hecc27e112013-10-03 16:12:43 -07004745 // Inform waitUntilRequestProcessed thread of a new request ID
4746 {
4747 Mutex::Autolock al(mLatestRequestMutex);
4748
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004749 mLatestRequestId = latestRequestId;
Zhijun Hecc27e112013-10-03 16:12:43 -07004750 mLatestRequestSignal.signal();
4751 }
4752
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004753 // Submit a batch of requests to HAL.
4754 // Use flush lock only when submitting multilple requests in a batch.
4755 // TODO: The problem with flush lock is flush() will be blocked by process_capture_request()
4756 // which may take a long time to finish so synchronizing flush() and
4757 // process_capture_request() defeats the purpose of cancelling requests ASAP with flush().
4758 // For now, only synchronize for high speed recording and we should figure something out for
4759 // removing the synchronization.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004760 bool useFlushLock = mNextRequests.size() > 1;
Eino-Ville Talvala17a61ad2013-06-03 16:53:32 -07004761
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004762 if (useFlushLock) {
4763 mFlushLock.lock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004764 }
4765
Zhijun Hef0645c12016-08-02 00:58:11 -07004766 ALOGVV("%s: %d: submitting %zu requests in a batch.", __FUNCTION__, __LINE__,
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004767 mNextRequests.size());
Igor Murashkin1e479c02013-09-06 16:55:14 -07004768
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08004769 sp<Camera3Device> parent = mParent.promote();
4770 if (parent != nullptr) {
4771 parent->mRequestBufferSM.onSubmittingRequest();
4772 }
4773
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004774 bool submitRequestSuccess = false;
Shuzhen Wang686f6442017-06-20 16:16:04 -07004775 nsecs_t tRequestStart = systemTime(SYSTEM_TIME_MONOTONIC);
Yin-Chia Yeh11648852019-05-16 10:42:54 -07004776 submitRequestSuccess = sendRequestsBatch();
4777
Shuzhen Wang686f6442017-06-20 16:16:04 -07004778 nsecs_t tRequestEnd = systemTime(SYSTEM_TIME_MONOTONIC);
4779 mRequestLatency.add(tRequestStart, tRequestEnd);
Igor Murashkin1e479c02013-09-06 16:55:14 -07004780
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004781 if (useFlushLock) {
4782 mFlushLock.unlock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004783 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004784
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004785 // Unset as current request
4786 {
4787 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004788 mNextRequests.clear();
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004789 }
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004790 mRequestSubmittedSignal.signal();
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004791
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004792 return submitRequestSuccess;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004793}
4794
Jayant Chowdhary65c9bf02021-09-03 16:44:16 +00004795status_t Camera3Device::removeFwkOnlyRegionKeys(CameraMetadata *request) {
4796 static const std::array<uint32_t, 4> kFwkOnlyRegionKeys = {ANDROID_CONTROL_AF_REGIONS_SET,
4797 ANDROID_CONTROL_AE_REGIONS_SET, ANDROID_CONTROL_AWB_REGIONS_SET,
4798 ANDROID_SCALER_CROP_REGION_SET};
4799 if (request == nullptr) {
4800 ALOGE("%s request metadata nullptr", __FUNCTION__);
4801 return BAD_VALUE;
4802 }
4803 status_t res = OK;
4804 for (const auto &key : kFwkOnlyRegionKeys) {
4805 if (request->exists(key)) {
4806 res = request->erase(key);
4807 if (res != OK) {
4808 return res;
4809 }
4810 }
4811 }
4812 return OK;
4813}
4814
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004815status_t Camera3Device::RequestThread::prepareHalRequests() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004816 ATRACE_CALL();
4817
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07004818 bool batchedRequest = mNextRequests[0].captureRequest->mBatchSize > 1;
Shuzhen Wang4a472662017-02-26 23:29:04 -08004819 for (size_t i = 0; i < mNextRequests.size(); i++) {
4820 auto& nextRequest = mNextRequests.editItemAt(i);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004821 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
Emilian Peevf4816702020-04-03 15:44:51 -07004822 camera_capture_request_t* halRequest = &nextRequest.halRequest;
4823 Vector<camera_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004824
4825 // Prepare a request to HAL
4826 halRequest->frame_number = captureRequest->mResultExtras.frameNumber;
4827
4828 // Insert any queued triggers (before metadata is locked)
4829 status_t res = insertTriggers(captureRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004830 if (res < 0) {
4831 SET_ERR("RequestThread: Unable to insert triggers "
4832 "(capture request %d, HAL device: %s (%d)",
4833 halRequest->frame_number, strerror(-res), res);
4834 return INVALID_OPERATION;
4835 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07004836
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004837 int triggerCount = res;
4838 bool triggersMixedIn = (triggerCount > 0 || mPrevTriggers > 0);
4839 mPrevTriggers = triggerCount;
4840
Emilian Peeve23f1d92021-09-20 14:56:01 -07004841 // Do not override rotate&crop for stream configurations that include
4842 // SurfaceViews(HW_COMPOSER) output. The display rotation there will be
4843 // compensated by NATIVE_WINDOW_TRANSFORM_INVERSE_DISPLAY
4844 bool rotateAndCropChanged = mComposerOutput ? false :
4845 overrideAutoRotateAndCrop(captureRequest);
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004846 bool testPatternChanged = overrideTestPattern(captureRequest);
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004847
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004848 // If the request is the same as last, or we had triggers now or last time or
4849 // changing overrides this time
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004850 bool newRequest =
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004851 (mPrevRequest != captureRequest || triggersMixedIn ||
4852 rotateAndCropChanged || testPatternChanged) &&
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07004853 // Request settings are all the same within one batch, so only treat the first
4854 // request in a batch as new
Zhijun He54c36822018-07-18 09:33:39 -07004855 !(batchedRequest && i > 0);
Emilian Peev00420d22018-02-05 21:33:13 +00004856 if (newRequest) {
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08004857 std::set<std::string> cameraIdsWithZoom;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004858 /**
4859 * HAL workaround:
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004860 * Insert a fake trigger ID if a trigger is set but no trigger ID is
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004861 */
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004862 res = addFakeTriggerIds(captureRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004863 if (res != OK) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004864 SET_ERR("RequestThread: Unable to insert fake trigger IDs "
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004865 "(capture request %d, HAL device: %s (%d)",
4866 halRequest->frame_number, strerror(-res), res);
4867 return INVALID_OPERATION;
4868 }
4869
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07004870 {
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07004871 sp<Camera3Device> parent = mParent.promote();
4872 if (parent != nullptr) {
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -07004873 List<PhysicalCameraSettings>::iterator it;
4874 for (it = captureRequest->mSettingsList.begin();
4875 it != captureRequest->mSettingsList.end(); it++) {
Jayant Chowdhary9255ce02021-07-15 11:18:17 -07004876 if (parent->mUHRCropAndMeteringRegionMappers.find(it->cameraId) ==
4877 parent->mUHRCropAndMeteringRegionMappers.end()) {
Jayant Chowdhary65c9bf02021-09-03 16:44:16 +00004878 if (removeFwkOnlyRegionKeys(&(it->metadata)) != OK) {
4879 SET_ERR("RequestThread: Unable to remove fwk-only keys from request"
4880 "%d: %s (%d)", halRequest->frame_number, strerror(-res),
4881 res);
4882 return INVALID_OPERATION;
4883 }
Jayant Chowdhary9255ce02021-07-15 11:18:17 -07004884 continue;
4885 }
4886
4887 if (!captureRequest->mUHRCropAndMeteringRegionsUpdated) {
4888 res = parent->mUHRCropAndMeteringRegionMappers[it->cameraId].
4889 updateCaptureRequest(&(it->metadata));
4890 if (res != OK) {
4891 SET_ERR("RequestThread: Unable to correct capture requests "
4892 "for scaler crop region and metering regions for request "
4893 "%d: %s (%d)", halRequest->frame_number, strerror(-res),
4894 res);
4895 return INVALID_OPERATION;
4896 }
4897 captureRequest->mUHRCropAndMeteringRegionsUpdated = true;
Jayant Chowdhary65c9bf02021-09-03 16:44:16 +00004898 if (removeFwkOnlyRegionKeys(&(it->metadata)) != OK) {
4899 SET_ERR("RequestThread: Unable to remove fwk-only keys from request"
4900 "%d: %s (%d)", halRequest->frame_number, strerror(-res),
4901 res);
4902 return INVALID_OPERATION;
4903 }
Jayant Chowdhary9255ce02021-07-15 11:18:17 -07004904 }
4905 }
4906
4907 // Correct metadata regions for distortion correction if enabled
4908 for (it = captureRequest->mSettingsList.begin();
4909 it != captureRequest->mSettingsList.end(); it++) {
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -07004910 if (parent->mDistortionMappers.find(it->cameraId) ==
4911 parent->mDistortionMappers.end()) {
4912 continue;
4913 }
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07004914
4915 if (!captureRequest->mDistortionCorrectionUpdated) {
4916 res = parent->mDistortionMappers[it->cameraId].correctCaptureRequest(
4917 &(it->metadata));
4918 if (res != OK) {
4919 SET_ERR("RequestThread: Unable to correct capture requests "
4920 "for lens distortion for request %d: %s (%d)",
4921 halRequest->frame_number, strerror(-res), res);
4922 return INVALID_OPERATION;
4923 }
4924 captureRequest->mDistortionCorrectionUpdated = true;
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -07004925 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07004926 }
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08004927
4928 for (it = captureRequest->mSettingsList.begin();
4929 it != captureRequest->mSettingsList.end(); it++) {
4930 if (parent->mZoomRatioMappers.find(it->cameraId) ==
4931 parent->mZoomRatioMappers.end()) {
4932 continue;
4933 }
4934
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07004935 if (!captureRequest->mZoomRatioIs1x) {
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08004936 cameraIdsWithZoom.insert(it->cameraId);
4937 }
4938
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07004939 if (!captureRequest->mZoomRatioUpdated) {
4940 res = parent->mZoomRatioMappers[it->cameraId].updateCaptureRequest(
4941 &(it->metadata));
4942 if (res != OK) {
4943 SET_ERR("RequestThread: Unable to correct capture requests "
4944 "for zoom ratio for request %d: %s (%d)",
4945 halRequest->frame_number, strerror(-res), res);
4946 return INVALID_OPERATION;
4947 }
4948 captureRequest->mZoomRatioUpdated = true;
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08004949 }
4950 }
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07004951 if (captureRequest->mRotateAndCropAuto &&
4952 !captureRequest->mRotationAndCropUpdated) {
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004953 for (it = captureRequest->mSettingsList.begin();
4954 it != captureRequest->mSettingsList.end(); it++) {
4955 auto mapper = parent->mRotateAndCropMappers.find(it->cameraId);
4956 if (mapper != parent->mRotateAndCropMappers.end()) {
4957 res = mapper->second.updateCaptureRequest(&(it->metadata));
4958 if (res != OK) {
4959 SET_ERR("RequestThread: Unable to correct capture requests "
4960 "for rotate-and-crop for request %d: %s (%d)",
4961 halRequest->frame_number, strerror(-res), res);
4962 return INVALID_OPERATION;
4963 }
4964 }
4965 }
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07004966 captureRequest->mRotationAndCropUpdated = true;
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004967 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07004968 }
4969 }
4970
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004971 /**
4972 * The request should be presorted so accesses in HAL
4973 * are O(logn). Sidenote, sorting a sorted metadata is nop.
4974 */
Emilian Peevaebbe412018-01-15 13:53:24 +00004975 captureRequest->mSettingsList.begin()->metadata.sort();
4976 halRequest->settings = captureRequest->mSettingsList.begin()->metadata.getAndLock();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004977 mPrevRequest = captureRequest;
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08004978 mPrevCameraIdsWithZoom = cameraIdsWithZoom;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004979 ALOGVV("%s: Request settings are NEW", __FUNCTION__);
4980
4981 IF_ALOGV() {
4982 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
4983 find_camera_metadata_ro_entry(
4984 halRequest->settings,
4985 ANDROID_CONTROL_AF_TRIGGER,
4986 &e
4987 );
4988 if (e.count > 0) {
4989 ALOGV("%s: Request (frame num %d) had AF trigger 0x%x",
4990 __FUNCTION__,
4991 halRequest->frame_number,
4992 e.data.u8[0]);
4993 }
4994 }
4995 } else {
4996 // leave request.settings NULL to indicate 'reuse latest given'
4997 ALOGVV("%s: Request settings are REUSED",
4998 __FUNCTION__);
4999 }
5000
Emilian Peevaebbe412018-01-15 13:53:24 +00005001 if (captureRequest->mSettingsList.size() > 1) {
5002 halRequest->num_physcam_settings = captureRequest->mSettingsList.size() - 1;
5003 halRequest->physcam_id = new const char* [halRequest->num_physcam_settings];
Emilian Peev00420d22018-02-05 21:33:13 +00005004 if (newRequest) {
5005 halRequest->physcam_settings =
5006 new const camera_metadata* [halRequest->num_physcam_settings];
5007 } else {
5008 halRequest->physcam_settings = nullptr;
5009 }
Emilian Peevaebbe412018-01-15 13:53:24 +00005010 auto it = ++captureRequest->mSettingsList.begin();
5011 size_t i = 0;
5012 for (; it != captureRequest->mSettingsList.end(); it++, i++) {
5013 halRequest->physcam_id[i] = it->cameraId.c_str();
Emilian Peev00420d22018-02-05 21:33:13 +00005014 if (newRequest) {
5015 it->metadata.sort();
5016 halRequest->physcam_settings[i] = it->metadata.getAndLock();
5017 }
Emilian Peevaebbe412018-01-15 13:53:24 +00005018 }
5019 }
5020
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005021 uint32_t totalNumBuffers = 0;
5022
5023 // Fill in buffers
5024 if (captureRequest->mInputStream != NULL) {
5025 halRequest->input_buffer = &captureRequest->mInputBuffer;
Shuzhen Wang83bff122020-11-20 15:51:39 -08005026
5027 halRequest->input_width = captureRequest->mInputBufferSize.width;
5028 halRequest->input_height = captureRequest->mInputBufferSize.height;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005029 totalNumBuffers += 1;
5030 } else {
5031 halRequest->input_buffer = NULL;
5032 }
5033
Emilian Peevf4816702020-04-03 15:44:51 -07005034 outputBuffers->insertAt(camera_stream_buffer_t(), 0,
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005035 captureRequest->mOutputStreams.size());
5036 halRequest->output_buffers = outputBuffers->array();
Shuzhen Wang99080502021-03-07 21:08:20 -08005037 std::set<std::set<String8>> requestedPhysicalCameras;
Yin-Chia Yehb3a80b12018-09-04 12:13:05 -07005038
5039 sp<Camera3Device> parent = mParent.promote();
5040 if (parent == NULL) {
5041 // Should not happen, and nowhere to send errors to, so just log it
5042 CLOGE("RequestThread: Parent is gone");
5043 return INVALID_OPERATION;
5044 }
5045 nsecs_t waitDuration = kBaseGetBufferWait + parent->getExpectedInFlightDuration();
5046
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005047 SurfaceMap uniqueSurfaceIdMap;
Shuzhen Wang4a472662017-02-26 23:29:04 -08005048 for (size_t j = 0; j < captureRequest->mOutputStreams.size(); j++) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005049 sp<Camera3OutputStreamInterface> outputStream =
5050 captureRequest->mOutputStreams.editItemAt(j);
5051 int streamId = outputStream->getId();
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07005052
5053 // Prepare video buffers for high speed recording on the first video request.
5054 if (mPrepareVideoStream && outputStream->isVideoStream()) {
5055 // Only try to prepare video stream on the first video request.
5056 mPrepareVideoStream = false;
5057
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07005058 res = outputStream->startPrepare(Camera3StreamInterface::ALLOCATE_PIPELINE_MAX,
5059 false /*blockRequest*/);
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07005060 while (res == NOT_ENOUGH_DATA) {
5061 res = outputStream->prepareNextBuffer();
5062 }
5063 if (res != OK) {
5064 ALOGW("%s: Preparing video buffers for high speed failed: %s (%d)",
5065 __FUNCTION__, strerror(-res), res);
5066 outputStream->cancelPrepare();
5067 }
5068 }
5069
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005070 std::vector<size_t> uniqueSurfaceIds;
5071 res = outputStream->getUniqueSurfaceIds(
5072 captureRequest->mOutputSurfaces[streamId],
5073 &uniqueSurfaceIds);
5074 // INVALID_OPERATION is normal output for streams not supporting surfaceIds
5075 if (res != OK && res != INVALID_OPERATION) {
5076 ALOGE("%s: failed to query stream %d unique surface IDs",
5077 __FUNCTION__, streamId);
5078 return res;
5079 }
5080 if (res == OK) {
5081 uniqueSurfaceIdMap.insert({streamId, std::move(uniqueSurfaceIds)});
5082 }
5083
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07005084 if (mUseHalBufManager) {
Yin-Chia Yeh110342b2018-11-19 11:47:46 -08005085 if (outputStream->isAbandoned()) {
Yin-Chia Yeha1b56c82019-03-27 15:50:39 -07005086 ALOGV("%s: stream %d is abandoned, skipping request", __FUNCTION__, streamId);
Yin-Chia Yeh110342b2018-11-19 11:47:46 -08005087 return TIMED_OUT;
5088 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07005089 // HAL will request buffer through requestStreamBuffer API
Emilian Peevf4816702020-04-03 15:44:51 -07005090 camera_stream_buffer_t& buffer = outputBuffers->editItemAt(j);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07005091 buffer.stream = outputStream->asHalStream();
5092 buffer.buffer = nullptr;
Emilian Peevf4816702020-04-03 15:44:51 -07005093 buffer.status = CAMERA_BUFFER_STATUS_OK;
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07005094 buffer.acquire_fence = -1;
5095 buffer.release_fence = -1;
Emilian Peevf0348ae2021-01-13 13:39:45 -08005096 // Mark the output stream as unpreparable to block clients from calling
5097 // 'prepare' after this request reaches CameraHal and before the respective
5098 // buffers are requested.
5099 outputStream->markUnpreparable();
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07005100 } else {
5101 res = outputStream->getBuffer(&outputBuffers->editItemAt(j),
5102 waitDuration,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005103 captureRequest->mOutputSurfaces[streamId]);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07005104 if (res != OK) {
5105 // Can't get output buffer from gralloc queue - this could be due to
5106 // abandoned queue or other consumer misbehavior, so not a fatal
5107 // error
Yin-Chia Yeha1b56c82019-03-27 15:50:39 -07005108 ALOGV("RequestThread: Can't get output buffer, skipping request:"
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07005109 " %s (%d)", strerror(-res), res);
5110
5111 return TIMED_OUT;
5112 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005113 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08005114
5115 {
5116 sp<Camera3Device> parent = mParent.promote();
5117 if (parent != nullptr) {
5118 const String8& streamCameraId = outputStream->getPhysicalCameraId();
5119 for (const auto& settings : captureRequest->mSettingsList) {
5120 if ((streamCameraId.isEmpty() &&
5121 parent->getId() == settings.cameraId.c_str()) ||
5122 streamCameraId == settings.cameraId.c_str()) {
5123 outputStream->fireBufferRequestForFrameNumber(
5124 captureRequest->mResultExtras.frameNumber,
5125 settings.metadata);
5126 }
5127 }
5128 }
5129 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07005130
Shuzhen Wang5c22c152017-12-31 17:12:25 -08005131 String8 physicalCameraId = outputStream->getPhysicalCameraId();
Shuzhen Wang99080502021-03-07 21:08:20 -08005132 int32_t streamGroupId = outputStream->getHalStreamGroupId();
5133 if (streamGroupId != -1 && mGroupIdPhysicalCameraMap.count(streamGroupId) == 1) {
5134 requestedPhysicalCameras.insert(mGroupIdPhysicalCameraMap[streamGroupId]);
5135 } else if (!physicalCameraId.isEmpty()) {
5136 requestedPhysicalCameras.insert(std::set<String8>({physicalCameraId}));
Shuzhen Wang5c22c152017-12-31 17:12:25 -08005137 }
5138 halRequest->num_output_buffers++;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005139 }
5140 totalNumBuffers += halRequest->num_output_buffers;
5141
5142 // Log request in the in-flight queue
Shuzhen Wang4a472662017-02-26 23:29:04 -08005143 // If this request list is for constrained high speed recording (not
5144 // preview), and the current request is not the last one in the batch,
5145 // do not send callback to the app.
5146 bool hasCallback = true;
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07005147 if (batchedRequest && i != mNextRequests.size()-1) {
Shuzhen Wang4a472662017-02-26 23:29:04 -08005148 hasCallback = false;
5149 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01005150 bool isStillCapture = false;
Shuzhen Wang26abaf42018-08-28 15:41:20 -07005151 bool isZslCapture = false;
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08005152 const camera_metadata_t* settings = halRequest->settings;
5153 bool shouldUnlockSettings = false;
5154 if (settings == nullptr) {
5155 shouldUnlockSettings = true;
5156 settings = captureRequest->mSettingsList.begin()->metadata.getAndLock();
5157 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01005158 if (!mNextRequests[0].captureRequest->mSettingsList.begin()->metadata.isEmpty()) {
5159 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08005160 find_camera_metadata_ro_entry(settings, ANDROID_CONTROL_CAPTURE_INTENT, &e);
Emilian Peev9dd21f42018-08-03 13:39:29 +01005161 if ((e.count > 0) && (e.data.u8[0] == ANDROID_CONTROL_CAPTURE_INTENT_STILL_CAPTURE)) {
5162 isStillCapture = true;
5163 ATRACE_ASYNC_BEGIN("still capture", mNextRequests[i].halRequest.frame_number);
5164 }
Shuzhen Wang26abaf42018-08-28 15:41:20 -07005165
Emilian Peevaf8416e2021-02-04 17:52:43 -08005166 e = camera_metadata_ro_entry_t();
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08005167 find_camera_metadata_ro_entry(settings, ANDROID_CONTROL_ENABLE_ZSL, &e);
Shuzhen Wang26abaf42018-08-28 15:41:20 -07005168 if ((e.count > 0) && (e.data.u8[0] == ANDROID_CONTROL_ENABLE_ZSL_TRUE)) {
5169 isZslCapture = true;
5170 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01005171 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005172 res = parent->registerInFlight(halRequest->frame_number,
5173 totalNumBuffers, captureRequest->mResultExtras,
5174 /*hasInput*/halRequest->input_buffer != NULL,
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07005175 hasCallback,
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08005176 calculateMaxExpectedDuration(settings),
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005177 requestedPhysicalCameras, isStillCapture, isZslCapture,
5178 captureRequest->mRotateAndCropAuto, mPrevCameraIdsWithZoom,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005179 (mUseHalBufManager) ? uniqueSurfaceIdMap :
Shuzhen Wang316781a2020-08-18 18:11:01 -07005180 SurfaceMap{}, captureRequest->mRequestTimeNs);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005181 ALOGVV("%s: registered in flight requestId = %" PRId32 ", frameNumber = %" PRId64
5182 ", burstId = %" PRId32 ".",
5183 __FUNCTION__,
5184 captureRequest->mResultExtras.requestId, captureRequest->mResultExtras.frameNumber,
5185 captureRequest->mResultExtras.burstId);
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08005186
5187 if (shouldUnlockSettings) {
5188 captureRequest->mSettingsList.begin()->metadata.unlock(settings);
5189 }
5190
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005191 if (res != OK) {
5192 SET_ERR("RequestThread: Unable to register new in-flight request:"
5193 " %s (%d)", strerror(-res), res);
5194 return INVALID_OPERATION;
5195 }
5196 }
5197
5198 return OK;
5199}
5200
Igor Murashkin1e479c02013-09-06 16:55:14 -07005201CameraMetadata Camera3Device::RequestThread::getLatestRequest() const {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005202 ATRACE_CALL();
Igor Murashkin1e479c02013-09-06 16:55:14 -07005203 Mutex::Autolock al(mLatestRequestMutex);
5204
5205 ALOGV("RequestThread::%s", __FUNCTION__);
5206
5207 return mLatestRequest;
5208}
5209
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005210bool Camera3Device::RequestThread::isStreamPending(
5211 sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005212 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005213 Mutex::Autolock l(mRequestLock);
5214
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005215 for (const auto& nextRequest : mNextRequests) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005216 if (!nextRequest.submitted) {
5217 for (const auto& s : nextRequest.captureRequest->mOutputStreams) {
5218 if (stream == s) return true;
5219 }
5220 if (stream == nextRequest.captureRequest->mInputStream) return true;
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07005221 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07005222 }
5223
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005224 for (const auto& request : mRequestQueue) {
5225 for (const auto& s : request->mOutputStreams) {
5226 if (stream == s) return true;
5227 }
5228 if (stream == request->mInputStream) return true;
5229 }
5230
5231 for (const auto& request : mRepeatingRequests) {
5232 for (const auto& s : request->mOutputStreams) {
5233 if (stream == s) return true;
5234 }
5235 if (stream == request->mInputStream) return true;
5236 }
5237
5238 return false;
5239}
Jianing Weicb0652e2014-03-12 18:29:36 -07005240
Emilian Peev40ead602017-09-26 15:46:36 +01005241bool Camera3Device::RequestThread::isOutputSurfacePending(int streamId, size_t surfaceId) {
5242 ATRACE_CALL();
5243 Mutex::Autolock l(mRequestLock);
5244
5245 for (const auto& nextRequest : mNextRequests) {
5246 for (const auto& s : nextRequest.captureRequest->mOutputSurfaces) {
5247 if (s.first == streamId) {
5248 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
5249 if (it != s.second.end()) {
5250 return true;
5251 }
5252 }
5253 }
5254 }
5255
5256 for (const auto& request : mRequestQueue) {
5257 for (const auto& s : request->mOutputSurfaces) {
5258 if (s.first == streamId) {
5259 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
5260 if (it != s.second.end()) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005261 return true;
Emilian Peev40ead602017-09-26 15:46:36 +01005262 }
5263 }
5264 }
5265 }
5266
5267 for (const auto& request : mRepeatingRequests) {
5268 for (const auto& s : request->mOutputSurfaces) {
5269 if (s.first == streamId) {
5270 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
5271 if (it != s.second.end()) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005272 return true;
Emilian Peev40ead602017-09-26 15:46:36 +01005273 }
5274 }
5275 }
5276 }
5277
5278 return false;
5279}
5280
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07005281void Camera3Device::RequestThread::signalPipelineDrain(const std::vector<int>& streamIds) {
5282 if (!mUseHalBufManager) {
5283 ALOGE("%s called for camera device not supporting HAL buffer management", __FUNCTION__);
5284 return;
5285 }
5286
5287 Mutex::Autolock pl(mPauseLock);
5288 if (mPaused) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005289 mInterface->signalPipelineDrain(streamIds);
5290 return;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07005291 }
5292 // If request thread is still busy, wait until paused then notify HAL
5293 mNotifyPipelineDrain = true;
5294 mStreamIdsToBeDrained = streamIds;
5295}
5296
Yin-Chia Yehe52b8fa2020-07-28 00:17:58 -07005297void Camera3Device::RequestThread::resetPipelineDrain() {
5298 Mutex::Autolock pl(mPauseLock);
5299 mNotifyPipelineDrain = false;
5300 mStreamIdsToBeDrained.clear();
5301}
5302
Emilian Peevc0fe54c2020-03-11 14:05:07 -07005303void Camera3Device::RequestThread::clearPreviousRequest() {
5304 Mutex::Autolock l(mRequestLock);
5305 mPrevRequest.clear();
5306}
5307
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005308status_t Camera3Device::RequestThread::switchToOffline(
5309 const std::vector<int32_t>& streamsToKeep,
5310 /*out*/hardware::camera::device::V3_6::CameraOfflineSessionInfo* offlineSessionInfo,
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005311 /*out*/sp<hardware::camera::device::V3_6::ICameraOfflineSession>* offlineSession,
5312 /*out*/camera3::BufferRecords* bufferRecords) {
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005313 Mutex::Autolock l(mRequestLock);
5314 clearRepeatingRequestsLocked(/*lastFrameNumber*/nullptr);
5315
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005316 // Wait until request thread is fully stopped
5317 // TBD: check if request thread is being paused by other APIs (shouldn't be)
5318
5319 // We could also check for mRepeatingRequests.empty(), but the API interface
5320 // is serialized by Camera3Device::mInterfaceLock so no one should be able to submit any
5321 // new requests during the call; hence skip that check.
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005322 bool queueEmpty = mNextRequests.empty() && mRequestQueue.empty();
5323 while (!queueEmpty) {
5324 status_t res = mRequestSubmittedSignal.waitRelative(mRequestLock, kRequestSubmitTimeout);
5325 if (res == TIMED_OUT) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005326 ALOGE("%s: request thread failed to submit one request within timeout!", __FUNCTION__);
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005327 return res;
5328 } else if (res != OK) {
5329 ALOGE("%s: request thread failed to submit a request: %s (%d)!",
5330 __FUNCTION__, strerror(-res), res);
5331 return res;
5332 }
5333 queueEmpty = mNextRequests.empty() && mRequestQueue.empty();
5334 }
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005335
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005336 return mInterface->switchToOffline(
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005337 streamsToKeep, offlineSessionInfo, offlineSession, bufferRecords);
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005338}
5339
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005340status_t Camera3Device::RequestThread::setRotateAndCropAutoBehavior(
5341 camera_metadata_enum_android_scaler_rotate_and_crop_t rotateAndCropValue) {
5342 ATRACE_CALL();
5343 Mutex::Autolock l(mTriggerMutex);
5344 if (rotateAndCropValue == ANDROID_SCALER_ROTATE_AND_CROP_AUTO) {
5345 return BAD_VALUE;
5346 }
5347 mRotateAndCropOverride = rotateAndCropValue;
5348 return OK;
5349}
5350
Emilian Peeve23f1d92021-09-20 14:56:01 -07005351status_t Camera3Device::RequestThread::setComposerSurface(bool composerSurfacePresent) {
5352 ATRACE_CALL();
5353 Mutex::Autolock l(mTriggerMutex);
5354 mComposerOutput = composerSurfacePresent;
5355 return OK;
5356}
5357
Eino-Ville Talvala11afe4f2021-05-27 14:45:31 -07005358status_t Camera3Device::RequestThread::setCameraMute(int32_t muteMode) {
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005359 ATRACE_CALL();
5360 Mutex::Autolock l(mTriggerMutex);
Eino-Ville Talvala11afe4f2021-05-27 14:45:31 -07005361 if (muteMode != mCameraMute) {
5362 mCameraMute = muteMode;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005363 mCameraMuteChanged = true;
5364 }
5365 return OK;
5366}
5367
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07005368nsecs_t Camera3Device::getExpectedInFlightDuration() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005369 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005370 std::lock_guard<std::mutex> l(mInFlightLock);
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07005371 return mExpectedInflightDuration > kMinInflightDuration ?
5372 mExpectedInflightDuration : kMinInflightDuration;
5373}
5374
Emilian Peevaebbe412018-01-15 13:53:24 +00005375void Camera3Device::RequestThread::cleanupPhysicalSettings(sp<CaptureRequest> request,
Emilian Peevf4816702020-04-03 15:44:51 -07005376 camera_capture_request_t *halRequest) {
Emilian Peevaebbe412018-01-15 13:53:24 +00005377 if ((request == nullptr) || (halRequest == nullptr)) {
5378 ALOGE("%s: Invalid request!", __FUNCTION__);
5379 return;
5380 }
5381
5382 if (halRequest->num_physcam_settings > 0) {
5383 if (halRequest->physcam_id != nullptr) {
5384 delete [] halRequest->physcam_id;
5385 halRequest->physcam_id = nullptr;
5386 }
5387 if (halRequest->physcam_settings != nullptr) {
5388 auto it = ++(request->mSettingsList.begin());
5389 size_t i = 0;
5390 for (; it != request->mSettingsList.end(); it++, i++) {
5391 it->metadata.unlock(halRequest->physcam_settings[i]);
5392 }
5393 delete [] halRequest->physcam_settings;
5394 halRequest->physcam_settings = nullptr;
5395 }
5396 }
5397}
5398
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005399void Camera3Device::RequestThread::cleanUpFailedRequests(bool sendRequestError) {
5400 if (mNextRequests.empty()) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005401 return;
5402 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005403
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005404 for (auto& nextRequest : mNextRequests) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005405 // Skip the ones that have been submitted successfully.
5406 if (nextRequest.submitted) {
5407 continue;
5408 }
5409
5410 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
Emilian Peevf4816702020-04-03 15:44:51 -07005411 camera_capture_request_t* halRequest = &nextRequest.halRequest;
5412 Vector<camera_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005413
5414 if (halRequest->settings != NULL) {
Emilian Peevaebbe412018-01-15 13:53:24 +00005415 captureRequest->mSettingsList.begin()->metadata.unlock(halRequest->settings);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005416 }
5417
Emilian Peevaebbe412018-01-15 13:53:24 +00005418 cleanupPhysicalSettings(captureRequest, halRequest);
5419
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005420 if (captureRequest->mInputStream != NULL) {
Emilian Peevf4816702020-04-03 15:44:51 -07005421 captureRequest->mInputBuffer.status = CAMERA_BUFFER_STATUS_ERROR;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005422 captureRequest->mInputStream->returnInputBuffer(captureRequest->mInputBuffer);
5423 }
5424
Yin-Chia Yeh21cb47b2019-01-18 15:08:17 -08005425 // No output buffer can be returned when using HAL buffer manager
5426 if (!mUseHalBufManager) {
5427 for (size_t i = 0; i < halRequest->num_output_buffers; i++) {
5428 //Buffers that failed processing could still have
5429 //valid acquire fence.
5430 int acquireFence = (*outputBuffers)[i].acquire_fence;
5431 if (0 <= acquireFence) {
5432 close(acquireFence);
5433 outputBuffers->editItemAt(i).acquire_fence = -1;
5434 }
Emilian Peevf4816702020-04-03 15:44:51 -07005435 outputBuffers->editItemAt(i).status = CAMERA_BUFFER_STATUS_ERROR;
Yin-Chia Yeh21cb47b2019-01-18 15:08:17 -08005436 captureRequest->mOutputStreams.editItemAt(i)->returnBuffer((*outputBuffers)[i], 0,
5437 /*timestampIncreasing*/true, std::vector<size_t> (),
5438 captureRequest->mResultExtras.frameNumber);
Emilian Peevc58cf4c2017-05-11 17:23:41 +01005439 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005440 }
5441
5442 if (sendRequestError) {
5443 Mutex::Autolock l(mRequestLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005444 sp<NotificationListener> listener = mListener.promote();
5445 if (listener != NULL) {
5446 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08005447 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005448 captureRequest->mResultExtras);
5449 }
5450 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07005451
5452 // Remove yet-to-be submitted inflight request from inflightMap
5453 {
5454 sp<Camera3Device> parent = mParent.promote();
5455 if (parent != NULL) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005456 std::lock_guard<std::mutex> l(parent->mInFlightLock);
Shuzhen Wangcadb3302016-11-04 14:17:56 -07005457 ssize_t idx = parent->mInFlightMap.indexOfKey(captureRequest->mResultExtras.frameNumber);
5458 if (idx >= 0) {
5459 ALOGV("%s: Remove inflight request from queue: frameNumber %" PRId64,
5460 __FUNCTION__, captureRequest->mResultExtras.frameNumber);
5461 parent->removeInFlightMapEntryLocked(idx);
5462 }
5463 }
5464 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005465 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07005466
5467 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005468 mNextRequests.clear();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005469}
5470
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005471void Camera3Device::RequestThread::waitForNextRequestBatch() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005472 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005473 // Optimized a bit for the simple steady-state case (single repeating
5474 // request), to avoid putting that request in the queue temporarily.
5475 Mutex::Autolock l(mRequestLock);
5476
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005477 assert(mNextRequests.empty());
5478
5479 NextRequest nextRequest;
5480 nextRequest.captureRequest = waitForNextRequestLocked();
5481 if (nextRequest.captureRequest == nullptr) {
5482 return;
5483 }
5484
Emilian Peevf4816702020-04-03 15:44:51 -07005485 nextRequest.halRequest = camera_capture_request_t();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005486 nextRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005487 mNextRequests.add(nextRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005488
5489 // Wait for additional requests
5490 const size_t batchSize = nextRequest.captureRequest->mBatchSize;
5491
5492 for (size_t i = 1; i < batchSize; i++) {
5493 NextRequest additionalRequest;
5494 additionalRequest.captureRequest = waitForNextRequestLocked();
5495 if (additionalRequest.captureRequest == nullptr) {
5496 break;
5497 }
5498
Emilian Peevf4816702020-04-03 15:44:51 -07005499 additionalRequest.halRequest = camera_capture_request_t();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005500 additionalRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005501 mNextRequests.add(additionalRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005502 }
5503
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005504 if (mNextRequests.size() < batchSize) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08005505 ALOGE("RequestThread: only get %zu out of %zu requests. Skipping requests.",
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005506 mNextRequests.size(), batchSize);
5507 cleanUpFailedRequests(/*sendRequestError*/true);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005508 }
5509
5510 return;
5511}
5512
5513sp<Camera3Device::CaptureRequest>
5514 Camera3Device::RequestThread::waitForNextRequestLocked() {
5515 status_t res;
5516 sp<CaptureRequest> nextRequest;
5517
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005518 while (mRequestQueue.empty()) {
5519 if (!mRepeatingRequests.empty()) {
5520 // Always atomically enqueue all requests in a repeating request
5521 // list. Guarantees a complete in-sequence set of captures to
5522 // application.
5523 const RequestList &requests = mRepeatingRequests;
Shuzhen Wang316781a2020-08-18 18:11:01 -07005524 if (mFirstRepeating) {
5525 mFirstRepeating = false;
5526 } else {
5527 for (auto& request : requests) {
5528 // For repeating requests, override timestamp request using
5529 // the time a request is inserted into the request queue,
5530 // because the original repeating request will have an old
5531 // fixed timestamp.
5532 request->mRequestTimeNs = systemTime();
5533 }
5534 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005535 RequestList::const_iterator firstRequest =
5536 requests.begin();
5537 nextRequest = *firstRequest;
5538 mRequestQueue.insert(mRequestQueue.end(),
5539 ++firstRequest,
5540 requests.end());
5541 // No need to wait any longer
Jianing Weicb0652e2014-03-12 18:29:36 -07005542
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005543 mRepeatingLastFrameNumber = mFrameNumber + requests.size() - 1;
Jianing Weicb0652e2014-03-12 18:29:36 -07005544
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005545 break;
5546 }
5547
5548 res = mRequestSignal.waitRelative(mRequestLock, kRequestTimeout);
5549
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005550 if ((mRequestQueue.empty() && mRepeatingRequests.empty()) ||
5551 exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005552 Mutex::Autolock pl(mPauseLock);
5553 if (mPaused == false) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005554 ALOGV("%s: RequestThread: Going idle", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005555 mPaused = true;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07005556 if (mNotifyPipelineDrain) {
5557 mInterface->signalPipelineDrain(mStreamIdsToBeDrained);
5558 mNotifyPipelineDrain = false;
5559 mStreamIdsToBeDrained.clear();
5560 }
Yin-Chia Yehc300a072019-02-13 14:56:57 -08005561 // Let the tracker know
5562 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5563 if (statusTracker != 0) {
5564 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
5565 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005566 sp<Camera3Device> parent = mParent.promote();
5567 if (parent != nullptr) {
5568 parent->mRequestBufferSM.onRequestThreadPaused();
5569 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005570 }
5571 // Stop waiting for now and let thread management happen
5572 return NULL;
5573 }
5574 }
5575
5576 if (nextRequest == NULL) {
5577 // Don't have a repeating request already in hand, so queue
5578 // must have an entry now.
5579 RequestList::iterator firstRequest =
5580 mRequestQueue.begin();
5581 nextRequest = *firstRequest;
5582 mRequestQueue.erase(firstRequest);
Shuzhen Wang9d066012016-09-30 11:30:20 -07005583 if (mRequestQueue.empty() && !nextRequest->mRepeating) {
5584 sp<NotificationListener> listener = mListener.promote();
5585 if (listener != NULL) {
5586 listener->notifyRequestQueueEmpty();
5587 }
5588 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005589 }
5590
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005591 // In case we've been unpaused by setPaused clearing mDoPause, need to
5592 // update internal pause state (capture/setRepeatingRequest unpause
5593 // directly).
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005594 Mutex::Autolock pl(mPauseLock);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005595 if (mPaused) {
5596 ALOGV("%s: RequestThread: Unpaused", __FUNCTION__);
5597 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5598 if (statusTracker != 0) {
5599 statusTracker->markComponentActive(mStatusId);
5600 }
5601 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005602 mPaused = false;
5603
5604 // Check if we've reconfigured since last time, and reset the preview
5605 // request if so. Can't use 'NULL request == repeat' across configure calls.
5606 if (mReconfigured) {
5607 mPrevRequest.clear();
5608 mReconfigured = false;
5609 }
5610
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005611 if (nextRequest != NULL) {
5612 nextRequest->mResultExtras.frameNumber = mFrameNumber++;
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07005613 nextRequest->mResultExtras.afTriggerId = mCurrentAfTriggerId;
5614 nextRequest->mResultExtras.precaptureTriggerId = mCurrentPreCaptureTriggerId;
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07005615
5616 // Since RequestThread::clear() removes buffers from the input stream,
5617 // get the right buffer here before unlocking mRequestLock
5618 if (nextRequest->mInputStream != NULL) {
Shuzhen Wang83bff122020-11-20 15:51:39 -08005619 res = nextRequest->mInputStream->getInputBuffer(&nextRequest->mInputBuffer,
5620 &nextRequest->mInputBufferSize);
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07005621 if (res != OK) {
5622 // Can't get input buffer from gralloc queue - this could be due to
5623 // disconnected queue or other producer misbehavior, so not a fatal
5624 // error
5625 ALOGE("%s: Can't get input buffer, skipping request:"
5626 " %s (%d)", __FUNCTION__, strerror(-res), res);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005627
5628 sp<NotificationListener> listener = mListener.promote();
5629 if (listener != NULL) {
5630 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08005631 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07005632 nextRequest->mResultExtras);
5633 }
5634 return NULL;
5635 }
5636 }
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005637 }
Chien-Yu Chend196d612015-06-22 19:49:01 -07005638
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005639 return nextRequest;
5640}
5641
5642bool Camera3Device::RequestThread::waitIfPaused() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005643 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005644 status_t res;
5645 Mutex::Autolock l(mPauseLock);
5646 while (mDoPause) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005647 if (mPaused == false) {
5648 mPaused = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005649 ALOGV("%s: RequestThread: Paused", __FUNCTION__);
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07005650 if (mNotifyPipelineDrain) {
5651 mInterface->signalPipelineDrain(mStreamIdsToBeDrained);
5652 mNotifyPipelineDrain = false;
5653 mStreamIdsToBeDrained.clear();
5654 }
Yin-Chia Yehc300a072019-02-13 14:56:57 -08005655 // Let the tracker know
5656 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5657 if (statusTracker != 0) {
5658 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
5659 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005660 sp<Camera3Device> parent = mParent.promote();
5661 if (parent != nullptr) {
5662 parent->mRequestBufferSM.onRequestThreadPaused();
5663 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005664 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005665
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005666 res = mDoPauseSignal.waitRelative(mPauseLock, kRequestTimeout);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005667 if (res == TIMED_OUT || exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005668 return true;
5669 }
5670 }
5671 // We don't set mPaused to false here, because waitForNextRequest needs
5672 // to further manage the paused state in case of starvation.
5673 return false;
5674}
5675
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005676void Camera3Device::RequestThread::unpauseForNewRequests() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005677 ATRACE_CALL();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005678 // With work to do, mark thread as unpaused.
5679 // If paused by request (setPaused), don't resume, to avoid
5680 // extra signaling/waiting overhead to waitUntilPaused
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005681 mRequestSignal.signal();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005682 Mutex::Autolock p(mPauseLock);
5683 if (!mDoPause) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005684 ALOGV("%s: RequestThread: Going active", __FUNCTION__);
5685 if (mPaused) {
5686 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5687 if (statusTracker != 0) {
5688 statusTracker->markComponentActive(mStatusId);
5689 }
5690 }
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005691 mPaused = false;
5692 }
5693}
5694
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07005695void Camera3Device::RequestThread::setErrorState(const char *fmt, ...) {
5696 sp<Camera3Device> parent = mParent.promote();
5697 if (parent != NULL) {
5698 va_list args;
5699 va_start(args, fmt);
5700
5701 parent->setErrorStateV(fmt, args);
5702
5703 va_end(args);
5704 }
5705}
5706
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005707status_t Camera3Device::RequestThread::insertTriggers(
5708 const sp<CaptureRequest> &request) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005709 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005710 Mutex::Autolock al(mTriggerMutex);
5711
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07005712 sp<Camera3Device> parent = mParent.promote();
5713 if (parent == NULL) {
5714 CLOGE("RequestThread: Parent is gone");
5715 return DEAD_OBJECT;
5716 }
5717
Emilian Peevaebbe412018-01-15 13:53:24 +00005718 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005719 size_t count = mTriggerMap.size();
5720
5721 for (size_t i = 0; i < count; ++i) {
5722 RequestTrigger trigger = mTriggerMap.valueAt(i);
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005723 uint32_t tag = trigger.metadataTag;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07005724
5725 if (tag == ANDROID_CONTROL_AF_TRIGGER_ID || tag == ANDROID_CONTROL_AE_PRECAPTURE_ID) {
5726 bool isAeTrigger = (trigger.metadataTag == ANDROID_CONTROL_AE_PRECAPTURE_ID);
5727 uint32_t triggerId = static_cast<uint32_t>(trigger.entryValue);
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07005728 if (isAeTrigger) {
5729 request->mResultExtras.precaptureTriggerId = triggerId;
5730 mCurrentPreCaptureTriggerId = triggerId;
5731 } else {
5732 request->mResultExtras.afTriggerId = triggerId;
5733 mCurrentAfTriggerId = triggerId;
5734 }
Emilian Peev7e25e5e2017-04-07 15:48:49 +01005735 continue;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07005736 }
5737
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005738 camera_metadata_entry entry = metadata.find(tag);
5739
5740 if (entry.count > 0) {
5741 /**
5742 * Already has an entry for this trigger in the request.
5743 * Rewrite it with our requested trigger value.
5744 */
5745 RequestTrigger oldTrigger = trigger;
5746
5747 oldTrigger.entryValue = entry.data.u8[0];
5748
5749 mTriggerReplacedMap.add(tag, oldTrigger);
5750 } else {
5751 /**
5752 * More typical, no trigger entry, so we just add it
5753 */
5754 mTriggerRemovedMap.add(tag, trigger);
5755 }
5756
5757 status_t res;
5758
5759 switch (trigger.getTagType()) {
5760 case TYPE_BYTE: {
5761 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
5762 res = metadata.update(tag,
5763 &entryValue,
5764 /*count*/1);
5765 break;
5766 }
5767 case TYPE_INT32:
5768 res = metadata.update(tag,
5769 &trigger.entryValue,
5770 /*count*/1);
5771 break;
5772 default:
5773 ALOGE("%s: Type not supported: 0x%x",
5774 __FUNCTION__,
5775 trigger.getTagType());
5776 return INVALID_OPERATION;
5777 }
5778
5779 if (res != OK) {
5780 ALOGE("%s: Failed to update request metadata with trigger tag %s"
5781 ", value %d", __FUNCTION__, trigger.getTagName(),
5782 trigger.entryValue);
5783 return res;
5784 }
5785
5786 ALOGV("%s: Mixed in trigger %s, value %d", __FUNCTION__,
5787 trigger.getTagName(),
5788 trigger.entryValue);
5789 }
5790
5791 mTriggerMap.clear();
5792
5793 return count;
5794}
5795
5796status_t Camera3Device::RequestThread::removeTriggers(
5797 const sp<CaptureRequest> &request) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005798 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005799 Mutex::Autolock al(mTriggerMutex);
5800
Emilian Peevaebbe412018-01-15 13:53:24 +00005801 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005802
5803 /**
5804 * Replace all old entries with their old values.
5805 */
5806 for (size_t i = 0; i < mTriggerReplacedMap.size(); ++i) {
5807 RequestTrigger trigger = mTriggerReplacedMap.valueAt(i);
5808
5809 status_t res;
5810
5811 uint32_t tag = trigger.metadataTag;
5812 switch (trigger.getTagType()) {
5813 case TYPE_BYTE: {
5814 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
5815 res = metadata.update(tag,
5816 &entryValue,
5817 /*count*/1);
5818 break;
5819 }
5820 case TYPE_INT32:
5821 res = metadata.update(tag,
5822 &trigger.entryValue,
5823 /*count*/1);
5824 break;
5825 default:
5826 ALOGE("%s: Type not supported: 0x%x",
5827 __FUNCTION__,
5828 trigger.getTagType());
5829 return INVALID_OPERATION;
5830 }
5831
5832 if (res != OK) {
5833 ALOGE("%s: Failed to restore request metadata with trigger tag %s"
5834 ", trigger value %d", __FUNCTION__,
5835 trigger.getTagName(), trigger.entryValue);
5836 return res;
5837 }
5838 }
5839 mTriggerReplacedMap.clear();
5840
5841 /**
5842 * Remove all new entries.
5843 */
5844 for (size_t i = 0; i < mTriggerRemovedMap.size(); ++i) {
5845 RequestTrigger trigger = mTriggerRemovedMap.valueAt(i);
5846 status_t res = metadata.erase(trigger.metadataTag);
5847
5848 if (res != OK) {
5849 ALOGE("%s: Failed to erase metadata with trigger tag %s"
5850 ", trigger value %d", __FUNCTION__,
5851 trigger.getTagName(), trigger.entryValue);
5852 return res;
5853 }
5854 }
5855 mTriggerRemovedMap.clear();
5856
5857 return OK;
5858}
5859
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04005860status_t Camera3Device::RequestThread::addFakeTriggerIds(
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005861 const sp<CaptureRequest> &request) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08005862 // Trigger ID 0 had special meaning in the HAL2 spec, so avoid it here
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04005863 static const int32_t fakeTriggerId = 1;
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005864 status_t res;
5865
Emilian Peevaebbe412018-01-15 13:53:24 +00005866 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005867
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04005868 // If AF trigger is active, insert a fake AF trigger ID if none already
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005869 // exists
5870 camera_metadata_entry afTrigger = metadata.find(ANDROID_CONTROL_AF_TRIGGER);
5871 camera_metadata_entry afId = metadata.find(ANDROID_CONTROL_AF_TRIGGER_ID);
5872 if (afTrigger.count > 0 &&
5873 afTrigger.data.u8[0] != ANDROID_CONTROL_AF_TRIGGER_IDLE &&
5874 afId.count == 0) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04005875 res = metadata.update(ANDROID_CONTROL_AF_TRIGGER_ID, &fakeTriggerId, 1);
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005876 if (res != OK) return res;
5877 }
5878
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04005879 // If AE precapture trigger is active, insert a fake precapture trigger ID
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005880 // if none already exists
5881 camera_metadata_entry pcTrigger =
5882 metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER);
5883 camera_metadata_entry pcId = metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_ID);
5884 if (pcTrigger.count > 0 &&
5885 pcTrigger.data.u8[0] != ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_IDLE &&
5886 pcId.count == 0) {
5887 res = metadata.update(ANDROID_CONTROL_AE_PRECAPTURE_ID,
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04005888 &fakeTriggerId, 1);
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005889 if (res != OK) return res;
5890 }
5891
5892 return OK;
5893}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005894
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005895bool Camera3Device::RequestThread::overrideAutoRotateAndCrop(
5896 const sp<CaptureRequest> &request) {
5897 ATRACE_CALL();
5898
5899 if (request->mRotateAndCropAuto) {
5900 Mutex::Autolock l(mTriggerMutex);
5901 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
5902
5903 auto rotateAndCropEntry = metadata.find(ANDROID_SCALER_ROTATE_AND_CROP);
5904 if (rotateAndCropEntry.count > 0) {
5905 if (rotateAndCropEntry.data.u8[0] == mRotateAndCropOverride) {
5906 return false;
5907 } else {
5908 rotateAndCropEntry.data.u8[0] = mRotateAndCropOverride;
5909 return true;
5910 }
5911 } else {
5912 uint8_t rotateAndCrop_u8 = mRotateAndCropOverride;
5913 metadata.update(ANDROID_SCALER_ROTATE_AND_CROP,
5914 &rotateAndCrop_u8, 1);
5915 return true;
5916 }
5917 }
5918 return false;
5919}
5920
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005921bool Camera3Device::RequestThread::overrideTestPattern(
5922 const sp<CaptureRequest> &request) {
5923 ATRACE_CALL();
5924
Eino-Ville Talvala1646c3c2021-07-29 13:48:40 -07005925 if (!mSupportCameraMute) return false;
Eino-Ville Talvalac2459842021-07-22 16:36:36 -07005926
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005927 Mutex::Autolock l(mTriggerMutex);
5928
5929 bool changed = false;
5930
5931 int32_t testPatternMode = request->mOriginalTestPatternMode;
5932 int32_t testPatternData[4] = {
5933 request->mOriginalTestPatternData[0],
5934 request->mOriginalTestPatternData[1],
5935 request->mOriginalTestPatternData[2],
5936 request->mOriginalTestPatternData[3]
5937 };
5938
Eino-Ville Talvala11afe4f2021-05-27 14:45:31 -07005939 if (mCameraMute != ANDROID_SENSOR_TEST_PATTERN_MODE_OFF) {
5940 testPatternMode = mCameraMute;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005941 testPatternData[0] = 0;
5942 testPatternData[1] = 0;
5943 testPatternData[2] = 0;
5944 testPatternData[3] = 0;
5945 }
5946
5947 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
5948
5949 auto testPatternEntry = metadata.find(ANDROID_SENSOR_TEST_PATTERN_MODE);
5950 if (testPatternEntry.count > 0) {
5951 if (testPatternEntry.data.i32[0] != testPatternMode) {
5952 testPatternEntry.data.i32[0] = testPatternMode;
5953 changed = true;
5954 }
5955 } else {
5956 metadata.update(ANDROID_SENSOR_TEST_PATTERN_MODE,
5957 &testPatternMode, 1);
5958 changed = true;
5959 }
5960
5961 auto testPatternColor = metadata.find(ANDROID_SENSOR_TEST_PATTERN_DATA);
Eino-Ville Talvalac2459842021-07-22 16:36:36 -07005962 if (testPatternColor.count >= 4) {
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005963 for (size_t i = 0; i < 4; i++) {
Eino-Ville Talvalac2459842021-07-22 16:36:36 -07005964 if (testPatternColor.data.i32[i] != testPatternData[i]) {
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005965 testPatternColor.data.i32[i] = testPatternData[i];
5966 changed = true;
5967 }
5968 }
5969 } else {
5970 metadata.update(ANDROID_SENSOR_TEST_PATTERN_DATA,
Eino-Ville Talvalac2459842021-07-22 16:36:36 -07005971 testPatternData, 4);
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005972 changed = true;
5973 }
5974
5975 return changed;
5976}
5977
Cliff Wuc2ad9c82021-04-21 00:58:58 +08005978status_t Camera3Device::RequestThread::setHalInterface(
5979 sp<HalInterface> newHalInterface) {
5980 if (newHalInterface.get() == nullptr) {
5981 ALOGE("%s: The newHalInterface does not exist!", __FUNCTION__);
5982 return DEAD_OBJECT;
5983 }
5984
5985 mInterface = newHalInterface;
5986
5987 return OK;
5988}
5989
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005990/**
5991 * PreparerThread inner class methods
5992 */
5993
5994Camera3Device::PreparerThread::PreparerThread() :
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07005995 Thread(/*canCallJava*/false), mListener(nullptr),
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005996 mActive(false), mCancelNow(false), mCurrentMaxCount(0), mCurrentPrepareComplete(false) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005997}
5998
5999Camera3Device::PreparerThread::~PreparerThread() {
6000 Thread::requestExitAndWait();
6001 if (mCurrentStream != nullptr) {
6002 mCurrentStream->cancelPrepare();
6003 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
6004 mCurrentStream.clear();
6005 }
6006 clear();
6007}
6008
Ruben Brunkc78ac262015-08-13 17:58:46 -07006009status_t Camera3Device::PreparerThread::prepare(int maxCount, sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07006010 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006011 status_t res;
6012
6013 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006014 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006015
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07006016 res = stream->startPrepare(maxCount, true /*blockRequest*/);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006017 if (res == OK) {
6018 // No preparation needed, fire listener right off
6019 ALOGV("%s: Stream %d already prepared", __FUNCTION__, stream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006020 if (listener != NULL) {
6021 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006022 }
6023 return OK;
6024 } else if (res != NOT_ENOUGH_DATA) {
6025 return res;
6026 }
6027
6028 // Need to prepare, start up thread if necessary
6029 if (!mActive) {
6030 // mRunning will change to false before the thread fully shuts down, so wait to be sure it
6031 // isn't running
6032 Thread::requestExitAndWait();
6033 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
6034 if (res != OK) {
6035 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__, res, strerror(-res));
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006036 if (listener != NULL) {
6037 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006038 }
6039 return res;
6040 }
6041 mCancelNow = false;
6042 mActive = true;
6043 ALOGV("%s: Preparer stream started", __FUNCTION__);
6044 }
6045
6046 // queue up the work
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006047 mPendingStreams.emplace(maxCount, stream);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006048 ALOGV("%s: Stream %d queued for preparing", __FUNCTION__, stream->getId());
6049
6050 return OK;
6051}
6052
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006053void Camera3Device::PreparerThread::pause() {
6054 ATRACE_CALL();
6055
6056 Mutex::Autolock l(mLock);
6057
6058 std::unordered_map<int, sp<camera3::Camera3StreamInterface> > pendingStreams;
6059 pendingStreams.insert(mPendingStreams.begin(), mPendingStreams.end());
6060 sp<camera3::Camera3StreamInterface> currentStream = mCurrentStream;
6061 int currentMaxCount = mCurrentMaxCount;
6062 mPendingStreams.clear();
6063 mCancelNow = true;
6064 while (mActive) {
6065 auto res = mThreadActiveSignal.waitRelative(mLock, kActiveTimeout);
6066 if (res == TIMED_OUT) {
6067 ALOGE("%s: Timed out waiting on prepare thread!", __FUNCTION__);
6068 return;
6069 } else if (res != OK) {
6070 ALOGE("%s: Encountered an error: %d waiting on prepare thread!", __FUNCTION__, res);
6071 return;
6072 }
6073 }
6074
6075 //Check whether the prepare thread was able to complete the current
6076 //stream. In case work is still pending emplace it along with the rest
6077 //of the streams in the pending list.
6078 if (currentStream != nullptr) {
6079 if (!mCurrentPrepareComplete) {
6080 pendingStreams.emplace(currentMaxCount, currentStream);
6081 }
6082 }
6083
6084 mPendingStreams.insert(pendingStreams.begin(), pendingStreams.end());
6085 for (const auto& it : mPendingStreams) {
6086 it.second->cancelPrepare();
6087 }
6088}
6089
6090status_t Camera3Device::PreparerThread::resume() {
6091 ATRACE_CALL();
6092 status_t res;
6093
6094 Mutex::Autolock l(mLock);
6095 sp<NotificationListener> listener = mListener.promote();
6096
6097 if (mActive) {
6098 ALOGE("%s: Trying to resume an already active prepare thread!", __FUNCTION__);
6099 return NO_INIT;
6100 }
6101
6102 auto it = mPendingStreams.begin();
6103 for (; it != mPendingStreams.end();) {
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07006104 res = it->second->startPrepare(it->first, true /*blockRequest*/);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006105 if (res == OK) {
6106 if (listener != NULL) {
6107 listener->notifyPrepared(it->second->getId());
6108 }
6109 it = mPendingStreams.erase(it);
6110 } else if (res != NOT_ENOUGH_DATA) {
6111 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__,
6112 res, strerror(-res));
6113 it = mPendingStreams.erase(it);
6114 } else {
6115 it++;
6116 }
6117 }
6118
6119 if (mPendingStreams.empty()) {
6120 return OK;
6121 }
6122
6123 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
6124 if (res != OK) {
6125 ALOGE("%s: Unable to start preparer stream: %d (%s)",
6126 __FUNCTION__, res, strerror(-res));
6127 return res;
6128 }
6129 mCancelNow = false;
6130 mActive = true;
6131 ALOGV("%s: Preparer stream started", __FUNCTION__);
6132
6133 return OK;
6134}
6135
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006136status_t Camera3Device::PreparerThread::clear() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07006137 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006138 Mutex::Autolock l(mLock);
6139
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006140 for (const auto& it : mPendingStreams) {
6141 it.second->cancelPrepare();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006142 }
6143 mPendingStreams.clear();
6144 mCancelNow = true;
6145
6146 return OK;
6147}
6148
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006149void Camera3Device::PreparerThread::setNotificationListener(wp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07006150 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006151 Mutex::Autolock l(mLock);
6152 mListener = listener;
6153}
6154
6155bool Camera3Device::PreparerThread::threadLoop() {
6156 status_t res;
6157 {
6158 Mutex::Autolock l(mLock);
6159 if (mCurrentStream == nullptr) {
6160 // End thread if done with work
6161 if (mPendingStreams.empty()) {
6162 ALOGV("%s: Preparer stream out of work", __FUNCTION__);
6163 // threadLoop _must not_ re-acquire mLock after it sets mActive to false; would
6164 // cause deadlock with prepare()'s requestExitAndWait triggered by !mActive.
6165 mActive = false;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006166 mThreadActiveSignal.signal();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006167 return false;
6168 }
6169
6170 // Get next stream to prepare
6171 auto it = mPendingStreams.begin();
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006172 mCurrentStream = it->second;
6173 mCurrentMaxCount = it->first;
6174 mCurrentPrepareComplete = false;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006175 mPendingStreams.erase(it);
6176 ATRACE_ASYNC_BEGIN("stream prepare", mCurrentStream->getId());
6177 ALOGV("%s: Preparing stream %d", __FUNCTION__, mCurrentStream->getId());
6178 } else if (mCancelNow) {
6179 mCurrentStream->cancelPrepare();
6180 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
6181 ALOGV("%s: Cancelling stream %d prepare", __FUNCTION__, mCurrentStream->getId());
6182 mCurrentStream.clear();
6183 mCancelNow = false;
6184 return true;
6185 }
6186 }
6187
6188 res = mCurrentStream->prepareNextBuffer();
6189 if (res == NOT_ENOUGH_DATA) return true;
6190 if (res != OK) {
6191 // Something bad happened; try to recover by cancelling prepare and
6192 // signalling listener anyway
6193 ALOGE("%s: Stream %d returned error %d (%s) during prepare", __FUNCTION__,
6194 mCurrentStream->getId(), res, strerror(-res));
6195 mCurrentStream->cancelPrepare();
6196 }
6197
6198 // This stream has finished, notify listener
6199 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006200 sp<NotificationListener> listener = mListener.promote();
6201 if (listener != NULL) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006202 ALOGV("%s: Stream %d prepare done, signaling listener", __FUNCTION__,
6203 mCurrentStream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006204 listener->notifyPrepared(mCurrentStream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006205 }
6206
6207 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
6208 mCurrentStream.clear();
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006209 mCurrentPrepareComplete = true;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006210
6211 return true;
6212}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07006213
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006214status_t Camera3Device::RequestBufferStateMachine::initialize(
6215 sp<camera3::StatusTracker> statusTracker) {
6216 if (statusTracker == nullptr) {
6217 ALOGE("%s: statusTracker is null", __FUNCTION__);
6218 return BAD_VALUE;
6219 }
6220
6221 std::lock_guard<std::mutex> lock(mLock);
6222 mStatusTracker = statusTracker;
Yin-Chia Yeh87b3ec02019-06-03 10:44:39 -07006223 mRequestBufferStatusId = statusTracker->addComponent("BufferRequestSM");
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006224 return OK;
6225}
6226
6227bool Camera3Device::RequestBufferStateMachine::startRequestBuffer() {
6228 std::lock_guard<std::mutex> lock(mLock);
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08006229 if (mStatus == RB_STATUS_READY || mStatus == RB_STATUS_PENDING_STOP) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006230 mRequestBufferOngoing = true;
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08006231 notifyTrackerLocked(/*active*/true);
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006232 return true;
6233 }
6234 return false;
6235}
6236
6237void Camera3Device::RequestBufferStateMachine::endRequestBuffer() {
6238 std::lock_guard<std::mutex> lock(mLock);
6239 if (!mRequestBufferOngoing) {
6240 ALOGE("%s called without a successful startRequestBuffer call first!", __FUNCTION__);
6241 return;
6242 }
6243 mRequestBufferOngoing = false;
6244 if (mStatus == RB_STATUS_PENDING_STOP) {
6245 checkSwitchToStopLocked();
6246 }
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08006247 notifyTrackerLocked(/*active*/false);
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006248}
6249
6250void Camera3Device::RequestBufferStateMachine::onStreamsConfigured() {
6251 std::lock_guard<std::mutex> lock(mLock);
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006252 mSwitchedToOffline = false;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006253 mStatus = RB_STATUS_READY;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006254 return;
6255}
6256
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08006257void Camera3Device::RequestBufferStateMachine::onSubmittingRequest() {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006258 std::lock_guard<std::mutex> lock(mLock);
6259 mRequestThreadPaused = false;
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08006260 // inflight map register actually happens in prepareHalRequest now, but it is close enough
6261 // approximation.
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006262 mInflightMapEmpty = false;
6263 if (mStatus == RB_STATUS_STOPPED) {
6264 mStatus = RB_STATUS_READY;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006265 }
6266 return;
6267}
6268
6269void Camera3Device::RequestBufferStateMachine::onRequestThreadPaused() {
6270 std::lock_guard<std::mutex> lock(mLock);
6271 mRequestThreadPaused = true;
6272 if (mStatus == RB_STATUS_PENDING_STOP) {
6273 checkSwitchToStopLocked();
6274 }
6275 return;
6276}
6277
6278void Camera3Device::RequestBufferStateMachine::onInflightMapEmpty() {
6279 std::lock_guard<std::mutex> lock(mLock);
6280 mInflightMapEmpty = true;
6281 if (mStatus == RB_STATUS_PENDING_STOP) {
6282 checkSwitchToStopLocked();
6283 }
6284 return;
6285}
6286
6287void Camera3Device::RequestBufferStateMachine::onWaitUntilIdle() {
6288 std::lock_guard<std::mutex> lock(mLock);
6289 if (!checkSwitchToStopLocked()) {
6290 mStatus = RB_STATUS_PENDING_STOP;
6291 }
6292 return;
6293}
6294
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006295bool Camera3Device::RequestBufferStateMachine::onSwitchToOfflineSuccess() {
6296 std::lock_guard<std::mutex> lock(mLock);
6297 if (mRequestBufferOngoing) {
6298 ALOGE("%s: HAL must not be requesting buffer after HAL returns switchToOffline!",
6299 __FUNCTION__);
6300 return false;
6301 }
6302 mSwitchedToOffline = true;
6303 mInflightMapEmpty = true;
6304 mRequestThreadPaused = true;
6305 mStatus = RB_STATUS_STOPPED;
6306 return true;
6307}
6308
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006309void Camera3Device::RequestBufferStateMachine::notifyTrackerLocked(bool active) {
6310 sp<StatusTracker> statusTracker = mStatusTracker.promote();
6311 if (statusTracker != nullptr) {
6312 if (active) {
6313 statusTracker->markComponentActive(mRequestBufferStatusId);
6314 } else {
6315 statusTracker->markComponentIdle(mRequestBufferStatusId, Fence::NO_FENCE);
6316 }
6317 }
6318}
6319
6320bool Camera3Device::RequestBufferStateMachine::checkSwitchToStopLocked() {
6321 if (mInflightMapEmpty && mRequestThreadPaused && !mRequestBufferOngoing) {
6322 mStatus = RB_STATUS_STOPPED;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006323 return true;
6324 }
6325 return false;
6326}
6327
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006328bool Camera3Device::startRequestBuffer() {
6329 return mRequestBufferSM.startRequestBuffer();
6330}
Shuzhen Wang268a1362018-10-16 16:32:59 -07006331
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006332void Camera3Device::endRequestBuffer() {
6333 mRequestBufferSM.endRequestBuffer();
6334}
Shuzhen Wang268a1362018-10-16 16:32:59 -07006335
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006336nsecs_t Camera3Device::getWaitDuration() {
6337 return kBaseGetBufferWait + getExpectedInFlightDuration();
6338}
Shuzhen Wang268a1362018-10-16 16:32:59 -07006339
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006340void Camera3Device::getInflightBufferKeys(std::vector<std::pair<int32_t, int32_t>>* out) {
6341 mInterface->getInflightBufferKeys(out);
6342}
Shuzhen Wang268a1362018-10-16 16:32:59 -07006343
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006344void Camera3Device::getInflightRequestBufferKeys(std::vector<uint64_t>* out) {
6345 mInterface->getInflightRequestBufferKeys(out);
6346}
Shuzhen Wang268a1362018-10-16 16:32:59 -07006347
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006348std::vector<sp<Camera3StreamInterface>> Camera3Device::getAllStreams() {
6349 std::vector<sp<Camera3StreamInterface>> ret;
6350 bool hasInputStream = mInputStream != nullptr;
6351 ret.reserve(mOutputStreams.size() + mDeletedStreams.size() + ((hasInputStream) ? 1 : 0));
6352 if (hasInputStream) {
6353 ret.push_back(mInputStream);
Shuzhen Wang268a1362018-10-16 16:32:59 -07006354 }
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006355 for (size_t i = 0; i < mOutputStreams.size(); i++) {
6356 ret.push_back(mOutputStreams[i]);
6357 }
6358 for (size_t i = 0; i < mDeletedStreams.size(); i++) {
6359 ret.push_back(mDeletedStreams[i]);
6360 }
6361 return ret;
Shuzhen Wang268a1362018-10-16 16:32:59 -07006362}
6363
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006364status_t Camera3Device::switchToOffline(
6365 const std::vector<int32_t>& streamsToKeep,
6366 /*out*/ sp<CameraOfflineSessionBase>* session) {
6367 ATRACE_CALL();
6368 if (session == nullptr) {
6369 ALOGE("%s: session must not be null", __FUNCTION__);
6370 return BAD_VALUE;
6371 }
6372
6373 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006374
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006375 bool hasInputStream = mInputStream != nullptr;
6376 int32_t inputStreamId = hasInputStream ? mInputStream->getId() : -1;
6377 bool inputStreamSupportsOffline = hasInputStream ?
6378 mInputStream->getOfflineProcessingSupport() : false;
6379 auto outputStreamIds = mOutputStreams.getStreamIds();
6380 auto streamIds = outputStreamIds;
6381 if (hasInputStream) {
6382 streamIds.push_back(mInputStream->getId());
6383 }
6384
6385 // Check all streams in streamsToKeep supports offline mode
6386 for (auto id : streamsToKeep) {
6387 if (std::find(streamIds.begin(), streamIds.end(), id) == streamIds.end()) {
6388 ALOGE("%s: Unknown stream ID %d", __FUNCTION__, id);
6389 return BAD_VALUE;
6390 } else if (id == inputStreamId) {
6391 if (!inputStreamSupportsOffline) {
6392 ALOGE("%s: input stream %d cannot be switched to offline",
6393 __FUNCTION__, id);
6394 return BAD_VALUE;
6395 }
6396 } else {
6397 sp<camera3::Camera3OutputStreamInterface> stream = mOutputStreams.get(id);
6398 if (!stream->getOfflineProcessingSupport()) {
6399 ALOGE("%s: output stream %d cannot be switched to offline",
6400 __FUNCTION__, id);
6401 return BAD_VALUE;
6402 }
6403 }
6404 }
6405
6406 // TODO: block surface sharing and surface group streams until we can support them
6407
6408 // Stop repeating request, wait until all remaining requests are submitted, then call into
6409 // HAL switchToOffline
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006410 hardware::camera::device::V3_6::CameraOfflineSessionInfo offlineSessionInfo;
6411 sp<hardware::camera::device::V3_6::ICameraOfflineSession> offlineSession;
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006412 camera3::BufferRecords bufferRecords;
6413 status_t ret = mRequestThread->switchToOffline(
6414 streamsToKeep, &offlineSessionInfo, &offlineSession, &bufferRecords);
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006415
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006416 if (ret != OK) {
6417 SET_ERR("Switch to offline failed: %s (%d)", strerror(-ret), ret);
6418 return ret;
6419 }
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006420
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006421 bool succ = mRequestBufferSM.onSwitchToOfflineSuccess();
6422 if (!succ) {
6423 SET_ERR("HAL must not be calling requestStreamBuffers call");
6424 // TODO: block ALL callbacks from HAL till app configured new streams?
6425 return UNKNOWN_ERROR;
6426 }
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006427
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006428 // Verify offlineSessionInfo
6429 std::vector<int32_t> offlineStreamIds;
6430 offlineStreamIds.reserve(offlineSessionInfo.offlineStreams.size());
6431 for (auto offlineStream : offlineSessionInfo.offlineStreams) {
6432 // verify stream IDs
6433 int32_t id = offlineStream.id;
6434 if (std::find(streamIds.begin(), streamIds.end(), id) == streamIds.end()) {
6435 SET_ERR("stream ID %d not found!", id);
6436 return UNKNOWN_ERROR;
6437 }
6438
6439 // When not using HAL buf manager, only allow streams requested by app to be preserved
6440 if (!mUseHalBufManager) {
6441 if (std::find(streamsToKeep.begin(), streamsToKeep.end(), id) == streamsToKeep.end()) {
6442 SET_ERR("stream ID %d must not be switched to offline!", id);
6443 return UNKNOWN_ERROR;
6444 }
6445 }
6446
6447 offlineStreamIds.push_back(id);
6448 sp<Camera3StreamInterface> stream = (id == inputStreamId) ?
6449 static_cast<sp<Camera3StreamInterface>>(mInputStream) :
6450 static_cast<sp<Camera3StreamInterface>>(mOutputStreams.get(id));
6451 // Verify number of outstanding buffers
6452 if (stream->getOutstandingBuffersCount() != offlineStream.numOutstandingBuffers) {
6453 SET_ERR("Offline stream %d # of remaining buffer mismatch: (%zu,%d) (service/HAL)",
6454 id, stream->getOutstandingBuffersCount(), offlineStream.numOutstandingBuffers);
6455 return UNKNOWN_ERROR;
6456 }
6457 }
6458
6459 // Verify all streams to be deleted don't have any outstanding buffers
6460 if (hasInputStream && std::find(offlineStreamIds.begin(), offlineStreamIds.end(),
6461 inputStreamId) == offlineStreamIds.end()) {
6462 if (mInputStream->hasOutstandingBuffers()) {
6463 SET_ERR("Input stream %d still has %zu outstanding buffer!",
6464 inputStreamId, mInputStream->getOutstandingBuffersCount());
6465 return UNKNOWN_ERROR;
6466 }
6467 }
6468
6469 for (const auto& outStreamId : outputStreamIds) {
6470 if (std::find(offlineStreamIds.begin(), offlineStreamIds.end(),
6471 outStreamId) == offlineStreamIds.end()) {
6472 auto outStream = mOutputStreams.get(outStreamId);
6473 if (outStream->hasOutstandingBuffers()) {
6474 SET_ERR("Output stream %d still has %zu outstanding buffer!",
6475 outStreamId, outStream->getOutstandingBuffersCount());
6476 return UNKNOWN_ERROR;
6477 }
6478 }
6479 }
6480
6481 InFlightRequestMap offlineReqs;
6482 // Verify inflight requests and their pending buffers
6483 {
6484 std::lock_guard<std::mutex> l(mInFlightLock);
6485 for (auto offlineReq : offlineSessionInfo.offlineRequests) {
6486 int idx = mInFlightMap.indexOfKey(offlineReq.frameNumber);
6487 if (idx == NAME_NOT_FOUND) {
6488 SET_ERR("Offline request frame number %d not found!", offlineReq.frameNumber);
6489 return UNKNOWN_ERROR;
6490 }
6491
6492 const auto& inflightReq = mInFlightMap.valueAt(idx);
6493 // TODO: check specific stream IDs
6494 size_t numBuffersLeft = static_cast<size_t>(inflightReq.numBuffersLeft);
6495 if (numBuffersLeft != offlineReq.pendingStreams.size()) {
6496 SET_ERR("Offline request # of remaining buffer mismatch: (%d,%d) (service/HAL)",
6497 inflightReq.numBuffersLeft, offlineReq.pendingStreams.size());
6498 return UNKNOWN_ERROR;
6499 }
6500 offlineReqs.add(offlineReq.frameNumber, inflightReq);
6501 }
6502 }
6503
6504 // Create Camera3OfflineSession and transfer object ownership
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006505 // (streams, inflight requests, buffer caches)
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006506 camera3::StreamSet offlineStreamSet;
6507 sp<camera3::Camera3Stream> inputStream;
6508 for (auto offlineStream : offlineSessionInfo.offlineStreams) {
6509 int32_t id = offlineStream.id;
6510 if (mInputStream != nullptr && id == mInputStream->getId()) {
6511 inputStream = mInputStream;
6512 } else {
6513 offlineStreamSet.add(id, mOutputStreams.get(id));
6514 }
6515 }
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006516
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006517 // TODO: check if we need to lock before copying states
6518 // though technically no other thread should be talking to Camera3Device at this point
6519 Camera3OfflineStates offlineStates(
6520 mTagMonitor, mVendorTagId, mUseHalBufManager, mNeedFixupMonochromeTags,
Shuzhen Wangb7b42652020-05-07 11:59:02 -07006521 mUsePartialResult, mNumPartialResults, mLastCompletedRegularFrameNumber,
6522 mLastCompletedReprocessFrameNumber, mLastCompletedZslFrameNumber,
6523 mNextResultFrameNumber, mNextReprocessResultFrameNumber,
6524 mNextZslStillResultFrameNumber, mNextShutterFrameNumber,
6525 mNextReprocessShutterFrameNumber, mNextZslStillShutterFrameNumber,
6526 mDeviceInfo, mPhysicalDeviceInfoMap, mDistortionMappers,
6527 mZoomRatioMappers, mRotateAndCropMappers);
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006528
6529 *session = new Camera3OfflineSession(mId, inputStream, offlineStreamSet,
6530 std::move(bufferRecords), offlineReqs, offlineStates, offlineSession);
6531
6532 // Delete all streams that has been transferred to offline session
6533 Mutex::Autolock l(mLock);
6534 for (auto offlineStream : offlineSessionInfo.offlineStreams) {
6535 int32_t id = offlineStream.id;
6536 if (mInputStream != nullptr && id == mInputStream->getId()) {
6537 mInputStream.clear();
6538 } else {
6539 mOutputStreams.remove(id);
6540 }
6541 }
6542
6543 // disconnect all other streams and switch to UNCONFIGURED state
6544 if (mInputStream != nullptr) {
6545 ret = mInputStream->disconnect();
6546 if (ret != OK) {
6547 SET_ERR_L("disconnect input stream failed!");
6548 return UNKNOWN_ERROR;
6549 }
6550 }
6551
6552 for (auto streamId : mOutputStreams.getStreamIds()) {
6553 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
6554 ret = stream->disconnect();
6555 if (ret != OK) {
6556 SET_ERR_L("disconnect output stream %d failed!", streamId);
6557 return UNKNOWN_ERROR;
6558 }
6559 }
6560
6561 mInputStream.clear();
6562 mOutputStreams.clear();
6563 mNeedConfig = true;
6564 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
6565 mOperatingMode = NO_MODE;
6566 mIsConstrainedHighSpeedConfiguration = false;
Emilian Peevc0fe54c2020-03-11 14:05:07 -07006567 mRequestThread->clearPreviousRequest();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006568
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006569 return OK;
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006570 // TO be done by CameraDeviceClient/Camera3OfflineSession
6571 // register the offline client to camera service
6572 // Setup result passthing threads etc
6573 // Initialize offline session so HAL can start sending callback to it (result Fmq)
6574 // TODO: check how many onIdle callback will be sent
6575 // Java side to make sure the CameraCaptureSession is properly closed
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006576}
6577
Emilian Peevcc0b7952020-01-07 13:54:47 -08006578void Camera3Device::getOfflineStreamIds(std::vector<int> *offlineStreamIds) {
6579 ATRACE_CALL();
6580
6581 if (offlineStreamIds == nullptr) {
6582 return;
6583 }
6584
6585 Mutex::Autolock il(mInterfaceLock);
6586
6587 auto streamIds = mOutputStreams.getStreamIds();
6588 bool hasInputStream = mInputStream != nullptr;
6589 if (hasInputStream && mInputStream->getOfflineProcessingSupport()) {
6590 offlineStreamIds->push_back(mInputStream->getId());
6591 }
6592
6593 for (const auto & streamId : streamIds) {
6594 sp<camera3::Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
6595 // Streams that use the camera buffer manager are currently not supported in
6596 // offline mode
6597 if (stream->getOfflineProcessingSupport() &&
6598 (stream->getStreamSetId() == CAMERA3_STREAM_SET_ID_INVALID)) {
6599 offlineStreamIds->push_back(streamId);
6600 }
6601 }
6602}
6603
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08006604status_t Camera3Device::setRotateAndCropAutoBehavior(
6605 camera_metadata_enum_android_scaler_rotate_and_crop_t rotateAndCropValue) {
6606 ATRACE_CALL();
6607 Mutex::Autolock il(mInterfaceLock);
6608 Mutex::Autolock l(mLock);
6609 if (mRequestThread == nullptr) {
6610 return INVALID_OPERATION;
6611 }
6612 return mRequestThread->setRotateAndCropAutoBehavior(rotateAndCropValue);
6613}
6614
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08006615bool Camera3Device::supportsCameraMute() {
6616 Mutex::Autolock il(mInterfaceLock);
6617 Mutex::Autolock l(mLock);
6618
6619 return mSupportCameraMute;
6620}
6621
6622status_t Camera3Device::setCameraMute(bool enabled) {
6623 ATRACE_CALL();
6624 Mutex::Autolock il(mInterfaceLock);
6625 Mutex::Autolock l(mLock);
6626
6627 if (mRequestThread == nullptr || !mSupportCameraMute) {
6628 return INVALID_OPERATION;
6629 }
Eino-Ville Talvala11afe4f2021-05-27 14:45:31 -07006630 int32_t muteMode =
6631 !enabled ? ANDROID_SENSOR_TEST_PATTERN_MODE_OFF :
6632 mSupportTestPatternSolidColor ? ANDROID_SENSOR_TEST_PATTERN_MODE_SOLID_COLOR :
6633 ANDROID_SENSOR_TEST_PATTERN_MODE_BLACK;
6634 return mRequestThread->setCameraMute(muteMode);
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08006635}
6636
Cliff Wuc2ad9c82021-04-21 00:58:58 +08006637status_t Camera3Device::injectCamera(const String8& injectedCamId,
6638 sp<CameraProviderManager> manager) {
6639 ALOGI("%s Injection camera: injectedCamId = %s", __FUNCTION__, injectedCamId.string());
6640 ATRACE_CALL();
6641 Mutex::Autolock il(mInterfaceLock);
6642
6643 status_t res = NO_ERROR;
6644 if (mInjectionMethods->isInjecting()) {
6645 if (injectedCamId == mInjectionMethods->getInjectedCamId()) {
6646 return OK;
6647 } else {
6648 res = mInjectionMethods->stopInjection();
6649 if (res != OK) {
6650 ALOGE("%s: Failed to stop the injection camera! ret != NO_ERROR: %d",
6651 __FUNCTION__, res);
6652 return res;
6653 }
6654 }
6655 }
6656
6657 res = mInjectionMethods->injectionInitialize(injectedCamId, manager, this);
6658 if (res != OK) {
6659 ALOGE("%s: Failed to initialize the injection camera! ret != NO_ERROR: %d",
6660 __FUNCTION__, res);
6661 return res;
6662 }
6663
6664 camera3::camera_stream_configuration injectionConfig;
6665 std::vector<uint32_t> injectionBufferSizes;
6666 mInjectionMethods->getInjectionConfig(&injectionConfig, &injectionBufferSizes);
6667 // When the second display of android is cast to the remote device, and the opened camera is
6668 // also cast to the second display, in this case, because the camera has configured the streams
6669 // at this time, we can directly call injectCamera() to replace the internal camera with
6670 // injection camera.
6671 if (mOperatingMode >= 0 && injectionConfig.num_streams > 0
6672 && injectionBufferSizes.size() > 0) {
6673 ALOGV("%s: The opened camera is directly cast to the remote device.", __FUNCTION__);
6674 res = mInjectionMethods->injectCamera(
6675 injectionConfig, injectionBufferSizes);
6676 if (res != OK) {
6677 ALOGE("Can't finish inject camera process!");
6678 return res;
6679 }
6680 }
6681
6682 return OK;
6683}
6684
6685status_t Camera3Device::stopInjection() {
6686 ALOGI("%s: Injection camera: stopInjection", __FUNCTION__);
6687 Mutex::Autolock il(mInterfaceLock);
6688 return mInjectionMethods->stopInjection();
6689}
6690
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08006691}; // namespace android