blob: b9a97befa937988499a1688e5b659247e855636c [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) {
Shuzhen Wang911c6a32021-10-27 13:36:03 -07002459 for (auto& settings : newRequest->mSettingsList) {
2460 auto testPatternModeEntry =
2461 settings.metadata.find(ANDROID_SENSOR_TEST_PATTERN_MODE);
2462 settings.mOriginalTestPatternMode = testPatternModeEntry.count > 0 ?
2463 testPatternModeEntry.data.i32[0] :
2464 ANDROID_SENSOR_TEST_PATTERN_MODE_OFF;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08002465
Shuzhen Wang911c6a32021-10-27 13:36:03 -07002466 auto testPatternDataEntry =
2467 settings.metadata.find(ANDROID_SENSOR_TEST_PATTERN_DATA);
2468 if (testPatternDataEntry.count >= 4) {
2469 memcpy(settings.mOriginalTestPatternData, testPatternDataEntry.data.i32,
2470 sizeof(PhysicalCameraSettings::mOriginalTestPatternData));
2471 } else {
2472 settings.mOriginalTestPatternData[0] = 0;
2473 settings.mOriginalTestPatternData[1] = 0;
2474 settings.mOriginalTestPatternData[2] = 0;
2475 settings.mOriginalTestPatternData[3] = 0;
2476 }
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08002477 }
2478 }
2479
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002480 return newRequest;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002481}
2482
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002483void Camera3Device::cancelStreamsConfigurationLocked() {
2484 int res = OK;
2485 if (mInputStream != NULL && mInputStream->isConfiguring()) {
2486 res = mInputStream->cancelConfiguration();
2487 if (res != OK) {
2488 CLOGE("Can't cancel configuring input stream %d: %s (%d)",
2489 mInputStream->getId(), strerror(-res), res);
2490 }
2491 }
2492
2493 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002494 sp<Camera3OutputStreamInterface> outputStream = mOutputStreams[i];
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002495 if (outputStream->isConfiguring()) {
2496 res = outputStream->cancelConfiguration();
2497 if (res != OK) {
2498 CLOGE("Can't cancel configuring output stream %d: %s (%d)",
2499 outputStream->getId(), strerror(-res), res);
2500 }
2501 }
2502 }
2503
2504 // Return state to that at start of call, so that future configures
2505 // properly clean things up
2506 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
2507 mNeedConfig = true;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002508
2509 res = mPreparerThread->resume();
2510 if (res != OK) {
2511 ALOGE("%s: Camera %s: Preparer thread failed to resume!", __FUNCTION__, mId.string());
2512 }
2513}
2514
Emilian Peev0d0191e2020-04-21 17:01:18 -07002515bool Camera3Device::checkAbandonedStreamsLocked() {
2516 if ((mInputStream.get() != nullptr) && (mInputStream->isAbandoned())) {
2517 return true;
2518 }
2519
2520 for (size_t i = 0; i < mOutputStreams.size(); i++) {
2521 auto stream = mOutputStreams[i];
2522 if ((stream.get() != nullptr) && (stream->isAbandoned())) {
2523 return true;
2524 }
2525 }
2526
2527 return false;
2528}
2529
Emilian Peev3bead5f2020-05-28 17:29:08 -07002530bool Camera3Device::reconfigureCamera(const CameraMetadata& sessionParams, int clientStatusId) {
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002531 ATRACE_CALL();
2532 bool ret = false;
2533
Shuzhen Wang316781a2020-08-18 18:11:01 -07002534 nsecs_t startTime = systemTime();
2535
Jayant Chowdhary646c31b2020-01-30 13:09:59 -08002536 Mutex::Autolock il(mInterfaceLock);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002537 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
2538
2539 Mutex::Autolock l(mLock);
Emilian Peev0d0191e2020-04-21 17:01:18 -07002540 if (checkAbandonedStreamsLocked()) {
2541 ALOGW("%s: Abandoned stream detected, session parameters can't be applied correctly!",
2542 __FUNCTION__);
2543 return true;
2544 }
2545
Emilian Peev3bead5f2020-05-28 17:29:08 -07002546 status_t rc = NO_ERROR;
2547 bool markClientActive = false;
2548 if (mStatus == STATUS_ACTIVE) {
2549 markClientActive = true;
2550 mPauseStateNotify = true;
2551 mStatusTracker->markComponentIdle(clientStatusId, Fence::NO_FENCE);
2552
2553 rc = internalPauseAndWaitLocked(maxExpectedDuration);
2554 }
2555
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002556 if (rc == NO_ERROR) {
2557 mNeedConfig = true;
2558 rc = configureStreamsLocked(mOperatingMode, sessionParams, /*notifyRequestThread*/ false);
2559 if (rc == NO_ERROR) {
2560 ret = true;
2561 mPauseStateNotify = false;
2562 //Moving to active state while holding 'mLock' is important.
2563 //There could be pending calls to 'create-/deleteStream' which
2564 //will trigger another stream configuration while the already
2565 //present streams end up with outstanding buffers that will
2566 //not get drained.
2567 internalUpdateStatusLocked(STATUS_ACTIVE);
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002568 } else if (rc == DEAD_OBJECT) {
2569 // DEAD_OBJECT can be returned if either the consumer surface is
2570 // abandoned, or the HAL has died.
2571 // - If the HAL has died, configureStreamsLocked call will set
2572 // device to error state,
2573 // - If surface is abandoned, we should not set device to error
2574 // state.
2575 ALOGE("Failed to re-configure camera due to abandoned surface");
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002576 } else {
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002577 SET_ERR_L("Failed to re-configure camera: %d", rc);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002578 }
2579 } else {
2580 ALOGE("%s: Failed to pause streaming: %d", __FUNCTION__, rc);
2581 }
2582
Shuzhen Wang316781a2020-08-18 18:11:01 -07002583 CameraServiceProxyWrapper::logStreamConfigured(mId, mOperatingMode, true /*internalReconfig*/,
2584 ns2ms(systemTime() - startTime));
2585
Emilian Peev3bead5f2020-05-28 17:29:08 -07002586 if (markClientActive) {
2587 mStatusTracker->markComponentActive(clientStatusId);
2588 }
2589
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002590 return ret;
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002591}
2592
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002593status_t Camera3Device::configureStreamsLocked(int operatingMode,
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002594 const CameraMetadata& sessionParams, bool notifyRequestThread) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002595 ATRACE_CALL();
2596 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002597
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002598 if (mStatus != STATUS_UNCONFIGURED && mStatus != STATUS_CONFIGURED) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002599 CLOGE("Not idle");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002600 return INVALID_OPERATION;
2601 }
2602
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08002603 if (operatingMode < 0) {
2604 CLOGE("Invalid operating mode: %d", operatingMode);
2605 return BAD_VALUE;
2606 }
2607
2608 bool isConstrainedHighSpeed =
2609 static_cast<int>(StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE) ==
2610 operatingMode;
2611
2612 if (mOperatingMode != operatingMode) {
2613 mNeedConfig = true;
2614 mIsConstrainedHighSpeedConfiguration = isConstrainedHighSpeed;
2615 mOperatingMode = operatingMode;
2616 }
2617
Shuzhen Wang0cf01cb2019-09-05 13:33:06 -07002618 // In case called from configureStreams, abort queued input buffers not belonging to
2619 // any pending requests.
2620 if (mInputStream != NULL && notifyRequestThread) {
2621 while (true) {
Emilian Peevf4816702020-04-03 15:44:51 -07002622 camera_stream_buffer_t inputBuffer;
Shuzhen Wang83bff122020-11-20 15:51:39 -08002623 camera3::Size inputBufferSize;
Shuzhen Wang0cf01cb2019-09-05 13:33:06 -07002624 status_t res = mInputStream->getInputBuffer(&inputBuffer,
Shuzhen Wang83bff122020-11-20 15:51:39 -08002625 &inputBufferSize, /*respectHalLimit*/ false);
Shuzhen Wang0cf01cb2019-09-05 13:33:06 -07002626 if (res != OK) {
2627 // Exhausted acquiring all input buffers.
2628 break;
2629 }
2630
Emilian Peevf4816702020-04-03 15:44:51 -07002631 inputBuffer.status = CAMERA_BUFFER_STATUS_ERROR;
Shuzhen Wang0cf01cb2019-09-05 13:33:06 -07002632 res = mInputStream->returnInputBuffer(inputBuffer);
2633 if (res != OK) {
2634 ALOGE("%s: %d: couldn't return input buffer while clearing input queue: "
2635 "%s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
2636 }
2637 }
2638 }
2639
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002640 if (!mNeedConfig) {
2641 ALOGV("%s: Skipping config, no stream changes", __FUNCTION__);
2642 return OK;
2643 }
2644
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002645 // Workaround for device HALv3.2 or older spec bug - zero streams requires
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002646 // adding a fake stream instead.
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002647 // TODO: Bug: 17321404 for fixing the HAL spec and removing this workaround.
2648 if (mOutputStreams.size() == 0) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002649 addFakeStreamLocked();
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002650 } else {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002651 tryRemoveFakeStreamLocked();
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002652 }
2653
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002654 // Start configuring the streams
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002655 ALOGV("%s: Camera %s: Starting stream configuration", __FUNCTION__, mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002656
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002657 mPreparerThread->pause();
2658
Emilian Peevf4816702020-04-03 15:44:51 -07002659 camera_stream_configuration config;
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -08002660 config.operation_mode = mOperatingMode;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002661 config.num_streams = (mInputStream != NULL) + mOutputStreams.size();
Shuzhen Wang83bff122020-11-20 15:51:39 -08002662 config.input_is_multi_resolution = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002663
Emilian Peevf4816702020-04-03 15:44:51 -07002664 Vector<camera3::camera_stream_t*> streams;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002665 streams.setCapacity(config.num_streams);
Emilian Peev192ee832018-01-31 14:46:47 +00002666 std::vector<uint32_t> bufferSizes(config.num_streams, 0);
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002667
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002668
2669 if (mInputStream != NULL) {
Emilian Peevf4816702020-04-03 15:44:51 -07002670 camera3::camera_stream_t *inputStream;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002671 inputStream = mInputStream->startConfiguration();
2672 if (inputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002673 CLOGE("Can't start input stream configuration");
2674 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002675 return INVALID_OPERATION;
2676 }
2677 streams.add(inputStream);
Shuzhen Wang83bff122020-11-20 15:51:39 -08002678
2679 config.input_is_multi_resolution = mIsInputStreamMultiResolution;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002680 }
2681
Shuzhen Wang99080502021-03-07 21:08:20 -08002682 mGroupIdPhysicalCameraMap.clear();
Emilian Peeve23f1d92021-09-20 14:56:01 -07002683 bool composerSurfacePresent = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002684 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Igor Murashkin2fba5842013-04-22 14:03:54 -07002685
2686 // Don't configure bidi streams twice, nor add them twice to the list
2687 if (mOutputStreams[i].get() ==
2688 static_cast<Camera3StreamInterface*>(mInputStream.get())) {
2689
2690 config.num_streams--;
2691 continue;
2692 }
2693
Emilian Peevf4816702020-04-03 15:44:51 -07002694 camera3::camera_stream_t *outputStream;
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002695 outputStream = mOutputStreams[i]->startConfiguration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002696 if (outputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002697 CLOGE("Can't start output stream configuration");
2698 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002699 return INVALID_OPERATION;
2700 }
2701 streams.add(outputStream);
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002702
Shuzhen Wangb7ab1e42019-02-20 15:42:23 -08002703 if (outputStream->format == HAL_PIXEL_FORMAT_BLOB) {
Emilian Peev192ee832018-01-31 14:46:47 +00002704 size_t k = i + ((mInputStream != nullptr) ? 1 : 0); // Input stream if present should
2705 // always occupy the initial entry.
Shuzhen Wangb7ab1e42019-02-20 15:42:23 -08002706 if (outputStream->data_space == HAL_DATASPACE_V0_JFIF) {
2707 bufferSizes[k] = static_cast<uint32_t>(
2708 getJpegBufferSize(outputStream->width, outputStream->height));
2709 } else if (outputStream->data_space ==
2710 static_cast<android_dataspace>(HAL_DATASPACE_JPEG_APP_SEGMENTS)) {
2711 bufferSizes[k] = outputStream->width * outputStream->height;
2712 } else {
2713 ALOGW("%s: Blob dataSpace %d not supported",
2714 __FUNCTION__, outputStream->data_space);
2715 }
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002716 }
Shuzhen Wang99080502021-03-07 21:08:20 -08002717
2718 if (mOutputStreams[i]->isMultiResolution()) {
2719 int32_t streamGroupId = mOutputStreams[i]->getHalStreamGroupId();
2720 const String8& physicalCameraId = mOutputStreams[i]->getPhysicalCameraId();
2721 mGroupIdPhysicalCameraMap[streamGroupId].insert(physicalCameraId);
2722 }
Emilian Peeve23f1d92021-09-20 14:56:01 -07002723
2724 if (outputStream->usage & GraphicBuffer::USAGE_HW_COMPOSER) {
2725 composerSurfacePresent = true;
2726 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002727 }
2728
2729 config.streams = streams.editArray();
2730
2731 // Do the HAL configuration; will potentially touch stream
Shuzhen Wang92653952019-05-07 15:11:43 -07002732 // max_buffers, usage, and priv fields, as well as data_space and format
2733 // fields for IMPLEMENTATION_DEFINED formats.
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002734
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002735 const camera_metadata_t *sessionBuffer = sessionParams.getAndLock();
Emilian Peev192ee832018-01-31 14:46:47 +00002736 res = mInterface->configureStreams(sessionBuffer, &config, bufferSizes);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002737 sessionParams.unlock(sessionBuffer);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002738
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002739 if (res == BAD_VALUE) {
2740 // HAL rejected this set of streams as unsupported, clean up config
2741 // attempt and return to unconfigured state
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002742 CLOGE("Set of requested inputs/outputs not supported by HAL");
2743 cancelStreamsConfigurationLocked();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002744 return BAD_VALUE;
2745 } else if (res != OK) {
2746 // Some other kind of error from configure_streams - this is not
2747 // expected
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002748 SET_ERR_L("Unable to configure streams with HAL: %s (%d)",
2749 strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002750 return res;
2751 }
2752
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002753 // Finish all stream configuration immediately.
2754 // TODO: Try to relax this later back to lazy completion, which should be
2755 // faster
2756
Igor Murashkin073f8572013-05-02 14:59:28 -07002757 if (mInputStream != NULL && mInputStream->isConfiguring()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002758 bool streamReConfigured = false;
2759 res = mInputStream->finishConfiguration(&streamReConfigured);
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002760 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002761 CLOGE("Can't finish configuring input stream %d: %s (%d)",
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002762 mInputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002763 cancelStreamsConfigurationLocked();
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002764 if ((res == NO_INIT || res == DEAD_OBJECT) && mInputStream->isAbandoned()) {
2765 return DEAD_OBJECT;
2766 }
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002767 return BAD_VALUE;
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002768 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002769 if (streamReConfigured) {
2770 mInterface->onStreamReConfigured(mInputStream->getId());
2771 }
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002772 }
2773
2774 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002775 sp<Camera3OutputStreamInterface> outputStream = mOutputStreams[i];
Zhijun He5d677d12016-05-29 16:52:39 -07002776 if (outputStream->isConfiguring() && !outputStream->isConsumerConfigurationDeferred()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002777 bool streamReConfigured = false;
2778 res = outputStream->finishConfiguration(&streamReConfigured);
Igor Murashkin073f8572013-05-02 14:59:28 -07002779 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002780 CLOGE("Can't finish configuring output stream %d: %s (%d)",
Igor Murashkin073f8572013-05-02 14:59:28 -07002781 outputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002782 cancelStreamsConfigurationLocked();
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002783 if ((res == NO_INIT || res == DEAD_OBJECT) && outputStream->isAbandoned()) {
2784 return DEAD_OBJECT;
2785 }
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002786 return BAD_VALUE;
Igor Murashkin073f8572013-05-02 14:59:28 -07002787 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002788 if (streamReConfigured) {
2789 mInterface->onStreamReConfigured(outputStream->getId());
2790 }
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002791 }
2792 }
2793
Emilian Peeve23f1d92021-09-20 14:56:01 -07002794 mRequestThread->setComposerSurface(composerSurfacePresent);
2795
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002796 // Request thread needs to know to avoid using repeat-last-settings protocol
2797 // across configure_streams() calls
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002798 if (notifyRequestThread) {
Shuzhen Wang99080502021-03-07 21:08:20 -08002799 mRequestThread->configurationComplete(mIsConstrainedHighSpeedConfiguration,
2800 sessionParams, mGroupIdPhysicalCameraMap);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002801 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002802
Zhijun He90f7c372016-08-16 16:19:43 -07002803 char value[PROPERTY_VALUE_MAX];
2804 property_get("camera.fifo.disable", value, "0");
2805 int32_t disableFifo = atoi(value);
2806 if (disableFifo != 1) {
2807 // Boost priority of request thread to SCHED_FIFO.
2808 pid_t requestThreadTid = mRequestThread->getTid();
2809 res = requestPriority(getpid(), requestThreadTid,
Mikhail Naganov83f04272017-02-07 10:45:09 -08002810 kRequestThreadPriority, /*isForApp*/ false, /*asynchronous*/ false);
Zhijun He90f7c372016-08-16 16:19:43 -07002811 if (res != OK) {
2812 ALOGW("Can't set realtime priority for request processing thread: %s (%d)",
2813 strerror(-res), res);
2814 } else {
2815 ALOGD("Set real time priority for request queue thread (tid %d)", requestThreadTid);
2816 }
Eino-Ville Talvalaf99498e2015-09-25 16:52:55 -07002817 }
2818
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002819 // Update device state
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002820 const camera_metadata_t *newSessionParams = sessionParams.getAndLock();
2821 const camera_metadata_t *currentSessionParams = mSessionParams.getAndLock();
2822 bool updateSessionParams = (newSessionParams != currentSessionParams) ? true : false;
2823 sessionParams.unlock(newSessionParams);
2824 mSessionParams.unlock(currentSessionParams);
2825 if (updateSessionParams) {
2826 mSessionParams = sessionParams;
2827 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002828
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002829 mNeedConfig = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002830
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002831 internalUpdateStatusLocked((mFakeStreamId == NO_STREAM) ?
Ruben Brunk183f0562015-08-12 12:55:02 -07002832 STATUS_CONFIGURED : STATUS_UNCONFIGURED);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002833
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002834 ALOGV("%s: Camera %s: Stream configuration complete", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002835
Zhijun He0a210512014-07-24 13:45:15 -07002836 // tear down the deleted streams after configure streams.
2837 mDeletedStreams.clear();
2838
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002839 auto rc = mPreparerThread->resume();
2840 if (rc != OK) {
2841 SET_ERR_L("%s: Camera %s: Preparer thread failed to resume!", __FUNCTION__, mId.string());
2842 return rc;
2843 }
2844
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002845 if (mFakeStreamId == NO_STREAM) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07002846 mRequestBufferSM.onStreamsConfigured();
2847 }
2848
Cliff Wuc2ad9c82021-04-21 00:58:58 +08002849 // Since the streams configuration of the injection camera is based on the internal camera, we
2850 // must wait until the internal camera configure streams before calling injectCamera() to
2851 // configure the injection streams.
2852 if (mInjectionMethods->isInjecting()) {
2853 ALOGV("%s: Injection camera %s: Start to configure streams.",
2854 __FUNCTION__, mInjectionMethods->getInjectedCamId().string());
2855 res = mInjectionMethods->injectCamera(config, bufferSizes);
2856 if (res != OK) {
2857 ALOGE("Can't finish inject camera process!");
2858 return res;
2859 }
2860 }
2861
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002862 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002863}
2864
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002865status_t Camera3Device::addFakeStreamLocked() {
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002866 ATRACE_CALL();
2867 status_t res;
2868
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002869 if (mFakeStreamId != NO_STREAM) {
2870 // Should never be adding a second fake stream when one is already
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002871 // active
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002872 SET_ERR_L("%s: Camera %s: A fake stream already exists!",
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002873 __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002874 return INVALID_OPERATION;
2875 }
2876
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002877 ALOGV("%s: Camera %s: Adding a fake stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002878
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002879 sp<Camera3OutputStreamInterface> fakeStream =
2880 new Camera3FakeStream(mNextStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002881
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002882 res = mOutputStreams.add(mNextStreamId, fakeStream);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002883 if (res < 0) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002884 SET_ERR_L("Can't add fake stream to set: %s (%d)", strerror(-res), res);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002885 return res;
2886 }
2887
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002888 mFakeStreamId = mNextStreamId;
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002889 mNextStreamId++;
2890
2891 return OK;
2892}
2893
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002894status_t Camera3Device::tryRemoveFakeStreamLocked() {
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002895 ATRACE_CALL();
2896 status_t res;
2897
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002898 if (mFakeStreamId == NO_STREAM) return OK;
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002899 if (mOutputStreams.size() == 1) return OK;
2900
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002901 ALOGV("%s: Camera %s: Removing the fake stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002902
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002903 // Ok, have a fake stream and there's at least one other output stream,
2904 // so remove the fake
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002905
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002906 sp<Camera3StreamInterface> deletedStream = mOutputStreams.get(mFakeStreamId);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002907 if (deletedStream == nullptr) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002908 SET_ERR_L("Fake stream %d does not appear to exist", mFakeStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002909 return INVALID_OPERATION;
2910 }
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002911 mOutputStreams.remove(mFakeStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002912
2913 // Free up the stream endpoint so that it can be used by some other stream
2914 res = deletedStream->disconnect();
2915 if (res != OK) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002916 SET_ERR_L("Can't disconnect deleted fake stream %d", mFakeStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002917 // fall through since we want to still list the stream as deleted.
2918 }
2919 mDeletedStreams.add(deletedStream);
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002920 mFakeStreamId = NO_STREAM;
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002921
2922 return res;
2923}
2924
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002925void Camera3Device::setErrorState(const char *fmt, ...) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002926 ATRACE_CALL();
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002927 Mutex::Autolock l(mLock);
2928 va_list args;
2929 va_start(args, fmt);
2930
2931 setErrorStateLockedV(fmt, args);
2932
2933 va_end(args);
2934}
2935
2936void Camera3Device::setErrorStateV(const char *fmt, va_list args) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002937 ATRACE_CALL();
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002938 Mutex::Autolock l(mLock);
2939 setErrorStateLockedV(fmt, args);
2940}
2941
2942void Camera3Device::setErrorStateLocked(const char *fmt, ...) {
2943 va_list args;
2944 va_start(args, fmt);
2945
2946 setErrorStateLockedV(fmt, args);
2947
2948 va_end(args);
2949}
2950
2951void Camera3Device::setErrorStateLockedV(const char *fmt, va_list args) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002952 // Print out all error messages to log
2953 String8 errorCause = String8::formatV(fmt, args);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002954 ALOGE("Camera %s: %s", mId.string(), errorCause.string());
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002955
2956 // But only do error state transition steps for the first error
Zhijun Heb05eeae2013-06-06 13:51:22 -07002957 if (mStatus == STATUS_ERROR || mStatus == STATUS_UNINITIALIZED) return;
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002958
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002959 mErrorCause = errorCause;
2960
Yin-Chia Yeh3d145ae2017-07-27 12:47:03 -07002961 if (mRequestThread != nullptr) {
2962 mRequestThread->setPaused(true);
2963 }
Ruben Brunk183f0562015-08-12 12:55:02 -07002964 internalUpdateStatusLocked(STATUS_ERROR);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002965
2966 // Notify upstream about a device error
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002967 sp<NotificationListener> listener = mListener.promote();
2968 if (listener != NULL) {
2969 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002970 CaptureResultExtras());
Shuzhen Wang316781a2020-08-18 18:11:01 -07002971 mSessionStatsBuilder.onDeviceError();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002972 }
2973
2974 // Save stack trace. View by dumping it later.
2975 CameraTraces::saveTrace();
2976 // TODO: consider adding errorCause and client pid/procname
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002977}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002978
2979/**
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002980 * In-flight request management
2981 */
2982
Jianing Weicb0652e2014-03-12 18:29:36 -07002983status_t Camera3Device::registerInFlight(uint32_t frameNumber,
Chien-Yu Chend196d612015-06-22 19:49:01 -07002984 int32_t numBuffers, CaptureResultExtras resultExtras, bool hasInput,
Shuzhen Wang5c22c152017-12-31 17:12:25 -08002985 bool hasAppCallback, nsecs_t maxExpectedDuration,
Shuzhen Wang99080502021-03-07 21:08:20 -08002986 const std::set<std::set<String8>>& physicalCameraIds,
2987 bool isStillCapture, bool isZslCapture, bool rotateAndCropAuto,
2988 const std::set<std::string>& cameraIdsWithZoom,
Shuzhen Wang316781a2020-08-18 18:11:01 -07002989 const SurfaceMap& outputSurfaces, nsecs_t requestTimeNs) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002990 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002991 std::lock_guard<std::mutex> l(mInFlightLock);
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002992
2993 ssize_t res;
Chien-Yu Chend196d612015-06-22 19:49:01 -07002994 res = mInFlightMap.add(frameNumber, InFlightRequest(numBuffers, resultExtras, hasInput,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07002995 hasAppCallback, maxExpectedDuration, physicalCameraIds, isStillCapture, isZslCapture,
Shuzhen Wang316781a2020-08-18 18:11:01 -07002996 rotateAndCropAuto, cameraIdsWithZoom, requestTimeNs, outputSurfaces));
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002997 if (res < 0) return res;
2998
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07002999 if (mInFlightMap.size() == 1) {
Emilian Peev26d975d2018-07-05 14:52:57 +01003000 // Hold a separate dedicated tracker lock to prevent race with disconnect and also
3001 // avoid a deadlock during reprocess requests.
3002 Mutex::Autolock l(mTrackerLock);
Yin-Chia Yeh38dfde52017-06-27 17:13:33 -07003003 if (mStatusTracker != nullptr) {
3004 mStatusTracker->markComponentActive(mInFlightStatusId);
3005 }
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07003006 }
3007
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003008 mExpectedInflightDuration += maxExpectedDuration;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003009 return OK;
3010}
3011
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003012void Camera3Device::onInflightEntryRemovedLocked(nsecs_t duration) {
Shuzhen Wangcadb3302016-11-04 14:17:56 -07003013 // Indicate idle inFlightMap to the status tracker
3014 if (mInFlightMap.size() == 0) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07003015 mRequestBufferSM.onInflightMapEmpty();
Emilian Peev26d975d2018-07-05 14:52:57 +01003016 // Hold a separate dedicated tracker lock to prevent race with disconnect and also
3017 // avoid a deadlock during reprocess requests.
3018 Mutex::Autolock l(mTrackerLock);
Yin-Chia Yeh38dfde52017-06-27 17:13:33 -07003019 if (mStatusTracker != nullptr) {
3020 mStatusTracker->markComponentIdle(mInFlightStatusId, Fence::NO_FENCE);
3021 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07003022 }
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003023 mExpectedInflightDuration -= duration;
Shuzhen Wangcadb3302016-11-04 14:17:56 -07003024}
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003025
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003026void Camera3Device::checkInflightMapLengthLocked() {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04003027 // Validation check - if we have too many in-flight frames with long total inflight duration,
Yin-Chia Yeh99fd0972019-06-27 14:22:44 -07003028 // something has likely gone wrong. This might still be legit only if application send in
3029 // a long burst of long exposure requests.
3030 if (mExpectedInflightDuration > kMinWarnInflightDuration) {
3031 if (!mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() > kInFlightWarnLimit) {
3032 CLOGW("In-flight list too large: %zu, total inflight duration %" PRIu64,
3033 mInFlightMap.size(), mExpectedInflightDuration);
3034 } else if (mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() >
3035 kInFlightWarnLimitHighSpeed) {
3036 CLOGW("In-flight list too large for high speed configuration: %zu,"
3037 "total inflight duration %" PRIu64,
3038 mInFlightMap.size(), mExpectedInflightDuration);
3039 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003040 }
3041}
3042
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003043void Camera3Device::onInflightMapFlushedLocked() {
3044 mExpectedInflightDuration = 0;
3045}
3046
3047void Camera3Device::removeInFlightMapEntryLocked(int idx) {
Jayant Chowdharyd4776262020-06-23 23:45:57 -07003048 ATRACE_HFR_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003049 nsecs_t duration = mInFlightMap.valueAt(idx).maxExpectedDuration;
3050 mInFlightMap.removeItemsAt(idx, 1);
3051
3052 onInflightEntryRemovedLocked(duration);
3053}
3054
3055
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003056void Camera3Device::flushInflightRequests() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003057 ATRACE_CALL();
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003058 sp<NotificationListener> listener;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003059 {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003060 std::lock_guard<std::mutex> l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003061 listener = mListener.promote();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003062 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003063
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003064 FlushInflightReqStates states {
3065 mId, mInFlightLock, mInFlightMap, mUseHalBufManager,
Shuzhen Wang316781a2020-08-18 18:11:01 -07003066 listener, *this, *mInterface, *this, mSessionStatsBuilder};
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003067
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003068 camera3::flushInflightRequests(states);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003069}
3070
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003071CameraMetadata Camera3Device::getLatestRequestLocked() {
Igor Murashkin1e479c02013-09-06 16:55:14 -07003072 ALOGV("%s", __FUNCTION__);
3073
Igor Murashkin1e479c02013-09-06 16:55:14 -07003074 CameraMetadata retVal;
3075
3076 if (mRequestThread != NULL) {
3077 retVal = mRequestThread->getLatestRequest();
3078 }
3079
Igor Murashkin1e479c02013-09-06 16:55:14 -07003080 return retVal;
3081}
3082
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07003083void Camera3Device::monitorMetadata(TagMonitor::eventSource source,
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003084 int64_t frameNumber, nsecs_t timestamp, const CameraMetadata& metadata,
3085 const std::unordered_map<std::string, CameraMetadata>& physicalMetadata) {
3086
3087 mTagMonitor.monitorMetadata(source, frameNumber, timestamp, metadata,
3088 physicalMetadata);
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07003089}
3090
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003091/**
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003092 * HalInterface inner class methods
3093 */
3094
Yifan Hongf79b5542017-04-11 14:44:25 -07003095Camera3Device::HalInterface::HalInterface(
3096 sp<ICameraDeviceSession> &session,
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003097 std::shared_ptr<RequestMetadataQueue> queue,
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003098 bool useHalBufManager, bool supportOfflineProcessing) :
Yifan Hongf79b5542017-04-11 14:44:25 -07003099 mHidlSession(session),
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003100 mRequestMetadataQueue(queue),
Emilian Peev4ec17882019-01-24 17:16:58 -08003101 mUseHalBufManager(useHalBufManager),
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003102 mIsReconfigurationQuerySupported(true),
3103 mSupportOfflineProcessing(supportOfflineProcessing) {
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003104 // Check with hardware service manager if we can downcast these interfaces
3105 // Somewhat expensive, so cache the results at startup
Shuzhen Wang83bff122020-11-20 15:51:39 -08003106 auto castResult_3_7 = device::V3_7::ICameraDeviceSession::castFrom(mHidlSession);
3107 if (castResult_3_7.isOk()) {
3108 mHidlSession_3_7 = castResult_3_7;
3109 }
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003110 auto castResult_3_6 = device::V3_6::ICameraDeviceSession::castFrom(mHidlSession);
3111 if (castResult_3_6.isOk()) {
3112 mHidlSession_3_6 = castResult_3_6;
3113 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003114 auto castResult_3_5 = device::V3_5::ICameraDeviceSession::castFrom(mHidlSession);
3115 if (castResult_3_5.isOk()) {
3116 mHidlSession_3_5 = castResult_3_5;
3117 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003118 auto castResult_3_4 = device::V3_4::ICameraDeviceSession::castFrom(mHidlSession);
3119 if (castResult_3_4.isOk()) {
3120 mHidlSession_3_4 = castResult_3_4;
3121 }
3122 auto castResult_3_3 = device::V3_3::ICameraDeviceSession::castFrom(mHidlSession);
3123 if (castResult_3_3.isOk()) {
3124 mHidlSession_3_3 = castResult_3_3;
3125 }
3126}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003127
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003128Camera3Device::HalInterface::HalInterface() :
3129 mUseHalBufManager(false),
3130 mSupportOfflineProcessing(false) {}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003131
3132Camera3Device::HalInterface::HalInterface(const HalInterface& other) :
Yifan Hongf79b5542017-04-11 14:44:25 -07003133 mHidlSession(other.mHidlSession),
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003134 mRequestMetadataQueue(other.mRequestMetadataQueue),
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003135 mUseHalBufManager(other.mUseHalBufManager),
3136 mSupportOfflineProcessing(other.mSupportOfflineProcessing) {}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003137
3138bool Camera3Device::HalInterface::valid() {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003139 return (mHidlSession != nullptr);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003140}
3141
3142void Camera3Device::HalInterface::clear() {
Shuzhen Wang83bff122020-11-20 15:51:39 -08003143 mHidlSession_3_7.clear();
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003144 mHidlSession_3_6.clear();
Emilian Peev644a3e12018-11-23 13:52:39 +00003145 mHidlSession_3_5.clear();
Emilian Peev9e740b02018-01-30 18:28:03 +00003146 mHidlSession_3_4.clear();
3147 mHidlSession_3_3.clear();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003148 mHidlSession.clear();
3149}
3150
3151status_t Camera3Device::HalInterface::constructDefaultRequestSettings(
Emilian Peevf4816702020-04-03 15:44:51 -07003152 camera_request_template_t templateId,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003153 /*out*/ camera_metadata_t **requestTemplate) {
3154 ATRACE_NAME("CameraHal::constructDefaultRequestSettings");
3155 if (!valid()) return INVALID_OPERATION;
3156 status_t res = OK;
3157
Emilian Peev31abd0a2017-05-11 18:37:46 +01003158 common::V1_0::Status status;
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003159
3160 auto requestCallback = [&status, &requestTemplate]
Emilian Peev31abd0a2017-05-11 18:37:46 +01003161 (common::V1_0::Status s, const device::V3_2::CameraMetadata& request) {
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003162 status = s;
3163 if (status == common::V1_0::Status::OK) {
3164 const camera_metadata *r =
3165 reinterpret_cast<const camera_metadata_t*>(request.data());
3166 size_t expectedSize = request.size();
3167 int ret = validate_camera_metadata_structure(r, &expectedSize);
3168 if (ret == OK || ret == CAMERA_METADATA_VALIDATION_SHIFTED) {
3169 *requestTemplate = clone_camera_metadata(r);
3170 if (*requestTemplate == nullptr) {
3171 ALOGE("%s: Unable to clone camera metadata received from HAL",
3172 __FUNCTION__);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003173 status = common::V1_0::Status::INTERNAL_ERROR;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003174 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003175 } else {
3176 ALOGE("%s: Malformed camera metadata received from HAL", __FUNCTION__);
3177 status = common::V1_0::Status::INTERNAL_ERROR;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003178 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003179 }
3180 };
3181 hardware::Return<void> err;
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003182 RequestTemplate id;
3183 switch (templateId) {
Emilian Peevf4816702020-04-03 15:44:51 -07003184 case CAMERA_TEMPLATE_PREVIEW:
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003185 id = RequestTemplate::PREVIEW;
3186 break;
Emilian Peevf4816702020-04-03 15:44:51 -07003187 case CAMERA_TEMPLATE_STILL_CAPTURE:
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003188 id = RequestTemplate::STILL_CAPTURE;
3189 break;
Emilian Peevf4816702020-04-03 15:44:51 -07003190 case CAMERA_TEMPLATE_VIDEO_RECORD:
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003191 id = RequestTemplate::VIDEO_RECORD;
3192 break;
Emilian Peevf4816702020-04-03 15:44:51 -07003193 case CAMERA_TEMPLATE_VIDEO_SNAPSHOT:
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003194 id = RequestTemplate::VIDEO_SNAPSHOT;
3195 break;
Emilian Peevf4816702020-04-03 15:44:51 -07003196 case CAMERA_TEMPLATE_ZERO_SHUTTER_LAG:
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003197 id = RequestTemplate::ZERO_SHUTTER_LAG;
3198 break;
Emilian Peevf4816702020-04-03 15:44:51 -07003199 case CAMERA_TEMPLATE_MANUAL:
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003200 id = RequestTemplate::MANUAL;
3201 break;
3202 default:
3203 // Unknown template ID, or this HAL is too old to support it
3204 return BAD_VALUE;
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003205 }
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003206 err = mHidlSession->constructDefaultRequestSettings(id, requestCallback);
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003207
Emilian Peev31abd0a2017-05-11 18:37:46 +01003208 if (!err.isOk()) {
3209 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3210 res = DEAD_OBJECT;
3211 } else {
3212 res = CameraProviderManager::mapToStatusT(status);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003213 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003214
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003215 return res;
3216}
3217
Emilian Peev4ec17882019-01-24 17:16:58 -08003218bool Camera3Device::HalInterface::isReconfigurationRequired(CameraMetadata& oldSessionParams,
3219 CameraMetadata& newSessionParams) {
3220 // We do reconfiguration by default;
3221 bool ret = true;
3222 if ((mHidlSession_3_5 != nullptr) && mIsReconfigurationQuerySupported) {
3223 android::hardware::hidl_vec<uint8_t> oldParams, newParams;
3224 camera_metadata_t* oldSessioMeta = const_cast<camera_metadata_t*>(
3225 oldSessionParams.getAndLock());
3226 camera_metadata_t* newSessioMeta = const_cast<camera_metadata_t*>(
3227 newSessionParams.getAndLock());
3228 oldParams.setToExternal(reinterpret_cast<uint8_t*>(oldSessioMeta),
3229 get_camera_metadata_size(oldSessioMeta));
3230 newParams.setToExternal(reinterpret_cast<uint8_t*>(newSessioMeta),
3231 get_camera_metadata_size(newSessioMeta));
3232 hardware::camera::common::V1_0::Status callStatus;
3233 bool required;
3234 auto hidlCb = [&callStatus, &required] (hardware::camera::common::V1_0::Status s,
3235 bool requiredFlag) {
3236 callStatus = s;
3237 required = requiredFlag;
3238 };
3239 auto err = mHidlSession_3_5->isReconfigurationRequired(oldParams, newParams, hidlCb);
3240 oldSessionParams.unlock(oldSessioMeta);
3241 newSessionParams.unlock(newSessioMeta);
3242 if (err.isOk()) {
3243 switch (callStatus) {
3244 case hardware::camera::common::V1_0::Status::OK:
3245 ret = required;
3246 break;
3247 case hardware::camera::common::V1_0::Status::METHOD_NOT_SUPPORTED:
3248 mIsReconfigurationQuerySupported = false;
3249 ret = true;
3250 break;
3251 default:
3252 ALOGV("%s: Reconfiguration query failed: %d", __FUNCTION__, callStatus);
3253 ret = true;
3254 }
3255 } else {
3256 ALOGE("%s: Unexpected binder error: %s", __FUNCTION__, err.description().c_str());
3257 ret = true;
3258 }
3259 }
3260
3261 return ret;
3262}
3263
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003264status_t Camera3Device::HalInterface::configureStreams(const camera_metadata_t *sessionParams,
Emilian Peevf4816702020-04-03 15:44:51 -07003265 camera_stream_configuration *config, const std::vector<uint32_t>& bufferSizes) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003266 ATRACE_NAME("CameraHal::configureStreams");
3267 if (!valid()) return INVALID_OPERATION;
3268 status_t res = OK;
3269
Shuzhen Wang83bff122020-11-20 15:51:39 -08003270 if (config->input_is_multi_resolution && mHidlSession_3_7 == nullptr) {
3271 ALOGE("%s: Camera device doesn't support multi-resolution input stream", __FUNCTION__);
3272 return BAD_VALUE;
3273 }
3274
Emilian Peev31abd0a2017-05-11 18:37:46 +01003275 // Convert stream config to HIDL
3276 std::set<int> activeStreams;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003277 device::V3_2::StreamConfiguration requestedConfiguration3_2;
3278 device::V3_4::StreamConfiguration requestedConfiguration3_4;
Shuzhen Wang83bff122020-11-20 15:51:39 -08003279 device::V3_7::StreamConfiguration requestedConfiguration3_7;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003280 requestedConfiguration3_2.streams.resize(config->num_streams);
3281 requestedConfiguration3_4.streams.resize(config->num_streams);
Shuzhen Wang83bff122020-11-20 15:51:39 -08003282 requestedConfiguration3_7.streams.resize(config->num_streams);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003283 for (size_t i = 0; i < config->num_streams; i++) {
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003284 device::V3_2::Stream &dst3_2 = requestedConfiguration3_2.streams[i];
3285 device::V3_4::Stream &dst3_4 = requestedConfiguration3_4.streams[i];
Shuzhen Wang83bff122020-11-20 15:51:39 -08003286 device::V3_7::Stream &dst3_7 = requestedConfiguration3_7.streams[i];
Emilian Peevf4816702020-04-03 15:44:51 -07003287 camera3::camera_stream_t *src = config->streams[i];
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003288
Emilian Peev31abd0a2017-05-11 18:37:46 +01003289 Camera3Stream* cam3stream = Camera3Stream::cast(src);
3290 cam3stream->setBufferFreedListener(this);
3291 int streamId = cam3stream->getId();
3292 StreamType streamType;
3293 switch (src->stream_type) {
Emilian Peevf4816702020-04-03 15:44:51 -07003294 case CAMERA_STREAM_OUTPUT:
Emilian Peev31abd0a2017-05-11 18:37:46 +01003295 streamType = StreamType::OUTPUT;
3296 break;
Emilian Peevf4816702020-04-03 15:44:51 -07003297 case CAMERA_STREAM_INPUT:
Emilian Peev31abd0a2017-05-11 18:37:46 +01003298 streamType = StreamType::INPUT;
3299 break;
3300 default:
3301 ALOGE("%s: Stream %d: Unsupported stream type %d",
3302 __FUNCTION__, streamId, config->streams[i]->stream_type);
3303 return BAD_VALUE;
3304 }
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003305 dst3_2.id = streamId;
3306 dst3_2.streamType = streamType;
3307 dst3_2.width = src->width;
3308 dst3_2.height = src->height;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003309 dst3_2.usage = mapToConsumerUsage(cam3stream->getUsage());
Emilian Peevf4816702020-04-03 15:44:51 -07003310 dst3_2.rotation = mapToStreamRotation((camera_stream_rotation_t) src->rotation);
Shuzhen Wang92653952019-05-07 15:11:43 -07003311 // For HidlSession version 3.5 or newer, the format and dataSpace sent
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08003312 // to HAL are original, not the overridden ones.
Shuzhen Wang92653952019-05-07 15:11:43 -07003313 if (mHidlSession_3_5 != nullptr) {
3314 dst3_2.format = mapToPixelFormat(cam3stream->isFormatOverridden() ?
3315 cam3stream->getOriginalFormat() : src->format);
3316 dst3_2.dataSpace = mapToHidlDataspace(cam3stream->isDataSpaceOverridden() ?
3317 cam3stream->getOriginalDataSpace() : src->data_space);
3318 } else {
3319 dst3_2.format = mapToPixelFormat(src->format);
3320 dst3_2.dataSpace = mapToHidlDataspace(src->data_space);
3321 }
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003322 dst3_4.v3_2 = dst3_2;
Emilian Peev192ee832018-01-31 14:46:47 +00003323 dst3_4.bufferSize = bufferSizes[i];
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003324 if (src->physical_camera_id != nullptr) {
3325 dst3_4.physicalCameraId = src->physical_camera_id;
3326 }
Shuzhen Wang83bff122020-11-20 15:51:39 -08003327 dst3_7.v3_4 = dst3_4;
3328 dst3_7.groupId = cam3stream->getHalStreamGroupId();
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08003329 dst3_7.sensorPixelModesUsed.resize(src->sensor_pixel_modes_used.size());
3330 size_t j = 0;
3331 for (int mode : src->sensor_pixel_modes_used) {
3332 dst3_7.sensorPixelModesUsed[j++] =
3333 static_cast<CameraMetadataEnumAndroidSensorPixelMode>(mode);
3334 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003335 activeStreams.insert(streamId);
3336 // Create Buffer ID map if necessary
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003337 mBufferRecords.tryCreateBufferCache(streamId);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003338 }
3339 // remove BufferIdMap for deleted streams
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003340 mBufferRecords.removeInactiveBufferCaches(activeStreams);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003341
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003342 StreamConfigurationMode operationMode;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003343 res = mapToStreamConfigurationMode(
Emilian Peevf4816702020-04-03 15:44:51 -07003344 (camera_stream_configuration_mode_t) config->operation_mode,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003345 /*out*/ &operationMode);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003346 if (res != OK) {
3347 return res;
3348 }
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003349 requestedConfiguration3_2.operationMode = operationMode;
3350 requestedConfiguration3_4.operationMode = operationMode;
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08003351 requestedConfiguration3_7.operationMode = operationMode;
3352 size_t sessionParamSize = get_camera_metadata_size(sessionParams);
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003353 requestedConfiguration3_4.sessionParams.setToExternal(
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003354 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(sessionParams)),
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08003355 sessionParamSize);
Shuzhen Wang83bff122020-11-20 15:51:39 -08003356 requestedConfiguration3_7.operationMode = operationMode;
3357 requestedConfiguration3_7.sessionParams.setToExternal(
3358 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(sessionParams)),
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08003359 sessionParamSize);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003360
Emilian Peev31abd0a2017-05-11 18:37:46 +01003361 // Invoke configureStreams
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003362 device::V3_3::HalStreamConfiguration finalConfiguration;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003363 device::V3_4::HalStreamConfiguration finalConfiguration3_4;
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003364 device::V3_6::HalStreamConfiguration finalConfiguration3_6;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003365 common::V1_0::Status status;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003366
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003367 auto configStream34Cb = [&status, &finalConfiguration3_4]
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003368 (common::V1_0::Status s, const device::V3_4::HalStreamConfiguration& halConfiguration) {
3369 finalConfiguration3_4 = halConfiguration;
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003370 status = s;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003371 };
3372
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003373 auto configStream36Cb = [&status, &finalConfiguration3_6]
3374 (common::V1_0::Status s, const device::V3_6::HalStreamConfiguration& halConfiguration) {
3375 finalConfiguration3_6 = halConfiguration;
3376 status = s;
3377 };
3378
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003379 auto postprocConfigStream34 = [&finalConfiguration, &finalConfiguration3_4]
3380 (hardware::Return<void>& err) -> status_t {
3381 if (!err.isOk()) {
3382 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3383 return DEAD_OBJECT;
3384 }
3385 finalConfiguration.streams.resize(finalConfiguration3_4.streams.size());
3386 for (size_t i = 0; i < finalConfiguration3_4.streams.size(); i++) {
3387 finalConfiguration.streams[i] = finalConfiguration3_4.streams[i].v3_3;
3388 }
3389 return OK;
3390 };
3391
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003392 auto postprocConfigStream36 = [&finalConfiguration, &finalConfiguration3_6]
3393 (hardware::Return<void>& err) -> status_t {
3394 if (!err.isOk()) {
3395 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3396 return DEAD_OBJECT;
3397 }
3398 finalConfiguration.streams.resize(finalConfiguration3_6.streams.size());
3399 for (size_t i = 0; i < finalConfiguration3_6.streams.size(); i++) {
3400 finalConfiguration.streams[i] = finalConfiguration3_6.streams[i].v3_4.v3_3;
3401 }
3402 return OK;
3403 };
3404
Shuzhen Wang92653952019-05-07 15:11:43 -07003405 // See which version of HAL we have
Shuzhen Wang83bff122020-11-20 15:51:39 -08003406 if (mHidlSession_3_7 != nullptr) {
3407 ALOGV("%s: v3.7 device found", __FUNCTION__);
3408 requestedConfiguration3_7.streamConfigCounter = mNextStreamConfigCounter++;
3409 requestedConfiguration3_7.multiResolutionInputImage = config->input_is_multi_resolution;
3410 auto err = mHidlSession_3_7->configureStreams_3_7(
3411 requestedConfiguration3_7, configStream36Cb);
3412 res = postprocConfigStream36(err);
3413 if (res != OK) {
3414 return res;
3415 }
3416 } else if (mHidlSession_3_6 != nullptr) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003417 ALOGV("%s: v3.6 device found", __FUNCTION__);
3418 device::V3_5::StreamConfiguration requestedConfiguration3_5;
3419 requestedConfiguration3_5.v3_4 = requestedConfiguration3_4;
3420 requestedConfiguration3_5.streamConfigCounter = mNextStreamConfigCounter++;
3421 auto err = mHidlSession_3_6->configureStreams_3_6(
3422 requestedConfiguration3_5, configStream36Cb);
3423 res = postprocConfigStream36(err);
3424 if (res != OK) {
3425 return res;
3426 }
3427 } else if (mHidlSession_3_5 != nullptr) {
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003428 ALOGV("%s: v3.5 device found", __FUNCTION__);
3429 device::V3_5::StreamConfiguration requestedConfiguration3_5;
3430 requestedConfiguration3_5.v3_4 = requestedConfiguration3_4;
3431 requestedConfiguration3_5.streamConfigCounter = mNextStreamConfigCounter++;
3432 auto err = mHidlSession_3_5->configureStreams_3_5(
3433 requestedConfiguration3_5, configStream34Cb);
3434 res = postprocConfigStream34(err);
3435 if (res != OK) {
3436 return res;
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003437 }
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003438 } else if (mHidlSession_3_4 != nullptr) {
3439 // We do; use v3.4 for the call
3440 ALOGV("%s: v3.4 device found", __FUNCTION__);
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003441 auto err = mHidlSession_3_4->configureStreams_3_4(
3442 requestedConfiguration3_4, configStream34Cb);
3443 res = postprocConfigStream34(err);
3444 if (res != OK) {
3445 return res;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003446 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003447 } else if (mHidlSession_3_3 != nullptr) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003448 // We do; use v3.3 for the call
3449 ALOGV("%s: v3.3 device found", __FUNCTION__);
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003450 auto err = mHidlSession_3_3->configureStreams_3_3(requestedConfiguration3_2,
Emilian Peev31abd0a2017-05-11 18:37:46 +01003451 [&status, &finalConfiguration]
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003452 (common::V1_0::Status s, const device::V3_3::HalStreamConfiguration& halConfiguration) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003453 finalConfiguration = halConfiguration;
3454 status = s;
3455 });
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003456 if (!err.isOk()) {
3457 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3458 return DEAD_OBJECT;
3459 }
3460 } else {
3461 // We don't; use v3.2 call and construct a v3.3 HalStreamConfiguration
3462 ALOGV("%s: v3.2 device found", __FUNCTION__);
3463 HalStreamConfiguration finalConfiguration_3_2;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003464 auto err = mHidlSession->configureStreams(requestedConfiguration3_2,
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003465 [&status, &finalConfiguration_3_2]
3466 (common::V1_0::Status s, const HalStreamConfiguration& halConfiguration) {
3467 finalConfiguration_3_2 = halConfiguration;
3468 status = s;
3469 });
3470 if (!err.isOk()) {
3471 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3472 return DEAD_OBJECT;
3473 }
3474 finalConfiguration.streams.resize(finalConfiguration_3_2.streams.size());
3475 for (size_t i = 0; i < finalConfiguration_3_2.streams.size(); i++) {
3476 finalConfiguration.streams[i].v3_2 = finalConfiguration_3_2.streams[i];
3477 finalConfiguration.streams[i].overrideDataSpace =
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003478 requestedConfiguration3_2.streams[i].dataSpace;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003479 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003480 }
3481
3482 if (status != common::V1_0::Status::OK ) {
3483 return CameraProviderManager::mapToStatusT(status);
3484 }
3485
3486 // And convert output stream configuration from HIDL
3487
3488 for (size_t i = 0; i < config->num_streams; i++) {
Emilian Peevf4816702020-04-03 15:44:51 -07003489 camera3::camera_stream_t *dst = config->streams[i];
Emilian Peev31abd0a2017-05-11 18:37:46 +01003490 int streamId = Camera3Stream::cast(dst)->getId();
3491
3492 // Start scan at i, with the assumption that the stream order matches
3493 size_t realIdx = i;
3494 bool found = false;
Eino-Ville Talvala370875f2019-04-12 12:40:27 -07003495 size_t halStreamCount = finalConfiguration.streams.size();
3496 for (size_t idx = 0; idx < halStreamCount; idx++) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003497 if (finalConfiguration.streams[realIdx].v3_2.id == streamId) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003498 found = true;
3499 break;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003500 }
Eino-Ville Talvala370875f2019-04-12 12:40:27 -07003501 realIdx = (realIdx >= halStreamCount - 1) ? 0 : realIdx + 1;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003502 }
3503 if (!found) {
3504 ALOGE("%s: Stream %d not found in stream configuration response from HAL",
3505 __FUNCTION__, streamId);
3506 return INVALID_OPERATION;
3507 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003508 device::V3_3::HalStream &src = finalConfiguration.streams[realIdx];
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003509 device::V3_6::HalStream &src_36 = finalConfiguration3_6.streams[realIdx];
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003510
Emilian Peev710c1422017-08-30 11:19:38 +01003511 Camera3Stream* dstStream = Camera3Stream::cast(dst);
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003512 int overrideFormat = mapToFrameworkFormat(src.v3_2.overrideFormat);
3513 android_dataspace overrideDataSpace = mapToFrameworkDataspace(src.overrideDataSpace);
3514
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003515 if (mHidlSession_3_6 != nullptr) {
3516 dstStream->setOfflineProcessingSupport(src_36.supportOffline);
3517 }
3518
Yin-Chia Yeh90667662019-07-01 15:45:00 -07003519 if (dstStream->getOriginalFormat() != HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
Shuzhen Wang92653952019-05-07 15:11:43 -07003520 dstStream->setFormatOverride(false);
3521 dstStream->setDataSpaceOverride(false);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003522 if (dst->format != overrideFormat) {
3523 ALOGE("%s: Stream %d: Format override not allowed for format 0x%x", __FUNCTION__,
3524 streamId, dst->format);
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003525 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003526 if (dst->data_space != overrideDataSpace) {
3527 ALOGE("%s: Stream %d: DataSpace override not allowed for format 0x%x", __FUNCTION__,
3528 streamId, dst->format);
3529 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003530 } else {
Shuzhen Wang92653952019-05-07 15:11:43 -07003531 bool needFormatOverride =
3532 requestedConfiguration3_2.streams[i].format != src.v3_2.overrideFormat;
3533 bool needDataspaceOverride =
3534 requestedConfiguration3_2.streams[i].dataSpace != src.overrideDataSpace;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003535 // Override allowed with IMPLEMENTATION_DEFINED
Shuzhen Wang92653952019-05-07 15:11:43 -07003536 dstStream->setFormatOverride(needFormatOverride);
3537 dstStream->setDataSpaceOverride(needDataspaceOverride);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003538 dst->format = overrideFormat;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003539 dst->data_space = overrideDataSpace;
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003540 }
3541
Emilian Peevf4816702020-04-03 15:44:51 -07003542 if (dst->stream_type == CAMERA_STREAM_INPUT) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003543 if (src.v3_2.producerUsage != 0) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003544 ALOGE("%s: Stream %d: INPUT streams must have 0 for producer usage",
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003545 __FUNCTION__, streamId);
3546 return INVALID_OPERATION;
3547 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003548 dstStream->setUsage(
3549 mapConsumerToFrameworkUsage(src.v3_2.consumerUsage));
Emilian Peev31abd0a2017-05-11 18:37:46 +01003550 } else {
3551 // OUTPUT
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003552 if (src.v3_2.consumerUsage != 0) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003553 ALOGE("%s: Stream %d: OUTPUT streams must have 0 for consumer usage",
3554 __FUNCTION__, streamId);
3555 return INVALID_OPERATION;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003556 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003557 dstStream->setUsage(
3558 mapProducerToFrameworkUsage(src.v3_2.producerUsage));
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003559 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003560 dst->max_buffers = src.v3_2.maxBuffers;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003561 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003562
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003563 return res;
3564}
3565
Cliff Wuc2ad9c82021-04-21 00:58:58 +08003566status_t Camera3Device::HalInterface::configureInjectedStreams(
3567 const camera_metadata_t* sessionParams, camera_stream_configuration* config,
3568 const std::vector<uint32_t>& bufferSizes,
3569 const CameraMetadata& cameraCharacteristics) {
3570 ATRACE_NAME("InjectionCameraHal::configureStreams");
3571 if (!valid()) return INVALID_OPERATION;
3572 status_t res = OK;
3573
3574 if (config->input_is_multi_resolution) {
3575 ALOGE("%s: Injection camera device doesn't support multi-resolution input "
3576 "stream", __FUNCTION__);
3577 return BAD_VALUE;
3578 }
3579
3580 // Convert stream config to HIDL
3581 std::set<int> activeStreams;
3582 device::V3_2::StreamConfiguration requestedConfiguration3_2;
3583 device::V3_4::StreamConfiguration requestedConfiguration3_4;
3584 device::V3_7::StreamConfiguration requestedConfiguration3_7;
3585 requestedConfiguration3_2.streams.resize(config->num_streams);
3586 requestedConfiguration3_4.streams.resize(config->num_streams);
3587 requestedConfiguration3_7.streams.resize(config->num_streams);
3588 for (size_t i = 0; i < config->num_streams; i++) {
3589 device::V3_2::Stream& dst3_2 = requestedConfiguration3_2.streams[i];
3590 device::V3_4::Stream& dst3_4 = requestedConfiguration3_4.streams[i];
3591 device::V3_7::Stream& dst3_7 = requestedConfiguration3_7.streams[i];
3592 camera3::camera_stream_t* src = config->streams[i];
3593
3594 Camera3Stream* cam3stream = Camera3Stream::cast(src);
3595 cam3stream->setBufferFreedListener(this);
3596 int streamId = cam3stream->getId();
3597 StreamType streamType;
3598 switch (src->stream_type) {
3599 case CAMERA_STREAM_OUTPUT:
3600 streamType = StreamType::OUTPUT;
3601 break;
3602 case CAMERA_STREAM_INPUT:
3603 streamType = StreamType::INPUT;
3604 break;
3605 default:
3606 ALOGE("%s: Stream %d: Unsupported stream type %d", __FUNCTION__,
3607 streamId, config->streams[i]->stream_type);
3608 return BAD_VALUE;
3609 }
3610 dst3_2.id = streamId;
3611 dst3_2.streamType = streamType;
3612 dst3_2.width = src->width;
3613 dst3_2.height = src->height;
3614 dst3_2.usage = mapToConsumerUsage(cam3stream->getUsage());
3615 dst3_2.rotation =
3616 mapToStreamRotation((camera_stream_rotation_t)src->rotation);
3617 // For HidlSession version 3.5 or newer, the format and dataSpace sent
3618 // to HAL are original, not the overridden ones.
3619 if (mHidlSession_3_5 != nullptr) {
3620 dst3_2.format = mapToPixelFormat(cam3stream->isFormatOverridden()
3621 ? cam3stream->getOriginalFormat()
3622 : src->format);
3623 dst3_2.dataSpace =
3624 mapToHidlDataspace(cam3stream->isDataSpaceOverridden()
3625 ? cam3stream->getOriginalDataSpace()
3626 : src->data_space);
3627 } else {
3628 dst3_2.format = mapToPixelFormat(src->format);
3629 dst3_2.dataSpace = mapToHidlDataspace(src->data_space);
3630 }
3631 dst3_4.v3_2 = dst3_2;
3632 dst3_4.bufferSize = bufferSizes[i];
3633 if (src->physical_camera_id != nullptr) {
3634 dst3_4.physicalCameraId = src->physical_camera_id;
3635 }
3636 dst3_7.v3_4 = dst3_4;
3637 dst3_7.groupId = cam3stream->getHalStreamGroupId();
3638 dst3_7.sensorPixelModesUsed.resize(src->sensor_pixel_modes_used.size());
3639 size_t j = 0;
3640 for (int mode : src->sensor_pixel_modes_used) {
3641 dst3_7.sensorPixelModesUsed[j++] =
3642 static_cast<CameraMetadataEnumAndroidSensorPixelMode>(mode);
3643 }
3644 activeStreams.insert(streamId);
3645 // Create Buffer ID map if necessary
3646 mBufferRecords.tryCreateBufferCache(streamId);
3647 }
3648 // remove BufferIdMap for deleted streams
3649 mBufferRecords.removeInactiveBufferCaches(activeStreams);
3650
3651 StreamConfigurationMode operationMode;
3652 res = mapToStreamConfigurationMode(
3653 (camera_stream_configuration_mode_t)config->operation_mode,
3654 /*out*/ &operationMode);
3655 if (res != OK) {
3656 return res;
3657 }
3658 requestedConfiguration3_7.operationMode = operationMode;
3659 size_t sessionParamSize = get_camera_metadata_size(sessionParams);
3660 requestedConfiguration3_7.operationMode = operationMode;
3661 requestedConfiguration3_7.sessionParams.setToExternal(
3662 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(sessionParams)),
3663 sessionParamSize);
3664
3665 // See which version of HAL we have
3666 if (mHidlSession_3_7 != nullptr) {
3667 requestedConfiguration3_7.streamConfigCounter = mNextStreamConfigCounter++;
3668 requestedConfiguration3_7.multiResolutionInputImage =
3669 config->input_is_multi_resolution;
3670
3671 const camera_metadata_t* rawMetadata = cameraCharacteristics.getAndLock();
3672 ::android::hardware::camera::device::V3_2::CameraMetadata hidlChars = {};
3673 hidlChars.setToExternal(
3674 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(rawMetadata)),
3675 get_camera_metadata_size(rawMetadata));
3676 cameraCharacteristics.unlock(rawMetadata);
3677
3678 sp<hardware::camera::device::V3_7::ICameraInjectionSession>
3679 hidlInjectionSession_3_7;
3680 auto castInjectionResult_3_7 =
3681 device::V3_7::ICameraInjectionSession::castFrom(mHidlSession_3_7);
3682 if (castInjectionResult_3_7.isOk()) {
3683 hidlInjectionSession_3_7 = castInjectionResult_3_7;
3684 } else {
3685 ALOGE("%s: Transaction error: %s", __FUNCTION__,
3686 castInjectionResult_3_7.description().c_str());
3687 return DEAD_OBJECT;
3688 }
3689
3690 auto err = hidlInjectionSession_3_7->configureInjectionStreams(
3691 requestedConfiguration3_7, hidlChars);
3692 if (!err.isOk()) {
3693 ALOGE("%s: Transaction error: %s", __FUNCTION__,
3694 err.description().c_str());
3695 return DEAD_OBJECT;
3696 }
3697 } else {
3698 ALOGE("%s: mHidlSession_3_7 does not exist, the lowest version of injection "
3699 "session is 3.7", __FUNCTION__);
3700 return DEAD_OBJECT;
3701 }
3702
3703 return res;
3704}
3705
Emilian Peevf4816702020-04-03 15:44:51 -07003706status_t Camera3Device::HalInterface::wrapAsHidlRequest(camera_capture_request_t* request,
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003707 /*out*/device::V3_2::CaptureRequest* captureRequest,
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003708 /*out*/std::vector<native_handle_t*>* handlesCreated,
3709 /*out*/std::vector<std::pair<int32_t, int32_t>>* inflightBuffers) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003710 ATRACE_CALL();
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003711 if (captureRequest == nullptr || handlesCreated == nullptr || inflightBuffers == nullptr) {
3712 ALOGE("%s: captureRequest (%p), handlesCreated (%p), and inflightBuffers(%p) "
3713 "must not be null", __FUNCTION__, captureRequest, handlesCreated, inflightBuffers);
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003714 return BAD_VALUE;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003715 }
3716
3717 captureRequest->frameNumber = request->frame_number;
Yifan Hongf79b5542017-04-11 14:44:25 -07003718
3719 captureRequest->fmqSettingsSize = 0;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003720
3721 {
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003722 if (request->input_buffer != nullptr) {
3723 int32_t streamId = Camera3Stream::cast(request->input_buffer->stream)->getId();
3724 buffer_handle_t buf = *(request->input_buffer->buffer);
3725 auto pair = getBufferId(buf, streamId);
3726 bool isNewBuffer = pair.first;
3727 uint64_t bufferId = pair.second;
3728 captureRequest->inputBuffer.streamId = streamId;
3729 captureRequest->inputBuffer.bufferId = bufferId;
3730 captureRequest->inputBuffer.buffer = (isNewBuffer) ? buf : nullptr;
3731 captureRequest->inputBuffer.status = BufferStatus::OK;
3732 native_handle_t *acquireFence = nullptr;
3733 if (request->input_buffer->acquire_fence != -1) {
3734 acquireFence = native_handle_create(1,0);
3735 acquireFence->data[0] = request->input_buffer->acquire_fence;
3736 handlesCreated->push_back(acquireFence);
3737 }
3738 captureRequest->inputBuffer.acquireFence = acquireFence;
3739 captureRequest->inputBuffer.releaseFence = nullptr;
3740
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003741 mBufferRecords.pushInflightBuffer(captureRequest->frameNumber, streamId,
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003742 request->input_buffer->buffer);
3743 inflightBuffers->push_back(std::make_pair(captureRequest->frameNumber, streamId));
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003744 } else {
3745 captureRequest->inputBuffer.streamId = -1;
3746 captureRequest->inputBuffer.bufferId = BUFFER_ID_NO_BUFFER;
3747 }
3748
3749 captureRequest->outputBuffers.resize(request->num_output_buffers);
3750 for (size_t i = 0; i < request->num_output_buffers; i++) {
Emilian Peevf4816702020-04-03 15:44:51 -07003751 const camera_stream_buffer_t *src = request->output_buffers + i;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003752 StreamBuffer &dst = captureRequest->outputBuffers[i];
3753 int32_t streamId = Camera3Stream::cast(src->stream)->getId();
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003754 if (src->buffer != nullptr) {
3755 buffer_handle_t buf = *(src->buffer);
3756 auto pair = getBufferId(buf, streamId);
3757 bool isNewBuffer = pair.first;
3758 dst.bufferId = pair.second;
3759 dst.buffer = isNewBuffer ? buf : nullptr;
3760 native_handle_t *acquireFence = nullptr;
3761 if (src->acquire_fence != -1) {
3762 acquireFence = native_handle_create(1,0);
3763 acquireFence->data[0] = src->acquire_fence;
3764 handlesCreated->push_back(acquireFence);
3765 }
3766 dst.acquireFence = acquireFence;
3767 } else if (mUseHalBufManager) {
3768 // HAL buffer management path
3769 dst.bufferId = BUFFER_ID_NO_BUFFER;
3770 dst.buffer = nullptr;
3771 dst.acquireFence = nullptr;
3772 } else {
3773 ALOGE("%s: cannot send a null buffer in capture request!", __FUNCTION__);
3774 return BAD_VALUE;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003775 }
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003776 dst.streamId = streamId;
3777 dst.status = BufferStatus::OK;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003778 dst.releaseFence = nullptr;
3779
Yin-Chia Yeh5f840f82019-03-05 11:59:04 -08003780 // Output buffers are empty when using HAL buffer manager
3781 if (!mUseHalBufManager) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003782 mBufferRecords.pushInflightBuffer(
3783 captureRequest->frameNumber, streamId, src->buffer);
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003784 inflightBuffers->push_back(std::make_pair(captureRequest->frameNumber, streamId));
Yin-Chia Yeh5f840f82019-03-05 11:59:04 -08003785 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003786 }
3787 }
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003788 return OK;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003789}
3790
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003791void Camera3Device::HalInterface::cleanupNativeHandles(
3792 std::vector<native_handle_t*> *handles, bool closeFd) {
3793 if (handles == nullptr) {
3794 return;
3795 }
3796 if (closeFd) {
3797 for (auto& handle : *handles) {
3798 native_handle_close(handle);
3799 }
3800 }
3801 for (auto& handle : *handles) {
3802 native_handle_delete(handle);
3803 }
3804 handles->clear();
3805 return;
3806}
3807
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003808status_t Camera3Device::HalInterface::processBatchCaptureRequests(
Emilian Peevf4816702020-04-03 15:44:51 -07003809 std::vector<camera_capture_request_t*>& requests,/*out*/uint32_t* numRequestProcessed) {
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003810 ATRACE_NAME("CameraHal::processBatchCaptureRequests");
3811 if (!valid()) return INVALID_OPERATION;
3812
Emilian Peevaebbe412018-01-15 13:53:24 +00003813 sp<device::V3_4::ICameraDeviceSession> hidlSession_3_4;
Shuzhen Wang83bff122020-11-20 15:51:39 -08003814 sp<device::V3_7::ICameraDeviceSession> hidlSession_3_7;
3815 auto castResult_3_7 = device::V3_7::ICameraDeviceSession::castFrom(mHidlSession);
3816 if (castResult_3_7.isOk()) {
3817 hidlSession_3_7 = castResult_3_7;
3818 }
Emilian Peevaebbe412018-01-15 13:53:24 +00003819 auto castResult_3_4 = device::V3_4::ICameraDeviceSession::castFrom(mHidlSession);
3820 if (castResult_3_4.isOk()) {
3821 hidlSession_3_4 = castResult_3_4;
3822 }
3823
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003824 hardware::hidl_vec<device::V3_2::CaptureRequest> captureRequests;
Emilian Peevaebbe412018-01-15 13:53:24 +00003825 hardware::hidl_vec<device::V3_4::CaptureRequest> captureRequests_3_4;
Shuzhen Wang83bff122020-11-20 15:51:39 -08003826 hardware::hidl_vec<device::V3_7::CaptureRequest> captureRequests_3_7;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003827 size_t batchSize = requests.size();
Shuzhen Wang83bff122020-11-20 15:51:39 -08003828 if (hidlSession_3_7 != nullptr) {
3829 captureRequests_3_7.resize(batchSize);
3830 } else if (hidlSession_3_4 != nullptr) {
Emilian Peevaebbe412018-01-15 13:53:24 +00003831 captureRequests_3_4.resize(batchSize);
3832 } else {
3833 captureRequests.resize(batchSize);
3834 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003835 std::vector<native_handle_t*> handlesCreated;
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003836 std::vector<std::pair<int32_t, int32_t>> inflightBuffers;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003837
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003838 status_t res = OK;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003839 for (size_t i = 0; i < batchSize; i++) {
Shuzhen Wang83bff122020-11-20 15:51:39 -08003840 if (hidlSession_3_7 != nullptr) {
3841 res = wrapAsHidlRequest(requests[i], /*out*/&captureRequests_3_7[i].v3_4.v3_2,
3842 /*out*/&handlesCreated, /*out*/&inflightBuffers);
3843 } else if (hidlSession_3_4 != nullptr) {
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003844 res = wrapAsHidlRequest(requests[i], /*out*/&captureRequests_3_4[i].v3_2,
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003845 /*out*/&handlesCreated, /*out*/&inflightBuffers);
Emilian Peevaebbe412018-01-15 13:53:24 +00003846 } else {
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003847 res = wrapAsHidlRequest(requests[i], /*out*/&captureRequests[i],
3848 /*out*/&handlesCreated, /*out*/&inflightBuffers);
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003849 }
3850 if (res != OK) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003851 mBufferRecords.popInflightBuffers(inflightBuffers);
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003852 cleanupNativeHandles(&handlesCreated);
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003853 return res;
Emilian Peevaebbe412018-01-15 13:53:24 +00003854 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003855 }
3856
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003857 std::vector<device::V3_2::BufferCache> cachesToRemove;
3858 {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003859 std::lock_guard<std::mutex> lock(mFreedBuffersLock);
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003860 for (auto& pair : mFreedBuffers) {
3861 // The stream might have been removed since onBufferFreed
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003862 if (mBufferRecords.isStreamCached(pair.first)) {
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003863 cachesToRemove.push_back({pair.first, pair.second});
3864 }
3865 }
3866 mFreedBuffers.clear();
3867 }
3868
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003869 common::V1_0::Status status = common::V1_0::Status::INTERNAL_ERROR;
3870 *numRequestProcessed = 0;
Yifan Hongf79b5542017-04-11 14:44:25 -07003871
3872 // Write metadata to FMQ.
3873 for (size_t i = 0; i < batchSize; i++) {
Emilian Peevf4816702020-04-03 15:44:51 -07003874 camera_capture_request_t* request = requests[i];
Emilian Peevaebbe412018-01-15 13:53:24 +00003875 device::V3_2::CaptureRequest* captureRequest;
Shuzhen Wang83bff122020-11-20 15:51:39 -08003876 if (hidlSession_3_7 != nullptr) {
3877 captureRequest = &captureRequests_3_7[i].v3_4.v3_2;
3878 } else if (hidlSession_3_4 != nullptr) {
Emilian Peevaebbe412018-01-15 13:53:24 +00003879 captureRequest = &captureRequests_3_4[i].v3_2;
3880 } else {
3881 captureRequest = &captureRequests[i];
3882 }
Yifan Hongf79b5542017-04-11 14:44:25 -07003883
3884 if (request->settings != nullptr) {
3885 size_t settingsSize = get_camera_metadata_size(request->settings);
3886 if (mRequestMetadataQueue != nullptr && mRequestMetadataQueue->write(
3887 reinterpret_cast<const uint8_t*>(request->settings), settingsSize)) {
3888 captureRequest->settings.resize(0);
3889 captureRequest->fmqSettingsSize = settingsSize;
3890 } else {
3891 if (mRequestMetadataQueue != nullptr) {
3892 ALOGW("%s: couldn't utilize fmq, fallback to hwbinder", __FUNCTION__);
3893 }
3894 captureRequest->settings.setToExternal(
3895 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(request->settings)),
3896 get_camera_metadata_size(request->settings));
3897 captureRequest->fmqSettingsSize = 0u;
3898 }
3899 } else {
3900 // A null request settings maps to a size-0 CameraMetadata
3901 captureRequest->settings.resize(0);
3902 captureRequest->fmqSettingsSize = 0u;
3903 }
Emilian Peevaebbe412018-01-15 13:53:24 +00003904
Shuzhen Wang83bff122020-11-20 15:51:39 -08003905 // hidl session 3.7 specific handling.
3906 if (hidlSession_3_7 != nullptr) {
3907 captureRequests_3_7[i].inputWidth = request->input_width;
3908 captureRequests_3_7[i].inputHeight = request->input_height;
3909 }
3910
3911 // hidl session 3.7 and 3.4 specific handling.
3912 if (hidlSession_3_7 != nullptr || hidlSession_3_4 != nullptr) {
3913 hardware::hidl_vec<device::V3_4::PhysicalCameraSetting>& physicalCameraSettings =
3914 (hidlSession_3_7 != nullptr) ?
3915 captureRequests_3_7[i].v3_4.physicalCameraSettings :
3916 captureRequests_3_4[i].physicalCameraSettings;
3917 physicalCameraSettings.resize(request->num_physcam_settings);
Emilian Peevaebbe412018-01-15 13:53:24 +00003918 for (size_t j = 0; j < request->num_physcam_settings; j++) {
Emilian Peev00420d22018-02-05 21:33:13 +00003919 if (request->physcam_settings != nullptr) {
3920 size_t settingsSize = get_camera_metadata_size(request->physcam_settings[j]);
3921 if (mRequestMetadataQueue != nullptr && mRequestMetadataQueue->write(
3922 reinterpret_cast<const uint8_t*>(request->physcam_settings[j]),
3923 settingsSize)) {
Shuzhen Wang83bff122020-11-20 15:51:39 -08003924 physicalCameraSettings[j].settings.resize(0);
3925 physicalCameraSettings[j].fmqSettingsSize = settingsSize;
Emilian Peev00420d22018-02-05 21:33:13 +00003926 } else {
3927 if (mRequestMetadataQueue != nullptr) {
3928 ALOGW("%s: couldn't utilize fmq, fallback to hwbinder", __FUNCTION__);
3929 }
Shuzhen Wang83bff122020-11-20 15:51:39 -08003930 physicalCameraSettings[j].settings.setToExternal(
Emilian Peev00420d22018-02-05 21:33:13 +00003931 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(
3932 request->physcam_settings[j])),
3933 get_camera_metadata_size(request->physcam_settings[j]));
Shuzhen Wang83bff122020-11-20 15:51:39 -08003934 physicalCameraSettings[j].fmqSettingsSize = 0u;
Emilian Peevaebbe412018-01-15 13:53:24 +00003935 }
Emilian Peev00420d22018-02-05 21:33:13 +00003936 } else {
Yin-Chia Yeha2849702021-03-10 10:11:33 -08003937 physicalCameraSettings[j].fmqSettingsSize = 0u;
3938 physicalCameraSettings[j].settings.resize(0);
Emilian Peevaebbe412018-01-15 13:53:24 +00003939 }
Shuzhen Wang83bff122020-11-20 15:51:39 -08003940 physicalCameraSettings[j].physicalCameraId = request->physcam_id[j];
Emilian Peevaebbe412018-01-15 13:53:24 +00003941 }
3942 }
Yifan Hongf79b5542017-04-11 14:44:25 -07003943 }
Emilian Peevaebbe412018-01-15 13:53:24 +00003944
3945 hardware::details::return_status err;
Jayant Chowdharyc8d581e2018-07-16 14:46:23 -07003946 auto resultCallback =
3947 [&status, &numRequestProcessed] (auto s, uint32_t n) {
3948 status = s;
3949 *numRequestProcessed = n;
3950 };
Shuzhen Wang83bff122020-11-20 15:51:39 -08003951 if (hidlSession_3_7 != nullptr) {
3952 err = hidlSession_3_7->processCaptureRequest_3_7(captureRequests_3_7, cachesToRemove,
3953 resultCallback);
3954 } else if (hidlSession_3_4 != nullptr) {
Emilian Peevaebbe412018-01-15 13:53:24 +00003955 err = hidlSession_3_4->processCaptureRequest_3_4(captureRequests_3_4, cachesToRemove,
Jayant Chowdharyc8d581e2018-07-16 14:46:23 -07003956 resultCallback);
Emilian Peevaebbe412018-01-15 13:53:24 +00003957 } else {
3958 err = mHidlSession->processCaptureRequest(captureRequests, cachesToRemove,
Jayant Chowdharyc8d581e2018-07-16 14:46:23 -07003959 resultCallback);
Emilian Peevaebbe412018-01-15 13:53:24 +00003960 }
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -07003961 if (!err.isOk()) {
3962 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003963 status = common::V1_0::Status::CAMERA_DISCONNECTED;
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -07003964 }
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003965
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003966 if (status == common::V1_0::Status::OK && *numRequestProcessed != batchSize) {
3967 ALOGE("%s: processCaptureRequest returns OK but processed %d/%zu requests",
3968 __FUNCTION__, *numRequestProcessed, batchSize);
3969 status = common::V1_0::Status::INTERNAL_ERROR;
3970 }
3971
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003972 res = CameraProviderManager::mapToStatusT(status);
3973 if (res == OK) {
3974 if (mHidlSession->isRemote()) {
3975 // Only close acquire fence FDs when the HIDL transaction succeeds (so the FDs have been
3976 // sent to camera HAL processes)
3977 cleanupNativeHandles(&handlesCreated, /*closeFd*/true);
3978 } else {
3979 // In passthrough mode the FDs are now owned by HAL
3980 cleanupNativeHandles(&handlesCreated);
3981 }
3982 } else {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003983 mBufferRecords.popInflightBuffers(inflightBuffers);
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003984 cleanupNativeHandles(&handlesCreated);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003985 }
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003986 return res;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003987}
3988
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003989status_t Camera3Device::HalInterface::flush() {
3990 ATRACE_NAME("CameraHal::flush");
3991 if (!valid()) return INVALID_OPERATION;
3992 status_t res = OK;
3993
Emilian Peev31abd0a2017-05-11 18:37:46 +01003994 auto err = mHidlSession->flush();
3995 if (!err.isOk()) {
3996 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3997 res = DEAD_OBJECT;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003998 } else {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003999 res = CameraProviderManager::mapToStatusT(err);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004000 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01004001
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004002 return res;
4003}
4004
Emilian Peev31abd0a2017-05-11 18:37:46 +01004005status_t Camera3Device::HalInterface::dump(int /*fd*/) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004006 ATRACE_NAME("CameraHal::dump");
4007 if (!valid()) return INVALID_OPERATION;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004008
Emilian Peev31abd0a2017-05-11 18:37:46 +01004009 // Handled by CameraProviderManager::dump
4010
4011 return OK;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004012}
4013
4014status_t Camera3Device::HalInterface::close() {
4015 ATRACE_NAME("CameraHal::close()");
4016 if (!valid()) return INVALID_OPERATION;
4017 status_t res = OK;
4018
Emilian Peev31abd0a2017-05-11 18:37:46 +01004019 auto err = mHidlSession->close();
4020 // Interface will be dead shortly anyway, so don't log errors
4021 if (!err.isOk()) {
4022 res = DEAD_OBJECT;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004023 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01004024
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004025 return res;
4026}
4027
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004028void Camera3Device::HalInterface::signalPipelineDrain(const std::vector<int>& streamIds) {
4029 ATRACE_NAME("CameraHal::signalPipelineDrain");
4030 if (!valid() || mHidlSession_3_5 == nullptr) {
4031 ALOGE("%s called on invalid camera!", __FUNCTION__);
4032 return;
4033 }
4034
Yin-Chia Yehc300a072019-02-13 14:56:57 -08004035 auto err = mHidlSession_3_5->signalStreamFlush(streamIds, mNextStreamConfigCounter - 1);
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004036 if (!err.isOk()) {
4037 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
4038 return;
4039 }
4040}
4041
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004042status_t Camera3Device::HalInterface::switchToOffline(
4043 const std::vector<int32_t>& streamsToKeep,
4044 /*out*/hardware::camera::device::V3_6::CameraOfflineSessionInfo* offlineSessionInfo,
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004045 /*out*/sp<hardware::camera::device::V3_6::ICameraOfflineSession>* offlineSession,
4046 /*out*/camera3::BufferRecords* bufferRecords) {
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004047 ATRACE_NAME("CameraHal::switchToOffline");
4048 if (!valid() || mHidlSession_3_6 == nullptr) {
4049 ALOGE("%s called on invalid camera!", __FUNCTION__);
4050 return INVALID_OPERATION;
4051 }
4052
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004053 if (offlineSessionInfo == nullptr || offlineSession == nullptr || bufferRecords == nullptr) {
4054 ALOGE("%s: output arguments must not be null!", __FUNCTION__);
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004055 return INVALID_OPERATION;
4056 }
4057
4058 common::V1_0::Status status = common::V1_0::Status::INTERNAL_ERROR;
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004059 auto resultCallback =
4060 [&status, &offlineSessionInfo, &offlineSession] (auto s, auto info, auto session) {
4061 status = s;
4062 *offlineSessionInfo = info;
4063 *offlineSession = session;
4064 };
4065 auto err = mHidlSession_3_6->switchToOffline(streamsToKeep, resultCallback);
4066
4067 if (!err.isOk()) {
4068 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
4069 return DEAD_OBJECT;
4070 }
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004071
4072 status_t ret = CameraProviderManager::mapToStatusT(status);
4073 if (ret != OK) {
4074 return ret;
4075 }
4076
4077 // TODO: assert no ongoing requestBuffer/returnBuffer call here
4078 // TODO: update RequestBufferStateMachine to block requestBuffer/returnBuffer once HAL
4079 // returns from switchToOffline.
4080
4081
4082 // Validate buffer caches
4083 std::vector<int32_t> streams;
4084 streams.reserve(offlineSessionInfo->offlineStreams.size());
4085 for (auto offlineStream : offlineSessionInfo->offlineStreams) {
4086 int32_t id = offlineStream.id;
4087 streams.push_back(id);
4088 // Verify buffer caches
4089 std::vector<uint64_t> bufIds(offlineStream.circulatingBufferIds.begin(),
4090 offlineStream.circulatingBufferIds.end());
4091 if (!verifyBufferIds(id, bufIds)) {
4092 ALOGE("%s: stream ID %d buffer cache records mismatch!", __FUNCTION__, id);
4093 return UNKNOWN_ERROR;
4094 }
4095 }
4096
4097 // Move buffer records
4098 bufferRecords->takeBufferCaches(mBufferRecords, streams);
4099 bufferRecords->takeInflightBufferMap(mBufferRecords);
4100 bufferRecords->takeRequestedBufferMap(mBufferRecords);
4101 return ret;
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004102}
4103
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07004104void Camera3Device::HalInterface::getInflightBufferKeys(
4105 std::vector<std::pair<int32_t, int32_t>>* out) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004106 mBufferRecords.getInflightBufferKeys(out);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07004107 return;
4108}
4109
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08004110void Camera3Device::HalInterface::getInflightRequestBufferKeys(
4111 std::vector<uint64_t>* out) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004112 mBufferRecords.getInflightRequestBufferKeys(out);
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08004113 return;
4114}
4115
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004116bool Camera3Device::HalInterface::verifyBufferIds(
4117 int32_t streamId, std::vector<uint64_t>& bufIds) {
4118 return mBufferRecords.verifyBufferIds(streamId, bufIds);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004119}
4120
4121status_t Camera3Device::HalInterface::popInflightBuffer(
Yin-Chia Yehf4650602017-01-10 13:13:39 -08004122 int32_t frameNumber, int32_t streamId,
4123 /*out*/ buffer_handle_t **buffer) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004124 return mBufferRecords.popInflightBuffer(frameNumber, streamId, buffer);
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07004125}
4126
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004127status_t Camera3Device::HalInterface::pushInflightRequestBuffer(
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08004128 uint64_t bufferId, buffer_handle_t* buf, int32_t streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004129 return mBufferRecords.pushInflightRequestBuffer(bufferId, buf, streamId);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004130}
4131
4132// Find and pop a buffer_handle_t based on bufferId
4133status_t Camera3Device::HalInterface::popInflightRequestBuffer(
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08004134 uint64_t bufferId,
4135 /*out*/ buffer_handle_t** buffer,
4136 /*optional out*/ int32_t* streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004137 return mBufferRecords.popInflightRequestBuffer(bufferId, buffer, streamId);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004138}
4139
Yin-Chia Yeh77327052017-01-09 18:23:07 -08004140std::pair<bool, uint64_t> Camera3Device::HalInterface::getBufferId(
4141 const buffer_handle_t& buf, int streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004142 return mBufferRecords.getBufferId(buf, streamId);
Yin-Chia Yeh77327052017-01-09 18:23:07 -08004143}
4144
Shuzhen Wangcd5b1822021-09-07 11:52:48 -07004145uint64_t Camera3Device::HalInterface::removeOneBufferCache(int streamId,
4146 const native_handle_t* handle) {
4147 return mBufferRecords.removeOneBufferCache(streamId, handle);
4148}
4149
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07004150void Camera3Device::HalInterface::onBufferFreed(
4151 int streamId, const native_handle_t* handle) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004152 uint32_t bufferId = mBufferRecords.removeOneBufferCache(streamId, handle);
4153 std::lock_guard<std::mutex> lock(mFreedBuffersLock);
4154 if (bufferId != BUFFER_ID_NO_BUFFER) {
4155 mFreedBuffers.push_back(std::make_pair(streamId, bufferId));
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07004156 }
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07004157}
4158
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07004159void Camera3Device::HalInterface::onStreamReConfigured(int streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004160 std::vector<uint64_t> bufIds = mBufferRecords.clearBufferCaches(streamId);
4161 std::lock_guard<std::mutex> lock(mFreedBuffersLock);
4162 for (auto bufferId : bufIds) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07004163 mFreedBuffers.push_back(std::make_pair(streamId, bufferId));
4164 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07004165}
4166
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004167/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004168 * RequestThread inner class methods
4169 */
4170
4171Camera3Device::RequestThread::RequestThread(wp<Camera3Device> parent,
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004172 sp<StatusTracker> statusTracker,
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004173 sp<HalInterface> interface, const Vector<int32_t>& sessionParamKeys,
Eino-Ville Talvala1646c3c2021-07-29 13:48:40 -07004174 bool useHalBufManager,
4175 bool supportCameraMute) :
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004176 Thread(/*canCallJava*/false),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004177 mParent(parent),
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004178 mStatusTracker(statusTracker),
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004179 mInterface(interface),
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07004180 mListener(nullptr),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004181 mId(getId(parent)),
Shuzhen Wang316781a2020-08-18 18:11:01 -07004182 mFirstRepeating(false),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004183 mReconfigured(false),
4184 mDoPause(false),
4185 mPaused(true),
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004186 mNotifyPipelineDrain(false),
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004187 mFrameNumber(0),
Jianing Weicb0652e2014-03-12 18:29:36 -07004188 mLatestRequestId(NAME_NOT_FOUND),
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07004189 mCurrentAfTriggerId(0),
4190 mCurrentPreCaptureTriggerId(0),
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004191 mRotateAndCropOverride(ANDROID_SCALER_ROTATE_AND_CROP_NONE),
Emilian Peeve23f1d92021-09-20 14:56:01 -07004192 mComposerOutput(false),
Eino-Ville Talvala11afe4f2021-05-27 14:45:31 -07004193 mCameraMute(ANDROID_SENSOR_TEST_PATTERN_MODE_OFF),
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004194 mCameraMuteChanged(false),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004195 mRepeatingLastFrameNumber(
4196 hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES),
Shuzhen Wang686f6442017-06-20 16:16:04 -07004197 mPrepareVideoStream(false),
Emilian Peeva14b4dd2018-05-15 11:00:31 +01004198 mConstrainedMode(false),
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004199 mRequestLatency(kRequestLatencyBinSize),
4200 mSessionParamKeys(sessionParamKeys),
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004201 mLatestSessionParams(sessionParamKeys.size()),
Eino-Ville Talvala1646c3c2021-07-29 13:48:40 -07004202 mUseHalBufManager(useHalBufManager),
4203 mSupportCameraMute(supportCameraMute){
Yin-Chia Yeh87b3ec02019-06-03 10:44:39 -07004204 mStatusId = statusTracker->addComponent("RequestThread");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004205}
4206
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004207Camera3Device::RequestThread::~RequestThread() {}
4208
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004209void Camera3Device::RequestThread::setNotificationListener(
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004210 wp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004211 ATRACE_CALL();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004212 Mutex::Autolock l(mRequestLock);
4213 mListener = listener;
4214}
4215
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004216void Camera3Device::RequestThread::configurationComplete(bool isConstrainedHighSpeed,
Shuzhen Wang99080502021-03-07 21:08:20 -08004217 const CameraMetadata& sessionParams,
4218 const std::map<int32_t, std::set<String8>>& groupIdPhysicalCameraMap) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004219 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004220 Mutex::Autolock l(mRequestLock);
4221 mReconfigured = true;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004222 mLatestSessionParams = sessionParams;
Shuzhen Wang99080502021-03-07 21:08:20 -08004223 mGroupIdPhysicalCameraMap = groupIdPhysicalCameraMap;
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07004224 // Prepare video stream for high speed recording.
4225 mPrepareVideoStream = isConstrainedHighSpeed;
Emilian Peeva14b4dd2018-05-15 11:00:31 +01004226 mConstrainedMode = isConstrainedHighSpeed;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004227}
4228
Jianing Wei90e59c92014-03-12 18:29:36 -07004229status_t Camera3Device::RequestThread::queueRequestList(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004230 List<sp<CaptureRequest> > &requests,
4231 /*out*/
4232 int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004233 ATRACE_CALL();
Jianing Wei90e59c92014-03-12 18:29:36 -07004234 Mutex::Autolock l(mRequestLock);
4235 for (List<sp<CaptureRequest> >::iterator it = requests.begin(); it != requests.end();
4236 ++it) {
4237 mRequestQueue.push_back(*it);
4238 }
4239
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004240 if (lastFrameNumber != NULL) {
4241 *lastFrameNumber = mFrameNumber + mRequestQueue.size() - 1;
4242 ALOGV("%s: requestId %d, mFrameNumber %" PRId32 ", lastFrameNumber %" PRId64 ".",
4243 __FUNCTION__, (*(requests.begin()))->mResultExtras.requestId, mFrameNumber,
4244 *lastFrameNumber);
4245 }
Jianing Weicb0652e2014-03-12 18:29:36 -07004246
Jianing Wei90e59c92014-03-12 18:29:36 -07004247 unpauseForNewRequests();
4248
4249 return OK;
4250}
4251
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004252
4253status_t Camera3Device::RequestThread::queueTrigger(
4254 RequestTrigger trigger[],
4255 size_t count) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004256 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004257 Mutex::Autolock l(mTriggerMutex);
4258 status_t ret;
4259
4260 for (size_t i = 0; i < count; ++i) {
4261 ret = queueTriggerLocked(trigger[i]);
4262
4263 if (ret != OK) {
4264 return ret;
4265 }
4266 }
4267
4268 return OK;
4269}
4270
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004271const String8& Camera3Device::RequestThread::getId(const wp<Camera3Device> &device) {
4272 static String8 deadId("<DeadDevice>");
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004273 sp<Camera3Device> d = device.promote();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004274 if (d != nullptr) return d->mId;
4275 return deadId;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004276}
4277
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004278status_t Camera3Device::RequestThread::queueTriggerLocked(
4279 RequestTrigger trigger) {
4280
4281 uint32_t tag = trigger.metadataTag;
4282 ssize_t index = mTriggerMap.indexOfKey(tag);
4283
4284 switch (trigger.getTagType()) {
4285 case TYPE_BYTE:
4286 // fall-through
4287 case TYPE_INT32:
4288 break;
4289 default:
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004290 ALOGE("%s: Type not supported: 0x%x", __FUNCTION__,
4291 trigger.getTagType());
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004292 return INVALID_OPERATION;
4293 }
4294
4295 /**
4296 * Collect only the latest trigger, since we only have 1 field
4297 * in the request settings per trigger tag, and can't send more than 1
4298 * trigger per request.
4299 */
4300 if (index != NAME_NOT_FOUND) {
4301 mTriggerMap.editValueAt(index) = trigger;
4302 } else {
4303 mTriggerMap.add(tag, trigger);
4304 }
4305
4306 return OK;
4307}
4308
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004309status_t Camera3Device::RequestThread::setRepeatingRequests(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004310 const RequestList &requests,
4311 /*out*/
4312 int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004313 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004314 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004315 if (lastFrameNumber != NULL) {
4316 *lastFrameNumber = mRepeatingLastFrameNumber;
4317 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004318 mRepeatingRequests.clear();
Shuzhen Wang316781a2020-08-18 18:11:01 -07004319 mFirstRepeating = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004320 mRepeatingRequests.insert(mRepeatingRequests.begin(),
4321 requests.begin(), requests.end());
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004322
4323 unpauseForNewRequests();
4324
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004325 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004326 return OK;
4327}
4328
Chih-Hung Hsieh8b0b9712016-08-09 14:25:53 -07004329bool Camera3Device::RequestThread::isRepeatingRequestLocked(const sp<CaptureRequest>& requestIn) {
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07004330 if (mRepeatingRequests.empty()) {
4331 return false;
4332 }
4333 int32_t requestId = requestIn->mResultExtras.requestId;
4334 const RequestList &repeatRequests = mRepeatingRequests;
4335 // All repeating requests are guaranteed to have same id so only check first quest
4336 const sp<CaptureRequest> firstRequest = *repeatRequests.begin();
4337 return (firstRequest->mResultExtras.requestId == requestId);
4338}
4339
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004340status_t Camera3Device::RequestThread::clearRepeatingRequests(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004341 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004342 Mutex::Autolock l(mRequestLock);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004343 return clearRepeatingRequestsLocked(lastFrameNumber);
4344
4345}
4346
4347status_t Camera3Device::RequestThread::clearRepeatingRequestsLocked(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004348 mRepeatingRequests.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004349 if (lastFrameNumber != NULL) {
4350 *lastFrameNumber = mRepeatingLastFrameNumber;
4351 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004352 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004353 return OK;
4354}
4355
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004356status_t Camera3Device::RequestThread::clear(
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004357 /*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004358 ATRACE_CALL();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004359 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004360 ALOGV("RequestThread::%s:", __FUNCTION__);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004361
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004362 mRepeatingRequests.clear();
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07004363
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004364 // Send errors for all requests pending in the request queue, including
4365 // pending repeating requests
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004366 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004367 if (listener != NULL) {
4368 for (RequestList::iterator it = mRequestQueue.begin();
4369 it != mRequestQueue.end(); ++it) {
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004370 // Abort the input buffers for reprocess requests.
4371 if ((*it)->mInputStream != NULL) {
Emilian Peevf4816702020-04-03 15:44:51 -07004372 camera_stream_buffer_t inputBuffer;
Shuzhen Wang83bff122020-11-20 15:51:39 -08004373 camera3::Size inputBufferSize;
Eino-Ville Talvalaba435252017-06-21 16:07:25 -07004374 status_t res = (*it)->mInputStream->getInputBuffer(&inputBuffer,
Shuzhen Wang83bff122020-11-20 15:51:39 -08004375 &inputBufferSize, /*respectHalLimit*/ false);
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004376 if (res != OK) {
4377 ALOGW("%s: %d: couldn't get input buffer while clearing the request "
4378 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
4379 } else {
Emilian Peevf4816702020-04-03 15:44:51 -07004380 inputBuffer.status = CAMERA_BUFFER_STATUS_ERROR;
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004381 res = (*it)->mInputStream->returnInputBuffer(inputBuffer);
4382 if (res != OK) {
4383 ALOGE("%s: %d: couldn't return input buffer while clearing the request "
4384 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
4385 }
4386 }
4387 }
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004388 // Set the frame number this request would have had, if it
4389 // had been submitted; this frame number will not be reused.
4390 // The requestId and burstId fields were set when the request was
4391 // submitted originally (in convertMetadataListToRequestListLocked)
4392 (*it)->mResultExtras.frameNumber = mFrameNumber++;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004393 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004394 (*it)->mResultExtras);
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07004395 }
4396 }
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004397 mRequestQueue.clear();
Jinguang Dongb26e7a02016-11-14 16:04:02 +08004398
4399 Mutex::Autolock al(mTriggerMutex);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004400 mTriggerMap.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004401 if (lastFrameNumber != NULL) {
4402 *lastFrameNumber = mRepeatingLastFrameNumber;
4403 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004404 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Emilian Peev8dae54c2019-12-02 15:17:17 -08004405 mRequestSignal.signal();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004406 return OK;
4407}
4408
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004409status_t Camera3Device::RequestThread::flush() {
4410 ATRACE_CALL();
4411 Mutex::Autolock l(mFlushLock);
4412
Emilian Peev08dd2452017-04-06 16:55:14 +01004413 return mInterface->flush();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004414}
4415
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004416void Camera3Device::RequestThread::setPaused(bool paused) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004417 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004418 Mutex::Autolock l(mPauseLock);
4419 mDoPause = paused;
4420 mDoPauseSignal.signal();
4421}
4422
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004423status_t Camera3Device::RequestThread::waitUntilRequestProcessed(
4424 int32_t requestId, nsecs_t timeout) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004425 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004426 Mutex::Autolock l(mLatestRequestMutex);
4427 status_t res;
4428 while (mLatestRequestId != requestId) {
4429 nsecs_t startTime = systemTime();
4430
4431 res = mLatestRequestSignal.waitRelative(mLatestRequestMutex, timeout);
4432 if (res != OK) return res;
4433
4434 timeout -= (systemTime() - startTime);
4435 }
4436
4437 return OK;
4438}
4439
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004440void Camera3Device::RequestThread::requestExit() {
4441 // Call parent to set up shutdown
4442 Thread::requestExit();
4443 // The exit from any possible waits
4444 mDoPauseSignal.signal();
4445 mRequestSignal.signal();
Shuzhen Wang686f6442017-06-20 16:16:04 -07004446
4447 mRequestLatency.log("ProcessCaptureRequest latency histogram");
4448 mRequestLatency.reset();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004449}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004450
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004451void Camera3Device::RequestThread::checkAndStopRepeatingRequest() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004452 ATRACE_CALL();
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07004453 bool surfaceAbandoned = false;
4454 int64_t lastFrameNumber = 0;
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004455 sp<NotificationListener> listener;
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07004456 {
4457 Mutex::Autolock l(mRequestLock);
4458 // Check all streams needed by repeating requests are still valid. Otherwise, stop
4459 // repeating requests.
4460 for (const auto& request : mRepeatingRequests) {
4461 for (const auto& s : request->mOutputStreams) {
4462 if (s->isAbandoned()) {
4463 surfaceAbandoned = true;
4464 clearRepeatingRequestsLocked(&lastFrameNumber);
4465 break;
4466 }
4467 }
4468 if (surfaceAbandoned) {
4469 break;
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004470 }
4471 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004472 listener = mListener.promote();
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004473 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004474
4475 if (listener != NULL && surfaceAbandoned) {
4476 listener->notifyRepeatingRequestError(lastFrameNumber);
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07004477 }
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004478}
4479
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004480bool Camera3Device::RequestThread::sendRequestsBatch() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004481 ATRACE_CALL();
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004482 status_t res;
4483 size_t batchSize = mNextRequests.size();
Emilian Peevf4816702020-04-03 15:44:51 -07004484 std::vector<camera_capture_request_t*> requests(batchSize);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004485 uint32_t numRequestProcessed = 0;
4486 for (size_t i = 0; i < batchSize; i++) {
4487 requests[i] = &mNextRequests.editItemAt(i).halRequest;
Yin-Chia Yeh885691c2018-05-01 15:54:24 -07004488 ATRACE_ASYNC_BEGIN("frame capture", mNextRequests[i].halRequest.frame_number);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004489 }
4490
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004491 res = mInterface->processBatchCaptureRequests(requests, &numRequestProcessed);
4492
4493 bool triggerRemoveFailed = false;
4494 NextRequest& triggerFailedRequest = mNextRequests.editItemAt(0);
4495 for (size_t i = 0; i < numRequestProcessed; i++) {
4496 NextRequest& nextRequest = mNextRequests.editItemAt(i);
4497 nextRequest.submitted = true;
4498
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004499 updateNextRequest(nextRequest);
Emilian Peevaebbe412018-01-15 13:53:24 +00004500
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004501 if (!triggerRemoveFailed) {
4502 // Remove any previously queued triggers (after unlock)
4503 status_t removeTriggerRes = removeTriggers(mPrevRequest);
4504 if (removeTriggerRes != OK) {
4505 triggerRemoveFailed = true;
4506 triggerFailedRequest = nextRequest;
4507 }
4508 }
4509 }
4510
4511 if (triggerRemoveFailed) {
4512 SET_ERR("RequestThread: Unable to remove triggers "
4513 "(capture request %d, HAL device: %s (%d)",
4514 triggerFailedRequest.halRequest.frame_number, strerror(-res), res);
4515 cleanUpFailedRequests(/*sendRequestError*/ false);
4516 return false;
4517 }
4518
4519 if (res != OK) {
4520 // Should only get a failure here for malformed requests or device-level
4521 // errors, so consider all errors fatal. Bad metadata failures should
4522 // come through notify.
4523 SET_ERR("RequestThread: Unable to submit capture request %d to HAL device: %s (%d)",
4524 mNextRequests[numRequestProcessed].halRequest.frame_number,
4525 strerror(-res), res);
4526 cleanUpFailedRequests(/*sendRequestError*/ false);
4527 return false;
4528 }
4529 return true;
4530}
4531
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07004532nsecs_t Camera3Device::RequestThread::calculateMaxExpectedDuration(const camera_metadata_t *request) {
4533 nsecs_t maxExpectedDuration = kDefaultExpectedDuration;
4534 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
4535 find_camera_metadata_ro_entry(request,
4536 ANDROID_CONTROL_AE_MODE,
4537 &e);
4538 if (e.count == 0) return maxExpectedDuration;
4539
4540 switch (e.data.u8[0]) {
4541 case ANDROID_CONTROL_AE_MODE_OFF:
4542 find_camera_metadata_ro_entry(request,
4543 ANDROID_SENSOR_EXPOSURE_TIME,
4544 &e);
4545 if (e.count > 0) {
4546 maxExpectedDuration = e.data.i64[0];
4547 }
4548 find_camera_metadata_ro_entry(request,
4549 ANDROID_SENSOR_FRAME_DURATION,
4550 &e);
4551 if (e.count > 0) {
4552 maxExpectedDuration = std::max(e.data.i64[0], maxExpectedDuration);
4553 }
4554 break;
4555 default:
4556 find_camera_metadata_ro_entry(request,
4557 ANDROID_CONTROL_AE_TARGET_FPS_RANGE,
4558 &e);
4559 if (e.count > 1) {
4560 maxExpectedDuration = 1e9 / e.data.u8[0];
4561 }
4562 break;
4563 }
4564
4565 return maxExpectedDuration;
4566}
4567
Emilian Peeva14b4dd2018-05-15 11:00:31 +01004568bool Camera3Device::RequestThread::skipHFRTargetFPSUpdate(int32_t tag,
4569 const camera_metadata_ro_entry_t& newEntry, const camera_metadata_entry_t& currentEntry) {
4570 if (mConstrainedMode && (ANDROID_CONTROL_AE_TARGET_FPS_RANGE == tag) &&
4571 (newEntry.count == currentEntry.count) && (currentEntry.count == 2) &&
4572 (currentEntry.data.i32[1] == newEntry.data.i32[1])) {
4573 return true;
4574 }
4575
4576 return false;
4577}
4578
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004579void Camera3Device::RequestThread::updateNextRequest(NextRequest& nextRequest) {
4580 // Update the latest request sent to HAL
Shuzhen Wang83bff122020-11-20 15:51:39 -08004581 camera_capture_request_t& halRequest = nextRequest.halRequest;
4582 if (halRequest.settings != NULL) { // Don't update if they were unchanged
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004583 Mutex::Autolock al(mLatestRequestMutex);
4584
Shuzhen Wang83bff122020-11-20 15:51:39 -08004585 camera_metadata_t* cloned = clone_camera_metadata(halRequest.settings);
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004586 mLatestRequest.acquire(cloned);
4587
4588 mLatestPhysicalRequest.clear();
Shuzhen Wang83bff122020-11-20 15:51:39 -08004589 for (uint32_t i = 0; i < halRequest.num_physcam_settings; i++) {
4590 cloned = clone_camera_metadata(halRequest.physcam_settings[i]);
4591 mLatestPhysicalRequest.emplace(halRequest.physcam_id[i],
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004592 CameraMetadata(cloned));
4593 }
4594
4595 sp<Camera3Device> parent = mParent.promote();
4596 if (parent != NULL) {
4597 parent->monitorMetadata(TagMonitor::REQUEST,
Shuzhen Wang83bff122020-11-20 15:51:39 -08004598 halRequest.frame_number,
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004599 0, mLatestRequest, mLatestPhysicalRequest);
4600 }
4601 }
4602
Shuzhen Wang83bff122020-11-20 15:51:39 -08004603 if (halRequest.settings != NULL) {
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004604 nextRequest.captureRequest->mSettingsList.begin()->metadata.unlock(
Shuzhen Wang83bff122020-11-20 15:51:39 -08004605 halRequest.settings);
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004606 }
4607
Shuzhen Wang83bff122020-11-20 15:51:39 -08004608 cleanupPhysicalSettings(nextRequest.captureRequest, &halRequest);
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004609}
4610
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004611bool Camera3Device::RequestThread::updateSessionParameters(const CameraMetadata& settings) {
4612 ATRACE_CALL();
4613 bool updatesDetected = false;
4614
Emilian Peev4ec17882019-01-24 17:16:58 -08004615 CameraMetadata updatedParams(mLatestSessionParams);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004616 for (auto tag : mSessionParamKeys) {
4617 camera_metadata_ro_entry entry = settings.find(tag);
Emilian Peev4ec17882019-01-24 17:16:58 -08004618 camera_metadata_entry lastEntry = updatedParams.find(tag);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004619
4620 if (entry.count > 0) {
4621 bool isDifferent = false;
4622 if (lastEntry.count > 0) {
4623 // Have a last value, compare to see if changed
4624 if (lastEntry.type == entry.type &&
4625 lastEntry.count == entry.count) {
4626 // Same type and count, compare values
4627 size_t bytesPerValue = camera_metadata_type_size[lastEntry.type];
4628 size_t entryBytes = bytesPerValue * lastEntry.count;
4629 int cmp = memcmp(entry.data.u8, lastEntry.data.u8, entryBytes);
4630 if (cmp != 0) {
4631 isDifferent = true;
4632 }
4633 } else {
4634 // Count or type has changed
4635 isDifferent = true;
4636 }
4637 } else {
4638 // No last entry, so always consider to be different
4639 isDifferent = true;
4640 }
4641
4642 if (isDifferent) {
4643 ALOGV("%s: Session parameter tag id %d changed", __FUNCTION__, tag);
Emilian Peeva14b4dd2018-05-15 11:00:31 +01004644 if (!skipHFRTargetFPSUpdate(tag, entry, lastEntry)) {
4645 updatesDetected = true;
4646 }
Emilian Peev4ec17882019-01-24 17:16:58 -08004647 updatedParams.update(entry);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004648 }
4649 } else if (lastEntry.count > 0) {
4650 // Value has been removed
4651 ALOGV("%s: Session parameter tag id %d removed", __FUNCTION__, tag);
Emilian Peev4ec17882019-01-24 17:16:58 -08004652 updatedParams.erase(tag);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004653 updatesDetected = true;
4654 }
4655 }
4656
Emilian Peev4ec17882019-01-24 17:16:58 -08004657 bool reconfigureRequired;
4658 if (updatesDetected) {
4659 reconfigureRequired = mInterface->isReconfigurationRequired(mLatestSessionParams,
4660 updatedParams);
4661 mLatestSessionParams = updatedParams;
4662 } else {
4663 reconfigureRequired = false;
4664 }
4665
4666 return reconfigureRequired;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004667}
4668
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004669bool Camera3Device::RequestThread::threadLoop() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004670 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004671 status_t res;
Jayant Chowdhary37eca242019-11-18 08:55:56 -08004672 // Any function called from threadLoop() must not hold mInterfaceLock since
4673 // it could lead to deadlocks (disconnect() -> hold mInterfaceMutex -> wait for request thread
4674 // to finish -> request thread waits on mInterfaceMutex) http://b/143513518
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004675
4676 // Handle paused state.
4677 if (waitIfPaused()) {
4678 return true;
4679 }
4680
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004681 // Wait for the next batch of requests.
4682 waitForNextRequestBatch();
4683 if (mNextRequests.size() == 0) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004684 return true;
4685 }
4686
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004687 // Get the latest request ID, if any
4688 int latestRequestId;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004689 camera_metadata_entry_t requestIdEntry = mNextRequests[mNextRequests.size() - 1].
Emilian Peevaebbe412018-01-15 13:53:24 +00004690 captureRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_ID);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004691 if (requestIdEntry.count > 0) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004692 latestRequestId = requestIdEntry.data.i32[0];
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004693 } else {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004694 ALOGW("%s: Did not have android.request.id set in the request.", __FUNCTION__);
4695 latestRequestId = NAME_NOT_FOUND;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004696 }
4697
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004698 // 'mNextRequests' will at this point contain either a set of HFR batched requests
4699 // or a single request from streaming or burst. In either case the first element
4700 // should contain the latest camera settings that we need to check for any session
4701 // parameter updates.
Emilian Peevaebbe412018-01-15 13:53:24 +00004702 if (updateSessionParameters(mNextRequests[0].captureRequest->mSettingsList.begin()->metadata)) {
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004703 res = OK;
4704
4705 //Input stream buffers are already acquired at this point so an input stream
4706 //will not be able to move to idle state unless we force it.
4707 if (mNextRequests[0].captureRequest->mInputStream != nullptr) {
4708 res = mNextRequests[0].captureRequest->mInputStream->forceToIdle();
4709 if (res != OK) {
4710 ALOGE("%s: Failed to force idle input stream: %d", __FUNCTION__, res);
4711 cleanUpFailedRequests(/*sendRequestError*/ false);
4712 return false;
4713 }
4714 }
4715
4716 if (res == OK) {
Emilian Peev3bead5f2020-05-28 17:29:08 -07004717 sp<Camera3Device> parent = mParent.promote();
4718 if (parent != nullptr) {
4719 mReconfigured |= parent->reconfigureCamera(mLatestSessionParams, mStatusId);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004720 }
Emilian Peev3bead5f2020-05-28 17:29:08 -07004721 setPaused(false);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004722
4723 if (mNextRequests[0].captureRequest->mInputStream != nullptr) {
4724 mNextRequests[0].captureRequest->mInputStream->restoreConfiguredState();
4725 if (res != OK) {
4726 ALOGE("%s: Failed to restore configured input stream: %d", __FUNCTION__, res);
4727 cleanUpFailedRequests(/*sendRequestError*/ false);
4728 return false;
4729 }
4730 }
4731 }
4732 }
4733
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004734 // Prepare a batch of HAL requests and output buffers.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004735 res = prepareHalRequests();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004736 if (res == TIMED_OUT) {
4737 // Not a fatal error if getting output buffers time out.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004738 cleanUpFailedRequests(/*sendRequestError*/ true);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004739 // Check if any stream is abandoned.
4740 checkAndStopRepeatingRequest();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004741 return true;
4742 } else if (res != OK) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004743 cleanUpFailedRequests(/*sendRequestError*/ false);
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004744 return false;
4745 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004746
Zhijun Hecc27e112013-10-03 16:12:43 -07004747 // Inform waitUntilRequestProcessed thread of a new request ID
4748 {
4749 Mutex::Autolock al(mLatestRequestMutex);
4750
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004751 mLatestRequestId = latestRequestId;
Zhijun Hecc27e112013-10-03 16:12:43 -07004752 mLatestRequestSignal.signal();
4753 }
4754
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004755 // Submit a batch of requests to HAL.
4756 // Use flush lock only when submitting multilple requests in a batch.
4757 // TODO: The problem with flush lock is flush() will be blocked by process_capture_request()
4758 // which may take a long time to finish so synchronizing flush() and
4759 // process_capture_request() defeats the purpose of cancelling requests ASAP with flush().
4760 // For now, only synchronize for high speed recording and we should figure something out for
4761 // removing the synchronization.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004762 bool useFlushLock = mNextRequests.size() > 1;
Eino-Ville Talvala17a61ad2013-06-03 16:53:32 -07004763
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004764 if (useFlushLock) {
4765 mFlushLock.lock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004766 }
4767
Zhijun Hef0645c12016-08-02 00:58:11 -07004768 ALOGVV("%s: %d: submitting %zu requests in a batch.", __FUNCTION__, __LINE__,
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004769 mNextRequests.size());
Igor Murashkin1e479c02013-09-06 16:55:14 -07004770
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08004771 sp<Camera3Device> parent = mParent.promote();
4772 if (parent != nullptr) {
4773 parent->mRequestBufferSM.onSubmittingRequest();
4774 }
4775
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004776 bool submitRequestSuccess = false;
Shuzhen Wang686f6442017-06-20 16:16:04 -07004777 nsecs_t tRequestStart = systemTime(SYSTEM_TIME_MONOTONIC);
Yin-Chia Yeh11648852019-05-16 10:42:54 -07004778 submitRequestSuccess = sendRequestsBatch();
4779
Shuzhen Wang686f6442017-06-20 16:16:04 -07004780 nsecs_t tRequestEnd = systemTime(SYSTEM_TIME_MONOTONIC);
4781 mRequestLatency.add(tRequestStart, tRequestEnd);
Igor Murashkin1e479c02013-09-06 16:55:14 -07004782
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004783 if (useFlushLock) {
4784 mFlushLock.unlock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004785 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004786
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004787 // Unset as current request
4788 {
4789 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004790 mNextRequests.clear();
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004791 }
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004792 mRequestSubmittedSignal.signal();
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004793
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004794 return submitRequestSuccess;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004795}
4796
Jayant Chowdhary65c9bf02021-09-03 16:44:16 +00004797status_t Camera3Device::removeFwkOnlyRegionKeys(CameraMetadata *request) {
4798 static const std::array<uint32_t, 4> kFwkOnlyRegionKeys = {ANDROID_CONTROL_AF_REGIONS_SET,
4799 ANDROID_CONTROL_AE_REGIONS_SET, ANDROID_CONTROL_AWB_REGIONS_SET,
4800 ANDROID_SCALER_CROP_REGION_SET};
4801 if (request == nullptr) {
4802 ALOGE("%s request metadata nullptr", __FUNCTION__);
4803 return BAD_VALUE;
4804 }
4805 status_t res = OK;
4806 for (const auto &key : kFwkOnlyRegionKeys) {
4807 if (request->exists(key)) {
4808 res = request->erase(key);
4809 if (res != OK) {
4810 return res;
4811 }
4812 }
4813 }
4814 return OK;
4815}
4816
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004817status_t Camera3Device::RequestThread::prepareHalRequests() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004818 ATRACE_CALL();
4819
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07004820 bool batchedRequest = mNextRequests[0].captureRequest->mBatchSize > 1;
Shuzhen Wang4a472662017-02-26 23:29:04 -08004821 for (size_t i = 0; i < mNextRequests.size(); i++) {
4822 auto& nextRequest = mNextRequests.editItemAt(i);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004823 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
Emilian Peevf4816702020-04-03 15:44:51 -07004824 camera_capture_request_t* halRequest = &nextRequest.halRequest;
4825 Vector<camera_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004826
4827 // Prepare a request to HAL
4828 halRequest->frame_number = captureRequest->mResultExtras.frameNumber;
4829
4830 // Insert any queued triggers (before metadata is locked)
4831 status_t res = insertTriggers(captureRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004832 if (res < 0) {
4833 SET_ERR("RequestThread: Unable to insert triggers "
4834 "(capture request %d, HAL device: %s (%d)",
4835 halRequest->frame_number, strerror(-res), res);
4836 return INVALID_OPERATION;
4837 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07004838
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004839 int triggerCount = res;
4840 bool triggersMixedIn = (triggerCount > 0 || mPrevTriggers > 0);
4841 mPrevTriggers = triggerCount;
4842
Emilian Peeve23f1d92021-09-20 14:56:01 -07004843 // Do not override rotate&crop for stream configurations that include
4844 // SurfaceViews(HW_COMPOSER) output. The display rotation there will be
4845 // compensated by NATIVE_WINDOW_TRANSFORM_INVERSE_DISPLAY
4846 bool rotateAndCropChanged = mComposerOutput ? false :
4847 overrideAutoRotateAndCrop(captureRequest);
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004848 bool testPatternChanged = overrideTestPattern(captureRequest);
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004849
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004850 // If the request is the same as last, or we had triggers now or last time or
4851 // changing overrides this time
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004852 bool newRequest =
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004853 (mPrevRequest != captureRequest || triggersMixedIn ||
4854 rotateAndCropChanged || testPatternChanged) &&
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07004855 // Request settings are all the same within one batch, so only treat the first
4856 // request in a batch as new
Zhijun He54c36822018-07-18 09:33:39 -07004857 !(batchedRequest && i > 0);
Emilian Peev00420d22018-02-05 21:33:13 +00004858 if (newRequest) {
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08004859 std::set<std::string> cameraIdsWithZoom;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004860 /**
4861 * HAL workaround:
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004862 * Insert a fake trigger ID if a trigger is set but no trigger ID is
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004863 */
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004864 res = addFakeTriggerIds(captureRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004865 if (res != OK) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004866 SET_ERR("RequestThread: Unable to insert fake trigger IDs "
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004867 "(capture request %d, HAL device: %s (%d)",
4868 halRequest->frame_number, strerror(-res), res);
4869 return INVALID_OPERATION;
4870 }
4871
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07004872 {
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07004873 sp<Camera3Device> parent = mParent.promote();
4874 if (parent != nullptr) {
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -07004875 List<PhysicalCameraSettings>::iterator it;
4876 for (it = captureRequest->mSettingsList.begin();
4877 it != captureRequest->mSettingsList.end(); it++) {
Jayant Chowdhary9255ce02021-07-15 11:18:17 -07004878 if (parent->mUHRCropAndMeteringRegionMappers.find(it->cameraId) ==
4879 parent->mUHRCropAndMeteringRegionMappers.end()) {
Jayant Chowdhary65c9bf02021-09-03 16:44:16 +00004880 if (removeFwkOnlyRegionKeys(&(it->metadata)) != OK) {
4881 SET_ERR("RequestThread: Unable to remove fwk-only keys from request"
4882 "%d: %s (%d)", halRequest->frame_number, strerror(-res),
4883 res);
4884 return INVALID_OPERATION;
4885 }
Jayant Chowdhary9255ce02021-07-15 11:18:17 -07004886 continue;
4887 }
4888
4889 if (!captureRequest->mUHRCropAndMeteringRegionsUpdated) {
4890 res = parent->mUHRCropAndMeteringRegionMappers[it->cameraId].
4891 updateCaptureRequest(&(it->metadata));
4892 if (res != OK) {
4893 SET_ERR("RequestThread: Unable to correct capture requests "
4894 "for scaler crop region and metering regions for request "
4895 "%d: %s (%d)", halRequest->frame_number, strerror(-res),
4896 res);
4897 return INVALID_OPERATION;
4898 }
4899 captureRequest->mUHRCropAndMeteringRegionsUpdated = true;
Jayant Chowdhary65c9bf02021-09-03 16:44:16 +00004900 if (removeFwkOnlyRegionKeys(&(it->metadata)) != OK) {
4901 SET_ERR("RequestThread: Unable to remove fwk-only keys from request"
4902 "%d: %s (%d)", halRequest->frame_number, strerror(-res),
4903 res);
4904 return INVALID_OPERATION;
4905 }
Jayant Chowdhary9255ce02021-07-15 11:18:17 -07004906 }
4907 }
4908
4909 // Correct metadata regions for distortion correction if enabled
4910 for (it = captureRequest->mSettingsList.begin();
4911 it != captureRequest->mSettingsList.end(); it++) {
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -07004912 if (parent->mDistortionMappers.find(it->cameraId) ==
4913 parent->mDistortionMappers.end()) {
4914 continue;
4915 }
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07004916
4917 if (!captureRequest->mDistortionCorrectionUpdated) {
4918 res = parent->mDistortionMappers[it->cameraId].correctCaptureRequest(
4919 &(it->metadata));
4920 if (res != OK) {
4921 SET_ERR("RequestThread: Unable to correct capture requests "
4922 "for lens distortion for request %d: %s (%d)",
4923 halRequest->frame_number, strerror(-res), res);
4924 return INVALID_OPERATION;
4925 }
4926 captureRequest->mDistortionCorrectionUpdated = true;
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -07004927 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07004928 }
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08004929
4930 for (it = captureRequest->mSettingsList.begin();
4931 it != captureRequest->mSettingsList.end(); it++) {
4932 if (parent->mZoomRatioMappers.find(it->cameraId) ==
4933 parent->mZoomRatioMappers.end()) {
4934 continue;
4935 }
4936
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07004937 if (!captureRequest->mZoomRatioIs1x) {
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08004938 cameraIdsWithZoom.insert(it->cameraId);
4939 }
4940
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07004941 if (!captureRequest->mZoomRatioUpdated) {
4942 res = parent->mZoomRatioMappers[it->cameraId].updateCaptureRequest(
4943 &(it->metadata));
4944 if (res != OK) {
4945 SET_ERR("RequestThread: Unable to correct capture requests "
4946 "for zoom ratio for request %d: %s (%d)",
4947 halRequest->frame_number, strerror(-res), res);
4948 return INVALID_OPERATION;
4949 }
4950 captureRequest->mZoomRatioUpdated = true;
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08004951 }
4952 }
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07004953 if (captureRequest->mRotateAndCropAuto &&
4954 !captureRequest->mRotationAndCropUpdated) {
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004955 for (it = captureRequest->mSettingsList.begin();
4956 it != captureRequest->mSettingsList.end(); it++) {
4957 auto mapper = parent->mRotateAndCropMappers.find(it->cameraId);
4958 if (mapper != parent->mRotateAndCropMappers.end()) {
4959 res = mapper->second.updateCaptureRequest(&(it->metadata));
4960 if (res != OK) {
4961 SET_ERR("RequestThread: Unable to correct capture requests "
4962 "for rotate-and-crop for request %d: %s (%d)",
4963 halRequest->frame_number, strerror(-res), res);
4964 return INVALID_OPERATION;
4965 }
4966 }
4967 }
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07004968 captureRequest->mRotationAndCropUpdated = true;
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004969 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07004970 }
4971 }
4972
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004973 /**
4974 * The request should be presorted so accesses in HAL
4975 * are O(logn). Sidenote, sorting a sorted metadata is nop.
4976 */
Emilian Peevaebbe412018-01-15 13:53:24 +00004977 captureRequest->mSettingsList.begin()->metadata.sort();
4978 halRequest->settings = captureRequest->mSettingsList.begin()->metadata.getAndLock();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004979 mPrevRequest = captureRequest;
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08004980 mPrevCameraIdsWithZoom = cameraIdsWithZoom;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004981 ALOGVV("%s: Request settings are NEW", __FUNCTION__);
4982
4983 IF_ALOGV() {
4984 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
4985 find_camera_metadata_ro_entry(
4986 halRequest->settings,
4987 ANDROID_CONTROL_AF_TRIGGER,
4988 &e
4989 );
4990 if (e.count > 0) {
4991 ALOGV("%s: Request (frame num %d) had AF trigger 0x%x",
4992 __FUNCTION__,
4993 halRequest->frame_number,
4994 e.data.u8[0]);
4995 }
4996 }
4997 } else {
4998 // leave request.settings NULL to indicate 'reuse latest given'
4999 ALOGVV("%s: Request settings are REUSED",
5000 __FUNCTION__);
5001 }
5002
Emilian Peevaebbe412018-01-15 13:53:24 +00005003 if (captureRequest->mSettingsList.size() > 1) {
5004 halRequest->num_physcam_settings = captureRequest->mSettingsList.size() - 1;
5005 halRequest->physcam_id = new const char* [halRequest->num_physcam_settings];
Emilian Peev00420d22018-02-05 21:33:13 +00005006 if (newRequest) {
5007 halRequest->physcam_settings =
5008 new const camera_metadata* [halRequest->num_physcam_settings];
5009 } else {
5010 halRequest->physcam_settings = nullptr;
5011 }
Emilian Peevaebbe412018-01-15 13:53:24 +00005012 auto it = ++captureRequest->mSettingsList.begin();
5013 size_t i = 0;
5014 for (; it != captureRequest->mSettingsList.end(); it++, i++) {
5015 halRequest->physcam_id[i] = it->cameraId.c_str();
Emilian Peev00420d22018-02-05 21:33:13 +00005016 if (newRequest) {
5017 it->metadata.sort();
5018 halRequest->physcam_settings[i] = it->metadata.getAndLock();
5019 }
Emilian Peevaebbe412018-01-15 13:53:24 +00005020 }
5021 }
5022
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005023 uint32_t totalNumBuffers = 0;
5024
5025 // Fill in buffers
5026 if (captureRequest->mInputStream != NULL) {
5027 halRequest->input_buffer = &captureRequest->mInputBuffer;
Shuzhen Wang83bff122020-11-20 15:51:39 -08005028
5029 halRequest->input_width = captureRequest->mInputBufferSize.width;
5030 halRequest->input_height = captureRequest->mInputBufferSize.height;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005031 totalNumBuffers += 1;
5032 } else {
5033 halRequest->input_buffer = NULL;
5034 }
5035
Emilian Peevf4816702020-04-03 15:44:51 -07005036 outputBuffers->insertAt(camera_stream_buffer_t(), 0,
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005037 captureRequest->mOutputStreams.size());
5038 halRequest->output_buffers = outputBuffers->array();
Shuzhen Wang99080502021-03-07 21:08:20 -08005039 std::set<std::set<String8>> requestedPhysicalCameras;
Yin-Chia Yehb3a80b12018-09-04 12:13:05 -07005040
5041 sp<Camera3Device> parent = mParent.promote();
5042 if (parent == NULL) {
5043 // Should not happen, and nowhere to send errors to, so just log it
5044 CLOGE("RequestThread: Parent is gone");
5045 return INVALID_OPERATION;
5046 }
5047 nsecs_t waitDuration = kBaseGetBufferWait + parent->getExpectedInFlightDuration();
5048
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005049 SurfaceMap uniqueSurfaceIdMap;
Shuzhen Wang4a472662017-02-26 23:29:04 -08005050 for (size_t j = 0; j < captureRequest->mOutputStreams.size(); j++) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005051 sp<Camera3OutputStreamInterface> outputStream =
5052 captureRequest->mOutputStreams.editItemAt(j);
5053 int streamId = outputStream->getId();
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07005054
5055 // Prepare video buffers for high speed recording on the first video request.
5056 if (mPrepareVideoStream && outputStream->isVideoStream()) {
5057 // Only try to prepare video stream on the first video request.
5058 mPrepareVideoStream = false;
5059
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07005060 res = outputStream->startPrepare(Camera3StreamInterface::ALLOCATE_PIPELINE_MAX,
5061 false /*blockRequest*/);
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07005062 while (res == NOT_ENOUGH_DATA) {
5063 res = outputStream->prepareNextBuffer();
5064 }
5065 if (res != OK) {
5066 ALOGW("%s: Preparing video buffers for high speed failed: %s (%d)",
5067 __FUNCTION__, strerror(-res), res);
5068 outputStream->cancelPrepare();
5069 }
5070 }
5071
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005072 std::vector<size_t> uniqueSurfaceIds;
5073 res = outputStream->getUniqueSurfaceIds(
5074 captureRequest->mOutputSurfaces[streamId],
5075 &uniqueSurfaceIds);
5076 // INVALID_OPERATION is normal output for streams not supporting surfaceIds
5077 if (res != OK && res != INVALID_OPERATION) {
5078 ALOGE("%s: failed to query stream %d unique surface IDs",
5079 __FUNCTION__, streamId);
5080 return res;
5081 }
5082 if (res == OK) {
5083 uniqueSurfaceIdMap.insert({streamId, std::move(uniqueSurfaceIds)});
5084 }
5085
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07005086 if (mUseHalBufManager) {
Yin-Chia Yeh110342b2018-11-19 11:47:46 -08005087 if (outputStream->isAbandoned()) {
Yin-Chia Yeha1b56c82019-03-27 15:50:39 -07005088 ALOGV("%s: stream %d is abandoned, skipping request", __FUNCTION__, streamId);
Yin-Chia Yeh110342b2018-11-19 11:47:46 -08005089 return TIMED_OUT;
5090 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07005091 // HAL will request buffer through requestStreamBuffer API
Emilian Peevf4816702020-04-03 15:44:51 -07005092 camera_stream_buffer_t& buffer = outputBuffers->editItemAt(j);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07005093 buffer.stream = outputStream->asHalStream();
5094 buffer.buffer = nullptr;
Emilian Peevf4816702020-04-03 15:44:51 -07005095 buffer.status = CAMERA_BUFFER_STATUS_OK;
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07005096 buffer.acquire_fence = -1;
5097 buffer.release_fence = -1;
Emilian Peevf0348ae2021-01-13 13:39:45 -08005098 // Mark the output stream as unpreparable to block clients from calling
5099 // 'prepare' after this request reaches CameraHal and before the respective
5100 // buffers are requested.
5101 outputStream->markUnpreparable();
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07005102 } else {
5103 res = outputStream->getBuffer(&outputBuffers->editItemAt(j),
5104 waitDuration,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005105 captureRequest->mOutputSurfaces[streamId]);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07005106 if (res != OK) {
5107 // Can't get output buffer from gralloc queue - this could be due to
5108 // abandoned queue or other consumer misbehavior, so not a fatal
5109 // error
Yin-Chia Yeha1b56c82019-03-27 15:50:39 -07005110 ALOGV("RequestThread: Can't get output buffer, skipping request:"
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07005111 " %s (%d)", strerror(-res), res);
5112
5113 return TIMED_OUT;
5114 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005115 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08005116
5117 {
5118 sp<Camera3Device> parent = mParent.promote();
5119 if (parent != nullptr) {
5120 const String8& streamCameraId = outputStream->getPhysicalCameraId();
5121 for (const auto& settings : captureRequest->mSettingsList) {
5122 if ((streamCameraId.isEmpty() &&
5123 parent->getId() == settings.cameraId.c_str()) ||
5124 streamCameraId == settings.cameraId.c_str()) {
5125 outputStream->fireBufferRequestForFrameNumber(
5126 captureRequest->mResultExtras.frameNumber,
5127 settings.metadata);
5128 }
5129 }
5130 }
5131 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07005132
Shuzhen Wang5c22c152017-12-31 17:12:25 -08005133 String8 physicalCameraId = outputStream->getPhysicalCameraId();
Shuzhen Wang99080502021-03-07 21:08:20 -08005134 int32_t streamGroupId = outputStream->getHalStreamGroupId();
5135 if (streamGroupId != -1 && mGroupIdPhysicalCameraMap.count(streamGroupId) == 1) {
5136 requestedPhysicalCameras.insert(mGroupIdPhysicalCameraMap[streamGroupId]);
5137 } else if (!physicalCameraId.isEmpty()) {
5138 requestedPhysicalCameras.insert(std::set<String8>({physicalCameraId}));
Shuzhen Wang5c22c152017-12-31 17:12:25 -08005139 }
5140 halRequest->num_output_buffers++;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005141 }
5142 totalNumBuffers += halRequest->num_output_buffers;
5143
5144 // Log request in the in-flight queue
Shuzhen Wang4a472662017-02-26 23:29:04 -08005145 // If this request list is for constrained high speed recording (not
5146 // preview), and the current request is not the last one in the batch,
5147 // do not send callback to the app.
5148 bool hasCallback = true;
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07005149 if (batchedRequest && i != mNextRequests.size()-1) {
Shuzhen Wang4a472662017-02-26 23:29:04 -08005150 hasCallback = false;
5151 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01005152 bool isStillCapture = false;
Shuzhen Wang26abaf42018-08-28 15:41:20 -07005153 bool isZslCapture = false;
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08005154 const camera_metadata_t* settings = halRequest->settings;
5155 bool shouldUnlockSettings = false;
5156 if (settings == nullptr) {
5157 shouldUnlockSettings = true;
5158 settings = captureRequest->mSettingsList.begin()->metadata.getAndLock();
5159 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01005160 if (!mNextRequests[0].captureRequest->mSettingsList.begin()->metadata.isEmpty()) {
5161 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08005162 find_camera_metadata_ro_entry(settings, ANDROID_CONTROL_CAPTURE_INTENT, &e);
Emilian Peev9dd21f42018-08-03 13:39:29 +01005163 if ((e.count > 0) && (e.data.u8[0] == ANDROID_CONTROL_CAPTURE_INTENT_STILL_CAPTURE)) {
5164 isStillCapture = true;
5165 ATRACE_ASYNC_BEGIN("still capture", mNextRequests[i].halRequest.frame_number);
5166 }
Shuzhen Wang26abaf42018-08-28 15:41:20 -07005167
Emilian Peevaf8416e2021-02-04 17:52:43 -08005168 e = camera_metadata_ro_entry_t();
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08005169 find_camera_metadata_ro_entry(settings, ANDROID_CONTROL_ENABLE_ZSL, &e);
Shuzhen Wang26abaf42018-08-28 15:41:20 -07005170 if ((e.count > 0) && (e.data.u8[0] == ANDROID_CONTROL_ENABLE_ZSL_TRUE)) {
5171 isZslCapture = true;
5172 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01005173 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005174 res = parent->registerInFlight(halRequest->frame_number,
5175 totalNumBuffers, captureRequest->mResultExtras,
5176 /*hasInput*/halRequest->input_buffer != NULL,
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07005177 hasCallback,
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08005178 calculateMaxExpectedDuration(settings),
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005179 requestedPhysicalCameras, isStillCapture, isZslCapture,
5180 captureRequest->mRotateAndCropAuto, mPrevCameraIdsWithZoom,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005181 (mUseHalBufManager) ? uniqueSurfaceIdMap :
Shuzhen Wang316781a2020-08-18 18:11:01 -07005182 SurfaceMap{}, captureRequest->mRequestTimeNs);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005183 ALOGVV("%s: registered in flight requestId = %" PRId32 ", frameNumber = %" PRId64
5184 ", burstId = %" PRId32 ".",
5185 __FUNCTION__,
5186 captureRequest->mResultExtras.requestId, captureRequest->mResultExtras.frameNumber,
5187 captureRequest->mResultExtras.burstId);
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08005188
5189 if (shouldUnlockSettings) {
5190 captureRequest->mSettingsList.begin()->metadata.unlock(settings);
5191 }
5192
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005193 if (res != OK) {
5194 SET_ERR("RequestThread: Unable to register new in-flight request:"
5195 " %s (%d)", strerror(-res), res);
5196 return INVALID_OPERATION;
5197 }
5198 }
5199
5200 return OK;
5201}
5202
Igor Murashkin1e479c02013-09-06 16:55:14 -07005203CameraMetadata Camera3Device::RequestThread::getLatestRequest() const {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005204 ATRACE_CALL();
Igor Murashkin1e479c02013-09-06 16:55:14 -07005205 Mutex::Autolock al(mLatestRequestMutex);
5206
5207 ALOGV("RequestThread::%s", __FUNCTION__);
5208
5209 return mLatestRequest;
5210}
5211
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005212bool Camera3Device::RequestThread::isStreamPending(
5213 sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005214 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005215 Mutex::Autolock l(mRequestLock);
5216
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005217 for (const auto& nextRequest : mNextRequests) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005218 if (!nextRequest.submitted) {
5219 for (const auto& s : nextRequest.captureRequest->mOutputStreams) {
5220 if (stream == s) return true;
5221 }
5222 if (stream == nextRequest.captureRequest->mInputStream) return true;
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07005223 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07005224 }
5225
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005226 for (const auto& request : mRequestQueue) {
5227 for (const auto& s : request->mOutputStreams) {
5228 if (stream == s) return true;
5229 }
5230 if (stream == request->mInputStream) return true;
5231 }
5232
5233 for (const auto& request : mRepeatingRequests) {
5234 for (const auto& s : request->mOutputStreams) {
5235 if (stream == s) return true;
5236 }
5237 if (stream == request->mInputStream) return true;
5238 }
5239
5240 return false;
5241}
Jianing Weicb0652e2014-03-12 18:29:36 -07005242
Emilian Peev40ead602017-09-26 15:46:36 +01005243bool Camera3Device::RequestThread::isOutputSurfacePending(int streamId, size_t surfaceId) {
5244 ATRACE_CALL();
5245 Mutex::Autolock l(mRequestLock);
5246
5247 for (const auto& nextRequest : mNextRequests) {
5248 for (const auto& s : nextRequest.captureRequest->mOutputSurfaces) {
5249 if (s.first == streamId) {
5250 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
5251 if (it != s.second.end()) {
5252 return true;
5253 }
5254 }
5255 }
5256 }
5257
5258 for (const auto& request : mRequestQueue) {
5259 for (const auto& s : request->mOutputSurfaces) {
5260 if (s.first == streamId) {
5261 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
5262 if (it != s.second.end()) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005263 return true;
Emilian Peev40ead602017-09-26 15:46:36 +01005264 }
5265 }
5266 }
5267 }
5268
5269 for (const auto& request : mRepeatingRequests) {
5270 for (const auto& s : request->mOutputSurfaces) {
5271 if (s.first == streamId) {
5272 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
5273 if (it != s.second.end()) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005274 return true;
Emilian Peev40ead602017-09-26 15:46:36 +01005275 }
5276 }
5277 }
5278 }
5279
5280 return false;
5281}
5282
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07005283void Camera3Device::RequestThread::signalPipelineDrain(const std::vector<int>& streamIds) {
5284 if (!mUseHalBufManager) {
5285 ALOGE("%s called for camera device not supporting HAL buffer management", __FUNCTION__);
5286 return;
5287 }
5288
5289 Mutex::Autolock pl(mPauseLock);
5290 if (mPaused) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005291 mInterface->signalPipelineDrain(streamIds);
5292 return;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07005293 }
5294 // If request thread is still busy, wait until paused then notify HAL
5295 mNotifyPipelineDrain = true;
5296 mStreamIdsToBeDrained = streamIds;
5297}
5298
Yin-Chia Yehe52b8fa2020-07-28 00:17:58 -07005299void Camera3Device::RequestThread::resetPipelineDrain() {
5300 Mutex::Autolock pl(mPauseLock);
5301 mNotifyPipelineDrain = false;
5302 mStreamIdsToBeDrained.clear();
5303}
5304
Emilian Peevc0fe54c2020-03-11 14:05:07 -07005305void Camera3Device::RequestThread::clearPreviousRequest() {
5306 Mutex::Autolock l(mRequestLock);
5307 mPrevRequest.clear();
5308}
5309
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005310status_t Camera3Device::RequestThread::switchToOffline(
5311 const std::vector<int32_t>& streamsToKeep,
5312 /*out*/hardware::camera::device::V3_6::CameraOfflineSessionInfo* offlineSessionInfo,
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005313 /*out*/sp<hardware::camera::device::V3_6::ICameraOfflineSession>* offlineSession,
5314 /*out*/camera3::BufferRecords* bufferRecords) {
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005315 Mutex::Autolock l(mRequestLock);
5316 clearRepeatingRequestsLocked(/*lastFrameNumber*/nullptr);
5317
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005318 // Wait until request thread is fully stopped
5319 // TBD: check if request thread is being paused by other APIs (shouldn't be)
5320
5321 // We could also check for mRepeatingRequests.empty(), but the API interface
5322 // is serialized by Camera3Device::mInterfaceLock so no one should be able to submit any
5323 // new requests during the call; hence skip that check.
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005324 bool queueEmpty = mNextRequests.empty() && mRequestQueue.empty();
5325 while (!queueEmpty) {
5326 status_t res = mRequestSubmittedSignal.waitRelative(mRequestLock, kRequestSubmitTimeout);
5327 if (res == TIMED_OUT) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005328 ALOGE("%s: request thread failed to submit one request within timeout!", __FUNCTION__);
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005329 return res;
5330 } else if (res != OK) {
5331 ALOGE("%s: request thread failed to submit a request: %s (%d)!",
5332 __FUNCTION__, strerror(-res), res);
5333 return res;
5334 }
5335 queueEmpty = mNextRequests.empty() && mRequestQueue.empty();
5336 }
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005337
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005338 return mInterface->switchToOffline(
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005339 streamsToKeep, offlineSessionInfo, offlineSession, bufferRecords);
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005340}
5341
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005342status_t Camera3Device::RequestThread::setRotateAndCropAutoBehavior(
5343 camera_metadata_enum_android_scaler_rotate_and_crop_t rotateAndCropValue) {
5344 ATRACE_CALL();
5345 Mutex::Autolock l(mTriggerMutex);
5346 if (rotateAndCropValue == ANDROID_SCALER_ROTATE_AND_CROP_AUTO) {
5347 return BAD_VALUE;
5348 }
5349 mRotateAndCropOverride = rotateAndCropValue;
5350 return OK;
5351}
5352
Emilian Peeve23f1d92021-09-20 14:56:01 -07005353status_t Camera3Device::RequestThread::setComposerSurface(bool composerSurfacePresent) {
5354 ATRACE_CALL();
5355 Mutex::Autolock l(mTriggerMutex);
5356 mComposerOutput = composerSurfacePresent;
5357 return OK;
5358}
5359
Eino-Ville Talvala11afe4f2021-05-27 14:45:31 -07005360status_t Camera3Device::RequestThread::setCameraMute(int32_t muteMode) {
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005361 ATRACE_CALL();
5362 Mutex::Autolock l(mTriggerMutex);
Eino-Ville Talvala11afe4f2021-05-27 14:45:31 -07005363 if (muteMode != mCameraMute) {
5364 mCameraMute = muteMode;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005365 mCameraMuteChanged = true;
5366 }
5367 return OK;
5368}
5369
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07005370nsecs_t Camera3Device::getExpectedInFlightDuration() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005371 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005372 std::lock_guard<std::mutex> l(mInFlightLock);
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07005373 return mExpectedInflightDuration > kMinInflightDuration ?
5374 mExpectedInflightDuration : kMinInflightDuration;
5375}
5376
Emilian Peevaebbe412018-01-15 13:53:24 +00005377void Camera3Device::RequestThread::cleanupPhysicalSettings(sp<CaptureRequest> request,
Emilian Peevf4816702020-04-03 15:44:51 -07005378 camera_capture_request_t *halRequest) {
Emilian Peevaebbe412018-01-15 13:53:24 +00005379 if ((request == nullptr) || (halRequest == nullptr)) {
5380 ALOGE("%s: Invalid request!", __FUNCTION__);
5381 return;
5382 }
5383
5384 if (halRequest->num_physcam_settings > 0) {
5385 if (halRequest->physcam_id != nullptr) {
5386 delete [] halRequest->physcam_id;
5387 halRequest->physcam_id = nullptr;
5388 }
5389 if (halRequest->physcam_settings != nullptr) {
5390 auto it = ++(request->mSettingsList.begin());
5391 size_t i = 0;
5392 for (; it != request->mSettingsList.end(); it++, i++) {
5393 it->metadata.unlock(halRequest->physcam_settings[i]);
5394 }
5395 delete [] halRequest->physcam_settings;
5396 halRequest->physcam_settings = nullptr;
5397 }
5398 }
5399}
5400
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005401void Camera3Device::RequestThread::cleanUpFailedRequests(bool sendRequestError) {
5402 if (mNextRequests.empty()) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005403 return;
5404 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005405
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005406 for (auto& nextRequest : mNextRequests) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005407 // Skip the ones that have been submitted successfully.
5408 if (nextRequest.submitted) {
5409 continue;
5410 }
5411
5412 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
Emilian Peevf4816702020-04-03 15:44:51 -07005413 camera_capture_request_t* halRequest = &nextRequest.halRequest;
5414 Vector<camera_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005415
5416 if (halRequest->settings != NULL) {
Emilian Peevaebbe412018-01-15 13:53:24 +00005417 captureRequest->mSettingsList.begin()->metadata.unlock(halRequest->settings);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005418 }
5419
Emilian Peevaebbe412018-01-15 13:53:24 +00005420 cleanupPhysicalSettings(captureRequest, halRequest);
5421
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005422 if (captureRequest->mInputStream != NULL) {
Emilian Peevf4816702020-04-03 15:44:51 -07005423 captureRequest->mInputBuffer.status = CAMERA_BUFFER_STATUS_ERROR;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005424 captureRequest->mInputStream->returnInputBuffer(captureRequest->mInputBuffer);
5425 }
5426
Yin-Chia Yeh21cb47b2019-01-18 15:08:17 -08005427 // No output buffer can be returned when using HAL buffer manager
5428 if (!mUseHalBufManager) {
5429 for (size_t i = 0; i < halRequest->num_output_buffers; i++) {
5430 //Buffers that failed processing could still have
5431 //valid acquire fence.
5432 int acquireFence = (*outputBuffers)[i].acquire_fence;
5433 if (0 <= acquireFence) {
5434 close(acquireFence);
5435 outputBuffers->editItemAt(i).acquire_fence = -1;
5436 }
Emilian Peevf4816702020-04-03 15:44:51 -07005437 outputBuffers->editItemAt(i).status = CAMERA_BUFFER_STATUS_ERROR;
Yin-Chia Yeh21cb47b2019-01-18 15:08:17 -08005438 captureRequest->mOutputStreams.editItemAt(i)->returnBuffer((*outputBuffers)[i], 0,
5439 /*timestampIncreasing*/true, std::vector<size_t> (),
5440 captureRequest->mResultExtras.frameNumber);
Emilian Peevc58cf4c2017-05-11 17:23:41 +01005441 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005442 }
5443
5444 if (sendRequestError) {
5445 Mutex::Autolock l(mRequestLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005446 sp<NotificationListener> listener = mListener.promote();
5447 if (listener != NULL) {
5448 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08005449 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005450 captureRequest->mResultExtras);
5451 }
5452 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07005453
5454 // Remove yet-to-be submitted inflight request from inflightMap
5455 {
5456 sp<Camera3Device> parent = mParent.promote();
5457 if (parent != NULL) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005458 std::lock_guard<std::mutex> l(parent->mInFlightLock);
Shuzhen Wangcadb3302016-11-04 14:17:56 -07005459 ssize_t idx = parent->mInFlightMap.indexOfKey(captureRequest->mResultExtras.frameNumber);
5460 if (idx >= 0) {
5461 ALOGV("%s: Remove inflight request from queue: frameNumber %" PRId64,
5462 __FUNCTION__, captureRequest->mResultExtras.frameNumber);
5463 parent->removeInFlightMapEntryLocked(idx);
5464 }
5465 }
5466 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005467 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07005468
5469 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005470 mNextRequests.clear();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005471}
5472
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005473void Camera3Device::RequestThread::waitForNextRequestBatch() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005474 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005475 // Optimized a bit for the simple steady-state case (single repeating
5476 // request), to avoid putting that request in the queue temporarily.
5477 Mutex::Autolock l(mRequestLock);
5478
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005479 assert(mNextRequests.empty());
5480
5481 NextRequest nextRequest;
5482 nextRequest.captureRequest = waitForNextRequestLocked();
5483 if (nextRequest.captureRequest == nullptr) {
5484 return;
5485 }
5486
Emilian Peevf4816702020-04-03 15:44:51 -07005487 nextRequest.halRequest = camera_capture_request_t();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005488 nextRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005489 mNextRequests.add(nextRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005490
5491 // Wait for additional requests
5492 const size_t batchSize = nextRequest.captureRequest->mBatchSize;
5493
5494 for (size_t i = 1; i < batchSize; i++) {
5495 NextRequest additionalRequest;
5496 additionalRequest.captureRequest = waitForNextRequestLocked();
5497 if (additionalRequest.captureRequest == nullptr) {
5498 break;
5499 }
5500
Emilian Peevf4816702020-04-03 15:44:51 -07005501 additionalRequest.halRequest = camera_capture_request_t();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005502 additionalRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005503 mNextRequests.add(additionalRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005504 }
5505
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005506 if (mNextRequests.size() < batchSize) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08005507 ALOGE("RequestThread: only get %zu out of %zu requests. Skipping requests.",
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005508 mNextRequests.size(), batchSize);
5509 cleanUpFailedRequests(/*sendRequestError*/true);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005510 }
5511
5512 return;
5513}
5514
5515sp<Camera3Device::CaptureRequest>
5516 Camera3Device::RequestThread::waitForNextRequestLocked() {
5517 status_t res;
5518 sp<CaptureRequest> nextRequest;
5519
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005520 while (mRequestQueue.empty()) {
5521 if (!mRepeatingRequests.empty()) {
5522 // Always atomically enqueue all requests in a repeating request
5523 // list. Guarantees a complete in-sequence set of captures to
5524 // application.
5525 const RequestList &requests = mRepeatingRequests;
Shuzhen Wang316781a2020-08-18 18:11:01 -07005526 if (mFirstRepeating) {
5527 mFirstRepeating = false;
5528 } else {
5529 for (auto& request : requests) {
5530 // For repeating requests, override timestamp request using
5531 // the time a request is inserted into the request queue,
5532 // because the original repeating request will have an old
5533 // fixed timestamp.
5534 request->mRequestTimeNs = systemTime();
5535 }
5536 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005537 RequestList::const_iterator firstRequest =
5538 requests.begin();
5539 nextRequest = *firstRequest;
5540 mRequestQueue.insert(mRequestQueue.end(),
5541 ++firstRequest,
5542 requests.end());
5543 // No need to wait any longer
Jianing Weicb0652e2014-03-12 18:29:36 -07005544
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005545 mRepeatingLastFrameNumber = mFrameNumber + requests.size() - 1;
Jianing Weicb0652e2014-03-12 18:29:36 -07005546
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005547 break;
5548 }
5549
5550 res = mRequestSignal.waitRelative(mRequestLock, kRequestTimeout);
5551
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005552 if ((mRequestQueue.empty() && mRepeatingRequests.empty()) ||
5553 exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005554 Mutex::Autolock pl(mPauseLock);
5555 if (mPaused == false) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005556 ALOGV("%s: RequestThread: Going idle", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005557 mPaused = true;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07005558 if (mNotifyPipelineDrain) {
5559 mInterface->signalPipelineDrain(mStreamIdsToBeDrained);
5560 mNotifyPipelineDrain = false;
5561 mStreamIdsToBeDrained.clear();
5562 }
Yin-Chia Yehc300a072019-02-13 14:56:57 -08005563 // Let the tracker know
5564 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5565 if (statusTracker != 0) {
5566 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
5567 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005568 sp<Camera3Device> parent = mParent.promote();
5569 if (parent != nullptr) {
5570 parent->mRequestBufferSM.onRequestThreadPaused();
5571 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005572 }
5573 // Stop waiting for now and let thread management happen
5574 return NULL;
5575 }
5576 }
5577
5578 if (nextRequest == NULL) {
5579 // Don't have a repeating request already in hand, so queue
5580 // must have an entry now.
5581 RequestList::iterator firstRequest =
5582 mRequestQueue.begin();
5583 nextRequest = *firstRequest;
5584 mRequestQueue.erase(firstRequest);
Shuzhen Wang9d066012016-09-30 11:30:20 -07005585 if (mRequestQueue.empty() && !nextRequest->mRepeating) {
5586 sp<NotificationListener> listener = mListener.promote();
5587 if (listener != NULL) {
5588 listener->notifyRequestQueueEmpty();
5589 }
5590 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005591 }
5592
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005593 // In case we've been unpaused by setPaused clearing mDoPause, need to
5594 // update internal pause state (capture/setRepeatingRequest unpause
5595 // directly).
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005596 Mutex::Autolock pl(mPauseLock);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005597 if (mPaused) {
5598 ALOGV("%s: RequestThread: Unpaused", __FUNCTION__);
5599 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5600 if (statusTracker != 0) {
5601 statusTracker->markComponentActive(mStatusId);
5602 }
5603 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005604 mPaused = false;
5605
5606 // Check if we've reconfigured since last time, and reset the preview
5607 // request if so. Can't use 'NULL request == repeat' across configure calls.
5608 if (mReconfigured) {
5609 mPrevRequest.clear();
5610 mReconfigured = false;
5611 }
5612
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005613 if (nextRequest != NULL) {
5614 nextRequest->mResultExtras.frameNumber = mFrameNumber++;
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07005615 nextRequest->mResultExtras.afTriggerId = mCurrentAfTriggerId;
5616 nextRequest->mResultExtras.precaptureTriggerId = mCurrentPreCaptureTriggerId;
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07005617
5618 // Since RequestThread::clear() removes buffers from the input stream,
5619 // get the right buffer here before unlocking mRequestLock
5620 if (nextRequest->mInputStream != NULL) {
Shuzhen Wang83bff122020-11-20 15:51:39 -08005621 res = nextRequest->mInputStream->getInputBuffer(&nextRequest->mInputBuffer,
5622 &nextRequest->mInputBufferSize);
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07005623 if (res != OK) {
5624 // Can't get input buffer from gralloc queue - this could be due to
5625 // disconnected queue or other producer misbehavior, so not a fatal
5626 // error
5627 ALOGE("%s: Can't get input buffer, skipping request:"
5628 " %s (%d)", __FUNCTION__, strerror(-res), res);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005629
5630 sp<NotificationListener> listener = mListener.promote();
5631 if (listener != NULL) {
5632 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08005633 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07005634 nextRequest->mResultExtras);
5635 }
5636 return NULL;
5637 }
5638 }
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005639 }
Chien-Yu Chend196d612015-06-22 19:49:01 -07005640
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005641 return nextRequest;
5642}
5643
5644bool Camera3Device::RequestThread::waitIfPaused() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005645 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005646 status_t res;
5647 Mutex::Autolock l(mPauseLock);
5648 while (mDoPause) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005649 if (mPaused == false) {
5650 mPaused = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005651 ALOGV("%s: RequestThread: Paused", __FUNCTION__);
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07005652 if (mNotifyPipelineDrain) {
5653 mInterface->signalPipelineDrain(mStreamIdsToBeDrained);
5654 mNotifyPipelineDrain = false;
5655 mStreamIdsToBeDrained.clear();
5656 }
Yin-Chia Yehc300a072019-02-13 14:56:57 -08005657 // Let the tracker know
5658 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5659 if (statusTracker != 0) {
5660 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
5661 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005662 sp<Camera3Device> parent = mParent.promote();
5663 if (parent != nullptr) {
5664 parent->mRequestBufferSM.onRequestThreadPaused();
5665 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005666 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005667
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005668 res = mDoPauseSignal.waitRelative(mPauseLock, kRequestTimeout);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005669 if (res == TIMED_OUT || exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005670 return true;
5671 }
5672 }
5673 // We don't set mPaused to false here, because waitForNextRequest needs
5674 // to further manage the paused state in case of starvation.
5675 return false;
5676}
5677
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005678void Camera3Device::RequestThread::unpauseForNewRequests() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005679 ATRACE_CALL();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005680 // With work to do, mark thread as unpaused.
5681 // If paused by request (setPaused), don't resume, to avoid
5682 // extra signaling/waiting overhead to waitUntilPaused
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005683 mRequestSignal.signal();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005684 Mutex::Autolock p(mPauseLock);
5685 if (!mDoPause) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005686 ALOGV("%s: RequestThread: Going active", __FUNCTION__);
5687 if (mPaused) {
5688 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5689 if (statusTracker != 0) {
5690 statusTracker->markComponentActive(mStatusId);
5691 }
5692 }
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005693 mPaused = false;
5694 }
5695}
5696
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07005697void Camera3Device::RequestThread::setErrorState(const char *fmt, ...) {
5698 sp<Camera3Device> parent = mParent.promote();
5699 if (parent != NULL) {
5700 va_list args;
5701 va_start(args, fmt);
5702
5703 parent->setErrorStateV(fmt, args);
5704
5705 va_end(args);
5706 }
5707}
5708
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005709status_t Camera3Device::RequestThread::insertTriggers(
5710 const sp<CaptureRequest> &request) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005711 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005712 Mutex::Autolock al(mTriggerMutex);
5713
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07005714 sp<Camera3Device> parent = mParent.promote();
5715 if (parent == NULL) {
5716 CLOGE("RequestThread: Parent is gone");
5717 return DEAD_OBJECT;
5718 }
5719
Emilian Peevaebbe412018-01-15 13:53:24 +00005720 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005721 size_t count = mTriggerMap.size();
5722
5723 for (size_t i = 0; i < count; ++i) {
5724 RequestTrigger trigger = mTriggerMap.valueAt(i);
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005725 uint32_t tag = trigger.metadataTag;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07005726
5727 if (tag == ANDROID_CONTROL_AF_TRIGGER_ID || tag == ANDROID_CONTROL_AE_PRECAPTURE_ID) {
5728 bool isAeTrigger = (trigger.metadataTag == ANDROID_CONTROL_AE_PRECAPTURE_ID);
5729 uint32_t triggerId = static_cast<uint32_t>(trigger.entryValue);
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07005730 if (isAeTrigger) {
5731 request->mResultExtras.precaptureTriggerId = triggerId;
5732 mCurrentPreCaptureTriggerId = triggerId;
5733 } else {
5734 request->mResultExtras.afTriggerId = triggerId;
5735 mCurrentAfTriggerId = triggerId;
5736 }
Emilian Peev7e25e5e2017-04-07 15:48:49 +01005737 continue;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07005738 }
5739
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005740 camera_metadata_entry entry = metadata.find(tag);
5741
5742 if (entry.count > 0) {
5743 /**
5744 * Already has an entry for this trigger in the request.
5745 * Rewrite it with our requested trigger value.
5746 */
5747 RequestTrigger oldTrigger = trigger;
5748
5749 oldTrigger.entryValue = entry.data.u8[0];
5750
5751 mTriggerReplacedMap.add(tag, oldTrigger);
5752 } else {
5753 /**
5754 * More typical, no trigger entry, so we just add it
5755 */
5756 mTriggerRemovedMap.add(tag, trigger);
5757 }
5758
5759 status_t res;
5760
5761 switch (trigger.getTagType()) {
5762 case TYPE_BYTE: {
5763 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
5764 res = metadata.update(tag,
5765 &entryValue,
5766 /*count*/1);
5767 break;
5768 }
5769 case TYPE_INT32:
5770 res = metadata.update(tag,
5771 &trigger.entryValue,
5772 /*count*/1);
5773 break;
5774 default:
5775 ALOGE("%s: Type not supported: 0x%x",
5776 __FUNCTION__,
5777 trigger.getTagType());
5778 return INVALID_OPERATION;
5779 }
5780
5781 if (res != OK) {
5782 ALOGE("%s: Failed to update request metadata with trigger tag %s"
5783 ", value %d", __FUNCTION__, trigger.getTagName(),
5784 trigger.entryValue);
5785 return res;
5786 }
5787
5788 ALOGV("%s: Mixed in trigger %s, value %d", __FUNCTION__,
5789 trigger.getTagName(),
5790 trigger.entryValue);
5791 }
5792
5793 mTriggerMap.clear();
5794
5795 return count;
5796}
5797
5798status_t Camera3Device::RequestThread::removeTriggers(
5799 const sp<CaptureRequest> &request) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005800 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005801 Mutex::Autolock al(mTriggerMutex);
5802
Emilian Peevaebbe412018-01-15 13:53:24 +00005803 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005804
5805 /**
5806 * Replace all old entries with their old values.
5807 */
5808 for (size_t i = 0; i < mTriggerReplacedMap.size(); ++i) {
5809 RequestTrigger trigger = mTriggerReplacedMap.valueAt(i);
5810
5811 status_t res;
5812
5813 uint32_t tag = trigger.metadataTag;
5814 switch (trigger.getTagType()) {
5815 case TYPE_BYTE: {
5816 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
5817 res = metadata.update(tag,
5818 &entryValue,
5819 /*count*/1);
5820 break;
5821 }
5822 case TYPE_INT32:
5823 res = metadata.update(tag,
5824 &trigger.entryValue,
5825 /*count*/1);
5826 break;
5827 default:
5828 ALOGE("%s: Type not supported: 0x%x",
5829 __FUNCTION__,
5830 trigger.getTagType());
5831 return INVALID_OPERATION;
5832 }
5833
5834 if (res != OK) {
5835 ALOGE("%s: Failed to restore request metadata with trigger tag %s"
5836 ", trigger value %d", __FUNCTION__,
5837 trigger.getTagName(), trigger.entryValue);
5838 return res;
5839 }
5840 }
5841 mTriggerReplacedMap.clear();
5842
5843 /**
5844 * Remove all new entries.
5845 */
5846 for (size_t i = 0; i < mTriggerRemovedMap.size(); ++i) {
5847 RequestTrigger trigger = mTriggerRemovedMap.valueAt(i);
5848 status_t res = metadata.erase(trigger.metadataTag);
5849
5850 if (res != OK) {
5851 ALOGE("%s: Failed to erase metadata with trigger tag %s"
5852 ", trigger value %d", __FUNCTION__,
5853 trigger.getTagName(), trigger.entryValue);
5854 return res;
5855 }
5856 }
5857 mTriggerRemovedMap.clear();
5858
5859 return OK;
5860}
5861
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04005862status_t Camera3Device::RequestThread::addFakeTriggerIds(
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005863 const sp<CaptureRequest> &request) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08005864 // Trigger ID 0 had special meaning in the HAL2 spec, so avoid it here
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04005865 static const int32_t fakeTriggerId = 1;
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005866 status_t res;
5867
Emilian Peevaebbe412018-01-15 13:53:24 +00005868 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005869
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04005870 // If AF trigger is active, insert a fake AF trigger ID if none already
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005871 // exists
5872 camera_metadata_entry afTrigger = metadata.find(ANDROID_CONTROL_AF_TRIGGER);
5873 camera_metadata_entry afId = metadata.find(ANDROID_CONTROL_AF_TRIGGER_ID);
5874 if (afTrigger.count > 0 &&
5875 afTrigger.data.u8[0] != ANDROID_CONTROL_AF_TRIGGER_IDLE &&
5876 afId.count == 0) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04005877 res = metadata.update(ANDROID_CONTROL_AF_TRIGGER_ID, &fakeTriggerId, 1);
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005878 if (res != OK) return res;
5879 }
5880
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04005881 // If AE precapture trigger is active, insert a fake precapture trigger ID
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005882 // if none already exists
5883 camera_metadata_entry pcTrigger =
5884 metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER);
5885 camera_metadata_entry pcId = metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_ID);
5886 if (pcTrigger.count > 0 &&
5887 pcTrigger.data.u8[0] != ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_IDLE &&
5888 pcId.count == 0) {
5889 res = metadata.update(ANDROID_CONTROL_AE_PRECAPTURE_ID,
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04005890 &fakeTriggerId, 1);
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005891 if (res != OK) return res;
5892 }
5893
5894 return OK;
5895}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005896
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005897bool Camera3Device::RequestThread::overrideAutoRotateAndCrop(
5898 const sp<CaptureRequest> &request) {
5899 ATRACE_CALL();
5900
5901 if (request->mRotateAndCropAuto) {
5902 Mutex::Autolock l(mTriggerMutex);
5903 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
5904
5905 auto rotateAndCropEntry = metadata.find(ANDROID_SCALER_ROTATE_AND_CROP);
5906 if (rotateAndCropEntry.count > 0) {
5907 if (rotateAndCropEntry.data.u8[0] == mRotateAndCropOverride) {
5908 return false;
5909 } else {
5910 rotateAndCropEntry.data.u8[0] = mRotateAndCropOverride;
5911 return true;
5912 }
5913 } else {
5914 uint8_t rotateAndCrop_u8 = mRotateAndCropOverride;
5915 metadata.update(ANDROID_SCALER_ROTATE_AND_CROP,
5916 &rotateAndCrop_u8, 1);
5917 return true;
5918 }
5919 }
5920 return false;
5921}
5922
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005923bool Camera3Device::RequestThread::overrideTestPattern(
5924 const sp<CaptureRequest> &request) {
5925 ATRACE_CALL();
5926
Eino-Ville Talvala1646c3c2021-07-29 13:48:40 -07005927 if (!mSupportCameraMute) return false;
Eino-Ville Talvalac2459842021-07-22 16:36:36 -07005928
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005929 Mutex::Autolock l(mTriggerMutex);
5930
5931 bool changed = false;
5932
Shuzhen Wang911c6a32021-10-27 13:36:03 -07005933 // For a multi-camera, the physical cameras support the same set of
5934 // test pattern modes as the logical camera.
5935 for (auto& settings : request->mSettingsList) {
5936 CameraMetadata &metadata = settings.metadata;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005937
Shuzhen Wang911c6a32021-10-27 13:36:03 -07005938 int32_t testPatternMode = settings.mOriginalTestPatternMode;
5939 int32_t testPatternData[4] = {
5940 settings.mOriginalTestPatternData[0],
5941 settings.mOriginalTestPatternData[1],
5942 settings.mOriginalTestPatternData[2],
5943 settings.mOriginalTestPatternData[3]
5944 };
5945 if (mCameraMute != ANDROID_SENSOR_TEST_PATTERN_MODE_OFF) {
5946 testPatternMode = mCameraMute;
5947 testPatternData[0] = 0;
5948 testPatternData[1] = 0;
5949 testPatternData[2] = 0;
5950 testPatternData[3] = 0;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005951 }
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005952
Shuzhen Wang911c6a32021-10-27 13:36:03 -07005953 auto testPatternEntry = metadata.find(ANDROID_SENSOR_TEST_PATTERN_MODE);
5954 bool supportTestPatternModeKey = settings.mHasTestPatternModeTag;
5955 if (testPatternEntry.count > 0) {
5956 if (testPatternEntry.data.i32[0] != testPatternMode) {
5957 testPatternEntry.data.i32[0] = testPatternMode;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005958 changed = true;
5959 }
Shuzhen Wang911c6a32021-10-27 13:36:03 -07005960 } else if (supportTestPatternModeKey) {
5961 metadata.update(ANDROID_SENSOR_TEST_PATTERN_MODE,
5962 &testPatternMode, 1);
5963 changed = true;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005964 }
Shuzhen Wang911c6a32021-10-27 13:36:03 -07005965
5966 auto testPatternColor = metadata.find(ANDROID_SENSOR_TEST_PATTERN_DATA);
5967 bool supportTestPatternDataKey = settings.mHasTestPatternDataTag;
5968 if (testPatternColor.count >= 4) {
5969 for (size_t i = 0; i < 4; i++) {
5970 if (testPatternColor.data.i32[i] != testPatternData[i]) {
5971 testPatternColor.data.i32[i] = testPatternData[i];
5972 changed = true;
5973 }
5974 }
5975 } else if (supportTestPatternDataKey) {
5976 metadata.update(ANDROID_SENSOR_TEST_PATTERN_DATA,
5977 testPatternData, 4);
5978 changed = true;
5979 }
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005980 }
5981
5982 return changed;
5983}
5984
Cliff Wuc2ad9c82021-04-21 00:58:58 +08005985status_t Camera3Device::RequestThread::setHalInterface(
5986 sp<HalInterface> newHalInterface) {
5987 if (newHalInterface.get() == nullptr) {
5988 ALOGE("%s: The newHalInterface does not exist!", __FUNCTION__);
5989 return DEAD_OBJECT;
5990 }
5991
5992 mInterface = newHalInterface;
5993
5994 return OK;
5995}
5996
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005997/**
5998 * PreparerThread inner class methods
5999 */
6000
6001Camera3Device::PreparerThread::PreparerThread() :
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07006002 Thread(/*canCallJava*/false), mListener(nullptr),
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006003 mActive(false), mCancelNow(false), mCurrentMaxCount(0), mCurrentPrepareComplete(false) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006004}
6005
6006Camera3Device::PreparerThread::~PreparerThread() {
6007 Thread::requestExitAndWait();
6008 if (mCurrentStream != nullptr) {
6009 mCurrentStream->cancelPrepare();
6010 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
6011 mCurrentStream.clear();
6012 }
6013 clear();
6014}
6015
Ruben Brunkc78ac262015-08-13 17:58:46 -07006016status_t Camera3Device::PreparerThread::prepare(int maxCount, sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07006017 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006018 status_t res;
6019
6020 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006021 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006022
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07006023 res = stream->startPrepare(maxCount, true /*blockRequest*/);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006024 if (res == OK) {
6025 // No preparation needed, fire listener right off
6026 ALOGV("%s: Stream %d already prepared", __FUNCTION__, stream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006027 if (listener != NULL) {
6028 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006029 }
6030 return OK;
6031 } else if (res != NOT_ENOUGH_DATA) {
6032 return res;
6033 }
6034
6035 // Need to prepare, start up thread if necessary
6036 if (!mActive) {
6037 // mRunning will change to false before the thread fully shuts down, so wait to be sure it
6038 // isn't running
6039 Thread::requestExitAndWait();
6040 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
6041 if (res != OK) {
6042 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__, res, strerror(-res));
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006043 if (listener != NULL) {
6044 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006045 }
6046 return res;
6047 }
6048 mCancelNow = false;
6049 mActive = true;
6050 ALOGV("%s: Preparer stream started", __FUNCTION__);
6051 }
6052
6053 // queue up the work
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006054 mPendingStreams.emplace(maxCount, stream);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006055 ALOGV("%s: Stream %d queued for preparing", __FUNCTION__, stream->getId());
6056
6057 return OK;
6058}
6059
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006060void Camera3Device::PreparerThread::pause() {
6061 ATRACE_CALL();
6062
6063 Mutex::Autolock l(mLock);
6064
6065 std::unordered_map<int, sp<camera3::Camera3StreamInterface> > pendingStreams;
6066 pendingStreams.insert(mPendingStreams.begin(), mPendingStreams.end());
6067 sp<camera3::Camera3StreamInterface> currentStream = mCurrentStream;
6068 int currentMaxCount = mCurrentMaxCount;
6069 mPendingStreams.clear();
6070 mCancelNow = true;
6071 while (mActive) {
6072 auto res = mThreadActiveSignal.waitRelative(mLock, kActiveTimeout);
6073 if (res == TIMED_OUT) {
6074 ALOGE("%s: Timed out waiting on prepare thread!", __FUNCTION__);
6075 return;
6076 } else if (res != OK) {
6077 ALOGE("%s: Encountered an error: %d waiting on prepare thread!", __FUNCTION__, res);
6078 return;
6079 }
6080 }
6081
6082 //Check whether the prepare thread was able to complete the current
6083 //stream. In case work is still pending emplace it along with the rest
6084 //of the streams in the pending list.
6085 if (currentStream != nullptr) {
6086 if (!mCurrentPrepareComplete) {
6087 pendingStreams.emplace(currentMaxCount, currentStream);
6088 }
6089 }
6090
6091 mPendingStreams.insert(pendingStreams.begin(), pendingStreams.end());
6092 for (const auto& it : mPendingStreams) {
6093 it.second->cancelPrepare();
6094 }
6095}
6096
6097status_t Camera3Device::PreparerThread::resume() {
6098 ATRACE_CALL();
6099 status_t res;
6100
6101 Mutex::Autolock l(mLock);
6102 sp<NotificationListener> listener = mListener.promote();
6103
6104 if (mActive) {
6105 ALOGE("%s: Trying to resume an already active prepare thread!", __FUNCTION__);
6106 return NO_INIT;
6107 }
6108
6109 auto it = mPendingStreams.begin();
6110 for (; it != mPendingStreams.end();) {
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07006111 res = it->second->startPrepare(it->first, true /*blockRequest*/);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006112 if (res == OK) {
6113 if (listener != NULL) {
6114 listener->notifyPrepared(it->second->getId());
6115 }
6116 it = mPendingStreams.erase(it);
6117 } else if (res != NOT_ENOUGH_DATA) {
6118 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__,
6119 res, strerror(-res));
6120 it = mPendingStreams.erase(it);
6121 } else {
6122 it++;
6123 }
6124 }
6125
6126 if (mPendingStreams.empty()) {
6127 return OK;
6128 }
6129
6130 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
6131 if (res != OK) {
6132 ALOGE("%s: Unable to start preparer stream: %d (%s)",
6133 __FUNCTION__, res, strerror(-res));
6134 return res;
6135 }
6136 mCancelNow = false;
6137 mActive = true;
6138 ALOGV("%s: Preparer stream started", __FUNCTION__);
6139
6140 return OK;
6141}
6142
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006143status_t Camera3Device::PreparerThread::clear() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07006144 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006145 Mutex::Autolock l(mLock);
6146
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006147 for (const auto& it : mPendingStreams) {
6148 it.second->cancelPrepare();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006149 }
6150 mPendingStreams.clear();
6151 mCancelNow = true;
6152
6153 return OK;
6154}
6155
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006156void Camera3Device::PreparerThread::setNotificationListener(wp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07006157 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006158 Mutex::Autolock l(mLock);
6159 mListener = listener;
6160}
6161
6162bool Camera3Device::PreparerThread::threadLoop() {
6163 status_t res;
6164 {
6165 Mutex::Autolock l(mLock);
6166 if (mCurrentStream == nullptr) {
6167 // End thread if done with work
6168 if (mPendingStreams.empty()) {
6169 ALOGV("%s: Preparer stream out of work", __FUNCTION__);
6170 // threadLoop _must not_ re-acquire mLock after it sets mActive to false; would
6171 // cause deadlock with prepare()'s requestExitAndWait triggered by !mActive.
6172 mActive = false;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006173 mThreadActiveSignal.signal();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006174 return false;
6175 }
6176
6177 // Get next stream to prepare
6178 auto it = mPendingStreams.begin();
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006179 mCurrentStream = it->second;
6180 mCurrentMaxCount = it->first;
6181 mCurrentPrepareComplete = false;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006182 mPendingStreams.erase(it);
6183 ATRACE_ASYNC_BEGIN("stream prepare", mCurrentStream->getId());
6184 ALOGV("%s: Preparing stream %d", __FUNCTION__, mCurrentStream->getId());
6185 } else if (mCancelNow) {
6186 mCurrentStream->cancelPrepare();
6187 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
6188 ALOGV("%s: Cancelling stream %d prepare", __FUNCTION__, mCurrentStream->getId());
6189 mCurrentStream.clear();
6190 mCancelNow = false;
6191 return true;
6192 }
6193 }
6194
6195 res = mCurrentStream->prepareNextBuffer();
6196 if (res == NOT_ENOUGH_DATA) return true;
6197 if (res != OK) {
6198 // Something bad happened; try to recover by cancelling prepare and
6199 // signalling listener anyway
6200 ALOGE("%s: Stream %d returned error %d (%s) during prepare", __FUNCTION__,
6201 mCurrentStream->getId(), res, strerror(-res));
6202 mCurrentStream->cancelPrepare();
6203 }
6204
6205 // This stream has finished, notify listener
6206 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006207 sp<NotificationListener> listener = mListener.promote();
6208 if (listener != NULL) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006209 ALOGV("%s: Stream %d prepare done, signaling listener", __FUNCTION__,
6210 mCurrentStream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006211 listener->notifyPrepared(mCurrentStream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006212 }
6213
6214 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
6215 mCurrentStream.clear();
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006216 mCurrentPrepareComplete = true;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006217
6218 return true;
6219}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07006220
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006221status_t Camera3Device::RequestBufferStateMachine::initialize(
6222 sp<camera3::StatusTracker> statusTracker) {
6223 if (statusTracker == nullptr) {
6224 ALOGE("%s: statusTracker is null", __FUNCTION__);
6225 return BAD_VALUE;
6226 }
6227
6228 std::lock_guard<std::mutex> lock(mLock);
6229 mStatusTracker = statusTracker;
Yin-Chia Yeh87b3ec02019-06-03 10:44:39 -07006230 mRequestBufferStatusId = statusTracker->addComponent("BufferRequestSM");
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006231 return OK;
6232}
6233
6234bool Camera3Device::RequestBufferStateMachine::startRequestBuffer() {
6235 std::lock_guard<std::mutex> lock(mLock);
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08006236 if (mStatus == RB_STATUS_READY || mStatus == RB_STATUS_PENDING_STOP) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006237 mRequestBufferOngoing = true;
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08006238 notifyTrackerLocked(/*active*/true);
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006239 return true;
6240 }
6241 return false;
6242}
6243
6244void Camera3Device::RequestBufferStateMachine::endRequestBuffer() {
6245 std::lock_guard<std::mutex> lock(mLock);
6246 if (!mRequestBufferOngoing) {
6247 ALOGE("%s called without a successful startRequestBuffer call first!", __FUNCTION__);
6248 return;
6249 }
6250 mRequestBufferOngoing = false;
6251 if (mStatus == RB_STATUS_PENDING_STOP) {
6252 checkSwitchToStopLocked();
6253 }
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08006254 notifyTrackerLocked(/*active*/false);
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006255}
6256
6257void Camera3Device::RequestBufferStateMachine::onStreamsConfigured() {
6258 std::lock_guard<std::mutex> lock(mLock);
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006259 mSwitchedToOffline = false;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006260 mStatus = RB_STATUS_READY;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006261 return;
6262}
6263
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08006264void Camera3Device::RequestBufferStateMachine::onSubmittingRequest() {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006265 std::lock_guard<std::mutex> lock(mLock);
6266 mRequestThreadPaused = false;
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08006267 // inflight map register actually happens in prepareHalRequest now, but it is close enough
6268 // approximation.
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006269 mInflightMapEmpty = false;
6270 if (mStatus == RB_STATUS_STOPPED) {
6271 mStatus = RB_STATUS_READY;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006272 }
6273 return;
6274}
6275
6276void Camera3Device::RequestBufferStateMachine::onRequestThreadPaused() {
6277 std::lock_guard<std::mutex> lock(mLock);
6278 mRequestThreadPaused = true;
6279 if (mStatus == RB_STATUS_PENDING_STOP) {
6280 checkSwitchToStopLocked();
6281 }
6282 return;
6283}
6284
6285void Camera3Device::RequestBufferStateMachine::onInflightMapEmpty() {
6286 std::lock_guard<std::mutex> lock(mLock);
6287 mInflightMapEmpty = true;
6288 if (mStatus == RB_STATUS_PENDING_STOP) {
6289 checkSwitchToStopLocked();
6290 }
6291 return;
6292}
6293
6294void Camera3Device::RequestBufferStateMachine::onWaitUntilIdle() {
6295 std::lock_guard<std::mutex> lock(mLock);
6296 if (!checkSwitchToStopLocked()) {
6297 mStatus = RB_STATUS_PENDING_STOP;
6298 }
6299 return;
6300}
6301
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006302bool Camera3Device::RequestBufferStateMachine::onSwitchToOfflineSuccess() {
6303 std::lock_guard<std::mutex> lock(mLock);
6304 if (mRequestBufferOngoing) {
6305 ALOGE("%s: HAL must not be requesting buffer after HAL returns switchToOffline!",
6306 __FUNCTION__);
6307 return false;
6308 }
6309 mSwitchedToOffline = true;
6310 mInflightMapEmpty = true;
6311 mRequestThreadPaused = true;
6312 mStatus = RB_STATUS_STOPPED;
6313 return true;
6314}
6315
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006316void Camera3Device::RequestBufferStateMachine::notifyTrackerLocked(bool active) {
6317 sp<StatusTracker> statusTracker = mStatusTracker.promote();
6318 if (statusTracker != nullptr) {
6319 if (active) {
6320 statusTracker->markComponentActive(mRequestBufferStatusId);
6321 } else {
6322 statusTracker->markComponentIdle(mRequestBufferStatusId, Fence::NO_FENCE);
6323 }
6324 }
6325}
6326
6327bool Camera3Device::RequestBufferStateMachine::checkSwitchToStopLocked() {
6328 if (mInflightMapEmpty && mRequestThreadPaused && !mRequestBufferOngoing) {
6329 mStatus = RB_STATUS_STOPPED;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006330 return true;
6331 }
6332 return false;
6333}
6334
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006335bool Camera3Device::startRequestBuffer() {
6336 return mRequestBufferSM.startRequestBuffer();
6337}
Shuzhen Wang268a1362018-10-16 16:32:59 -07006338
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006339void Camera3Device::endRequestBuffer() {
6340 mRequestBufferSM.endRequestBuffer();
6341}
Shuzhen Wang268a1362018-10-16 16:32:59 -07006342
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006343nsecs_t Camera3Device::getWaitDuration() {
6344 return kBaseGetBufferWait + getExpectedInFlightDuration();
6345}
Shuzhen Wang268a1362018-10-16 16:32:59 -07006346
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006347void Camera3Device::getInflightBufferKeys(std::vector<std::pair<int32_t, int32_t>>* out) {
6348 mInterface->getInflightBufferKeys(out);
6349}
Shuzhen Wang268a1362018-10-16 16:32:59 -07006350
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006351void Camera3Device::getInflightRequestBufferKeys(std::vector<uint64_t>* out) {
6352 mInterface->getInflightRequestBufferKeys(out);
6353}
Shuzhen Wang268a1362018-10-16 16:32:59 -07006354
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006355std::vector<sp<Camera3StreamInterface>> Camera3Device::getAllStreams() {
6356 std::vector<sp<Camera3StreamInterface>> ret;
6357 bool hasInputStream = mInputStream != nullptr;
6358 ret.reserve(mOutputStreams.size() + mDeletedStreams.size() + ((hasInputStream) ? 1 : 0));
6359 if (hasInputStream) {
6360 ret.push_back(mInputStream);
Shuzhen Wang268a1362018-10-16 16:32:59 -07006361 }
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006362 for (size_t i = 0; i < mOutputStreams.size(); i++) {
6363 ret.push_back(mOutputStreams[i]);
6364 }
6365 for (size_t i = 0; i < mDeletedStreams.size(); i++) {
6366 ret.push_back(mDeletedStreams[i]);
6367 }
6368 return ret;
Shuzhen Wang268a1362018-10-16 16:32:59 -07006369}
6370
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006371status_t Camera3Device::switchToOffline(
6372 const std::vector<int32_t>& streamsToKeep,
6373 /*out*/ sp<CameraOfflineSessionBase>* session) {
6374 ATRACE_CALL();
6375 if (session == nullptr) {
6376 ALOGE("%s: session must not be null", __FUNCTION__);
6377 return BAD_VALUE;
6378 }
6379
6380 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006381
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006382 bool hasInputStream = mInputStream != nullptr;
6383 int32_t inputStreamId = hasInputStream ? mInputStream->getId() : -1;
6384 bool inputStreamSupportsOffline = hasInputStream ?
6385 mInputStream->getOfflineProcessingSupport() : false;
6386 auto outputStreamIds = mOutputStreams.getStreamIds();
6387 auto streamIds = outputStreamIds;
6388 if (hasInputStream) {
6389 streamIds.push_back(mInputStream->getId());
6390 }
6391
6392 // Check all streams in streamsToKeep supports offline mode
6393 for (auto id : streamsToKeep) {
6394 if (std::find(streamIds.begin(), streamIds.end(), id) == streamIds.end()) {
6395 ALOGE("%s: Unknown stream ID %d", __FUNCTION__, id);
6396 return BAD_VALUE;
6397 } else if (id == inputStreamId) {
6398 if (!inputStreamSupportsOffline) {
6399 ALOGE("%s: input stream %d cannot be switched to offline",
6400 __FUNCTION__, id);
6401 return BAD_VALUE;
6402 }
6403 } else {
6404 sp<camera3::Camera3OutputStreamInterface> stream = mOutputStreams.get(id);
6405 if (!stream->getOfflineProcessingSupport()) {
6406 ALOGE("%s: output stream %d cannot be switched to offline",
6407 __FUNCTION__, id);
6408 return BAD_VALUE;
6409 }
6410 }
6411 }
6412
6413 // TODO: block surface sharing and surface group streams until we can support them
6414
6415 // Stop repeating request, wait until all remaining requests are submitted, then call into
6416 // HAL switchToOffline
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006417 hardware::camera::device::V3_6::CameraOfflineSessionInfo offlineSessionInfo;
6418 sp<hardware::camera::device::V3_6::ICameraOfflineSession> offlineSession;
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006419 camera3::BufferRecords bufferRecords;
6420 status_t ret = mRequestThread->switchToOffline(
6421 streamsToKeep, &offlineSessionInfo, &offlineSession, &bufferRecords);
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006422
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006423 if (ret != OK) {
6424 SET_ERR("Switch to offline failed: %s (%d)", strerror(-ret), ret);
6425 return ret;
6426 }
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006427
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006428 bool succ = mRequestBufferSM.onSwitchToOfflineSuccess();
6429 if (!succ) {
6430 SET_ERR("HAL must not be calling requestStreamBuffers call");
6431 // TODO: block ALL callbacks from HAL till app configured new streams?
6432 return UNKNOWN_ERROR;
6433 }
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006434
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006435 // Verify offlineSessionInfo
6436 std::vector<int32_t> offlineStreamIds;
6437 offlineStreamIds.reserve(offlineSessionInfo.offlineStreams.size());
6438 for (auto offlineStream : offlineSessionInfo.offlineStreams) {
6439 // verify stream IDs
6440 int32_t id = offlineStream.id;
6441 if (std::find(streamIds.begin(), streamIds.end(), id) == streamIds.end()) {
6442 SET_ERR("stream ID %d not found!", id);
6443 return UNKNOWN_ERROR;
6444 }
6445
6446 // When not using HAL buf manager, only allow streams requested by app to be preserved
6447 if (!mUseHalBufManager) {
6448 if (std::find(streamsToKeep.begin(), streamsToKeep.end(), id) == streamsToKeep.end()) {
6449 SET_ERR("stream ID %d must not be switched to offline!", id);
6450 return UNKNOWN_ERROR;
6451 }
6452 }
6453
6454 offlineStreamIds.push_back(id);
6455 sp<Camera3StreamInterface> stream = (id == inputStreamId) ?
6456 static_cast<sp<Camera3StreamInterface>>(mInputStream) :
6457 static_cast<sp<Camera3StreamInterface>>(mOutputStreams.get(id));
6458 // Verify number of outstanding buffers
6459 if (stream->getOutstandingBuffersCount() != offlineStream.numOutstandingBuffers) {
6460 SET_ERR("Offline stream %d # of remaining buffer mismatch: (%zu,%d) (service/HAL)",
6461 id, stream->getOutstandingBuffersCount(), offlineStream.numOutstandingBuffers);
6462 return UNKNOWN_ERROR;
6463 }
6464 }
6465
6466 // Verify all streams to be deleted don't have any outstanding buffers
6467 if (hasInputStream && std::find(offlineStreamIds.begin(), offlineStreamIds.end(),
6468 inputStreamId) == offlineStreamIds.end()) {
6469 if (mInputStream->hasOutstandingBuffers()) {
6470 SET_ERR("Input stream %d still has %zu outstanding buffer!",
6471 inputStreamId, mInputStream->getOutstandingBuffersCount());
6472 return UNKNOWN_ERROR;
6473 }
6474 }
6475
6476 for (const auto& outStreamId : outputStreamIds) {
6477 if (std::find(offlineStreamIds.begin(), offlineStreamIds.end(),
6478 outStreamId) == offlineStreamIds.end()) {
6479 auto outStream = mOutputStreams.get(outStreamId);
6480 if (outStream->hasOutstandingBuffers()) {
6481 SET_ERR("Output stream %d still has %zu outstanding buffer!",
6482 outStreamId, outStream->getOutstandingBuffersCount());
6483 return UNKNOWN_ERROR;
6484 }
6485 }
6486 }
6487
6488 InFlightRequestMap offlineReqs;
6489 // Verify inflight requests and their pending buffers
6490 {
6491 std::lock_guard<std::mutex> l(mInFlightLock);
6492 for (auto offlineReq : offlineSessionInfo.offlineRequests) {
6493 int idx = mInFlightMap.indexOfKey(offlineReq.frameNumber);
6494 if (idx == NAME_NOT_FOUND) {
6495 SET_ERR("Offline request frame number %d not found!", offlineReq.frameNumber);
6496 return UNKNOWN_ERROR;
6497 }
6498
6499 const auto& inflightReq = mInFlightMap.valueAt(idx);
6500 // TODO: check specific stream IDs
6501 size_t numBuffersLeft = static_cast<size_t>(inflightReq.numBuffersLeft);
6502 if (numBuffersLeft != offlineReq.pendingStreams.size()) {
6503 SET_ERR("Offline request # of remaining buffer mismatch: (%d,%d) (service/HAL)",
6504 inflightReq.numBuffersLeft, offlineReq.pendingStreams.size());
6505 return UNKNOWN_ERROR;
6506 }
6507 offlineReqs.add(offlineReq.frameNumber, inflightReq);
6508 }
6509 }
6510
6511 // Create Camera3OfflineSession and transfer object ownership
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006512 // (streams, inflight requests, buffer caches)
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006513 camera3::StreamSet offlineStreamSet;
6514 sp<camera3::Camera3Stream> inputStream;
6515 for (auto offlineStream : offlineSessionInfo.offlineStreams) {
6516 int32_t id = offlineStream.id;
6517 if (mInputStream != nullptr && id == mInputStream->getId()) {
6518 inputStream = mInputStream;
6519 } else {
6520 offlineStreamSet.add(id, mOutputStreams.get(id));
6521 }
6522 }
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006523
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006524 // TODO: check if we need to lock before copying states
6525 // though technically no other thread should be talking to Camera3Device at this point
6526 Camera3OfflineStates offlineStates(
6527 mTagMonitor, mVendorTagId, mUseHalBufManager, mNeedFixupMonochromeTags,
Shuzhen Wangb7b42652020-05-07 11:59:02 -07006528 mUsePartialResult, mNumPartialResults, mLastCompletedRegularFrameNumber,
6529 mLastCompletedReprocessFrameNumber, mLastCompletedZslFrameNumber,
6530 mNextResultFrameNumber, mNextReprocessResultFrameNumber,
6531 mNextZslStillResultFrameNumber, mNextShutterFrameNumber,
6532 mNextReprocessShutterFrameNumber, mNextZslStillShutterFrameNumber,
6533 mDeviceInfo, mPhysicalDeviceInfoMap, mDistortionMappers,
6534 mZoomRatioMappers, mRotateAndCropMappers);
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006535
6536 *session = new Camera3OfflineSession(mId, inputStream, offlineStreamSet,
6537 std::move(bufferRecords), offlineReqs, offlineStates, offlineSession);
6538
6539 // Delete all streams that has been transferred to offline session
6540 Mutex::Autolock l(mLock);
6541 for (auto offlineStream : offlineSessionInfo.offlineStreams) {
6542 int32_t id = offlineStream.id;
6543 if (mInputStream != nullptr && id == mInputStream->getId()) {
6544 mInputStream.clear();
6545 } else {
6546 mOutputStreams.remove(id);
6547 }
6548 }
6549
6550 // disconnect all other streams and switch to UNCONFIGURED state
6551 if (mInputStream != nullptr) {
6552 ret = mInputStream->disconnect();
6553 if (ret != OK) {
6554 SET_ERR_L("disconnect input stream failed!");
6555 return UNKNOWN_ERROR;
6556 }
6557 }
6558
6559 for (auto streamId : mOutputStreams.getStreamIds()) {
6560 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
6561 ret = stream->disconnect();
6562 if (ret != OK) {
6563 SET_ERR_L("disconnect output stream %d failed!", streamId);
6564 return UNKNOWN_ERROR;
6565 }
6566 }
6567
6568 mInputStream.clear();
6569 mOutputStreams.clear();
6570 mNeedConfig = true;
6571 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
6572 mOperatingMode = NO_MODE;
6573 mIsConstrainedHighSpeedConfiguration = false;
Emilian Peevc0fe54c2020-03-11 14:05:07 -07006574 mRequestThread->clearPreviousRequest();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006575
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006576 return OK;
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006577 // TO be done by CameraDeviceClient/Camera3OfflineSession
6578 // register the offline client to camera service
6579 // Setup result passthing threads etc
6580 // Initialize offline session so HAL can start sending callback to it (result Fmq)
6581 // TODO: check how many onIdle callback will be sent
6582 // Java side to make sure the CameraCaptureSession is properly closed
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006583}
6584
Emilian Peevcc0b7952020-01-07 13:54:47 -08006585void Camera3Device::getOfflineStreamIds(std::vector<int> *offlineStreamIds) {
6586 ATRACE_CALL();
6587
6588 if (offlineStreamIds == nullptr) {
6589 return;
6590 }
6591
6592 Mutex::Autolock il(mInterfaceLock);
6593
6594 auto streamIds = mOutputStreams.getStreamIds();
6595 bool hasInputStream = mInputStream != nullptr;
6596 if (hasInputStream && mInputStream->getOfflineProcessingSupport()) {
6597 offlineStreamIds->push_back(mInputStream->getId());
6598 }
6599
6600 for (const auto & streamId : streamIds) {
6601 sp<camera3::Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
6602 // Streams that use the camera buffer manager are currently not supported in
6603 // offline mode
6604 if (stream->getOfflineProcessingSupport() &&
6605 (stream->getStreamSetId() == CAMERA3_STREAM_SET_ID_INVALID)) {
6606 offlineStreamIds->push_back(streamId);
6607 }
6608 }
6609}
6610
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08006611status_t Camera3Device::setRotateAndCropAutoBehavior(
6612 camera_metadata_enum_android_scaler_rotate_and_crop_t rotateAndCropValue) {
6613 ATRACE_CALL();
6614 Mutex::Autolock il(mInterfaceLock);
6615 Mutex::Autolock l(mLock);
6616 if (mRequestThread == nullptr) {
6617 return INVALID_OPERATION;
6618 }
6619 return mRequestThread->setRotateAndCropAutoBehavior(rotateAndCropValue);
6620}
6621
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08006622bool Camera3Device::supportsCameraMute() {
6623 Mutex::Autolock il(mInterfaceLock);
6624 Mutex::Autolock l(mLock);
6625
6626 return mSupportCameraMute;
6627}
6628
6629status_t Camera3Device::setCameraMute(bool enabled) {
6630 ATRACE_CALL();
6631 Mutex::Autolock il(mInterfaceLock);
6632 Mutex::Autolock l(mLock);
6633
6634 if (mRequestThread == nullptr || !mSupportCameraMute) {
6635 return INVALID_OPERATION;
6636 }
Eino-Ville Talvala11afe4f2021-05-27 14:45:31 -07006637 int32_t muteMode =
6638 !enabled ? ANDROID_SENSOR_TEST_PATTERN_MODE_OFF :
6639 mSupportTestPatternSolidColor ? ANDROID_SENSOR_TEST_PATTERN_MODE_SOLID_COLOR :
6640 ANDROID_SENSOR_TEST_PATTERN_MODE_BLACK;
6641 return mRequestThread->setCameraMute(muteMode);
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08006642}
6643
Cliff Wuc2ad9c82021-04-21 00:58:58 +08006644status_t Camera3Device::injectCamera(const String8& injectedCamId,
6645 sp<CameraProviderManager> manager) {
6646 ALOGI("%s Injection camera: injectedCamId = %s", __FUNCTION__, injectedCamId.string());
6647 ATRACE_CALL();
6648 Mutex::Autolock il(mInterfaceLock);
6649
6650 status_t res = NO_ERROR;
6651 if (mInjectionMethods->isInjecting()) {
6652 if (injectedCamId == mInjectionMethods->getInjectedCamId()) {
6653 return OK;
6654 } else {
6655 res = mInjectionMethods->stopInjection();
6656 if (res != OK) {
6657 ALOGE("%s: Failed to stop the injection camera! ret != NO_ERROR: %d",
6658 __FUNCTION__, res);
6659 return res;
6660 }
6661 }
6662 }
6663
6664 res = mInjectionMethods->injectionInitialize(injectedCamId, manager, this);
6665 if (res != OK) {
6666 ALOGE("%s: Failed to initialize the injection camera! ret != NO_ERROR: %d",
6667 __FUNCTION__, res);
6668 return res;
6669 }
6670
6671 camera3::camera_stream_configuration injectionConfig;
6672 std::vector<uint32_t> injectionBufferSizes;
6673 mInjectionMethods->getInjectionConfig(&injectionConfig, &injectionBufferSizes);
6674 // When the second display of android is cast to the remote device, and the opened camera is
6675 // also cast to the second display, in this case, because the camera has configured the streams
6676 // at this time, we can directly call injectCamera() to replace the internal camera with
6677 // injection camera.
6678 if (mOperatingMode >= 0 && injectionConfig.num_streams > 0
6679 && injectionBufferSizes.size() > 0) {
6680 ALOGV("%s: The opened camera is directly cast to the remote device.", __FUNCTION__);
6681 res = mInjectionMethods->injectCamera(
6682 injectionConfig, injectionBufferSizes);
6683 if (res != OK) {
6684 ALOGE("Can't finish inject camera process!");
6685 return res;
6686 }
6687 }
6688
6689 return OK;
6690}
6691
6692status_t Camera3Device::stopInjection() {
6693 ALOGI("%s: Injection camera: stopInjection", __FUNCTION__);
6694 Mutex::Autolock il(mInterfaceLock);
6695 return mInjectionMethods->stopInjection();
6696}
6697
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08006698}; // namespace android