blob: 2f571a65c30b72b472ddfdc93171a438023c901f [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
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -0800605ssize_t Camera3Device::getJpegBufferSize(const CameraMetadata &info, uint32_t width,
606 uint32_t height) const {
Jayant Chowdharycd3d36b2021-07-10 10:53:53 -0700607 // Get max jpeg size (area-wise) for default sensor pixel mode
608 camera3::Size maxDefaultJpegResolution =
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -0800609 SessionConfigurationUtils::getMaxJpegResolution(info,
Jayant Chowdharycd3d36b2021-07-10 10:53:53 -0700610 /*isUltraHighResolutionSensor*/false);
611 // Get max jpeg size (area-wise) for max resolution sensor pixel mode / 0 if
612 // not ultra high res sensor
613 camera3::Size uhrMaxJpegResolution =
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -0800614 SessionConfigurationUtils::getMaxJpegResolution(info,
Jayant Chowdharycd3d36b2021-07-10 10:53:53 -0700615 /*isUltraHighResolution*/true);
616 if (maxDefaultJpegResolution.width == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800617 ALOGE("%s: Camera %s: Can't find valid available jpeg sizes in static metadata!",
618 __FUNCTION__, mId.string());
Zhijun Hef7da0962014-04-24 13:27:56 -0700619 return BAD_VALUE;
620 }
Jayant Chowdharycd3d36b2021-07-10 10:53:53 -0700621 bool useMaxSensorPixelModeThreshold = false;
622 if (uhrMaxJpegResolution.width != 0 &&
623 width * height > maxDefaultJpegResolution.width * maxDefaultJpegResolution.height) {
624 // Use the ultra high res max jpeg size and max jpeg buffer size
625 useMaxSensorPixelModeThreshold = true;
626 }
Zhijun Hef7da0962014-04-24 13:27:56 -0700627
Zhijun Hef7da0962014-04-24 13:27:56 -0700628 // Get max jpeg buffer size
629 ssize_t maxJpegBufferSize = 0;
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -0800630 camera_metadata_ro_entry jpegBufMaxSize = info.find(ANDROID_JPEG_MAX_SIZE);
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700631 if (jpegBufMaxSize.count == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800632 ALOGE("%s: Camera %s: Can't find maximum JPEG size in static metadata!", __FUNCTION__,
633 mId.string());
Zhijun Hef7da0962014-04-24 13:27:56 -0700634 return BAD_VALUE;
635 }
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700636 maxJpegBufferSize = jpegBufMaxSize.data.i32[0];
Jayant Chowdharycd3d36b2021-07-10 10:53:53 -0700637
638 camera3::Size chosenMaxJpegResolution = maxDefaultJpegResolution;
639 if (useMaxSensorPixelModeThreshold) {
640 maxJpegBufferSize =
641 SessionConfigurationUtils::getUHRMaxJpegBufferSize(uhrMaxJpegResolution,
642 maxDefaultJpegResolution, maxJpegBufferSize);
643 chosenMaxJpegResolution = uhrMaxJpegResolution;
644 }
Yin-Chia Yeh0c4e56d2015-01-09 15:21:27 -0800645 assert(kMinJpegBufferSize < maxJpegBufferSize);
Zhijun Hef7da0962014-04-24 13:27:56 -0700646
647 // Calculate final jpeg buffer size for the given resolution.
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700648 float scaleFactor = ((float) (width * height)) /
Jayant Chowdharycd3d36b2021-07-10 10:53:53 -0700649 (chosenMaxJpegResolution.width * chosenMaxJpegResolution.height);
Yin-Chia Yeh0c4e56d2015-01-09 15:21:27 -0800650 ssize_t jpegBufferSize = scaleFactor * (maxJpegBufferSize - kMinJpegBufferSize) +
651 kMinJpegBufferSize;
Zhijun Hef7da0962014-04-24 13:27:56 -0700652 if (jpegBufferSize > maxJpegBufferSize) {
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -0800653 ALOGI("%s: jpeg buffer size calculated is > maxJpeg bufferSize(%zd), clamping",
654 __FUNCTION__, maxJpegBufferSize);
Zhijun Hef7da0962014-04-24 13:27:56 -0700655 jpegBufferSize = maxJpegBufferSize;
Zhijun Hef7da0962014-04-24 13:27:56 -0700656 }
Zhijun Hef7da0962014-04-24 13:27:56 -0700657 return jpegBufferSize;
658}
659
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -0800660ssize_t Camera3Device::getPointCloudBufferSize(const CameraMetadata &info) const {
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700661 const int FLOATS_PER_POINT=4;
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -0800662 camera_metadata_ro_entry maxPointCount = info.find(ANDROID_DEPTH_MAX_DEPTH_SAMPLES);
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700663 if (maxPointCount.count == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800664 ALOGE("%s: Camera %s: Can't find maximum depth point cloud size in static metadata!",
665 __FUNCTION__, mId.string());
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700666 return BAD_VALUE;
667 }
668 ssize_t maxBytesForPointCloud = sizeof(android_depth_points) +
669 maxPointCount.data.i32[0] * sizeof(float) * FLOATS_PER_POINT;
670 return maxBytesForPointCloud;
671}
672
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -0800673ssize_t Camera3Device::getRawOpaqueBufferSize(const CameraMetadata &info, int32_t width,
674 int32_t height, bool maxResolution) const {
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800675 const int PER_CONFIGURATION_SIZE = 3;
676 const int WIDTH_OFFSET = 0;
677 const int HEIGHT_OFFSET = 1;
678 const int SIZE_OFFSET = 2;
679 camera_metadata_ro_entry rawOpaqueSizes =
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -0800680 info.find(
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -0800681 camera3::SessionConfigurationUtils::getAppropriateModeTag(
682 ANDROID_SENSOR_OPAQUE_RAW_SIZE,
683 maxResolution));
Aurimas Liutikasbc57b122016-02-16 09:59:16 -0800684 size_t count = rawOpaqueSizes.count;
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800685 if (count == 0 || (count % PER_CONFIGURATION_SIZE)) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800686 ALOGE("%s: Camera %s: bad opaque RAW size static metadata length(%zu)!",
687 __FUNCTION__, mId.string(), count);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800688 return BAD_VALUE;
689 }
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700690
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800691 for (size_t i = 0; i < count; i += PER_CONFIGURATION_SIZE) {
692 if (width == rawOpaqueSizes.data.i32[i + WIDTH_OFFSET] &&
693 height == rawOpaqueSizes.data.i32[i + HEIGHT_OFFSET]) {
694 return rawOpaqueSizes.data.i32[i + SIZE_OFFSET];
695 }
696 }
697
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800698 ALOGE("%s: Camera %s: cannot find size for %dx%d opaque RAW image!",
699 __FUNCTION__, mId.string(), width, height);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800700 return BAD_VALUE;
701}
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700702
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800703status_t Camera3Device::dump(int fd, const Vector<String16> &args) {
704 ATRACE_CALL();
705 (void)args;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700706
707 // Try to lock, but continue in case of failure (to avoid blocking in
708 // deadlocks)
709 bool gotInterfaceLock = tryLockSpinRightRound(mInterfaceLock);
710 bool gotLock = tryLockSpinRightRound(mLock);
711
712 ALOGW_IF(!gotInterfaceLock,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800713 "Camera %s: %s: Unable to lock interface lock, proceeding anyway",
714 mId.string(), __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700715 ALOGW_IF(!gotLock,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800716 "Camera %s: %s: Unable to lock main lock, proceeding anyway",
717 mId.string(), __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700718
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800719 bool dumpTemplates = false;
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700720
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800721 String16 templatesOption("-t");
722 int n = args.size();
723 for (int i = 0; i < n; i++) {
724 if (args[i] == templatesOption) {
725 dumpTemplates = true;
726 }
Emilian Peevbd8c5032018-02-14 23:05:40 +0000727 if (args[i] == TagMonitor::kMonitorOption) {
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700728 if (i + 1 < n) {
729 String8 monitorTags = String8(args[i + 1]);
730 if (monitorTags == "off") {
731 mTagMonitor.disableMonitoring();
732 } else {
733 mTagMonitor.parseTagsToMonitor(monitorTags);
734 }
735 } else {
736 mTagMonitor.disableMonitoring();
737 }
738 }
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800739 }
740
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800741 String8 lines;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800742
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800743 const char *status =
744 mStatus == STATUS_ERROR ? "ERROR" :
745 mStatus == STATUS_UNINITIALIZED ? "UNINITIALIZED" :
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700746 mStatus == STATUS_UNCONFIGURED ? "UNCONFIGURED" :
747 mStatus == STATUS_CONFIGURED ? "CONFIGURED" :
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800748 mStatus == STATUS_ACTIVE ? "ACTIVE" :
749 "Unknown";
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700750
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800751 lines.appendFormat(" Device status: %s\n", status);
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700752 if (mStatus == STATUS_ERROR) {
753 lines.appendFormat(" Error cause: %s\n", mErrorCause.string());
754 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800755 lines.appendFormat(" Stream configuration:\n");
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800756 const char *mode =
757 mOperatingMode == static_cast<int>(StreamConfigurationMode::NORMAL_MODE) ? "NORMAL" :
758 mOperatingMode == static_cast<int>(
759 StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE) ? "CONSTRAINED_HIGH_SPEED" :
760 "CUSTOM";
761 lines.appendFormat(" Operation mode: %s (%d) \n", mode, mOperatingMode);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800762
763 if (mInputStream != NULL) {
764 write(fd, lines.string(), lines.size());
765 mInputStream->dump(fd, args);
766 } else {
767 lines.appendFormat(" No input stream.\n");
768 write(fd, lines.string(), lines.size());
769 }
770 for (size_t i = 0; i < mOutputStreams.size(); i++) {
771 mOutputStreams[i]->dump(fd,args);
772 }
773
Zhijun He431503c2016-03-07 17:30:16 -0800774 if (mBufferManager != NULL) {
775 lines = String8(" Camera3 Buffer Manager:\n");
776 write(fd, lines.string(), lines.size());
777 mBufferManager->dump(fd, args);
778 }
Zhijun He125684a2015-12-26 15:07:30 -0800779
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700780 lines = String8(" In-flight requests:\n");
Emilian Peeva6138c52021-06-24 12:52:38 -0700781 if (mInFlightLock.try_lock()) {
782 if (mInFlightMap.size() == 0) {
783 lines.append(" None\n");
784 } else {
785 for (size_t i = 0; i < mInFlightMap.size(); i++) {
786 InFlightRequest r = mInFlightMap.valueAt(i);
787 lines.appendFormat(" Frame %d | Timestamp: %" PRId64 ", metadata"
788 " arrived: %s, buffers left: %d\n", mInFlightMap.keyAt(i),
789 r.shutterTimestamp, r.haveResultMetadata ? "true" : "false",
790 r.numBuffersLeft);
791 }
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700792 }
Emilian Peeva6138c52021-06-24 12:52:38 -0700793 mInFlightLock.unlock();
794 } else {
795 lines.append(" Failed to acquire In-flight lock!\n");
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700796 }
797 write(fd, lines.string(), lines.size());
798
Shuzhen Wang686f6442017-06-20 16:16:04 -0700799 if (mRequestThread != NULL) {
800 mRequestThread->dumpCaptureRequestLatency(fd,
801 " ProcessCaptureRequest latency histogram:");
802 }
803
Igor Murashkin1e479c02013-09-06 16:55:14 -0700804 {
805 lines = String8(" Last request sent:\n");
806 write(fd, lines.string(), lines.size());
807
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700808 CameraMetadata lastRequest = getLatestRequestLocked();
Igor Murashkin1e479c02013-09-06 16:55:14 -0700809 lastRequest.dump(fd, /*verbosity*/2, /*indentation*/6);
810 }
811
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800812 if (dumpTemplates) {
Emilian Peevf4816702020-04-03 15:44:51 -0700813 const char *templateNames[CAMERA_TEMPLATE_COUNT] = {
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800814 "TEMPLATE_PREVIEW",
815 "TEMPLATE_STILL_CAPTURE",
816 "TEMPLATE_VIDEO_RECORD",
817 "TEMPLATE_VIDEO_SNAPSHOT",
818 "TEMPLATE_ZERO_SHUTTER_LAG",
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -0800819 "TEMPLATE_MANUAL",
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800820 };
821
Emilian Peevf4816702020-04-03 15:44:51 -0700822 for (int i = 1; i < CAMERA_TEMPLATE_COUNT; i++) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800823 camera_metadata_t *templateRequest = nullptr;
824 mInterface->constructDefaultRequestSettings(
Emilian Peevf4816702020-04-03 15:44:51 -0700825 (camera_request_template_t) i, &templateRequest);
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800826 lines = String8::format(" HAL Request %s:\n", templateNames[i-1]);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800827 if (templateRequest == nullptr) {
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800828 lines.append(" Not supported\n");
829 write(fd, lines.string(), lines.size());
830 } else {
831 write(fd, lines.string(), lines.size());
832 dump_indented_camera_metadata(templateRequest,
833 fd, /*verbosity*/2, /*indentation*/8);
834 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800835 free_camera_metadata(templateRequest);
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800836 }
837 }
838
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700839 mTagMonitor.dumpMonitoredMetadata(fd);
840
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800841 if (mInterface->valid()) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -0800842 lines = String8(" HAL device dump:\n");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800843 write(fd, lines.string(), lines.size());
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800844 mInterface->dump(fd);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800845 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800846
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700847 if (gotLock) mLock.unlock();
848 if (gotInterfaceLock) mInterfaceLock.unlock();
849
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800850 return OK;
851}
852
Avichal Rakesh7e53cad2021-10-05 13:46:30 -0700853status_t Camera3Device::startWatchingTags(const String8 &tags) {
854 mTagMonitor.parseTagsToMonitor(tags);
855 return OK;
856}
857
858status_t Camera3Device::stopWatchingTags() {
859 mTagMonitor.disableMonitoring();
860 return OK;
861}
862
863status_t Camera3Device::dumpWatchedEventsToVector(std::vector<std::string> &out) {
864 mTagMonitor.getLatestMonitoredTagEvents(out);
865 return OK;
866}
867
Emilian Peevfaa4bde2020-01-23 12:19:37 -0800868const CameraMetadata& Camera3Device::infoPhysical(const String8& physicalId) const {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800869 ALOGVV("%s: E", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800870 if (CC_UNLIKELY(mStatus == STATUS_UNINITIALIZED ||
871 mStatus == STATUS_ERROR)) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700872 ALOGW("%s: Access to static info %s!", __FUNCTION__,
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800873 mStatus == STATUS_ERROR ?
874 "when in error state" : "before init");
875 }
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700876 if (physicalId.isEmpty()) {
877 return mDeviceInfo;
878 } else {
879 std::string id(physicalId.c_str());
880 if (mPhysicalDeviceInfoMap.find(id) != mPhysicalDeviceInfoMap.end()) {
881 return mPhysicalDeviceInfoMap.at(id);
882 } else {
883 ALOGE("%s: Invalid physical camera id %s", __FUNCTION__, physicalId.c_str());
884 return mDeviceInfo;
885 }
886 }
887}
888
889const CameraMetadata& Camera3Device::info() const {
890 String8 emptyId;
Emilian Peevfaa4bde2020-01-23 12:19:37 -0800891 return infoPhysical(emptyId);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800892}
893
Jianing Wei90e59c92014-03-12 18:29:36 -0700894status_t Camera3Device::checkStatusOkToCaptureLocked() {
895 switch (mStatus) {
896 case STATUS_ERROR:
897 CLOGE("Device has encountered a serious error");
898 return INVALID_OPERATION;
899 case STATUS_UNINITIALIZED:
900 CLOGE("Device not initialized");
901 return INVALID_OPERATION;
902 case STATUS_UNCONFIGURED:
903 case STATUS_CONFIGURED:
904 case STATUS_ACTIVE:
905 // OK
906 break;
907 default:
908 SET_ERR_L("Unexpected status: %d", mStatus);
909 return INVALID_OPERATION;
910 }
911 return OK;
912}
913
914status_t Camera3Device::convertMetadataListToRequestListLocked(
Emilian Peevaebbe412018-01-15 13:53:24 +0000915 const List<const PhysicalCameraSettingsList> &metadataList,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700916 const std::list<const SurfaceMap> &surfaceMaps,
Shuzhen Wang316781a2020-08-18 18:11:01 -0700917 bool repeating, nsecs_t requestTimeNs,
Shuzhen Wang9d066012016-09-30 11:30:20 -0700918 RequestList *requestList) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700919 if (requestList == NULL) {
920 CLOGE("requestList cannot be NULL.");
921 return BAD_VALUE;
922 }
923
Jianing Weicb0652e2014-03-12 18:29:36 -0700924 int32_t burstId = 0;
Emilian Peevaebbe412018-01-15 13:53:24 +0000925 List<const PhysicalCameraSettingsList>::const_iterator metadataIt = metadataList.begin();
Shuzhen Wang0129d522016-10-30 22:43:41 -0700926 std::list<const SurfaceMap>::const_iterator surfaceMapIt = surfaceMaps.begin();
927 for (; metadataIt != metadataList.end() && surfaceMapIt != surfaceMaps.end();
928 ++metadataIt, ++surfaceMapIt) {
929 sp<CaptureRequest> newRequest = setUpRequestLocked(*metadataIt, *surfaceMapIt);
Jianing Wei90e59c92014-03-12 18:29:36 -0700930 if (newRequest == 0) {
931 CLOGE("Can't create capture request");
932 return BAD_VALUE;
933 }
Jianing Weicb0652e2014-03-12 18:29:36 -0700934
Shuzhen Wang9d066012016-09-30 11:30:20 -0700935 newRequest->mRepeating = repeating;
Shuzhen Wang316781a2020-08-18 18:11:01 -0700936 newRequest->mRequestTimeNs = requestTimeNs;
Shuzhen Wang9d066012016-09-30 11:30:20 -0700937
Jianing Weicb0652e2014-03-12 18:29:36 -0700938 // Setup burst Id and request Id
939 newRequest->mResultExtras.burstId = burstId++;
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -0800940 auto requestIdEntry = metadataIt->begin()->metadata.find(ANDROID_REQUEST_ID);
941 if (requestIdEntry.count == 0) {
Jianing Weicb0652e2014-03-12 18:29:36 -0700942 CLOGE("RequestID does not exist in metadata");
943 return BAD_VALUE;
944 }
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -0800945 newRequest->mResultExtras.requestId = requestIdEntry.data.i32[0];
Jianing Weicb0652e2014-03-12 18:29:36 -0700946
Jianing Wei90e59c92014-03-12 18:29:36 -0700947 requestList->push_back(newRequest);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700948
949 ALOGV("%s: requestId = %" PRId32, __FUNCTION__, newRequest->mResultExtras.requestId);
Jianing Wei90e59c92014-03-12 18:29:36 -0700950 }
Shuzhen Wang0129d522016-10-30 22:43:41 -0700951 if (metadataIt != metadataList.end() || surfaceMapIt != surfaceMaps.end()) {
952 ALOGE("%s: metadataList and surfaceMaps are not the same size!", __FUNCTION__);
953 return BAD_VALUE;
954 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -0700955
956 // Setup batch size if this is a high speed video recording request.
957 if (mIsConstrainedHighSpeedConfiguration && requestList->size() > 0) {
958 auto firstRequest = requestList->begin();
959 for (auto& outputStream : (*firstRequest)->mOutputStreams) {
960 if (outputStream->isVideoStream()) {
961 (*firstRequest)->mBatchSize = requestList->size();
Yin-Chia Yeh14ef48d2020-02-10 15:06:37 -0800962 outputStream->setBatchSize(requestList->size());
Chien-Yu Chen85a64552015-08-28 15:46:12 -0700963 break;
964 }
965 }
966 }
967
Jianing Wei90e59c92014-03-12 18:29:36 -0700968 return OK;
969}
970
Yin-Chia Yeh7e5a2042019-02-06 16:01:06 -0800971status_t Camera3Device::capture(CameraMetadata &request, int64_t* lastFrameNumber) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800972 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800973
Emilian Peevaebbe412018-01-15 13:53:24 +0000974 List<const PhysicalCameraSettingsList> requestsList;
Shuzhen Wang0129d522016-10-30 22:43:41 -0700975 std::list<const SurfaceMap> surfaceMaps;
Emilian Peevaebbe412018-01-15 13:53:24 +0000976 convertToRequestList(requestsList, surfaceMaps, request);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700977
Yin-Chia Yeh7e5a2042019-02-06 16:01:06 -0800978 return captureList(requestsList, surfaceMaps, lastFrameNumber);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700979}
980
Emilian Peevaebbe412018-01-15 13:53:24 +0000981void Camera3Device::convertToRequestList(List<const PhysicalCameraSettingsList>& requestsList,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700982 std::list<const SurfaceMap>& surfaceMaps,
983 const CameraMetadata& request) {
Emilian Peevaebbe412018-01-15 13:53:24 +0000984 PhysicalCameraSettingsList requestList;
985 requestList.push_back({std::string(getId().string()), request});
986 requestsList.push_back(requestList);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700987
988 SurfaceMap surfaceMap;
989 camera_metadata_ro_entry streams = request.find(ANDROID_REQUEST_OUTPUT_STREAMS);
990 // With no surface list passed in, stream and surface will have 1-to-1
991 // mapping. So the surface index is 0 for each stream in the surfaceMap.
992 for (size_t i = 0; i < streams.count; i++) {
993 surfaceMap[streams.data.i32[i]].push_back(0);
994 }
995 surfaceMaps.push_back(surfaceMap);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800996}
997
Jianing Wei90e59c92014-03-12 18:29:36 -0700998status_t Camera3Device::submitRequestsHelper(
Emilian Peevaebbe412018-01-15 13:53:24 +0000999 const List<const PhysicalCameraSettingsList> &requests,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001000 const std::list<const SurfaceMap> &surfaceMaps,
1001 bool repeating,
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07001002 /*out*/
1003 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -07001004 ATRACE_CALL();
Shuzhen Wang316781a2020-08-18 18:11:01 -07001005 nsecs_t requestTimeNs = systemTime();
1006
Jianing Wei90e59c92014-03-12 18:29:36 -07001007 Mutex::Autolock il(mInterfaceLock);
1008 Mutex::Autolock l(mLock);
1009
1010 status_t res = checkStatusOkToCaptureLocked();
1011 if (res != OK) {
1012 // error logged by previous call
1013 return res;
1014 }
1015
1016 RequestList requestList;
1017
Shuzhen Wang0129d522016-10-30 22:43:41 -07001018 res = convertMetadataListToRequestListLocked(requests, surfaceMaps,
Shuzhen Wang316781a2020-08-18 18:11:01 -07001019 repeating, requestTimeNs, /*out*/&requestList);
Jianing Wei90e59c92014-03-12 18:29:36 -07001020 if (res != OK) {
1021 // error logged by previous call
1022 return res;
1023 }
1024
1025 if (repeating) {
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07001026 res = mRequestThread->setRepeatingRequests(requestList, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -07001027 } else {
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07001028 res = mRequestThread->queueRequestList(requestList, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -07001029 }
1030
1031 if (res == OK) {
1032 waitUntilStateThenRelock(/*active*/true, kActiveTimeout);
1033 if (res != OK) {
1034 SET_ERR_L("Can't transition to active in %f seconds!",
1035 kActiveTimeout/1e9);
1036 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001037 ALOGV("Camera %s: Capture request %" PRId32 " enqueued", mId.string(),
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07001038 (*(requestList.begin()))->mResultExtras.requestId);
Jianing Wei90e59c92014-03-12 18:29:36 -07001039 } else {
1040 CLOGE("Cannot queue request. Impossible.");
1041 return BAD_VALUE;
1042 }
1043
1044 return res;
1045}
1046
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001047hardware::Return<void> Camera3Device::requestStreamBuffers(
1048 const hardware::hidl_vec<hardware::camera::device::V3_5::BufferRequest>& bufReqs,
1049 requestStreamBuffers_cb _hidl_cb) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001050 RequestBufferStates states {
Shuzhen Wang316781a2020-08-18 18:11:01 -07001051 mId, mRequestBufferInterfaceLock, mUseHalBufManager, mOutputStreams, mSessionStatsBuilder,
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001052 *this, *mInterface, *this};
1053 camera3::requestStreamBuffers(states, bufReqs, _hidl_cb);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001054 return hardware::Void();
1055}
1056
1057hardware::Return<void> Camera3Device::returnStreamBuffers(
1058 const hardware::hidl_vec<hardware::camera::device::V3_2::StreamBuffer>& buffers) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001059 ReturnBufferStates states {
Shuzhen Wang316781a2020-08-18 18:11:01 -07001060 mId, mUseHalBufManager, mOutputStreams, mSessionStatsBuilder, *mInterface};
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001061 camera3::returnStreamBuffers(states, buffers);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001062 return hardware::Void();
1063}
1064
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001065hardware::Return<void> Camera3Device::processCaptureResult_3_4(
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001066 const hardware::hidl_vec<
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001067 hardware::camera::device::V3_4::CaptureResult>& results) {
Yin-Chia Yeh657c1872017-07-18 18:09:57 -07001068 // Ideally we should grab mLock, but that can lead to deadlock, and
1069 // it's not super important to get up to date value of mStatus for this
1070 // warning print, hence skipping the lock here
1071 if (mStatus == STATUS_ERROR) {
1072 // Per API contract, HAL should act as closed after device error
1073 // But mStatus can be set to error by framework as well, so just log
1074 // a warning here.
1075 ALOGW("%s: received capture result in error state.", __FUNCTION__);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07001076 }
Yifan Honga640c5a2017-04-12 16:30:31 -07001077
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001078 sp<NotificationListener> listener;
1079 {
1080 std::lock_guard<std::mutex> l(mOutputLock);
1081 listener = mListener.promote();
1082 }
1083
Yifan Honga640c5a2017-04-12 16:30:31 -07001084 if (mProcessCaptureResultLock.tryLock() != OK) {
1085 // This should never happen; it indicates a wrong client implementation
1086 // that doesn't follow the contract. But, we can be tolerant here.
1087 ALOGE("%s: callback overlapped! waiting 1s...",
1088 __FUNCTION__);
1089 if (mProcessCaptureResultLock.timedLock(1000000000 /* 1s */) != OK) {
1090 ALOGE("%s: cannot acquire lock in 1s, dropping results",
1091 __FUNCTION__);
1092 // really don't know what to do, so bail out.
1093 return hardware::Void();
1094 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001095 }
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001096 CaptureOutputStates states {
1097 mId,
Shuzhen Wangb7b42652020-05-07 11:59:02 -07001098 mInFlightLock, mLastCompletedRegularFrameNumber,
1099 mLastCompletedReprocessFrameNumber, mLastCompletedZslFrameNumber,
1100 mInFlightMap, mOutputLock, mResultQueue, mResultSignal,
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001101 mNextShutterFrameNumber,
1102 mNextReprocessShutterFrameNumber, mNextZslStillShutterFrameNumber,
1103 mNextResultFrameNumber,
1104 mNextReprocessResultFrameNumber, mNextZslStillResultFrameNumber,
1105 mUseHalBufManager, mUsePartialResult, mNeedFixupMonochromeTags,
1106 mNumPartialResults, mVendorTagId, mDeviceInfo, mPhysicalDeviceInfoMap,
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08001107 mResultMetadataQueue, mDistortionMappers, mZoomRatioMappers, mRotateAndCropMappers,
Shuzhen Wang316781a2020-08-18 18:11:01 -07001108 mTagMonitor, mInputStream, mOutputStreams, mSessionStatsBuilder, listener, *this, *this,
Emilian Peev5104fe92021-10-21 14:27:09 -07001109 *mInterface, mLegacyClient
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001110 };
1111
Yifan Honga640c5a2017-04-12 16:30:31 -07001112 for (const auto& result : results) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001113 processOneCaptureResultLocked(states, result.v3_2, result.physicalCameraMetadata);
Yifan Honga640c5a2017-04-12 16:30:31 -07001114 }
1115 mProcessCaptureResultLock.unlock();
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001116 return hardware::Void();
1117}
1118
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001119// Only one processCaptureResult should be called at a time, so
1120// the locks won't block. The locks are present here simply to enforce this.
1121hardware::Return<void> Camera3Device::processCaptureResult(
1122 const hardware::hidl_vec<
1123 hardware::camera::device::V3_2::CaptureResult>& results) {
1124 hardware::hidl_vec<hardware::camera::device::V3_4::PhysicalCameraMetadata> noPhysMetadata;
1125
1126 // Ideally we should grab mLock, but that can lead to deadlock, and
1127 // it's not super important to get up to date value of mStatus for this
1128 // warning print, hence skipping the lock here
1129 if (mStatus == STATUS_ERROR) {
1130 // Per API contract, HAL should act as closed after device error
1131 // But mStatus can be set to error by framework as well, so just log
1132 // a warning here.
1133 ALOGW("%s: received capture result in error state.", __FUNCTION__);
1134 }
1135
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001136 sp<NotificationListener> listener;
1137 {
1138 std::lock_guard<std::mutex> l(mOutputLock);
1139 listener = mListener.promote();
1140 }
1141
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001142 if (mProcessCaptureResultLock.tryLock() != OK) {
1143 // This should never happen; it indicates a wrong client implementation
1144 // that doesn't follow the contract. But, we can be tolerant here.
1145 ALOGE("%s: callback overlapped! waiting 1s...",
1146 __FUNCTION__);
1147 if (mProcessCaptureResultLock.timedLock(1000000000 /* 1s */) != OK) {
1148 ALOGE("%s: cannot acquire lock in 1s, dropping results",
1149 __FUNCTION__);
1150 // really don't know what to do, so bail out.
1151 return hardware::Void();
1152 }
1153 }
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001154
1155 CaptureOutputStates states {
1156 mId,
Shuzhen Wangb7b42652020-05-07 11:59:02 -07001157 mInFlightLock, mLastCompletedRegularFrameNumber,
1158 mLastCompletedReprocessFrameNumber, mLastCompletedZslFrameNumber,
1159 mInFlightMap, mOutputLock, mResultQueue, mResultSignal,
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001160 mNextShutterFrameNumber,
1161 mNextReprocessShutterFrameNumber, mNextZslStillShutterFrameNumber,
1162 mNextResultFrameNumber,
1163 mNextReprocessResultFrameNumber, mNextZslStillResultFrameNumber,
1164 mUseHalBufManager, mUsePartialResult, mNeedFixupMonochromeTags,
1165 mNumPartialResults, mVendorTagId, mDeviceInfo, mPhysicalDeviceInfoMap,
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08001166 mResultMetadataQueue, mDistortionMappers, mZoomRatioMappers, mRotateAndCropMappers,
Shuzhen Wang316781a2020-08-18 18:11:01 -07001167 mTagMonitor, mInputStream, mOutputStreams, mSessionStatsBuilder, listener, *this, *this,
Emilian Peev5104fe92021-10-21 14:27:09 -07001168 *mInterface, mLegacyClient
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001169 };
1170
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001171 for (const auto& result : results) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001172 processOneCaptureResultLocked(states, result, noPhysMetadata);
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001173 }
1174 mProcessCaptureResultLock.unlock();
1175 return hardware::Void();
1176}
1177
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001178hardware::Return<void> Camera3Device::notify(
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001179 const hardware::hidl_vec<hardware::camera::device::V3_2::NotifyMsg>& msgs) {
Shuzhen Wang90708ea2021-11-04 11:40:49 -07001180 return notifyHelper<hardware::camera::device::V3_2::NotifyMsg>(msgs);
1181}
1182
1183hardware::Return<void> Camera3Device::notify_3_8(
1184 const hardware::hidl_vec<hardware::camera::device::V3_8::NotifyMsg>& msgs) {
1185 return notifyHelper<hardware::camera::device::V3_8::NotifyMsg>(msgs);
1186}
1187
1188template<typename NotifyMsgType>
1189hardware::Return<void> Camera3Device::notifyHelper(const hardware::hidl_vec<NotifyMsgType>& msgs) {
Yin-Chia Yeh657c1872017-07-18 18:09:57 -07001190 // Ideally we should grab mLock, but that can lead to deadlock, and
1191 // it's not super important to get up to date value of mStatus for this
1192 // warning print, hence skipping the lock here
1193 if (mStatus == STATUS_ERROR) {
1194 // Per API contract, HAL should act as closed after device error
1195 // But mStatus can be set to error by framework as well, so just log
1196 // a warning here.
1197 ALOGW("%s: received notify message in error state.", __FUNCTION__);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07001198 }
Yin-Chia Yeh657c1872017-07-18 18:09:57 -07001199
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001200 sp<NotificationListener> listener;
1201 {
1202 std::lock_guard<std::mutex> l(mOutputLock);
1203 listener = mListener.promote();
1204 }
1205
1206 CaptureOutputStates states {
1207 mId,
Shuzhen Wangb7b42652020-05-07 11:59:02 -07001208 mInFlightLock, mLastCompletedRegularFrameNumber,
1209 mLastCompletedReprocessFrameNumber, mLastCompletedZslFrameNumber,
1210 mInFlightMap, mOutputLock, mResultQueue, mResultSignal,
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001211 mNextShutterFrameNumber,
1212 mNextReprocessShutterFrameNumber, mNextZslStillShutterFrameNumber,
1213 mNextResultFrameNumber,
1214 mNextReprocessResultFrameNumber, mNextZslStillResultFrameNumber,
1215 mUseHalBufManager, mUsePartialResult, mNeedFixupMonochromeTags,
1216 mNumPartialResults, mVendorTagId, mDeviceInfo, mPhysicalDeviceInfoMap,
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08001217 mResultMetadataQueue, mDistortionMappers, mZoomRatioMappers, mRotateAndCropMappers,
Shuzhen Wang316781a2020-08-18 18:11:01 -07001218 mTagMonitor, mInputStream, mOutputStreams, mSessionStatsBuilder, listener, *this, *this,
Emilian Peev5104fe92021-10-21 14:27:09 -07001219 *mInterface, mLegacyClient
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001220 };
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001221 for (const auto& msg : msgs) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001222 camera3::notify(states, msg);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001223 }
1224 return hardware::Void();
1225}
1226
Emilian Peevaebbe412018-01-15 13:53:24 +00001227status_t Camera3Device::captureList(const List<const PhysicalCameraSettingsList> &requestsList,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001228 const std::list<const SurfaceMap> &surfaceMaps,
Jianing Weicb0652e2014-03-12 18:29:36 -07001229 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -07001230 ATRACE_CALL();
1231
Emilian Peevaebbe412018-01-15 13:53:24 +00001232 return submitRequestsHelper(requestsList, surfaceMaps, /*repeating*/false, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -07001233}
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001234
Jianing Weicb0652e2014-03-12 18:29:36 -07001235status_t Camera3Device::setStreamingRequest(const CameraMetadata &request,
1236 int64_t* /*lastFrameNumber*/) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001237 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001238
Emilian Peevaebbe412018-01-15 13:53:24 +00001239 List<const PhysicalCameraSettingsList> requestsList;
Shuzhen Wang0129d522016-10-30 22:43:41 -07001240 std::list<const SurfaceMap> surfaceMaps;
Emilian Peevaebbe412018-01-15 13:53:24 +00001241 convertToRequestList(requestsList, surfaceMaps, request);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001242
Emilian Peevaebbe412018-01-15 13:53:24 +00001243 return setStreamingRequestList(requestsList, /*surfaceMap*/surfaceMaps,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001244 /*lastFrameNumber*/NULL);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001245}
1246
Emilian Peevaebbe412018-01-15 13:53:24 +00001247status_t Camera3Device::setStreamingRequestList(
1248 const List<const PhysicalCameraSettingsList> &requestsList,
1249 const std::list<const SurfaceMap> &surfaceMaps, int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -07001250 ATRACE_CALL();
1251
Emilian Peevaebbe412018-01-15 13:53:24 +00001252 return submitRequestsHelper(requestsList, surfaceMaps, /*repeating*/true, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -07001253}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001254
1255sp<Camera3Device::CaptureRequest> Camera3Device::setUpRequestLocked(
Emilian Peevaebbe412018-01-15 13:53:24 +00001256 const PhysicalCameraSettingsList &request, const SurfaceMap &surfaceMap) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001257 status_t res;
1258
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001259 if (mStatus == STATUS_UNCONFIGURED || mNeedConfig) {
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08001260 // This point should only be reached via API1 (API2 must explicitly call configureStreams)
1261 // so unilaterally select normal operating mode.
Emilian Peevaebbe412018-01-15 13:53:24 +00001262 res = filterParamsAndConfigureLocked(request.begin()->metadata,
Emilian Peevf4816702020-04-03 15:44:51 -07001263 CAMERA_STREAM_CONFIGURATION_NORMAL_MODE);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001264 // Stream configuration failed. Client might try other configuraitons.
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001265 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001266 CLOGE("Can't set up streams: %s (%d)", strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001267 return NULL;
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001268 } else if (mStatus == STATUS_UNCONFIGURED) {
1269 // Stream configuration successfully configure to empty stream configuration.
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001270 CLOGE("No streams configured");
1271 return NULL;
1272 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001273 }
1274
Shuzhen Wang0129d522016-10-30 22:43:41 -07001275 sp<CaptureRequest> newRequest = createCaptureRequest(request, surfaceMap);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001276 return newRequest;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001277}
1278
Jianing Weicb0652e2014-03-12 18:29:36 -07001279status_t Camera3Device::clearStreamingRequest(int64_t *lastFrameNumber) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001280 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001281 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001282 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001283
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001284 switch (mStatus) {
1285 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001286 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001287 return INVALID_OPERATION;
1288 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001289 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001290 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001291 case STATUS_UNCONFIGURED:
1292 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001293 case STATUS_ACTIVE:
1294 // OK
1295 break;
1296 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001297 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001298 return INVALID_OPERATION;
1299 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001300 ALOGV("Camera %s: Clearing repeating request", mId.string());
Jianing Weicb0652e2014-03-12 18:29:36 -07001301
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07001302 return mRequestThread->clearRepeatingRequests(lastFrameNumber);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001303}
1304
1305status_t Camera3Device::waitUntilRequestReceived(int32_t requestId, nsecs_t timeout) {
1306 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001307 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001308
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001309 return mRequestThread->waitUntilRequestProcessed(requestId, timeout);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001310}
1311
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001312status_t Camera3Device::createInputStream(
Shuzhen Wang83bff122020-11-20 15:51:39 -08001313 uint32_t width, uint32_t height, int format, bool isMultiResolution, int *id) {
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001314 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001315 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001316 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001317 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001318 ALOGV("Camera %s: Creating new input stream %d: %d x %d, format %d",
1319 mId.string(), mNextStreamId, width, height, format);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001320
1321 status_t res;
1322 bool wasActive = false;
1323
1324 switch (mStatus) {
1325 case STATUS_ERROR:
1326 ALOGE("%s: Device has encountered a serious error", __FUNCTION__);
1327 return INVALID_OPERATION;
1328 case STATUS_UNINITIALIZED:
1329 ALOGE("%s: Device not initialized", __FUNCTION__);
1330 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001331 case STATUS_UNCONFIGURED:
1332 case STATUS_CONFIGURED:
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001333 // OK
1334 break;
1335 case STATUS_ACTIVE:
1336 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001337 res = internalPauseAndWaitLocked(maxExpectedDuration);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001338 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001339 SET_ERR_L("Can't pause captures to reconfigure streams!");
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001340 return res;
1341 }
1342 wasActive = true;
1343 break;
1344 default:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001345 SET_ERR_L("%s: Unexpected status: %d", mStatus);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001346 return INVALID_OPERATION;
1347 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001348 assert(mStatus != STATUS_ACTIVE);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001349
1350 if (mInputStream != 0) {
1351 ALOGE("%s: Cannot create more than 1 input stream", __FUNCTION__);
1352 return INVALID_OPERATION;
1353 }
1354
1355 sp<Camera3InputStream> newStream = new Camera3InputStream(mNextStreamId,
1356 width, height, format);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001357 newStream->setStatusTracker(mStatusTracker);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001358
1359 mInputStream = newStream;
Shuzhen Wang83bff122020-11-20 15:51:39 -08001360 mIsInputStreamMultiResolution = isMultiResolution;
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001361
1362 *id = mNextStreamId++;
1363
1364 // Continue captures if active at start
1365 if (wasActive) {
1366 ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001367 // Reuse current operating mode and session parameters for new stream config
1368 res = configureStreamsLocked(mOperatingMode, mSessionParams);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001369 if (res != OK) {
1370 ALOGE("%s: Can't reconfigure device for new stream %d: %s (%d)",
1371 __FUNCTION__, mNextStreamId, strerror(-res), res);
1372 return res;
1373 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001374 internalResumeLocked();
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001375 }
1376
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001377 ALOGV("Camera %s: Created input stream", mId.string());
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001378 return OK;
1379}
1380
Eino-Ville Talvala727d1722015-06-09 13:44:19 -07001381status_t Camera3Device::createStream(sp<Surface> consumer,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001382 uint32_t width, uint32_t height, int format,
Emilian Peevf4816702020-04-03 15:44:51 -07001383 android_dataspace dataSpace, camera_stream_rotation_t rotation, int *id,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001384 const String8& physicalCameraId,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001385 const std::unordered_set<int32_t> &sensorPixelModesUsed,
1386 std::vector<int> *surfaceIds, int streamSetId, bool isShared, bool isMultiResolution,
1387 uint64_t consumerUsage) {
Shuzhen Wang0129d522016-10-30 22:43:41 -07001388 ATRACE_CALL();
1389
1390 if (consumer == nullptr) {
1391 ALOGE("%s: consumer must not be null", __FUNCTION__);
1392 return BAD_VALUE;
1393 }
1394
1395 std::vector<sp<Surface>> consumers;
1396 consumers.push_back(consumer);
1397
1398 return createStream(consumers, /*hasDeferredConsumer*/ false, width, height,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001399 format, dataSpace, rotation, id, physicalCameraId, sensorPixelModesUsed, surfaceIds,
1400 streamSetId, isShared, isMultiResolution, consumerUsage);
1401}
1402
1403static bool isRawFormat(int format) {
1404 switch (format) {
1405 case HAL_PIXEL_FORMAT_RAW16:
1406 case HAL_PIXEL_FORMAT_RAW12:
1407 case HAL_PIXEL_FORMAT_RAW10:
1408 case HAL_PIXEL_FORMAT_RAW_OPAQUE:
1409 return true;
1410 default:
1411 return false;
1412 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001413}
1414
1415status_t Camera3Device::createStream(const std::vector<sp<Surface>>& consumers,
1416 bool hasDeferredConsumer, uint32_t width, uint32_t height, int format,
Emilian Peevf4816702020-04-03 15:44:51 -07001417 android_dataspace dataSpace, camera_stream_rotation_t rotation, int *id,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001418 const String8& physicalCameraId, const std::unordered_set<int32_t> &sensorPixelModesUsed,
Shuzhen Wang83bff122020-11-20 15:51:39 -08001419 std::vector<int> *surfaceIds, int streamSetId, bool isShared, bool isMultiResolution,
1420 uint64_t consumerUsage) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001421 ATRACE_CALL();
Emilian Peev40ead602017-09-26 15:46:36 +01001422
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001423 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001424 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001425 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001426 ALOGV("Camera %s: Creating new stream %d: %d x %d, format %d, dataspace %d rotation %d"
Shuzhen Wang83bff122020-11-20 15:51:39 -08001427 " consumer usage %" PRIu64 ", isShared %d, physicalCameraId %s, isMultiResolution %d",
1428 mId.string(), mNextStreamId, width, height, format, dataSpace, rotation,
1429 consumerUsage, isShared, physicalCameraId.string(), isMultiResolution);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001430
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001431 status_t res;
1432 bool wasActive = false;
1433
1434 switch (mStatus) {
1435 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001436 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001437 return INVALID_OPERATION;
1438 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001439 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001440 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001441 case STATUS_UNCONFIGURED:
1442 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001443 // OK
1444 break;
1445 case STATUS_ACTIVE:
1446 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001447 res = internalPauseAndWaitLocked(maxExpectedDuration);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001448 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001449 SET_ERR_L("Can't pause captures to reconfigure streams!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001450 return res;
1451 }
1452 wasActive = true;
1453 break;
1454 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001455 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001456 return INVALID_OPERATION;
1457 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001458 assert(mStatus != STATUS_ACTIVE);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001459
1460 sp<Camera3OutputStream> newStream;
Zhijun He5d677d12016-05-29 16:52:39 -07001461
Shuzhen Wang0129d522016-10-30 22:43:41 -07001462 if (consumers.size() == 0 && !hasDeferredConsumer) {
1463 ALOGE("%s: Number of consumers cannot be smaller than 1", __FUNCTION__);
1464 return BAD_VALUE;
1465 }
Zhijun He5d677d12016-05-29 16:52:39 -07001466
Shuzhen Wang0129d522016-10-30 22:43:41 -07001467 if (hasDeferredConsumer && format != HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
Zhijun He5d677d12016-05-29 16:52:39 -07001468 ALOGE("Deferred consumer stream creation only support IMPLEMENTATION_DEFINED format");
1469 return BAD_VALUE;
1470 }
1471
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001472 if (isRawFormat(format) && sensorPixelModesUsed.size() > 1) {
1473 // We can't use one stream with a raw format in both sensor pixel modes since its going to
1474 // be found in only one sensor pixel mode.
1475 ALOGE("%s: RAW opaque stream cannot be used with > 1 sensor pixel modes", __FUNCTION__);
1476 return BAD_VALUE;
1477 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001478 if (format == HAL_PIXEL_FORMAT_BLOB) {
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -07001479 ssize_t blobBufferSize;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001480 if (dataSpace == HAL_DATASPACE_DEPTH) {
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -08001481 blobBufferSize = getPointCloudBufferSize(infoPhysical(physicalCameraId));
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -07001482 if (blobBufferSize <= 0) {
1483 SET_ERR_L("Invalid point cloud buffer size %zd", blobBufferSize);
1484 return BAD_VALUE;
1485 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001486 } else if (dataSpace == static_cast<android_dataspace>(HAL_DATASPACE_JPEG_APP_SEGMENTS)) {
1487 blobBufferSize = width * height;
1488 } else {
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -08001489 blobBufferSize = getJpegBufferSize(infoPhysical(physicalCameraId), width, height);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001490 if (blobBufferSize <= 0) {
1491 SET_ERR_L("Invalid jpeg buffer size %zd", blobBufferSize);
1492 return BAD_VALUE;
1493 }
Zhijun Hef7da0962014-04-24 13:27:56 -07001494 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001495 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001496 width, height, blobBufferSize, format, dataSpace, rotation,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001497 mTimestampOffset, physicalCameraId, sensorPixelModesUsed, streamSetId,
1498 isMultiResolution);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -08001499 } else if (format == HAL_PIXEL_FORMAT_RAW_OPAQUE) {
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001500 bool maxResolution =
1501 sensorPixelModesUsed.find(ANDROID_SENSOR_PIXEL_MODE_MAXIMUM_RESOLUTION) !=
1502 sensorPixelModesUsed.end();
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -08001503 ssize_t rawOpaqueBufferSize = getRawOpaqueBufferSize(infoPhysical(physicalCameraId), width,
1504 height, maxResolution);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -08001505 if (rawOpaqueBufferSize <= 0) {
1506 SET_ERR_L("Invalid RAW opaque buffer size %zd", rawOpaqueBufferSize);
1507 return BAD_VALUE;
1508 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001509 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001510 width, height, rawOpaqueBufferSize, format, dataSpace, rotation,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001511 mTimestampOffset, physicalCameraId, sensorPixelModesUsed, streamSetId,
1512 isMultiResolution);
Shuzhen Wang758c2152017-01-10 18:26:18 -08001513 } else if (isShared) {
1514 newStream = new Camera3SharedOutputStream(mNextStreamId, consumers,
1515 width, height, format, consumerUsage, dataSpace, rotation,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001516 mTimestampOffset, physicalCameraId, sensorPixelModesUsed, streamSetId,
1517 mUseHalBufManager);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001518 } else if (consumers.size() == 0 && hasDeferredConsumer) {
Zhijun He5d677d12016-05-29 16:52:39 -07001519 newStream = new Camera3OutputStream(mNextStreamId,
1520 width, height, format, consumerUsage, dataSpace, rotation,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001521 mTimestampOffset, physicalCameraId, sensorPixelModesUsed, streamSetId,
1522 isMultiResolution);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001523 } else {
Shuzhen Wang0129d522016-10-30 22:43:41 -07001524 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001525 width, height, format, dataSpace, rotation,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001526 mTimestampOffset, physicalCameraId, sensorPixelModesUsed, streamSetId,
1527 isMultiResolution);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001528 }
Emilian Peev40ead602017-09-26 15:46:36 +01001529
1530 size_t consumerCount = consumers.size();
1531 for (size_t i = 0; i < consumerCount; i++) {
1532 int id = newStream->getSurfaceId(consumers[i]);
1533 if (id < 0) {
1534 SET_ERR_L("Invalid surface id");
1535 return BAD_VALUE;
1536 }
1537 if (surfaceIds != nullptr) {
1538 surfaceIds->push_back(id);
1539 }
1540 }
1541
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001542 newStream->setStatusTracker(mStatusTracker);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001543
Emilian Peev08dd2452017-04-06 16:55:14 +01001544 newStream->setBufferManager(mBufferManager);
Zhijun He125684a2015-12-26 15:07:30 -08001545
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08001546 newStream->setImageDumpMask(mImageDumpMask);
1547
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001548 res = mOutputStreams.add(mNextStreamId, newStream);
1549 if (res < 0) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001550 SET_ERR_L("Can't add new stream to set: %s (%d)", strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001551 return res;
1552 }
1553
Shuzhen Wang316781a2020-08-18 18:11:01 -07001554 mSessionStatsBuilder.addStream(mNextStreamId);
1555
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001556 *id = mNextStreamId++;
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07001557 mNeedConfig = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001558
1559 // Continue captures if active at start
1560 if (wasActive) {
1561 ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001562 // Reuse current operating mode and session parameters for new stream config
1563 res = configureStreamsLocked(mOperatingMode, mSessionParams);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001564 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001565 CLOGE("Can't reconfigure device for new stream %d: %s (%d)",
1566 mNextStreamId, strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001567 return res;
1568 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001569 internalResumeLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001570 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001571 ALOGV("Camera %s: Created new stream", mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001572 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001573}
1574
Emilian Peev710c1422017-08-30 11:19:38 +01001575status_t Camera3Device::getStreamInfo(int id, StreamInfo *streamInfo) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001576 ATRACE_CALL();
Emilian Peev710c1422017-08-30 11:19:38 +01001577 if (nullptr == streamInfo) {
1578 return BAD_VALUE;
1579 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001580 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001581 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001582
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001583 switch (mStatus) {
1584 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001585 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001586 return INVALID_OPERATION;
1587 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001588 CLOGE("Device not initialized!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001589 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001590 case STATUS_UNCONFIGURED:
1591 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001592 case STATUS_ACTIVE:
1593 // OK
1594 break;
1595 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001596 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001597 return INVALID_OPERATION;
1598 }
1599
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001600 sp<Camera3StreamInterface> stream = mOutputStreams.get(id);
1601 if (stream == nullptr) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001602 CLOGE("Stream %d is unknown", id);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001603 return BAD_VALUE;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001604 }
1605
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001606 streamInfo->width = stream->getWidth();
1607 streamInfo->height = stream->getHeight();
1608 streamInfo->format = stream->getFormat();
1609 streamInfo->dataSpace = stream->getDataSpace();
1610 streamInfo->formatOverridden = stream->isFormatOverridden();
1611 streamInfo->originalFormat = stream->getOriginalFormat();
1612 streamInfo->dataSpaceOverridden = stream->isDataSpaceOverridden();
1613 streamInfo->originalDataSpace = stream->getOriginalDataSpace();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001614 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001615}
1616
1617status_t Camera3Device::setStreamTransform(int id,
1618 int transform) {
1619 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001620 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001621 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001622
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001623 switch (mStatus) {
1624 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001625 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001626 return INVALID_OPERATION;
1627 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001628 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001629 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001630 case STATUS_UNCONFIGURED:
1631 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001632 case STATUS_ACTIVE:
1633 // OK
1634 break;
1635 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001636 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001637 return INVALID_OPERATION;
1638 }
1639
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001640 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(id);
1641 if (stream == nullptr) {
1642 CLOGE("Stream %d does not exist", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001643 return BAD_VALUE;
1644 }
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001645 return stream->setTransform(transform);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001646}
1647
1648status_t Camera3Device::deleteStream(int id) {
1649 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001650 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001651 Mutex::Autolock l(mLock);
1652 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001653
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001654 ALOGV("%s: Camera %s: Deleting stream %d", __FUNCTION__, mId.string(), id);
Igor Murashkine2172be2013-05-28 15:31:39 -07001655
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001656 // CameraDevice semantics require device to already be idle before
1657 // deleteStream is called, unlike for createStream.
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001658 if (mStatus == STATUS_ACTIVE) {
Yin-Chia Yeh693047d2018-03-08 12:14:19 -08001659 ALOGW("%s: Camera %s: Device not idle", __FUNCTION__, mId.string());
Igor Murashkin52827132013-05-13 14:53:44 -07001660 return -EBUSY;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001661 }
1662
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07001663 if (mStatus == STATUS_ERROR) {
1664 ALOGW("%s: Camera %s: deleteStream not allowed in ERROR state",
1665 __FUNCTION__, mId.string());
1666 return -EBUSY;
1667 }
1668
Igor Murashkin2fba5842013-04-22 14:03:54 -07001669 sp<Camera3StreamInterface> deletedStream;
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001670 sp<Camera3StreamInterface> stream = mOutputStreams.get(id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001671 if (mInputStream != NULL && id == mInputStream->getId()) {
1672 deletedStream = mInputStream;
1673 mInputStream.clear();
1674 } else {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001675 if (stream == nullptr) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001676 CLOGE("Stream %d does not exist", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001677 return BAD_VALUE;
1678 }
Shuzhen Wang316781a2020-08-18 18:11:01 -07001679 mSessionStatsBuilder.removeStream(id);
Zhijun He5f446352014-01-22 09:49:33 -08001680 }
1681
1682 // Delete output stream or the output part of a bi-directional stream.
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001683 if (stream != nullptr) {
1684 deletedStream = stream;
1685 mOutputStreams.remove(id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001686 }
1687
1688 // Free up the stream endpoint so that it can be used by some other stream
1689 res = deletedStream->disconnect();
1690 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001691 SET_ERR_L("Can't disconnect deleted stream %d", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001692 // fall through since we want to still list the stream as deleted.
1693 }
1694 mDeletedStreams.add(deletedStream);
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07001695 mNeedConfig = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001696
1697 return res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001698}
1699
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001700status_t Camera3Device::configureStreams(const CameraMetadata& sessionParams, int operatingMode) {
Igor Murashkine2d167e2014-08-19 16:19:59 -07001701 ATRACE_CALL();
1702 ALOGV("%s: E", __FUNCTION__);
1703
1704 Mutex::Autolock il(mInterfaceLock);
1705 Mutex::Autolock l(mLock);
Chien-Yu Chen17338fc2015-06-18 16:30:12 -07001706
Emilian Peev811d2952018-05-25 11:08:40 +01001707 // In case the client doesn't include any session parameter, try a
1708 // speculative configuration using the values from the last cached
1709 // default request.
1710 if (sessionParams.isEmpty() &&
Emilian Peevf4816702020-04-03 15:44:51 -07001711 ((mLastTemplateId > 0) && (mLastTemplateId < CAMERA_TEMPLATE_COUNT)) &&
Emilian Peev811d2952018-05-25 11:08:40 +01001712 (!mRequestTemplateCache[mLastTemplateId].isEmpty())) {
1713 ALOGV("%s: Speculative session param configuration with template id: %d", __func__,
1714 mLastTemplateId);
1715 return filterParamsAndConfigureLocked(mRequestTemplateCache[mLastTemplateId],
1716 operatingMode);
1717 }
1718
Emilian Peevac3ce6c2017-12-12 15:27:02 +00001719 return filterParamsAndConfigureLocked(sessionParams, operatingMode);
1720}
1721
1722status_t Camera3Device::filterParamsAndConfigureLocked(const CameraMetadata& sessionParams,
1723 int operatingMode) {
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001724 //Filter out any incoming session parameters
1725 const CameraMetadata params(sessionParams);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001726 camera_metadata_entry_t availableSessionKeys = mDeviceInfo.find(
1727 ANDROID_REQUEST_AVAILABLE_SESSION_KEYS);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00001728 CameraMetadata filteredParams(availableSessionKeys.count);
1729 camera_metadata_t *meta = const_cast<camera_metadata_t *>(
1730 filteredParams.getAndLock());
1731 set_camera_metadata_vendor_id(meta, mVendorTagId);
1732 filteredParams.unlock(meta);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001733 if (availableSessionKeys.count > 0) {
1734 for (size_t i = 0; i < availableSessionKeys.count; i++) {
1735 camera_metadata_ro_entry entry = params.find(
1736 availableSessionKeys.data.i32[i]);
1737 if (entry.count > 0) {
1738 filteredParams.update(entry);
1739 }
1740 }
1741 }
1742
1743 return configureStreamsLocked(operatingMode, filteredParams);
Igor Murashkine2d167e2014-08-19 16:19:59 -07001744}
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001745
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07001746status_t Camera3Device::getInputBufferProducer(
1747 sp<IGraphicBufferProducer> *producer) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07001748 ATRACE_CALL();
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07001749 Mutex::Autolock il(mInterfaceLock);
1750 Mutex::Autolock l(mLock);
1751
1752 if (producer == NULL) {
1753 return BAD_VALUE;
1754 } else if (mInputStream == NULL) {
1755 return INVALID_OPERATION;
1756 }
1757
1758 return mInputStream->getInputBufferProducer(producer);
1759}
1760
Emilian Peevf4816702020-04-03 15:44:51 -07001761status_t Camera3Device::createDefaultRequest(camera_request_template_t templateId,
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001762 CameraMetadata *request) {
1763 ATRACE_CALL();
Alex Rayfe7e0c62013-05-30 00:12:13 -07001764 ALOGV("%s: for template %d", __FUNCTION__, templateId);
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08001765
Emilian Peevf4816702020-04-03 15:44:51 -07001766 if (templateId <= 0 || templateId >= CAMERA_TEMPLATE_COUNT) {
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08001767 android_errorWriteWithInfoLog(CameraService::SN_EVENT_LOG_ID, "26866110",
Jayant Chowdhary12361932018-08-27 14:46:13 -07001768 CameraThreadState::getCallingUid(), nullptr, 0);
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08001769 return BAD_VALUE;
1770 }
1771
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001772 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001773
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001774 {
1775 Mutex::Autolock l(mLock);
1776 switch (mStatus) {
1777 case STATUS_ERROR:
1778 CLOGE("Device has encountered a serious error");
1779 return INVALID_OPERATION;
1780 case STATUS_UNINITIALIZED:
1781 CLOGE("Device is not initialized!");
1782 return INVALID_OPERATION;
1783 case STATUS_UNCONFIGURED:
1784 case STATUS_CONFIGURED:
1785 case STATUS_ACTIVE:
1786 // OK
1787 break;
1788 default:
1789 SET_ERR_L("Unexpected status: %d", mStatus);
1790 return INVALID_OPERATION;
1791 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001792
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001793 if (!mRequestTemplateCache[templateId].isEmpty()) {
1794 *request = mRequestTemplateCache[templateId];
Emilian Peev811d2952018-05-25 11:08:40 +01001795 mLastTemplateId = templateId;
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001796 return OK;
1797 }
Zhijun Hea1530f12014-09-14 12:44:20 -07001798 }
1799
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001800 camera_metadata_t *rawRequest;
1801 status_t res = mInterface->constructDefaultRequestSettings(
Emilian Peevf4816702020-04-03 15:44:51 -07001802 (camera_request_template_t) templateId, &rawRequest);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001803
1804 {
1805 Mutex::Autolock l(mLock);
1806 if (res == BAD_VALUE) {
1807 ALOGI("%s: template %d is not supported on this camera device",
1808 __FUNCTION__, templateId);
1809 return res;
1810 } else if (res != OK) {
1811 CLOGE("Unable to construct request template %d: %s (%d)",
1812 templateId, strerror(-res), res);
1813 return res;
1814 }
1815
1816 set_camera_metadata_vendor_id(rawRequest, mVendorTagId);
1817 mRequestTemplateCache[templateId].acquire(rawRequest);
1818
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08001819 // Override the template request with zoomRatioMapper
1820 res = mZoomRatioMappers[mId.c_str()].initZoomRatioInTemplate(
1821 &mRequestTemplateCache[templateId]);
1822 if (res != OK) {
1823 CLOGE("Failed to update zoom ratio for template %d: %s (%d)",
1824 templateId, strerror(-res), res);
1825 return res;
1826 }
1827
Shuzhen Wangd25dc972020-03-24 17:11:43 -07001828 // Fill in JPEG_QUALITY if not available
1829 if (!mRequestTemplateCache[templateId].exists(ANDROID_JPEG_QUALITY)) {
1830 static const uint8_t kDefaultJpegQuality = 95;
1831 mRequestTemplateCache[templateId].update(ANDROID_JPEG_QUALITY,
1832 &kDefaultJpegQuality, 1);
1833 }
1834
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001835 *request = mRequestTemplateCache[templateId];
Emilian Peev811d2952018-05-25 11:08:40 +01001836 mLastTemplateId = templateId;
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001837 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001838 return OK;
1839}
1840
1841status_t Camera3Device::waitUntilDrained() {
1842 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001843 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001844 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001845 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001846
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001847 return waitUntilDrainedLocked(maxExpectedDuration);
Zhijun He69a37482014-03-23 18:44:49 -07001848}
1849
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001850status_t Camera3Device::waitUntilDrainedLocked(nsecs_t maxExpectedDuration) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001851 switch (mStatus) {
1852 case STATUS_UNINITIALIZED:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001853 case STATUS_UNCONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001854 ALOGV("%s: Already idle", __FUNCTION__);
1855 return OK;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001856 case STATUS_CONFIGURED:
1857 // To avoid race conditions, check with tracker to be sure
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001858 case STATUS_ERROR:
1859 case STATUS_ACTIVE:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001860 // Need to verify shut down
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001861 break;
1862 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001863 SET_ERR_L("Unexpected status: %d",mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001864 return INVALID_OPERATION;
1865 }
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07001866 ALOGV("%s: Camera %s: Waiting until idle (%" PRIi64 "ns)", __FUNCTION__, mId.string(),
1867 maxExpectedDuration);
1868 status_t res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
Eino-Ville Talvala9c8a0912014-09-14 14:52:19 -07001869 if (res != OK) {
Yin-Chia Yeh87b3ec02019-06-03 10:44:39 -07001870 mStatusTracker->dumpActiveComponents();
Eino-Ville Talvala9c8a0912014-09-14 14:52:19 -07001871 SET_ERR_L("Error waiting for HAL to drain: %s (%d)", strerror(-res),
1872 res);
1873 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001874 return res;
1875}
1876
Ruben Brunk183f0562015-08-12 12:55:02 -07001877void Camera3Device::internalUpdateStatusLocked(Status status) {
1878 mStatus = status;
1879 mRecentStatusUpdates.add(mStatus);
1880 mStatusChanged.broadcast();
1881}
1882
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001883// Pause to reconfigure
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001884status_t Camera3Device::internalPauseAndWaitLocked(nsecs_t maxExpectedDuration) {
Emilian Peeve86358b2019-02-15 13:51:39 -08001885 if (mRequestThread.get() != nullptr) {
1886 mRequestThread->setPaused(true);
1887 } else {
1888 return NO_INIT;
1889 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001890
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07001891 ALOGV("%s: Camera %s: Internal wait until idle (% " PRIi64 " ns)", __FUNCTION__, mId.string(),
1892 maxExpectedDuration);
1893 status_t res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001894 if (res != OK) {
1895 SET_ERR_L("Can't idle device in %f seconds!",
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07001896 maxExpectedDuration/1e9);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001897 }
1898
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001899 return res;
1900}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001901
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001902// Resume after internalPauseAndWaitLocked
1903status_t Camera3Device::internalResumeLocked() {
1904 status_t res;
1905
1906 mRequestThread->setPaused(false);
1907
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08001908 ALOGV("%s: Camera %s: Internal wait until active (% " PRIi64 " ns)", __FUNCTION__, mId.string(),
1909 kActiveTimeout);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001910 res = waitUntilStateThenRelock(/*active*/ true, kActiveTimeout);
1911 if (res != OK) {
1912 SET_ERR_L("Can't transition to active in %f seconds!",
1913 kActiveTimeout/1e9);
1914 }
1915 mPauseStateNotify = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001916 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001917}
1918
Ruben Brunk183f0562015-08-12 12:55:02 -07001919status_t Camera3Device::waitUntilStateThenRelock(bool active, nsecs_t timeout) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001920 status_t res = OK;
Ruben Brunk183f0562015-08-12 12:55:02 -07001921
1922 size_t startIndex = 0;
1923 if (mStatusWaiters == 0) {
1924 // Clear the list of recent statuses if there are no existing threads waiting on updates to
1925 // this status list
1926 mRecentStatusUpdates.clear();
1927 } else {
1928 // If other threads are waiting on updates to this status list, set the position of the
1929 // first element that this list will check rather than clearing the list.
1930 startIndex = mRecentStatusUpdates.size();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001931 }
1932
Ruben Brunk183f0562015-08-12 12:55:02 -07001933 mStatusWaiters++;
1934
Yin-Chia Yehe52b8fa2020-07-28 00:17:58 -07001935 bool signalPipelineDrain = false;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07001936 if (!active && mUseHalBufManager) {
1937 auto streamIds = mOutputStreams.getStreamIds();
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08001938 if (mStatus == STATUS_ACTIVE) {
1939 mRequestThread->signalPipelineDrain(streamIds);
Yin-Chia Yehe52b8fa2020-07-28 00:17:58 -07001940 signalPipelineDrain = true;
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08001941 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07001942 mRequestBufferSM.onWaitUntilIdle();
1943 }
1944
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001945 bool stateSeen = false;
1946 do {
Ruben Brunk183f0562015-08-12 12:55:02 -07001947 if (active == (mStatus == STATUS_ACTIVE)) {
1948 // Desired state is current
1949 break;
1950 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001951
1952 res = mStatusChanged.waitRelative(mLock, timeout);
1953 if (res != OK) break;
1954
Ruben Brunk183f0562015-08-12 12:55:02 -07001955 // This is impossible, but if not, could result in subtle deadlocks and invalid state
1956 // transitions.
1957 LOG_ALWAYS_FATAL_IF(startIndex > mRecentStatusUpdates.size(),
1958 "%s: Skipping status updates in Camera3Device, may result in deadlock.",
1959 __FUNCTION__);
1960
1961 // Encountered desired state since we began waiting
1962 for (size_t i = startIndex; i < mRecentStatusUpdates.size(); i++) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001963 if (active == (mRecentStatusUpdates[i] == STATUS_ACTIVE) ) {
1964 stateSeen = true;
1965 break;
1966 }
1967 }
1968 } while (!stateSeen);
1969
Yin-Chia Yehe52b8fa2020-07-28 00:17:58 -07001970 if (signalPipelineDrain) {
1971 mRequestThread->resetPipelineDrain();
1972 }
1973
Ruben Brunk183f0562015-08-12 12:55:02 -07001974 mStatusWaiters--;
1975
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001976 return res;
1977}
1978
1979
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001980status_t Camera3Device::setNotifyCallback(wp<NotificationListener> listener) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001981 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001982 std::lock_guard<std::mutex> l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001983
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001984 if (listener != NULL && mListener != NULL) {
1985 ALOGW("%s: Replacing old callback listener", __FUNCTION__);
1986 }
1987 mListener = listener;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001988 mRequestThread->setNotificationListener(listener);
1989 mPreparerThread->setNotificationListener(listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001990
1991 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001992}
1993
Eino-Ville Talvala46910bd2013-07-18 19:15:17 -07001994bool Camera3Device::willNotify3A() {
1995 return false;
1996}
1997
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001998status_t Camera3Device::waitForNextFrame(nsecs_t timeout) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07001999 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002000 std::unique_lock<std::mutex> l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002001
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002002 while (mResultQueue.empty()) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002003 auto st = mResultSignal.wait_for(l, std::chrono::nanoseconds(timeout));
2004 if (st == std::cv_status::timeout) {
2005 return TIMED_OUT;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002006 }
2007 }
2008 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002009}
2010
Jianing Weicb0652e2014-03-12 18:29:36 -07002011status_t Camera3Device::getNextResult(CaptureResult *frame) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002012 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002013 std::lock_guard<std::mutex> l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002014
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002015 if (mResultQueue.empty()) {
2016 return NOT_ENOUGH_DATA;
2017 }
2018
Jianing Weicb0652e2014-03-12 18:29:36 -07002019 if (frame == NULL) {
2020 ALOGE("%s: argument cannot be NULL", __FUNCTION__);
2021 return BAD_VALUE;
2022 }
2023
2024 CaptureResult &result = *(mResultQueue.begin());
2025 frame->mResultExtras = result.mResultExtras;
2026 frame->mMetadata.acquire(result.mMetadata);
Shuzhen Wang5c22c152017-12-31 17:12:25 -08002027 frame->mPhysicalMetadatas = std::move(result.mPhysicalMetadatas);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002028 mResultQueue.erase(mResultQueue.begin());
2029
2030 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002031}
2032
2033status_t Camera3Device::triggerAutofocus(uint32_t id) {
2034 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002035 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002036
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002037 ALOGV("%s: Triggering autofocus, id %d", __FUNCTION__, id);
2038 // Mix-in this trigger into the next request and only the next request.
2039 RequestTrigger trigger[] = {
2040 {
2041 ANDROID_CONTROL_AF_TRIGGER,
2042 ANDROID_CONTROL_AF_TRIGGER_START
2043 },
2044 {
2045 ANDROID_CONTROL_AF_TRIGGER_ID,
2046 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07002047 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002048 };
2049
2050 return mRequestThread->queueTrigger(trigger,
2051 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002052}
2053
2054status_t Camera3Device::triggerCancelAutofocus(uint32_t id) {
2055 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002056 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002057
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002058 ALOGV("%s: Triggering cancel autofocus, id %d", __FUNCTION__, id);
2059 // Mix-in this trigger into the next request and only the next request.
2060 RequestTrigger trigger[] = {
2061 {
2062 ANDROID_CONTROL_AF_TRIGGER,
2063 ANDROID_CONTROL_AF_TRIGGER_CANCEL
2064 },
2065 {
2066 ANDROID_CONTROL_AF_TRIGGER_ID,
2067 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07002068 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002069 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002070
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002071 return mRequestThread->queueTrigger(trigger,
2072 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002073}
2074
2075status_t Camera3Device::triggerPrecaptureMetering(uint32_t id) {
2076 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002077 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002078
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002079 ALOGV("%s: Triggering precapture metering, id %d", __FUNCTION__, id);
2080 // Mix-in this trigger into the next request and only the next request.
2081 RequestTrigger trigger[] = {
2082 {
2083 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER,
2084 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_START
2085 },
2086 {
2087 ANDROID_CONTROL_AE_PRECAPTURE_ID,
2088 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07002089 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002090 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002091
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002092 return mRequestThread->queueTrigger(trigger,
2093 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002094}
2095
Jianing Weicb0652e2014-03-12 18:29:36 -07002096status_t Camera3Device::flush(int64_t *frameNumber) {
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07002097 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002098 ALOGV("%s: Camera %s: Flushing all requests", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002099 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07002100
Zhijun He7ef20392014-04-21 16:04:17 -07002101 {
2102 Mutex::Autolock l(mLock);
Emilian Peeved2ebe42018-09-25 16:59:09 +01002103
2104 // b/116514106 "disconnect()" can get called twice for the same device. The
2105 // camera device will not be initialized during the second run.
2106 if (mStatus == STATUS_UNINITIALIZED) {
2107 return OK;
2108 }
2109
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002110 mRequestThread->clear(/*out*/frameNumber);
Shuzhen Wang316781a2020-08-18 18:11:01 -07002111
2112 // Stop session and stream counter
2113 mSessionStatsBuilder.stopCounter();
Zhijun He7ef20392014-04-21 16:04:17 -07002114 }
2115
Emilian Peev08dd2452017-04-06 16:55:14 +01002116 return mRequestThread->flush();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07002117}
2118
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002119status_t Camera3Device::prepare(int streamId) {
Ruben Brunkc78ac262015-08-13 17:58:46 -07002120 return prepare(camera3::Camera3StreamInterface::ALLOCATE_PIPELINE_MAX, streamId);
2121}
2122
2123status_t Camera3Device::prepare(int maxCount, int streamId) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002124 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002125 ALOGV("%s: Camera %s: Preparing stream %d", __FUNCTION__, mId.string(), streamId);
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07002126 Mutex::Autolock il(mInterfaceLock);
2127 Mutex::Autolock l(mLock);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002128
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002129 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
2130 if (stream == nullptr) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002131 CLOGE("Stream %d does not exist", streamId);
2132 return BAD_VALUE;
2133 }
2134
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002135 if (stream->isUnpreparable() || stream->hasOutstandingBuffers() ) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07002136 CLOGE("Stream %d has already been a request target", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002137 return BAD_VALUE;
2138 }
2139
2140 if (mRequestThread->isStreamPending(stream)) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07002141 CLOGE("Stream %d is already a target in a pending request", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002142 return BAD_VALUE;
2143 }
2144
Ruben Brunkc78ac262015-08-13 17:58:46 -07002145 return mPreparerThread->prepare(maxCount, stream);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002146}
2147
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002148status_t Camera3Device::tearDown(int streamId) {
2149 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002150 ALOGV("%s: Camera %s: Tearing down stream %d", __FUNCTION__, mId.string(), streamId);
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002151 Mutex::Autolock il(mInterfaceLock);
2152 Mutex::Autolock l(mLock);
2153
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002154 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
2155 if (stream == nullptr) {
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002156 CLOGE("Stream %d does not exist", streamId);
2157 return BAD_VALUE;
2158 }
2159
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002160 if (stream->hasOutstandingBuffers() || mRequestThread->isStreamPending(stream)) {
2161 CLOGE("Stream %d is a target of a in-progress request", streamId);
2162 return BAD_VALUE;
2163 }
2164
2165 return stream->tearDown();
2166}
2167
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002168status_t Camera3Device::addBufferListenerForStream(int streamId,
2169 wp<Camera3StreamBufferListener> listener) {
2170 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002171 ALOGV("%s: Camera %s: Adding buffer listener for stream %d", __FUNCTION__, mId.string(), streamId);
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002172 Mutex::Autolock il(mInterfaceLock);
2173 Mutex::Autolock l(mLock);
2174
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002175 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
2176 if (stream == nullptr) {
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002177 CLOGE("Stream %d does not exist", streamId);
2178 return BAD_VALUE;
2179 }
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002180 stream->addBufferListener(listener);
2181
2182 return OK;
2183}
2184
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002185/**
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002186 * Methods called by subclasses
2187 */
2188
2189void Camera3Device::notifyStatus(bool idle) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002190 ATRACE_CALL();
Shuzhen Wang316781a2020-08-18 18:11:01 -07002191 std::vector<int> streamIds;
2192 std::vector<hardware::CameraStreamStats> streamStats;
2193
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002194 {
2195 // Need mLock to safely update state and synchronize to current
2196 // state of methods in flight.
2197 Mutex::Autolock l(mLock);
2198 // We can get various system-idle notices from the status tracker
2199 // while starting up. Only care about them if we've actually sent
2200 // in some requests recently.
2201 if (mStatus != STATUS_ACTIVE && mStatus != STATUS_CONFIGURED) {
2202 return;
2203 }
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08002204 ALOGV("%s: Camera %s: Now %s, pauseState: %s", __FUNCTION__, mId.string(),
2205 idle ? "idle" : "active", mPauseStateNotify ? "true" : "false");
Ruben Brunk183f0562015-08-12 12:55:02 -07002206 internalUpdateStatusLocked(idle ? STATUS_CONFIGURED : STATUS_ACTIVE);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002207
2208 // Skip notifying listener if we're doing some user-transparent
2209 // state changes
2210 if (mPauseStateNotify) return;
Shuzhen Wang316781a2020-08-18 18:11:01 -07002211
2212 // Populate stream statistics in case of Idle
2213 if (idle) {
2214 for (size_t i = 0; i < mOutputStreams.size(); i++) {
2215 auto stream = mOutputStreams[i];
2216 if (stream.get() == nullptr) continue;
2217 streamIds.push_back(stream->getId());
2218 Camera3Stream* camera3Stream = Camera3Stream::cast(stream->asHalStream());
2219 int64_t usage = 0LL;
2220 if (camera3Stream != nullptr) {
2221 usage = camera3Stream->getUsage();
2222 }
2223 streamStats.emplace_back(stream->getWidth(), stream->getHeight(),
2224 stream->getFormat(), stream->getDataSpace(), usage,
2225 stream->getMaxHalBuffers(),
2226 stream->getMaxTotalBuffers() - stream->getMaxHalBuffers());
2227 }
2228 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002229 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002230
2231 sp<NotificationListener> listener;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002232 {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002233 std::lock_guard<std::mutex> l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002234 listener = mListener.promote();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002235 }
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07002236 status_t res = OK;
2237 if (listener != nullptr) {
2238 if (idle) {
2239 // Get session stats from the builder, and notify the listener.
2240 int64_t requestCount, resultErrorCount;
2241 bool deviceError;
2242 std::map<int, StreamStats> streamStatsMap;
2243 mSessionStatsBuilder.buildAndReset(&requestCount, &resultErrorCount,
2244 &deviceError, &streamStatsMap);
2245 for (size_t i = 0; i < streamIds.size(); i++) {
2246 int streamId = streamIds[i];
2247 auto stats = streamStatsMap.find(streamId);
2248 if (stats != streamStatsMap.end()) {
2249 streamStats[i].mRequestCount = stats->second.mRequestedFrameCount;
2250 streamStats[i].mErrorCount = stats->second.mDroppedFrameCount;
2251 streamStats[i].mStartLatencyMs = stats->second.mStartLatencyMs;
2252 streamStats[i].mHistogramType =
2253 hardware::CameraStreamStats::HISTOGRAM_TYPE_CAPTURE_LATENCY;
2254 streamStats[i].mHistogramBins.assign(
2255 stats->second.mCaptureLatencyBins.begin(),
2256 stats->second.mCaptureLatencyBins.end());
2257 streamStats[i].mHistogramCounts.assign(
2258 stats->second.mCaptureLatencyHistogram.begin(),
2259 stats->second.mCaptureLatencyHistogram.end());
2260 }
Shuzhen Wang316781a2020-08-18 18:11:01 -07002261 }
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07002262 listener->notifyIdle(requestCount, resultErrorCount, deviceError, streamStats);
2263 } else {
2264 res = listener->notifyActive();
Shuzhen Wang316781a2020-08-18 18:11:01 -07002265 }
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07002266 }
2267 if (res != OK) {
2268 SET_ERR("Camera access permission lost mid-operation: %s (%d)",
2269 strerror(-res), res);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002270 }
2271}
2272
Shuzhen Wang758c2152017-01-10 18:26:18 -08002273status_t Camera3Device::setConsumerSurfaces(int streamId,
Emilian Peev40ead602017-09-26 15:46:36 +01002274 const std::vector<sp<Surface>>& consumers, std::vector<int> *surfaceIds) {
Zhijun He5d677d12016-05-29 16:52:39 -07002275 ATRACE_CALL();
Shuzhen Wang758c2152017-01-10 18:26:18 -08002276 ALOGV("%s: Camera %s: set consumer surface for stream %d",
2277 __FUNCTION__, mId.string(), streamId);
Emilian Peev40ead602017-09-26 15:46:36 +01002278
2279 if (surfaceIds == nullptr) {
2280 return BAD_VALUE;
2281 }
2282
Zhijun He5d677d12016-05-29 16:52:39 -07002283 Mutex::Autolock il(mInterfaceLock);
2284 Mutex::Autolock l(mLock);
2285
Shuzhen Wang758c2152017-01-10 18:26:18 -08002286 if (consumers.size() == 0) {
2287 CLOGE("No consumer is passed!");
Zhijun He5d677d12016-05-29 16:52:39 -07002288 return BAD_VALUE;
2289 }
2290
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002291 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
2292 if (stream == nullptr) {
Zhijun He5d677d12016-05-29 16:52:39 -07002293 CLOGE("Stream %d is unknown", streamId);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002294 return BAD_VALUE;
Zhijun He5d677d12016-05-29 16:52:39 -07002295 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002296
2297 // isConsumerConfigurationDeferred will be off after setConsumers
2298 bool isDeferred = stream->isConsumerConfigurationDeferred();
Shuzhen Wang758c2152017-01-10 18:26:18 -08002299 status_t res = stream->setConsumers(consumers);
Zhijun He5d677d12016-05-29 16:52:39 -07002300 if (res != OK) {
2301 CLOGE("Stream %d set consumer failed (error %d %s) ", streamId, res, strerror(-res));
2302 return res;
2303 }
2304
Emilian Peev40ead602017-09-26 15:46:36 +01002305 for (auto &consumer : consumers) {
2306 int id = stream->getSurfaceId(consumer);
2307 if (id < 0) {
2308 CLOGE("Invalid surface id!");
2309 return BAD_VALUE;
2310 }
2311 surfaceIds->push_back(id);
2312 }
2313
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002314 if (isDeferred) {
Shuzhen Wang0129d522016-10-30 22:43:41 -07002315 if (!stream->isConfiguring()) {
2316 CLOGE("Stream %d was already fully configured.", streamId);
2317 return INVALID_OPERATION;
2318 }
Zhijun He5d677d12016-05-29 16:52:39 -07002319
Shuzhen Wang0129d522016-10-30 22:43:41 -07002320 res = stream->finishConfiguration();
2321 if (res != OK) {
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002322 // If finishConfiguration fails due to abandoned surface, do not set
2323 // device to error state.
2324 bool isSurfaceAbandoned =
2325 (res == NO_INIT || res == DEAD_OBJECT) && stream->isAbandoned();
2326 if (!isSurfaceAbandoned) {
2327 SET_ERR_L("Can't finish configuring output stream %d: %s (%d)",
2328 stream->getId(), strerror(-res), res);
2329 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07002330 return res;
2331 }
Zhijun He5d677d12016-05-29 16:52:39 -07002332 }
2333
2334 return OK;
2335}
2336
Emilian Peev40ead602017-09-26 15:46:36 +01002337status_t Camera3Device::updateStream(int streamId, const std::vector<sp<Surface>> &newSurfaces,
2338 const std::vector<OutputStreamInfo> &outputInfo,
2339 const std::vector<size_t> &removedSurfaceIds, KeyedVector<sp<Surface>, size_t> *outputMap) {
2340 Mutex::Autolock il(mInterfaceLock);
2341 Mutex::Autolock l(mLock);
2342
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002343 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
2344 if (stream == nullptr) {
Emilian Peev40ead602017-09-26 15:46:36 +01002345 CLOGE("Stream %d is unknown", streamId);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002346 return BAD_VALUE;
Emilian Peev40ead602017-09-26 15:46:36 +01002347 }
2348
2349 for (const auto &it : removedSurfaceIds) {
2350 if (mRequestThread->isOutputSurfacePending(streamId, it)) {
2351 CLOGE("Shared surface still part of a pending request!");
2352 return -EBUSY;
2353 }
2354 }
2355
Emilian Peev40ead602017-09-26 15:46:36 +01002356 status_t res = stream->updateStream(newSurfaces, outputInfo, removedSurfaceIds, outputMap);
2357 if (res != OK) {
2358 CLOGE("Stream %d failed to update stream (error %d %s) ",
2359 streamId, res, strerror(-res));
2360 if (res == UNKNOWN_ERROR) {
2361 SET_ERR_L("%s: Stream update failed to revert to previous output configuration!",
2362 __FUNCTION__);
2363 }
2364 return res;
2365 }
2366
2367 return res;
2368}
2369
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002370status_t Camera3Device::dropStreamBuffers(bool dropping, int streamId) {
2371 Mutex::Autolock il(mInterfaceLock);
2372 Mutex::Autolock l(mLock);
2373
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002374 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
2375 if (stream == nullptr) {
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002376 ALOGE("%s: Stream %d is not found.", __FUNCTION__, streamId);
2377 return BAD_VALUE;
2378 }
Shuzhen Wang316781a2020-08-18 18:11:01 -07002379
2380 if (dropping) {
2381 mSessionStatsBuilder.stopCounter(streamId);
2382 } else {
2383 mSessionStatsBuilder.startCounter(streamId);
2384 }
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002385 return stream->dropBuffers(dropping);
2386}
2387
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002388/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002389 * Camera3Device private methods
2390 */
2391
2392sp<Camera3Device::CaptureRequest> Camera3Device::createCaptureRequest(
Emilian Peevaebbe412018-01-15 13:53:24 +00002393 const PhysicalCameraSettingsList &request, const SurfaceMap &surfaceMap) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002394 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002395
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08002396 sp<CaptureRequest> newRequest = new CaptureRequest();
Emilian Peevaebbe412018-01-15 13:53:24 +00002397 newRequest->mSettingsList = request;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002398
2399 camera_metadata_entry_t inputStreams =
Emilian Peevaebbe412018-01-15 13:53:24 +00002400 newRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_INPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002401 if (inputStreams.count > 0) {
2402 if (mInputStream == NULL ||
Zhijun Hed1d64672013-09-06 15:00:01 -07002403 mInputStream->getId() != inputStreams.data.i32[0]) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002404 CLOGE("Request references unknown input stream %d",
2405 inputStreams.data.u8[0]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002406 return NULL;
2407 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002408
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002409 if (mInputStream->isConfiguring()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002410 SET_ERR_L("%s: input stream %d is not configured!",
2411 __FUNCTION__, mInputStream->getId());
2412 return NULL;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002413 }
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07002414 // Check if stream prepare is blocking requests.
2415 if (mInputStream->isBlockedByPrepare()) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002416 CLOGE("Request references an input stream that's being prepared!");
2417 return NULL;
2418 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002419
2420 newRequest->mInputStream = mInputStream;
Emilian Peevaebbe412018-01-15 13:53:24 +00002421 newRequest->mSettingsList.begin()->metadata.erase(ANDROID_REQUEST_INPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002422 }
2423
2424 camera_metadata_entry_t streams =
Emilian Peevaebbe412018-01-15 13:53:24 +00002425 newRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_OUTPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002426 if (streams.count == 0) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002427 CLOGE("Zero output streams specified!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002428 return NULL;
2429 }
2430
2431 for (size_t i = 0; i < streams.count; i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002432 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streams.data.i32[i]);
2433 if (stream == nullptr) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002434 CLOGE("Request references unknown stream %d",
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002435 streams.data.i32[i]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002436 return NULL;
2437 }
Zhijun He5d677d12016-05-29 16:52:39 -07002438 // It is illegal to include a deferred consumer output stream into a request
Shuzhen Wang0129d522016-10-30 22:43:41 -07002439 auto iter = surfaceMap.find(streams.data.i32[i]);
2440 if (iter != surfaceMap.end()) {
2441 const std::vector<size_t>& surfaces = iter->second;
2442 for (const auto& surface : surfaces) {
2443 if (stream->isConsumerConfigurationDeferred(surface)) {
2444 CLOGE("Stream %d surface %zu hasn't finished configuration yet "
2445 "due to deferred consumer", stream->getId(), surface);
2446 return NULL;
2447 }
2448 }
Yin-Chia Yeh0b287572018-10-15 12:38:13 -07002449 newRequest->mOutputSurfaces[streams.data.i32[i]] = surfaces;
Zhijun He5d677d12016-05-29 16:52:39 -07002450 }
2451
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002452 if (stream->isConfiguring()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002453 SET_ERR_L("%s: stream %d is not configured!", __FUNCTION__, stream->getId());
2454 return NULL;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002455 }
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07002456 // Check if stream prepare is blocking requests.
2457 if (stream->isBlockedByPrepare()) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002458 CLOGE("Request references an output stream that's being prepared!");
2459 return NULL;
2460 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002461
2462 newRequest->mOutputStreams.push(stream);
2463 }
Emilian Peevaebbe412018-01-15 13:53:24 +00002464 newRequest->mSettingsList.begin()->metadata.erase(ANDROID_REQUEST_OUTPUT_STREAMS);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07002465 newRequest->mBatchSize = 1;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002466
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08002467 auto rotateAndCropEntry =
2468 newRequest->mSettingsList.begin()->metadata.find(ANDROID_SCALER_ROTATE_AND_CROP);
2469 if (rotateAndCropEntry.count > 0 &&
2470 rotateAndCropEntry.data.u8[0] == ANDROID_SCALER_ROTATE_AND_CROP_AUTO) {
2471 newRequest->mRotateAndCropAuto = true;
2472 } else {
2473 newRequest->mRotateAndCropAuto = false;
2474 }
2475
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07002476 auto zoomRatioEntry =
2477 newRequest->mSettingsList.begin()->metadata.find(ANDROID_CONTROL_ZOOM_RATIO);
2478 if (zoomRatioEntry.count > 0 &&
2479 zoomRatioEntry.data.f[0] == 1.0f) {
2480 newRequest->mZoomRatioIs1x = true;
2481 } else {
2482 newRequest->mZoomRatioIs1x = false;
2483 }
2484
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08002485 if (mSupportCameraMute) {
Shuzhen Wang911c6a32021-10-27 13:36:03 -07002486 for (auto& settings : newRequest->mSettingsList) {
2487 auto testPatternModeEntry =
2488 settings.metadata.find(ANDROID_SENSOR_TEST_PATTERN_MODE);
2489 settings.mOriginalTestPatternMode = testPatternModeEntry.count > 0 ?
2490 testPatternModeEntry.data.i32[0] :
2491 ANDROID_SENSOR_TEST_PATTERN_MODE_OFF;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08002492
Shuzhen Wang911c6a32021-10-27 13:36:03 -07002493 auto testPatternDataEntry =
2494 settings.metadata.find(ANDROID_SENSOR_TEST_PATTERN_DATA);
2495 if (testPatternDataEntry.count >= 4) {
2496 memcpy(settings.mOriginalTestPatternData, testPatternDataEntry.data.i32,
2497 sizeof(PhysicalCameraSettings::mOriginalTestPatternData));
2498 } else {
2499 settings.mOriginalTestPatternData[0] = 0;
2500 settings.mOriginalTestPatternData[1] = 0;
2501 settings.mOriginalTestPatternData[2] = 0;
2502 settings.mOriginalTestPatternData[3] = 0;
2503 }
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08002504 }
2505 }
2506
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002507 return newRequest;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002508}
2509
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002510void Camera3Device::cancelStreamsConfigurationLocked() {
2511 int res = OK;
2512 if (mInputStream != NULL && mInputStream->isConfiguring()) {
2513 res = mInputStream->cancelConfiguration();
2514 if (res != OK) {
2515 CLOGE("Can't cancel configuring input stream %d: %s (%d)",
2516 mInputStream->getId(), strerror(-res), res);
2517 }
2518 }
2519
2520 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002521 sp<Camera3OutputStreamInterface> outputStream = mOutputStreams[i];
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002522 if (outputStream->isConfiguring()) {
2523 res = outputStream->cancelConfiguration();
2524 if (res != OK) {
2525 CLOGE("Can't cancel configuring output stream %d: %s (%d)",
2526 outputStream->getId(), strerror(-res), res);
2527 }
2528 }
2529 }
2530
2531 // Return state to that at start of call, so that future configures
2532 // properly clean things up
2533 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
2534 mNeedConfig = true;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002535
2536 res = mPreparerThread->resume();
2537 if (res != OK) {
2538 ALOGE("%s: Camera %s: Preparer thread failed to resume!", __FUNCTION__, mId.string());
2539 }
2540}
2541
Emilian Peev0d0191e2020-04-21 17:01:18 -07002542bool Camera3Device::checkAbandonedStreamsLocked() {
2543 if ((mInputStream.get() != nullptr) && (mInputStream->isAbandoned())) {
2544 return true;
2545 }
2546
2547 for (size_t i = 0; i < mOutputStreams.size(); i++) {
2548 auto stream = mOutputStreams[i];
2549 if ((stream.get() != nullptr) && (stream->isAbandoned())) {
2550 return true;
2551 }
2552 }
2553
2554 return false;
2555}
2556
Emilian Peev3bead5f2020-05-28 17:29:08 -07002557bool Camera3Device::reconfigureCamera(const CameraMetadata& sessionParams, int clientStatusId) {
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002558 ATRACE_CALL();
2559 bool ret = false;
2560
Shuzhen Wang316781a2020-08-18 18:11:01 -07002561 nsecs_t startTime = systemTime();
2562
Jayant Chowdhary646c31b2020-01-30 13:09:59 -08002563 Mutex::Autolock il(mInterfaceLock);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002564 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
2565
2566 Mutex::Autolock l(mLock);
Emilian Peev0d0191e2020-04-21 17:01:18 -07002567 if (checkAbandonedStreamsLocked()) {
2568 ALOGW("%s: Abandoned stream detected, session parameters can't be applied correctly!",
2569 __FUNCTION__);
2570 return true;
2571 }
2572
Emilian Peev3bead5f2020-05-28 17:29:08 -07002573 status_t rc = NO_ERROR;
2574 bool markClientActive = false;
2575 if (mStatus == STATUS_ACTIVE) {
2576 markClientActive = true;
2577 mPauseStateNotify = true;
2578 mStatusTracker->markComponentIdle(clientStatusId, Fence::NO_FENCE);
2579
2580 rc = internalPauseAndWaitLocked(maxExpectedDuration);
2581 }
2582
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002583 if (rc == NO_ERROR) {
2584 mNeedConfig = true;
2585 rc = configureStreamsLocked(mOperatingMode, sessionParams, /*notifyRequestThread*/ false);
2586 if (rc == NO_ERROR) {
2587 ret = true;
2588 mPauseStateNotify = false;
2589 //Moving to active state while holding 'mLock' is important.
2590 //There could be pending calls to 'create-/deleteStream' which
2591 //will trigger another stream configuration while the already
2592 //present streams end up with outstanding buffers that will
2593 //not get drained.
2594 internalUpdateStatusLocked(STATUS_ACTIVE);
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002595 } else if (rc == DEAD_OBJECT) {
2596 // DEAD_OBJECT can be returned if either the consumer surface is
2597 // abandoned, or the HAL has died.
2598 // - If the HAL has died, configureStreamsLocked call will set
2599 // device to error state,
2600 // - If surface is abandoned, we should not set device to error
2601 // state.
2602 ALOGE("Failed to re-configure camera due to abandoned surface");
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002603 } else {
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002604 SET_ERR_L("Failed to re-configure camera: %d", rc);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002605 }
2606 } else {
2607 ALOGE("%s: Failed to pause streaming: %d", __FUNCTION__, rc);
2608 }
2609
Shuzhen Wang316781a2020-08-18 18:11:01 -07002610 CameraServiceProxyWrapper::logStreamConfigured(mId, mOperatingMode, true /*internalReconfig*/,
2611 ns2ms(systemTime() - startTime));
2612
Emilian Peev3bead5f2020-05-28 17:29:08 -07002613 if (markClientActive) {
2614 mStatusTracker->markComponentActive(clientStatusId);
2615 }
2616
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002617 return ret;
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002618}
2619
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002620status_t Camera3Device::configureStreamsLocked(int operatingMode,
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002621 const CameraMetadata& sessionParams, bool notifyRequestThread) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002622 ATRACE_CALL();
2623 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002624
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002625 if (mStatus != STATUS_UNCONFIGURED && mStatus != STATUS_CONFIGURED) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002626 CLOGE("Not idle");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002627 return INVALID_OPERATION;
2628 }
2629
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08002630 if (operatingMode < 0) {
2631 CLOGE("Invalid operating mode: %d", operatingMode);
2632 return BAD_VALUE;
2633 }
2634
2635 bool isConstrainedHighSpeed =
2636 static_cast<int>(StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE) ==
2637 operatingMode;
2638
2639 if (mOperatingMode != operatingMode) {
2640 mNeedConfig = true;
2641 mIsConstrainedHighSpeedConfiguration = isConstrainedHighSpeed;
2642 mOperatingMode = operatingMode;
2643 }
2644
Shuzhen Wang0cf01cb2019-09-05 13:33:06 -07002645 // In case called from configureStreams, abort queued input buffers not belonging to
2646 // any pending requests.
2647 if (mInputStream != NULL && notifyRequestThread) {
2648 while (true) {
Emilian Peevf4816702020-04-03 15:44:51 -07002649 camera_stream_buffer_t inputBuffer;
Shuzhen Wang83bff122020-11-20 15:51:39 -08002650 camera3::Size inputBufferSize;
Shuzhen Wang0cf01cb2019-09-05 13:33:06 -07002651 status_t res = mInputStream->getInputBuffer(&inputBuffer,
Shuzhen Wang83bff122020-11-20 15:51:39 -08002652 &inputBufferSize, /*respectHalLimit*/ false);
Shuzhen Wang0cf01cb2019-09-05 13:33:06 -07002653 if (res != OK) {
2654 // Exhausted acquiring all input buffers.
2655 break;
2656 }
2657
Emilian Peevf4816702020-04-03 15:44:51 -07002658 inputBuffer.status = CAMERA_BUFFER_STATUS_ERROR;
Shuzhen Wang0cf01cb2019-09-05 13:33:06 -07002659 res = mInputStream->returnInputBuffer(inputBuffer);
2660 if (res != OK) {
2661 ALOGE("%s: %d: couldn't return input buffer while clearing input queue: "
2662 "%s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
2663 }
2664 }
2665 }
2666
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002667 if (!mNeedConfig) {
2668 ALOGV("%s: Skipping config, no stream changes", __FUNCTION__);
2669 return OK;
2670 }
2671
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002672 // Workaround for device HALv3.2 or older spec bug - zero streams requires
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002673 // adding a fake stream instead.
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002674 // TODO: Bug: 17321404 for fixing the HAL spec and removing this workaround.
2675 if (mOutputStreams.size() == 0) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002676 addFakeStreamLocked();
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002677 } else {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002678 tryRemoveFakeStreamLocked();
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002679 }
2680
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002681 // Start configuring the streams
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002682 ALOGV("%s: Camera %s: Starting stream configuration", __FUNCTION__, mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002683
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002684 mPreparerThread->pause();
2685
Emilian Peevf4816702020-04-03 15:44:51 -07002686 camera_stream_configuration config;
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -08002687 config.operation_mode = mOperatingMode;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002688 config.num_streams = (mInputStream != NULL) + mOutputStreams.size();
Shuzhen Wang83bff122020-11-20 15:51:39 -08002689 config.input_is_multi_resolution = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002690
Emilian Peevf4816702020-04-03 15:44:51 -07002691 Vector<camera3::camera_stream_t*> streams;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002692 streams.setCapacity(config.num_streams);
Emilian Peev192ee832018-01-31 14:46:47 +00002693 std::vector<uint32_t> bufferSizes(config.num_streams, 0);
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002694
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002695
2696 if (mInputStream != NULL) {
Emilian Peevf4816702020-04-03 15:44:51 -07002697 camera3::camera_stream_t *inputStream;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002698 inputStream = mInputStream->startConfiguration();
2699 if (inputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002700 CLOGE("Can't start input stream configuration");
2701 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002702 return INVALID_OPERATION;
2703 }
2704 streams.add(inputStream);
Shuzhen Wang83bff122020-11-20 15:51:39 -08002705
2706 config.input_is_multi_resolution = mIsInputStreamMultiResolution;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002707 }
2708
Shuzhen Wang99080502021-03-07 21:08:20 -08002709 mGroupIdPhysicalCameraMap.clear();
Emilian Peeve23f1d92021-09-20 14:56:01 -07002710 bool composerSurfacePresent = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002711 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Igor Murashkin2fba5842013-04-22 14:03:54 -07002712
2713 // Don't configure bidi streams twice, nor add them twice to the list
2714 if (mOutputStreams[i].get() ==
2715 static_cast<Camera3StreamInterface*>(mInputStream.get())) {
2716
2717 config.num_streams--;
2718 continue;
2719 }
2720
Emilian Peevf4816702020-04-03 15:44:51 -07002721 camera3::camera_stream_t *outputStream;
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002722 outputStream = mOutputStreams[i]->startConfiguration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002723 if (outputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002724 CLOGE("Can't start output stream configuration");
2725 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002726 return INVALID_OPERATION;
2727 }
2728 streams.add(outputStream);
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002729
Shuzhen Wangb7ab1e42019-02-20 15:42:23 -08002730 if (outputStream->format == HAL_PIXEL_FORMAT_BLOB) {
Emilian Peev192ee832018-01-31 14:46:47 +00002731 size_t k = i + ((mInputStream != nullptr) ? 1 : 0); // Input stream if present should
2732 // always occupy the initial entry.
Shuzhen Wangb7ab1e42019-02-20 15:42:23 -08002733 if (outputStream->data_space == HAL_DATASPACE_V0_JFIF) {
2734 bufferSizes[k] = static_cast<uint32_t>(
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -08002735 getJpegBufferSize(infoPhysical(String8(outputStream->physical_camera_id)),
2736 outputStream->width, outputStream->height));
Shuzhen Wangb7ab1e42019-02-20 15:42:23 -08002737 } else if (outputStream->data_space ==
2738 static_cast<android_dataspace>(HAL_DATASPACE_JPEG_APP_SEGMENTS)) {
2739 bufferSizes[k] = outputStream->width * outputStream->height;
2740 } else {
2741 ALOGW("%s: Blob dataSpace %d not supported",
2742 __FUNCTION__, outputStream->data_space);
2743 }
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002744 }
Shuzhen Wang99080502021-03-07 21:08:20 -08002745
2746 if (mOutputStreams[i]->isMultiResolution()) {
2747 int32_t streamGroupId = mOutputStreams[i]->getHalStreamGroupId();
2748 const String8& physicalCameraId = mOutputStreams[i]->getPhysicalCameraId();
2749 mGroupIdPhysicalCameraMap[streamGroupId].insert(physicalCameraId);
2750 }
Emilian Peeve23f1d92021-09-20 14:56:01 -07002751
2752 if (outputStream->usage & GraphicBuffer::USAGE_HW_COMPOSER) {
2753 composerSurfacePresent = true;
2754 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002755 }
2756
2757 config.streams = streams.editArray();
2758
2759 // Do the HAL configuration; will potentially touch stream
Shuzhen Wang92653952019-05-07 15:11:43 -07002760 // max_buffers, usage, and priv fields, as well as data_space and format
2761 // fields for IMPLEMENTATION_DEFINED formats.
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002762
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002763 const camera_metadata_t *sessionBuffer = sessionParams.getAndLock();
Emilian Peev192ee832018-01-31 14:46:47 +00002764 res = mInterface->configureStreams(sessionBuffer, &config, bufferSizes);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002765 sessionParams.unlock(sessionBuffer);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002766
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002767 if (res == BAD_VALUE) {
2768 // HAL rejected this set of streams as unsupported, clean up config
2769 // attempt and return to unconfigured state
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002770 CLOGE("Set of requested inputs/outputs not supported by HAL");
2771 cancelStreamsConfigurationLocked();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002772 return BAD_VALUE;
2773 } else if (res != OK) {
2774 // Some other kind of error from configure_streams - this is not
2775 // expected
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002776 SET_ERR_L("Unable to configure streams with HAL: %s (%d)",
2777 strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002778 return res;
2779 }
2780
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002781 // Finish all stream configuration immediately.
2782 // TODO: Try to relax this later back to lazy completion, which should be
2783 // faster
2784
Igor Murashkin073f8572013-05-02 14:59:28 -07002785 if (mInputStream != NULL && mInputStream->isConfiguring()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002786 bool streamReConfigured = false;
2787 res = mInputStream->finishConfiguration(&streamReConfigured);
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002788 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002789 CLOGE("Can't finish configuring input stream %d: %s (%d)",
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002790 mInputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002791 cancelStreamsConfigurationLocked();
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002792 if ((res == NO_INIT || res == DEAD_OBJECT) && mInputStream->isAbandoned()) {
2793 return DEAD_OBJECT;
2794 }
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002795 return BAD_VALUE;
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002796 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002797 if (streamReConfigured) {
2798 mInterface->onStreamReConfigured(mInputStream->getId());
2799 }
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002800 }
2801
2802 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002803 sp<Camera3OutputStreamInterface> outputStream = mOutputStreams[i];
Zhijun He5d677d12016-05-29 16:52:39 -07002804 if (outputStream->isConfiguring() && !outputStream->isConsumerConfigurationDeferred()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002805 bool streamReConfigured = false;
2806 res = outputStream->finishConfiguration(&streamReConfigured);
Igor Murashkin073f8572013-05-02 14:59:28 -07002807 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002808 CLOGE("Can't finish configuring output stream %d: %s (%d)",
Igor Murashkin073f8572013-05-02 14:59:28 -07002809 outputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002810 cancelStreamsConfigurationLocked();
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002811 if ((res == NO_INIT || res == DEAD_OBJECT) && outputStream->isAbandoned()) {
2812 return DEAD_OBJECT;
2813 }
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002814 return BAD_VALUE;
Igor Murashkin073f8572013-05-02 14:59:28 -07002815 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002816 if (streamReConfigured) {
2817 mInterface->onStreamReConfigured(outputStream->getId());
2818 }
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002819 }
2820 }
2821
Emilian Peeve23f1d92021-09-20 14:56:01 -07002822 mRequestThread->setComposerSurface(composerSurfacePresent);
2823
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002824 // Request thread needs to know to avoid using repeat-last-settings protocol
2825 // across configure_streams() calls
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002826 if (notifyRequestThread) {
Shuzhen Wang99080502021-03-07 21:08:20 -08002827 mRequestThread->configurationComplete(mIsConstrainedHighSpeedConfiguration,
2828 sessionParams, mGroupIdPhysicalCameraMap);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002829 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002830
Zhijun He90f7c372016-08-16 16:19:43 -07002831 char value[PROPERTY_VALUE_MAX];
2832 property_get("camera.fifo.disable", value, "0");
2833 int32_t disableFifo = atoi(value);
2834 if (disableFifo != 1) {
2835 // Boost priority of request thread to SCHED_FIFO.
2836 pid_t requestThreadTid = mRequestThread->getTid();
2837 res = requestPriority(getpid(), requestThreadTid,
Mikhail Naganov83f04272017-02-07 10:45:09 -08002838 kRequestThreadPriority, /*isForApp*/ false, /*asynchronous*/ false);
Zhijun He90f7c372016-08-16 16:19:43 -07002839 if (res != OK) {
2840 ALOGW("Can't set realtime priority for request processing thread: %s (%d)",
2841 strerror(-res), res);
2842 } else {
2843 ALOGD("Set real time priority for request queue thread (tid %d)", requestThreadTid);
2844 }
Eino-Ville Talvalaf99498e2015-09-25 16:52:55 -07002845 }
2846
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002847 // Update device state
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002848 const camera_metadata_t *newSessionParams = sessionParams.getAndLock();
2849 const camera_metadata_t *currentSessionParams = mSessionParams.getAndLock();
2850 bool updateSessionParams = (newSessionParams != currentSessionParams) ? true : false;
2851 sessionParams.unlock(newSessionParams);
2852 mSessionParams.unlock(currentSessionParams);
2853 if (updateSessionParams) {
2854 mSessionParams = sessionParams;
2855 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002856
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002857 mNeedConfig = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002858
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002859 internalUpdateStatusLocked((mFakeStreamId == NO_STREAM) ?
Ruben Brunk183f0562015-08-12 12:55:02 -07002860 STATUS_CONFIGURED : STATUS_UNCONFIGURED);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002861
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002862 ALOGV("%s: Camera %s: Stream configuration complete", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002863
Zhijun He0a210512014-07-24 13:45:15 -07002864 // tear down the deleted streams after configure streams.
2865 mDeletedStreams.clear();
2866
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002867 auto rc = mPreparerThread->resume();
2868 if (rc != OK) {
2869 SET_ERR_L("%s: Camera %s: Preparer thread failed to resume!", __FUNCTION__, mId.string());
2870 return rc;
2871 }
2872
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002873 if (mFakeStreamId == NO_STREAM) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07002874 mRequestBufferSM.onStreamsConfigured();
2875 }
2876
Cliff Wu3b268182021-07-06 15:44:43 +08002877 // First call injectCamera() and then run configureStreamsLocked() case:
Cliff Wuc2ad9c82021-04-21 00:58:58 +08002878 // Since the streams configuration of the injection camera is based on the internal camera, we
Cliff Wu3b268182021-07-06 15:44:43 +08002879 // must wait until the internal camera configure streams before running the injection job to
Cliff Wuc2ad9c82021-04-21 00:58:58 +08002880 // configure the injection streams.
2881 if (mInjectionMethods->isInjecting()) {
Cliff Wu3b268182021-07-06 15:44:43 +08002882 ALOGD("%s: Injection camera %s: Start to configure streams.",
Cliff Wuc2ad9c82021-04-21 00:58:58 +08002883 __FUNCTION__, mInjectionMethods->getInjectedCamId().string());
2884 res = mInjectionMethods->injectCamera(config, bufferSizes);
2885 if (res != OK) {
2886 ALOGE("Can't finish inject camera process!");
2887 return res;
2888 }
Cliff Wu3b268182021-07-06 15:44:43 +08002889 } else {
2890 // First run configureStreamsLocked() and then call injectCamera() case:
2891 // If the stream configuration has been completed and camera deive is active, but the
2892 // injection camera has not been injected yet, we need to store the stream configuration of
2893 // the internal camera (because the stream configuration of the injection camera is based
2894 // on the internal camera). When injecting occurs later, this configuration can be used by
2895 // the injection camera.
2896 ALOGV("%s: The stream configuration is complete and the camera device is active, but the"
2897 " injection camera has not been injected yet.", __FUNCTION__);
2898 mInjectionMethods->storeInjectionConfig(config, bufferSizes);
Cliff Wuc2ad9c82021-04-21 00:58:58 +08002899 }
2900
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002901 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002902}
2903
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002904status_t Camera3Device::addFakeStreamLocked() {
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002905 ATRACE_CALL();
2906 status_t res;
2907
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002908 if (mFakeStreamId != NO_STREAM) {
2909 // Should never be adding a second fake stream when one is already
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002910 // active
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002911 SET_ERR_L("%s: Camera %s: A fake stream already exists!",
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002912 __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002913 return INVALID_OPERATION;
2914 }
2915
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002916 ALOGV("%s: Camera %s: Adding a fake stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002917
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002918 sp<Camera3OutputStreamInterface> fakeStream =
2919 new Camera3FakeStream(mNextStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002920
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002921 res = mOutputStreams.add(mNextStreamId, fakeStream);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002922 if (res < 0) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002923 SET_ERR_L("Can't add fake stream to set: %s (%d)", strerror(-res), res);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002924 return res;
2925 }
2926
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002927 mFakeStreamId = mNextStreamId;
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002928 mNextStreamId++;
2929
2930 return OK;
2931}
2932
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002933status_t Camera3Device::tryRemoveFakeStreamLocked() {
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002934 ATRACE_CALL();
2935 status_t res;
2936
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002937 if (mFakeStreamId == NO_STREAM) return OK;
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002938 if (mOutputStreams.size() == 1) return OK;
2939
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002940 ALOGV("%s: Camera %s: Removing the fake stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002941
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002942 // Ok, have a fake stream and there's at least one other output stream,
2943 // so remove the fake
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002944
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002945 sp<Camera3StreamInterface> deletedStream = mOutputStreams.get(mFakeStreamId);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002946 if (deletedStream == nullptr) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002947 SET_ERR_L("Fake stream %d does not appear to exist", mFakeStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002948 return INVALID_OPERATION;
2949 }
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002950 mOutputStreams.remove(mFakeStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002951
2952 // Free up the stream endpoint so that it can be used by some other stream
2953 res = deletedStream->disconnect();
2954 if (res != OK) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002955 SET_ERR_L("Can't disconnect deleted fake stream %d", mFakeStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002956 // fall through since we want to still list the stream as deleted.
2957 }
2958 mDeletedStreams.add(deletedStream);
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002959 mFakeStreamId = NO_STREAM;
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002960
2961 return res;
2962}
2963
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002964void Camera3Device::setErrorState(const char *fmt, ...) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002965 ATRACE_CALL();
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002966 Mutex::Autolock l(mLock);
2967 va_list args;
2968 va_start(args, fmt);
2969
2970 setErrorStateLockedV(fmt, args);
2971
2972 va_end(args);
2973}
2974
2975void Camera3Device::setErrorStateV(const char *fmt, va_list args) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002976 ATRACE_CALL();
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002977 Mutex::Autolock l(mLock);
2978 setErrorStateLockedV(fmt, args);
2979}
2980
2981void Camera3Device::setErrorStateLocked(const char *fmt, ...) {
2982 va_list args;
2983 va_start(args, fmt);
2984
2985 setErrorStateLockedV(fmt, args);
2986
2987 va_end(args);
2988}
2989
2990void Camera3Device::setErrorStateLockedV(const char *fmt, va_list args) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002991 // Print out all error messages to log
2992 String8 errorCause = String8::formatV(fmt, args);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002993 ALOGE("Camera %s: %s", mId.string(), errorCause.string());
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002994
2995 // But only do error state transition steps for the first error
Zhijun Heb05eeae2013-06-06 13:51:22 -07002996 if (mStatus == STATUS_ERROR || mStatus == STATUS_UNINITIALIZED) return;
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002997
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002998 mErrorCause = errorCause;
2999
Yin-Chia Yeh3d145ae2017-07-27 12:47:03 -07003000 if (mRequestThread != nullptr) {
3001 mRequestThread->setPaused(true);
3002 }
Ruben Brunk183f0562015-08-12 12:55:02 -07003003 internalUpdateStatusLocked(STATUS_ERROR);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003004
3005 // Notify upstream about a device error
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003006 sp<NotificationListener> listener = mListener.promote();
3007 if (listener != NULL) {
3008 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003009 CaptureResultExtras());
Shuzhen Wang316781a2020-08-18 18:11:01 -07003010 mSessionStatsBuilder.onDeviceError();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003011 }
3012
3013 // Save stack trace. View by dumping it later.
3014 CameraTraces::saveTrace();
3015 // TODO: consider adding errorCause and client pid/procname
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07003016}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003017
3018/**
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003019 * In-flight request management
3020 */
3021
Jianing Weicb0652e2014-03-12 18:29:36 -07003022status_t Camera3Device::registerInFlight(uint32_t frameNumber,
Chien-Yu Chend196d612015-06-22 19:49:01 -07003023 int32_t numBuffers, CaptureResultExtras resultExtras, bool hasInput,
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003024 bool hasAppCallback, nsecs_t maxExpectedDuration,
Shuzhen Wang99080502021-03-07 21:08:20 -08003025 const std::set<std::set<String8>>& physicalCameraIds,
3026 bool isStillCapture, bool isZslCapture, bool rotateAndCropAuto,
3027 const std::set<std::string>& cameraIdsWithZoom,
Shuzhen Wang316781a2020-08-18 18:11:01 -07003028 const SurfaceMap& outputSurfaces, nsecs_t requestTimeNs) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003029 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003030 std::lock_guard<std::mutex> l(mInFlightLock);
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003031
3032 ssize_t res;
Chien-Yu Chend196d612015-06-22 19:49:01 -07003033 res = mInFlightMap.add(frameNumber, InFlightRequest(numBuffers, resultExtras, hasInput,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003034 hasAppCallback, maxExpectedDuration, physicalCameraIds, isStillCapture, isZslCapture,
Shuzhen Wang316781a2020-08-18 18:11:01 -07003035 rotateAndCropAuto, cameraIdsWithZoom, requestTimeNs, outputSurfaces));
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003036 if (res < 0) return res;
3037
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07003038 if (mInFlightMap.size() == 1) {
Emilian Peev26d975d2018-07-05 14:52:57 +01003039 // Hold a separate dedicated tracker lock to prevent race with disconnect and also
3040 // avoid a deadlock during reprocess requests.
3041 Mutex::Autolock l(mTrackerLock);
Yin-Chia Yeh38dfde52017-06-27 17:13:33 -07003042 if (mStatusTracker != nullptr) {
3043 mStatusTracker->markComponentActive(mInFlightStatusId);
3044 }
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07003045 }
3046
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003047 mExpectedInflightDuration += maxExpectedDuration;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003048 return OK;
3049}
3050
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003051void Camera3Device::onInflightEntryRemovedLocked(nsecs_t duration) {
Shuzhen Wangcadb3302016-11-04 14:17:56 -07003052 // Indicate idle inFlightMap to the status tracker
3053 if (mInFlightMap.size() == 0) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07003054 mRequestBufferSM.onInflightMapEmpty();
Emilian Peev26d975d2018-07-05 14:52:57 +01003055 // Hold a separate dedicated tracker lock to prevent race with disconnect and also
3056 // avoid a deadlock during reprocess requests.
3057 Mutex::Autolock l(mTrackerLock);
Yin-Chia Yeh38dfde52017-06-27 17:13:33 -07003058 if (mStatusTracker != nullptr) {
3059 mStatusTracker->markComponentIdle(mInFlightStatusId, Fence::NO_FENCE);
3060 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07003061 }
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003062 mExpectedInflightDuration -= duration;
Shuzhen Wangcadb3302016-11-04 14:17:56 -07003063}
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003064
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003065void Camera3Device::checkInflightMapLengthLocked() {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04003066 // Validation check - if we have too many in-flight frames with long total inflight duration,
Yin-Chia Yeh99fd0972019-06-27 14:22:44 -07003067 // something has likely gone wrong. This might still be legit only if application send in
3068 // a long burst of long exposure requests.
3069 if (mExpectedInflightDuration > kMinWarnInflightDuration) {
3070 if (!mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() > kInFlightWarnLimit) {
3071 CLOGW("In-flight list too large: %zu, total inflight duration %" PRIu64,
3072 mInFlightMap.size(), mExpectedInflightDuration);
3073 } else if (mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() >
3074 kInFlightWarnLimitHighSpeed) {
3075 CLOGW("In-flight list too large for high speed configuration: %zu,"
3076 "total inflight duration %" PRIu64,
3077 mInFlightMap.size(), mExpectedInflightDuration);
3078 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003079 }
3080}
3081
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003082void Camera3Device::onInflightMapFlushedLocked() {
3083 mExpectedInflightDuration = 0;
3084}
3085
3086void Camera3Device::removeInFlightMapEntryLocked(int idx) {
Jayant Chowdharyd4776262020-06-23 23:45:57 -07003087 ATRACE_HFR_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003088 nsecs_t duration = mInFlightMap.valueAt(idx).maxExpectedDuration;
3089 mInFlightMap.removeItemsAt(idx, 1);
3090
3091 onInflightEntryRemovedLocked(duration);
3092}
3093
3094
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003095void Camera3Device::flushInflightRequests() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003096 ATRACE_CALL();
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003097 sp<NotificationListener> listener;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003098 {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003099 std::lock_guard<std::mutex> l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003100 listener = mListener.promote();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003101 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003102
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003103 FlushInflightReqStates states {
3104 mId, mInFlightLock, mInFlightMap, mUseHalBufManager,
Shuzhen Wang316781a2020-08-18 18:11:01 -07003105 listener, *this, *mInterface, *this, mSessionStatsBuilder};
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003106
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003107 camera3::flushInflightRequests(states);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003108}
3109
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003110CameraMetadata Camera3Device::getLatestRequestLocked() {
Igor Murashkin1e479c02013-09-06 16:55:14 -07003111 ALOGV("%s", __FUNCTION__);
3112
Igor Murashkin1e479c02013-09-06 16:55:14 -07003113 CameraMetadata retVal;
3114
3115 if (mRequestThread != NULL) {
3116 retVal = mRequestThread->getLatestRequest();
3117 }
3118
Igor Murashkin1e479c02013-09-06 16:55:14 -07003119 return retVal;
3120}
3121
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07003122void Camera3Device::monitorMetadata(TagMonitor::eventSource source,
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003123 int64_t frameNumber, nsecs_t timestamp, const CameraMetadata& metadata,
Jayant Chowdharycd277cd2021-08-11 15:48:40 -07003124 const std::unordered_map<std::string, CameraMetadata>& physicalMetadata,
Jayant Chowdharyc30b4c32021-08-18 11:43:16 -07003125 const camera_stream_buffer_t *outputBuffers, uint32_t numOutputBuffers,
3126 int32_t inputStreamId) {
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003127
3128 mTagMonitor.monitorMetadata(source, frameNumber, timestamp, metadata,
Jayant Chowdharyc30b4c32021-08-18 11:43:16 -07003129 physicalMetadata, outputBuffers, numOutputBuffers, inputStreamId);
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07003130}
3131
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003132/**
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003133 * HalInterface inner class methods
3134 */
3135
Yifan Hongf79b5542017-04-11 14:44:25 -07003136Camera3Device::HalInterface::HalInterface(
3137 sp<ICameraDeviceSession> &session,
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003138 std::shared_ptr<RequestMetadataQueue> queue,
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003139 bool useHalBufManager, bool supportOfflineProcessing) :
Yifan Hongf79b5542017-04-11 14:44:25 -07003140 mHidlSession(session),
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003141 mRequestMetadataQueue(queue),
Emilian Peev4ec17882019-01-24 17:16:58 -08003142 mUseHalBufManager(useHalBufManager),
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003143 mIsReconfigurationQuerySupported(true),
3144 mSupportOfflineProcessing(supportOfflineProcessing) {
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003145 // Check with hardware service manager if we can downcast these interfaces
3146 // Somewhat expensive, so cache the results at startup
Shuzhen Wang83bff122020-11-20 15:51:39 -08003147 auto castResult_3_7 = device::V3_7::ICameraDeviceSession::castFrom(mHidlSession);
3148 if (castResult_3_7.isOk()) {
3149 mHidlSession_3_7 = castResult_3_7;
3150 }
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003151 auto castResult_3_6 = device::V3_6::ICameraDeviceSession::castFrom(mHidlSession);
3152 if (castResult_3_6.isOk()) {
3153 mHidlSession_3_6 = castResult_3_6;
3154 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003155 auto castResult_3_5 = device::V3_5::ICameraDeviceSession::castFrom(mHidlSession);
3156 if (castResult_3_5.isOk()) {
3157 mHidlSession_3_5 = castResult_3_5;
3158 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003159 auto castResult_3_4 = device::V3_4::ICameraDeviceSession::castFrom(mHidlSession);
3160 if (castResult_3_4.isOk()) {
3161 mHidlSession_3_4 = castResult_3_4;
3162 }
3163 auto castResult_3_3 = device::V3_3::ICameraDeviceSession::castFrom(mHidlSession);
3164 if (castResult_3_3.isOk()) {
3165 mHidlSession_3_3 = castResult_3_3;
3166 }
3167}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003168
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003169Camera3Device::HalInterface::HalInterface() :
3170 mUseHalBufManager(false),
3171 mSupportOfflineProcessing(false) {}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003172
3173Camera3Device::HalInterface::HalInterface(const HalInterface& other) :
Yifan Hongf79b5542017-04-11 14:44:25 -07003174 mHidlSession(other.mHidlSession),
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003175 mRequestMetadataQueue(other.mRequestMetadataQueue),
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003176 mUseHalBufManager(other.mUseHalBufManager),
3177 mSupportOfflineProcessing(other.mSupportOfflineProcessing) {}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003178
3179bool Camera3Device::HalInterface::valid() {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003180 return (mHidlSession != nullptr);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003181}
3182
3183void Camera3Device::HalInterface::clear() {
Shuzhen Wang83bff122020-11-20 15:51:39 -08003184 mHidlSession_3_7.clear();
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003185 mHidlSession_3_6.clear();
Emilian Peev644a3e12018-11-23 13:52:39 +00003186 mHidlSession_3_5.clear();
Emilian Peev9e740b02018-01-30 18:28:03 +00003187 mHidlSession_3_4.clear();
3188 mHidlSession_3_3.clear();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003189 mHidlSession.clear();
3190}
3191
3192status_t Camera3Device::HalInterface::constructDefaultRequestSettings(
Emilian Peevf4816702020-04-03 15:44:51 -07003193 camera_request_template_t templateId,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003194 /*out*/ camera_metadata_t **requestTemplate) {
3195 ATRACE_NAME("CameraHal::constructDefaultRequestSettings");
3196 if (!valid()) return INVALID_OPERATION;
3197 status_t res = OK;
3198
Emilian Peev31abd0a2017-05-11 18:37:46 +01003199 common::V1_0::Status status;
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003200
3201 auto requestCallback = [&status, &requestTemplate]
Emilian Peev31abd0a2017-05-11 18:37:46 +01003202 (common::V1_0::Status s, const device::V3_2::CameraMetadata& request) {
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003203 status = s;
3204 if (status == common::V1_0::Status::OK) {
3205 const camera_metadata *r =
3206 reinterpret_cast<const camera_metadata_t*>(request.data());
3207 size_t expectedSize = request.size();
3208 int ret = validate_camera_metadata_structure(r, &expectedSize);
3209 if (ret == OK || ret == CAMERA_METADATA_VALIDATION_SHIFTED) {
3210 *requestTemplate = clone_camera_metadata(r);
3211 if (*requestTemplate == nullptr) {
3212 ALOGE("%s: Unable to clone camera metadata received from HAL",
3213 __FUNCTION__);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003214 status = common::V1_0::Status::INTERNAL_ERROR;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003215 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003216 } else {
3217 ALOGE("%s: Malformed camera metadata received from HAL", __FUNCTION__);
3218 status = common::V1_0::Status::INTERNAL_ERROR;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003219 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003220 }
3221 };
3222 hardware::Return<void> err;
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003223 RequestTemplate id;
3224 switch (templateId) {
Emilian Peevf4816702020-04-03 15:44:51 -07003225 case CAMERA_TEMPLATE_PREVIEW:
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003226 id = RequestTemplate::PREVIEW;
3227 break;
Emilian Peevf4816702020-04-03 15:44:51 -07003228 case CAMERA_TEMPLATE_STILL_CAPTURE:
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003229 id = RequestTemplate::STILL_CAPTURE;
3230 break;
Emilian Peevf4816702020-04-03 15:44:51 -07003231 case CAMERA_TEMPLATE_VIDEO_RECORD:
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003232 id = RequestTemplate::VIDEO_RECORD;
3233 break;
Emilian Peevf4816702020-04-03 15:44:51 -07003234 case CAMERA_TEMPLATE_VIDEO_SNAPSHOT:
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003235 id = RequestTemplate::VIDEO_SNAPSHOT;
3236 break;
Emilian Peevf4816702020-04-03 15:44:51 -07003237 case CAMERA_TEMPLATE_ZERO_SHUTTER_LAG:
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003238 id = RequestTemplate::ZERO_SHUTTER_LAG;
3239 break;
Emilian Peevf4816702020-04-03 15:44:51 -07003240 case CAMERA_TEMPLATE_MANUAL:
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003241 id = RequestTemplate::MANUAL;
3242 break;
3243 default:
3244 // Unknown template ID, or this HAL is too old to support it
3245 return BAD_VALUE;
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003246 }
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003247 err = mHidlSession->constructDefaultRequestSettings(id, requestCallback);
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003248
Emilian Peev31abd0a2017-05-11 18:37:46 +01003249 if (!err.isOk()) {
3250 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3251 res = DEAD_OBJECT;
3252 } else {
3253 res = CameraProviderManager::mapToStatusT(status);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003254 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003255
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003256 return res;
3257}
3258
Emilian Peev4ec17882019-01-24 17:16:58 -08003259bool Camera3Device::HalInterface::isReconfigurationRequired(CameraMetadata& oldSessionParams,
3260 CameraMetadata& newSessionParams) {
3261 // We do reconfiguration by default;
3262 bool ret = true;
3263 if ((mHidlSession_3_5 != nullptr) && mIsReconfigurationQuerySupported) {
3264 android::hardware::hidl_vec<uint8_t> oldParams, newParams;
3265 camera_metadata_t* oldSessioMeta = const_cast<camera_metadata_t*>(
3266 oldSessionParams.getAndLock());
3267 camera_metadata_t* newSessioMeta = const_cast<camera_metadata_t*>(
3268 newSessionParams.getAndLock());
3269 oldParams.setToExternal(reinterpret_cast<uint8_t*>(oldSessioMeta),
3270 get_camera_metadata_size(oldSessioMeta));
3271 newParams.setToExternal(reinterpret_cast<uint8_t*>(newSessioMeta),
3272 get_camera_metadata_size(newSessioMeta));
3273 hardware::camera::common::V1_0::Status callStatus;
3274 bool required;
3275 auto hidlCb = [&callStatus, &required] (hardware::camera::common::V1_0::Status s,
3276 bool requiredFlag) {
3277 callStatus = s;
3278 required = requiredFlag;
3279 };
3280 auto err = mHidlSession_3_5->isReconfigurationRequired(oldParams, newParams, hidlCb);
3281 oldSessionParams.unlock(oldSessioMeta);
3282 newSessionParams.unlock(newSessioMeta);
3283 if (err.isOk()) {
3284 switch (callStatus) {
3285 case hardware::camera::common::V1_0::Status::OK:
3286 ret = required;
3287 break;
3288 case hardware::camera::common::V1_0::Status::METHOD_NOT_SUPPORTED:
3289 mIsReconfigurationQuerySupported = false;
3290 ret = true;
3291 break;
3292 default:
3293 ALOGV("%s: Reconfiguration query failed: %d", __FUNCTION__, callStatus);
3294 ret = true;
3295 }
3296 } else {
3297 ALOGE("%s: Unexpected binder error: %s", __FUNCTION__, err.description().c_str());
3298 ret = true;
3299 }
3300 }
3301
3302 return ret;
3303}
3304
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003305status_t Camera3Device::HalInterface::configureStreams(const camera_metadata_t *sessionParams,
Emilian Peevf4816702020-04-03 15:44:51 -07003306 camera_stream_configuration *config, const std::vector<uint32_t>& bufferSizes) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003307 ATRACE_NAME("CameraHal::configureStreams");
3308 if (!valid()) return INVALID_OPERATION;
3309 status_t res = OK;
3310
Shuzhen Wang83bff122020-11-20 15:51:39 -08003311 if (config->input_is_multi_resolution && mHidlSession_3_7 == nullptr) {
3312 ALOGE("%s: Camera device doesn't support multi-resolution input stream", __FUNCTION__);
3313 return BAD_VALUE;
3314 }
3315
Emilian Peev31abd0a2017-05-11 18:37:46 +01003316 // Convert stream config to HIDL
3317 std::set<int> activeStreams;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003318 device::V3_2::StreamConfiguration requestedConfiguration3_2;
3319 device::V3_4::StreamConfiguration requestedConfiguration3_4;
Shuzhen Wang83bff122020-11-20 15:51:39 -08003320 device::V3_7::StreamConfiguration requestedConfiguration3_7;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003321 requestedConfiguration3_2.streams.resize(config->num_streams);
3322 requestedConfiguration3_4.streams.resize(config->num_streams);
Shuzhen Wang83bff122020-11-20 15:51:39 -08003323 requestedConfiguration3_7.streams.resize(config->num_streams);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003324 for (size_t i = 0; i < config->num_streams; i++) {
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003325 device::V3_2::Stream &dst3_2 = requestedConfiguration3_2.streams[i];
3326 device::V3_4::Stream &dst3_4 = requestedConfiguration3_4.streams[i];
Shuzhen Wang83bff122020-11-20 15:51:39 -08003327 device::V3_7::Stream &dst3_7 = requestedConfiguration3_7.streams[i];
Emilian Peevf4816702020-04-03 15:44:51 -07003328 camera3::camera_stream_t *src = config->streams[i];
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003329
Emilian Peev31abd0a2017-05-11 18:37:46 +01003330 Camera3Stream* cam3stream = Camera3Stream::cast(src);
3331 cam3stream->setBufferFreedListener(this);
3332 int streamId = cam3stream->getId();
3333 StreamType streamType;
3334 switch (src->stream_type) {
Emilian Peevf4816702020-04-03 15:44:51 -07003335 case CAMERA_STREAM_OUTPUT:
Emilian Peev31abd0a2017-05-11 18:37:46 +01003336 streamType = StreamType::OUTPUT;
3337 break;
Emilian Peevf4816702020-04-03 15:44:51 -07003338 case CAMERA_STREAM_INPUT:
Emilian Peev31abd0a2017-05-11 18:37:46 +01003339 streamType = StreamType::INPUT;
3340 break;
3341 default:
3342 ALOGE("%s: Stream %d: Unsupported stream type %d",
3343 __FUNCTION__, streamId, config->streams[i]->stream_type);
3344 return BAD_VALUE;
3345 }
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003346 dst3_2.id = streamId;
3347 dst3_2.streamType = streamType;
3348 dst3_2.width = src->width;
3349 dst3_2.height = src->height;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003350 dst3_2.usage = mapToConsumerUsage(cam3stream->getUsage());
Emilian Peevf4816702020-04-03 15:44:51 -07003351 dst3_2.rotation = mapToStreamRotation((camera_stream_rotation_t) src->rotation);
Shuzhen Wang92653952019-05-07 15:11:43 -07003352 // For HidlSession version 3.5 or newer, the format and dataSpace sent
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08003353 // to HAL are original, not the overridden ones.
Shuzhen Wang92653952019-05-07 15:11:43 -07003354 if (mHidlSession_3_5 != nullptr) {
3355 dst3_2.format = mapToPixelFormat(cam3stream->isFormatOverridden() ?
3356 cam3stream->getOriginalFormat() : src->format);
3357 dst3_2.dataSpace = mapToHidlDataspace(cam3stream->isDataSpaceOverridden() ?
3358 cam3stream->getOriginalDataSpace() : src->data_space);
3359 } else {
3360 dst3_2.format = mapToPixelFormat(src->format);
3361 dst3_2.dataSpace = mapToHidlDataspace(src->data_space);
3362 }
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003363 dst3_4.v3_2 = dst3_2;
Emilian Peev192ee832018-01-31 14:46:47 +00003364 dst3_4.bufferSize = bufferSizes[i];
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003365 if (src->physical_camera_id != nullptr) {
3366 dst3_4.physicalCameraId = src->physical_camera_id;
3367 }
Shuzhen Wang83bff122020-11-20 15:51:39 -08003368 dst3_7.v3_4 = dst3_4;
3369 dst3_7.groupId = cam3stream->getHalStreamGroupId();
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08003370 dst3_7.sensorPixelModesUsed.resize(src->sensor_pixel_modes_used.size());
3371 size_t j = 0;
3372 for (int mode : src->sensor_pixel_modes_used) {
3373 dst3_7.sensorPixelModesUsed[j++] =
3374 static_cast<CameraMetadataEnumAndroidSensorPixelMode>(mode);
3375 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003376 activeStreams.insert(streamId);
3377 // Create Buffer ID map if necessary
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003378 mBufferRecords.tryCreateBufferCache(streamId);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003379 }
3380 // remove BufferIdMap for deleted streams
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003381 mBufferRecords.removeInactiveBufferCaches(activeStreams);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003382
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003383 StreamConfigurationMode operationMode;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003384 res = mapToStreamConfigurationMode(
Emilian Peevf4816702020-04-03 15:44:51 -07003385 (camera_stream_configuration_mode_t) config->operation_mode,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003386 /*out*/ &operationMode);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003387 if (res != OK) {
3388 return res;
3389 }
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003390 requestedConfiguration3_2.operationMode = operationMode;
3391 requestedConfiguration3_4.operationMode = operationMode;
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08003392 requestedConfiguration3_7.operationMode = operationMode;
3393 size_t sessionParamSize = get_camera_metadata_size(sessionParams);
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003394 requestedConfiguration3_4.sessionParams.setToExternal(
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003395 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(sessionParams)),
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08003396 sessionParamSize);
Shuzhen Wang83bff122020-11-20 15:51:39 -08003397 requestedConfiguration3_7.operationMode = operationMode;
3398 requestedConfiguration3_7.sessionParams.setToExternal(
3399 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(sessionParams)),
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08003400 sessionParamSize);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003401
Emilian Peev31abd0a2017-05-11 18:37:46 +01003402 // Invoke configureStreams
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003403 device::V3_3::HalStreamConfiguration finalConfiguration;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003404 device::V3_4::HalStreamConfiguration finalConfiguration3_4;
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003405 device::V3_6::HalStreamConfiguration finalConfiguration3_6;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003406 common::V1_0::Status status;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003407
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003408 auto configStream34Cb = [&status, &finalConfiguration3_4]
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003409 (common::V1_0::Status s, const device::V3_4::HalStreamConfiguration& halConfiguration) {
3410 finalConfiguration3_4 = halConfiguration;
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003411 status = s;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003412 };
3413
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003414 auto configStream36Cb = [&status, &finalConfiguration3_6]
3415 (common::V1_0::Status s, const device::V3_6::HalStreamConfiguration& halConfiguration) {
3416 finalConfiguration3_6 = halConfiguration;
3417 status = s;
3418 };
3419
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003420 auto postprocConfigStream34 = [&finalConfiguration, &finalConfiguration3_4]
3421 (hardware::Return<void>& err) -> status_t {
3422 if (!err.isOk()) {
3423 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3424 return DEAD_OBJECT;
3425 }
3426 finalConfiguration.streams.resize(finalConfiguration3_4.streams.size());
3427 for (size_t i = 0; i < finalConfiguration3_4.streams.size(); i++) {
3428 finalConfiguration.streams[i] = finalConfiguration3_4.streams[i].v3_3;
3429 }
3430 return OK;
3431 };
3432
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003433 auto postprocConfigStream36 = [&finalConfiguration, &finalConfiguration3_6]
3434 (hardware::Return<void>& err) -> status_t {
3435 if (!err.isOk()) {
3436 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3437 return DEAD_OBJECT;
3438 }
3439 finalConfiguration.streams.resize(finalConfiguration3_6.streams.size());
3440 for (size_t i = 0; i < finalConfiguration3_6.streams.size(); i++) {
3441 finalConfiguration.streams[i] = finalConfiguration3_6.streams[i].v3_4.v3_3;
3442 }
3443 return OK;
3444 };
3445
Shuzhen Wang92653952019-05-07 15:11:43 -07003446 // See which version of HAL we have
Shuzhen Wang83bff122020-11-20 15:51:39 -08003447 if (mHidlSession_3_7 != nullptr) {
3448 ALOGV("%s: v3.7 device found", __FUNCTION__);
3449 requestedConfiguration3_7.streamConfigCounter = mNextStreamConfigCounter++;
3450 requestedConfiguration3_7.multiResolutionInputImage = config->input_is_multi_resolution;
3451 auto err = mHidlSession_3_7->configureStreams_3_7(
3452 requestedConfiguration3_7, configStream36Cb);
3453 res = postprocConfigStream36(err);
3454 if (res != OK) {
3455 return res;
3456 }
3457 } else if (mHidlSession_3_6 != nullptr) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003458 ALOGV("%s: v3.6 device found", __FUNCTION__);
3459 device::V3_5::StreamConfiguration requestedConfiguration3_5;
3460 requestedConfiguration3_5.v3_4 = requestedConfiguration3_4;
3461 requestedConfiguration3_5.streamConfigCounter = mNextStreamConfigCounter++;
3462 auto err = mHidlSession_3_6->configureStreams_3_6(
3463 requestedConfiguration3_5, configStream36Cb);
3464 res = postprocConfigStream36(err);
3465 if (res != OK) {
3466 return res;
3467 }
3468 } else if (mHidlSession_3_5 != nullptr) {
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003469 ALOGV("%s: v3.5 device found", __FUNCTION__);
3470 device::V3_5::StreamConfiguration requestedConfiguration3_5;
3471 requestedConfiguration3_5.v3_4 = requestedConfiguration3_4;
3472 requestedConfiguration3_5.streamConfigCounter = mNextStreamConfigCounter++;
3473 auto err = mHidlSession_3_5->configureStreams_3_5(
3474 requestedConfiguration3_5, configStream34Cb);
3475 res = postprocConfigStream34(err);
3476 if (res != OK) {
3477 return res;
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003478 }
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003479 } else if (mHidlSession_3_4 != nullptr) {
3480 // We do; use v3.4 for the call
3481 ALOGV("%s: v3.4 device found", __FUNCTION__);
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003482 auto err = mHidlSession_3_4->configureStreams_3_4(
3483 requestedConfiguration3_4, configStream34Cb);
3484 res = postprocConfigStream34(err);
3485 if (res != OK) {
3486 return res;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003487 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003488 } else if (mHidlSession_3_3 != nullptr) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003489 // We do; use v3.3 for the call
3490 ALOGV("%s: v3.3 device found", __FUNCTION__);
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003491 auto err = mHidlSession_3_3->configureStreams_3_3(requestedConfiguration3_2,
Emilian Peev31abd0a2017-05-11 18:37:46 +01003492 [&status, &finalConfiguration]
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003493 (common::V1_0::Status s, const device::V3_3::HalStreamConfiguration& halConfiguration) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003494 finalConfiguration = halConfiguration;
3495 status = s;
3496 });
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003497 if (!err.isOk()) {
3498 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3499 return DEAD_OBJECT;
3500 }
3501 } else {
3502 // We don't; use v3.2 call and construct a v3.3 HalStreamConfiguration
3503 ALOGV("%s: v3.2 device found", __FUNCTION__);
3504 HalStreamConfiguration finalConfiguration_3_2;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003505 auto err = mHidlSession->configureStreams(requestedConfiguration3_2,
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003506 [&status, &finalConfiguration_3_2]
3507 (common::V1_0::Status s, const HalStreamConfiguration& halConfiguration) {
3508 finalConfiguration_3_2 = halConfiguration;
3509 status = s;
3510 });
3511 if (!err.isOk()) {
3512 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3513 return DEAD_OBJECT;
3514 }
3515 finalConfiguration.streams.resize(finalConfiguration_3_2.streams.size());
3516 for (size_t i = 0; i < finalConfiguration_3_2.streams.size(); i++) {
3517 finalConfiguration.streams[i].v3_2 = finalConfiguration_3_2.streams[i];
3518 finalConfiguration.streams[i].overrideDataSpace =
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003519 requestedConfiguration3_2.streams[i].dataSpace;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003520 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003521 }
3522
3523 if (status != common::V1_0::Status::OK ) {
3524 return CameraProviderManager::mapToStatusT(status);
3525 }
3526
3527 // And convert output stream configuration from HIDL
3528
3529 for (size_t i = 0; i < config->num_streams; i++) {
Emilian Peevf4816702020-04-03 15:44:51 -07003530 camera3::camera_stream_t *dst = config->streams[i];
Emilian Peev31abd0a2017-05-11 18:37:46 +01003531 int streamId = Camera3Stream::cast(dst)->getId();
3532
3533 // Start scan at i, with the assumption that the stream order matches
3534 size_t realIdx = i;
3535 bool found = false;
Eino-Ville Talvala370875f2019-04-12 12:40:27 -07003536 size_t halStreamCount = finalConfiguration.streams.size();
3537 for (size_t idx = 0; idx < halStreamCount; idx++) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003538 if (finalConfiguration.streams[realIdx].v3_2.id == streamId) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003539 found = true;
3540 break;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003541 }
Eino-Ville Talvala370875f2019-04-12 12:40:27 -07003542 realIdx = (realIdx >= halStreamCount - 1) ? 0 : realIdx + 1;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003543 }
3544 if (!found) {
3545 ALOGE("%s: Stream %d not found in stream configuration response from HAL",
3546 __FUNCTION__, streamId);
3547 return INVALID_OPERATION;
3548 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003549 device::V3_3::HalStream &src = finalConfiguration.streams[realIdx];
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003550 device::V3_6::HalStream &src_36 = finalConfiguration3_6.streams[realIdx];
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003551
Emilian Peev710c1422017-08-30 11:19:38 +01003552 Camera3Stream* dstStream = Camera3Stream::cast(dst);
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003553 int overrideFormat = mapToFrameworkFormat(src.v3_2.overrideFormat);
3554 android_dataspace overrideDataSpace = mapToFrameworkDataspace(src.overrideDataSpace);
3555
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003556 if (mHidlSession_3_6 != nullptr) {
3557 dstStream->setOfflineProcessingSupport(src_36.supportOffline);
3558 }
3559
Yin-Chia Yeh90667662019-07-01 15:45:00 -07003560 if (dstStream->getOriginalFormat() != HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
Shuzhen Wang92653952019-05-07 15:11:43 -07003561 dstStream->setFormatOverride(false);
3562 dstStream->setDataSpaceOverride(false);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003563 if (dst->format != overrideFormat) {
3564 ALOGE("%s: Stream %d: Format override not allowed for format 0x%x", __FUNCTION__,
3565 streamId, dst->format);
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003566 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003567 if (dst->data_space != overrideDataSpace) {
3568 ALOGE("%s: Stream %d: DataSpace override not allowed for format 0x%x", __FUNCTION__,
3569 streamId, dst->format);
3570 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003571 } else {
Shuzhen Wang92653952019-05-07 15:11:43 -07003572 bool needFormatOverride =
3573 requestedConfiguration3_2.streams[i].format != src.v3_2.overrideFormat;
3574 bool needDataspaceOverride =
3575 requestedConfiguration3_2.streams[i].dataSpace != src.overrideDataSpace;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003576 // Override allowed with IMPLEMENTATION_DEFINED
Shuzhen Wang92653952019-05-07 15:11:43 -07003577 dstStream->setFormatOverride(needFormatOverride);
3578 dstStream->setDataSpaceOverride(needDataspaceOverride);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003579 dst->format = overrideFormat;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003580 dst->data_space = overrideDataSpace;
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003581 }
3582
Emilian Peevf4816702020-04-03 15:44:51 -07003583 if (dst->stream_type == CAMERA_STREAM_INPUT) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003584 if (src.v3_2.producerUsage != 0) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003585 ALOGE("%s: Stream %d: INPUT streams must have 0 for producer usage",
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003586 __FUNCTION__, streamId);
3587 return INVALID_OPERATION;
3588 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003589 dstStream->setUsage(
3590 mapConsumerToFrameworkUsage(src.v3_2.consumerUsage));
Emilian Peev31abd0a2017-05-11 18:37:46 +01003591 } else {
3592 // OUTPUT
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003593 if (src.v3_2.consumerUsage != 0) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003594 ALOGE("%s: Stream %d: OUTPUT streams must have 0 for consumer usage",
3595 __FUNCTION__, streamId);
3596 return INVALID_OPERATION;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003597 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003598 dstStream->setUsage(
3599 mapProducerToFrameworkUsage(src.v3_2.producerUsage));
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003600 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003601 dst->max_buffers = src.v3_2.maxBuffers;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003602 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003603
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003604 return res;
3605}
3606
Cliff Wuc2ad9c82021-04-21 00:58:58 +08003607status_t Camera3Device::HalInterface::configureInjectedStreams(
3608 const camera_metadata_t* sessionParams, camera_stream_configuration* config,
3609 const std::vector<uint32_t>& bufferSizes,
3610 const CameraMetadata& cameraCharacteristics) {
3611 ATRACE_NAME("InjectionCameraHal::configureStreams");
3612 if (!valid()) return INVALID_OPERATION;
3613 status_t res = OK;
3614
3615 if (config->input_is_multi_resolution) {
3616 ALOGE("%s: Injection camera device doesn't support multi-resolution input "
3617 "stream", __FUNCTION__);
3618 return BAD_VALUE;
3619 }
3620
3621 // Convert stream config to HIDL
3622 std::set<int> activeStreams;
3623 device::V3_2::StreamConfiguration requestedConfiguration3_2;
3624 device::V3_4::StreamConfiguration requestedConfiguration3_4;
3625 device::V3_7::StreamConfiguration requestedConfiguration3_7;
3626 requestedConfiguration3_2.streams.resize(config->num_streams);
3627 requestedConfiguration3_4.streams.resize(config->num_streams);
3628 requestedConfiguration3_7.streams.resize(config->num_streams);
3629 for (size_t i = 0; i < config->num_streams; i++) {
3630 device::V3_2::Stream& dst3_2 = requestedConfiguration3_2.streams[i];
3631 device::V3_4::Stream& dst3_4 = requestedConfiguration3_4.streams[i];
3632 device::V3_7::Stream& dst3_7 = requestedConfiguration3_7.streams[i];
3633 camera3::camera_stream_t* src = config->streams[i];
3634
3635 Camera3Stream* cam3stream = Camera3Stream::cast(src);
3636 cam3stream->setBufferFreedListener(this);
3637 int streamId = cam3stream->getId();
3638 StreamType streamType;
3639 switch (src->stream_type) {
3640 case CAMERA_STREAM_OUTPUT:
3641 streamType = StreamType::OUTPUT;
3642 break;
3643 case CAMERA_STREAM_INPUT:
3644 streamType = StreamType::INPUT;
3645 break;
3646 default:
3647 ALOGE("%s: Stream %d: Unsupported stream type %d", __FUNCTION__,
3648 streamId, config->streams[i]->stream_type);
3649 return BAD_VALUE;
3650 }
3651 dst3_2.id = streamId;
3652 dst3_2.streamType = streamType;
3653 dst3_2.width = src->width;
3654 dst3_2.height = src->height;
3655 dst3_2.usage = mapToConsumerUsage(cam3stream->getUsage());
3656 dst3_2.rotation =
3657 mapToStreamRotation((camera_stream_rotation_t)src->rotation);
3658 // For HidlSession version 3.5 or newer, the format and dataSpace sent
3659 // to HAL are original, not the overridden ones.
3660 if (mHidlSession_3_5 != nullptr) {
3661 dst3_2.format = mapToPixelFormat(cam3stream->isFormatOverridden()
3662 ? cam3stream->getOriginalFormat()
3663 : src->format);
3664 dst3_2.dataSpace =
3665 mapToHidlDataspace(cam3stream->isDataSpaceOverridden()
3666 ? cam3stream->getOriginalDataSpace()
3667 : src->data_space);
3668 } else {
3669 dst3_2.format = mapToPixelFormat(src->format);
3670 dst3_2.dataSpace = mapToHidlDataspace(src->data_space);
3671 }
3672 dst3_4.v3_2 = dst3_2;
3673 dst3_4.bufferSize = bufferSizes[i];
3674 if (src->physical_camera_id != nullptr) {
3675 dst3_4.physicalCameraId = src->physical_camera_id;
3676 }
3677 dst3_7.v3_4 = dst3_4;
3678 dst3_7.groupId = cam3stream->getHalStreamGroupId();
3679 dst3_7.sensorPixelModesUsed.resize(src->sensor_pixel_modes_used.size());
3680 size_t j = 0;
3681 for (int mode : src->sensor_pixel_modes_used) {
3682 dst3_7.sensorPixelModesUsed[j++] =
3683 static_cast<CameraMetadataEnumAndroidSensorPixelMode>(mode);
3684 }
3685 activeStreams.insert(streamId);
3686 // Create Buffer ID map if necessary
3687 mBufferRecords.tryCreateBufferCache(streamId);
3688 }
3689 // remove BufferIdMap for deleted streams
3690 mBufferRecords.removeInactiveBufferCaches(activeStreams);
3691
3692 StreamConfigurationMode operationMode;
3693 res = mapToStreamConfigurationMode(
3694 (camera_stream_configuration_mode_t)config->operation_mode,
3695 /*out*/ &operationMode);
3696 if (res != OK) {
3697 return res;
3698 }
3699 requestedConfiguration3_7.operationMode = operationMode;
3700 size_t sessionParamSize = get_camera_metadata_size(sessionParams);
3701 requestedConfiguration3_7.operationMode = operationMode;
3702 requestedConfiguration3_7.sessionParams.setToExternal(
3703 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(sessionParams)),
3704 sessionParamSize);
3705
3706 // See which version of HAL we have
3707 if (mHidlSession_3_7 != nullptr) {
3708 requestedConfiguration3_7.streamConfigCounter = mNextStreamConfigCounter++;
3709 requestedConfiguration3_7.multiResolutionInputImage =
3710 config->input_is_multi_resolution;
3711
3712 const camera_metadata_t* rawMetadata = cameraCharacteristics.getAndLock();
3713 ::android::hardware::camera::device::V3_2::CameraMetadata hidlChars = {};
3714 hidlChars.setToExternal(
3715 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(rawMetadata)),
3716 get_camera_metadata_size(rawMetadata));
3717 cameraCharacteristics.unlock(rawMetadata);
3718
3719 sp<hardware::camera::device::V3_7::ICameraInjectionSession>
3720 hidlInjectionSession_3_7;
3721 auto castInjectionResult_3_7 =
3722 device::V3_7::ICameraInjectionSession::castFrom(mHidlSession_3_7);
3723 if (castInjectionResult_3_7.isOk()) {
3724 hidlInjectionSession_3_7 = castInjectionResult_3_7;
3725 } else {
3726 ALOGE("%s: Transaction error: %s", __FUNCTION__,
3727 castInjectionResult_3_7.description().c_str());
3728 return DEAD_OBJECT;
3729 }
3730
3731 auto err = hidlInjectionSession_3_7->configureInjectionStreams(
3732 requestedConfiguration3_7, hidlChars);
3733 if (!err.isOk()) {
3734 ALOGE("%s: Transaction error: %s", __FUNCTION__,
3735 err.description().c_str());
3736 return DEAD_OBJECT;
3737 }
3738 } else {
3739 ALOGE("%s: mHidlSession_3_7 does not exist, the lowest version of injection "
3740 "session is 3.7", __FUNCTION__);
3741 return DEAD_OBJECT;
3742 }
3743
3744 return res;
3745}
3746
Emilian Peevf4816702020-04-03 15:44:51 -07003747status_t Camera3Device::HalInterface::wrapAsHidlRequest(camera_capture_request_t* request,
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003748 /*out*/device::V3_2::CaptureRequest* captureRequest,
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003749 /*out*/std::vector<native_handle_t*>* handlesCreated,
3750 /*out*/std::vector<std::pair<int32_t, int32_t>>* inflightBuffers) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003751 ATRACE_CALL();
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003752 if (captureRequest == nullptr || handlesCreated == nullptr || inflightBuffers == nullptr) {
3753 ALOGE("%s: captureRequest (%p), handlesCreated (%p), and inflightBuffers(%p) "
3754 "must not be null", __FUNCTION__, captureRequest, handlesCreated, inflightBuffers);
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003755 return BAD_VALUE;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003756 }
3757
3758 captureRequest->frameNumber = request->frame_number;
Yifan Hongf79b5542017-04-11 14:44:25 -07003759
3760 captureRequest->fmqSettingsSize = 0;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003761
3762 {
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003763 if (request->input_buffer != nullptr) {
3764 int32_t streamId = Camera3Stream::cast(request->input_buffer->stream)->getId();
3765 buffer_handle_t buf = *(request->input_buffer->buffer);
3766 auto pair = getBufferId(buf, streamId);
3767 bool isNewBuffer = pair.first;
3768 uint64_t bufferId = pair.second;
3769 captureRequest->inputBuffer.streamId = streamId;
3770 captureRequest->inputBuffer.bufferId = bufferId;
3771 captureRequest->inputBuffer.buffer = (isNewBuffer) ? buf : nullptr;
3772 captureRequest->inputBuffer.status = BufferStatus::OK;
3773 native_handle_t *acquireFence = nullptr;
3774 if (request->input_buffer->acquire_fence != -1) {
3775 acquireFence = native_handle_create(1,0);
3776 acquireFence->data[0] = request->input_buffer->acquire_fence;
3777 handlesCreated->push_back(acquireFence);
3778 }
3779 captureRequest->inputBuffer.acquireFence = acquireFence;
3780 captureRequest->inputBuffer.releaseFence = nullptr;
3781
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003782 mBufferRecords.pushInflightBuffer(captureRequest->frameNumber, streamId,
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003783 request->input_buffer->buffer);
3784 inflightBuffers->push_back(std::make_pair(captureRequest->frameNumber, streamId));
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003785 } else {
3786 captureRequest->inputBuffer.streamId = -1;
3787 captureRequest->inputBuffer.bufferId = BUFFER_ID_NO_BUFFER;
3788 }
3789
3790 captureRequest->outputBuffers.resize(request->num_output_buffers);
3791 for (size_t i = 0; i < request->num_output_buffers; i++) {
Emilian Peevf4816702020-04-03 15:44:51 -07003792 const camera_stream_buffer_t *src = request->output_buffers + i;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003793 StreamBuffer &dst = captureRequest->outputBuffers[i];
3794 int32_t streamId = Camera3Stream::cast(src->stream)->getId();
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003795 if (src->buffer != nullptr) {
3796 buffer_handle_t buf = *(src->buffer);
3797 auto pair = getBufferId(buf, streamId);
3798 bool isNewBuffer = pair.first;
3799 dst.bufferId = pair.second;
3800 dst.buffer = isNewBuffer ? buf : nullptr;
3801 native_handle_t *acquireFence = nullptr;
3802 if (src->acquire_fence != -1) {
3803 acquireFence = native_handle_create(1,0);
3804 acquireFence->data[0] = src->acquire_fence;
3805 handlesCreated->push_back(acquireFence);
3806 }
3807 dst.acquireFence = acquireFence;
3808 } else if (mUseHalBufManager) {
3809 // HAL buffer management path
3810 dst.bufferId = BUFFER_ID_NO_BUFFER;
3811 dst.buffer = nullptr;
3812 dst.acquireFence = nullptr;
3813 } else {
3814 ALOGE("%s: cannot send a null buffer in capture request!", __FUNCTION__);
3815 return BAD_VALUE;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003816 }
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003817 dst.streamId = streamId;
3818 dst.status = BufferStatus::OK;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003819 dst.releaseFence = nullptr;
3820
Yin-Chia Yeh5f840f82019-03-05 11:59:04 -08003821 // Output buffers are empty when using HAL buffer manager
3822 if (!mUseHalBufManager) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003823 mBufferRecords.pushInflightBuffer(
3824 captureRequest->frameNumber, streamId, src->buffer);
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003825 inflightBuffers->push_back(std::make_pair(captureRequest->frameNumber, streamId));
Yin-Chia Yeh5f840f82019-03-05 11:59:04 -08003826 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003827 }
3828 }
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003829 return OK;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003830}
3831
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003832void Camera3Device::HalInterface::cleanupNativeHandles(
3833 std::vector<native_handle_t*> *handles, bool closeFd) {
3834 if (handles == nullptr) {
3835 return;
3836 }
3837 if (closeFd) {
3838 for (auto& handle : *handles) {
3839 native_handle_close(handle);
3840 }
3841 }
3842 for (auto& handle : *handles) {
3843 native_handle_delete(handle);
3844 }
3845 handles->clear();
3846 return;
3847}
3848
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003849status_t Camera3Device::HalInterface::processBatchCaptureRequests(
Emilian Peevf4816702020-04-03 15:44:51 -07003850 std::vector<camera_capture_request_t*>& requests,/*out*/uint32_t* numRequestProcessed) {
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003851 ATRACE_NAME("CameraHal::processBatchCaptureRequests");
3852 if (!valid()) return INVALID_OPERATION;
3853
Emilian Peevaebbe412018-01-15 13:53:24 +00003854 sp<device::V3_4::ICameraDeviceSession> hidlSession_3_4;
Shuzhen Wang83bff122020-11-20 15:51:39 -08003855 sp<device::V3_7::ICameraDeviceSession> hidlSession_3_7;
3856 auto castResult_3_7 = device::V3_7::ICameraDeviceSession::castFrom(mHidlSession);
3857 if (castResult_3_7.isOk()) {
3858 hidlSession_3_7 = castResult_3_7;
3859 }
Emilian Peevaebbe412018-01-15 13:53:24 +00003860 auto castResult_3_4 = device::V3_4::ICameraDeviceSession::castFrom(mHidlSession);
3861 if (castResult_3_4.isOk()) {
3862 hidlSession_3_4 = castResult_3_4;
3863 }
3864
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003865 hardware::hidl_vec<device::V3_2::CaptureRequest> captureRequests;
Emilian Peevaebbe412018-01-15 13:53:24 +00003866 hardware::hidl_vec<device::V3_4::CaptureRequest> captureRequests_3_4;
Shuzhen Wang83bff122020-11-20 15:51:39 -08003867 hardware::hidl_vec<device::V3_7::CaptureRequest> captureRequests_3_7;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003868 size_t batchSize = requests.size();
Shuzhen Wang83bff122020-11-20 15:51:39 -08003869 if (hidlSession_3_7 != nullptr) {
3870 captureRequests_3_7.resize(batchSize);
3871 } else if (hidlSession_3_4 != nullptr) {
Emilian Peevaebbe412018-01-15 13:53:24 +00003872 captureRequests_3_4.resize(batchSize);
3873 } else {
3874 captureRequests.resize(batchSize);
3875 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003876 std::vector<native_handle_t*> handlesCreated;
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003877 std::vector<std::pair<int32_t, int32_t>> inflightBuffers;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003878
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003879 status_t res = OK;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003880 for (size_t i = 0; i < batchSize; i++) {
Shuzhen Wang83bff122020-11-20 15:51:39 -08003881 if (hidlSession_3_7 != nullptr) {
3882 res = wrapAsHidlRequest(requests[i], /*out*/&captureRequests_3_7[i].v3_4.v3_2,
3883 /*out*/&handlesCreated, /*out*/&inflightBuffers);
3884 } else if (hidlSession_3_4 != nullptr) {
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003885 res = wrapAsHidlRequest(requests[i], /*out*/&captureRequests_3_4[i].v3_2,
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003886 /*out*/&handlesCreated, /*out*/&inflightBuffers);
Emilian Peevaebbe412018-01-15 13:53:24 +00003887 } else {
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003888 res = wrapAsHidlRequest(requests[i], /*out*/&captureRequests[i],
3889 /*out*/&handlesCreated, /*out*/&inflightBuffers);
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003890 }
3891 if (res != OK) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003892 mBufferRecords.popInflightBuffers(inflightBuffers);
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003893 cleanupNativeHandles(&handlesCreated);
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003894 return res;
Emilian Peevaebbe412018-01-15 13:53:24 +00003895 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003896 }
3897
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003898 std::vector<device::V3_2::BufferCache> cachesToRemove;
3899 {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003900 std::lock_guard<std::mutex> lock(mFreedBuffersLock);
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003901 for (auto& pair : mFreedBuffers) {
3902 // The stream might have been removed since onBufferFreed
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003903 if (mBufferRecords.isStreamCached(pair.first)) {
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003904 cachesToRemove.push_back({pair.first, pair.second});
3905 }
3906 }
3907 mFreedBuffers.clear();
3908 }
3909
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003910 common::V1_0::Status status = common::V1_0::Status::INTERNAL_ERROR;
3911 *numRequestProcessed = 0;
Yifan Hongf79b5542017-04-11 14:44:25 -07003912
3913 // Write metadata to FMQ.
3914 for (size_t i = 0; i < batchSize; i++) {
Emilian Peevf4816702020-04-03 15:44:51 -07003915 camera_capture_request_t* request = requests[i];
Emilian Peevaebbe412018-01-15 13:53:24 +00003916 device::V3_2::CaptureRequest* captureRequest;
Shuzhen Wang83bff122020-11-20 15:51:39 -08003917 if (hidlSession_3_7 != nullptr) {
3918 captureRequest = &captureRequests_3_7[i].v3_4.v3_2;
3919 } else if (hidlSession_3_4 != nullptr) {
Emilian Peevaebbe412018-01-15 13:53:24 +00003920 captureRequest = &captureRequests_3_4[i].v3_2;
3921 } else {
3922 captureRequest = &captureRequests[i];
3923 }
Yifan Hongf79b5542017-04-11 14:44:25 -07003924
3925 if (request->settings != nullptr) {
3926 size_t settingsSize = get_camera_metadata_size(request->settings);
3927 if (mRequestMetadataQueue != nullptr && mRequestMetadataQueue->write(
3928 reinterpret_cast<const uint8_t*>(request->settings), settingsSize)) {
3929 captureRequest->settings.resize(0);
3930 captureRequest->fmqSettingsSize = settingsSize;
3931 } else {
3932 if (mRequestMetadataQueue != nullptr) {
3933 ALOGW("%s: couldn't utilize fmq, fallback to hwbinder", __FUNCTION__);
3934 }
3935 captureRequest->settings.setToExternal(
3936 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(request->settings)),
3937 get_camera_metadata_size(request->settings));
3938 captureRequest->fmqSettingsSize = 0u;
3939 }
3940 } else {
3941 // A null request settings maps to a size-0 CameraMetadata
3942 captureRequest->settings.resize(0);
3943 captureRequest->fmqSettingsSize = 0u;
3944 }
Emilian Peevaebbe412018-01-15 13:53:24 +00003945
Shuzhen Wang83bff122020-11-20 15:51:39 -08003946 // hidl session 3.7 specific handling.
3947 if (hidlSession_3_7 != nullptr) {
3948 captureRequests_3_7[i].inputWidth = request->input_width;
3949 captureRequests_3_7[i].inputHeight = request->input_height;
3950 }
3951
3952 // hidl session 3.7 and 3.4 specific handling.
3953 if (hidlSession_3_7 != nullptr || hidlSession_3_4 != nullptr) {
3954 hardware::hidl_vec<device::V3_4::PhysicalCameraSetting>& physicalCameraSettings =
3955 (hidlSession_3_7 != nullptr) ?
3956 captureRequests_3_7[i].v3_4.physicalCameraSettings :
3957 captureRequests_3_4[i].physicalCameraSettings;
3958 physicalCameraSettings.resize(request->num_physcam_settings);
Emilian Peevaebbe412018-01-15 13:53:24 +00003959 for (size_t j = 0; j < request->num_physcam_settings; j++) {
Emilian Peev00420d22018-02-05 21:33:13 +00003960 if (request->physcam_settings != nullptr) {
3961 size_t settingsSize = get_camera_metadata_size(request->physcam_settings[j]);
3962 if (mRequestMetadataQueue != nullptr && mRequestMetadataQueue->write(
3963 reinterpret_cast<const uint8_t*>(request->physcam_settings[j]),
3964 settingsSize)) {
Shuzhen Wang83bff122020-11-20 15:51:39 -08003965 physicalCameraSettings[j].settings.resize(0);
3966 physicalCameraSettings[j].fmqSettingsSize = settingsSize;
Emilian Peev00420d22018-02-05 21:33:13 +00003967 } else {
3968 if (mRequestMetadataQueue != nullptr) {
3969 ALOGW("%s: couldn't utilize fmq, fallback to hwbinder", __FUNCTION__);
3970 }
Shuzhen Wang83bff122020-11-20 15:51:39 -08003971 physicalCameraSettings[j].settings.setToExternal(
Emilian Peev00420d22018-02-05 21:33:13 +00003972 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(
3973 request->physcam_settings[j])),
3974 get_camera_metadata_size(request->physcam_settings[j]));
Shuzhen Wang83bff122020-11-20 15:51:39 -08003975 physicalCameraSettings[j].fmqSettingsSize = 0u;
Emilian Peevaebbe412018-01-15 13:53:24 +00003976 }
Emilian Peev00420d22018-02-05 21:33:13 +00003977 } else {
Yin-Chia Yeha2849702021-03-10 10:11:33 -08003978 physicalCameraSettings[j].fmqSettingsSize = 0u;
3979 physicalCameraSettings[j].settings.resize(0);
Emilian Peevaebbe412018-01-15 13:53:24 +00003980 }
Shuzhen Wang83bff122020-11-20 15:51:39 -08003981 physicalCameraSettings[j].physicalCameraId = request->physcam_id[j];
Emilian Peevaebbe412018-01-15 13:53:24 +00003982 }
3983 }
Yifan Hongf79b5542017-04-11 14:44:25 -07003984 }
Emilian Peevaebbe412018-01-15 13:53:24 +00003985
3986 hardware::details::return_status err;
Jayant Chowdharyc8d581e2018-07-16 14:46:23 -07003987 auto resultCallback =
3988 [&status, &numRequestProcessed] (auto s, uint32_t n) {
3989 status = s;
3990 *numRequestProcessed = n;
3991 };
Shuzhen Wang83bff122020-11-20 15:51:39 -08003992 if (hidlSession_3_7 != nullptr) {
3993 err = hidlSession_3_7->processCaptureRequest_3_7(captureRequests_3_7, cachesToRemove,
3994 resultCallback);
3995 } else if (hidlSession_3_4 != nullptr) {
Emilian Peevaebbe412018-01-15 13:53:24 +00003996 err = hidlSession_3_4->processCaptureRequest_3_4(captureRequests_3_4, cachesToRemove,
Jayant Chowdharyc8d581e2018-07-16 14:46:23 -07003997 resultCallback);
Emilian Peevaebbe412018-01-15 13:53:24 +00003998 } else {
3999 err = mHidlSession->processCaptureRequest(captureRequests, cachesToRemove,
Jayant Chowdharyc8d581e2018-07-16 14:46:23 -07004000 resultCallback);
Emilian Peevaebbe412018-01-15 13:53:24 +00004001 }
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -07004002 if (!err.isOk()) {
4003 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07004004 status = common::V1_0::Status::CAMERA_DISCONNECTED;
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -07004005 }
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07004006
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004007 if (status == common::V1_0::Status::OK && *numRequestProcessed != batchSize) {
4008 ALOGE("%s: processCaptureRequest returns OK but processed %d/%zu requests",
4009 __FUNCTION__, *numRequestProcessed, batchSize);
4010 status = common::V1_0::Status::INTERNAL_ERROR;
4011 }
4012
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07004013 res = CameraProviderManager::mapToStatusT(status);
4014 if (res == OK) {
4015 if (mHidlSession->isRemote()) {
4016 // Only close acquire fence FDs when the HIDL transaction succeeds (so the FDs have been
4017 // sent to camera HAL processes)
4018 cleanupNativeHandles(&handlesCreated, /*closeFd*/true);
4019 } else {
4020 // In passthrough mode the FDs are now owned by HAL
4021 cleanupNativeHandles(&handlesCreated);
4022 }
4023 } else {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004024 mBufferRecords.popInflightBuffers(inflightBuffers);
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07004025 cleanupNativeHandles(&handlesCreated);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004026 }
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07004027 return res;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004028}
4029
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004030status_t Camera3Device::HalInterface::flush() {
4031 ATRACE_NAME("CameraHal::flush");
4032 if (!valid()) return INVALID_OPERATION;
4033 status_t res = OK;
4034
Emilian Peev31abd0a2017-05-11 18:37:46 +01004035 auto err = mHidlSession->flush();
4036 if (!err.isOk()) {
4037 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
4038 res = DEAD_OBJECT;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004039 } else {
Emilian Peev31abd0a2017-05-11 18:37:46 +01004040 res = CameraProviderManager::mapToStatusT(err);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004041 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01004042
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004043 return res;
4044}
4045
Emilian Peev31abd0a2017-05-11 18:37:46 +01004046status_t Camera3Device::HalInterface::dump(int /*fd*/) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004047 ATRACE_NAME("CameraHal::dump");
4048 if (!valid()) return INVALID_OPERATION;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004049
Emilian Peev31abd0a2017-05-11 18:37:46 +01004050 // Handled by CameraProviderManager::dump
4051
4052 return OK;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004053}
4054
4055status_t Camera3Device::HalInterface::close() {
4056 ATRACE_NAME("CameraHal::close()");
4057 if (!valid()) return INVALID_OPERATION;
4058 status_t res = OK;
4059
Emilian Peev31abd0a2017-05-11 18:37:46 +01004060 auto err = mHidlSession->close();
4061 // Interface will be dead shortly anyway, so don't log errors
4062 if (!err.isOk()) {
4063 res = DEAD_OBJECT;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004064 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01004065
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004066 return res;
4067}
4068
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004069void Camera3Device::HalInterface::signalPipelineDrain(const std::vector<int>& streamIds) {
4070 ATRACE_NAME("CameraHal::signalPipelineDrain");
4071 if (!valid() || mHidlSession_3_5 == nullptr) {
4072 ALOGE("%s called on invalid camera!", __FUNCTION__);
4073 return;
4074 }
4075
Yin-Chia Yehc300a072019-02-13 14:56:57 -08004076 auto err = mHidlSession_3_5->signalStreamFlush(streamIds, mNextStreamConfigCounter - 1);
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004077 if (!err.isOk()) {
4078 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
4079 return;
4080 }
4081}
4082
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004083status_t Camera3Device::HalInterface::switchToOffline(
4084 const std::vector<int32_t>& streamsToKeep,
4085 /*out*/hardware::camera::device::V3_6::CameraOfflineSessionInfo* offlineSessionInfo,
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004086 /*out*/sp<hardware::camera::device::V3_6::ICameraOfflineSession>* offlineSession,
4087 /*out*/camera3::BufferRecords* bufferRecords) {
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004088 ATRACE_NAME("CameraHal::switchToOffline");
4089 if (!valid() || mHidlSession_3_6 == nullptr) {
4090 ALOGE("%s called on invalid camera!", __FUNCTION__);
4091 return INVALID_OPERATION;
4092 }
4093
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004094 if (offlineSessionInfo == nullptr || offlineSession == nullptr || bufferRecords == nullptr) {
4095 ALOGE("%s: output arguments must not be null!", __FUNCTION__);
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004096 return INVALID_OPERATION;
4097 }
4098
4099 common::V1_0::Status status = common::V1_0::Status::INTERNAL_ERROR;
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004100 auto resultCallback =
4101 [&status, &offlineSessionInfo, &offlineSession] (auto s, auto info, auto session) {
4102 status = s;
4103 *offlineSessionInfo = info;
4104 *offlineSession = session;
4105 };
4106 auto err = mHidlSession_3_6->switchToOffline(streamsToKeep, resultCallback);
4107
4108 if (!err.isOk()) {
4109 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
4110 return DEAD_OBJECT;
4111 }
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004112
4113 status_t ret = CameraProviderManager::mapToStatusT(status);
4114 if (ret != OK) {
4115 return ret;
4116 }
4117
4118 // TODO: assert no ongoing requestBuffer/returnBuffer call here
4119 // TODO: update RequestBufferStateMachine to block requestBuffer/returnBuffer once HAL
4120 // returns from switchToOffline.
4121
4122
4123 // Validate buffer caches
4124 std::vector<int32_t> streams;
4125 streams.reserve(offlineSessionInfo->offlineStreams.size());
4126 for (auto offlineStream : offlineSessionInfo->offlineStreams) {
4127 int32_t id = offlineStream.id;
4128 streams.push_back(id);
4129 // Verify buffer caches
4130 std::vector<uint64_t> bufIds(offlineStream.circulatingBufferIds.begin(),
4131 offlineStream.circulatingBufferIds.end());
4132 if (!verifyBufferIds(id, bufIds)) {
4133 ALOGE("%s: stream ID %d buffer cache records mismatch!", __FUNCTION__, id);
4134 return UNKNOWN_ERROR;
4135 }
4136 }
4137
4138 // Move buffer records
4139 bufferRecords->takeBufferCaches(mBufferRecords, streams);
4140 bufferRecords->takeInflightBufferMap(mBufferRecords);
4141 bufferRecords->takeRequestedBufferMap(mBufferRecords);
4142 return ret;
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004143}
4144
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07004145void Camera3Device::HalInterface::getInflightBufferKeys(
4146 std::vector<std::pair<int32_t, int32_t>>* out) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004147 mBufferRecords.getInflightBufferKeys(out);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07004148 return;
4149}
4150
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08004151void Camera3Device::HalInterface::getInflightRequestBufferKeys(
4152 std::vector<uint64_t>* out) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004153 mBufferRecords.getInflightRequestBufferKeys(out);
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08004154 return;
4155}
4156
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004157bool Camera3Device::HalInterface::verifyBufferIds(
4158 int32_t streamId, std::vector<uint64_t>& bufIds) {
4159 return mBufferRecords.verifyBufferIds(streamId, bufIds);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004160}
4161
4162status_t Camera3Device::HalInterface::popInflightBuffer(
Yin-Chia Yehf4650602017-01-10 13:13:39 -08004163 int32_t frameNumber, int32_t streamId,
4164 /*out*/ buffer_handle_t **buffer) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004165 return mBufferRecords.popInflightBuffer(frameNumber, streamId, buffer);
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07004166}
4167
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004168status_t Camera3Device::HalInterface::pushInflightRequestBuffer(
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08004169 uint64_t bufferId, buffer_handle_t* buf, int32_t streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004170 return mBufferRecords.pushInflightRequestBuffer(bufferId, buf, streamId);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004171}
4172
4173// Find and pop a buffer_handle_t based on bufferId
4174status_t Camera3Device::HalInterface::popInflightRequestBuffer(
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08004175 uint64_t bufferId,
4176 /*out*/ buffer_handle_t** buffer,
4177 /*optional out*/ int32_t* streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004178 return mBufferRecords.popInflightRequestBuffer(bufferId, buffer, streamId);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004179}
4180
Yin-Chia Yeh77327052017-01-09 18:23:07 -08004181std::pair<bool, uint64_t> Camera3Device::HalInterface::getBufferId(
4182 const buffer_handle_t& buf, int streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004183 return mBufferRecords.getBufferId(buf, streamId);
Yin-Chia Yeh77327052017-01-09 18:23:07 -08004184}
4185
Shuzhen Wangcd5b1822021-09-07 11:52:48 -07004186uint64_t Camera3Device::HalInterface::removeOneBufferCache(int streamId,
4187 const native_handle_t* handle) {
4188 return mBufferRecords.removeOneBufferCache(streamId, handle);
4189}
4190
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07004191void Camera3Device::HalInterface::onBufferFreed(
4192 int streamId, const native_handle_t* handle) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004193 uint32_t bufferId = mBufferRecords.removeOneBufferCache(streamId, handle);
4194 std::lock_guard<std::mutex> lock(mFreedBuffersLock);
4195 if (bufferId != BUFFER_ID_NO_BUFFER) {
4196 mFreedBuffers.push_back(std::make_pair(streamId, bufferId));
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07004197 }
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07004198}
4199
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07004200void Camera3Device::HalInterface::onStreamReConfigured(int streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004201 std::vector<uint64_t> bufIds = mBufferRecords.clearBufferCaches(streamId);
4202 std::lock_guard<std::mutex> lock(mFreedBuffersLock);
4203 for (auto bufferId : bufIds) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07004204 mFreedBuffers.push_back(std::make_pair(streamId, bufferId));
4205 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07004206}
4207
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004208/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004209 * RequestThread inner class methods
4210 */
4211
4212Camera3Device::RequestThread::RequestThread(wp<Camera3Device> parent,
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004213 sp<StatusTracker> statusTracker,
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004214 sp<HalInterface> interface, const Vector<int32_t>& sessionParamKeys,
Eino-Ville Talvala1646c3c2021-07-29 13:48:40 -07004215 bool useHalBufManager,
4216 bool supportCameraMute) :
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004217 Thread(/*canCallJava*/false),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004218 mParent(parent),
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004219 mStatusTracker(statusTracker),
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004220 mInterface(interface),
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07004221 mListener(nullptr),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004222 mId(getId(parent)),
Shuzhen Wang316781a2020-08-18 18:11:01 -07004223 mFirstRepeating(false),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004224 mReconfigured(false),
4225 mDoPause(false),
4226 mPaused(true),
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004227 mNotifyPipelineDrain(false),
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004228 mFrameNumber(0),
Jianing Weicb0652e2014-03-12 18:29:36 -07004229 mLatestRequestId(NAME_NOT_FOUND),
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07004230 mCurrentAfTriggerId(0),
4231 mCurrentPreCaptureTriggerId(0),
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004232 mRotateAndCropOverride(ANDROID_SCALER_ROTATE_AND_CROP_NONE),
Emilian Peeve23f1d92021-09-20 14:56:01 -07004233 mComposerOutput(false),
Eino-Ville Talvala11afe4f2021-05-27 14:45:31 -07004234 mCameraMute(ANDROID_SENSOR_TEST_PATTERN_MODE_OFF),
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004235 mCameraMuteChanged(false),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004236 mRepeatingLastFrameNumber(
4237 hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES),
Shuzhen Wang686f6442017-06-20 16:16:04 -07004238 mPrepareVideoStream(false),
Emilian Peeva14b4dd2018-05-15 11:00:31 +01004239 mConstrainedMode(false),
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004240 mRequestLatency(kRequestLatencyBinSize),
4241 mSessionParamKeys(sessionParamKeys),
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004242 mLatestSessionParams(sessionParamKeys.size()),
Eino-Ville Talvala1646c3c2021-07-29 13:48:40 -07004243 mUseHalBufManager(useHalBufManager),
4244 mSupportCameraMute(supportCameraMute){
Yin-Chia Yeh87b3ec02019-06-03 10:44:39 -07004245 mStatusId = statusTracker->addComponent("RequestThread");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004246}
4247
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004248Camera3Device::RequestThread::~RequestThread() {}
4249
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004250void Camera3Device::RequestThread::setNotificationListener(
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004251 wp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004252 ATRACE_CALL();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004253 Mutex::Autolock l(mRequestLock);
4254 mListener = listener;
4255}
4256
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004257void Camera3Device::RequestThread::configurationComplete(bool isConstrainedHighSpeed,
Shuzhen Wang99080502021-03-07 21:08:20 -08004258 const CameraMetadata& sessionParams,
4259 const std::map<int32_t, std::set<String8>>& groupIdPhysicalCameraMap) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004260 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004261 Mutex::Autolock l(mRequestLock);
4262 mReconfigured = true;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004263 mLatestSessionParams = sessionParams;
Shuzhen Wang99080502021-03-07 21:08:20 -08004264 mGroupIdPhysicalCameraMap = groupIdPhysicalCameraMap;
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07004265 // Prepare video stream for high speed recording.
4266 mPrepareVideoStream = isConstrainedHighSpeed;
Emilian Peeva14b4dd2018-05-15 11:00:31 +01004267 mConstrainedMode = isConstrainedHighSpeed;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004268}
4269
Jianing Wei90e59c92014-03-12 18:29:36 -07004270status_t Camera3Device::RequestThread::queueRequestList(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004271 List<sp<CaptureRequest> > &requests,
4272 /*out*/
4273 int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004274 ATRACE_CALL();
Jianing Wei90e59c92014-03-12 18:29:36 -07004275 Mutex::Autolock l(mRequestLock);
4276 for (List<sp<CaptureRequest> >::iterator it = requests.begin(); it != requests.end();
4277 ++it) {
4278 mRequestQueue.push_back(*it);
4279 }
4280
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004281 if (lastFrameNumber != NULL) {
4282 *lastFrameNumber = mFrameNumber + mRequestQueue.size() - 1;
4283 ALOGV("%s: requestId %d, mFrameNumber %" PRId32 ", lastFrameNumber %" PRId64 ".",
4284 __FUNCTION__, (*(requests.begin()))->mResultExtras.requestId, mFrameNumber,
4285 *lastFrameNumber);
4286 }
Jianing Weicb0652e2014-03-12 18:29:36 -07004287
Jianing Wei90e59c92014-03-12 18:29:36 -07004288 unpauseForNewRequests();
4289
4290 return OK;
4291}
4292
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004293
4294status_t Camera3Device::RequestThread::queueTrigger(
4295 RequestTrigger trigger[],
4296 size_t count) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004297 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004298 Mutex::Autolock l(mTriggerMutex);
4299 status_t ret;
4300
4301 for (size_t i = 0; i < count; ++i) {
4302 ret = queueTriggerLocked(trigger[i]);
4303
4304 if (ret != OK) {
4305 return ret;
4306 }
4307 }
4308
4309 return OK;
4310}
4311
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004312const String8& Camera3Device::RequestThread::getId(const wp<Camera3Device> &device) {
4313 static String8 deadId("<DeadDevice>");
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004314 sp<Camera3Device> d = device.promote();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004315 if (d != nullptr) return d->mId;
4316 return deadId;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004317}
4318
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004319status_t Camera3Device::RequestThread::queueTriggerLocked(
4320 RequestTrigger trigger) {
4321
4322 uint32_t tag = trigger.metadataTag;
4323 ssize_t index = mTriggerMap.indexOfKey(tag);
4324
4325 switch (trigger.getTagType()) {
4326 case TYPE_BYTE:
4327 // fall-through
4328 case TYPE_INT32:
4329 break;
4330 default:
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004331 ALOGE("%s: Type not supported: 0x%x", __FUNCTION__,
4332 trigger.getTagType());
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004333 return INVALID_OPERATION;
4334 }
4335
4336 /**
4337 * Collect only the latest trigger, since we only have 1 field
4338 * in the request settings per trigger tag, and can't send more than 1
4339 * trigger per request.
4340 */
4341 if (index != NAME_NOT_FOUND) {
4342 mTriggerMap.editValueAt(index) = trigger;
4343 } else {
4344 mTriggerMap.add(tag, trigger);
4345 }
4346
4347 return OK;
4348}
4349
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004350status_t Camera3Device::RequestThread::setRepeatingRequests(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004351 const RequestList &requests,
4352 /*out*/
4353 int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004354 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004355 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004356 if (lastFrameNumber != NULL) {
4357 *lastFrameNumber = mRepeatingLastFrameNumber;
4358 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004359 mRepeatingRequests.clear();
Shuzhen Wang316781a2020-08-18 18:11:01 -07004360 mFirstRepeating = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004361 mRepeatingRequests.insert(mRepeatingRequests.begin(),
4362 requests.begin(), requests.end());
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004363
4364 unpauseForNewRequests();
4365
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004366 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004367 return OK;
4368}
4369
Chih-Hung Hsieh8b0b9712016-08-09 14:25:53 -07004370bool Camera3Device::RequestThread::isRepeatingRequestLocked(const sp<CaptureRequest>& requestIn) {
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07004371 if (mRepeatingRequests.empty()) {
4372 return false;
4373 }
4374 int32_t requestId = requestIn->mResultExtras.requestId;
4375 const RequestList &repeatRequests = mRepeatingRequests;
4376 // All repeating requests are guaranteed to have same id so only check first quest
4377 const sp<CaptureRequest> firstRequest = *repeatRequests.begin();
4378 return (firstRequest->mResultExtras.requestId == requestId);
4379}
4380
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004381status_t Camera3Device::RequestThread::clearRepeatingRequests(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004382 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004383 Mutex::Autolock l(mRequestLock);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004384 return clearRepeatingRequestsLocked(lastFrameNumber);
4385
4386}
4387
4388status_t Camera3Device::RequestThread::clearRepeatingRequestsLocked(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004389 mRepeatingRequests.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004390 if (lastFrameNumber != NULL) {
4391 *lastFrameNumber = mRepeatingLastFrameNumber;
4392 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004393 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004394 return OK;
4395}
4396
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004397status_t Camera3Device::RequestThread::clear(
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004398 /*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004399 ATRACE_CALL();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004400 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004401 ALOGV("RequestThread::%s:", __FUNCTION__);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004402
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004403 mRepeatingRequests.clear();
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07004404
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004405 // Send errors for all requests pending in the request queue, including
4406 // pending repeating requests
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004407 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004408 if (listener != NULL) {
4409 for (RequestList::iterator it = mRequestQueue.begin();
4410 it != mRequestQueue.end(); ++it) {
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004411 // Abort the input buffers for reprocess requests.
4412 if ((*it)->mInputStream != NULL) {
Emilian Peevf4816702020-04-03 15:44:51 -07004413 camera_stream_buffer_t inputBuffer;
Shuzhen Wang83bff122020-11-20 15:51:39 -08004414 camera3::Size inputBufferSize;
Eino-Ville Talvalaba435252017-06-21 16:07:25 -07004415 status_t res = (*it)->mInputStream->getInputBuffer(&inputBuffer,
Shuzhen Wang83bff122020-11-20 15:51:39 -08004416 &inputBufferSize, /*respectHalLimit*/ false);
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004417 if (res != OK) {
4418 ALOGW("%s: %d: couldn't get input buffer while clearing the request "
4419 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
4420 } else {
Emilian Peevf4816702020-04-03 15:44:51 -07004421 inputBuffer.status = CAMERA_BUFFER_STATUS_ERROR;
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004422 res = (*it)->mInputStream->returnInputBuffer(inputBuffer);
4423 if (res != OK) {
4424 ALOGE("%s: %d: couldn't return input buffer while clearing the request "
4425 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
4426 }
4427 }
4428 }
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004429 // Set the frame number this request would have had, if it
4430 // had been submitted; this frame number will not be reused.
4431 // The requestId and burstId fields were set when the request was
4432 // submitted originally (in convertMetadataListToRequestListLocked)
4433 (*it)->mResultExtras.frameNumber = mFrameNumber++;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004434 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004435 (*it)->mResultExtras);
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07004436 }
4437 }
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004438 mRequestQueue.clear();
Jinguang Dongb26e7a02016-11-14 16:04:02 +08004439
4440 Mutex::Autolock al(mTriggerMutex);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004441 mTriggerMap.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004442 if (lastFrameNumber != NULL) {
4443 *lastFrameNumber = mRepeatingLastFrameNumber;
4444 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004445 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Emilian Peev8dae54c2019-12-02 15:17:17 -08004446 mRequestSignal.signal();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004447 return OK;
4448}
4449
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004450status_t Camera3Device::RequestThread::flush() {
4451 ATRACE_CALL();
4452 Mutex::Autolock l(mFlushLock);
4453
Emilian Peev08dd2452017-04-06 16:55:14 +01004454 return mInterface->flush();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004455}
4456
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004457void Camera3Device::RequestThread::setPaused(bool paused) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004458 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004459 Mutex::Autolock l(mPauseLock);
4460 mDoPause = paused;
4461 mDoPauseSignal.signal();
4462}
4463
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004464status_t Camera3Device::RequestThread::waitUntilRequestProcessed(
4465 int32_t requestId, nsecs_t timeout) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004466 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004467 Mutex::Autolock l(mLatestRequestMutex);
4468 status_t res;
4469 while (mLatestRequestId != requestId) {
4470 nsecs_t startTime = systemTime();
4471
4472 res = mLatestRequestSignal.waitRelative(mLatestRequestMutex, timeout);
4473 if (res != OK) return res;
4474
4475 timeout -= (systemTime() - startTime);
4476 }
4477
4478 return OK;
4479}
4480
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004481void Camera3Device::RequestThread::requestExit() {
4482 // Call parent to set up shutdown
4483 Thread::requestExit();
4484 // The exit from any possible waits
4485 mDoPauseSignal.signal();
4486 mRequestSignal.signal();
Shuzhen Wang686f6442017-06-20 16:16:04 -07004487
4488 mRequestLatency.log("ProcessCaptureRequest latency histogram");
4489 mRequestLatency.reset();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004490}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004491
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004492void Camera3Device::RequestThread::checkAndStopRepeatingRequest() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004493 ATRACE_CALL();
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07004494 bool surfaceAbandoned = false;
4495 int64_t lastFrameNumber = 0;
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004496 sp<NotificationListener> listener;
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07004497 {
4498 Mutex::Autolock l(mRequestLock);
4499 // Check all streams needed by repeating requests are still valid. Otherwise, stop
4500 // repeating requests.
4501 for (const auto& request : mRepeatingRequests) {
4502 for (const auto& s : request->mOutputStreams) {
4503 if (s->isAbandoned()) {
4504 surfaceAbandoned = true;
4505 clearRepeatingRequestsLocked(&lastFrameNumber);
4506 break;
4507 }
4508 }
4509 if (surfaceAbandoned) {
4510 break;
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004511 }
4512 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004513 listener = mListener.promote();
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004514 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004515
4516 if (listener != NULL && surfaceAbandoned) {
4517 listener->notifyRepeatingRequestError(lastFrameNumber);
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07004518 }
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004519}
4520
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004521bool Camera3Device::RequestThread::sendRequestsBatch() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004522 ATRACE_CALL();
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004523 status_t res;
4524 size_t batchSize = mNextRequests.size();
Emilian Peevf4816702020-04-03 15:44:51 -07004525 std::vector<camera_capture_request_t*> requests(batchSize);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004526 uint32_t numRequestProcessed = 0;
4527 for (size_t i = 0; i < batchSize; i++) {
4528 requests[i] = &mNextRequests.editItemAt(i).halRequest;
Yin-Chia Yeh885691c2018-05-01 15:54:24 -07004529 ATRACE_ASYNC_BEGIN("frame capture", mNextRequests[i].halRequest.frame_number);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004530 }
4531
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004532 res = mInterface->processBatchCaptureRequests(requests, &numRequestProcessed);
4533
4534 bool triggerRemoveFailed = false;
4535 NextRequest& triggerFailedRequest = mNextRequests.editItemAt(0);
4536 for (size_t i = 0; i < numRequestProcessed; i++) {
4537 NextRequest& nextRequest = mNextRequests.editItemAt(i);
4538 nextRequest.submitted = true;
4539
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004540 updateNextRequest(nextRequest);
Emilian Peevaebbe412018-01-15 13:53:24 +00004541
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004542 if (!triggerRemoveFailed) {
4543 // Remove any previously queued triggers (after unlock)
4544 status_t removeTriggerRes = removeTriggers(mPrevRequest);
4545 if (removeTriggerRes != OK) {
4546 triggerRemoveFailed = true;
4547 triggerFailedRequest = nextRequest;
4548 }
4549 }
4550 }
4551
4552 if (triggerRemoveFailed) {
4553 SET_ERR("RequestThread: Unable to remove triggers "
4554 "(capture request %d, HAL device: %s (%d)",
4555 triggerFailedRequest.halRequest.frame_number, strerror(-res), res);
4556 cleanUpFailedRequests(/*sendRequestError*/ false);
4557 return false;
4558 }
4559
4560 if (res != OK) {
4561 // Should only get a failure here for malformed requests or device-level
4562 // errors, so consider all errors fatal. Bad metadata failures should
4563 // come through notify.
4564 SET_ERR("RequestThread: Unable to submit capture request %d to HAL device: %s (%d)",
4565 mNextRequests[numRequestProcessed].halRequest.frame_number,
4566 strerror(-res), res);
4567 cleanUpFailedRequests(/*sendRequestError*/ false);
4568 return false;
4569 }
4570 return true;
4571}
4572
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07004573nsecs_t Camera3Device::RequestThread::calculateMaxExpectedDuration(const camera_metadata_t *request) {
4574 nsecs_t maxExpectedDuration = kDefaultExpectedDuration;
4575 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
4576 find_camera_metadata_ro_entry(request,
4577 ANDROID_CONTROL_AE_MODE,
4578 &e);
4579 if (e.count == 0) return maxExpectedDuration;
4580
4581 switch (e.data.u8[0]) {
4582 case ANDROID_CONTROL_AE_MODE_OFF:
4583 find_camera_metadata_ro_entry(request,
4584 ANDROID_SENSOR_EXPOSURE_TIME,
4585 &e);
4586 if (e.count > 0) {
4587 maxExpectedDuration = e.data.i64[0];
4588 }
4589 find_camera_metadata_ro_entry(request,
4590 ANDROID_SENSOR_FRAME_DURATION,
4591 &e);
4592 if (e.count > 0) {
4593 maxExpectedDuration = std::max(e.data.i64[0], maxExpectedDuration);
4594 }
4595 break;
4596 default:
4597 find_camera_metadata_ro_entry(request,
4598 ANDROID_CONTROL_AE_TARGET_FPS_RANGE,
4599 &e);
4600 if (e.count > 1) {
4601 maxExpectedDuration = 1e9 / e.data.u8[0];
4602 }
4603 break;
4604 }
4605
4606 return maxExpectedDuration;
4607}
4608
Emilian Peeva14b4dd2018-05-15 11:00:31 +01004609bool Camera3Device::RequestThread::skipHFRTargetFPSUpdate(int32_t tag,
4610 const camera_metadata_ro_entry_t& newEntry, const camera_metadata_entry_t& currentEntry) {
4611 if (mConstrainedMode && (ANDROID_CONTROL_AE_TARGET_FPS_RANGE == tag) &&
4612 (newEntry.count == currentEntry.count) && (currentEntry.count == 2) &&
4613 (currentEntry.data.i32[1] == newEntry.data.i32[1])) {
4614 return true;
4615 }
4616
4617 return false;
4618}
4619
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004620void Camera3Device::RequestThread::updateNextRequest(NextRequest& nextRequest) {
4621 // Update the latest request sent to HAL
Shuzhen Wang83bff122020-11-20 15:51:39 -08004622 camera_capture_request_t& halRequest = nextRequest.halRequest;
4623 if (halRequest.settings != NULL) { // Don't update if they were unchanged
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004624 Mutex::Autolock al(mLatestRequestMutex);
4625
Shuzhen Wang83bff122020-11-20 15:51:39 -08004626 camera_metadata_t* cloned = clone_camera_metadata(halRequest.settings);
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004627 mLatestRequest.acquire(cloned);
4628
4629 mLatestPhysicalRequest.clear();
Shuzhen Wang83bff122020-11-20 15:51:39 -08004630 for (uint32_t i = 0; i < halRequest.num_physcam_settings; i++) {
4631 cloned = clone_camera_metadata(halRequest.physcam_settings[i]);
4632 mLatestPhysicalRequest.emplace(halRequest.physcam_id[i],
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004633 CameraMetadata(cloned));
4634 }
4635
4636 sp<Camera3Device> parent = mParent.promote();
4637 if (parent != NULL) {
Jayant Chowdharycd277cd2021-08-11 15:48:40 -07004638 int32_t inputStreamId = -1;
4639 if (halRequest.input_buffer != nullptr) {
4640 inputStreamId = Camera3Stream::cast(halRequest.input_buffer->stream)->getId();
4641 }
4642
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004643 parent->monitorMetadata(TagMonitor::REQUEST,
Shuzhen Wang83bff122020-11-20 15:51:39 -08004644 halRequest.frame_number,
Jayant Chowdharyc30b4c32021-08-18 11:43:16 -07004645 0, mLatestRequest, mLatestPhysicalRequest, halRequest.output_buffers,
4646 halRequest.num_output_buffers, inputStreamId);
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004647 }
4648 }
4649
Shuzhen Wang83bff122020-11-20 15:51:39 -08004650 if (halRequest.settings != NULL) {
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004651 nextRequest.captureRequest->mSettingsList.begin()->metadata.unlock(
Shuzhen Wang83bff122020-11-20 15:51:39 -08004652 halRequest.settings);
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004653 }
4654
Shuzhen Wang83bff122020-11-20 15:51:39 -08004655 cleanupPhysicalSettings(nextRequest.captureRequest, &halRequest);
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004656}
4657
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004658bool Camera3Device::RequestThread::updateSessionParameters(const CameraMetadata& settings) {
4659 ATRACE_CALL();
4660 bool updatesDetected = false;
4661
Emilian Peev4ec17882019-01-24 17:16:58 -08004662 CameraMetadata updatedParams(mLatestSessionParams);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004663 for (auto tag : mSessionParamKeys) {
4664 camera_metadata_ro_entry entry = settings.find(tag);
Emilian Peev4ec17882019-01-24 17:16:58 -08004665 camera_metadata_entry lastEntry = updatedParams.find(tag);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004666
4667 if (entry.count > 0) {
4668 bool isDifferent = false;
4669 if (lastEntry.count > 0) {
4670 // Have a last value, compare to see if changed
4671 if (lastEntry.type == entry.type &&
4672 lastEntry.count == entry.count) {
4673 // Same type and count, compare values
4674 size_t bytesPerValue = camera_metadata_type_size[lastEntry.type];
4675 size_t entryBytes = bytesPerValue * lastEntry.count;
4676 int cmp = memcmp(entry.data.u8, lastEntry.data.u8, entryBytes);
4677 if (cmp != 0) {
4678 isDifferent = true;
4679 }
4680 } else {
4681 // Count or type has changed
4682 isDifferent = true;
4683 }
4684 } else {
4685 // No last entry, so always consider to be different
4686 isDifferent = true;
4687 }
4688
4689 if (isDifferent) {
4690 ALOGV("%s: Session parameter tag id %d changed", __FUNCTION__, tag);
Emilian Peeva14b4dd2018-05-15 11:00:31 +01004691 if (!skipHFRTargetFPSUpdate(tag, entry, lastEntry)) {
4692 updatesDetected = true;
4693 }
Emilian Peev4ec17882019-01-24 17:16:58 -08004694 updatedParams.update(entry);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004695 }
4696 } else if (lastEntry.count > 0) {
4697 // Value has been removed
4698 ALOGV("%s: Session parameter tag id %d removed", __FUNCTION__, tag);
Emilian Peev4ec17882019-01-24 17:16:58 -08004699 updatedParams.erase(tag);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004700 updatesDetected = true;
4701 }
4702 }
4703
Emilian Peev4ec17882019-01-24 17:16:58 -08004704 bool reconfigureRequired;
4705 if (updatesDetected) {
4706 reconfigureRequired = mInterface->isReconfigurationRequired(mLatestSessionParams,
4707 updatedParams);
4708 mLatestSessionParams = updatedParams;
4709 } else {
4710 reconfigureRequired = false;
4711 }
4712
4713 return reconfigureRequired;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004714}
4715
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004716bool Camera3Device::RequestThread::threadLoop() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004717 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004718 status_t res;
Jayant Chowdhary37eca242019-11-18 08:55:56 -08004719 // Any function called from threadLoop() must not hold mInterfaceLock since
4720 // it could lead to deadlocks (disconnect() -> hold mInterfaceMutex -> wait for request thread
4721 // to finish -> request thread waits on mInterfaceMutex) http://b/143513518
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004722
4723 // Handle paused state.
4724 if (waitIfPaused()) {
4725 return true;
4726 }
4727
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004728 // Wait for the next batch of requests.
4729 waitForNextRequestBatch();
4730 if (mNextRequests.size() == 0) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004731 return true;
4732 }
4733
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004734 // Get the latest request ID, if any
4735 int latestRequestId;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004736 camera_metadata_entry_t requestIdEntry = mNextRequests[mNextRequests.size() - 1].
Emilian Peevaebbe412018-01-15 13:53:24 +00004737 captureRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_ID);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004738 if (requestIdEntry.count > 0) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004739 latestRequestId = requestIdEntry.data.i32[0];
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004740 } else {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004741 ALOGW("%s: Did not have android.request.id set in the request.", __FUNCTION__);
4742 latestRequestId = NAME_NOT_FOUND;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004743 }
4744
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004745 // 'mNextRequests' will at this point contain either a set of HFR batched requests
4746 // or a single request from streaming or burst. In either case the first element
4747 // should contain the latest camera settings that we need to check for any session
4748 // parameter updates.
Emilian Peevaebbe412018-01-15 13:53:24 +00004749 if (updateSessionParameters(mNextRequests[0].captureRequest->mSettingsList.begin()->metadata)) {
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004750 res = OK;
4751
4752 //Input stream buffers are already acquired at this point so an input stream
4753 //will not be able to move to idle state unless we force it.
4754 if (mNextRequests[0].captureRequest->mInputStream != nullptr) {
4755 res = mNextRequests[0].captureRequest->mInputStream->forceToIdle();
4756 if (res != OK) {
4757 ALOGE("%s: Failed to force idle input stream: %d", __FUNCTION__, res);
4758 cleanUpFailedRequests(/*sendRequestError*/ false);
4759 return false;
4760 }
4761 }
4762
4763 if (res == OK) {
Emilian Peev3bead5f2020-05-28 17:29:08 -07004764 sp<Camera3Device> parent = mParent.promote();
4765 if (parent != nullptr) {
4766 mReconfigured |= parent->reconfigureCamera(mLatestSessionParams, mStatusId);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004767 }
Emilian Peev3bead5f2020-05-28 17:29:08 -07004768 setPaused(false);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004769
4770 if (mNextRequests[0].captureRequest->mInputStream != nullptr) {
4771 mNextRequests[0].captureRequest->mInputStream->restoreConfiguredState();
4772 if (res != OK) {
4773 ALOGE("%s: Failed to restore configured input stream: %d", __FUNCTION__, res);
4774 cleanUpFailedRequests(/*sendRequestError*/ false);
4775 return false;
4776 }
4777 }
4778 }
4779 }
4780
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004781 // Prepare a batch of HAL requests and output buffers.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004782 res = prepareHalRequests();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004783 if (res == TIMED_OUT) {
4784 // Not a fatal error if getting output buffers time out.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004785 cleanUpFailedRequests(/*sendRequestError*/ true);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004786 // Check if any stream is abandoned.
4787 checkAndStopRepeatingRequest();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004788 return true;
4789 } else if (res != OK) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004790 cleanUpFailedRequests(/*sendRequestError*/ false);
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004791 return false;
4792 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004793
Zhijun Hecc27e112013-10-03 16:12:43 -07004794 // Inform waitUntilRequestProcessed thread of a new request ID
4795 {
4796 Mutex::Autolock al(mLatestRequestMutex);
4797
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004798 mLatestRequestId = latestRequestId;
Zhijun Hecc27e112013-10-03 16:12:43 -07004799 mLatestRequestSignal.signal();
4800 }
4801
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004802 // Submit a batch of requests to HAL.
4803 // Use flush lock only when submitting multilple requests in a batch.
4804 // TODO: The problem with flush lock is flush() will be blocked by process_capture_request()
4805 // which may take a long time to finish so synchronizing flush() and
4806 // process_capture_request() defeats the purpose of cancelling requests ASAP with flush().
4807 // For now, only synchronize for high speed recording and we should figure something out for
4808 // removing the synchronization.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004809 bool useFlushLock = mNextRequests.size() > 1;
Eino-Ville Talvala17a61ad2013-06-03 16:53:32 -07004810
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004811 if (useFlushLock) {
4812 mFlushLock.lock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004813 }
4814
Zhijun Hef0645c12016-08-02 00:58:11 -07004815 ALOGVV("%s: %d: submitting %zu requests in a batch.", __FUNCTION__, __LINE__,
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004816 mNextRequests.size());
Igor Murashkin1e479c02013-09-06 16:55:14 -07004817
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08004818 sp<Camera3Device> parent = mParent.promote();
4819 if (parent != nullptr) {
4820 parent->mRequestBufferSM.onSubmittingRequest();
4821 }
4822
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004823 bool submitRequestSuccess = false;
Shuzhen Wang686f6442017-06-20 16:16:04 -07004824 nsecs_t tRequestStart = systemTime(SYSTEM_TIME_MONOTONIC);
Yin-Chia Yeh11648852019-05-16 10:42:54 -07004825 submitRequestSuccess = sendRequestsBatch();
4826
Shuzhen Wang686f6442017-06-20 16:16:04 -07004827 nsecs_t tRequestEnd = systemTime(SYSTEM_TIME_MONOTONIC);
4828 mRequestLatency.add(tRequestStart, tRequestEnd);
Igor Murashkin1e479c02013-09-06 16:55:14 -07004829
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004830 if (useFlushLock) {
4831 mFlushLock.unlock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004832 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004833
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004834 // Unset as current request
4835 {
4836 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004837 mNextRequests.clear();
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004838 }
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004839 mRequestSubmittedSignal.signal();
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004840
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004841 return submitRequestSuccess;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004842}
4843
Jayant Chowdhary65c9bf02021-09-03 16:44:16 +00004844status_t Camera3Device::removeFwkOnlyRegionKeys(CameraMetadata *request) {
4845 static const std::array<uint32_t, 4> kFwkOnlyRegionKeys = {ANDROID_CONTROL_AF_REGIONS_SET,
4846 ANDROID_CONTROL_AE_REGIONS_SET, ANDROID_CONTROL_AWB_REGIONS_SET,
4847 ANDROID_SCALER_CROP_REGION_SET};
4848 if (request == nullptr) {
4849 ALOGE("%s request metadata nullptr", __FUNCTION__);
4850 return BAD_VALUE;
4851 }
4852 status_t res = OK;
4853 for (const auto &key : kFwkOnlyRegionKeys) {
4854 if (request->exists(key)) {
4855 res = request->erase(key);
4856 if (res != OK) {
4857 return res;
4858 }
4859 }
4860 }
4861 return OK;
4862}
4863
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004864status_t Camera3Device::RequestThread::prepareHalRequests() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004865 ATRACE_CALL();
4866
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07004867 bool batchedRequest = mNextRequests[0].captureRequest->mBatchSize > 1;
Shuzhen Wang4a472662017-02-26 23:29:04 -08004868 for (size_t i = 0; i < mNextRequests.size(); i++) {
4869 auto& nextRequest = mNextRequests.editItemAt(i);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004870 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
Emilian Peevf4816702020-04-03 15:44:51 -07004871 camera_capture_request_t* halRequest = &nextRequest.halRequest;
4872 Vector<camera_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004873
4874 // Prepare a request to HAL
4875 halRequest->frame_number = captureRequest->mResultExtras.frameNumber;
4876
4877 // Insert any queued triggers (before metadata is locked)
4878 status_t res = insertTriggers(captureRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004879 if (res < 0) {
4880 SET_ERR("RequestThread: Unable to insert triggers "
4881 "(capture request %d, HAL device: %s (%d)",
4882 halRequest->frame_number, strerror(-res), res);
4883 return INVALID_OPERATION;
4884 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07004885
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004886 int triggerCount = res;
4887 bool triggersMixedIn = (triggerCount > 0 || mPrevTriggers > 0);
4888 mPrevTriggers = triggerCount;
4889
Emilian Peeve23f1d92021-09-20 14:56:01 -07004890 // Do not override rotate&crop for stream configurations that include
4891 // SurfaceViews(HW_COMPOSER) output. The display rotation there will be
4892 // compensated by NATIVE_WINDOW_TRANSFORM_INVERSE_DISPLAY
4893 bool rotateAndCropChanged = mComposerOutput ? false :
4894 overrideAutoRotateAndCrop(captureRequest);
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004895 bool testPatternChanged = overrideTestPattern(captureRequest);
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004896
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004897 // If the request is the same as last, or we had triggers now or last time or
4898 // changing overrides this time
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004899 bool newRequest =
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004900 (mPrevRequest != captureRequest || triggersMixedIn ||
4901 rotateAndCropChanged || testPatternChanged) &&
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07004902 // Request settings are all the same within one batch, so only treat the first
4903 // request in a batch as new
Zhijun He54c36822018-07-18 09:33:39 -07004904 !(batchedRequest && i > 0);
Emilian Peev00420d22018-02-05 21:33:13 +00004905 if (newRequest) {
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08004906 std::set<std::string> cameraIdsWithZoom;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004907 /**
4908 * HAL workaround:
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004909 * Insert a fake trigger ID if a trigger is set but no trigger ID is
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004910 */
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004911 res = addFakeTriggerIds(captureRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004912 if (res != OK) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004913 SET_ERR("RequestThread: Unable to insert fake trigger IDs "
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004914 "(capture request %d, HAL device: %s (%d)",
4915 halRequest->frame_number, strerror(-res), res);
4916 return INVALID_OPERATION;
4917 }
4918
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07004919 {
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07004920 sp<Camera3Device> parent = mParent.promote();
4921 if (parent != nullptr) {
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -07004922 List<PhysicalCameraSettings>::iterator it;
4923 for (it = captureRequest->mSettingsList.begin();
4924 it != captureRequest->mSettingsList.end(); it++) {
Jayant Chowdhary9255ce02021-07-15 11:18:17 -07004925 if (parent->mUHRCropAndMeteringRegionMappers.find(it->cameraId) ==
4926 parent->mUHRCropAndMeteringRegionMappers.end()) {
Jayant Chowdhary65c9bf02021-09-03 16:44:16 +00004927 if (removeFwkOnlyRegionKeys(&(it->metadata)) != OK) {
4928 SET_ERR("RequestThread: Unable to remove fwk-only keys from request"
4929 "%d: %s (%d)", halRequest->frame_number, strerror(-res),
4930 res);
4931 return INVALID_OPERATION;
4932 }
Jayant Chowdhary9255ce02021-07-15 11:18:17 -07004933 continue;
4934 }
4935
4936 if (!captureRequest->mUHRCropAndMeteringRegionsUpdated) {
4937 res = parent->mUHRCropAndMeteringRegionMappers[it->cameraId].
4938 updateCaptureRequest(&(it->metadata));
4939 if (res != OK) {
4940 SET_ERR("RequestThread: Unable to correct capture requests "
4941 "for scaler crop region and metering regions for request "
4942 "%d: %s (%d)", halRequest->frame_number, strerror(-res),
4943 res);
4944 return INVALID_OPERATION;
4945 }
4946 captureRequest->mUHRCropAndMeteringRegionsUpdated = true;
Jayant Chowdhary65c9bf02021-09-03 16:44:16 +00004947 if (removeFwkOnlyRegionKeys(&(it->metadata)) != OK) {
4948 SET_ERR("RequestThread: Unable to remove fwk-only keys from request"
4949 "%d: %s (%d)", halRequest->frame_number, strerror(-res),
4950 res);
4951 return INVALID_OPERATION;
4952 }
Jayant Chowdhary9255ce02021-07-15 11:18:17 -07004953 }
4954 }
4955
4956 // Correct metadata regions for distortion correction if enabled
4957 for (it = captureRequest->mSettingsList.begin();
4958 it != captureRequest->mSettingsList.end(); it++) {
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -07004959 if (parent->mDistortionMappers.find(it->cameraId) ==
4960 parent->mDistortionMappers.end()) {
4961 continue;
4962 }
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07004963
4964 if (!captureRequest->mDistortionCorrectionUpdated) {
4965 res = parent->mDistortionMappers[it->cameraId].correctCaptureRequest(
4966 &(it->metadata));
4967 if (res != OK) {
4968 SET_ERR("RequestThread: Unable to correct capture requests "
4969 "for lens distortion for request %d: %s (%d)",
4970 halRequest->frame_number, strerror(-res), res);
4971 return INVALID_OPERATION;
4972 }
4973 captureRequest->mDistortionCorrectionUpdated = true;
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -07004974 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07004975 }
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08004976
4977 for (it = captureRequest->mSettingsList.begin();
4978 it != captureRequest->mSettingsList.end(); it++) {
4979 if (parent->mZoomRatioMappers.find(it->cameraId) ==
4980 parent->mZoomRatioMappers.end()) {
4981 continue;
4982 }
4983
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07004984 if (!captureRequest->mZoomRatioIs1x) {
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08004985 cameraIdsWithZoom.insert(it->cameraId);
4986 }
4987
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07004988 if (!captureRequest->mZoomRatioUpdated) {
4989 res = parent->mZoomRatioMappers[it->cameraId].updateCaptureRequest(
4990 &(it->metadata));
4991 if (res != OK) {
4992 SET_ERR("RequestThread: Unable to correct capture requests "
4993 "for zoom ratio for request %d: %s (%d)",
4994 halRequest->frame_number, strerror(-res), res);
4995 return INVALID_OPERATION;
4996 }
4997 captureRequest->mZoomRatioUpdated = true;
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08004998 }
4999 }
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07005000 if (captureRequest->mRotateAndCropAuto &&
5001 !captureRequest->mRotationAndCropUpdated) {
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005002 for (it = captureRequest->mSettingsList.begin();
5003 it != captureRequest->mSettingsList.end(); it++) {
5004 auto mapper = parent->mRotateAndCropMappers.find(it->cameraId);
5005 if (mapper != parent->mRotateAndCropMappers.end()) {
5006 res = mapper->second.updateCaptureRequest(&(it->metadata));
5007 if (res != OK) {
5008 SET_ERR("RequestThread: Unable to correct capture requests "
5009 "for rotate-and-crop for request %d: %s (%d)",
5010 halRequest->frame_number, strerror(-res), res);
5011 return INVALID_OPERATION;
5012 }
5013 }
5014 }
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07005015 captureRequest->mRotationAndCropUpdated = true;
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005016 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07005017 }
5018 }
5019
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005020 /**
5021 * The request should be presorted so accesses in HAL
5022 * are O(logn). Sidenote, sorting a sorted metadata is nop.
5023 */
Emilian Peevaebbe412018-01-15 13:53:24 +00005024 captureRequest->mSettingsList.begin()->metadata.sort();
5025 halRequest->settings = captureRequest->mSettingsList.begin()->metadata.getAndLock();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005026 mPrevRequest = captureRequest;
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08005027 mPrevCameraIdsWithZoom = cameraIdsWithZoom;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005028 ALOGVV("%s: Request settings are NEW", __FUNCTION__);
5029
5030 IF_ALOGV() {
5031 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
5032 find_camera_metadata_ro_entry(
5033 halRequest->settings,
5034 ANDROID_CONTROL_AF_TRIGGER,
5035 &e
5036 );
5037 if (e.count > 0) {
5038 ALOGV("%s: Request (frame num %d) had AF trigger 0x%x",
5039 __FUNCTION__,
5040 halRequest->frame_number,
5041 e.data.u8[0]);
5042 }
5043 }
5044 } else {
5045 // leave request.settings NULL to indicate 'reuse latest given'
5046 ALOGVV("%s: Request settings are REUSED",
5047 __FUNCTION__);
5048 }
5049
Emilian Peevaebbe412018-01-15 13:53:24 +00005050 if (captureRequest->mSettingsList.size() > 1) {
5051 halRequest->num_physcam_settings = captureRequest->mSettingsList.size() - 1;
5052 halRequest->physcam_id = new const char* [halRequest->num_physcam_settings];
Emilian Peev00420d22018-02-05 21:33:13 +00005053 if (newRequest) {
5054 halRequest->physcam_settings =
5055 new const camera_metadata* [halRequest->num_physcam_settings];
5056 } else {
5057 halRequest->physcam_settings = nullptr;
5058 }
Emilian Peevaebbe412018-01-15 13:53:24 +00005059 auto it = ++captureRequest->mSettingsList.begin();
5060 size_t i = 0;
5061 for (; it != captureRequest->mSettingsList.end(); it++, i++) {
5062 halRequest->physcam_id[i] = it->cameraId.c_str();
Emilian Peev00420d22018-02-05 21:33:13 +00005063 if (newRequest) {
5064 it->metadata.sort();
5065 halRequest->physcam_settings[i] = it->metadata.getAndLock();
5066 }
Emilian Peevaebbe412018-01-15 13:53:24 +00005067 }
5068 }
5069
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005070 uint32_t totalNumBuffers = 0;
5071
5072 // Fill in buffers
5073 if (captureRequest->mInputStream != NULL) {
5074 halRequest->input_buffer = &captureRequest->mInputBuffer;
Shuzhen Wang83bff122020-11-20 15:51:39 -08005075
5076 halRequest->input_width = captureRequest->mInputBufferSize.width;
5077 halRequest->input_height = captureRequest->mInputBufferSize.height;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005078 totalNumBuffers += 1;
5079 } else {
5080 halRequest->input_buffer = NULL;
5081 }
5082
Emilian Peevf4816702020-04-03 15:44:51 -07005083 outputBuffers->insertAt(camera_stream_buffer_t(), 0,
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005084 captureRequest->mOutputStreams.size());
5085 halRequest->output_buffers = outputBuffers->array();
Shuzhen Wang99080502021-03-07 21:08:20 -08005086 std::set<std::set<String8>> requestedPhysicalCameras;
Yin-Chia Yehb3a80b12018-09-04 12:13:05 -07005087
5088 sp<Camera3Device> parent = mParent.promote();
5089 if (parent == NULL) {
5090 // Should not happen, and nowhere to send errors to, so just log it
5091 CLOGE("RequestThread: Parent is gone");
5092 return INVALID_OPERATION;
5093 }
5094 nsecs_t waitDuration = kBaseGetBufferWait + parent->getExpectedInFlightDuration();
5095
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005096 SurfaceMap uniqueSurfaceIdMap;
Shuzhen Wang4a472662017-02-26 23:29:04 -08005097 for (size_t j = 0; j < captureRequest->mOutputStreams.size(); j++) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005098 sp<Camera3OutputStreamInterface> outputStream =
5099 captureRequest->mOutputStreams.editItemAt(j);
5100 int streamId = outputStream->getId();
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07005101
5102 // Prepare video buffers for high speed recording on the first video request.
5103 if (mPrepareVideoStream && outputStream->isVideoStream()) {
5104 // Only try to prepare video stream on the first video request.
5105 mPrepareVideoStream = false;
5106
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07005107 res = outputStream->startPrepare(Camera3StreamInterface::ALLOCATE_PIPELINE_MAX,
5108 false /*blockRequest*/);
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07005109 while (res == NOT_ENOUGH_DATA) {
5110 res = outputStream->prepareNextBuffer();
5111 }
5112 if (res != OK) {
5113 ALOGW("%s: Preparing video buffers for high speed failed: %s (%d)",
5114 __FUNCTION__, strerror(-res), res);
5115 outputStream->cancelPrepare();
5116 }
5117 }
5118
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005119 std::vector<size_t> uniqueSurfaceIds;
5120 res = outputStream->getUniqueSurfaceIds(
5121 captureRequest->mOutputSurfaces[streamId],
5122 &uniqueSurfaceIds);
5123 // INVALID_OPERATION is normal output for streams not supporting surfaceIds
5124 if (res != OK && res != INVALID_OPERATION) {
5125 ALOGE("%s: failed to query stream %d unique surface IDs",
5126 __FUNCTION__, streamId);
5127 return res;
5128 }
5129 if (res == OK) {
5130 uniqueSurfaceIdMap.insert({streamId, std::move(uniqueSurfaceIds)});
5131 }
5132
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07005133 if (mUseHalBufManager) {
Yin-Chia Yeh110342b2018-11-19 11:47:46 -08005134 if (outputStream->isAbandoned()) {
Yin-Chia Yeha1b56c82019-03-27 15:50:39 -07005135 ALOGV("%s: stream %d is abandoned, skipping request", __FUNCTION__, streamId);
Yin-Chia Yeh110342b2018-11-19 11:47:46 -08005136 return TIMED_OUT;
5137 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07005138 // HAL will request buffer through requestStreamBuffer API
Emilian Peevf4816702020-04-03 15:44:51 -07005139 camera_stream_buffer_t& buffer = outputBuffers->editItemAt(j);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07005140 buffer.stream = outputStream->asHalStream();
5141 buffer.buffer = nullptr;
Emilian Peevf4816702020-04-03 15:44:51 -07005142 buffer.status = CAMERA_BUFFER_STATUS_OK;
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07005143 buffer.acquire_fence = -1;
5144 buffer.release_fence = -1;
Emilian Peevf0348ae2021-01-13 13:39:45 -08005145 // Mark the output stream as unpreparable to block clients from calling
5146 // 'prepare' after this request reaches CameraHal and before the respective
5147 // buffers are requested.
5148 outputStream->markUnpreparable();
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07005149 } else {
5150 res = outputStream->getBuffer(&outputBuffers->editItemAt(j),
5151 waitDuration,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005152 captureRequest->mOutputSurfaces[streamId]);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07005153 if (res != OK) {
5154 // Can't get output buffer from gralloc queue - this could be due to
5155 // abandoned queue or other consumer misbehavior, so not a fatal
5156 // error
Yin-Chia Yeha1b56c82019-03-27 15:50:39 -07005157 ALOGV("RequestThread: Can't get output buffer, skipping request:"
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07005158 " %s (%d)", strerror(-res), res);
5159
5160 return TIMED_OUT;
5161 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005162 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08005163
5164 {
5165 sp<Camera3Device> parent = mParent.promote();
5166 if (parent != nullptr) {
5167 const String8& streamCameraId = outputStream->getPhysicalCameraId();
5168 for (const auto& settings : captureRequest->mSettingsList) {
5169 if ((streamCameraId.isEmpty() &&
5170 parent->getId() == settings.cameraId.c_str()) ||
5171 streamCameraId == settings.cameraId.c_str()) {
5172 outputStream->fireBufferRequestForFrameNumber(
5173 captureRequest->mResultExtras.frameNumber,
5174 settings.metadata);
5175 }
5176 }
5177 }
5178 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07005179
Shuzhen Wang5c22c152017-12-31 17:12:25 -08005180 String8 physicalCameraId = outputStream->getPhysicalCameraId();
Shuzhen Wang99080502021-03-07 21:08:20 -08005181 int32_t streamGroupId = outputStream->getHalStreamGroupId();
5182 if (streamGroupId != -1 && mGroupIdPhysicalCameraMap.count(streamGroupId) == 1) {
5183 requestedPhysicalCameras.insert(mGroupIdPhysicalCameraMap[streamGroupId]);
5184 } else if (!physicalCameraId.isEmpty()) {
5185 requestedPhysicalCameras.insert(std::set<String8>({physicalCameraId}));
Shuzhen Wang5c22c152017-12-31 17:12:25 -08005186 }
5187 halRequest->num_output_buffers++;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005188 }
5189 totalNumBuffers += halRequest->num_output_buffers;
5190
5191 // Log request in the in-flight queue
Shuzhen Wang4a472662017-02-26 23:29:04 -08005192 // If this request list is for constrained high speed recording (not
5193 // preview), and the current request is not the last one in the batch,
5194 // do not send callback to the app.
5195 bool hasCallback = true;
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07005196 if (batchedRequest && i != mNextRequests.size()-1) {
Shuzhen Wang4a472662017-02-26 23:29:04 -08005197 hasCallback = false;
5198 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01005199 bool isStillCapture = false;
Shuzhen Wang26abaf42018-08-28 15:41:20 -07005200 bool isZslCapture = false;
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08005201 const camera_metadata_t* settings = halRequest->settings;
5202 bool shouldUnlockSettings = false;
5203 if (settings == nullptr) {
5204 shouldUnlockSettings = true;
5205 settings = captureRequest->mSettingsList.begin()->metadata.getAndLock();
5206 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01005207 if (!mNextRequests[0].captureRequest->mSettingsList.begin()->metadata.isEmpty()) {
5208 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08005209 find_camera_metadata_ro_entry(settings, ANDROID_CONTROL_CAPTURE_INTENT, &e);
Emilian Peev9dd21f42018-08-03 13:39:29 +01005210 if ((e.count > 0) && (e.data.u8[0] == ANDROID_CONTROL_CAPTURE_INTENT_STILL_CAPTURE)) {
5211 isStillCapture = true;
5212 ATRACE_ASYNC_BEGIN("still capture", mNextRequests[i].halRequest.frame_number);
5213 }
Shuzhen Wang26abaf42018-08-28 15:41:20 -07005214
Emilian Peevaf8416e2021-02-04 17:52:43 -08005215 e = camera_metadata_ro_entry_t();
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08005216 find_camera_metadata_ro_entry(settings, ANDROID_CONTROL_ENABLE_ZSL, &e);
Shuzhen Wang26abaf42018-08-28 15:41:20 -07005217 if ((e.count > 0) && (e.data.u8[0] == ANDROID_CONTROL_ENABLE_ZSL_TRUE)) {
5218 isZslCapture = true;
5219 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01005220 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005221 res = parent->registerInFlight(halRequest->frame_number,
5222 totalNumBuffers, captureRequest->mResultExtras,
5223 /*hasInput*/halRequest->input_buffer != NULL,
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07005224 hasCallback,
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08005225 calculateMaxExpectedDuration(settings),
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005226 requestedPhysicalCameras, isStillCapture, isZslCapture,
5227 captureRequest->mRotateAndCropAuto, mPrevCameraIdsWithZoom,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005228 (mUseHalBufManager) ? uniqueSurfaceIdMap :
Shuzhen Wang316781a2020-08-18 18:11:01 -07005229 SurfaceMap{}, captureRequest->mRequestTimeNs);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005230 ALOGVV("%s: registered in flight requestId = %" PRId32 ", frameNumber = %" PRId64
5231 ", burstId = %" PRId32 ".",
5232 __FUNCTION__,
5233 captureRequest->mResultExtras.requestId, captureRequest->mResultExtras.frameNumber,
5234 captureRequest->mResultExtras.burstId);
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08005235
5236 if (shouldUnlockSettings) {
5237 captureRequest->mSettingsList.begin()->metadata.unlock(settings);
5238 }
5239
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005240 if (res != OK) {
5241 SET_ERR("RequestThread: Unable to register new in-flight request:"
5242 " %s (%d)", strerror(-res), res);
5243 return INVALID_OPERATION;
5244 }
5245 }
5246
5247 return OK;
5248}
5249
Igor Murashkin1e479c02013-09-06 16:55:14 -07005250CameraMetadata Camera3Device::RequestThread::getLatestRequest() const {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005251 ATRACE_CALL();
Igor Murashkin1e479c02013-09-06 16:55:14 -07005252 Mutex::Autolock al(mLatestRequestMutex);
5253
5254 ALOGV("RequestThread::%s", __FUNCTION__);
5255
5256 return mLatestRequest;
5257}
5258
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005259bool Camera3Device::RequestThread::isStreamPending(
5260 sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005261 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005262 Mutex::Autolock l(mRequestLock);
5263
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005264 for (const auto& nextRequest : mNextRequests) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005265 if (!nextRequest.submitted) {
5266 for (const auto& s : nextRequest.captureRequest->mOutputStreams) {
5267 if (stream == s) return true;
5268 }
5269 if (stream == nextRequest.captureRequest->mInputStream) return true;
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07005270 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07005271 }
5272
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005273 for (const auto& request : mRequestQueue) {
5274 for (const auto& s : request->mOutputStreams) {
5275 if (stream == s) return true;
5276 }
5277 if (stream == request->mInputStream) return true;
5278 }
5279
5280 for (const auto& request : mRepeatingRequests) {
5281 for (const auto& s : request->mOutputStreams) {
5282 if (stream == s) return true;
5283 }
5284 if (stream == request->mInputStream) return true;
5285 }
5286
5287 return false;
5288}
Jianing Weicb0652e2014-03-12 18:29:36 -07005289
Emilian Peev40ead602017-09-26 15:46:36 +01005290bool Camera3Device::RequestThread::isOutputSurfacePending(int streamId, size_t surfaceId) {
5291 ATRACE_CALL();
5292 Mutex::Autolock l(mRequestLock);
5293
5294 for (const auto& nextRequest : mNextRequests) {
5295 for (const auto& s : nextRequest.captureRequest->mOutputSurfaces) {
5296 if (s.first == streamId) {
5297 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
5298 if (it != s.second.end()) {
5299 return true;
5300 }
5301 }
5302 }
5303 }
5304
5305 for (const auto& request : mRequestQueue) {
5306 for (const auto& s : request->mOutputSurfaces) {
5307 if (s.first == streamId) {
5308 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
5309 if (it != s.second.end()) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005310 return true;
Emilian Peev40ead602017-09-26 15:46:36 +01005311 }
5312 }
5313 }
5314 }
5315
5316 for (const auto& request : mRepeatingRequests) {
5317 for (const auto& s : request->mOutputSurfaces) {
5318 if (s.first == streamId) {
5319 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
5320 if (it != s.second.end()) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005321 return true;
Emilian Peev40ead602017-09-26 15:46:36 +01005322 }
5323 }
5324 }
5325 }
5326
5327 return false;
5328}
5329
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07005330void Camera3Device::RequestThread::signalPipelineDrain(const std::vector<int>& streamIds) {
5331 if (!mUseHalBufManager) {
5332 ALOGE("%s called for camera device not supporting HAL buffer management", __FUNCTION__);
5333 return;
5334 }
5335
5336 Mutex::Autolock pl(mPauseLock);
5337 if (mPaused) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005338 mInterface->signalPipelineDrain(streamIds);
5339 return;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07005340 }
5341 // If request thread is still busy, wait until paused then notify HAL
5342 mNotifyPipelineDrain = true;
5343 mStreamIdsToBeDrained = streamIds;
5344}
5345
Yin-Chia Yehe52b8fa2020-07-28 00:17:58 -07005346void Camera3Device::RequestThread::resetPipelineDrain() {
5347 Mutex::Autolock pl(mPauseLock);
5348 mNotifyPipelineDrain = false;
5349 mStreamIdsToBeDrained.clear();
5350}
5351
Emilian Peevc0fe54c2020-03-11 14:05:07 -07005352void Camera3Device::RequestThread::clearPreviousRequest() {
5353 Mutex::Autolock l(mRequestLock);
5354 mPrevRequest.clear();
5355}
5356
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005357status_t Camera3Device::RequestThread::switchToOffline(
5358 const std::vector<int32_t>& streamsToKeep,
5359 /*out*/hardware::camera::device::V3_6::CameraOfflineSessionInfo* offlineSessionInfo,
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005360 /*out*/sp<hardware::camera::device::V3_6::ICameraOfflineSession>* offlineSession,
5361 /*out*/camera3::BufferRecords* bufferRecords) {
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005362 Mutex::Autolock l(mRequestLock);
5363 clearRepeatingRequestsLocked(/*lastFrameNumber*/nullptr);
5364
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005365 // Wait until request thread is fully stopped
5366 // TBD: check if request thread is being paused by other APIs (shouldn't be)
5367
5368 // We could also check for mRepeatingRequests.empty(), but the API interface
5369 // is serialized by Camera3Device::mInterfaceLock so no one should be able to submit any
5370 // new requests during the call; hence skip that check.
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005371 bool queueEmpty = mNextRequests.empty() && mRequestQueue.empty();
5372 while (!queueEmpty) {
5373 status_t res = mRequestSubmittedSignal.waitRelative(mRequestLock, kRequestSubmitTimeout);
5374 if (res == TIMED_OUT) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005375 ALOGE("%s: request thread failed to submit one request within timeout!", __FUNCTION__);
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005376 return res;
5377 } else if (res != OK) {
5378 ALOGE("%s: request thread failed to submit a request: %s (%d)!",
5379 __FUNCTION__, strerror(-res), res);
5380 return res;
5381 }
5382 queueEmpty = mNextRequests.empty() && mRequestQueue.empty();
5383 }
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005384
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005385 return mInterface->switchToOffline(
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005386 streamsToKeep, offlineSessionInfo, offlineSession, bufferRecords);
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005387}
5388
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005389status_t Camera3Device::RequestThread::setRotateAndCropAutoBehavior(
5390 camera_metadata_enum_android_scaler_rotate_and_crop_t rotateAndCropValue) {
5391 ATRACE_CALL();
5392 Mutex::Autolock l(mTriggerMutex);
5393 if (rotateAndCropValue == ANDROID_SCALER_ROTATE_AND_CROP_AUTO) {
5394 return BAD_VALUE;
5395 }
5396 mRotateAndCropOverride = rotateAndCropValue;
5397 return OK;
5398}
5399
Emilian Peeve23f1d92021-09-20 14:56:01 -07005400status_t Camera3Device::RequestThread::setComposerSurface(bool composerSurfacePresent) {
5401 ATRACE_CALL();
5402 Mutex::Autolock l(mTriggerMutex);
5403 mComposerOutput = composerSurfacePresent;
5404 return OK;
5405}
5406
Eino-Ville Talvala11afe4f2021-05-27 14:45:31 -07005407status_t Camera3Device::RequestThread::setCameraMute(int32_t muteMode) {
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005408 ATRACE_CALL();
5409 Mutex::Autolock l(mTriggerMutex);
Eino-Ville Talvala11afe4f2021-05-27 14:45:31 -07005410 if (muteMode != mCameraMute) {
5411 mCameraMute = muteMode;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005412 mCameraMuteChanged = true;
5413 }
5414 return OK;
5415}
5416
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07005417nsecs_t Camera3Device::getExpectedInFlightDuration() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005418 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005419 std::lock_guard<std::mutex> l(mInFlightLock);
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07005420 return mExpectedInflightDuration > kMinInflightDuration ?
5421 mExpectedInflightDuration : kMinInflightDuration;
5422}
5423
Emilian Peevaebbe412018-01-15 13:53:24 +00005424void Camera3Device::RequestThread::cleanupPhysicalSettings(sp<CaptureRequest> request,
Emilian Peevf4816702020-04-03 15:44:51 -07005425 camera_capture_request_t *halRequest) {
Emilian Peevaebbe412018-01-15 13:53:24 +00005426 if ((request == nullptr) || (halRequest == nullptr)) {
5427 ALOGE("%s: Invalid request!", __FUNCTION__);
5428 return;
5429 }
5430
5431 if (halRequest->num_physcam_settings > 0) {
5432 if (halRequest->physcam_id != nullptr) {
5433 delete [] halRequest->physcam_id;
5434 halRequest->physcam_id = nullptr;
5435 }
5436 if (halRequest->physcam_settings != nullptr) {
5437 auto it = ++(request->mSettingsList.begin());
5438 size_t i = 0;
5439 for (; it != request->mSettingsList.end(); it++, i++) {
5440 it->metadata.unlock(halRequest->physcam_settings[i]);
5441 }
5442 delete [] halRequest->physcam_settings;
5443 halRequest->physcam_settings = nullptr;
5444 }
5445 }
5446}
5447
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005448void Camera3Device::RequestThread::cleanUpFailedRequests(bool sendRequestError) {
5449 if (mNextRequests.empty()) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005450 return;
5451 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005452
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005453 for (auto& nextRequest : mNextRequests) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005454 // Skip the ones that have been submitted successfully.
5455 if (nextRequest.submitted) {
5456 continue;
5457 }
5458
5459 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
Emilian Peevf4816702020-04-03 15:44:51 -07005460 camera_capture_request_t* halRequest = &nextRequest.halRequest;
5461 Vector<camera_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005462
5463 if (halRequest->settings != NULL) {
Emilian Peevaebbe412018-01-15 13:53:24 +00005464 captureRequest->mSettingsList.begin()->metadata.unlock(halRequest->settings);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005465 }
5466
Emilian Peevaebbe412018-01-15 13:53:24 +00005467 cleanupPhysicalSettings(captureRequest, halRequest);
5468
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005469 if (captureRequest->mInputStream != NULL) {
Emilian Peevf4816702020-04-03 15:44:51 -07005470 captureRequest->mInputBuffer.status = CAMERA_BUFFER_STATUS_ERROR;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005471 captureRequest->mInputStream->returnInputBuffer(captureRequest->mInputBuffer);
5472 }
5473
Yin-Chia Yeh21cb47b2019-01-18 15:08:17 -08005474 // No output buffer can be returned when using HAL buffer manager
5475 if (!mUseHalBufManager) {
5476 for (size_t i = 0; i < halRequest->num_output_buffers; i++) {
5477 //Buffers that failed processing could still have
5478 //valid acquire fence.
5479 int acquireFence = (*outputBuffers)[i].acquire_fence;
5480 if (0 <= acquireFence) {
5481 close(acquireFence);
5482 outputBuffers->editItemAt(i).acquire_fence = -1;
5483 }
Emilian Peevf4816702020-04-03 15:44:51 -07005484 outputBuffers->editItemAt(i).status = CAMERA_BUFFER_STATUS_ERROR;
Shuzhen Wang90708ea2021-11-04 11:40:49 -07005485 captureRequest->mOutputStreams.editItemAt(i)->returnBuffer((*outputBuffers)[i],
5486 /*timestamp*/0, /*readoutTimestamp*/0,
Yin-Chia Yeh21cb47b2019-01-18 15:08:17 -08005487 /*timestampIncreasing*/true, std::vector<size_t> (),
5488 captureRequest->mResultExtras.frameNumber);
Emilian Peevc58cf4c2017-05-11 17:23:41 +01005489 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005490 }
5491
5492 if (sendRequestError) {
5493 Mutex::Autolock l(mRequestLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005494 sp<NotificationListener> listener = mListener.promote();
5495 if (listener != NULL) {
5496 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08005497 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005498 captureRequest->mResultExtras);
5499 }
5500 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07005501
5502 // Remove yet-to-be submitted inflight request from inflightMap
5503 {
5504 sp<Camera3Device> parent = mParent.promote();
5505 if (parent != NULL) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005506 std::lock_guard<std::mutex> l(parent->mInFlightLock);
Shuzhen Wangcadb3302016-11-04 14:17:56 -07005507 ssize_t idx = parent->mInFlightMap.indexOfKey(captureRequest->mResultExtras.frameNumber);
5508 if (idx >= 0) {
5509 ALOGV("%s: Remove inflight request from queue: frameNumber %" PRId64,
5510 __FUNCTION__, captureRequest->mResultExtras.frameNumber);
5511 parent->removeInFlightMapEntryLocked(idx);
5512 }
5513 }
5514 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005515 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07005516
5517 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005518 mNextRequests.clear();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005519}
5520
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005521void Camera3Device::RequestThread::waitForNextRequestBatch() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005522 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005523 // Optimized a bit for the simple steady-state case (single repeating
5524 // request), to avoid putting that request in the queue temporarily.
5525 Mutex::Autolock l(mRequestLock);
5526
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005527 assert(mNextRequests.empty());
5528
5529 NextRequest nextRequest;
5530 nextRequest.captureRequest = waitForNextRequestLocked();
5531 if (nextRequest.captureRequest == nullptr) {
5532 return;
5533 }
5534
Emilian Peevf4816702020-04-03 15:44:51 -07005535 nextRequest.halRequest = camera_capture_request_t();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005536 nextRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005537 mNextRequests.add(nextRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005538
5539 // Wait for additional requests
5540 const size_t batchSize = nextRequest.captureRequest->mBatchSize;
5541
5542 for (size_t i = 1; i < batchSize; i++) {
5543 NextRequest additionalRequest;
5544 additionalRequest.captureRequest = waitForNextRequestLocked();
5545 if (additionalRequest.captureRequest == nullptr) {
5546 break;
5547 }
5548
Emilian Peevf4816702020-04-03 15:44:51 -07005549 additionalRequest.halRequest = camera_capture_request_t();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005550 additionalRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005551 mNextRequests.add(additionalRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005552 }
5553
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005554 if (mNextRequests.size() < batchSize) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08005555 ALOGE("RequestThread: only get %zu out of %zu requests. Skipping requests.",
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005556 mNextRequests.size(), batchSize);
5557 cleanUpFailedRequests(/*sendRequestError*/true);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005558 }
5559
5560 return;
5561}
5562
5563sp<Camera3Device::CaptureRequest>
5564 Camera3Device::RequestThread::waitForNextRequestLocked() {
5565 status_t res;
5566 sp<CaptureRequest> nextRequest;
5567
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005568 while (mRequestQueue.empty()) {
5569 if (!mRepeatingRequests.empty()) {
5570 // Always atomically enqueue all requests in a repeating request
5571 // list. Guarantees a complete in-sequence set of captures to
5572 // application.
5573 const RequestList &requests = mRepeatingRequests;
Shuzhen Wang316781a2020-08-18 18:11:01 -07005574 if (mFirstRepeating) {
5575 mFirstRepeating = false;
5576 } else {
5577 for (auto& request : requests) {
5578 // For repeating requests, override timestamp request using
5579 // the time a request is inserted into the request queue,
5580 // because the original repeating request will have an old
5581 // fixed timestamp.
5582 request->mRequestTimeNs = systemTime();
5583 }
5584 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005585 RequestList::const_iterator firstRequest =
5586 requests.begin();
5587 nextRequest = *firstRequest;
5588 mRequestQueue.insert(mRequestQueue.end(),
5589 ++firstRequest,
5590 requests.end());
5591 // No need to wait any longer
Jianing Weicb0652e2014-03-12 18:29:36 -07005592
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005593 mRepeatingLastFrameNumber = mFrameNumber + requests.size() - 1;
Jianing Weicb0652e2014-03-12 18:29:36 -07005594
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005595 break;
5596 }
5597
5598 res = mRequestSignal.waitRelative(mRequestLock, kRequestTimeout);
5599
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005600 if ((mRequestQueue.empty() && mRepeatingRequests.empty()) ||
5601 exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005602 Mutex::Autolock pl(mPauseLock);
5603 if (mPaused == false) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005604 ALOGV("%s: RequestThread: Going idle", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005605 mPaused = true;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07005606 if (mNotifyPipelineDrain) {
5607 mInterface->signalPipelineDrain(mStreamIdsToBeDrained);
5608 mNotifyPipelineDrain = false;
5609 mStreamIdsToBeDrained.clear();
5610 }
Yin-Chia Yehc300a072019-02-13 14:56:57 -08005611 // Let the tracker know
5612 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5613 if (statusTracker != 0) {
5614 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
5615 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005616 sp<Camera3Device> parent = mParent.promote();
5617 if (parent != nullptr) {
5618 parent->mRequestBufferSM.onRequestThreadPaused();
5619 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005620 }
5621 // Stop waiting for now and let thread management happen
5622 return NULL;
5623 }
5624 }
5625
5626 if (nextRequest == NULL) {
5627 // Don't have a repeating request already in hand, so queue
5628 // must have an entry now.
5629 RequestList::iterator firstRequest =
5630 mRequestQueue.begin();
5631 nextRequest = *firstRequest;
5632 mRequestQueue.erase(firstRequest);
Shuzhen Wang9d066012016-09-30 11:30:20 -07005633 if (mRequestQueue.empty() && !nextRequest->mRepeating) {
5634 sp<NotificationListener> listener = mListener.promote();
5635 if (listener != NULL) {
5636 listener->notifyRequestQueueEmpty();
5637 }
5638 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005639 }
5640
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005641 // In case we've been unpaused by setPaused clearing mDoPause, need to
5642 // update internal pause state (capture/setRepeatingRequest unpause
5643 // directly).
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005644 Mutex::Autolock pl(mPauseLock);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005645 if (mPaused) {
5646 ALOGV("%s: RequestThread: Unpaused", __FUNCTION__);
5647 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5648 if (statusTracker != 0) {
5649 statusTracker->markComponentActive(mStatusId);
5650 }
5651 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005652 mPaused = false;
5653
5654 // Check if we've reconfigured since last time, and reset the preview
5655 // request if so. Can't use 'NULL request == repeat' across configure calls.
5656 if (mReconfigured) {
5657 mPrevRequest.clear();
5658 mReconfigured = false;
5659 }
5660
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005661 if (nextRequest != NULL) {
5662 nextRequest->mResultExtras.frameNumber = mFrameNumber++;
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07005663 nextRequest->mResultExtras.afTriggerId = mCurrentAfTriggerId;
5664 nextRequest->mResultExtras.precaptureTriggerId = mCurrentPreCaptureTriggerId;
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07005665
5666 // Since RequestThread::clear() removes buffers from the input stream,
5667 // get the right buffer here before unlocking mRequestLock
5668 if (nextRequest->mInputStream != NULL) {
Shuzhen Wang83bff122020-11-20 15:51:39 -08005669 res = nextRequest->mInputStream->getInputBuffer(&nextRequest->mInputBuffer,
5670 &nextRequest->mInputBufferSize);
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07005671 if (res != OK) {
5672 // Can't get input buffer from gralloc queue - this could be due to
5673 // disconnected queue or other producer misbehavior, so not a fatal
5674 // error
5675 ALOGE("%s: Can't get input buffer, skipping request:"
5676 " %s (%d)", __FUNCTION__, strerror(-res), res);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005677
5678 sp<NotificationListener> listener = mListener.promote();
5679 if (listener != NULL) {
5680 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08005681 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07005682 nextRequest->mResultExtras);
5683 }
5684 return NULL;
5685 }
5686 }
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005687 }
Chien-Yu Chend196d612015-06-22 19:49:01 -07005688
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005689 return nextRequest;
5690}
5691
5692bool Camera3Device::RequestThread::waitIfPaused() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005693 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005694 status_t res;
5695 Mutex::Autolock l(mPauseLock);
5696 while (mDoPause) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005697 if (mPaused == false) {
5698 mPaused = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005699 ALOGV("%s: RequestThread: Paused", __FUNCTION__);
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07005700 if (mNotifyPipelineDrain) {
5701 mInterface->signalPipelineDrain(mStreamIdsToBeDrained);
5702 mNotifyPipelineDrain = false;
5703 mStreamIdsToBeDrained.clear();
5704 }
Yin-Chia Yehc300a072019-02-13 14:56:57 -08005705 // Let the tracker know
5706 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5707 if (statusTracker != 0) {
5708 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
5709 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005710 sp<Camera3Device> parent = mParent.promote();
5711 if (parent != nullptr) {
5712 parent->mRequestBufferSM.onRequestThreadPaused();
5713 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005714 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005715
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005716 res = mDoPauseSignal.waitRelative(mPauseLock, kRequestTimeout);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005717 if (res == TIMED_OUT || exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005718 return true;
5719 }
5720 }
5721 // We don't set mPaused to false here, because waitForNextRequest needs
5722 // to further manage the paused state in case of starvation.
5723 return false;
5724}
5725
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005726void Camera3Device::RequestThread::unpauseForNewRequests() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005727 ATRACE_CALL();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005728 // With work to do, mark thread as unpaused.
5729 // If paused by request (setPaused), don't resume, to avoid
5730 // extra signaling/waiting overhead to waitUntilPaused
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005731 mRequestSignal.signal();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005732 Mutex::Autolock p(mPauseLock);
5733 if (!mDoPause) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005734 ALOGV("%s: RequestThread: Going active", __FUNCTION__);
5735 if (mPaused) {
5736 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5737 if (statusTracker != 0) {
5738 statusTracker->markComponentActive(mStatusId);
5739 }
5740 }
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005741 mPaused = false;
5742 }
5743}
5744
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07005745void Camera3Device::RequestThread::setErrorState(const char *fmt, ...) {
5746 sp<Camera3Device> parent = mParent.promote();
5747 if (parent != NULL) {
5748 va_list args;
5749 va_start(args, fmt);
5750
5751 parent->setErrorStateV(fmt, args);
5752
5753 va_end(args);
5754 }
5755}
5756
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005757status_t Camera3Device::RequestThread::insertTriggers(
5758 const sp<CaptureRequest> &request) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005759 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005760 Mutex::Autolock al(mTriggerMutex);
5761
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07005762 sp<Camera3Device> parent = mParent.promote();
5763 if (parent == NULL) {
5764 CLOGE("RequestThread: Parent is gone");
5765 return DEAD_OBJECT;
5766 }
5767
Emilian Peevaebbe412018-01-15 13:53:24 +00005768 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005769 size_t count = mTriggerMap.size();
5770
5771 for (size_t i = 0; i < count; ++i) {
5772 RequestTrigger trigger = mTriggerMap.valueAt(i);
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005773 uint32_t tag = trigger.metadataTag;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07005774
5775 if (tag == ANDROID_CONTROL_AF_TRIGGER_ID || tag == ANDROID_CONTROL_AE_PRECAPTURE_ID) {
5776 bool isAeTrigger = (trigger.metadataTag == ANDROID_CONTROL_AE_PRECAPTURE_ID);
5777 uint32_t triggerId = static_cast<uint32_t>(trigger.entryValue);
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07005778 if (isAeTrigger) {
5779 request->mResultExtras.precaptureTriggerId = triggerId;
5780 mCurrentPreCaptureTriggerId = triggerId;
5781 } else {
5782 request->mResultExtras.afTriggerId = triggerId;
5783 mCurrentAfTriggerId = triggerId;
5784 }
Emilian Peev7e25e5e2017-04-07 15:48:49 +01005785 continue;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07005786 }
5787
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005788 camera_metadata_entry entry = metadata.find(tag);
5789
5790 if (entry.count > 0) {
5791 /**
5792 * Already has an entry for this trigger in the request.
5793 * Rewrite it with our requested trigger value.
5794 */
5795 RequestTrigger oldTrigger = trigger;
5796
5797 oldTrigger.entryValue = entry.data.u8[0];
5798
5799 mTriggerReplacedMap.add(tag, oldTrigger);
5800 } else {
5801 /**
5802 * More typical, no trigger entry, so we just add it
5803 */
5804 mTriggerRemovedMap.add(tag, trigger);
5805 }
5806
5807 status_t res;
5808
5809 switch (trigger.getTagType()) {
5810 case TYPE_BYTE: {
5811 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
5812 res = metadata.update(tag,
5813 &entryValue,
5814 /*count*/1);
5815 break;
5816 }
5817 case TYPE_INT32:
5818 res = metadata.update(tag,
5819 &trigger.entryValue,
5820 /*count*/1);
5821 break;
5822 default:
5823 ALOGE("%s: Type not supported: 0x%x",
5824 __FUNCTION__,
5825 trigger.getTagType());
5826 return INVALID_OPERATION;
5827 }
5828
5829 if (res != OK) {
5830 ALOGE("%s: Failed to update request metadata with trigger tag %s"
5831 ", value %d", __FUNCTION__, trigger.getTagName(),
5832 trigger.entryValue);
5833 return res;
5834 }
5835
5836 ALOGV("%s: Mixed in trigger %s, value %d", __FUNCTION__,
5837 trigger.getTagName(),
5838 trigger.entryValue);
5839 }
5840
5841 mTriggerMap.clear();
5842
5843 return count;
5844}
5845
5846status_t Camera3Device::RequestThread::removeTriggers(
5847 const sp<CaptureRequest> &request) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005848 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005849 Mutex::Autolock al(mTriggerMutex);
5850
Emilian Peevaebbe412018-01-15 13:53:24 +00005851 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005852
5853 /**
5854 * Replace all old entries with their old values.
5855 */
5856 for (size_t i = 0; i < mTriggerReplacedMap.size(); ++i) {
5857 RequestTrigger trigger = mTriggerReplacedMap.valueAt(i);
5858
5859 status_t res;
5860
5861 uint32_t tag = trigger.metadataTag;
5862 switch (trigger.getTagType()) {
5863 case TYPE_BYTE: {
5864 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
5865 res = metadata.update(tag,
5866 &entryValue,
5867 /*count*/1);
5868 break;
5869 }
5870 case TYPE_INT32:
5871 res = metadata.update(tag,
5872 &trigger.entryValue,
5873 /*count*/1);
5874 break;
5875 default:
5876 ALOGE("%s: Type not supported: 0x%x",
5877 __FUNCTION__,
5878 trigger.getTagType());
5879 return INVALID_OPERATION;
5880 }
5881
5882 if (res != OK) {
5883 ALOGE("%s: Failed to restore request metadata with trigger tag %s"
5884 ", trigger value %d", __FUNCTION__,
5885 trigger.getTagName(), trigger.entryValue);
5886 return res;
5887 }
5888 }
5889 mTriggerReplacedMap.clear();
5890
5891 /**
5892 * Remove all new entries.
5893 */
5894 for (size_t i = 0; i < mTriggerRemovedMap.size(); ++i) {
5895 RequestTrigger trigger = mTriggerRemovedMap.valueAt(i);
5896 status_t res = metadata.erase(trigger.metadataTag);
5897
5898 if (res != OK) {
5899 ALOGE("%s: Failed to erase metadata with trigger tag %s"
5900 ", trigger value %d", __FUNCTION__,
5901 trigger.getTagName(), trigger.entryValue);
5902 return res;
5903 }
5904 }
5905 mTriggerRemovedMap.clear();
5906
5907 return OK;
5908}
5909
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04005910status_t Camera3Device::RequestThread::addFakeTriggerIds(
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005911 const sp<CaptureRequest> &request) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08005912 // Trigger ID 0 had special meaning in the HAL2 spec, so avoid it here
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04005913 static const int32_t fakeTriggerId = 1;
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005914 status_t res;
5915
Emilian Peevaebbe412018-01-15 13:53:24 +00005916 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005917
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04005918 // If AF trigger is active, insert a fake AF trigger ID if none already
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005919 // exists
5920 camera_metadata_entry afTrigger = metadata.find(ANDROID_CONTROL_AF_TRIGGER);
5921 camera_metadata_entry afId = metadata.find(ANDROID_CONTROL_AF_TRIGGER_ID);
5922 if (afTrigger.count > 0 &&
5923 afTrigger.data.u8[0] != ANDROID_CONTROL_AF_TRIGGER_IDLE &&
5924 afId.count == 0) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04005925 res = metadata.update(ANDROID_CONTROL_AF_TRIGGER_ID, &fakeTriggerId, 1);
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005926 if (res != OK) return res;
5927 }
5928
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04005929 // If AE precapture trigger is active, insert a fake precapture trigger ID
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005930 // if none already exists
5931 camera_metadata_entry pcTrigger =
5932 metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER);
5933 camera_metadata_entry pcId = metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_ID);
5934 if (pcTrigger.count > 0 &&
5935 pcTrigger.data.u8[0] != ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_IDLE &&
5936 pcId.count == 0) {
5937 res = metadata.update(ANDROID_CONTROL_AE_PRECAPTURE_ID,
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04005938 &fakeTriggerId, 1);
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005939 if (res != OK) return res;
5940 }
5941
5942 return OK;
5943}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005944
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005945bool Camera3Device::RequestThread::overrideAutoRotateAndCrop(
5946 const sp<CaptureRequest> &request) {
5947 ATRACE_CALL();
5948
5949 if (request->mRotateAndCropAuto) {
5950 Mutex::Autolock l(mTriggerMutex);
5951 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
5952
5953 auto rotateAndCropEntry = metadata.find(ANDROID_SCALER_ROTATE_AND_CROP);
5954 if (rotateAndCropEntry.count > 0) {
5955 if (rotateAndCropEntry.data.u8[0] == mRotateAndCropOverride) {
5956 return false;
5957 } else {
5958 rotateAndCropEntry.data.u8[0] = mRotateAndCropOverride;
5959 return true;
5960 }
5961 } else {
5962 uint8_t rotateAndCrop_u8 = mRotateAndCropOverride;
5963 metadata.update(ANDROID_SCALER_ROTATE_AND_CROP,
5964 &rotateAndCrop_u8, 1);
5965 return true;
5966 }
5967 }
5968 return false;
5969}
5970
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005971bool Camera3Device::RequestThread::overrideTestPattern(
5972 const sp<CaptureRequest> &request) {
5973 ATRACE_CALL();
5974
Eino-Ville Talvala1646c3c2021-07-29 13:48:40 -07005975 if (!mSupportCameraMute) return false;
Eino-Ville Talvalac2459842021-07-22 16:36:36 -07005976
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005977 Mutex::Autolock l(mTriggerMutex);
5978
5979 bool changed = false;
5980
Shuzhen Wang911c6a32021-10-27 13:36:03 -07005981 // For a multi-camera, the physical cameras support the same set of
5982 // test pattern modes as the logical camera.
5983 for (auto& settings : request->mSettingsList) {
5984 CameraMetadata &metadata = settings.metadata;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005985
Shuzhen Wang911c6a32021-10-27 13:36:03 -07005986 int32_t testPatternMode = settings.mOriginalTestPatternMode;
5987 int32_t testPatternData[4] = {
5988 settings.mOriginalTestPatternData[0],
5989 settings.mOriginalTestPatternData[1],
5990 settings.mOriginalTestPatternData[2],
5991 settings.mOriginalTestPatternData[3]
5992 };
5993 if (mCameraMute != ANDROID_SENSOR_TEST_PATTERN_MODE_OFF) {
5994 testPatternMode = mCameraMute;
5995 testPatternData[0] = 0;
5996 testPatternData[1] = 0;
5997 testPatternData[2] = 0;
5998 testPatternData[3] = 0;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005999 }
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08006000
Shuzhen Wang911c6a32021-10-27 13:36:03 -07006001 auto testPatternEntry = metadata.find(ANDROID_SENSOR_TEST_PATTERN_MODE);
6002 bool supportTestPatternModeKey = settings.mHasTestPatternModeTag;
6003 if (testPatternEntry.count > 0) {
6004 if (testPatternEntry.data.i32[0] != testPatternMode) {
6005 testPatternEntry.data.i32[0] = testPatternMode;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08006006 changed = true;
6007 }
Shuzhen Wang911c6a32021-10-27 13:36:03 -07006008 } else if (supportTestPatternModeKey) {
6009 metadata.update(ANDROID_SENSOR_TEST_PATTERN_MODE,
6010 &testPatternMode, 1);
6011 changed = true;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08006012 }
Shuzhen Wang911c6a32021-10-27 13:36:03 -07006013
6014 auto testPatternColor = metadata.find(ANDROID_SENSOR_TEST_PATTERN_DATA);
6015 bool supportTestPatternDataKey = settings.mHasTestPatternDataTag;
6016 if (testPatternColor.count >= 4) {
6017 for (size_t i = 0; i < 4; i++) {
6018 if (testPatternColor.data.i32[i] != testPatternData[i]) {
6019 testPatternColor.data.i32[i] = testPatternData[i];
6020 changed = true;
6021 }
6022 }
6023 } else if (supportTestPatternDataKey) {
6024 metadata.update(ANDROID_SENSOR_TEST_PATTERN_DATA,
6025 testPatternData, 4);
6026 changed = true;
6027 }
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08006028 }
6029
6030 return changed;
6031}
6032
Cliff Wuc2ad9c82021-04-21 00:58:58 +08006033status_t Camera3Device::RequestThread::setHalInterface(
6034 sp<HalInterface> newHalInterface) {
6035 if (newHalInterface.get() == nullptr) {
6036 ALOGE("%s: The newHalInterface does not exist!", __FUNCTION__);
6037 return DEAD_OBJECT;
6038 }
6039
6040 mInterface = newHalInterface;
6041
6042 return OK;
6043}
6044
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006045/**
6046 * PreparerThread inner class methods
6047 */
6048
6049Camera3Device::PreparerThread::PreparerThread() :
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07006050 Thread(/*canCallJava*/false), mListener(nullptr),
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006051 mActive(false), mCancelNow(false), mCurrentMaxCount(0), mCurrentPrepareComplete(false) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006052}
6053
6054Camera3Device::PreparerThread::~PreparerThread() {
6055 Thread::requestExitAndWait();
6056 if (mCurrentStream != nullptr) {
6057 mCurrentStream->cancelPrepare();
6058 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
6059 mCurrentStream.clear();
6060 }
6061 clear();
6062}
6063
Ruben Brunkc78ac262015-08-13 17:58:46 -07006064status_t Camera3Device::PreparerThread::prepare(int maxCount, sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07006065 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006066 status_t res;
6067
6068 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006069 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006070
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07006071 res = stream->startPrepare(maxCount, true /*blockRequest*/);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006072 if (res == OK) {
6073 // No preparation needed, fire listener right off
6074 ALOGV("%s: Stream %d already prepared", __FUNCTION__, stream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006075 if (listener != NULL) {
6076 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006077 }
6078 return OK;
6079 } else if (res != NOT_ENOUGH_DATA) {
6080 return res;
6081 }
6082
6083 // Need to prepare, start up thread if necessary
6084 if (!mActive) {
6085 // mRunning will change to false before the thread fully shuts down, so wait to be sure it
6086 // isn't running
6087 Thread::requestExitAndWait();
6088 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
6089 if (res != OK) {
6090 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__, res, strerror(-res));
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006091 if (listener != NULL) {
6092 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006093 }
6094 return res;
6095 }
6096 mCancelNow = false;
6097 mActive = true;
6098 ALOGV("%s: Preparer stream started", __FUNCTION__);
6099 }
6100
6101 // queue up the work
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006102 mPendingStreams.emplace(maxCount, stream);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006103 ALOGV("%s: Stream %d queued for preparing", __FUNCTION__, stream->getId());
6104
6105 return OK;
6106}
6107
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006108void Camera3Device::PreparerThread::pause() {
6109 ATRACE_CALL();
6110
6111 Mutex::Autolock l(mLock);
6112
6113 std::unordered_map<int, sp<camera3::Camera3StreamInterface> > pendingStreams;
6114 pendingStreams.insert(mPendingStreams.begin(), mPendingStreams.end());
6115 sp<camera3::Camera3StreamInterface> currentStream = mCurrentStream;
6116 int currentMaxCount = mCurrentMaxCount;
6117 mPendingStreams.clear();
6118 mCancelNow = true;
6119 while (mActive) {
6120 auto res = mThreadActiveSignal.waitRelative(mLock, kActiveTimeout);
6121 if (res == TIMED_OUT) {
6122 ALOGE("%s: Timed out waiting on prepare thread!", __FUNCTION__);
6123 return;
6124 } else if (res != OK) {
6125 ALOGE("%s: Encountered an error: %d waiting on prepare thread!", __FUNCTION__, res);
6126 return;
6127 }
6128 }
6129
6130 //Check whether the prepare thread was able to complete the current
6131 //stream. In case work is still pending emplace it along with the rest
6132 //of the streams in the pending list.
6133 if (currentStream != nullptr) {
6134 if (!mCurrentPrepareComplete) {
6135 pendingStreams.emplace(currentMaxCount, currentStream);
6136 }
6137 }
6138
6139 mPendingStreams.insert(pendingStreams.begin(), pendingStreams.end());
6140 for (const auto& it : mPendingStreams) {
6141 it.second->cancelPrepare();
6142 }
6143}
6144
6145status_t Camera3Device::PreparerThread::resume() {
6146 ATRACE_CALL();
6147 status_t res;
6148
6149 Mutex::Autolock l(mLock);
6150 sp<NotificationListener> listener = mListener.promote();
6151
6152 if (mActive) {
6153 ALOGE("%s: Trying to resume an already active prepare thread!", __FUNCTION__);
6154 return NO_INIT;
6155 }
6156
6157 auto it = mPendingStreams.begin();
6158 for (; it != mPendingStreams.end();) {
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07006159 res = it->second->startPrepare(it->first, true /*blockRequest*/);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006160 if (res == OK) {
6161 if (listener != NULL) {
6162 listener->notifyPrepared(it->second->getId());
6163 }
6164 it = mPendingStreams.erase(it);
6165 } else if (res != NOT_ENOUGH_DATA) {
6166 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__,
6167 res, strerror(-res));
6168 it = mPendingStreams.erase(it);
6169 } else {
6170 it++;
6171 }
6172 }
6173
6174 if (mPendingStreams.empty()) {
6175 return OK;
6176 }
6177
6178 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
6179 if (res != OK) {
6180 ALOGE("%s: Unable to start preparer stream: %d (%s)",
6181 __FUNCTION__, res, strerror(-res));
6182 return res;
6183 }
6184 mCancelNow = false;
6185 mActive = true;
6186 ALOGV("%s: Preparer stream started", __FUNCTION__);
6187
6188 return OK;
6189}
6190
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006191status_t Camera3Device::PreparerThread::clear() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07006192 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006193 Mutex::Autolock l(mLock);
6194
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006195 for (const auto& it : mPendingStreams) {
6196 it.second->cancelPrepare();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006197 }
6198 mPendingStreams.clear();
6199 mCancelNow = true;
6200
6201 return OK;
6202}
6203
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006204void Camera3Device::PreparerThread::setNotificationListener(wp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07006205 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006206 Mutex::Autolock l(mLock);
6207 mListener = listener;
6208}
6209
6210bool Camera3Device::PreparerThread::threadLoop() {
6211 status_t res;
6212 {
6213 Mutex::Autolock l(mLock);
6214 if (mCurrentStream == nullptr) {
6215 // End thread if done with work
6216 if (mPendingStreams.empty()) {
6217 ALOGV("%s: Preparer stream out of work", __FUNCTION__);
6218 // threadLoop _must not_ re-acquire mLock after it sets mActive to false; would
6219 // cause deadlock with prepare()'s requestExitAndWait triggered by !mActive.
6220 mActive = false;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006221 mThreadActiveSignal.signal();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006222 return false;
6223 }
6224
6225 // Get next stream to prepare
6226 auto it = mPendingStreams.begin();
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006227 mCurrentStream = it->second;
6228 mCurrentMaxCount = it->first;
6229 mCurrentPrepareComplete = false;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006230 mPendingStreams.erase(it);
6231 ATRACE_ASYNC_BEGIN("stream prepare", mCurrentStream->getId());
6232 ALOGV("%s: Preparing stream %d", __FUNCTION__, mCurrentStream->getId());
6233 } else if (mCancelNow) {
6234 mCurrentStream->cancelPrepare();
6235 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
6236 ALOGV("%s: Cancelling stream %d prepare", __FUNCTION__, mCurrentStream->getId());
6237 mCurrentStream.clear();
6238 mCancelNow = false;
6239 return true;
6240 }
6241 }
6242
6243 res = mCurrentStream->prepareNextBuffer();
6244 if (res == NOT_ENOUGH_DATA) return true;
6245 if (res != OK) {
6246 // Something bad happened; try to recover by cancelling prepare and
6247 // signalling listener anyway
6248 ALOGE("%s: Stream %d returned error %d (%s) during prepare", __FUNCTION__,
6249 mCurrentStream->getId(), res, strerror(-res));
6250 mCurrentStream->cancelPrepare();
6251 }
6252
6253 // This stream has finished, notify listener
6254 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006255 sp<NotificationListener> listener = mListener.promote();
6256 if (listener != NULL) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006257 ALOGV("%s: Stream %d prepare done, signaling listener", __FUNCTION__,
6258 mCurrentStream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006259 listener->notifyPrepared(mCurrentStream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006260 }
6261
6262 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
6263 mCurrentStream.clear();
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006264 mCurrentPrepareComplete = true;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006265
6266 return true;
6267}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07006268
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006269status_t Camera3Device::RequestBufferStateMachine::initialize(
6270 sp<camera3::StatusTracker> statusTracker) {
6271 if (statusTracker == nullptr) {
6272 ALOGE("%s: statusTracker is null", __FUNCTION__);
6273 return BAD_VALUE;
6274 }
6275
6276 std::lock_guard<std::mutex> lock(mLock);
6277 mStatusTracker = statusTracker;
Yin-Chia Yeh87b3ec02019-06-03 10:44:39 -07006278 mRequestBufferStatusId = statusTracker->addComponent("BufferRequestSM");
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006279 return OK;
6280}
6281
6282bool Camera3Device::RequestBufferStateMachine::startRequestBuffer() {
6283 std::lock_guard<std::mutex> lock(mLock);
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08006284 if (mStatus == RB_STATUS_READY || mStatus == RB_STATUS_PENDING_STOP) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006285 mRequestBufferOngoing = true;
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08006286 notifyTrackerLocked(/*active*/true);
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006287 return true;
6288 }
6289 return false;
6290}
6291
6292void Camera3Device::RequestBufferStateMachine::endRequestBuffer() {
6293 std::lock_guard<std::mutex> lock(mLock);
6294 if (!mRequestBufferOngoing) {
6295 ALOGE("%s called without a successful startRequestBuffer call first!", __FUNCTION__);
6296 return;
6297 }
6298 mRequestBufferOngoing = false;
6299 if (mStatus == RB_STATUS_PENDING_STOP) {
6300 checkSwitchToStopLocked();
6301 }
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08006302 notifyTrackerLocked(/*active*/false);
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006303}
6304
6305void Camera3Device::RequestBufferStateMachine::onStreamsConfigured() {
6306 std::lock_guard<std::mutex> lock(mLock);
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006307 mSwitchedToOffline = false;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006308 mStatus = RB_STATUS_READY;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006309 return;
6310}
6311
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08006312void Camera3Device::RequestBufferStateMachine::onSubmittingRequest() {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006313 std::lock_guard<std::mutex> lock(mLock);
6314 mRequestThreadPaused = false;
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08006315 // inflight map register actually happens in prepareHalRequest now, but it is close enough
6316 // approximation.
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006317 mInflightMapEmpty = false;
6318 if (mStatus == RB_STATUS_STOPPED) {
6319 mStatus = RB_STATUS_READY;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006320 }
6321 return;
6322}
6323
6324void Camera3Device::RequestBufferStateMachine::onRequestThreadPaused() {
6325 std::lock_guard<std::mutex> lock(mLock);
6326 mRequestThreadPaused = true;
6327 if (mStatus == RB_STATUS_PENDING_STOP) {
6328 checkSwitchToStopLocked();
6329 }
6330 return;
6331}
6332
6333void Camera3Device::RequestBufferStateMachine::onInflightMapEmpty() {
6334 std::lock_guard<std::mutex> lock(mLock);
6335 mInflightMapEmpty = true;
6336 if (mStatus == RB_STATUS_PENDING_STOP) {
6337 checkSwitchToStopLocked();
6338 }
6339 return;
6340}
6341
6342void Camera3Device::RequestBufferStateMachine::onWaitUntilIdle() {
6343 std::lock_guard<std::mutex> lock(mLock);
6344 if (!checkSwitchToStopLocked()) {
6345 mStatus = RB_STATUS_PENDING_STOP;
6346 }
6347 return;
6348}
6349
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006350bool Camera3Device::RequestBufferStateMachine::onSwitchToOfflineSuccess() {
6351 std::lock_guard<std::mutex> lock(mLock);
6352 if (mRequestBufferOngoing) {
6353 ALOGE("%s: HAL must not be requesting buffer after HAL returns switchToOffline!",
6354 __FUNCTION__);
6355 return false;
6356 }
6357 mSwitchedToOffline = true;
6358 mInflightMapEmpty = true;
6359 mRequestThreadPaused = true;
6360 mStatus = RB_STATUS_STOPPED;
6361 return true;
6362}
6363
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006364void Camera3Device::RequestBufferStateMachine::notifyTrackerLocked(bool active) {
6365 sp<StatusTracker> statusTracker = mStatusTracker.promote();
6366 if (statusTracker != nullptr) {
6367 if (active) {
6368 statusTracker->markComponentActive(mRequestBufferStatusId);
6369 } else {
6370 statusTracker->markComponentIdle(mRequestBufferStatusId, Fence::NO_FENCE);
6371 }
6372 }
6373}
6374
6375bool Camera3Device::RequestBufferStateMachine::checkSwitchToStopLocked() {
6376 if (mInflightMapEmpty && mRequestThreadPaused && !mRequestBufferOngoing) {
6377 mStatus = RB_STATUS_STOPPED;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006378 return true;
6379 }
6380 return false;
6381}
6382
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006383bool Camera3Device::startRequestBuffer() {
6384 return mRequestBufferSM.startRequestBuffer();
6385}
Shuzhen Wang268a1362018-10-16 16:32:59 -07006386
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006387void Camera3Device::endRequestBuffer() {
6388 mRequestBufferSM.endRequestBuffer();
6389}
Shuzhen Wang268a1362018-10-16 16:32:59 -07006390
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006391nsecs_t Camera3Device::getWaitDuration() {
6392 return kBaseGetBufferWait + getExpectedInFlightDuration();
6393}
Shuzhen Wang268a1362018-10-16 16:32:59 -07006394
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006395void Camera3Device::getInflightBufferKeys(std::vector<std::pair<int32_t, int32_t>>* out) {
6396 mInterface->getInflightBufferKeys(out);
6397}
Shuzhen Wang268a1362018-10-16 16:32:59 -07006398
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006399void Camera3Device::getInflightRequestBufferKeys(std::vector<uint64_t>* out) {
6400 mInterface->getInflightRequestBufferKeys(out);
6401}
Shuzhen Wang268a1362018-10-16 16:32:59 -07006402
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006403std::vector<sp<Camera3StreamInterface>> Camera3Device::getAllStreams() {
6404 std::vector<sp<Camera3StreamInterface>> ret;
6405 bool hasInputStream = mInputStream != nullptr;
6406 ret.reserve(mOutputStreams.size() + mDeletedStreams.size() + ((hasInputStream) ? 1 : 0));
6407 if (hasInputStream) {
6408 ret.push_back(mInputStream);
Shuzhen Wang268a1362018-10-16 16:32:59 -07006409 }
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006410 for (size_t i = 0; i < mOutputStreams.size(); i++) {
6411 ret.push_back(mOutputStreams[i]);
6412 }
6413 for (size_t i = 0; i < mDeletedStreams.size(); i++) {
6414 ret.push_back(mDeletedStreams[i]);
6415 }
6416 return ret;
Shuzhen Wang268a1362018-10-16 16:32:59 -07006417}
6418
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006419status_t Camera3Device::switchToOffline(
6420 const std::vector<int32_t>& streamsToKeep,
6421 /*out*/ sp<CameraOfflineSessionBase>* session) {
6422 ATRACE_CALL();
6423 if (session == nullptr) {
6424 ALOGE("%s: session must not be null", __FUNCTION__);
6425 return BAD_VALUE;
6426 }
6427
6428 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006429
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006430 bool hasInputStream = mInputStream != nullptr;
6431 int32_t inputStreamId = hasInputStream ? mInputStream->getId() : -1;
6432 bool inputStreamSupportsOffline = hasInputStream ?
6433 mInputStream->getOfflineProcessingSupport() : false;
6434 auto outputStreamIds = mOutputStreams.getStreamIds();
6435 auto streamIds = outputStreamIds;
6436 if (hasInputStream) {
6437 streamIds.push_back(mInputStream->getId());
6438 }
6439
6440 // Check all streams in streamsToKeep supports offline mode
6441 for (auto id : streamsToKeep) {
6442 if (std::find(streamIds.begin(), streamIds.end(), id) == streamIds.end()) {
6443 ALOGE("%s: Unknown stream ID %d", __FUNCTION__, id);
6444 return BAD_VALUE;
6445 } else if (id == inputStreamId) {
6446 if (!inputStreamSupportsOffline) {
6447 ALOGE("%s: input stream %d cannot be switched to offline",
6448 __FUNCTION__, id);
6449 return BAD_VALUE;
6450 }
6451 } else {
6452 sp<camera3::Camera3OutputStreamInterface> stream = mOutputStreams.get(id);
6453 if (!stream->getOfflineProcessingSupport()) {
6454 ALOGE("%s: output stream %d cannot be switched to offline",
6455 __FUNCTION__, id);
6456 return BAD_VALUE;
6457 }
6458 }
6459 }
6460
6461 // TODO: block surface sharing and surface group streams until we can support them
6462
6463 // Stop repeating request, wait until all remaining requests are submitted, then call into
6464 // HAL switchToOffline
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006465 hardware::camera::device::V3_6::CameraOfflineSessionInfo offlineSessionInfo;
6466 sp<hardware::camera::device::V3_6::ICameraOfflineSession> offlineSession;
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006467 camera3::BufferRecords bufferRecords;
6468 status_t ret = mRequestThread->switchToOffline(
6469 streamsToKeep, &offlineSessionInfo, &offlineSession, &bufferRecords);
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006470
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006471 if (ret != OK) {
6472 SET_ERR("Switch to offline failed: %s (%d)", strerror(-ret), ret);
6473 return ret;
6474 }
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006475
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006476 bool succ = mRequestBufferSM.onSwitchToOfflineSuccess();
6477 if (!succ) {
6478 SET_ERR("HAL must not be calling requestStreamBuffers call");
6479 // TODO: block ALL callbacks from HAL till app configured new streams?
6480 return UNKNOWN_ERROR;
6481 }
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006482
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006483 // Verify offlineSessionInfo
6484 std::vector<int32_t> offlineStreamIds;
6485 offlineStreamIds.reserve(offlineSessionInfo.offlineStreams.size());
6486 for (auto offlineStream : offlineSessionInfo.offlineStreams) {
6487 // verify stream IDs
6488 int32_t id = offlineStream.id;
6489 if (std::find(streamIds.begin(), streamIds.end(), id) == streamIds.end()) {
6490 SET_ERR("stream ID %d not found!", id);
6491 return UNKNOWN_ERROR;
6492 }
6493
6494 // When not using HAL buf manager, only allow streams requested by app to be preserved
6495 if (!mUseHalBufManager) {
6496 if (std::find(streamsToKeep.begin(), streamsToKeep.end(), id) == streamsToKeep.end()) {
6497 SET_ERR("stream ID %d must not be switched to offline!", id);
6498 return UNKNOWN_ERROR;
6499 }
6500 }
6501
6502 offlineStreamIds.push_back(id);
6503 sp<Camera3StreamInterface> stream = (id == inputStreamId) ?
6504 static_cast<sp<Camera3StreamInterface>>(mInputStream) :
6505 static_cast<sp<Camera3StreamInterface>>(mOutputStreams.get(id));
6506 // Verify number of outstanding buffers
6507 if (stream->getOutstandingBuffersCount() != offlineStream.numOutstandingBuffers) {
6508 SET_ERR("Offline stream %d # of remaining buffer mismatch: (%zu,%d) (service/HAL)",
6509 id, stream->getOutstandingBuffersCount(), offlineStream.numOutstandingBuffers);
6510 return UNKNOWN_ERROR;
6511 }
6512 }
6513
6514 // Verify all streams to be deleted don't have any outstanding buffers
6515 if (hasInputStream && std::find(offlineStreamIds.begin(), offlineStreamIds.end(),
6516 inputStreamId) == offlineStreamIds.end()) {
6517 if (mInputStream->hasOutstandingBuffers()) {
6518 SET_ERR("Input stream %d still has %zu outstanding buffer!",
6519 inputStreamId, mInputStream->getOutstandingBuffersCount());
6520 return UNKNOWN_ERROR;
6521 }
6522 }
6523
6524 for (const auto& outStreamId : outputStreamIds) {
6525 if (std::find(offlineStreamIds.begin(), offlineStreamIds.end(),
6526 outStreamId) == offlineStreamIds.end()) {
6527 auto outStream = mOutputStreams.get(outStreamId);
6528 if (outStream->hasOutstandingBuffers()) {
6529 SET_ERR("Output stream %d still has %zu outstanding buffer!",
6530 outStreamId, outStream->getOutstandingBuffersCount());
6531 return UNKNOWN_ERROR;
6532 }
6533 }
6534 }
6535
6536 InFlightRequestMap offlineReqs;
6537 // Verify inflight requests and their pending buffers
6538 {
6539 std::lock_guard<std::mutex> l(mInFlightLock);
6540 for (auto offlineReq : offlineSessionInfo.offlineRequests) {
6541 int idx = mInFlightMap.indexOfKey(offlineReq.frameNumber);
6542 if (idx == NAME_NOT_FOUND) {
6543 SET_ERR("Offline request frame number %d not found!", offlineReq.frameNumber);
6544 return UNKNOWN_ERROR;
6545 }
6546
6547 const auto& inflightReq = mInFlightMap.valueAt(idx);
6548 // TODO: check specific stream IDs
6549 size_t numBuffersLeft = static_cast<size_t>(inflightReq.numBuffersLeft);
6550 if (numBuffersLeft != offlineReq.pendingStreams.size()) {
6551 SET_ERR("Offline request # of remaining buffer mismatch: (%d,%d) (service/HAL)",
6552 inflightReq.numBuffersLeft, offlineReq.pendingStreams.size());
6553 return UNKNOWN_ERROR;
6554 }
6555 offlineReqs.add(offlineReq.frameNumber, inflightReq);
6556 }
6557 }
6558
6559 // Create Camera3OfflineSession and transfer object ownership
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006560 // (streams, inflight requests, buffer caches)
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006561 camera3::StreamSet offlineStreamSet;
6562 sp<camera3::Camera3Stream> inputStream;
6563 for (auto offlineStream : offlineSessionInfo.offlineStreams) {
6564 int32_t id = offlineStream.id;
6565 if (mInputStream != nullptr && id == mInputStream->getId()) {
6566 inputStream = mInputStream;
6567 } else {
6568 offlineStreamSet.add(id, mOutputStreams.get(id));
6569 }
6570 }
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006571
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006572 // TODO: check if we need to lock before copying states
6573 // though technically no other thread should be talking to Camera3Device at this point
6574 Camera3OfflineStates offlineStates(
6575 mTagMonitor, mVendorTagId, mUseHalBufManager, mNeedFixupMonochromeTags,
Shuzhen Wangb7b42652020-05-07 11:59:02 -07006576 mUsePartialResult, mNumPartialResults, mLastCompletedRegularFrameNumber,
6577 mLastCompletedReprocessFrameNumber, mLastCompletedZslFrameNumber,
6578 mNextResultFrameNumber, mNextReprocessResultFrameNumber,
6579 mNextZslStillResultFrameNumber, mNextShutterFrameNumber,
6580 mNextReprocessShutterFrameNumber, mNextZslStillShutterFrameNumber,
6581 mDeviceInfo, mPhysicalDeviceInfoMap, mDistortionMappers,
6582 mZoomRatioMappers, mRotateAndCropMappers);
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006583
6584 *session = new Camera3OfflineSession(mId, inputStream, offlineStreamSet,
6585 std::move(bufferRecords), offlineReqs, offlineStates, offlineSession);
6586
6587 // Delete all streams that has been transferred to offline session
6588 Mutex::Autolock l(mLock);
6589 for (auto offlineStream : offlineSessionInfo.offlineStreams) {
6590 int32_t id = offlineStream.id;
6591 if (mInputStream != nullptr && id == mInputStream->getId()) {
6592 mInputStream.clear();
6593 } else {
6594 mOutputStreams.remove(id);
6595 }
6596 }
6597
6598 // disconnect all other streams and switch to UNCONFIGURED state
6599 if (mInputStream != nullptr) {
6600 ret = mInputStream->disconnect();
6601 if (ret != OK) {
6602 SET_ERR_L("disconnect input stream failed!");
6603 return UNKNOWN_ERROR;
6604 }
6605 }
6606
6607 for (auto streamId : mOutputStreams.getStreamIds()) {
6608 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
6609 ret = stream->disconnect();
6610 if (ret != OK) {
6611 SET_ERR_L("disconnect output stream %d failed!", streamId);
6612 return UNKNOWN_ERROR;
6613 }
6614 }
6615
6616 mInputStream.clear();
6617 mOutputStreams.clear();
6618 mNeedConfig = true;
6619 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
6620 mOperatingMode = NO_MODE;
6621 mIsConstrainedHighSpeedConfiguration = false;
Emilian Peevc0fe54c2020-03-11 14:05:07 -07006622 mRequestThread->clearPreviousRequest();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006623
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006624 return OK;
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006625 // TO be done by CameraDeviceClient/Camera3OfflineSession
6626 // register the offline client to camera service
6627 // Setup result passthing threads etc
6628 // Initialize offline session so HAL can start sending callback to it (result Fmq)
6629 // TODO: check how many onIdle callback will be sent
6630 // Java side to make sure the CameraCaptureSession is properly closed
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006631}
6632
Emilian Peevcc0b7952020-01-07 13:54:47 -08006633void Camera3Device::getOfflineStreamIds(std::vector<int> *offlineStreamIds) {
6634 ATRACE_CALL();
6635
6636 if (offlineStreamIds == nullptr) {
6637 return;
6638 }
6639
6640 Mutex::Autolock il(mInterfaceLock);
6641
6642 auto streamIds = mOutputStreams.getStreamIds();
6643 bool hasInputStream = mInputStream != nullptr;
6644 if (hasInputStream && mInputStream->getOfflineProcessingSupport()) {
6645 offlineStreamIds->push_back(mInputStream->getId());
6646 }
6647
6648 for (const auto & streamId : streamIds) {
6649 sp<camera3::Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
6650 // Streams that use the camera buffer manager are currently not supported in
6651 // offline mode
6652 if (stream->getOfflineProcessingSupport() &&
6653 (stream->getStreamSetId() == CAMERA3_STREAM_SET_ID_INVALID)) {
6654 offlineStreamIds->push_back(streamId);
6655 }
6656 }
6657}
6658
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08006659status_t Camera3Device::setRotateAndCropAutoBehavior(
6660 camera_metadata_enum_android_scaler_rotate_and_crop_t rotateAndCropValue) {
6661 ATRACE_CALL();
6662 Mutex::Autolock il(mInterfaceLock);
6663 Mutex::Autolock l(mLock);
6664 if (mRequestThread == nullptr) {
6665 return INVALID_OPERATION;
6666 }
6667 return mRequestThread->setRotateAndCropAutoBehavior(rotateAndCropValue);
6668}
6669
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08006670bool Camera3Device::supportsCameraMute() {
6671 Mutex::Autolock il(mInterfaceLock);
6672 Mutex::Autolock l(mLock);
6673
6674 return mSupportCameraMute;
6675}
6676
6677status_t Camera3Device::setCameraMute(bool enabled) {
6678 ATRACE_CALL();
6679 Mutex::Autolock il(mInterfaceLock);
6680 Mutex::Autolock l(mLock);
6681
6682 if (mRequestThread == nullptr || !mSupportCameraMute) {
6683 return INVALID_OPERATION;
6684 }
Eino-Ville Talvala11afe4f2021-05-27 14:45:31 -07006685 int32_t muteMode =
6686 !enabled ? ANDROID_SENSOR_TEST_PATTERN_MODE_OFF :
6687 mSupportTestPatternSolidColor ? ANDROID_SENSOR_TEST_PATTERN_MODE_SOLID_COLOR :
6688 ANDROID_SENSOR_TEST_PATTERN_MODE_BLACK;
6689 return mRequestThread->setCameraMute(muteMode);
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08006690}
6691
Cliff Wuc2ad9c82021-04-21 00:58:58 +08006692status_t Camera3Device::injectCamera(const String8& injectedCamId,
6693 sp<CameraProviderManager> manager) {
6694 ALOGI("%s Injection camera: injectedCamId = %s", __FUNCTION__, injectedCamId.string());
6695 ATRACE_CALL();
6696 Mutex::Autolock il(mInterfaceLock);
Cliff Wu3b268182021-07-06 15:44:43 +08006697 // When the camera device is active, injectCamera() and stopInjection() will call
6698 // internalPauseAndWaitLocked() and internalResumeLocked(), and then they will call
6699 // mStatusChanged.waitRelative(mLock, timeout) of waitUntilStateThenRelock(). But
6700 // mStatusChanged.waitRelative(mLock, timeout)'s parameter: mutex "mLock" must be in the locked
6701 // state, so we need to add "Mutex::Autolock l(mLock)" to lock the "mLock" before calling
6702 // waitUntilStateThenRelock().
6703 Mutex::Autolock l(mLock);
Cliff Wuc2ad9c82021-04-21 00:58:58 +08006704
6705 status_t res = NO_ERROR;
6706 if (mInjectionMethods->isInjecting()) {
6707 if (injectedCamId == mInjectionMethods->getInjectedCamId()) {
6708 return OK;
6709 } else {
6710 res = mInjectionMethods->stopInjection();
6711 if (res != OK) {
6712 ALOGE("%s: Failed to stop the injection camera! ret != NO_ERROR: %d",
6713 __FUNCTION__, res);
6714 return res;
6715 }
6716 }
6717 }
6718
6719 res = mInjectionMethods->injectionInitialize(injectedCamId, manager, this);
6720 if (res != OK) {
6721 ALOGE("%s: Failed to initialize the injection camera! ret != NO_ERROR: %d",
6722 __FUNCTION__, res);
6723 return res;
6724 }
6725
Cliff Wuc2ad9c82021-04-21 00:58:58 +08006726 // When the second display of android is cast to the remote device, and the opened camera is
6727 // also cast to the second display, in this case, because the camera has configured the streams
6728 // at this time, we can directly call injectCamera() to replace the internal camera with
6729 // injection camera.
Cliff Wu3b268182021-07-06 15:44:43 +08006730 if (mInjectionMethods->isStreamConfigCompleteButNotInjected()) {
6731 ALOGD("%s: The opened camera is directly cast to the remote device.", __FUNCTION__);
6732
6733 camera3::camera_stream_configuration injectionConfig;
6734 std::vector<uint32_t> injectionBufferSizes;
6735 mInjectionMethods->getInjectionConfig(&injectionConfig, &injectionBufferSizes);
6736 if (mOperatingMode < 0 || injectionConfig.num_streams <= 0
6737 || injectionBufferSizes.size() <= 0) {
6738 ALOGE("Failed to inject camera due to abandoned configuration! "
6739 "mOperatingMode: %d injectionConfig.num_streams: %d "
6740 "injectionBufferSizes.size(): %zu", mOperatingMode,
6741 injectionConfig.num_streams, injectionBufferSizes.size());
6742 return DEAD_OBJECT;
6743 }
6744
Cliff Wuc2ad9c82021-04-21 00:58:58 +08006745 res = mInjectionMethods->injectCamera(
6746 injectionConfig, injectionBufferSizes);
6747 if (res != OK) {
6748 ALOGE("Can't finish inject camera process!");
6749 return res;
6750 }
6751 }
6752
6753 return OK;
6754}
6755
6756status_t Camera3Device::stopInjection() {
6757 ALOGI("%s: Injection camera: stopInjection", __FUNCTION__);
6758 Mutex::Autolock il(mInterfaceLock);
Cliff Wu3b268182021-07-06 15:44:43 +08006759 Mutex::Autolock l(mLock);
Cliff Wuc2ad9c82021-04-21 00:58:58 +08006760 return mInjectionMethods->stopInjection();
6761}
6762
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08006763}; // namespace android