blob: 3742a171966aaa97a1ff27aa92b72b9d240cfbe3 [file] [log] [blame]
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001/*
Shuzhen Wangc28189a2017-11-27 23:05:10 -08002 * Copyright (C) 2013-2018 The Android Open Source Project
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#define LOG_TAG "Camera3-Device"
18#define ATRACE_TAG ATRACE_TAG_CAMERA
19//#define LOG_NDEBUG 0
20//#define LOG_NNDEBUG 0 // Per-frame verbose logging
21
22#ifdef LOG_NNDEBUG
23#define ALOGVV(...) ALOGV(__VA_ARGS__)
24#else
25#define ALOGVV(...) ((void)0)
26#endif
27
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -070028// Convenience macro for transient errors
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080029#define CLOGE(fmt, ...) ALOGE("Camera %s: %s: " fmt, mId.string(), __FUNCTION__, \
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -070030 ##__VA_ARGS__)
31
Yin-Chia Yeh99fd0972019-06-27 14:22:44 -070032#define CLOGW(fmt, ...) ALOGW("Camera %s: %s: " fmt, mId.string(), __FUNCTION__, \
33 ##__VA_ARGS__)
34
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -070035// Convenience macros for transitioning to the error state
36#define SET_ERR(fmt, ...) setErrorState( \
37 "%s: " fmt, __FUNCTION__, \
38 ##__VA_ARGS__)
39#define SET_ERR_L(fmt, ...) setErrorStateLocked( \
40 "%s: " fmt, __FUNCTION__, \
41 ##__VA_ARGS__)
42
Colin Crosse5729fa2014-03-21 15:04:25 -070043#include <inttypes.h>
44
Shuzhen Wang5c22c152017-12-31 17:12:25 -080045#include <utility>
46
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080047#include <utils/Log.h>
48#include <utils/Trace.h>
49#include <utils/Timers.h>
Zhijun He90f7c372016-08-16 16:19:43 -070050#include <cutils/properties.h>
Eino-Ville Talvala7b82efe2013-07-25 17:12:35 -070051
Cliff Wuc2ad9c82021-04-21 00:58:58 +080052#include <android/hardware/camera/device/3.7/ICameraInjectionSession.h>
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -080053#include <android/hardware/camera2/ICameraDeviceUser.h>
54
Igor Murashkinff3e31d2013-10-23 16:40:06 -070055#include "utils/CameraTraces.h"
Eino-Ville Talvalaf99498e2015-09-25 16:52:55 -070056#include "mediautils/SchedulingPolicyService.h"
Eino-Ville Talvala7b82efe2013-07-25 17:12:35 -070057#include "device3/Camera3Device.h"
58#include "device3/Camera3OutputStream.h"
59#include "device3/Camera3InputStream.h"
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -040060#include "device3/Camera3FakeStream.h"
Shuzhen Wang0129d522016-10-30 22:43:41 -070061#include "device3/Camera3SharedOutputStream.h"
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -070062#include "CameraService.h"
Jayant Chowdhary12361932018-08-27 14:46:13 -070063#include "utils/CameraThreadState.h"
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -080064#include "utils/SessionConfigurationUtils.h"
Jayant Chowdharyd4776262020-06-23 23:45:57 -070065#include "utils/TraceHFR.h"
Shuzhen Wang316781a2020-08-18 18:11:01 -070066#include "utils/CameraServiceProxyWrapper.h"
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -080067
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -080068#include <algorithm>
Yin-Chia Yeh84be5782019-03-01 11:47:02 -080069#include <tuple>
70
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -080071using namespace android::camera3;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080072using namespace android::hardware::camera;
73using namespace android::hardware::camera::device::V3_2;
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -080074using android::hardware::camera::metadata::V3_6::CameraMetadataEnumAndroidSensorPixelMode;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080075
76namespace android {
77
Emilian Peev5104fe92021-10-21 14:27:09 -070078Camera3Device::Camera3Device(const String8 &id, bool overrideForPerfClass, bool legacyClient):
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080079 mId(id),
Emilian Peev5104fe92021-10-21 14:27:09 -070080 mLegacyClient(legacyClient),
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -080081 mOperatingMode(NO_MODE),
Eino-Ville Talvala9a179412015-06-09 13:15:16 -070082 mIsConstrainedHighSpeedConfiguration(false),
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -070083 mStatus(STATUS_UNINITIALIZED),
Ruben Brunk183f0562015-08-12 12:55:02 -070084 mStatusWaiters(0),
Zhijun He204e3292014-07-14 17:09:23 -070085 mUsePartialResult(false),
86 mNumPartialResults(1),
Shuzhen Wangc28dccc2016-02-11 23:48:46 -080087 mTimestampOffset(0),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -070088 mNextResultFrameNumber(0),
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -070089 mNextReprocessResultFrameNumber(0),
Shuzhen Wang5ee99842019-04-12 11:55:48 -070090 mNextZslStillResultFrameNumber(0),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -070091 mNextShutterFrameNumber(0),
Chien-Yu Chen3df11ce2015-09-30 14:13:30 -070092 mNextReprocessShutterFrameNumber(0),
Shuzhen Wang5ee99842019-04-12 11:55:48 -070093 mNextZslStillShutterFrameNumber(0),
Emilian Peev71c73a22017-03-21 16:35:51 +000094 mListener(NULL),
Emilian Peev811d2952018-05-25 11:08:40 +010095 mVendorTagId(CAMERA_METADATA_INVALID_VENDOR_ID),
Shuzhen Wang268a1362018-10-16 16:32:59 -070096 mLastTemplateId(-1),
Shuzhen Wangd4abdf72021-05-28 11:22:50 -070097 mNeedFixupMonochromeTags(false),
98 mOverrideForPerfClass(overrideForPerfClass)
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080099{
100 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800101 ALOGV("%s: Created device for camera %s", __FUNCTION__, mId.string());
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800102}
103
104Camera3Device::~Camera3Device()
105{
106 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800107 ALOGV("%s: Tearing down for camera id %s", __FUNCTION__, mId.string());
Yin-Chia Yehc5248132018-08-15 12:19:20 -0700108 disconnectImpl();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800109}
110
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800111const String8& Camera3Device::getId() const {
Igor Murashkin71381052013-03-04 14:53:08 -0800112 return mId;
113}
114
Emilian Peevbd8c5032018-02-14 23:05:40 +0000115status_t Camera3Device::initialize(sp<CameraProviderManager> manager, const String8& monitorTags) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800116 ATRACE_CALL();
117 Mutex::Autolock il(mInterfaceLock);
118 Mutex::Autolock l(mLock);
119
120 ALOGV("%s: Initializing HIDL device for camera %s", __FUNCTION__, mId.string());
121 if (mStatus != STATUS_UNINITIALIZED) {
122 CLOGE("Already initialized!");
123 return INVALID_OPERATION;
124 }
125 if (manager == nullptr) return INVALID_OPERATION;
126
127 sp<ICameraDeviceSession> session;
128 ATRACE_BEGIN("CameraHal::openSession");
Steven Moreland5ff9c912017-03-09 23:13:00 -0800129 status_t res = manager->openSession(mId.string(), this,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800130 /*out*/ &session);
131 ATRACE_END();
132 if (res != OK) {
133 SET_ERR_L("Could not open camera session: %s (%d)", strerror(-res), res);
134 return res;
135 }
136
Shuzhen Wangd4abdf72021-05-28 11:22:50 -0700137 res = manager->getCameraCharacteristics(mId.string(), mOverrideForPerfClass, &mDeviceInfo);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800138 if (res != OK) {
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700139 SET_ERR_L("Could not retrieve camera characteristics: %s (%d)", strerror(-res), res);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800140 session->close();
141 return res;
142 }
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800143 mSupportNativeZoomRatio = manager->supportNativeZoomRatio(mId.string());
Yin-Chia Yeh52778d42016-12-22 18:20:43 -0800144
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700145 std::vector<std::string> physicalCameraIds;
Shuzhen Wang03d8cc12018-09-12 14:17:09 -0700146 bool isLogical = manager->isLogicalCamera(mId.string(), &physicalCameraIds);
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700147 if (isLogical) {
148 for (auto& physicalId : physicalCameraIds) {
Shuzhen Wangd4abdf72021-05-28 11:22:50 -0700149 // Do not override characteristics for physical cameras
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -0700150 res = manager->getCameraCharacteristics(
Shuzhen Wangd4abdf72021-05-28 11:22:50 -0700151 physicalId, /*overrideForPerfClass*/false, &mPhysicalDeviceInfoMap[physicalId]);
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700152 if (res != OK) {
153 SET_ERR_L("Could not retrieve camera %s characteristics: %s (%d)",
154 physicalId.c_str(), strerror(-res), res);
155 session->close();
156 return res;
157 }
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -0700158
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800159 bool usePrecorrectArray =
160 DistortionMapper::isDistortionSupported(mPhysicalDeviceInfoMap[physicalId]);
161 if (usePrecorrectArray) {
162 res = mDistortionMappers[physicalId].setupStaticInfo(
163 mPhysicalDeviceInfoMap[physicalId]);
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -0700164 if (res != OK) {
165 SET_ERR_L("Unable to read camera %s's calibration fields for distortion "
166 "correction", physicalId.c_str());
167 session->close();
168 return res;
169 }
170 }
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800171
Shuzhen Wang1c834da2019-12-18 11:17:03 -0800172 mZoomRatioMappers[physicalId] = ZoomRatioMapper(
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800173 &mPhysicalDeviceInfoMap[physicalId],
174 mSupportNativeZoomRatio, usePrecorrectArray);
Jayant Chowdhary9255ce02021-07-15 11:18:17 -0700175
176 if (SessionConfigurationUtils::isUltraHighResolutionSensor(
177 mPhysicalDeviceInfoMap[physicalId])) {
178 mUHRCropAndMeteringRegionMappers[physicalId] =
179 UHRCropAndMeteringRegionMapper(mPhysicalDeviceInfoMap[physicalId],
180 usePrecorrectArray);
181 }
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700182 }
183 }
184
Yifan Hongf79b5542017-04-11 14:44:25 -0700185 std::shared_ptr<RequestMetadataQueue> queue;
Yifan Honga640c5a2017-04-12 16:30:31 -0700186 auto requestQueueRet = session->getCaptureRequestMetadataQueue(
187 [&queue](const auto& descriptor) {
188 queue = std::make_shared<RequestMetadataQueue>(descriptor);
189 if (!queue->isValid() || queue->availableToWrite() <= 0) {
190 ALOGE("HAL returns empty request metadata fmq, not use it");
191 queue = nullptr;
192 // don't use the queue onwards.
193 }
194 });
195 if (!requestQueueRet.isOk()) {
196 ALOGE("Transaction error when getting request metadata fmq: %s, not use it",
197 requestQueueRet.description().c_str());
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -0700198 return DEAD_OBJECT;
Yifan Hongf79b5542017-04-11 14:44:25 -0700199 }
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700200
201 std::unique_ptr<ResultMetadataQueue>& resQueue = mResultMetadataQueue;
Yifan Honga640c5a2017-04-12 16:30:31 -0700202 auto resultQueueRet = session->getCaptureResultMetadataQueue(
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700203 [&resQueue](const auto& descriptor) {
204 resQueue = std::make_unique<ResultMetadataQueue>(descriptor);
205 if (!resQueue->isValid() || resQueue->availableToWrite() <= 0) {
Yifan Honga640c5a2017-04-12 16:30:31 -0700206 ALOGE("HAL returns empty result metadata fmq, not use it");
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700207 resQueue = nullptr;
208 // Don't use the resQueue onwards.
Yifan Honga640c5a2017-04-12 16:30:31 -0700209 }
210 });
211 if (!resultQueueRet.isOk()) {
212 ALOGE("Transaction error when getting result metadata queue from camera session: %s",
213 resultQueueRet.description().c_str());
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -0700214 return DEAD_OBJECT;
Yifan Honga640c5a2017-04-12 16:30:31 -0700215 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -0700216 IF_ALOGV() {
217 session->interfaceChain([](
218 ::android::hardware::hidl_vec<::android::hardware::hidl_string> interfaceChain) {
219 ALOGV("Session interface chain:");
Chih-Hung Hsieh3ef324d2018-12-11 11:48:12 -0800220 for (const auto& iface : interfaceChain) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -0700221 ALOGV(" %s", iface.c_str());
222 }
223 });
224 }
Yifan Hongf79b5542017-04-11 14:44:25 -0700225
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -0800226 camera_metadata_entry bufMgrMode =
227 mDeviceInfo.find(ANDROID_INFO_SUPPORTED_BUFFER_MANAGEMENT_VERSION);
228 if (bufMgrMode.count > 0) {
229 mUseHalBufManager = (bufMgrMode.data.u8[0] ==
230 ANDROID_INFO_SUPPORTED_BUFFER_MANAGEMENT_VERSION_HIDL_DEVICE_3_5);
231 }
232
Yin-Chia Yehb978c382019-10-30 00:22:37 -0700233 camera_metadata_entry_t capabilities = mDeviceInfo.find(ANDROID_REQUEST_AVAILABLE_CAPABILITIES);
234 for (size_t i = 0; i < capabilities.count; i++) {
235 uint8_t capability = capabilities.data.u8[i];
236 if (capability == ANDROID_REQUEST_AVAILABLE_CAPABILITIES_OFFLINE_PROCESSING) {
237 mSupportOfflineProcessing = true;
238 }
239 }
240
241 mInterface = new HalInterface(session, queue, mUseHalBufManager, mSupportOfflineProcessing);
Emilian Peev71c73a22017-03-21 16:35:51 +0000242 std::string providerType;
243 mVendorTagId = manager->getProviderTagIdLocked(mId.string());
Emilian Peevbd8c5032018-02-14 23:05:40 +0000244 mTagMonitor.initialize(mVendorTagId);
245 if (!monitorTags.isEmpty()) {
246 mTagMonitor.parseTagsToMonitor(String8(monitorTags));
247 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800248
Shuzhen Wang268a1362018-10-16 16:32:59 -0700249 // Metadata tags needs fixup for monochrome camera device version less
250 // than 3.5.
251 hardware::hidl_version maxVersion{0,0};
252 res = manager->getHighestSupportedVersion(mId.string(), &maxVersion);
253 if (res != OK) {
254 ALOGE("%s: Error in getting camera device version id: %s (%d)",
255 __FUNCTION__, strerror(-res), res);
256 return res;
257 }
258 int deviceVersion = HARDWARE_DEVICE_API_VERSION(
259 maxVersion.get_major(), maxVersion.get_minor());
260
261 bool isMonochrome = false;
Yin-Chia Yehb978c382019-10-30 00:22:37 -0700262 for (size_t i = 0; i < capabilities.count; i++) {
263 uint8_t capability = capabilities.data.u8[i];
Shuzhen Wang268a1362018-10-16 16:32:59 -0700264 if (capability == ANDROID_REQUEST_AVAILABLE_CAPABILITIES_MONOCHROME) {
265 isMonochrome = true;
266 }
267 }
268 mNeedFixupMonochromeTags = (isMonochrome && deviceVersion < CAMERA_DEVICE_API_VERSION_3_5);
269
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800270 return initializeCommonLocked();
271}
272
273status_t Camera3Device::initializeCommonLocked() {
274
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700275 /** Start up status tracker thread */
276 mStatusTracker = new StatusTracker(this);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800277 status_t res = mStatusTracker->run(String8::format("C3Dev-%s-Status", mId.string()).string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700278 if (res != OK) {
279 SET_ERR_L("Unable to start status tracking thread: %s (%d)",
280 strerror(-res), res);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800281 mInterface->close();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700282 mStatusTracker.clear();
283 return res;
284 }
285
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -0700286 /** Register in-flight map to the status tracker */
Yin-Chia Yeh87b3ec02019-06-03 10:44:39 -0700287 mInFlightStatusId = mStatusTracker->addComponent("InflightRequests");
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -0700288
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -0700289 if (mUseHalBufManager) {
290 res = mRequestBufferSM.initialize(mStatusTracker);
291 if (res != OK) {
292 SET_ERR_L("Unable to start request buffer state machine: %s (%d)",
293 strerror(-res), res);
294 mInterface->close();
295 mStatusTracker.clear();
296 return res;
297 }
298 }
299
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -0800300 /** Create buffer manager */
301 mBufferManager = new Camera3BufferManager();
302
303 Vector<int32_t> sessionParamKeys;
304 camera_metadata_entry_t sessionKeysEntry = mDeviceInfo.find(
305 ANDROID_REQUEST_AVAILABLE_SESSION_KEYS);
306 if (sessionKeysEntry.count > 0) {
307 sessionParamKeys.insertArrayAt(sessionKeysEntry.data.i32, 0, sessionKeysEntry.count);
308 }
309
Eino-Ville Talvala1646c3c2021-07-29 13:48:40 -0700310 camera_metadata_entry_t availableTestPatternModes = mDeviceInfo.find(
311 ANDROID_SENSOR_AVAILABLE_TEST_PATTERN_MODES);
312 for (size_t i = 0; i < availableTestPatternModes.count; i++) {
313 if (availableTestPatternModes.data.i32[i] ==
314 ANDROID_SENSOR_TEST_PATTERN_MODE_SOLID_COLOR) {
315 mSupportCameraMute = true;
316 mSupportTestPatternSolidColor = true;
317 break;
318 } else if (availableTestPatternModes.data.i32[i] ==
319 ANDROID_SENSOR_TEST_PATTERN_MODE_BLACK) {
320 mSupportCameraMute = true;
321 mSupportTestPatternSolidColor = false;
322 }
323 }
324
Chien-Yu Chenab5135b2015-06-30 11:20:58 -0700325 /** Start up request queue thread */
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -0700326 mRequestThread = new RequestThread(
Eino-Ville Talvala1646c3c2021-07-29 13:48:40 -0700327 this, mStatusTracker, mInterface, sessionParamKeys,
328 mUseHalBufManager, mSupportCameraMute);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800329 res = mRequestThread->run(String8::format("C3Dev-%s-ReqQueue", mId.string()).string());
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800330 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700331 SET_ERR_L("Unable to start request queue thread: %s (%d)",
332 strerror(-res), res);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800333 mInterface->close();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800334 mRequestThread.clear();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800335 return res;
336 }
337
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -0700338 mPreparerThread = new PreparerThread();
339
Ruben Brunk183f0562015-08-12 12:55:02 -0700340 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800341 mNextStreamId = 0;
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -0400342 mFakeStreamId = NO_STREAM;
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -0700343 mNeedConfig = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700344 mPauseStateNotify = false;
Shuzhen Wang83bff122020-11-20 15:51:39 -0800345 mIsInputStreamMultiResolution = false;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800346
Shuzhen Wangc28dccc2016-02-11 23:48:46 -0800347 // Measure the clock domain offset between camera and video/hw_composer
348 camera_metadata_entry timestampSource =
349 mDeviceInfo.find(ANDROID_SENSOR_INFO_TIMESTAMP_SOURCE);
350 if (timestampSource.count > 0 && timestampSource.data.u8[0] ==
351 ANDROID_SENSOR_INFO_TIMESTAMP_SOURCE_REALTIME) {
352 mTimestampOffset = getMonoToBoottimeOffset();
353 }
354
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -0700355 // Will the HAL be sending in early partial result metadata?
Emilian Peev08dd2452017-04-06 16:55:14 +0100356 camera_metadata_entry partialResultsCount =
357 mDeviceInfo.find(ANDROID_REQUEST_PARTIAL_RESULT_COUNT);
358 if (partialResultsCount.count > 0) {
359 mNumPartialResults = partialResultsCount.data.i32[0];
360 mUsePartialResult = (mNumPartialResults > 1);
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -0700361 }
362
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800363 bool usePrecorrectArray = DistortionMapper::isDistortionSupported(mDeviceInfo);
364 if (usePrecorrectArray) {
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -0700365 res = mDistortionMappers[mId.c_str()].setupStaticInfo(mDeviceInfo);
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -0700366 if (res != OK) {
367 SET_ERR_L("Unable to read necessary calibration fields for distortion correction");
368 return res;
369 }
370 }
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800371
Shuzhen Wang1c834da2019-12-18 11:17:03 -0800372 mZoomRatioMappers[mId.c_str()] = ZoomRatioMapper(&mDeviceInfo,
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800373 mSupportNativeZoomRatio, usePrecorrectArray);
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800374
Jayant Chowdhary9255ce02021-07-15 11:18:17 -0700375 if (SessionConfigurationUtils::isUltraHighResolutionSensor(mDeviceInfo)) {
376 mUHRCropAndMeteringRegionMappers[mId.c_str()] =
377 UHRCropAndMeteringRegionMapper(mDeviceInfo, usePrecorrectArray);
378 }
379
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -0800380 if (RotateAndCropMapper::isNeeded(&mDeviceInfo)) {
381 mRotateAndCropMappers.emplace(mId.c_str(), &mDeviceInfo);
382 }
383
Cliff Wuc2ad9c82021-04-21 00:58:58 +0800384 mInjectionMethods = new Camera3DeviceInjectionMethods(this);
385
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800386 return OK;
387}
388
389status_t Camera3Device::disconnect() {
Yin-Chia Yehc5248132018-08-15 12:19:20 -0700390 return disconnectImpl();
391}
392
393status_t Camera3Device::disconnectImpl() {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800394 ATRACE_CALL();
Yin-Chia Yehe1c80632016-08-08 14:48:05 -0700395 ALOGI("%s: E", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800396
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700397 status_t res = OK;
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700398 std::vector<wp<Camera3StreamInterface>> streams;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700399 {
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800400 Mutex::Autolock il(mInterfaceLock);
401 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
402 {
403 Mutex::Autolock l(mLock);
404 if (mStatus == STATUS_UNINITIALIZED) return res;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700405
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800406 if (mStatus == STATUS_ACTIVE ||
407 (mStatus == STATUS_ERROR && mRequestThread != NULL)) {
408 res = mRequestThread->clearRepeatingRequests();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700409 if (res != OK) {
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800410 SET_ERR_L("Can't stop streaming");
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700411 // Continue to close device even in case of error
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800412 } else {
413 res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
414 if (res != OK) {
415 SET_ERR_L("Timeout waiting for HAL to drain (% " PRIi64 " ns)",
416 maxExpectedDuration);
417 // Continue to close device even in case of error
418 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700419 }
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700420 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800421
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800422 if (mStatus == STATUS_ERROR) {
423 CLOGE("Shutting down in an error state");
424 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700425
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800426 if (mStatusTracker != NULL) {
427 mStatusTracker->requestExit();
428 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700429
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800430 if (mRequestThread != NULL) {
431 mRequestThread->requestExit();
432 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700433
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800434 streams.reserve(mOutputStreams.size() + (mInputStream != nullptr ? 1 : 0));
435 for (size_t i = 0; i < mOutputStreams.size(); i++) {
436 streams.push_back(mOutputStreams[i]);
437 }
438 if (mInputStream != nullptr) {
439 streams.push_back(mInputStream);
440 }
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700441 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700442 }
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800443 // Joining done without holding mLock and mInterfaceLock, otherwise deadlocks may ensue
444 // as the threads try to access parent state (b/143513518)
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700445 if (mRequestThread != NULL && mStatus != STATUS_ERROR) {
446 // HAL may be in a bad state, so waiting for request thread
447 // (which may be stuck in the HAL processCaptureRequest call)
448 // could be dangerous.
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800449 // give up mInterfaceLock here and then lock it again. Could this lead
450 // to other deadlocks
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700451 mRequestThread->join();
452 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700453 {
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800454 Mutex::Autolock il(mInterfaceLock);
455 if (mStatusTracker != NULL) {
456 mStatusTracker->join();
457 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800458
Cliff Wuc2ad9c82021-04-21 00:58:58 +0800459 if (mInjectionMethods->isInjecting()) {
460 mInjectionMethods->stopInjection();
461 }
462
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800463 HalInterface* interface;
464 {
465 Mutex::Autolock l(mLock);
466 mRequestThread.clear();
467 Mutex::Autolock stLock(mTrackerLock);
468 mStatusTracker.clear();
469 interface = mInterface.get();
470 }
Eino-Ville Talvalaefff1c42015-08-28 16:27:27 -0700471
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800472 // Call close without internal mutex held, as the HAL close may need to
473 // wait on assorted callbacks,etc, to complete before it can return.
474 interface->close();
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700475
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800476 flushInflightRequests();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800477
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800478 {
479 Mutex::Autolock l(mLock);
480 mInterface->clear();
481 mOutputStreams.clear();
482 mInputStream.clear();
483 mDeletedStreams.clear();
484 mBufferManager.clear();
485 internalUpdateStatusLocked(STATUS_UNINITIALIZED);
486 }
487
488 for (auto& weakStream : streams) {
489 sp<Camera3StreamInterface> stream = weakStream.promote();
490 if (stream != nullptr) {
491 ALOGE("%s: Stream %d leaked! strong reference (%d)!",
492 __FUNCTION__, stream->getId(), stream->getStrongCount() - 1);
493 }
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700494 }
495 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -0700496 ALOGI("%s: X", __FUNCTION__);
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700497 return res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800498}
499
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700500// For dumping/debugging only -
501// try to acquire a lock a few times, eventually give up to proceed with
502// debug/dump operations
503bool Camera3Device::tryLockSpinRightRound(Mutex& lock) {
504 bool gotLock = false;
505 for (size_t i = 0; i < kDumpLockAttempts; ++i) {
506 if (lock.tryLock() == NO_ERROR) {
507 gotLock = true;
508 break;
509 } else {
510 usleep(kDumpSleepDuration);
511 }
512 }
513 return gotLock;
514}
515
Shuzhen Wangc28dccc2016-02-11 23:48:46 -0800516nsecs_t Camera3Device::getMonoToBoottimeOffset() {
517 // try three times to get the clock offset, choose the one
518 // with the minimum gap in measurements.
519 const int tries = 3;
520 nsecs_t bestGap, measured;
521 for (int i = 0; i < tries; ++i) {
522 const nsecs_t tmono = systemTime(SYSTEM_TIME_MONOTONIC);
523 const nsecs_t tbase = systemTime(SYSTEM_TIME_BOOTTIME);
524 const nsecs_t tmono2 = systemTime(SYSTEM_TIME_MONOTONIC);
525 const nsecs_t gap = tmono2 - tmono;
526 if (i == 0 || gap < bestGap) {
527 bestGap = gap;
528 measured = tbase - ((tmono + tmono2) >> 1);
529 }
530 }
531 return measured;
532}
533
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800534hardware::graphics::common::V1_0::PixelFormat Camera3Device::mapToPixelFormat(
535 int frameworkFormat) {
536 return (hardware::graphics::common::V1_0::PixelFormat) frameworkFormat;
537}
538
539DataspaceFlags Camera3Device::mapToHidlDataspace(
540 android_dataspace dataSpace) {
541 return dataSpace;
542}
543
Chia-I Wu67a0c0e2017-04-06 13:37:01 -0700544BufferUsageFlags Camera3Device::mapToConsumerUsage(
Emilian Peev050f5dc2017-05-18 14:43:56 +0100545 uint64_t usage) {
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -0700546 return usage;
547}
548
Emilian Peevf4816702020-04-03 15:44:51 -0700549StreamRotation Camera3Device::mapToStreamRotation(camera_stream_rotation_t rotation) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800550 switch (rotation) {
Emilian Peevf4816702020-04-03 15:44:51 -0700551 case CAMERA_STREAM_ROTATION_0:
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800552 return StreamRotation::ROTATION_0;
Emilian Peevf4816702020-04-03 15:44:51 -0700553 case CAMERA_STREAM_ROTATION_90:
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800554 return StreamRotation::ROTATION_90;
Emilian Peevf4816702020-04-03 15:44:51 -0700555 case CAMERA_STREAM_ROTATION_180:
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800556 return StreamRotation::ROTATION_180;
Emilian Peevf4816702020-04-03 15:44:51 -0700557 case CAMERA_STREAM_ROTATION_270:
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800558 return StreamRotation::ROTATION_270;
559 }
560 ALOGE("%s: Unknown stream rotation %d", __FUNCTION__, rotation);
561 return StreamRotation::ROTATION_0;
562}
563
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800564status_t Camera3Device::mapToStreamConfigurationMode(
Emilian Peevf4816702020-04-03 15:44:51 -0700565 camera_stream_configuration_mode_t operationMode, StreamConfigurationMode *mode) {
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800566 if (mode == nullptr) return BAD_VALUE;
Emilian Peevf4816702020-04-03 15:44:51 -0700567 if (operationMode < CAMERA_VENDOR_STREAM_CONFIGURATION_MODE_START) {
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800568 switch(operationMode) {
Emilian Peevf4816702020-04-03 15:44:51 -0700569 case CAMERA_STREAM_CONFIGURATION_NORMAL_MODE:
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800570 *mode = StreamConfigurationMode::NORMAL_MODE;
571 break;
Emilian Peevf4816702020-04-03 15:44:51 -0700572 case CAMERA_STREAM_CONFIGURATION_CONSTRAINED_HIGH_SPEED_MODE:
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800573 *mode = StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE;
574 break;
575 default:
576 ALOGE("%s: Unknown stream configuration mode %d", __FUNCTION__, operationMode);
577 return BAD_VALUE;
578 }
579 } else {
580 *mode = static_cast<StreamConfigurationMode>(operationMode);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800581 }
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800582 return OK;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800583}
584
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800585int Camera3Device::mapToFrameworkFormat(
586 hardware::graphics::common::V1_0::PixelFormat pixelFormat) {
587 return static_cast<uint32_t>(pixelFormat);
588}
589
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -0700590android_dataspace Camera3Device::mapToFrameworkDataspace(
591 DataspaceFlags dataSpace) {
592 return static_cast<android_dataspace>(dataSpace);
593}
594
Emilian Peev050f5dc2017-05-18 14:43:56 +0100595uint64_t Camera3Device::mapConsumerToFrameworkUsage(
Chia-I Wu67a0c0e2017-04-06 13:37:01 -0700596 BufferUsageFlags usage) {
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -0700597 return usage;
598}
599
Emilian Peev050f5dc2017-05-18 14:43:56 +0100600uint64_t Camera3Device::mapProducerToFrameworkUsage(
Chia-I Wu67a0c0e2017-04-06 13:37:01 -0700601 BufferUsageFlags usage) {
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -0700602 return usage;
603}
604
Zhijun Hef7da0962014-04-24 13:27:56 -0700605ssize_t Camera3Device::getJpegBufferSize(uint32_t width, uint32_t height) const {
Jayant Chowdharycd3d36b2021-07-10 10:53:53 -0700606 // Get max jpeg size (area-wise) for default sensor pixel mode
607 camera3::Size maxDefaultJpegResolution =
608 SessionConfigurationUtils::getMaxJpegResolution(mDeviceInfo,
609 /*isUltraHighResolutionSensor*/false);
610 // Get max jpeg size (area-wise) for max resolution sensor pixel mode / 0 if
611 // not ultra high res sensor
612 camera3::Size uhrMaxJpegResolution =
613 SessionConfigurationUtils::getMaxJpegResolution(mDeviceInfo,
614 /*isUltraHighResolution*/true);
615 if (maxDefaultJpegResolution.width == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800616 ALOGE("%s: Camera %s: Can't find valid available jpeg sizes in static metadata!",
617 __FUNCTION__, mId.string());
Zhijun Hef7da0962014-04-24 13:27:56 -0700618 return BAD_VALUE;
619 }
Jayant Chowdharycd3d36b2021-07-10 10:53:53 -0700620 bool useMaxSensorPixelModeThreshold = false;
621 if (uhrMaxJpegResolution.width != 0 &&
622 width * height > maxDefaultJpegResolution.width * maxDefaultJpegResolution.height) {
623 // Use the ultra high res max jpeg size and max jpeg buffer size
624 useMaxSensorPixelModeThreshold = true;
625 }
Zhijun Hef7da0962014-04-24 13:27:56 -0700626
Zhijun Hef7da0962014-04-24 13:27:56 -0700627 // Get max jpeg buffer size
628 ssize_t maxJpegBufferSize = 0;
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700629 camera_metadata_ro_entry jpegBufMaxSize = mDeviceInfo.find(ANDROID_JPEG_MAX_SIZE);
630 if (jpegBufMaxSize.count == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800631 ALOGE("%s: Camera %s: Can't find maximum JPEG size in static metadata!", __FUNCTION__,
632 mId.string());
Zhijun Hef7da0962014-04-24 13:27:56 -0700633 return BAD_VALUE;
634 }
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700635 maxJpegBufferSize = jpegBufMaxSize.data.i32[0];
Jayant Chowdharycd3d36b2021-07-10 10:53:53 -0700636
637 camera3::Size chosenMaxJpegResolution = maxDefaultJpegResolution;
638 if (useMaxSensorPixelModeThreshold) {
639 maxJpegBufferSize =
640 SessionConfigurationUtils::getUHRMaxJpegBufferSize(uhrMaxJpegResolution,
641 maxDefaultJpegResolution, maxJpegBufferSize);
642 chosenMaxJpegResolution = uhrMaxJpegResolution;
643 }
Yin-Chia Yeh0c4e56d2015-01-09 15:21:27 -0800644 assert(kMinJpegBufferSize < maxJpegBufferSize);
Zhijun Hef7da0962014-04-24 13:27:56 -0700645
646 // Calculate final jpeg buffer size for the given resolution.
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700647 float scaleFactor = ((float) (width * height)) /
Jayant Chowdharycd3d36b2021-07-10 10:53:53 -0700648 (chosenMaxJpegResolution.width * chosenMaxJpegResolution.height);
Yin-Chia Yeh0c4e56d2015-01-09 15:21:27 -0800649 ssize_t jpegBufferSize = scaleFactor * (maxJpegBufferSize - kMinJpegBufferSize) +
650 kMinJpegBufferSize;
Zhijun Hef7da0962014-04-24 13:27:56 -0700651 if (jpegBufferSize > maxJpegBufferSize) {
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -0800652 ALOGI("%s: jpeg buffer size calculated is > maxJpeg bufferSize(%zd), clamping",
653 __FUNCTION__, maxJpegBufferSize);
Zhijun Hef7da0962014-04-24 13:27:56 -0700654 jpegBufferSize = maxJpegBufferSize;
Zhijun Hef7da0962014-04-24 13:27:56 -0700655 }
Zhijun Hef7da0962014-04-24 13:27:56 -0700656 return jpegBufferSize;
657}
658
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700659ssize_t Camera3Device::getPointCloudBufferSize() const {
660 const int FLOATS_PER_POINT=4;
661 camera_metadata_ro_entry maxPointCount = mDeviceInfo.find(ANDROID_DEPTH_MAX_DEPTH_SAMPLES);
662 if (maxPointCount.count == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800663 ALOGE("%s: Camera %s: Can't find maximum depth point cloud size in static metadata!",
664 __FUNCTION__, mId.string());
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700665 return BAD_VALUE;
666 }
667 ssize_t maxBytesForPointCloud = sizeof(android_depth_points) +
668 maxPointCount.data.i32[0] * sizeof(float) * FLOATS_PER_POINT;
669 return maxBytesForPointCloud;
670}
671
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -0800672ssize_t Camera3Device::getRawOpaqueBufferSize(int32_t width, int32_t height,
673 bool maxResolution) const {
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800674 const int PER_CONFIGURATION_SIZE = 3;
675 const int WIDTH_OFFSET = 0;
676 const int HEIGHT_OFFSET = 1;
677 const int SIZE_OFFSET = 2;
678 camera_metadata_ro_entry rawOpaqueSizes =
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -0800679 mDeviceInfo.find(
680 camera3::SessionConfigurationUtils::getAppropriateModeTag(
681 ANDROID_SENSOR_OPAQUE_RAW_SIZE,
682 maxResolution));
Aurimas Liutikasbc57b122016-02-16 09:59:16 -0800683 size_t count = rawOpaqueSizes.count;
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800684 if (count == 0 || (count % PER_CONFIGURATION_SIZE)) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800685 ALOGE("%s: Camera %s: bad opaque RAW size static metadata length(%zu)!",
686 __FUNCTION__, mId.string(), count);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800687 return BAD_VALUE;
688 }
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700689
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800690 for (size_t i = 0; i < count; i += PER_CONFIGURATION_SIZE) {
691 if (width == rawOpaqueSizes.data.i32[i + WIDTH_OFFSET] &&
692 height == rawOpaqueSizes.data.i32[i + HEIGHT_OFFSET]) {
693 return rawOpaqueSizes.data.i32[i + SIZE_OFFSET];
694 }
695 }
696
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800697 ALOGE("%s: Camera %s: cannot find size for %dx%d opaque RAW image!",
698 __FUNCTION__, mId.string(), width, height);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800699 return BAD_VALUE;
700}
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700701
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800702status_t Camera3Device::dump(int fd, const Vector<String16> &args) {
703 ATRACE_CALL();
704 (void)args;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700705
706 // Try to lock, but continue in case of failure (to avoid blocking in
707 // deadlocks)
708 bool gotInterfaceLock = tryLockSpinRightRound(mInterfaceLock);
709 bool gotLock = tryLockSpinRightRound(mLock);
710
711 ALOGW_IF(!gotInterfaceLock,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800712 "Camera %s: %s: Unable to lock interface lock, proceeding anyway",
713 mId.string(), __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700714 ALOGW_IF(!gotLock,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800715 "Camera %s: %s: Unable to lock main lock, proceeding anyway",
716 mId.string(), __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700717
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800718 bool dumpTemplates = false;
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700719
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800720 String16 templatesOption("-t");
721 int n = args.size();
722 for (int i = 0; i < n; i++) {
723 if (args[i] == templatesOption) {
724 dumpTemplates = true;
725 }
Emilian Peevbd8c5032018-02-14 23:05:40 +0000726 if (args[i] == TagMonitor::kMonitorOption) {
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700727 if (i + 1 < n) {
728 String8 monitorTags = String8(args[i + 1]);
729 if (monitorTags == "off") {
730 mTagMonitor.disableMonitoring();
731 } else {
732 mTagMonitor.parseTagsToMonitor(monitorTags);
733 }
734 } else {
735 mTagMonitor.disableMonitoring();
736 }
737 }
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800738 }
739
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800740 String8 lines;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800741
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800742 const char *status =
743 mStatus == STATUS_ERROR ? "ERROR" :
744 mStatus == STATUS_UNINITIALIZED ? "UNINITIALIZED" :
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700745 mStatus == STATUS_UNCONFIGURED ? "UNCONFIGURED" :
746 mStatus == STATUS_CONFIGURED ? "CONFIGURED" :
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800747 mStatus == STATUS_ACTIVE ? "ACTIVE" :
748 "Unknown";
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700749
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800750 lines.appendFormat(" Device status: %s\n", status);
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700751 if (mStatus == STATUS_ERROR) {
752 lines.appendFormat(" Error cause: %s\n", mErrorCause.string());
753 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800754 lines.appendFormat(" Stream configuration:\n");
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800755 const char *mode =
756 mOperatingMode == static_cast<int>(StreamConfigurationMode::NORMAL_MODE) ? "NORMAL" :
757 mOperatingMode == static_cast<int>(
758 StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE) ? "CONSTRAINED_HIGH_SPEED" :
759 "CUSTOM";
760 lines.appendFormat(" Operation mode: %s (%d) \n", mode, mOperatingMode);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800761
762 if (mInputStream != NULL) {
763 write(fd, lines.string(), lines.size());
764 mInputStream->dump(fd, args);
765 } else {
766 lines.appendFormat(" No input stream.\n");
767 write(fd, lines.string(), lines.size());
768 }
769 for (size_t i = 0; i < mOutputStreams.size(); i++) {
770 mOutputStreams[i]->dump(fd,args);
771 }
772
Zhijun He431503c2016-03-07 17:30:16 -0800773 if (mBufferManager != NULL) {
774 lines = String8(" Camera3 Buffer Manager:\n");
775 write(fd, lines.string(), lines.size());
776 mBufferManager->dump(fd, args);
777 }
Zhijun He125684a2015-12-26 15:07:30 -0800778
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700779 lines = String8(" In-flight requests:\n");
Emilian Peeva6138c52021-06-24 12:52:38 -0700780 if (mInFlightLock.try_lock()) {
781 if (mInFlightMap.size() == 0) {
782 lines.append(" None\n");
783 } else {
784 for (size_t i = 0; i < mInFlightMap.size(); i++) {
785 InFlightRequest r = mInFlightMap.valueAt(i);
786 lines.appendFormat(" Frame %d | Timestamp: %" PRId64 ", metadata"
787 " arrived: %s, buffers left: %d\n", mInFlightMap.keyAt(i),
788 r.shutterTimestamp, r.haveResultMetadata ? "true" : "false",
789 r.numBuffersLeft);
790 }
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700791 }
Emilian Peeva6138c52021-06-24 12:52:38 -0700792 mInFlightLock.unlock();
793 } else {
794 lines.append(" Failed to acquire In-flight lock!\n");
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700795 }
796 write(fd, lines.string(), lines.size());
797
Shuzhen Wang686f6442017-06-20 16:16:04 -0700798 if (mRequestThread != NULL) {
799 mRequestThread->dumpCaptureRequestLatency(fd,
800 " ProcessCaptureRequest latency histogram:");
801 }
802
Igor Murashkin1e479c02013-09-06 16:55:14 -0700803 {
804 lines = String8(" Last request sent:\n");
805 write(fd, lines.string(), lines.size());
806
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700807 CameraMetadata lastRequest = getLatestRequestLocked();
Igor Murashkin1e479c02013-09-06 16:55:14 -0700808 lastRequest.dump(fd, /*verbosity*/2, /*indentation*/6);
809 }
810
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800811 if (dumpTemplates) {
Emilian Peevf4816702020-04-03 15:44:51 -0700812 const char *templateNames[CAMERA_TEMPLATE_COUNT] = {
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800813 "TEMPLATE_PREVIEW",
814 "TEMPLATE_STILL_CAPTURE",
815 "TEMPLATE_VIDEO_RECORD",
816 "TEMPLATE_VIDEO_SNAPSHOT",
817 "TEMPLATE_ZERO_SHUTTER_LAG",
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -0800818 "TEMPLATE_MANUAL",
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800819 };
820
Emilian Peevf4816702020-04-03 15:44:51 -0700821 for (int i = 1; i < CAMERA_TEMPLATE_COUNT; i++) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800822 camera_metadata_t *templateRequest = nullptr;
823 mInterface->constructDefaultRequestSettings(
Emilian Peevf4816702020-04-03 15:44:51 -0700824 (camera_request_template_t) i, &templateRequest);
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800825 lines = String8::format(" HAL Request %s:\n", templateNames[i-1]);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800826 if (templateRequest == nullptr) {
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800827 lines.append(" Not supported\n");
828 write(fd, lines.string(), lines.size());
829 } else {
830 write(fd, lines.string(), lines.size());
831 dump_indented_camera_metadata(templateRequest,
832 fd, /*verbosity*/2, /*indentation*/8);
833 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800834 free_camera_metadata(templateRequest);
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800835 }
836 }
837
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700838 mTagMonitor.dumpMonitoredMetadata(fd);
839
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800840 if (mInterface->valid()) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -0800841 lines = String8(" HAL device dump:\n");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800842 write(fd, lines.string(), lines.size());
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800843 mInterface->dump(fd);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800844 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800845
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700846 if (gotLock) mLock.unlock();
847 if (gotInterfaceLock) mInterfaceLock.unlock();
848
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800849 return OK;
850}
851
Avichal Rakesh7e53cad2021-10-05 13:46:30 -0700852status_t Camera3Device::startWatchingTags(const String8 &tags) {
853 mTagMonitor.parseTagsToMonitor(tags);
854 return OK;
855}
856
857status_t Camera3Device::stopWatchingTags() {
858 mTagMonitor.disableMonitoring();
859 return OK;
860}
861
862status_t Camera3Device::dumpWatchedEventsToVector(std::vector<std::string> &out) {
863 mTagMonitor.getLatestMonitoredTagEvents(out);
864 return OK;
865}
866
Emilian Peevfaa4bde2020-01-23 12:19:37 -0800867const CameraMetadata& Camera3Device::infoPhysical(const String8& physicalId) const {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800868 ALOGVV("%s: E", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800869 if (CC_UNLIKELY(mStatus == STATUS_UNINITIALIZED ||
870 mStatus == STATUS_ERROR)) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700871 ALOGW("%s: Access to static info %s!", __FUNCTION__,
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800872 mStatus == STATUS_ERROR ?
873 "when in error state" : "before init");
874 }
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700875 if (physicalId.isEmpty()) {
876 return mDeviceInfo;
877 } else {
878 std::string id(physicalId.c_str());
879 if (mPhysicalDeviceInfoMap.find(id) != mPhysicalDeviceInfoMap.end()) {
880 return mPhysicalDeviceInfoMap.at(id);
881 } else {
882 ALOGE("%s: Invalid physical camera id %s", __FUNCTION__, physicalId.c_str());
883 return mDeviceInfo;
884 }
885 }
886}
887
888const CameraMetadata& Camera3Device::info() const {
889 String8 emptyId;
Emilian Peevfaa4bde2020-01-23 12:19:37 -0800890 return infoPhysical(emptyId);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800891}
892
Jianing Wei90e59c92014-03-12 18:29:36 -0700893status_t Camera3Device::checkStatusOkToCaptureLocked() {
894 switch (mStatus) {
895 case STATUS_ERROR:
896 CLOGE("Device has encountered a serious error");
897 return INVALID_OPERATION;
898 case STATUS_UNINITIALIZED:
899 CLOGE("Device not initialized");
900 return INVALID_OPERATION;
901 case STATUS_UNCONFIGURED:
902 case STATUS_CONFIGURED:
903 case STATUS_ACTIVE:
904 // OK
905 break;
906 default:
907 SET_ERR_L("Unexpected status: %d", mStatus);
908 return INVALID_OPERATION;
909 }
910 return OK;
911}
912
913status_t Camera3Device::convertMetadataListToRequestListLocked(
Emilian Peevaebbe412018-01-15 13:53:24 +0000914 const List<const PhysicalCameraSettingsList> &metadataList,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700915 const std::list<const SurfaceMap> &surfaceMaps,
Shuzhen Wang316781a2020-08-18 18:11:01 -0700916 bool repeating, nsecs_t requestTimeNs,
Shuzhen Wang9d066012016-09-30 11:30:20 -0700917 RequestList *requestList) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700918 if (requestList == NULL) {
919 CLOGE("requestList cannot be NULL.");
920 return BAD_VALUE;
921 }
922
Jianing Weicb0652e2014-03-12 18:29:36 -0700923 int32_t burstId = 0;
Emilian Peevaebbe412018-01-15 13:53:24 +0000924 List<const PhysicalCameraSettingsList>::const_iterator metadataIt = metadataList.begin();
Shuzhen Wang0129d522016-10-30 22:43:41 -0700925 std::list<const SurfaceMap>::const_iterator surfaceMapIt = surfaceMaps.begin();
926 for (; metadataIt != metadataList.end() && surfaceMapIt != surfaceMaps.end();
927 ++metadataIt, ++surfaceMapIt) {
928 sp<CaptureRequest> newRequest = setUpRequestLocked(*metadataIt, *surfaceMapIt);
Jianing Wei90e59c92014-03-12 18:29:36 -0700929 if (newRequest == 0) {
930 CLOGE("Can't create capture request");
931 return BAD_VALUE;
932 }
Jianing Weicb0652e2014-03-12 18:29:36 -0700933
Shuzhen Wang9d066012016-09-30 11:30:20 -0700934 newRequest->mRepeating = repeating;
Shuzhen Wang316781a2020-08-18 18:11:01 -0700935 newRequest->mRequestTimeNs = requestTimeNs;
Shuzhen Wang9d066012016-09-30 11:30:20 -0700936
Jianing Weicb0652e2014-03-12 18:29:36 -0700937 // Setup burst Id and request Id
938 newRequest->mResultExtras.burstId = burstId++;
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -0800939 auto requestIdEntry = metadataIt->begin()->metadata.find(ANDROID_REQUEST_ID);
940 if (requestIdEntry.count == 0) {
Jianing Weicb0652e2014-03-12 18:29:36 -0700941 CLOGE("RequestID does not exist in metadata");
942 return BAD_VALUE;
943 }
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -0800944 newRequest->mResultExtras.requestId = requestIdEntry.data.i32[0];
Jianing Weicb0652e2014-03-12 18:29:36 -0700945
Jianing Wei90e59c92014-03-12 18:29:36 -0700946 requestList->push_back(newRequest);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700947
948 ALOGV("%s: requestId = %" PRId32, __FUNCTION__, newRequest->mResultExtras.requestId);
Jianing Wei90e59c92014-03-12 18:29:36 -0700949 }
Shuzhen Wang0129d522016-10-30 22:43:41 -0700950 if (metadataIt != metadataList.end() || surfaceMapIt != surfaceMaps.end()) {
951 ALOGE("%s: metadataList and surfaceMaps are not the same size!", __FUNCTION__);
952 return BAD_VALUE;
953 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -0700954
955 // Setup batch size if this is a high speed video recording request.
956 if (mIsConstrainedHighSpeedConfiguration && requestList->size() > 0) {
957 auto firstRequest = requestList->begin();
958 for (auto& outputStream : (*firstRequest)->mOutputStreams) {
959 if (outputStream->isVideoStream()) {
960 (*firstRequest)->mBatchSize = requestList->size();
Yin-Chia Yeh14ef48d2020-02-10 15:06:37 -0800961 outputStream->setBatchSize(requestList->size());
Chien-Yu Chen85a64552015-08-28 15:46:12 -0700962 break;
963 }
964 }
965 }
966
Jianing Wei90e59c92014-03-12 18:29:36 -0700967 return OK;
968}
969
Yin-Chia Yeh7e5a2042019-02-06 16:01:06 -0800970status_t Camera3Device::capture(CameraMetadata &request, int64_t* lastFrameNumber) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800971 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800972
Emilian Peevaebbe412018-01-15 13:53:24 +0000973 List<const PhysicalCameraSettingsList> requestsList;
Shuzhen Wang0129d522016-10-30 22:43:41 -0700974 std::list<const SurfaceMap> surfaceMaps;
Emilian Peevaebbe412018-01-15 13:53:24 +0000975 convertToRequestList(requestsList, surfaceMaps, request);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700976
Yin-Chia Yeh7e5a2042019-02-06 16:01:06 -0800977 return captureList(requestsList, surfaceMaps, lastFrameNumber);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700978}
979
Emilian Peevaebbe412018-01-15 13:53:24 +0000980void Camera3Device::convertToRequestList(List<const PhysicalCameraSettingsList>& requestsList,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700981 std::list<const SurfaceMap>& surfaceMaps,
982 const CameraMetadata& request) {
Emilian Peevaebbe412018-01-15 13:53:24 +0000983 PhysicalCameraSettingsList requestList;
984 requestList.push_back({std::string(getId().string()), request});
985 requestsList.push_back(requestList);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700986
987 SurfaceMap surfaceMap;
988 camera_metadata_ro_entry streams = request.find(ANDROID_REQUEST_OUTPUT_STREAMS);
989 // With no surface list passed in, stream and surface will have 1-to-1
990 // mapping. So the surface index is 0 for each stream in the surfaceMap.
991 for (size_t i = 0; i < streams.count; i++) {
992 surfaceMap[streams.data.i32[i]].push_back(0);
993 }
994 surfaceMaps.push_back(surfaceMap);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800995}
996
Jianing Wei90e59c92014-03-12 18:29:36 -0700997status_t Camera3Device::submitRequestsHelper(
Emilian Peevaebbe412018-01-15 13:53:24 +0000998 const List<const PhysicalCameraSettingsList> &requests,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700999 const std::list<const SurfaceMap> &surfaceMaps,
1000 bool repeating,
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07001001 /*out*/
1002 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -07001003 ATRACE_CALL();
Shuzhen Wang316781a2020-08-18 18:11:01 -07001004 nsecs_t requestTimeNs = systemTime();
1005
Jianing Wei90e59c92014-03-12 18:29:36 -07001006 Mutex::Autolock il(mInterfaceLock);
1007 Mutex::Autolock l(mLock);
1008
1009 status_t res = checkStatusOkToCaptureLocked();
1010 if (res != OK) {
1011 // error logged by previous call
1012 return res;
1013 }
1014
1015 RequestList requestList;
1016
Shuzhen Wang0129d522016-10-30 22:43:41 -07001017 res = convertMetadataListToRequestListLocked(requests, surfaceMaps,
Shuzhen Wang316781a2020-08-18 18:11:01 -07001018 repeating, requestTimeNs, /*out*/&requestList);
Jianing Wei90e59c92014-03-12 18:29:36 -07001019 if (res != OK) {
1020 // error logged by previous call
1021 return res;
1022 }
1023
1024 if (repeating) {
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07001025 res = mRequestThread->setRepeatingRequests(requestList, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -07001026 } else {
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07001027 res = mRequestThread->queueRequestList(requestList, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -07001028 }
1029
1030 if (res == OK) {
1031 waitUntilStateThenRelock(/*active*/true, kActiveTimeout);
1032 if (res != OK) {
1033 SET_ERR_L("Can't transition to active in %f seconds!",
1034 kActiveTimeout/1e9);
1035 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001036 ALOGV("Camera %s: Capture request %" PRId32 " enqueued", mId.string(),
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07001037 (*(requestList.begin()))->mResultExtras.requestId);
Jianing Wei90e59c92014-03-12 18:29:36 -07001038 } else {
1039 CLOGE("Cannot queue request. Impossible.");
1040 return BAD_VALUE;
1041 }
1042
1043 return res;
1044}
1045
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001046hardware::Return<void> Camera3Device::requestStreamBuffers(
1047 const hardware::hidl_vec<hardware::camera::device::V3_5::BufferRequest>& bufReqs,
1048 requestStreamBuffers_cb _hidl_cb) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001049 RequestBufferStates states {
Shuzhen Wang316781a2020-08-18 18:11:01 -07001050 mId, mRequestBufferInterfaceLock, mUseHalBufManager, mOutputStreams, mSessionStatsBuilder,
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001051 *this, *mInterface, *this};
1052 camera3::requestStreamBuffers(states, bufReqs, _hidl_cb);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001053 return hardware::Void();
1054}
1055
1056hardware::Return<void> Camera3Device::returnStreamBuffers(
1057 const hardware::hidl_vec<hardware::camera::device::V3_2::StreamBuffer>& buffers) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001058 ReturnBufferStates states {
Shuzhen Wang316781a2020-08-18 18:11:01 -07001059 mId, mUseHalBufManager, mOutputStreams, mSessionStatsBuilder, *mInterface};
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001060 camera3::returnStreamBuffers(states, buffers);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001061 return hardware::Void();
1062}
1063
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001064hardware::Return<void> Camera3Device::processCaptureResult_3_4(
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001065 const hardware::hidl_vec<
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001066 hardware::camera::device::V3_4::CaptureResult>& results) {
Yin-Chia Yeh657c1872017-07-18 18:09:57 -07001067 // Ideally we should grab mLock, but that can lead to deadlock, and
1068 // it's not super important to get up to date value of mStatus for this
1069 // warning print, hence skipping the lock here
1070 if (mStatus == STATUS_ERROR) {
1071 // Per API contract, HAL should act as closed after device error
1072 // But mStatus can be set to error by framework as well, so just log
1073 // a warning here.
1074 ALOGW("%s: received capture result in error state.", __FUNCTION__);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07001075 }
Yifan Honga640c5a2017-04-12 16:30:31 -07001076
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001077 sp<NotificationListener> listener;
1078 {
1079 std::lock_guard<std::mutex> l(mOutputLock);
1080 listener = mListener.promote();
1081 }
1082
Yifan Honga640c5a2017-04-12 16:30:31 -07001083 if (mProcessCaptureResultLock.tryLock() != OK) {
1084 // This should never happen; it indicates a wrong client implementation
1085 // that doesn't follow the contract. But, we can be tolerant here.
1086 ALOGE("%s: callback overlapped! waiting 1s...",
1087 __FUNCTION__);
1088 if (mProcessCaptureResultLock.timedLock(1000000000 /* 1s */) != OK) {
1089 ALOGE("%s: cannot acquire lock in 1s, dropping results",
1090 __FUNCTION__);
1091 // really don't know what to do, so bail out.
1092 return hardware::Void();
1093 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001094 }
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001095 CaptureOutputStates states {
1096 mId,
Shuzhen Wangb7b42652020-05-07 11:59:02 -07001097 mInFlightLock, mLastCompletedRegularFrameNumber,
1098 mLastCompletedReprocessFrameNumber, mLastCompletedZslFrameNumber,
1099 mInFlightMap, mOutputLock, mResultQueue, mResultSignal,
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001100 mNextShutterFrameNumber,
1101 mNextReprocessShutterFrameNumber, mNextZslStillShutterFrameNumber,
1102 mNextResultFrameNumber,
1103 mNextReprocessResultFrameNumber, mNextZslStillResultFrameNumber,
1104 mUseHalBufManager, mUsePartialResult, mNeedFixupMonochromeTags,
1105 mNumPartialResults, mVendorTagId, mDeviceInfo, mPhysicalDeviceInfoMap,
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08001106 mResultMetadataQueue, mDistortionMappers, mZoomRatioMappers, mRotateAndCropMappers,
Shuzhen Wang316781a2020-08-18 18:11:01 -07001107 mTagMonitor, mInputStream, mOutputStreams, mSessionStatsBuilder, listener, *this, *this,
Emilian Peev5104fe92021-10-21 14:27:09 -07001108 *mInterface, mLegacyClient
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001109 };
1110
Yifan Honga640c5a2017-04-12 16:30:31 -07001111 for (const auto& result : results) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001112 processOneCaptureResultLocked(states, result.v3_2, result.physicalCameraMetadata);
Yifan Honga640c5a2017-04-12 16:30:31 -07001113 }
1114 mProcessCaptureResultLock.unlock();
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001115 return hardware::Void();
1116}
1117
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001118// Only one processCaptureResult should be called at a time, so
1119// the locks won't block. The locks are present here simply to enforce this.
1120hardware::Return<void> Camera3Device::processCaptureResult(
1121 const hardware::hidl_vec<
1122 hardware::camera::device::V3_2::CaptureResult>& results) {
1123 hardware::hidl_vec<hardware::camera::device::V3_4::PhysicalCameraMetadata> noPhysMetadata;
1124
1125 // Ideally we should grab mLock, but that can lead to deadlock, and
1126 // it's not super important to get up to date value of mStatus for this
1127 // warning print, hence skipping the lock here
1128 if (mStatus == STATUS_ERROR) {
1129 // Per API contract, HAL should act as closed after device error
1130 // But mStatus can be set to error by framework as well, so just log
1131 // a warning here.
1132 ALOGW("%s: received capture result in error state.", __FUNCTION__);
1133 }
1134
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001135 sp<NotificationListener> listener;
1136 {
1137 std::lock_guard<std::mutex> l(mOutputLock);
1138 listener = mListener.promote();
1139 }
1140
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001141 if (mProcessCaptureResultLock.tryLock() != OK) {
1142 // This should never happen; it indicates a wrong client implementation
1143 // that doesn't follow the contract. But, we can be tolerant here.
1144 ALOGE("%s: callback overlapped! waiting 1s...",
1145 __FUNCTION__);
1146 if (mProcessCaptureResultLock.timedLock(1000000000 /* 1s */) != OK) {
1147 ALOGE("%s: cannot acquire lock in 1s, dropping results",
1148 __FUNCTION__);
1149 // really don't know what to do, so bail out.
1150 return hardware::Void();
1151 }
1152 }
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001153
1154 CaptureOutputStates states {
1155 mId,
Shuzhen Wangb7b42652020-05-07 11:59:02 -07001156 mInFlightLock, mLastCompletedRegularFrameNumber,
1157 mLastCompletedReprocessFrameNumber, mLastCompletedZslFrameNumber,
1158 mInFlightMap, mOutputLock, mResultQueue, mResultSignal,
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001159 mNextShutterFrameNumber,
1160 mNextReprocessShutterFrameNumber, mNextZslStillShutterFrameNumber,
1161 mNextResultFrameNumber,
1162 mNextReprocessResultFrameNumber, mNextZslStillResultFrameNumber,
1163 mUseHalBufManager, mUsePartialResult, mNeedFixupMonochromeTags,
1164 mNumPartialResults, mVendorTagId, mDeviceInfo, mPhysicalDeviceInfoMap,
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08001165 mResultMetadataQueue, mDistortionMappers, mZoomRatioMappers, mRotateAndCropMappers,
Shuzhen Wang316781a2020-08-18 18:11:01 -07001166 mTagMonitor, mInputStream, mOutputStreams, mSessionStatsBuilder, listener, *this, *this,
Emilian Peev5104fe92021-10-21 14:27:09 -07001167 *mInterface, mLegacyClient
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001168 };
1169
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001170 for (const auto& result : results) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001171 processOneCaptureResultLocked(states, result, noPhysMetadata);
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001172 }
1173 mProcessCaptureResultLock.unlock();
1174 return hardware::Void();
1175}
1176
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001177hardware::Return<void> Camera3Device::notify(
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001178 const hardware::hidl_vec<hardware::camera::device::V3_2::NotifyMsg>& msgs) {
Shuzhen Wang90708ea2021-11-04 11:40:49 -07001179 return notifyHelper<hardware::camera::device::V3_2::NotifyMsg>(msgs);
1180}
1181
1182hardware::Return<void> Camera3Device::notify_3_8(
1183 const hardware::hidl_vec<hardware::camera::device::V3_8::NotifyMsg>& msgs) {
1184 return notifyHelper<hardware::camera::device::V3_8::NotifyMsg>(msgs);
1185}
1186
1187template<typename NotifyMsgType>
1188hardware::Return<void> Camera3Device::notifyHelper(const hardware::hidl_vec<NotifyMsgType>& msgs) {
Yin-Chia Yeh657c1872017-07-18 18:09:57 -07001189 // Ideally we should grab mLock, but that can lead to deadlock, and
1190 // it's not super important to get up to date value of mStatus for this
1191 // warning print, hence skipping the lock here
1192 if (mStatus == STATUS_ERROR) {
1193 // Per API contract, HAL should act as closed after device error
1194 // But mStatus can be set to error by framework as well, so just log
1195 // a warning here.
1196 ALOGW("%s: received notify message in error state.", __FUNCTION__);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07001197 }
Yin-Chia Yeh657c1872017-07-18 18:09:57 -07001198
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001199 sp<NotificationListener> listener;
1200 {
1201 std::lock_guard<std::mutex> l(mOutputLock);
1202 listener = mListener.promote();
1203 }
1204
1205 CaptureOutputStates states {
1206 mId,
Shuzhen Wangb7b42652020-05-07 11:59:02 -07001207 mInFlightLock, mLastCompletedRegularFrameNumber,
1208 mLastCompletedReprocessFrameNumber, mLastCompletedZslFrameNumber,
1209 mInFlightMap, mOutputLock, mResultQueue, mResultSignal,
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001210 mNextShutterFrameNumber,
1211 mNextReprocessShutterFrameNumber, mNextZslStillShutterFrameNumber,
1212 mNextResultFrameNumber,
1213 mNextReprocessResultFrameNumber, mNextZslStillResultFrameNumber,
1214 mUseHalBufManager, mUsePartialResult, mNeedFixupMonochromeTags,
1215 mNumPartialResults, mVendorTagId, mDeviceInfo, mPhysicalDeviceInfoMap,
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08001216 mResultMetadataQueue, mDistortionMappers, mZoomRatioMappers, mRotateAndCropMappers,
Shuzhen Wang316781a2020-08-18 18:11:01 -07001217 mTagMonitor, mInputStream, mOutputStreams, mSessionStatsBuilder, listener, *this, *this,
Emilian Peev5104fe92021-10-21 14:27:09 -07001218 *mInterface, mLegacyClient
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001219 };
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001220 for (const auto& msg : msgs) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001221 camera3::notify(states, msg);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001222 }
1223 return hardware::Void();
1224}
1225
Emilian Peevaebbe412018-01-15 13:53:24 +00001226status_t Camera3Device::captureList(const List<const PhysicalCameraSettingsList> &requestsList,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001227 const std::list<const SurfaceMap> &surfaceMaps,
Jianing Weicb0652e2014-03-12 18:29:36 -07001228 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -07001229 ATRACE_CALL();
1230
Emilian Peevaebbe412018-01-15 13:53:24 +00001231 return submitRequestsHelper(requestsList, surfaceMaps, /*repeating*/false, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -07001232}
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001233
Jianing Weicb0652e2014-03-12 18:29:36 -07001234status_t Camera3Device::setStreamingRequest(const CameraMetadata &request,
1235 int64_t* /*lastFrameNumber*/) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001236 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001237
Emilian Peevaebbe412018-01-15 13:53:24 +00001238 List<const PhysicalCameraSettingsList> requestsList;
Shuzhen Wang0129d522016-10-30 22:43:41 -07001239 std::list<const SurfaceMap> surfaceMaps;
Emilian Peevaebbe412018-01-15 13:53:24 +00001240 convertToRequestList(requestsList, surfaceMaps, request);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001241
Emilian Peevaebbe412018-01-15 13:53:24 +00001242 return setStreamingRequestList(requestsList, /*surfaceMap*/surfaceMaps,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001243 /*lastFrameNumber*/NULL);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001244}
1245
Emilian Peevaebbe412018-01-15 13:53:24 +00001246status_t Camera3Device::setStreamingRequestList(
1247 const List<const PhysicalCameraSettingsList> &requestsList,
1248 const std::list<const SurfaceMap> &surfaceMaps, int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -07001249 ATRACE_CALL();
1250
Emilian Peevaebbe412018-01-15 13:53:24 +00001251 return submitRequestsHelper(requestsList, surfaceMaps, /*repeating*/true, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -07001252}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001253
1254sp<Camera3Device::CaptureRequest> Camera3Device::setUpRequestLocked(
Emilian Peevaebbe412018-01-15 13:53:24 +00001255 const PhysicalCameraSettingsList &request, const SurfaceMap &surfaceMap) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001256 status_t res;
1257
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001258 if (mStatus == STATUS_UNCONFIGURED || mNeedConfig) {
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08001259 // This point should only be reached via API1 (API2 must explicitly call configureStreams)
1260 // so unilaterally select normal operating mode.
Emilian Peevaebbe412018-01-15 13:53:24 +00001261 res = filterParamsAndConfigureLocked(request.begin()->metadata,
Emilian Peevf4816702020-04-03 15:44:51 -07001262 CAMERA_STREAM_CONFIGURATION_NORMAL_MODE);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001263 // Stream configuration failed. Client might try other configuraitons.
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001264 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001265 CLOGE("Can't set up streams: %s (%d)", strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001266 return NULL;
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001267 } else if (mStatus == STATUS_UNCONFIGURED) {
1268 // Stream configuration successfully configure to empty stream configuration.
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001269 CLOGE("No streams configured");
1270 return NULL;
1271 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001272 }
1273
Shuzhen Wang0129d522016-10-30 22:43:41 -07001274 sp<CaptureRequest> newRequest = createCaptureRequest(request, surfaceMap);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001275 return newRequest;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001276}
1277
Jianing Weicb0652e2014-03-12 18:29:36 -07001278status_t Camera3Device::clearStreamingRequest(int64_t *lastFrameNumber) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001279 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001280 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001281 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001282
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001283 switch (mStatus) {
1284 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001285 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001286 return INVALID_OPERATION;
1287 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001288 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001289 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001290 case STATUS_UNCONFIGURED:
1291 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001292 case STATUS_ACTIVE:
1293 // OK
1294 break;
1295 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001296 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001297 return INVALID_OPERATION;
1298 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001299 ALOGV("Camera %s: Clearing repeating request", mId.string());
Jianing Weicb0652e2014-03-12 18:29:36 -07001300
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07001301 return mRequestThread->clearRepeatingRequests(lastFrameNumber);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001302}
1303
1304status_t Camera3Device::waitUntilRequestReceived(int32_t requestId, nsecs_t timeout) {
1305 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001306 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001307
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001308 return mRequestThread->waitUntilRequestProcessed(requestId, timeout);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001309}
1310
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001311status_t Camera3Device::createInputStream(
Shuzhen Wang83bff122020-11-20 15:51:39 -08001312 uint32_t width, uint32_t height, int format, bool isMultiResolution, int *id) {
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001313 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001314 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001315 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001316 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001317 ALOGV("Camera %s: Creating new input stream %d: %d x %d, format %d",
1318 mId.string(), mNextStreamId, width, height, format);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001319
1320 status_t res;
1321 bool wasActive = false;
1322
1323 switch (mStatus) {
1324 case STATUS_ERROR:
1325 ALOGE("%s: Device has encountered a serious error", __FUNCTION__);
1326 return INVALID_OPERATION;
1327 case STATUS_UNINITIALIZED:
1328 ALOGE("%s: Device not initialized", __FUNCTION__);
1329 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001330 case STATUS_UNCONFIGURED:
1331 case STATUS_CONFIGURED:
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001332 // OK
1333 break;
1334 case STATUS_ACTIVE:
1335 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001336 res = internalPauseAndWaitLocked(maxExpectedDuration);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001337 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001338 SET_ERR_L("Can't pause captures to reconfigure streams!");
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001339 return res;
1340 }
1341 wasActive = true;
1342 break;
1343 default:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001344 SET_ERR_L("%s: Unexpected status: %d", mStatus);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001345 return INVALID_OPERATION;
1346 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001347 assert(mStatus != STATUS_ACTIVE);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001348
1349 if (mInputStream != 0) {
1350 ALOGE("%s: Cannot create more than 1 input stream", __FUNCTION__);
1351 return INVALID_OPERATION;
1352 }
1353
1354 sp<Camera3InputStream> newStream = new Camera3InputStream(mNextStreamId,
1355 width, height, format);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001356 newStream->setStatusTracker(mStatusTracker);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001357
1358 mInputStream = newStream;
Shuzhen Wang83bff122020-11-20 15:51:39 -08001359 mIsInputStreamMultiResolution = isMultiResolution;
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001360
1361 *id = mNextStreamId++;
1362
1363 // Continue captures if active at start
1364 if (wasActive) {
1365 ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001366 // Reuse current operating mode and session parameters for new stream config
1367 res = configureStreamsLocked(mOperatingMode, mSessionParams);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001368 if (res != OK) {
1369 ALOGE("%s: Can't reconfigure device for new stream %d: %s (%d)",
1370 __FUNCTION__, mNextStreamId, strerror(-res), res);
1371 return res;
1372 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001373 internalResumeLocked();
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001374 }
1375
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001376 ALOGV("Camera %s: Created input stream", mId.string());
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001377 return OK;
1378}
1379
Eino-Ville Talvala727d1722015-06-09 13:44:19 -07001380status_t Camera3Device::createStream(sp<Surface> consumer,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001381 uint32_t width, uint32_t height, int format,
Emilian Peevf4816702020-04-03 15:44:51 -07001382 android_dataspace dataSpace, camera_stream_rotation_t rotation, int *id,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001383 const String8& physicalCameraId,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001384 const std::unordered_set<int32_t> &sensorPixelModesUsed,
1385 std::vector<int> *surfaceIds, int streamSetId, bool isShared, bool isMultiResolution,
1386 uint64_t consumerUsage) {
Shuzhen Wang0129d522016-10-30 22:43:41 -07001387 ATRACE_CALL();
1388
1389 if (consumer == nullptr) {
1390 ALOGE("%s: consumer must not be null", __FUNCTION__);
1391 return BAD_VALUE;
1392 }
1393
1394 std::vector<sp<Surface>> consumers;
1395 consumers.push_back(consumer);
1396
1397 return createStream(consumers, /*hasDeferredConsumer*/ false, width, height,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001398 format, dataSpace, rotation, id, physicalCameraId, sensorPixelModesUsed, surfaceIds,
1399 streamSetId, isShared, isMultiResolution, consumerUsage);
1400}
1401
1402static bool isRawFormat(int format) {
1403 switch (format) {
1404 case HAL_PIXEL_FORMAT_RAW16:
1405 case HAL_PIXEL_FORMAT_RAW12:
1406 case HAL_PIXEL_FORMAT_RAW10:
1407 case HAL_PIXEL_FORMAT_RAW_OPAQUE:
1408 return true;
1409 default:
1410 return false;
1411 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001412}
1413
1414status_t Camera3Device::createStream(const std::vector<sp<Surface>>& consumers,
1415 bool hasDeferredConsumer, uint32_t width, uint32_t height, int format,
Emilian Peevf4816702020-04-03 15:44:51 -07001416 android_dataspace dataSpace, camera_stream_rotation_t rotation, int *id,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001417 const String8& physicalCameraId, const std::unordered_set<int32_t> &sensorPixelModesUsed,
Shuzhen Wang83bff122020-11-20 15:51:39 -08001418 std::vector<int> *surfaceIds, int streamSetId, bool isShared, bool isMultiResolution,
1419 uint64_t consumerUsage) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001420 ATRACE_CALL();
Emilian Peev40ead602017-09-26 15:46:36 +01001421
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001422 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001423 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001424 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001425 ALOGV("Camera %s: Creating new stream %d: %d x %d, format %d, dataspace %d rotation %d"
Shuzhen Wang83bff122020-11-20 15:51:39 -08001426 " consumer usage %" PRIu64 ", isShared %d, physicalCameraId %s, isMultiResolution %d",
1427 mId.string(), mNextStreamId, width, height, format, dataSpace, rotation,
1428 consumerUsage, isShared, physicalCameraId.string(), isMultiResolution);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001429
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001430 status_t res;
1431 bool wasActive = false;
1432
1433 switch (mStatus) {
1434 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001435 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001436 return INVALID_OPERATION;
1437 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001438 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001439 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001440 case STATUS_UNCONFIGURED:
1441 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001442 // OK
1443 break;
1444 case STATUS_ACTIVE:
1445 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001446 res = internalPauseAndWaitLocked(maxExpectedDuration);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001447 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001448 SET_ERR_L("Can't pause captures to reconfigure streams!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001449 return res;
1450 }
1451 wasActive = true;
1452 break;
1453 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001454 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001455 return INVALID_OPERATION;
1456 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001457 assert(mStatus != STATUS_ACTIVE);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001458
1459 sp<Camera3OutputStream> newStream;
Zhijun He5d677d12016-05-29 16:52:39 -07001460
Shuzhen Wang0129d522016-10-30 22:43:41 -07001461 if (consumers.size() == 0 && !hasDeferredConsumer) {
1462 ALOGE("%s: Number of consumers cannot be smaller than 1", __FUNCTION__);
1463 return BAD_VALUE;
1464 }
Zhijun He5d677d12016-05-29 16:52:39 -07001465
Shuzhen Wang0129d522016-10-30 22:43:41 -07001466 if (hasDeferredConsumer && format != HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
Zhijun He5d677d12016-05-29 16:52:39 -07001467 ALOGE("Deferred consumer stream creation only support IMPLEMENTATION_DEFINED format");
1468 return BAD_VALUE;
1469 }
1470
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001471 if (isRawFormat(format) && sensorPixelModesUsed.size() > 1) {
1472 // We can't use one stream with a raw format in both sensor pixel modes since its going to
1473 // be found in only one sensor pixel mode.
1474 ALOGE("%s: RAW opaque stream cannot be used with > 1 sensor pixel modes", __FUNCTION__);
1475 return BAD_VALUE;
1476 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001477 if (format == HAL_PIXEL_FORMAT_BLOB) {
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -07001478 ssize_t blobBufferSize;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001479 if (dataSpace == HAL_DATASPACE_DEPTH) {
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -07001480 blobBufferSize = getPointCloudBufferSize();
1481 if (blobBufferSize <= 0) {
1482 SET_ERR_L("Invalid point cloud buffer size %zd", blobBufferSize);
1483 return BAD_VALUE;
1484 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001485 } else if (dataSpace == static_cast<android_dataspace>(HAL_DATASPACE_JPEG_APP_SEGMENTS)) {
1486 blobBufferSize = width * height;
1487 } else {
1488 blobBufferSize = getJpegBufferSize(width, height);
1489 if (blobBufferSize <= 0) {
1490 SET_ERR_L("Invalid jpeg buffer size %zd", blobBufferSize);
1491 return BAD_VALUE;
1492 }
Zhijun Hef7da0962014-04-24 13:27:56 -07001493 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001494 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001495 width, height, blobBufferSize, format, dataSpace, rotation,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001496 mTimestampOffset, physicalCameraId, sensorPixelModesUsed, streamSetId,
1497 isMultiResolution);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -08001498 } else if (format == HAL_PIXEL_FORMAT_RAW_OPAQUE) {
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001499 bool maxResolution =
1500 sensorPixelModesUsed.find(ANDROID_SENSOR_PIXEL_MODE_MAXIMUM_RESOLUTION) !=
1501 sensorPixelModesUsed.end();
1502 ssize_t rawOpaqueBufferSize = getRawOpaqueBufferSize(width, height, maxResolution);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -08001503 if (rawOpaqueBufferSize <= 0) {
1504 SET_ERR_L("Invalid RAW opaque buffer size %zd", rawOpaqueBufferSize);
1505 return BAD_VALUE;
1506 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001507 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001508 width, height, rawOpaqueBufferSize, format, dataSpace, rotation,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001509 mTimestampOffset, physicalCameraId, sensorPixelModesUsed, streamSetId,
1510 isMultiResolution);
Shuzhen Wang758c2152017-01-10 18:26:18 -08001511 } else if (isShared) {
1512 newStream = new Camera3SharedOutputStream(mNextStreamId, consumers,
1513 width, height, format, consumerUsage, dataSpace, rotation,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001514 mTimestampOffset, physicalCameraId, sensorPixelModesUsed, streamSetId,
1515 mUseHalBufManager);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001516 } else if (consumers.size() == 0 && hasDeferredConsumer) {
Zhijun He5d677d12016-05-29 16:52:39 -07001517 newStream = new Camera3OutputStream(mNextStreamId,
1518 width, height, format, consumerUsage, dataSpace, rotation,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001519 mTimestampOffset, physicalCameraId, sensorPixelModesUsed, streamSetId,
1520 isMultiResolution);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001521 } else {
Shuzhen Wang0129d522016-10-30 22:43:41 -07001522 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001523 width, height, format, dataSpace, rotation,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001524 mTimestampOffset, physicalCameraId, sensorPixelModesUsed, streamSetId,
1525 isMultiResolution);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001526 }
Emilian Peev40ead602017-09-26 15:46:36 +01001527
1528 size_t consumerCount = consumers.size();
1529 for (size_t i = 0; i < consumerCount; i++) {
1530 int id = newStream->getSurfaceId(consumers[i]);
1531 if (id < 0) {
1532 SET_ERR_L("Invalid surface id");
1533 return BAD_VALUE;
1534 }
1535 if (surfaceIds != nullptr) {
1536 surfaceIds->push_back(id);
1537 }
1538 }
1539
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001540 newStream->setStatusTracker(mStatusTracker);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001541
Emilian Peev08dd2452017-04-06 16:55:14 +01001542 newStream->setBufferManager(mBufferManager);
Zhijun He125684a2015-12-26 15:07:30 -08001543
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08001544 newStream->setImageDumpMask(mImageDumpMask);
1545
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001546 res = mOutputStreams.add(mNextStreamId, newStream);
1547 if (res < 0) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001548 SET_ERR_L("Can't add new stream to set: %s (%d)", strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001549 return res;
1550 }
1551
Shuzhen Wang316781a2020-08-18 18:11:01 -07001552 mSessionStatsBuilder.addStream(mNextStreamId);
1553
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001554 *id = mNextStreamId++;
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07001555 mNeedConfig = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001556
1557 // Continue captures if active at start
1558 if (wasActive) {
1559 ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001560 // Reuse current operating mode and session parameters for new stream config
1561 res = configureStreamsLocked(mOperatingMode, mSessionParams);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001562 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001563 CLOGE("Can't reconfigure device for new stream %d: %s (%d)",
1564 mNextStreamId, strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001565 return res;
1566 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001567 internalResumeLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001568 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001569 ALOGV("Camera %s: Created new stream", mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001570 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001571}
1572
Emilian Peev710c1422017-08-30 11:19:38 +01001573status_t Camera3Device::getStreamInfo(int id, StreamInfo *streamInfo) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001574 ATRACE_CALL();
Emilian Peev710c1422017-08-30 11:19:38 +01001575 if (nullptr == streamInfo) {
1576 return BAD_VALUE;
1577 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001578 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001579 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001580
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001581 switch (mStatus) {
1582 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001583 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001584 return INVALID_OPERATION;
1585 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001586 CLOGE("Device not initialized!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001587 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001588 case STATUS_UNCONFIGURED:
1589 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001590 case STATUS_ACTIVE:
1591 // OK
1592 break;
1593 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001594 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001595 return INVALID_OPERATION;
1596 }
1597
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001598 sp<Camera3StreamInterface> stream = mOutputStreams.get(id);
1599 if (stream == nullptr) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001600 CLOGE("Stream %d is unknown", id);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001601 return BAD_VALUE;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001602 }
1603
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001604 streamInfo->width = stream->getWidth();
1605 streamInfo->height = stream->getHeight();
1606 streamInfo->format = stream->getFormat();
1607 streamInfo->dataSpace = stream->getDataSpace();
1608 streamInfo->formatOverridden = stream->isFormatOverridden();
1609 streamInfo->originalFormat = stream->getOriginalFormat();
1610 streamInfo->dataSpaceOverridden = stream->isDataSpaceOverridden();
1611 streamInfo->originalDataSpace = stream->getOriginalDataSpace();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001612 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001613}
1614
1615status_t Camera3Device::setStreamTransform(int id,
1616 int transform) {
1617 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001618 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001619 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001620
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001621 switch (mStatus) {
1622 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001623 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001624 return INVALID_OPERATION;
1625 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001626 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001627 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001628 case STATUS_UNCONFIGURED:
1629 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001630 case STATUS_ACTIVE:
1631 // OK
1632 break;
1633 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001634 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001635 return INVALID_OPERATION;
1636 }
1637
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001638 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(id);
1639 if (stream == nullptr) {
1640 CLOGE("Stream %d does not exist", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001641 return BAD_VALUE;
1642 }
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001643 return stream->setTransform(transform);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001644}
1645
1646status_t Camera3Device::deleteStream(int id) {
1647 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001648 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001649 Mutex::Autolock l(mLock);
1650 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001651
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001652 ALOGV("%s: Camera %s: Deleting stream %d", __FUNCTION__, mId.string(), id);
Igor Murashkine2172be2013-05-28 15:31:39 -07001653
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001654 // CameraDevice semantics require device to already be idle before
1655 // deleteStream is called, unlike for createStream.
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001656 if (mStatus == STATUS_ACTIVE) {
Yin-Chia Yeh693047d2018-03-08 12:14:19 -08001657 ALOGW("%s: Camera %s: Device not idle", __FUNCTION__, mId.string());
Igor Murashkin52827132013-05-13 14:53:44 -07001658 return -EBUSY;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001659 }
1660
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07001661 if (mStatus == STATUS_ERROR) {
1662 ALOGW("%s: Camera %s: deleteStream not allowed in ERROR state",
1663 __FUNCTION__, mId.string());
1664 return -EBUSY;
1665 }
1666
Igor Murashkin2fba5842013-04-22 14:03:54 -07001667 sp<Camera3StreamInterface> deletedStream;
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001668 sp<Camera3StreamInterface> stream = mOutputStreams.get(id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001669 if (mInputStream != NULL && id == mInputStream->getId()) {
1670 deletedStream = mInputStream;
1671 mInputStream.clear();
1672 } else {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001673 if (stream == nullptr) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001674 CLOGE("Stream %d does not exist", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001675 return BAD_VALUE;
1676 }
Shuzhen Wang316781a2020-08-18 18:11:01 -07001677 mSessionStatsBuilder.removeStream(id);
Zhijun He5f446352014-01-22 09:49:33 -08001678 }
1679
1680 // Delete output stream or the output part of a bi-directional stream.
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001681 if (stream != nullptr) {
1682 deletedStream = stream;
1683 mOutputStreams.remove(id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001684 }
1685
1686 // Free up the stream endpoint so that it can be used by some other stream
1687 res = deletedStream->disconnect();
1688 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001689 SET_ERR_L("Can't disconnect deleted stream %d", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001690 // fall through since we want to still list the stream as deleted.
1691 }
1692 mDeletedStreams.add(deletedStream);
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07001693 mNeedConfig = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001694
1695 return res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001696}
1697
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001698status_t Camera3Device::configureStreams(const CameraMetadata& sessionParams, int operatingMode) {
Igor Murashkine2d167e2014-08-19 16:19:59 -07001699 ATRACE_CALL();
1700 ALOGV("%s: E", __FUNCTION__);
1701
1702 Mutex::Autolock il(mInterfaceLock);
1703 Mutex::Autolock l(mLock);
Chien-Yu Chen17338fc2015-06-18 16:30:12 -07001704
Emilian Peev811d2952018-05-25 11:08:40 +01001705 // In case the client doesn't include any session parameter, try a
1706 // speculative configuration using the values from the last cached
1707 // default request.
1708 if (sessionParams.isEmpty() &&
Emilian Peevf4816702020-04-03 15:44:51 -07001709 ((mLastTemplateId > 0) && (mLastTemplateId < CAMERA_TEMPLATE_COUNT)) &&
Emilian Peev811d2952018-05-25 11:08:40 +01001710 (!mRequestTemplateCache[mLastTemplateId].isEmpty())) {
1711 ALOGV("%s: Speculative session param configuration with template id: %d", __func__,
1712 mLastTemplateId);
1713 return filterParamsAndConfigureLocked(mRequestTemplateCache[mLastTemplateId],
1714 operatingMode);
1715 }
1716
Emilian Peevac3ce6c2017-12-12 15:27:02 +00001717 return filterParamsAndConfigureLocked(sessionParams, operatingMode);
1718}
1719
1720status_t Camera3Device::filterParamsAndConfigureLocked(const CameraMetadata& sessionParams,
1721 int operatingMode) {
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001722 //Filter out any incoming session parameters
1723 const CameraMetadata params(sessionParams);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001724 camera_metadata_entry_t availableSessionKeys = mDeviceInfo.find(
1725 ANDROID_REQUEST_AVAILABLE_SESSION_KEYS);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00001726 CameraMetadata filteredParams(availableSessionKeys.count);
1727 camera_metadata_t *meta = const_cast<camera_metadata_t *>(
1728 filteredParams.getAndLock());
1729 set_camera_metadata_vendor_id(meta, mVendorTagId);
1730 filteredParams.unlock(meta);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001731 if (availableSessionKeys.count > 0) {
1732 for (size_t i = 0; i < availableSessionKeys.count; i++) {
1733 camera_metadata_ro_entry entry = params.find(
1734 availableSessionKeys.data.i32[i]);
1735 if (entry.count > 0) {
1736 filteredParams.update(entry);
1737 }
1738 }
1739 }
1740
1741 return configureStreamsLocked(operatingMode, filteredParams);
Igor Murashkine2d167e2014-08-19 16:19:59 -07001742}
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001743
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07001744status_t Camera3Device::getInputBufferProducer(
1745 sp<IGraphicBufferProducer> *producer) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07001746 ATRACE_CALL();
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07001747 Mutex::Autolock il(mInterfaceLock);
1748 Mutex::Autolock l(mLock);
1749
1750 if (producer == NULL) {
1751 return BAD_VALUE;
1752 } else if (mInputStream == NULL) {
1753 return INVALID_OPERATION;
1754 }
1755
1756 return mInputStream->getInputBufferProducer(producer);
1757}
1758
Emilian Peevf4816702020-04-03 15:44:51 -07001759status_t Camera3Device::createDefaultRequest(camera_request_template_t templateId,
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001760 CameraMetadata *request) {
1761 ATRACE_CALL();
Alex Rayfe7e0c62013-05-30 00:12:13 -07001762 ALOGV("%s: for template %d", __FUNCTION__, templateId);
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08001763
Emilian Peevf4816702020-04-03 15:44:51 -07001764 if (templateId <= 0 || templateId >= CAMERA_TEMPLATE_COUNT) {
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08001765 android_errorWriteWithInfoLog(CameraService::SN_EVENT_LOG_ID, "26866110",
Jayant Chowdhary12361932018-08-27 14:46:13 -07001766 CameraThreadState::getCallingUid(), nullptr, 0);
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08001767 return BAD_VALUE;
1768 }
1769
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001770 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001771
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001772 {
1773 Mutex::Autolock l(mLock);
1774 switch (mStatus) {
1775 case STATUS_ERROR:
1776 CLOGE("Device has encountered a serious error");
1777 return INVALID_OPERATION;
1778 case STATUS_UNINITIALIZED:
1779 CLOGE("Device is not initialized!");
1780 return INVALID_OPERATION;
1781 case STATUS_UNCONFIGURED:
1782 case STATUS_CONFIGURED:
1783 case STATUS_ACTIVE:
1784 // OK
1785 break;
1786 default:
1787 SET_ERR_L("Unexpected status: %d", mStatus);
1788 return INVALID_OPERATION;
1789 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001790
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001791 if (!mRequestTemplateCache[templateId].isEmpty()) {
1792 *request = mRequestTemplateCache[templateId];
Emilian Peev811d2952018-05-25 11:08:40 +01001793 mLastTemplateId = templateId;
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001794 return OK;
1795 }
Zhijun Hea1530f12014-09-14 12:44:20 -07001796 }
1797
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001798 camera_metadata_t *rawRequest;
1799 status_t res = mInterface->constructDefaultRequestSettings(
Emilian Peevf4816702020-04-03 15:44:51 -07001800 (camera_request_template_t) templateId, &rawRequest);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001801
1802 {
1803 Mutex::Autolock l(mLock);
1804 if (res == BAD_VALUE) {
1805 ALOGI("%s: template %d is not supported on this camera device",
1806 __FUNCTION__, templateId);
1807 return res;
1808 } else if (res != OK) {
1809 CLOGE("Unable to construct request template %d: %s (%d)",
1810 templateId, strerror(-res), res);
1811 return res;
1812 }
1813
1814 set_camera_metadata_vendor_id(rawRequest, mVendorTagId);
1815 mRequestTemplateCache[templateId].acquire(rawRequest);
1816
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08001817 // Override the template request with zoomRatioMapper
1818 res = mZoomRatioMappers[mId.c_str()].initZoomRatioInTemplate(
1819 &mRequestTemplateCache[templateId]);
1820 if (res != OK) {
1821 CLOGE("Failed to update zoom ratio for template %d: %s (%d)",
1822 templateId, strerror(-res), res);
1823 return res;
1824 }
1825
Shuzhen Wangd25dc972020-03-24 17:11:43 -07001826 // Fill in JPEG_QUALITY if not available
1827 if (!mRequestTemplateCache[templateId].exists(ANDROID_JPEG_QUALITY)) {
1828 static const uint8_t kDefaultJpegQuality = 95;
1829 mRequestTemplateCache[templateId].update(ANDROID_JPEG_QUALITY,
1830 &kDefaultJpegQuality, 1);
1831 }
1832
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001833 *request = mRequestTemplateCache[templateId];
Emilian Peev811d2952018-05-25 11:08:40 +01001834 mLastTemplateId = templateId;
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001835 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001836 return OK;
1837}
1838
1839status_t Camera3Device::waitUntilDrained() {
1840 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001841 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001842 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001843 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001844
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001845 return waitUntilDrainedLocked(maxExpectedDuration);
Zhijun He69a37482014-03-23 18:44:49 -07001846}
1847
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001848status_t Camera3Device::waitUntilDrainedLocked(nsecs_t maxExpectedDuration) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001849 switch (mStatus) {
1850 case STATUS_UNINITIALIZED:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001851 case STATUS_UNCONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001852 ALOGV("%s: Already idle", __FUNCTION__);
1853 return OK;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001854 case STATUS_CONFIGURED:
1855 // To avoid race conditions, check with tracker to be sure
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001856 case STATUS_ERROR:
1857 case STATUS_ACTIVE:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001858 // Need to verify shut down
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001859 break;
1860 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001861 SET_ERR_L("Unexpected status: %d",mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001862 return INVALID_OPERATION;
1863 }
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07001864 ALOGV("%s: Camera %s: Waiting until idle (%" PRIi64 "ns)", __FUNCTION__, mId.string(),
1865 maxExpectedDuration);
1866 status_t res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
Eino-Ville Talvala9c8a0912014-09-14 14:52:19 -07001867 if (res != OK) {
Yin-Chia Yeh87b3ec02019-06-03 10:44:39 -07001868 mStatusTracker->dumpActiveComponents();
Eino-Ville Talvala9c8a0912014-09-14 14:52:19 -07001869 SET_ERR_L("Error waiting for HAL to drain: %s (%d)", strerror(-res),
1870 res);
1871 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001872 return res;
1873}
1874
Ruben Brunk183f0562015-08-12 12:55:02 -07001875void Camera3Device::internalUpdateStatusLocked(Status status) {
1876 mStatus = status;
1877 mRecentStatusUpdates.add(mStatus);
1878 mStatusChanged.broadcast();
1879}
1880
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001881// Pause to reconfigure
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001882status_t Camera3Device::internalPauseAndWaitLocked(nsecs_t maxExpectedDuration) {
Emilian Peeve86358b2019-02-15 13:51:39 -08001883 if (mRequestThread.get() != nullptr) {
1884 mRequestThread->setPaused(true);
1885 } else {
1886 return NO_INIT;
1887 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001888
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07001889 ALOGV("%s: Camera %s: Internal wait until idle (% " PRIi64 " ns)", __FUNCTION__, mId.string(),
1890 maxExpectedDuration);
1891 status_t res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001892 if (res != OK) {
1893 SET_ERR_L("Can't idle device in %f seconds!",
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07001894 maxExpectedDuration/1e9);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001895 }
1896
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001897 return res;
1898}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001899
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001900// Resume after internalPauseAndWaitLocked
1901status_t Camera3Device::internalResumeLocked() {
1902 status_t res;
1903
1904 mRequestThread->setPaused(false);
1905
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08001906 ALOGV("%s: Camera %s: Internal wait until active (% " PRIi64 " ns)", __FUNCTION__, mId.string(),
1907 kActiveTimeout);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001908 res = waitUntilStateThenRelock(/*active*/ true, kActiveTimeout);
1909 if (res != OK) {
1910 SET_ERR_L("Can't transition to active in %f seconds!",
1911 kActiveTimeout/1e9);
1912 }
1913 mPauseStateNotify = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001914 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001915}
1916
Ruben Brunk183f0562015-08-12 12:55:02 -07001917status_t Camera3Device::waitUntilStateThenRelock(bool active, nsecs_t timeout) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001918 status_t res = OK;
Ruben Brunk183f0562015-08-12 12:55:02 -07001919
1920 size_t startIndex = 0;
1921 if (mStatusWaiters == 0) {
1922 // Clear the list of recent statuses if there are no existing threads waiting on updates to
1923 // this status list
1924 mRecentStatusUpdates.clear();
1925 } else {
1926 // If other threads are waiting on updates to this status list, set the position of the
1927 // first element that this list will check rather than clearing the list.
1928 startIndex = mRecentStatusUpdates.size();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001929 }
1930
Ruben Brunk183f0562015-08-12 12:55:02 -07001931 mStatusWaiters++;
1932
Yin-Chia Yehe52b8fa2020-07-28 00:17:58 -07001933 bool signalPipelineDrain = false;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07001934 if (!active && mUseHalBufManager) {
1935 auto streamIds = mOutputStreams.getStreamIds();
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08001936 if (mStatus == STATUS_ACTIVE) {
1937 mRequestThread->signalPipelineDrain(streamIds);
Yin-Chia Yehe52b8fa2020-07-28 00:17:58 -07001938 signalPipelineDrain = true;
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08001939 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07001940 mRequestBufferSM.onWaitUntilIdle();
1941 }
1942
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001943 bool stateSeen = false;
1944 do {
Ruben Brunk183f0562015-08-12 12:55:02 -07001945 if (active == (mStatus == STATUS_ACTIVE)) {
1946 // Desired state is current
1947 break;
1948 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001949
1950 res = mStatusChanged.waitRelative(mLock, timeout);
1951 if (res != OK) break;
1952
Ruben Brunk183f0562015-08-12 12:55:02 -07001953 // This is impossible, but if not, could result in subtle deadlocks and invalid state
1954 // transitions.
1955 LOG_ALWAYS_FATAL_IF(startIndex > mRecentStatusUpdates.size(),
1956 "%s: Skipping status updates in Camera3Device, may result in deadlock.",
1957 __FUNCTION__);
1958
1959 // Encountered desired state since we began waiting
1960 for (size_t i = startIndex; i < mRecentStatusUpdates.size(); i++) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001961 if (active == (mRecentStatusUpdates[i] == STATUS_ACTIVE) ) {
1962 stateSeen = true;
1963 break;
1964 }
1965 }
1966 } while (!stateSeen);
1967
Yin-Chia Yehe52b8fa2020-07-28 00:17:58 -07001968 if (signalPipelineDrain) {
1969 mRequestThread->resetPipelineDrain();
1970 }
1971
Ruben Brunk183f0562015-08-12 12:55:02 -07001972 mStatusWaiters--;
1973
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001974 return res;
1975}
1976
1977
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001978status_t Camera3Device::setNotifyCallback(wp<NotificationListener> listener) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001979 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001980 std::lock_guard<std::mutex> l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001981
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001982 if (listener != NULL && mListener != NULL) {
1983 ALOGW("%s: Replacing old callback listener", __FUNCTION__);
1984 }
1985 mListener = listener;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001986 mRequestThread->setNotificationListener(listener);
1987 mPreparerThread->setNotificationListener(listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001988
1989 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001990}
1991
Eino-Ville Talvala46910bd2013-07-18 19:15:17 -07001992bool Camera3Device::willNotify3A() {
1993 return false;
1994}
1995
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001996status_t Camera3Device::waitForNextFrame(nsecs_t timeout) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07001997 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001998 std::unique_lock<std::mutex> l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001999
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002000 while (mResultQueue.empty()) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002001 auto st = mResultSignal.wait_for(l, std::chrono::nanoseconds(timeout));
2002 if (st == std::cv_status::timeout) {
2003 return TIMED_OUT;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002004 }
2005 }
2006 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002007}
2008
Jianing Weicb0652e2014-03-12 18:29:36 -07002009status_t Camera3Device::getNextResult(CaptureResult *frame) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002010 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002011 std::lock_guard<std::mutex> l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002012
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002013 if (mResultQueue.empty()) {
2014 return NOT_ENOUGH_DATA;
2015 }
2016
Jianing Weicb0652e2014-03-12 18:29:36 -07002017 if (frame == NULL) {
2018 ALOGE("%s: argument cannot be NULL", __FUNCTION__);
2019 return BAD_VALUE;
2020 }
2021
2022 CaptureResult &result = *(mResultQueue.begin());
2023 frame->mResultExtras = result.mResultExtras;
2024 frame->mMetadata.acquire(result.mMetadata);
Shuzhen Wang5c22c152017-12-31 17:12:25 -08002025 frame->mPhysicalMetadatas = std::move(result.mPhysicalMetadatas);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002026 mResultQueue.erase(mResultQueue.begin());
2027
2028 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002029}
2030
2031status_t Camera3Device::triggerAutofocus(uint32_t id) {
2032 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002033 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002034
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002035 ALOGV("%s: Triggering autofocus, id %d", __FUNCTION__, id);
2036 // Mix-in this trigger into the next request and only the next request.
2037 RequestTrigger trigger[] = {
2038 {
2039 ANDROID_CONTROL_AF_TRIGGER,
2040 ANDROID_CONTROL_AF_TRIGGER_START
2041 },
2042 {
2043 ANDROID_CONTROL_AF_TRIGGER_ID,
2044 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07002045 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002046 };
2047
2048 return mRequestThread->queueTrigger(trigger,
2049 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002050}
2051
2052status_t Camera3Device::triggerCancelAutofocus(uint32_t id) {
2053 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002054 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002055
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002056 ALOGV("%s: Triggering cancel autofocus, id %d", __FUNCTION__, id);
2057 // Mix-in this trigger into the next request and only the next request.
2058 RequestTrigger trigger[] = {
2059 {
2060 ANDROID_CONTROL_AF_TRIGGER,
2061 ANDROID_CONTROL_AF_TRIGGER_CANCEL
2062 },
2063 {
2064 ANDROID_CONTROL_AF_TRIGGER_ID,
2065 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07002066 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002067 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002068
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002069 return mRequestThread->queueTrigger(trigger,
2070 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002071}
2072
2073status_t Camera3Device::triggerPrecaptureMetering(uint32_t id) {
2074 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002075 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002076
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002077 ALOGV("%s: Triggering precapture metering, id %d", __FUNCTION__, id);
2078 // Mix-in this trigger into the next request and only the next request.
2079 RequestTrigger trigger[] = {
2080 {
2081 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER,
2082 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_START
2083 },
2084 {
2085 ANDROID_CONTROL_AE_PRECAPTURE_ID,
2086 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07002087 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002088 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002089
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002090 return mRequestThread->queueTrigger(trigger,
2091 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002092}
2093
Jianing Weicb0652e2014-03-12 18:29:36 -07002094status_t Camera3Device::flush(int64_t *frameNumber) {
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07002095 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002096 ALOGV("%s: Camera %s: Flushing all requests", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002097 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07002098
Zhijun He7ef20392014-04-21 16:04:17 -07002099 {
2100 Mutex::Autolock l(mLock);
Emilian Peeved2ebe42018-09-25 16:59:09 +01002101
2102 // b/116514106 "disconnect()" can get called twice for the same device. The
2103 // camera device will not be initialized during the second run.
2104 if (mStatus == STATUS_UNINITIALIZED) {
2105 return OK;
2106 }
2107
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002108 mRequestThread->clear(/*out*/frameNumber);
Shuzhen Wang316781a2020-08-18 18:11:01 -07002109
2110 // Stop session and stream counter
2111 mSessionStatsBuilder.stopCounter();
Zhijun He7ef20392014-04-21 16:04:17 -07002112 }
2113
Emilian Peev08dd2452017-04-06 16:55:14 +01002114 return mRequestThread->flush();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07002115}
2116
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002117status_t Camera3Device::prepare(int streamId) {
Ruben Brunkc78ac262015-08-13 17:58:46 -07002118 return prepare(camera3::Camera3StreamInterface::ALLOCATE_PIPELINE_MAX, streamId);
2119}
2120
2121status_t Camera3Device::prepare(int maxCount, int streamId) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002122 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002123 ALOGV("%s: Camera %s: Preparing stream %d", __FUNCTION__, mId.string(), streamId);
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07002124 Mutex::Autolock il(mInterfaceLock);
2125 Mutex::Autolock l(mLock);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002126
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002127 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
2128 if (stream == nullptr) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002129 CLOGE("Stream %d does not exist", streamId);
2130 return BAD_VALUE;
2131 }
2132
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002133 if (stream->isUnpreparable() || stream->hasOutstandingBuffers() ) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07002134 CLOGE("Stream %d has already been a request target", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002135 return BAD_VALUE;
2136 }
2137
2138 if (mRequestThread->isStreamPending(stream)) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07002139 CLOGE("Stream %d is already a target in a pending request", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002140 return BAD_VALUE;
2141 }
2142
Ruben Brunkc78ac262015-08-13 17:58:46 -07002143 return mPreparerThread->prepare(maxCount, stream);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002144}
2145
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002146status_t Camera3Device::tearDown(int streamId) {
2147 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002148 ALOGV("%s: Camera %s: Tearing down stream %d", __FUNCTION__, mId.string(), streamId);
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002149 Mutex::Autolock il(mInterfaceLock);
2150 Mutex::Autolock l(mLock);
2151
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002152 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
2153 if (stream == nullptr) {
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002154 CLOGE("Stream %d does not exist", streamId);
2155 return BAD_VALUE;
2156 }
2157
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002158 if (stream->hasOutstandingBuffers() || mRequestThread->isStreamPending(stream)) {
2159 CLOGE("Stream %d is a target of a in-progress request", streamId);
2160 return BAD_VALUE;
2161 }
2162
2163 return stream->tearDown();
2164}
2165
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002166status_t Camera3Device::addBufferListenerForStream(int streamId,
2167 wp<Camera3StreamBufferListener> listener) {
2168 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002169 ALOGV("%s: Camera %s: Adding buffer listener for stream %d", __FUNCTION__, mId.string(), streamId);
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002170 Mutex::Autolock il(mInterfaceLock);
2171 Mutex::Autolock l(mLock);
2172
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002173 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
2174 if (stream == nullptr) {
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002175 CLOGE("Stream %d does not exist", streamId);
2176 return BAD_VALUE;
2177 }
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002178 stream->addBufferListener(listener);
2179
2180 return OK;
2181}
2182
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002183/**
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002184 * Methods called by subclasses
2185 */
2186
2187void Camera3Device::notifyStatus(bool idle) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002188 ATRACE_CALL();
Shuzhen Wang316781a2020-08-18 18:11:01 -07002189 std::vector<int> streamIds;
2190 std::vector<hardware::CameraStreamStats> streamStats;
2191
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002192 {
2193 // Need mLock to safely update state and synchronize to current
2194 // state of methods in flight.
2195 Mutex::Autolock l(mLock);
2196 // We can get various system-idle notices from the status tracker
2197 // while starting up. Only care about them if we've actually sent
2198 // in some requests recently.
2199 if (mStatus != STATUS_ACTIVE && mStatus != STATUS_CONFIGURED) {
2200 return;
2201 }
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08002202 ALOGV("%s: Camera %s: Now %s, pauseState: %s", __FUNCTION__, mId.string(),
2203 idle ? "idle" : "active", mPauseStateNotify ? "true" : "false");
Ruben Brunk183f0562015-08-12 12:55:02 -07002204 internalUpdateStatusLocked(idle ? STATUS_CONFIGURED : STATUS_ACTIVE);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002205
2206 // Skip notifying listener if we're doing some user-transparent
2207 // state changes
2208 if (mPauseStateNotify) return;
Shuzhen Wang316781a2020-08-18 18:11:01 -07002209
2210 // Populate stream statistics in case of Idle
2211 if (idle) {
2212 for (size_t i = 0; i < mOutputStreams.size(); i++) {
2213 auto stream = mOutputStreams[i];
2214 if (stream.get() == nullptr) continue;
2215 streamIds.push_back(stream->getId());
2216 Camera3Stream* camera3Stream = Camera3Stream::cast(stream->asHalStream());
2217 int64_t usage = 0LL;
2218 if (camera3Stream != nullptr) {
2219 usage = camera3Stream->getUsage();
2220 }
2221 streamStats.emplace_back(stream->getWidth(), stream->getHeight(),
2222 stream->getFormat(), stream->getDataSpace(), usage,
2223 stream->getMaxHalBuffers(),
2224 stream->getMaxTotalBuffers() - stream->getMaxHalBuffers());
2225 }
2226 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002227 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002228
2229 sp<NotificationListener> listener;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002230 {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002231 std::lock_guard<std::mutex> l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002232 listener = mListener.promote();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002233 }
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07002234 status_t res = OK;
2235 if (listener != nullptr) {
2236 if (idle) {
2237 // Get session stats from the builder, and notify the listener.
2238 int64_t requestCount, resultErrorCount;
2239 bool deviceError;
2240 std::map<int, StreamStats> streamStatsMap;
2241 mSessionStatsBuilder.buildAndReset(&requestCount, &resultErrorCount,
2242 &deviceError, &streamStatsMap);
2243 for (size_t i = 0; i < streamIds.size(); i++) {
2244 int streamId = streamIds[i];
2245 auto stats = streamStatsMap.find(streamId);
2246 if (stats != streamStatsMap.end()) {
2247 streamStats[i].mRequestCount = stats->second.mRequestedFrameCount;
2248 streamStats[i].mErrorCount = stats->second.mDroppedFrameCount;
2249 streamStats[i].mStartLatencyMs = stats->second.mStartLatencyMs;
2250 streamStats[i].mHistogramType =
2251 hardware::CameraStreamStats::HISTOGRAM_TYPE_CAPTURE_LATENCY;
2252 streamStats[i].mHistogramBins.assign(
2253 stats->second.mCaptureLatencyBins.begin(),
2254 stats->second.mCaptureLatencyBins.end());
2255 streamStats[i].mHistogramCounts.assign(
2256 stats->second.mCaptureLatencyHistogram.begin(),
2257 stats->second.mCaptureLatencyHistogram.end());
2258 }
Shuzhen Wang316781a2020-08-18 18:11:01 -07002259 }
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07002260 listener->notifyIdle(requestCount, resultErrorCount, deviceError, streamStats);
2261 } else {
2262 res = listener->notifyActive();
Shuzhen Wang316781a2020-08-18 18:11:01 -07002263 }
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07002264 }
2265 if (res != OK) {
2266 SET_ERR("Camera access permission lost mid-operation: %s (%d)",
2267 strerror(-res), res);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002268 }
2269}
2270
Shuzhen Wang758c2152017-01-10 18:26:18 -08002271status_t Camera3Device::setConsumerSurfaces(int streamId,
Emilian Peev40ead602017-09-26 15:46:36 +01002272 const std::vector<sp<Surface>>& consumers, std::vector<int> *surfaceIds) {
Zhijun He5d677d12016-05-29 16:52:39 -07002273 ATRACE_CALL();
Shuzhen Wang758c2152017-01-10 18:26:18 -08002274 ALOGV("%s: Camera %s: set consumer surface for stream %d",
2275 __FUNCTION__, mId.string(), streamId);
Emilian Peev40ead602017-09-26 15:46:36 +01002276
2277 if (surfaceIds == nullptr) {
2278 return BAD_VALUE;
2279 }
2280
Zhijun He5d677d12016-05-29 16:52:39 -07002281 Mutex::Autolock il(mInterfaceLock);
2282 Mutex::Autolock l(mLock);
2283
Shuzhen Wang758c2152017-01-10 18:26:18 -08002284 if (consumers.size() == 0) {
2285 CLOGE("No consumer is passed!");
Zhijun He5d677d12016-05-29 16:52:39 -07002286 return BAD_VALUE;
2287 }
2288
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002289 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
2290 if (stream == nullptr) {
Zhijun He5d677d12016-05-29 16:52:39 -07002291 CLOGE("Stream %d is unknown", streamId);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002292 return BAD_VALUE;
Zhijun He5d677d12016-05-29 16:52:39 -07002293 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002294
2295 // isConsumerConfigurationDeferred will be off after setConsumers
2296 bool isDeferred = stream->isConsumerConfigurationDeferred();
Shuzhen Wang758c2152017-01-10 18:26:18 -08002297 status_t res = stream->setConsumers(consumers);
Zhijun He5d677d12016-05-29 16:52:39 -07002298 if (res != OK) {
2299 CLOGE("Stream %d set consumer failed (error %d %s) ", streamId, res, strerror(-res));
2300 return res;
2301 }
2302
Emilian Peev40ead602017-09-26 15:46:36 +01002303 for (auto &consumer : consumers) {
2304 int id = stream->getSurfaceId(consumer);
2305 if (id < 0) {
2306 CLOGE("Invalid surface id!");
2307 return BAD_VALUE;
2308 }
2309 surfaceIds->push_back(id);
2310 }
2311
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002312 if (isDeferred) {
Shuzhen Wang0129d522016-10-30 22:43:41 -07002313 if (!stream->isConfiguring()) {
2314 CLOGE("Stream %d was already fully configured.", streamId);
2315 return INVALID_OPERATION;
2316 }
Zhijun He5d677d12016-05-29 16:52:39 -07002317
Shuzhen Wang0129d522016-10-30 22:43:41 -07002318 res = stream->finishConfiguration();
2319 if (res != OK) {
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002320 // If finishConfiguration fails due to abandoned surface, do not set
2321 // device to error state.
2322 bool isSurfaceAbandoned =
2323 (res == NO_INIT || res == DEAD_OBJECT) && stream->isAbandoned();
2324 if (!isSurfaceAbandoned) {
2325 SET_ERR_L("Can't finish configuring output stream %d: %s (%d)",
2326 stream->getId(), strerror(-res), res);
2327 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07002328 return res;
2329 }
Zhijun He5d677d12016-05-29 16:52:39 -07002330 }
2331
2332 return OK;
2333}
2334
Emilian Peev40ead602017-09-26 15:46:36 +01002335status_t Camera3Device::updateStream(int streamId, const std::vector<sp<Surface>> &newSurfaces,
2336 const std::vector<OutputStreamInfo> &outputInfo,
2337 const std::vector<size_t> &removedSurfaceIds, KeyedVector<sp<Surface>, size_t> *outputMap) {
2338 Mutex::Autolock il(mInterfaceLock);
2339 Mutex::Autolock l(mLock);
2340
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002341 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
2342 if (stream == nullptr) {
Emilian Peev40ead602017-09-26 15:46:36 +01002343 CLOGE("Stream %d is unknown", streamId);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002344 return BAD_VALUE;
Emilian Peev40ead602017-09-26 15:46:36 +01002345 }
2346
2347 for (const auto &it : removedSurfaceIds) {
2348 if (mRequestThread->isOutputSurfacePending(streamId, it)) {
2349 CLOGE("Shared surface still part of a pending request!");
2350 return -EBUSY;
2351 }
2352 }
2353
Emilian Peev40ead602017-09-26 15:46:36 +01002354 status_t res = stream->updateStream(newSurfaces, outputInfo, removedSurfaceIds, outputMap);
2355 if (res != OK) {
2356 CLOGE("Stream %d failed to update stream (error %d %s) ",
2357 streamId, res, strerror(-res));
2358 if (res == UNKNOWN_ERROR) {
2359 SET_ERR_L("%s: Stream update failed to revert to previous output configuration!",
2360 __FUNCTION__);
2361 }
2362 return res;
2363 }
2364
2365 return res;
2366}
2367
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002368status_t Camera3Device::dropStreamBuffers(bool dropping, int streamId) {
2369 Mutex::Autolock il(mInterfaceLock);
2370 Mutex::Autolock l(mLock);
2371
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002372 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
2373 if (stream == nullptr) {
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002374 ALOGE("%s: Stream %d is not found.", __FUNCTION__, streamId);
2375 return BAD_VALUE;
2376 }
Shuzhen Wang316781a2020-08-18 18:11:01 -07002377
2378 if (dropping) {
2379 mSessionStatsBuilder.stopCounter(streamId);
2380 } else {
2381 mSessionStatsBuilder.startCounter(streamId);
2382 }
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002383 return stream->dropBuffers(dropping);
2384}
2385
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002386/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002387 * Camera3Device private methods
2388 */
2389
2390sp<Camera3Device::CaptureRequest> Camera3Device::createCaptureRequest(
Emilian Peevaebbe412018-01-15 13:53:24 +00002391 const PhysicalCameraSettingsList &request, const SurfaceMap &surfaceMap) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002392 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002393
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08002394 sp<CaptureRequest> newRequest = new CaptureRequest();
Emilian Peevaebbe412018-01-15 13:53:24 +00002395 newRequest->mSettingsList = request;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002396
2397 camera_metadata_entry_t inputStreams =
Emilian Peevaebbe412018-01-15 13:53:24 +00002398 newRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_INPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002399 if (inputStreams.count > 0) {
2400 if (mInputStream == NULL ||
Zhijun Hed1d64672013-09-06 15:00:01 -07002401 mInputStream->getId() != inputStreams.data.i32[0]) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002402 CLOGE("Request references unknown input stream %d",
2403 inputStreams.data.u8[0]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002404 return NULL;
2405 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002406
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002407 if (mInputStream->isConfiguring()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002408 SET_ERR_L("%s: input stream %d is not configured!",
2409 __FUNCTION__, mInputStream->getId());
2410 return NULL;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002411 }
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07002412 // Check if stream prepare is blocking requests.
2413 if (mInputStream->isBlockedByPrepare()) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002414 CLOGE("Request references an input stream that's being prepared!");
2415 return NULL;
2416 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002417
2418 newRequest->mInputStream = mInputStream;
Emilian Peevaebbe412018-01-15 13:53:24 +00002419 newRequest->mSettingsList.begin()->metadata.erase(ANDROID_REQUEST_INPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002420 }
2421
2422 camera_metadata_entry_t streams =
Emilian Peevaebbe412018-01-15 13:53:24 +00002423 newRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_OUTPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002424 if (streams.count == 0) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002425 CLOGE("Zero output streams specified!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002426 return NULL;
2427 }
2428
2429 for (size_t i = 0; i < streams.count; i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002430 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streams.data.i32[i]);
2431 if (stream == nullptr) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002432 CLOGE("Request references unknown stream %d",
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002433 streams.data.i32[i]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002434 return NULL;
2435 }
Zhijun He5d677d12016-05-29 16:52:39 -07002436 // It is illegal to include a deferred consumer output stream into a request
Shuzhen Wang0129d522016-10-30 22:43:41 -07002437 auto iter = surfaceMap.find(streams.data.i32[i]);
2438 if (iter != surfaceMap.end()) {
2439 const std::vector<size_t>& surfaces = iter->second;
2440 for (const auto& surface : surfaces) {
2441 if (stream->isConsumerConfigurationDeferred(surface)) {
2442 CLOGE("Stream %d surface %zu hasn't finished configuration yet "
2443 "due to deferred consumer", stream->getId(), surface);
2444 return NULL;
2445 }
2446 }
Yin-Chia Yeh0b287572018-10-15 12:38:13 -07002447 newRequest->mOutputSurfaces[streams.data.i32[i]] = surfaces;
Zhijun He5d677d12016-05-29 16:52:39 -07002448 }
2449
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002450 if (stream->isConfiguring()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002451 SET_ERR_L("%s: stream %d is not configured!", __FUNCTION__, stream->getId());
2452 return NULL;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002453 }
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07002454 // Check if stream prepare is blocking requests.
2455 if (stream->isBlockedByPrepare()) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002456 CLOGE("Request references an output stream that's being prepared!");
2457 return NULL;
2458 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002459
2460 newRequest->mOutputStreams.push(stream);
2461 }
Emilian Peevaebbe412018-01-15 13:53:24 +00002462 newRequest->mSettingsList.begin()->metadata.erase(ANDROID_REQUEST_OUTPUT_STREAMS);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07002463 newRequest->mBatchSize = 1;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002464
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08002465 auto rotateAndCropEntry =
2466 newRequest->mSettingsList.begin()->metadata.find(ANDROID_SCALER_ROTATE_AND_CROP);
2467 if (rotateAndCropEntry.count > 0 &&
2468 rotateAndCropEntry.data.u8[0] == ANDROID_SCALER_ROTATE_AND_CROP_AUTO) {
2469 newRequest->mRotateAndCropAuto = true;
2470 } else {
2471 newRequest->mRotateAndCropAuto = false;
2472 }
2473
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07002474 auto zoomRatioEntry =
2475 newRequest->mSettingsList.begin()->metadata.find(ANDROID_CONTROL_ZOOM_RATIO);
2476 if (zoomRatioEntry.count > 0 &&
2477 zoomRatioEntry.data.f[0] == 1.0f) {
2478 newRequest->mZoomRatioIs1x = true;
2479 } else {
2480 newRequest->mZoomRatioIs1x = false;
2481 }
2482
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08002483 if (mSupportCameraMute) {
Shuzhen Wang911c6a32021-10-27 13:36:03 -07002484 for (auto& settings : newRequest->mSettingsList) {
2485 auto testPatternModeEntry =
2486 settings.metadata.find(ANDROID_SENSOR_TEST_PATTERN_MODE);
2487 settings.mOriginalTestPatternMode = testPatternModeEntry.count > 0 ?
2488 testPatternModeEntry.data.i32[0] :
2489 ANDROID_SENSOR_TEST_PATTERN_MODE_OFF;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08002490
Shuzhen Wang911c6a32021-10-27 13:36:03 -07002491 auto testPatternDataEntry =
2492 settings.metadata.find(ANDROID_SENSOR_TEST_PATTERN_DATA);
2493 if (testPatternDataEntry.count >= 4) {
2494 memcpy(settings.mOriginalTestPatternData, testPatternDataEntry.data.i32,
2495 sizeof(PhysicalCameraSettings::mOriginalTestPatternData));
2496 } else {
2497 settings.mOriginalTestPatternData[0] = 0;
2498 settings.mOriginalTestPatternData[1] = 0;
2499 settings.mOriginalTestPatternData[2] = 0;
2500 settings.mOriginalTestPatternData[3] = 0;
2501 }
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08002502 }
2503 }
2504
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002505 return newRequest;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002506}
2507
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002508void Camera3Device::cancelStreamsConfigurationLocked() {
2509 int res = OK;
2510 if (mInputStream != NULL && mInputStream->isConfiguring()) {
2511 res = mInputStream->cancelConfiguration();
2512 if (res != OK) {
2513 CLOGE("Can't cancel configuring input stream %d: %s (%d)",
2514 mInputStream->getId(), strerror(-res), res);
2515 }
2516 }
2517
2518 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002519 sp<Camera3OutputStreamInterface> outputStream = mOutputStreams[i];
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002520 if (outputStream->isConfiguring()) {
2521 res = outputStream->cancelConfiguration();
2522 if (res != OK) {
2523 CLOGE("Can't cancel configuring output stream %d: %s (%d)",
2524 outputStream->getId(), strerror(-res), res);
2525 }
2526 }
2527 }
2528
2529 // Return state to that at start of call, so that future configures
2530 // properly clean things up
2531 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
2532 mNeedConfig = true;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002533
2534 res = mPreparerThread->resume();
2535 if (res != OK) {
2536 ALOGE("%s: Camera %s: Preparer thread failed to resume!", __FUNCTION__, mId.string());
2537 }
2538}
2539
Emilian Peev0d0191e2020-04-21 17:01:18 -07002540bool Camera3Device::checkAbandonedStreamsLocked() {
2541 if ((mInputStream.get() != nullptr) && (mInputStream->isAbandoned())) {
2542 return true;
2543 }
2544
2545 for (size_t i = 0; i < mOutputStreams.size(); i++) {
2546 auto stream = mOutputStreams[i];
2547 if ((stream.get() != nullptr) && (stream->isAbandoned())) {
2548 return true;
2549 }
2550 }
2551
2552 return false;
2553}
2554
Emilian Peev3bead5f2020-05-28 17:29:08 -07002555bool Camera3Device::reconfigureCamera(const CameraMetadata& sessionParams, int clientStatusId) {
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002556 ATRACE_CALL();
2557 bool ret = false;
2558
Shuzhen Wang316781a2020-08-18 18:11:01 -07002559 nsecs_t startTime = systemTime();
2560
Jayant Chowdhary646c31b2020-01-30 13:09:59 -08002561 Mutex::Autolock il(mInterfaceLock);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002562 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
2563
2564 Mutex::Autolock l(mLock);
Emilian Peev0d0191e2020-04-21 17:01:18 -07002565 if (checkAbandonedStreamsLocked()) {
2566 ALOGW("%s: Abandoned stream detected, session parameters can't be applied correctly!",
2567 __FUNCTION__);
2568 return true;
2569 }
2570
Emilian Peev3bead5f2020-05-28 17:29:08 -07002571 status_t rc = NO_ERROR;
2572 bool markClientActive = false;
2573 if (mStatus == STATUS_ACTIVE) {
2574 markClientActive = true;
2575 mPauseStateNotify = true;
2576 mStatusTracker->markComponentIdle(clientStatusId, Fence::NO_FENCE);
2577
2578 rc = internalPauseAndWaitLocked(maxExpectedDuration);
2579 }
2580
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002581 if (rc == NO_ERROR) {
2582 mNeedConfig = true;
2583 rc = configureStreamsLocked(mOperatingMode, sessionParams, /*notifyRequestThread*/ false);
2584 if (rc == NO_ERROR) {
2585 ret = true;
2586 mPauseStateNotify = false;
2587 //Moving to active state while holding 'mLock' is important.
2588 //There could be pending calls to 'create-/deleteStream' which
2589 //will trigger another stream configuration while the already
2590 //present streams end up with outstanding buffers that will
2591 //not get drained.
2592 internalUpdateStatusLocked(STATUS_ACTIVE);
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002593 } else if (rc == DEAD_OBJECT) {
2594 // DEAD_OBJECT can be returned if either the consumer surface is
2595 // abandoned, or the HAL has died.
2596 // - If the HAL has died, configureStreamsLocked call will set
2597 // device to error state,
2598 // - If surface is abandoned, we should not set device to error
2599 // state.
2600 ALOGE("Failed to re-configure camera due to abandoned surface");
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002601 } else {
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002602 SET_ERR_L("Failed to re-configure camera: %d", rc);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002603 }
2604 } else {
2605 ALOGE("%s: Failed to pause streaming: %d", __FUNCTION__, rc);
2606 }
2607
Shuzhen Wang316781a2020-08-18 18:11:01 -07002608 CameraServiceProxyWrapper::logStreamConfigured(mId, mOperatingMode, true /*internalReconfig*/,
2609 ns2ms(systemTime() - startTime));
2610
Emilian Peev3bead5f2020-05-28 17:29:08 -07002611 if (markClientActive) {
2612 mStatusTracker->markComponentActive(clientStatusId);
2613 }
2614
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002615 return ret;
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002616}
2617
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002618status_t Camera3Device::configureStreamsLocked(int operatingMode,
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002619 const CameraMetadata& sessionParams, bool notifyRequestThread) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002620 ATRACE_CALL();
2621 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002622
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002623 if (mStatus != STATUS_UNCONFIGURED && mStatus != STATUS_CONFIGURED) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002624 CLOGE("Not idle");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002625 return INVALID_OPERATION;
2626 }
2627
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08002628 if (operatingMode < 0) {
2629 CLOGE("Invalid operating mode: %d", operatingMode);
2630 return BAD_VALUE;
2631 }
2632
2633 bool isConstrainedHighSpeed =
2634 static_cast<int>(StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE) ==
2635 operatingMode;
2636
2637 if (mOperatingMode != operatingMode) {
2638 mNeedConfig = true;
2639 mIsConstrainedHighSpeedConfiguration = isConstrainedHighSpeed;
2640 mOperatingMode = operatingMode;
2641 }
2642
Shuzhen Wang0cf01cb2019-09-05 13:33:06 -07002643 // In case called from configureStreams, abort queued input buffers not belonging to
2644 // any pending requests.
2645 if (mInputStream != NULL && notifyRequestThread) {
2646 while (true) {
Emilian Peevf4816702020-04-03 15:44:51 -07002647 camera_stream_buffer_t inputBuffer;
Shuzhen Wang83bff122020-11-20 15:51:39 -08002648 camera3::Size inputBufferSize;
Shuzhen Wang0cf01cb2019-09-05 13:33:06 -07002649 status_t res = mInputStream->getInputBuffer(&inputBuffer,
Shuzhen Wang83bff122020-11-20 15:51:39 -08002650 &inputBufferSize, /*respectHalLimit*/ false);
Shuzhen Wang0cf01cb2019-09-05 13:33:06 -07002651 if (res != OK) {
2652 // Exhausted acquiring all input buffers.
2653 break;
2654 }
2655
Emilian Peevf4816702020-04-03 15:44:51 -07002656 inputBuffer.status = CAMERA_BUFFER_STATUS_ERROR;
Shuzhen Wang0cf01cb2019-09-05 13:33:06 -07002657 res = mInputStream->returnInputBuffer(inputBuffer);
2658 if (res != OK) {
2659 ALOGE("%s: %d: couldn't return input buffer while clearing input queue: "
2660 "%s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
2661 }
2662 }
2663 }
2664
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002665 if (!mNeedConfig) {
2666 ALOGV("%s: Skipping config, no stream changes", __FUNCTION__);
2667 return OK;
2668 }
2669
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002670 // Workaround for device HALv3.2 or older spec bug - zero streams requires
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002671 // adding a fake stream instead.
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002672 // TODO: Bug: 17321404 for fixing the HAL spec and removing this workaround.
2673 if (mOutputStreams.size() == 0) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002674 addFakeStreamLocked();
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002675 } else {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002676 tryRemoveFakeStreamLocked();
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002677 }
2678
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002679 // Start configuring the streams
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002680 ALOGV("%s: Camera %s: Starting stream configuration", __FUNCTION__, mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002681
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002682 mPreparerThread->pause();
2683
Emilian Peevf4816702020-04-03 15:44:51 -07002684 camera_stream_configuration config;
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -08002685 config.operation_mode = mOperatingMode;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002686 config.num_streams = (mInputStream != NULL) + mOutputStreams.size();
Shuzhen Wang83bff122020-11-20 15:51:39 -08002687 config.input_is_multi_resolution = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002688
Emilian Peevf4816702020-04-03 15:44:51 -07002689 Vector<camera3::camera_stream_t*> streams;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002690 streams.setCapacity(config.num_streams);
Emilian Peev192ee832018-01-31 14:46:47 +00002691 std::vector<uint32_t> bufferSizes(config.num_streams, 0);
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002692
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002693
2694 if (mInputStream != NULL) {
Emilian Peevf4816702020-04-03 15:44:51 -07002695 camera3::camera_stream_t *inputStream;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002696 inputStream = mInputStream->startConfiguration();
2697 if (inputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002698 CLOGE("Can't start input stream configuration");
2699 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002700 return INVALID_OPERATION;
2701 }
2702 streams.add(inputStream);
Shuzhen Wang83bff122020-11-20 15:51:39 -08002703
2704 config.input_is_multi_resolution = mIsInputStreamMultiResolution;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002705 }
2706
Shuzhen Wang99080502021-03-07 21:08:20 -08002707 mGroupIdPhysicalCameraMap.clear();
Emilian Peeve23f1d92021-09-20 14:56:01 -07002708 bool composerSurfacePresent = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002709 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Igor Murashkin2fba5842013-04-22 14:03:54 -07002710
2711 // Don't configure bidi streams twice, nor add them twice to the list
2712 if (mOutputStreams[i].get() ==
2713 static_cast<Camera3StreamInterface*>(mInputStream.get())) {
2714
2715 config.num_streams--;
2716 continue;
2717 }
2718
Emilian Peevf4816702020-04-03 15:44:51 -07002719 camera3::camera_stream_t *outputStream;
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002720 outputStream = mOutputStreams[i]->startConfiguration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002721 if (outputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002722 CLOGE("Can't start output stream configuration");
2723 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002724 return INVALID_OPERATION;
2725 }
2726 streams.add(outputStream);
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002727
Shuzhen Wangb7ab1e42019-02-20 15:42:23 -08002728 if (outputStream->format == HAL_PIXEL_FORMAT_BLOB) {
Emilian Peev192ee832018-01-31 14:46:47 +00002729 size_t k = i + ((mInputStream != nullptr) ? 1 : 0); // Input stream if present should
2730 // always occupy the initial entry.
Shuzhen Wangb7ab1e42019-02-20 15:42:23 -08002731 if (outputStream->data_space == HAL_DATASPACE_V0_JFIF) {
2732 bufferSizes[k] = static_cast<uint32_t>(
2733 getJpegBufferSize(outputStream->width, outputStream->height));
2734 } else if (outputStream->data_space ==
2735 static_cast<android_dataspace>(HAL_DATASPACE_JPEG_APP_SEGMENTS)) {
2736 bufferSizes[k] = outputStream->width * outputStream->height;
2737 } else {
2738 ALOGW("%s: Blob dataSpace %d not supported",
2739 __FUNCTION__, outputStream->data_space);
2740 }
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002741 }
Shuzhen Wang99080502021-03-07 21:08:20 -08002742
2743 if (mOutputStreams[i]->isMultiResolution()) {
2744 int32_t streamGroupId = mOutputStreams[i]->getHalStreamGroupId();
2745 const String8& physicalCameraId = mOutputStreams[i]->getPhysicalCameraId();
2746 mGroupIdPhysicalCameraMap[streamGroupId].insert(physicalCameraId);
2747 }
Emilian Peeve23f1d92021-09-20 14:56:01 -07002748
2749 if (outputStream->usage & GraphicBuffer::USAGE_HW_COMPOSER) {
2750 composerSurfacePresent = true;
2751 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002752 }
2753
2754 config.streams = streams.editArray();
2755
2756 // Do the HAL configuration; will potentially touch stream
Shuzhen Wang92653952019-05-07 15:11:43 -07002757 // max_buffers, usage, and priv fields, as well as data_space and format
2758 // fields for IMPLEMENTATION_DEFINED formats.
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002759
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002760 const camera_metadata_t *sessionBuffer = sessionParams.getAndLock();
Emilian Peev192ee832018-01-31 14:46:47 +00002761 res = mInterface->configureStreams(sessionBuffer, &config, bufferSizes);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002762 sessionParams.unlock(sessionBuffer);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002763
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002764 if (res == BAD_VALUE) {
2765 // HAL rejected this set of streams as unsupported, clean up config
2766 // attempt and return to unconfigured state
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002767 CLOGE("Set of requested inputs/outputs not supported by HAL");
2768 cancelStreamsConfigurationLocked();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002769 return BAD_VALUE;
2770 } else if (res != OK) {
2771 // Some other kind of error from configure_streams - this is not
2772 // expected
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002773 SET_ERR_L("Unable to configure streams with HAL: %s (%d)",
2774 strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002775 return res;
2776 }
2777
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002778 // Finish all stream configuration immediately.
2779 // TODO: Try to relax this later back to lazy completion, which should be
2780 // faster
2781
Igor Murashkin073f8572013-05-02 14:59:28 -07002782 if (mInputStream != NULL && mInputStream->isConfiguring()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002783 bool streamReConfigured = false;
2784 res = mInputStream->finishConfiguration(&streamReConfigured);
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002785 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002786 CLOGE("Can't finish configuring input stream %d: %s (%d)",
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002787 mInputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002788 cancelStreamsConfigurationLocked();
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002789 if ((res == NO_INIT || res == DEAD_OBJECT) && mInputStream->isAbandoned()) {
2790 return DEAD_OBJECT;
2791 }
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002792 return BAD_VALUE;
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002793 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002794 if (streamReConfigured) {
2795 mInterface->onStreamReConfigured(mInputStream->getId());
2796 }
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002797 }
2798
2799 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002800 sp<Camera3OutputStreamInterface> outputStream = mOutputStreams[i];
Zhijun He5d677d12016-05-29 16:52:39 -07002801 if (outputStream->isConfiguring() && !outputStream->isConsumerConfigurationDeferred()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002802 bool streamReConfigured = false;
2803 res = outputStream->finishConfiguration(&streamReConfigured);
Igor Murashkin073f8572013-05-02 14:59:28 -07002804 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002805 CLOGE("Can't finish configuring output stream %d: %s (%d)",
Igor Murashkin073f8572013-05-02 14:59:28 -07002806 outputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002807 cancelStreamsConfigurationLocked();
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002808 if ((res == NO_INIT || res == DEAD_OBJECT) && outputStream->isAbandoned()) {
2809 return DEAD_OBJECT;
2810 }
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002811 return BAD_VALUE;
Igor Murashkin073f8572013-05-02 14:59:28 -07002812 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002813 if (streamReConfigured) {
2814 mInterface->onStreamReConfigured(outputStream->getId());
2815 }
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002816 }
2817 }
2818
Emilian Peeve23f1d92021-09-20 14:56:01 -07002819 mRequestThread->setComposerSurface(composerSurfacePresent);
2820
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002821 // Request thread needs to know to avoid using repeat-last-settings protocol
2822 // across configure_streams() calls
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002823 if (notifyRequestThread) {
Shuzhen Wang99080502021-03-07 21:08:20 -08002824 mRequestThread->configurationComplete(mIsConstrainedHighSpeedConfiguration,
2825 sessionParams, mGroupIdPhysicalCameraMap);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002826 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002827
Zhijun He90f7c372016-08-16 16:19:43 -07002828 char value[PROPERTY_VALUE_MAX];
2829 property_get("camera.fifo.disable", value, "0");
2830 int32_t disableFifo = atoi(value);
2831 if (disableFifo != 1) {
2832 // Boost priority of request thread to SCHED_FIFO.
2833 pid_t requestThreadTid = mRequestThread->getTid();
2834 res = requestPriority(getpid(), requestThreadTid,
Mikhail Naganov83f04272017-02-07 10:45:09 -08002835 kRequestThreadPriority, /*isForApp*/ false, /*asynchronous*/ false);
Zhijun He90f7c372016-08-16 16:19:43 -07002836 if (res != OK) {
2837 ALOGW("Can't set realtime priority for request processing thread: %s (%d)",
2838 strerror(-res), res);
2839 } else {
2840 ALOGD("Set real time priority for request queue thread (tid %d)", requestThreadTid);
2841 }
Eino-Ville Talvalaf99498e2015-09-25 16:52:55 -07002842 }
2843
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002844 // Update device state
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002845 const camera_metadata_t *newSessionParams = sessionParams.getAndLock();
2846 const camera_metadata_t *currentSessionParams = mSessionParams.getAndLock();
2847 bool updateSessionParams = (newSessionParams != currentSessionParams) ? true : false;
2848 sessionParams.unlock(newSessionParams);
2849 mSessionParams.unlock(currentSessionParams);
2850 if (updateSessionParams) {
2851 mSessionParams = sessionParams;
2852 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002853
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002854 mNeedConfig = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002855
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002856 internalUpdateStatusLocked((mFakeStreamId == NO_STREAM) ?
Ruben Brunk183f0562015-08-12 12:55:02 -07002857 STATUS_CONFIGURED : STATUS_UNCONFIGURED);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002858
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002859 ALOGV("%s: Camera %s: Stream configuration complete", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002860
Zhijun He0a210512014-07-24 13:45:15 -07002861 // tear down the deleted streams after configure streams.
2862 mDeletedStreams.clear();
2863
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002864 auto rc = mPreparerThread->resume();
2865 if (rc != OK) {
2866 SET_ERR_L("%s: Camera %s: Preparer thread failed to resume!", __FUNCTION__, mId.string());
2867 return rc;
2868 }
2869
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002870 if (mFakeStreamId == NO_STREAM) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07002871 mRequestBufferSM.onStreamsConfigured();
2872 }
2873
Cliff Wu3b268182021-07-06 15:44:43 +08002874 // First call injectCamera() and then run configureStreamsLocked() case:
Cliff Wuc2ad9c82021-04-21 00:58:58 +08002875 // Since the streams configuration of the injection camera is based on the internal camera, we
Cliff Wu3b268182021-07-06 15:44:43 +08002876 // must wait until the internal camera configure streams before running the injection job to
Cliff Wuc2ad9c82021-04-21 00:58:58 +08002877 // configure the injection streams.
2878 if (mInjectionMethods->isInjecting()) {
Cliff Wu3b268182021-07-06 15:44:43 +08002879 ALOGD("%s: Injection camera %s: Start to configure streams.",
Cliff Wuc2ad9c82021-04-21 00:58:58 +08002880 __FUNCTION__, mInjectionMethods->getInjectedCamId().string());
2881 res = mInjectionMethods->injectCamera(config, bufferSizes);
2882 if (res != OK) {
2883 ALOGE("Can't finish inject camera process!");
2884 return res;
2885 }
Cliff Wu3b268182021-07-06 15:44:43 +08002886 } else {
2887 // First run configureStreamsLocked() and then call injectCamera() case:
2888 // If the stream configuration has been completed and camera deive is active, but the
2889 // injection camera has not been injected yet, we need to store the stream configuration of
2890 // the internal camera (because the stream configuration of the injection camera is based
2891 // on the internal camera). When injecting occurs later, this configuration can be used by
2892 // the injection camera.
2893 ALOGV("%s: The stream configuration is complete and the camera device is active, but the"
2894 " injection camera has not been injected yet.", __FUNCTION__);
2895 mInjectionMethods->storeInjectionConfig(config, bufferSizes);
Cliff Wuc2ad9c82021-04-21 00:58:58 +08002896 }
2897
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002898 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002899}
2900
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002901status_t Camera3Device::addFakeStreamLocked() {
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002902 ATRACE_CALL();
2903 status_t res;
2904
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002905 if (mFakeStreamId != NO_STREAM) {
2906 // Should never be adding a second fake stream when one is already
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002907 // active
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002908 SET_ERR_L("%s: Camera %s: A fake stream already exists!",
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002909 __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002910 return INVALID_OPERATION;
2911 }
2912
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002913 ALOGV("%s: Camera %s: Adding a fake stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002914
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002915 sp<Camera3OutputStreamInterface> fakeStream =
2916 new Camera3FakeStream(mNextStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002917
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002918 res = mOutputStreams.add(mNextStreamId, fakeStream);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002919 if (res < 0) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002920 SET_ERR_L("Can't add fake stream to set: %s (%d)", strerror(-res), res);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002921 return res;
2922 }
2923
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002924 mFakeStreamId = mNextStreamId;
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002925 mNextStreamId++;
2926
2927 return OK;
2928}
2929
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002930status_t Camera3Device::tryRemoveFakeStreamLocked() {
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002931 ATRACE_CALL();
2932 status_t res;
2933
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002934 if (mFakeStreamId == NO_STREAM) return OK;
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002935 if (mOutputStreams.size() == 1) return OK;
2936
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002937 ALOGV("%s: Camera %s: Removing the fake stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002938
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002939 // Ok, have a fake stream and there's at least one other output stream,
2940 // so remove the fake
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002941
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002942 sp<Camera3StreamInterface> deletedStream = mOutputStreams.get(mFakeStreamId);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002943 if (deletedStream == nullptr) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002944 SET_ERR_L("Fake stream %d does not appear to exist", mFakeStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002945 return INVALID_OPERATION;
2946 }
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002947 mOutputStreams.remove(mFakeStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002948
2949 // Free up the stream endpoint so that it can be used by some other stream
2950 res = deletedStream->disconnect();
2951 if (res != OK) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002952 SET_ERR_L("Can't disconnect deleted fake stream %d", mFakeStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002953 // fall through since we want to still list the stream as deleted.
2954 }
2955 mDeletedStreams.add(deletedStream);
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002956 mFakeStreamId = NO_STREAM;
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002957
2958 return res;
2959}
2960
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002961void Camera3Device::setErrorState(const char *fmt, ...) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002962 ATRACE_CALL();
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002963 Mutex::Autolock l(mLock);
2964 va_list args;
2965 va_start(args, fmt);
2966
2967 setErrorStateLockedV(fmt, args);
2968
2969 va_end(args);
2970}
2971
2972void Camera3Device::setErrorStateV(const char *fmt, va_list args) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002973 ATRACE_CALL();
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002974 Mutex::Autolock l(mLock);
2975 setErrorStateLockedV(fmt, args);
2976}
2977
2978void Camera3Device::setErrorStateLocked(const char *fmt, ...) {
2979 va_list args;
2980 va_start(args, fmt);
2981
2982 setErrorStateLockedV(fmt, args);
2983
2984 va_end(args);
2985}
2986
2987void Camera3Device::setErrorStateLockedV(const char *fmt, va_list args) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002988 // Print out all error messages to log
2989 String8 errorCause = String8::formatV(fmt, args);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002990 ALOGE("Camera %s: %s", mId.string(), errorCause.string());
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002991
2992 // But only do error state transition steps for the first error
Zhijun Heb05eeae2013-06-06 13:51:22 -07002993 if (mStatus == STATUS_ERROR || mStatus == STATUS_UNINITIALIZED) return;
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002994
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002995 mErrorCause = errorCause;
2996
Yin-Chia Yeh3d145ae2017-07-27 12:47:03 -07002997 if (mRequestThread != nullptr) {
2998 mRequestThread->setPaused(true);
2999 }
Ruben Brunk183f0562015-08-12 12:55:02 -07003000 internalUpdateStatusLocked(STATUS_ERROR);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003001
3002 // Notify upstream about a device error
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003003 sp<NotificationListener> listener = mListener.promote();
3004 if (listener != NULL) {
3005 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003006 CaptureResultExtras());
Shuzhen Wang316781a2020-08-18 18:11:01 -07003007 mSessionStatsBuilder.onDeviceError();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003008 }
3009
3010 // Save stack trace. View by dumping it later.
3011 CameraTraces::saveTrace();
3012 // TODO: consider adding errorCause and client pid/procname
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07003013}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003014
3015/**
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003016 * In-flight request management
3017 */
3018
Jianing Weicb0652e2014-03-12 18:29:36 -07003019status_t Camera3Device::registerInFlight(uint32_t frameNumber,
Chien-Yu Chend196d612015-06-22 19:49:01 -07003020 int32_t numBuffers, CaptureResultExtras resultExtras, bool hasInput,
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003021 bool hasAppCallback, nsecs_t maxExpectedDuration,
Shuzhen Wang99080502021-03-07 21:08:20 -08003022 const std::set<std::set<String8>>& physicalCameraIds,
3023 bool isStillCapture, bool isZslCapture, bool rotateAndCropAuto,
3024 const std::set<std::string>& cameraIdsWithZoom,
Shuzhen Wang316781a2020-08-18 18:11:01 -07003025 const SurfaceMap& outputSurfaces, nsecs_t requestTimeNs) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003026 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003027 std::lock_guard<std::mutex> l(mInFlightLock);
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003028
3029 ssize_t res;
Chien-Yu Chend196d612015-06-22 19:49:01 -07003030 res = mInFlightMap.add(frameNumber, InFlightRequest(numBuffers, resultExtras, hasInput,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003031 hasAppCallback, maxExpectedDuration, physicalCameraIds, isStillCapture, isZslCapture,
Shuzhen Wang316781a2020-08-18 18:11:01 -07003032 rotateAndCropAuto, cameraIdsWithZoom, requestTimeNs, outputSurfaces));
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003033 if (res < 0) return res;
3034
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07003035 if (mInFlightMap.size() == 1) {
Emilian Peev26d975d2018-07-05 14:52:57 +01003036 // Hold a separate dedicated tracker lock to prevent race with disconnect and also
3037 // avoid a deadlock during reprocess requests.
3038 Mutex::Autolock l(mTrackerLock);
Yin-Chia Yeh38dfde52017-06-27 17:13:33 -07003039 if (mStatusTracker != nullptr) {
3040 mStatusTracker->markComponentActive(mInFlightStatusId);
3041 }
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07003042 }
3043
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003044 mExpectedInflightDuration += maxExpectedDuration;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003045 return OK;
3046}
3047
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003048void Camera3Device::onInflightEntryRemovedLocked(nsecs_t duration) {
Shuzhen Wangcadb3302016-11-04 14:17:56 -07003049 // Indicate idle inFlightMap to the status tracker
3050 if (mInFlightMap.size() == 0) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07003051 mRequestBufferSM.onInflightMapEmpty();
Emilian Peev26d975d2018-07-05 14:52:57 +01003052 // Hold a separate dedicated tracker lock to prevent race with disconnect and also
3053 // avoid a deadlock during reprocess requests.
3054 Mutex::Autolock l(mTrackerLock);
Yin-Chia Yeh38dfde52017-06-27 17:13:33 -07003055 if (mStatusTracker != nullptr) {
3056 mStatusTracker->markComponentIdle(mInFlightStatusId, Fence::NO_FENCE);
3057 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07003058 }
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003059 mExpectedInflightDuration -= duration;
Shuzhen Wangcadb3302016-11-04 14:17:56 -07003060}
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003061
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003062void Camera3Device::checkInflightMapLengthLocked() {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04003063 // Validation check - if we have too many in-flight frames with long total inflight duration,
Yin-Chia Yeh99fd0972019-06-27 14:22:44 -07003064 // something has likely gone wrong. This might still be legit only if application send in
3065 // a long burst of long exposure requests.
3066 if (mExpectedInflightDuration > kMinWarnInflightDuration) {
3067 if (!mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() > kInFlightWarnLimit) {
3068 CLOGW("In-flight list too large: %zu, total inflight duration %" PRIu64,
3069 mInFlightMap.size(), mExpectedInflightDuration);
3070 } else if (mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() >
3071 kInFlightWarnLimitHighSpeed) {
3072 CLOGW("In-flight list too large for high speed configuration: %zu,"
3073 "total inflight duration %" PRIu64,
3074 mInFlightMap.size(), mExpectedInflightDuration);
3075 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003076 }
3077}
3078
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003079void Camera3Device::onInflightMapFlushedLocked() {
3080 mExpectedInflightDuration = 0;
3081}
3082
3083void Camera3Device::removeInFlightMapEntryLocked(int idx) {
Jayant Chowdharyd4776262020-06-23 23:45:57 -07003084 ATRACE_HFR_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003085 nsecs_t duration = mInFlightMap.valueAt(idx).maxExpectedDuration;
3086 mInFlightMap.removeItemsAt(idx, 1);
3087
3088 onInflightEntryRemovedLocked(duration);
3089}
3090
3091
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003092void Camera3Device::flushInflightRequests() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003093 ATRACE_CALL();
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003094 sp<NotificationListener> listener;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003095 {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003096 std::lock_guard<std::mutex> l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003097 listener = mListener.promote();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003098 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003099
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003100 FlushInflightReqStates states {
3101 mId, mInFlightLock, mInFlightMap, mUseHalBufManager,
Shuzhen Wang316781a2020-08-18 18:11:01 -07003102 listener, *this, *mInterface, *this, mSessionStatsBuilder};
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003103
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003104 camera3::flushInflightRequests(states);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003105}
3106
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003107CameraMetadata Camera3Device::getLatestRequestLocked() {
Igor Murashkin1e479c02013-09-06 16:55:14 -07003108 ALOGV("%s", __FUNCTION__);
3109
Igor Murashkin1e479c02013-09-06 16:55:14 -07003110 CameraMetadata retVal;
3111
3112 if (mRequestThread != NULL) {
3113 retVal = mRequestThread->getLatestRequest();
3114 }
3115
Igor Murashkin1e479c02013-09-06 16:55:14 -07003116 return retVal;
3117}
3118
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07003119void Camera3Device::monitorMetadata(TagMonitor::eventSource source,
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003120 int64_t frameNumber, nsecs_t timestamp, const CameraMetadata& metadata,
Jayant Chowdharycd277cd2021-08-11 15:48:40 -07003121 const std::unordered_map<std::string, CameraMetadata>& physicalMetadata,
Jayant Chowdharyc30b4c32021-08-18 11:43:16 -07003122 const camera_stream_buffer_t *outputBuffers, uint32_t numOutputBuffers,
3123 int32_t inputStreamId) {
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003124
3125 mTagMonitor.monitorMetadata(source, frameNumber, timestamp, metadata,
Jayant Chowdharyc30b4c32021-08-18 11:43:16 -07003126 physicalMetadata, outputBuffers, numOutputBuffers, inputStreamId);
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07003127}
3128
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003129/**
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003130 * HalInterface inner class methods
3131 */
3132
Yifan Hongf79b5542017-04-11 14:44:25 -07003133Camera3Device::HalInterface::HalInterface(
3134 sp<ICameraDeviceSession> &session,
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003135 std::shared_ptr<RequestMetadataQueue> queue,
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003136 bool useHalBufManager, bool supportOfflineProcessing) :
Yifan Hongf79b5542017-04-11 14:44:25 -07003137 mHidlSession(session),
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003138 mRequestMetadataQueue(queue),
Emilian Peev4ec17882019-01-24 17:16:58 -08003139 mUseHalBufManager(useHalBufManager),
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003140 mIsReconfigurationQuerySupported(true),
3141 mSupportOfflineProcessing(supportOfflineProcessing) {
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003142 // Check with hardware service manager if we can downcast these interfaces
3143 // Somewhat expensive, so cache the results at startup
Shuzhen Wang83bff122020-11-20 15:51:39 -08003144 auto castResult_3_7 = device::V3_7::ICameraDeviceSession::castFrom(mHidlSession);
3145 if (castResult_3_7.isOk()) {
3146 mHidlSession_3_7 = castResult_3_7;
3147 }
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003148 auto castResult_3_6 = device::V3_6::ICameraDeviceSession::castFrom(mHidlSession);
3149 if (castResult_3_6.isOk()) {
3150 mHidlSession_3_6 = castResult_3_6;
3151 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003152 auto castResult_3_5 = device::V3_5::ICameraDeviceSession::castFrom(mHidlSession);
3153 if (castResult_3_5.isOk()) {
3154 mHidlSession_3_5 = castResult_3_5;
3155 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003156 auto castResult_3_4 = device::V3_4::ICameraDeviceSession::castFrom(mHidlSession);
3157 if (castResult_3_4.isOk()) {
3158 mHidlSession_3_4 = castResult_3_4;
3159 }
3160 auto castResult_3_3 = device::V3_3::ICameraDeviceSession::castFrom(mHidlSession);
3161 if (castResult_3_3.isOk()) {
3162 mHidlSession_3_3 = castResult_3_3;
3163 }
3164}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003165
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003166Camera3Device::HalInterface::HalInterface() :
3167 mUseHalBufManager(false),
3168 mSupportOfflineProcessing(false) {}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003169
3170Camera3Device::HalInterface::HalInterface(const HalInterface& other) :
Yifan Hongf79b5542017-04-11 14:44:25 -07003171 mHidlSession(other.mHidlSession),
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003172 mRequestMetadataQueue(other.mRequestMetadataQueue),
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003173 mUseHalBufManager(other.mUseHalBufManager),
3174 mSupportOfflineProcessing(other.mSupportOfflineProcessing) {}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003175
3176bool Camera3Device::HalInterface::valid() {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003177 return (mHidlSession != nullptr);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003178}
3179
3180void Camera3Device::HalInterface::clear() {
Shuzhen Wang83bff122020-11-20 15:51:39 -08003181 mHidlSession_3_7.clear();
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003182 mHidlSession_3_6.clear();
Emilian Peev644a3e12018-11-23 13:52:39 +00003183 mHidlSession_3_5.clear();
Emilian Peev9e740b02018-01-30 18:28:03 +00003184 mHidlSession_3_4.clear();
3185 mHidlSession_3_3.clear();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003186 mHidlSession.clear();
3187}
3188
3189status_t Camera3Device::HalInterface::constructDefaultRequestSettings(
Emilian Peevf4816702020-04-03 15:44:51 -07003190 camera_request_template_t templateId,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003191 /*out*/ camera_metadata_t **requestTemplate) {
3192 ATRACE_NAME("CameraHal::constructDefaultRequestSettings");
3193 if (!valid()) return INVALID_OPERATION;
3194 status_t res = OK;
3195
Emilian Peev31abd0a2017-05-11 18:37:46 +01003196 common::V1_0::Status status;
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003197
3198 auto requestCallback = [&status, &requestTemplate]
Emilian Peev31abd0a2017-05-11 18:37:46 +01003199 (common::V1_0::Status s, const device::V3_2::CameraMetadata& request) {
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003200 status = s;
3201 if (status == common::V1_0::Status::OK) {
3202 const camera_metadata *r =
3203 reinterpret_cast<const camera_metadata_t*>(request.data());
3204 size_t expectedSize = request.size();
3205 int ret = validate_camera_metadata_structure(r, &expectedSize);
3206 if (ret == OK || ret == CAMERA_METADATA_VALIDATION_SHIFTED) {
3207 *requestTemplate = clone_camera_metadata(r);
3208 if (*requestTemplate == nullptr) {
3209 ALOGE("%s: Unable to clone camera metadata received from HAL",
3210 __FUNCTION__);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003211 status = common::V1_0::Status::INTERNAL_ERROR;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003212 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003213 } else {
3214 ALOGE("%s: Malformed camera metadata received from HAL", __FUNCTION__);
3215 status = common::V1_0::Status::INTERNAL_ERROR;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003216 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003217 }
3218 };
3219 hardware::Return<void> err;
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003220 RequestTemplate id;
3221 switch (templateId) {
Emilian Peevf4816702020-04-03 15:44:51 -07003222 case CAMERA_TEMPLATE_PREVIEW:
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003223 id = RequestTemplate::PREVIEW;
3224 break;
Emilian Peevf4816702020-04-03 15:44:51 -07003225 case CAMERA_TEMPLATE_STILL_CAPTURE:
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003226 id = RequestTemplate::STILL_CAPTURE;
3227 break;
Emilian Peevf4816702020-04-03 15:44:51 -07003228 case CAMERA_TEMPLATE_VIDEO_RECORD:
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003229 id = RequestTemplate::VIDEO_RECORD;
3230 break;
Emilian Peevf4816702020-04-03 15:44:51 -07003231 case CAMERA_TEMPLATE_VIDEO_SNAPSHOT:
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003232 id = RequestTemplate::VIDEO_SNAPSHOT;
3233 break;
Emilian Peevf4816702020-04-03 15:44:51 -07003234 case CAMERA_TEMPLATE_ZERO_SHUTTER_LAG:
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003235 id = RequestTemplate::ZERO_SHUTTER_LAG;
3236 break;
Emilian Peevf4816702020-04-03 15:44:51 -07003237 case CAMERA_TEMPLATE_MANUAL:
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003238 id = RequestTemplate::MANUAL;
3239 break;
3240 default:
3241 // Unknown template ID, or this HAL is too old to support it
3242 return BAD_VALUE;
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003243 }
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003244 err = mHidlSession->constructDefaultRequestSettings(id, requestCallback);
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003245
Emilian Peev31abd0a2017-05-11 18:37:46 +01003246 if (!err.isOk()) {
3247 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3248 res = DEAD_OBJECT;
3249 } else {
3250 res = CameraProviderManager::mapToStatusT(status);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003251 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003252
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003253 return res;
3254}
3255
Emilian Peev4ec17882019-01-24 17:16:58 -08003256bool Camera3Device::HalInterface::isReconfigurationRequired(CameraMetadata& oldSessionParams,
3257 CameraMetadata& newSessionParams) {
3258 // We do reconfiguration by default;
3259 bool ret = true;
3260 if ((mHidlSession_3_5 != nullptr) && mIsReconfigurationQuerySupported) {
3261 android::hardware::hidl_vec<uint8_t> oldParams, newParams;
3262 camera_metadata_t* oldSessioMeta = const_cast<camera_metadata_t*>(
3263 oldSessionParams.getAndLock());
3264 camera_metadata_t* newSessioMeta = const_cast<camera_metadata_t*>(
3265 newSessionParams.getAndLock());
3266 oldParams.setToExternal(reinterpret_cast<uint8_t*>(oldSessioMeta),
3267 get_camera_metadata_size(oldSessioMeta));
3268 newParams.setToExternal(reinterpret_cast<uint8_t*>(newSessioMeta),
3269 get_camera_metadata_size(newSessioMeta));
3270 hardware::camera::common::V1_0::Status callStatus;
3271 bool required;
3272 auto hidlCb = [&callStatus, &required] (hardware::camera::common::V1_0::Status s,
3273 bool requiredFlag) {
3274 callStatus = s;
3275 required = requiredFlag;
3276 };
3277 auto err = mHidlSession_3_5->isReconfigurationRequired(oldParams, newParams, hidlCb);
3278 oldSessionParams.unlock(oldSessioMeta);
3279 newSessionParams.unlock(newSessioMeta);
3280 if (err.isOk()) {
3281 switch (callStatus) {
3282 case hardware::camera::common::V1_0::Status::OK:
3283 ret = required;
3284 break;
3285 case hardware::camera::common::V1_0::Status::METHOD_NOT_SUPPORTED:
3286 mIsReconfigurationQuerySupported = false;
3287 ret = true;
3288 break;
3289 default:
3290 ALOGV("%s: Reconfiguration query failed: %d", __FUNCTION__, callStatus);
3291 ret = true;
3292 }
3293 } else {
3294 ALOGE("%s: Unexpected binder error: %s", __FUNCTION__, err.description().c_str());
3295 ret = true;
3296 }
3297 }
3298
3299 return ret;
3300}
3301
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003302status_t Camera3Device::HalInterface::configureStreams(const camera_metadata_t *sessionParams,
Emilian Peevf4816702020-04-03 15:44:51 -07003303 camera_stream_configuration *config, const std::vector<uint32_t>& bufferSizes) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003304 ATRACE_NAME("CameraHal::configureStreams");
3305 if (!valid()) return INVALID_OPERATION;
3306 status_t res = OK;
3307
Shuzhen Wang83bff122020-11-20 15:51:39 -08003308 if (config->input_is_multi_resolution && mHidlSession_3_7 == nullptr) {
3309 ALOGE("%s: Camera device doesn't support multi-resolution input stream", __FUNCTION__);
3310 return BAD_VALUE;
3311 }
3312
Emilian Peev31abd0a2017-05-11 18:37:46 +01003313 // Convert stream config to HIDL
3314 std::set<int> activeStreams;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003315 device::V3_2::StreamConfiguration requestedConfiguration3_2;
3316 device::V3_4::StreamConfiguration requestedConfiguration3_4;
Shuzhen Wang83bff122020-11-20 15:51:39 -08003317 device::V3_7::StreamConfiguration requestedConfiguration3_7;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003318 requestedConfiguration3_2.streams.resize(config->num_streams);
3319 requestedConfiguration3_4.streams.resize(config->num_streams);
Shuzhen Wang83bff122020-11-20 15:51:39 -08003320 requestedConfiguration3_7.streams.resize(config->num_streams);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003321 for (size_t i = 0; i < config->num_streams; i++) {
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003322 device::V3_2::Stream &dst3_2 = requestedConfiguration3_2.streams[i];
3323 device::V3_4::Stream &dst3_4 = requestedConfiguration3_4.streams[i];
Shuzhen Wang83bff122020-11-20 15:51:39 -08003324 device::V3_7::Stream &dst3_7 = requestedConfiguration3_7.streams[i];
Emilian Peevf4816702020-04-03 15:44:51 -07003325 camera3::camera_stream_t *src = config->streams[i];
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003326
Emilian Peev31abd0a2017-05-11 18:37:46 +01003327 Camera3Stream* cam3stream = Camera3Stream::cast(src);
3328 cam3stream->setBufferFreedListener(this);
3329 int streamId = cam3stream->getId();
3330 StreamType streamType;
3331 switch (src->stream_type) {
Emilian Peevf4816702020-04-03 15:44:51 -07003332 case CAMERA_STREAM_OUTPUT:
Emilian Peev31abd0a2017-05-11 18:37:46 +01003333 streamType = StreamType::OUTPUT;
3334 break;
Emilian Peevf4816702020-04-03 15:44:51 -07003335 case CAMERA_STREAM_INPUT:
Emilian Peev31abd0a2017-05-11 18:37:46 +01003336 streamType = StreamType::INPUT;
3337 break;
3338 default:
3339 ALOGE("%s: Stream %d: Unsupported stream type %d",
3340 __FUNCTION__, streamId, config->streams[i]->stream_type);
3341 return BAD_VALUE;
3342 }
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003343 dst3_2.id = streamId;
3344 dst3_2.streamType = streamType;
3345 dst3_2.width = src->width;
3346 dst3_2.height = src->height;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003347 dst3_2.usage = mapToConsumerUsage(cam3stream->getUsage());
Emilian Peevf4816702020-04-03 15:44:51 -07003348 dst3_2.rotation = mapToStreamRotation((camera_stream_rotation_t) src->rotation);
Shuzhen Wang92653952019-05-07 15:11:43 -07003349 // For HidlSession version 3.5 or newer, the format and dataSpace sent
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08003350 // to HAL are original, not the overridden ones.
Shuzhen Wang92653952019-05-07 15:11:43 -07003351 if (mHidlSession_3_5 != nullptr) {
3352 dst3_2.format = mapToPixelFormat(cam3stream->isFormatOverridden() ?
3353 cam3stream->getOriginalFormat() : src->format);
3354 dst3_2.dataSpace = mapToHidlDataspace(cam3stream->isDataSpaceOverridden() ?
3355 cam3stream->getOriginalDataSpace() : src->data_space);
3356 } else {
3357 dst3_2.format = mapToPixelFormat(src->format);
3358 dst3_2.dataSpace = mapToHidlDataspace(src->data_space);
3359 }
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003360 dst3_4.v3_2 = dst3_2;
Emilian Peev192ee832018-01-31 14:46:47 +00003361 dst3_4.bufferSize = bufferSizes[i];
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003362 if (src->physical_camera_id != nullptr) {
3363 dst3_4.physicalCameraId = src->physical_camera_id;
3364 }
Shuzhen Wang83bff122020-11-20 15:51:39 -08003365 dst3_7.v3_4 = dst3_4;
3366 dst3_7.groupId = cam3stream->getHalStreamGroupId();
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08003367 dst3_7.sensorPixelModesUsed.resize(src->sensor_pixel_modes_used.size());
3368 size_t j = 0;
3369 for (int mode : src->sensor_pixel_modes_used) {
3370 dst3_7.sensorPixelModesUsed[j++] =
3371 static_cast<CameraMetadataEnumAndroidSensorPixelMode>(mode);
3372 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003373 activeStreams.insert(streamId);
3374 // Create Buffer ID map if necessary
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003375 mBufferRecords.tryCreateBufferCache(streamId);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003376 }
3377 // remove BufferIdMap for deleted streams
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003378 mBufferRecords.removeInactiveBufferCaches(activeStreams);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003379
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003380 StreamConfigurationMode operationMode;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003381 res = mapToStreamConfigurationMode(
Emilian Peevf4816702020-04-03 15:44:51 -07003382 (camera_stream_configuration_mode_t) config->operation_mode,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003383 /*out*/ &operationMode);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003384 if (res != OK) {
3385 return res;
3386 }
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003387 requestedConfiguration3_2.operationMode = operationMode;
3388 requestedConfiguration3_4.operationMode = operationMode;
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08003389 requestedConfiguration3_7.operationMode = operationMode;
3390 size_t sessionParamSize = get_camera_metadata_size(sessionParams);
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003391 requestedConfiguration3_4.sessionParams.setToExternal(
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003392 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(sessionParams)),
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08003393 sessionParamSize);
Shuzhen Wang83bff122020-11-20 15:51:39 -08003394 requestedConfiguration3_7.operationMode = operationMode;
3395 requestedConfiguration3_7.sessionParams.setToExternal(
3396 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(sessionParams)),
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08003397 sessionParamSize);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003398
Emilian Peev31abd0a2017-05-11 18:37:46 +01003399 // Invoke configureStreams
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003400 device::V3_3::HalStreamConfiguration finalConfiguration;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003401 device::V3_4::HalStreamConfiguration finalConfiguration3_4;
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003402 device::V3_6::HalStreamConfiguration finalConfiguration3_6;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003403 common::V1_0::Status status;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003404
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003405 auto configStream34Cb = [&status, &finalConfiguration3_4]
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003406 (common::V1_0::Status s, const device::V3_4::HalStreamConfiguration& halConfiguration) {
3407 finalConfiguration3_4 = halConfiguration;
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003408 status = s;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003409 };
3410
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003411 auto configStream36Cb = [&status, &finalConfiguration3_6]
3412 (common::V1_0::Status s, const device::V3_6::HalStreamConfiguration& halConfiguration) {
3413 finalConfiguration3_6 = halConfiguration;
3414 status = s;
3415 };
3416
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003417 auto postprocConfigStream34 = [&finalConfiguration, &finalConfiguration3_4]
3418 (hardware::Return<void>& err) -> status_t {
3419 if (!err.isOk()) {
3420 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3421 return DEAD_OBJECT;
3422 }
3423 finalConfiguration.streams.resize(finalConfiguration3_4.streams.size());
3424 for (size_t i = 0; i < finalConfiguration3_4.streams.size(); i++) {
3425 finalConfiguration.streams[i] = finalConfiguration3_4.streams[i].v3_3;
3426 }
3427 return OK;
3428 };
3429
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003430 auto postprocConfigStream36 = [&finalConfiguration, &finalConfiguration3_6]
3431 (hardware::Return<void>& err) -> status_t {
3432 if (!err.isOk()) {
3433 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3434 return DEAD_OBJECT;
3435 }
3436 finalConfiguration.streams.resize(finalConfiguration3_6.streams.size());
3437 for (size_t i = 0; i < finalConfiguration3_6.streams.size(); i++) {
3438 finalConfiguration.streams[i] = finalConfiguration3_6.streams[i].v3_4.v3_3;
3439 }
3440 return OK;
3441 };
3442
Shuzhen Wang92653952019-05-07 15:11:43 -07003443 // See which version of HAL we have
Shuzhen Wang83bff122020-11-20 15:51:39 -08003444 if (mHidlSession_3_7 != nullptr) {
3445 ALOGV("%s: v3.7 device found", __FUNCTION__);
3446 requestedConfiguration3_7.streamConfigCounter = mNextStreamConfigCounter++;
3447 requestedConfiguration3_7.multiResolutionInputImage = config->input_is_multi_resolution;
3448 auto err = mHidlSession_3_7->configureStreams_3_7(
3449 requestedConfiguration3_7, configStream36Cb);
3450 res = postprocConfigStream36(err);
3451 if (res != OK) {
3452 return res;
3453 }
3454 } else if (mHidlSession_3_6 != nullptr) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003455 ALOGV("%s: v3.6 device found", __FUNCTION__);
3456 device::V3_5::StreamConfiguration requestedConfiguration3_5;
3457 requestedConfiguration3_5.v3_4 = requestedConfiguration3_4;
3458 requestedConfiguration3_5.streamConfigCounter = mNextStreamConfigCounter++;
3459 auto err = mHidlSession_3_6->configureStreams_3_6(
3460 requestedConfiguration3_5, configStream36Cb);
3461 res = postprocConfigStream36(err);
3462 if (res != OK) {
3463 return res;
3464 }
3465 } else if (mHidlSession_3_5 != nullptr) {
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003466 ALOGV("%s: v3.5 device found", __FUNCTION__);
3467 device::V3_5::StreamConfiguration requestedConfiguration3_5;
3468 requestedConfiguration3_5.v3_4 = requestedConfiguration3_4;
3469 requestedConfiguration3_5.streamConfigCounter = mNextStreamConfigCounter++;
3470 auto err = mHidlSession_3_5->configureStreams_3_5(
3471 requestedConfiguration3_5, configStream34Cb);
3472 res = postprocConfigStream34(err);
3473 if (res != OK) {
3474 return res;
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003475 }
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003476 } else if (mHidlSession_3_4 != nullptr) {
3477 // We do; use v3.4 for the call
3478 ALOGV("%s: v3.4 device found", __FUNCTION__);
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003479 auto err = mHidlSession_3_4->configureStreams_3_4(
3480 requestedConfiguration3_4, configStream34Cb);
3481 res = postprocConfigStream34(err);
3482 if (res != OK) {
3483 return res;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003484 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003485 } else if (mHidlSession_3_3 != nullptr) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003486 // We do; use v3.3 for the call
3487 ALOGV("%s: v3.3 device found", __FUNCTION__);
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003488 auto err = mHidlSession_3_3->configureStreams_3_3(requestedConfiguration3_2,
Emilian Peev31abd0a2017-05-11 18:37:46 +01003489 [&status, &finalConfiguration]
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003490 (common::V1_0::Status s, const device::V3_3::HalStreamConfiguration& halConfiguration) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003491 finalConfiguration = halConfiguration;
3492 status = s;
3493 });
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003494 if (!err.isOk()) {
3495 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3496 return DEAD_OBJECT;
3497 }
3498 } else {
3499 // We don't; use v3.2 call and construct a v3.3 HalStreamConfiguration
3500 ALOGV("%s: v3.2 device found", __FUNCTION__);
3501 HalStreamConfiguration finalConfiguration_3_2;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003502 auto err = mHidlSession->configureStreams(requestedConfiguration3_2,
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003503 [&status, &finalConfiguration_3_2]
3504 (common::V1_0::Status s, const HalStreamConfiguration& halConfiguration) {
3505 finalConfiguration_3_2 = halConfiguration;
3506 status = s;
3507 });
3508 if (!err.isOk()) {
3509 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3510 return DEAD_OBJECT;
3511 }
3512 finalConfiguration.streams.resize(finalConfiguration_3_2.streams.size());
3513 for (size_t i = 0; i < finalConfiguration_3_2.streams.size(); i++) {
3514 finalConfiguration.streams[i].v3_2 = finalConfiguration_3_2.streams[i];
3515 finalConfiguration.streams[i].overrideDataSpace =
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003516 requestedConfiguration3_2.streams[i].dataSpace;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003517 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003518 }
3519
3520 if (status != common::V1_0::Status::OK ) {
3521 return CameraProviderManager::mapToStatusT(status);
3522 }
3523
3524 // And convert output stream configuration from HIDL
3525
3526 for (size_t i = 0; i < config->num_streams; i++) {
Emilian Peevf4816702020-04-03 15:44:51 -07003527 camera3::camera_stream_t *dst = config->streams[i];
Emilian Peev31abd0a2017-05-11 18:37:46 +01003528 int streamId = Camera3Stream::cast(dst)->getId();
3529
3530 // Start scan at i, with the assumption that the stream order matches
3531 size_t realIdx = i;
3532 bool found = false;
Eino-Ville Talvala370875f2019-04-12 12:40:27 -07003533 size_t halStreamCount = finalConfiguration.streams.size();
3534 for (size_t idx = 0; idx < halStreamCount; idx++) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003535 if (finalConfiguration.streams[realIdx].v3_2.id == streamId) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003536 found = true;
3537 break;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003538 }
Eino-Ville Talvala370875f2019-04-12 12:40:27 -07003539 realIdx = (realIdx >= halStreamCount - 1) ? 0 : realIdx + 1;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003540 }
3541 if (!found) {
3542 ALOGE("%s: Stream %d not found in stream configuration response from HAL",
3543 __FUNCTION__, streamId);
3544 return INVALID_OPERATION;
3545 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003546 device::V3_3::HalStream &src = finalConfiguration.streams[realIdx];
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003547 device::V3_6::HalStream &src_36 = finalConfiguration3_6.streams[realIdx];
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003548
Emilian Peev710c1422017-08-30 11:19:38 +01003549 Camera3Stream* dstStream = Camera3Stream::cast(dst);
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003550 int overrideFormat = mapToFrameworkFormat(src.v3_2.overrideFormat);
3551 android_dataspace overrideDataSpace = mapToFrameworkDataspace(src.overrideDataSpace);
3552
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003553 if (mHidlSession_3_6 != nullptr) {
3554 dstStream->setOfflineProcessingSupport(src_36.supportOffline);
3555 }
3556
Yin-Chia Yeh90667662019-07-01 15:45:00 -07003557 if (dstStream->getOriginalFormat() != HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
Shuzhen Wang92653952019-05-07 15:11:43 -07003558 dstStream->setFormatOverride(false);
3559 dstStream->setDataSpaceOverride(false);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003560 if (dst->format != overrideFormat) {
3561 ALOGE("%s: Stream %d: Format override not allowed for format 0x%x", __FUNCTION__,
3562 streamId, dst->format);
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003563 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003564 if (dst->data_space != overrideDataSpace) {
3565 ALOGE("%s: Stream %d: DataSpace override not allowed for format 0x%x", __FUNCTION__,
3566 streamId, dst->format);
3567 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003568 } else {
Shuzhen Wang92653952019-05-07 15:11:43 -07003569 bool needFormatOverride =
3570 requestedConfiguration3_2.streams[i].format != src.v3_2.overrideFormat;
3571 bool needDataspaceOverride =
3572 requestedConfiguration3_2.streams[i].dataSpace != src.overrideDataSpace;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003573 // Override allowed with IMPLEMENTATION_DEFINED
Shuzhen Wang92653952019-05-07 15:11:43 -07003574 dstStream->setFormatOverride(needFormatOverride);
3575 dstStream->setDataSpaceOverride(needDataspaceOverride);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003576 dst->format = overrideFormat;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003577 dst->data_space = overrideDataSpace;
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003578 }
3579
Emilian Peevf4816702020-04-03 15:44:51 -07003580 if (dst->stream_type == CAMERA_STREAM_INPUT) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003581 if (src.v3_2.producerUsage != 0) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003582 ALOGE("%s: Stream %d: INPUT streams must have 0 for producer usage",
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003583 __FUNCTION__, streamId);
3584 return INVALID_OPERATION;
3585 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003586 dstStream->setUsage(
3587 mapConsumerToFrameworkUsage(src.v3_2.consumerUsage));
Emilian Peev31abd0a2017-05-11 18:37:46 +01003588 } else {
3589 // OUTPUT
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003590 if (src.v3_2.consumerUsage != 0) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003591 ALOGE("%s: Stream %d: OUTPUT streams must have 0 for consumer usage",
3592 __FUNCTION__, streamId);
3593 return INVALID_OPERATION;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003594 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003595 dstStream->setUsage(
3596 mapProducerToFrameworkUsage(src.v3_2.producerUsage));
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003597 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003598 dst->max_buffers = src.v3_2.maxBuffers;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003599 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003600
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003601 return res;
3602}
3603
Cliff Wuc2ad9c82021-04-21 00:58:58 +08003604status_t Camera3Device::HalInterface::configureInjectedStreams(
3605 const camera_metadata_t* sessionParams, camera_stream_configuration* config,
3606 const std::vector<uint32_t>& bufferSizes,
3607 const CameraMetadata& cameraCharacteristics) {
3608 ATRACE_NAME("InjectionCameraHal::configureStreams");
3609 if (!valid()) return INVALID_OPERATION;
3610 status_t res = OK;
3611
3612 if (config->input_is_multi_resolution) {
3613 ALOGE("%s: Injection camera device doesn't support multi-resolution input "
3614 "stream", __FUNCTION__);
3615 return BAD_VALUE;
3616 }
3617
3618 // Convert stream config to HIDL
3619 std::set<int> activeStreams;
3620 device::V3_2::StreamConfiguration requestedConfiguration3_2;
3621 device::V3_4::StreamConfiguration requestedConfiguration3_4;
3622 device::V3_7::StreamConfiguration requestedConfiguration3_7;
3623 requestedConfiguration3_2.streams.resize(config->num_streams);
3624 requestedConfiguration3_4.streams.resize(config->num_streams);
3625 requestedConfiguration3_7.streams.resize(config->num_streams);
3626 for (size_t i = 0; i < config->num_streams; i++) {
3627 device::V3_2::Stream& dst3_2 = requestedConfiguration3_2.streams[i];
3628 device::V3_4::Stream& dst3_4 = requestedConfiguration3_4.streams[i];
3629 device::V3_7::Stream& dst3_7 = requestedConfiguration3_7.streams[i];
3630 camera3::camera_stream_t* src = config->streams[i];
3631
3632 Camera3Stream* cam3stream = Camera3Stream::cast(src);
3633 cam3stream->setBufferFreedListener(this);
3634 int streamId = cam3stream->getId();
3635 StreamType streamType;
3636 switch (src->stream_type) {
3637 case CAMERA_STREAM_OUTPUT:
3638 streamType = StreamType::OUTPUT;
3639 break;
3640 case CAMERA_STREAM_INPUT:
3641 streamType = StreamType::INPUT;
3642 break;
3643 default:
3644 ALOGE("%s: Stream %d: Unsupported stream type %d", __FUNCTION__,
3645 streamId, config->streams[i]->stream_type);
3646 return BAD_VALUE;
3647 }
3648 dst3_2.id = streamId;
3649 dst3_2.streamType = streamType;
3650 dst3_2.width = src->width;
3651 dst3_2.height = src->height;
3652 dst3_2.usage = mapToConsumerUsage(cam3stream->getUsage());
3653 dst3_2.rotation =
3654 mapToStreamRotation((camera_stream_rotation_t)src->rotation);
3655 // For HidlSession version 3.5 or newer, the format and dataSpace sent
3656 // to HAL are original, not the overridden ones.
3657 if (mHidlSession_3_5 != nullptr) {
3658 dst3_2.format = mapToPixelFormat(cam3stream->isFormatOverridden()
3659 ? cam3stream->getOriginalFormat()
3660 : src->format);
3661 dst3_2.dataSpace =
3662 mapToHidlDataspace(cam3stream->isDataSpaceOverridden()
3663 ? cam3stream->getOriginalDataSpace()
3664 : src->data_space);
3665 } else {
3666 dst3_2.format = mapToPixelFormat(src->format);
3667 dst3_2.dataSpace = mapToHidlDataspace(src->data_space);
3668 }
3669 dst3_4.v3_2 = dst3_2;
3670 dst3_4.bufferSize = bufferSizes[i];
3671 if (src->physical_camera_id != nullptr) {
3672 dst3_4.physicalCameraId = src->physical_camera_id;
3673 }
3674 dst3_7.v3_4 = dst3_4;
3675 dst3_7.groupId = cam3stream->getHalStreamGroupId();
3676 dst3_7.sensorPixelModesUsed.resize(src->sensor_pixel_modes_used.size());
3677 size_t j = 0;
3678 for (int mode : src->sensor_pixel_modes_used) {
3679 dst3_7.sensorPixelModesUsed[j++] =
3680 static_cast<CameraMetadataEnumAndroidSensorPixelMode>(mode);
3681 }
3682 activeStreams.insert(streamId);
3683 // Create Buffer ID map if necessary
3684 mBufferRecords.tryCreateBufferCache(streamId);
3685 }
3686 // remove BufferIdMap for deleted streams
3687 mBufferRecords.removeInactiveBufferCaches(activeStreams);
3688
3689 StreamConfigurationMode operationMode;
3690 res = mapToStreamConfigurationMode(
3691 (camera_stream_configuration_mode_t)config->operation_mode,
3692 /*out*/ &operationMode);
3693 if (res != OK) {
3694 return res;
3695 }
3696 requestedConfiguration3_7.operationMode = operationMode;
3697 size_t sessionParamSize = get_camera_metadata_size(sessionParams);
3698 requestedConfiguration3_7.operationMode = operationMode;
3699 requestedConfiguration3_7.sessionParams.setToExternal(
3700 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(sessionParams)),
3701 sessionParamSize);
3702
3703 // See which version of HAL we have
3704 if (mHidlSession_3_7 != nullptr) {
3705 requestedConfiguration3_7.streamConfigCounter = mNextStreamConfigCounter++;
3706 requestedConfiguration3_7.multiResolutionInputImage =
3707 config->input_is_multi_resolution;
3708
3709 const camera_metadata_t* rawMetadata = cameraCharacteristics.getAndLock();
3710 ::android::hardware::camera::device::V3_2::CameraMetadata hidlChars = {};
3711 hidlChars.setToExternal(
3712 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(rawMetadata)),
3713 get_camera_metadata_size(rawMetadata));
3714 cameraCharacteristics.unlock(rawMetadata);
3715
3716 sp<hardware::camera::device::V3_7::ICameraInjectionSession>
3717 hidlInjectionSession_3_7;
3718 auto castInjectionResult_3_7 =
3719 device::V3_7::ICameraInjectionSession::castFrom(mHidlSession_3_7);
3720 if (castInjectionResult_3_7.isOk()) {
3721 hidlInjectionSession_3_7 = castInjectionResult_3_7;
3722 } else {
3723 ALOGE("%s: Transaction error: %s", __FUNCTION__,
3724 castInjectionResult_3_7.description().c_str());
3725 return DEAD_OBJECT;
3726 }
3727
3728 auto err = hidlInjectionSession_3_7->configureInjectionStreams(
3729 requestedConfiguration3_7, hidlChars);
3730 if (!err.isOk()) {
3731 ALOGE("%s: Transaction error: %s", __FUNCTION__,
3732 err.description().c_str());
3733 return DEAD_OBJECT;
3734 }
3735 } else {
3736 ALOGE("%s: mHidlSession_3_7 does not exist, the lowest version of injection "
3737 "session is 3.7", __FUNCTION__);
3738 return DEAD_OBJECT;
3739 }
3740
3741 return res;
3742}
3743
Emilian Peevf4816702020-04-03 15:44:51 -07003744status_t Camera3Device::HalInterface::wrapAsHidlRequest(camera_capture_request_t* request,
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003745 /*out*/device::V3_2::CaptureRequest* captureRequest,
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003746 /*out*/std::vector<native_handle_t*>* handlesCreated,
3747 /*out*/std::vector<std::pair<int32_t, int32_t>>* inflightBuffers) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003748 ATRACE_CALL();
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003749 if (captureRequest == nullptr || handlesCreated == nullptr || inflightBuffers == nullptr) {
3750 ALOGE("%s: captureRequest (%p), handlesCreated (%p), and inflightBuffers(%p) "
3751 "must not be null", __FUNCTION__, captureRequest, handlesCreated, inflightBuffers);
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003752 return BAD_VALUE;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003753 }
3754
3755 captureRequest->frameNumber = request->frame_number;
Yifan Hongf79b5542017-04-11 14:44:25 -07003756
3757 captureRequest->fmqSettingsSize = 0;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003758
3759 {
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003760 if (request->input_buffer != nullptr) {
3761 int32_t streamId = Camera3Stream::cast(request->input_buffer->stream)->getId();
3762 buffer_handle_t buf = *(request->input_buffer->buffer);
3763 auto pair = getBufferId(buf, streamId);
3764 bool isNewBuffer = pair.first;
3765 uint64_t bufferId = pair.second;
3766 captureRequest->inputBuffer.streamId = streamId;
3767 captureRequest->inputBuffer.bufferId = bufferId;
3768 captureRequest->inputBuffer.buffer = (isNewBuffer) ? buf : nullptr;
3769 captureRequest->inputBuffer.status = BufferStatus::OK;
3770 native_handle_t *acquireFence = nullptr;
3771 if (request->input_buffer->acquire_fence != -1) {
3772 acquireFence = native_handle_create(1,0);
3773 acquireFence->data[0] = request->input_buffer->acquire_fence;
3774 handlesCreated->push_back(acquireFence);
3775 }
3776 captureRequest->inputBuffer.acquireFence = acquireFence;
3777 captureRequest->inputBuffer.releaseFence = nullptr;
3778
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003779 mBufferRecords.pushInflightBuffer(captureRequest->frameNumber, streamId,
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003780 request->input_buffer->buffer);
3781 inflightBuffers->push_back(std::make_pair(captureRequest->frameNumber, streamId));
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003782 } else {
3783 captureRequest->inputBuffer.streamId = -1;
3784 captureRequest->inputBuffer.bufferId = BUFFER_ID_NO_BUFFER;
3785 }
3786
3787 captureRequest->outputBuffers.resize(request->num_output_buffers);
3788 for (size_t i = 0; i < request->num_output_buffers; i++) {
Emilian Peevf4816702020-04-03 15:44:51 -07003789 const camera_stream_buffer_t *src = request->output_buffers + i;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003790 StreamBuffer &dst = captureRequest->outputBuffers[i];
3791 int32_t streamId = Camera3Stream::cast(src->stream)->getId();
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003792 if (src->buffer != nullptr) {
3793 buffer_handle_t buf = *(src->buffer);
3794 auto pair = getBufferId(buf, streamId);
3795 bool isNewBuffer = pair.first;
3796 dst.bufferId = pair.second;
3797 dst.buffer = isNewBuffer ? buf : nullptr;
3798 native_handle_t *acquireFence = nullptr;
3799 if (src->acquire_fence != -1) {
3800 acquireFence = native_handle_create(1,0);
3801 acquireFence->data[0] = src->acquire_fence;
3802 handlesCreated->push_back(acquireFence);
3803 }
3804 dst.acquireFence = acquireFence;
3805 } else if (mUseHalBufManager) {
3806 // HAL buffer management path
3807 dst.bufferId = BUFFER_ID_NO_BUFFER;
3808 dst.buffer = nullptr;
3809 dst.acquireFence = nullptr;
3810 } else {
3811 ALOGE("%s: cannot send a null buffer in capture request!", __FUNCTION__);
3812 return BAD_VALUE;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003813 }
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003814 dst.streamId = streamId;
3815 dst.status = BufferStatus::OK;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003816 dst.releaseFence = nullptr;
3817
Yin-Chia Yeh5f840f82019-03-05 11:59:04 -08003818 // Output buffers are empty when using HAL buffer manager
3819 if (!mUseHalBufManager) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003820 mBufferRecords.pushInflightBuffer(
3821 captureRequest->frameNumber, streamId, src->buffer);
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003822 inflightBuffers->push_back(std::make_pair(captureRequest->frameNumber, streamId));
Yin-Chia Yeh5f840f82019-03-05 11:59:04 -08003823 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003824 }
3825 }
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003826 return OK;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003827}
3828
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003829void Camera3Device::HalInterface::cleanupNativeHandles(
3830 std::vector<native_handle_t*> *handles, bool closeFd) {
3831 if (handles == nullptr) {
3832 return;
3833 }
3834 if (closeFd) {
3835 for (auto& handle : *handles) {
3836 native_handle_close(handle);
3837 }
3838 }
3839 for (auto& handle : *handles) {
3840 native_handle_delete(handle);
3841 }
3842 handles->clear();
3843 return;
3844}
3845
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003846status_t Camera3Device::HalInterface::processBatchCaptureRequests(
Emilian Peevf4816702020-04-03 15:44:51 -07003847 std::vector<camera_capture_request_t*>& requests,/*out*/uint32_t* numRequestProcessed) {
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003848 ATRACE_NAME("CameraHal::processBatchCaptureRequests");
3849 if (!valid()) return INVALID_OPERATION;
3850
Emilian Peevaebbe412018-01-15 13:53:24 +00003851 sp<device::V3_4::ICameraDeviceSession> hidlSession_3_4;
Shuzhen Wang83bff122020-11-20 15:51:39 -08003852 sp<device::V3_7::ICameraDeviceSession> hidlSession_3_7;
3853 auto castResult_3_7 = device::V3_7::ICameraDeviceSession::castFrom(mHidlSession);
3854 if (castResult_3_7.isOk()) {
3855 hidlSession_3_7 = castResult_3_7;
3856 }
Emilian Peevaebbe412018-01-15 13:53:24 +00003857 auto castResult_3_4 = device::V3_4::ICameraDeviceSession::castFrom(mHidlSession);
3858 if (castResult_3_4.isOk()) {
3859 hidlSession_3_4 = castResult_3_4;
3860 }
3861
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003862 hardware::hidl_vec<device::V3_2::CaptureRequest> captureRequests;
Emilian Peevaebbe412018-01-15 13:53:24 +00003863 hardware::hidl_vec<device::V3_4::CaptureRequest> captureRequests_3_4;
Shuzhen Wang83bff122020-11-20 15:51:39 -08003864 hardware::hidl_vec<device::V3_7::CaptureRequest> captureRequests_3_7;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003865 size_t batchSize = requests.size();
Shuzhen Wang83bff122020-11-20 15:51:39 -08003866 if (hidlSession_3_7 != nullptr) {
3867 captureRequests_3_7.resize(batchSize);
3868 } else if (hidlSession_3_4 != nullptr) {
Emilian Peevaebbe412018-01-15 13:53:24 +00003869 captureRequests_3_4.resize(batchSize);
3870 } else {
3871 captureRequests.resize(batchSize);
3872 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003873 std::vector<native_handle_t*> handlesCreated;
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003874 std::vector<std::pair<int32_t, int32_t>> inflightBuffers;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003875
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003876 status_t res = OK;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003877 for (size_t i = 0; i < batchSize; i++) {
Shuzhen Wang83bff122020-11-20 15:51:39 -08003878 if (hidlSession_3_7 != nullptr) {
3879 res = wrapAsHidlRequest(requests[i], /*out*/&captureRequests_3_7[i].v3_4.v3_2,
3880 /*out*/&handlesCreated, /*out*/&inflightBuffers);
3881 } else if (hidlSession_3_4 != nullptr) {
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003882 res = wrapAsHidlRequest(requests[i], /*out*/&captureRequests_3_4[i].v3_2,
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003883 /*out*/&handlesCreated, /*out*/&inflightBuffers);
Emilian Peevaebbe412018-01-15 13:53:24 +00003884 } else {
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003885 res = wrapAsHidlRequest(requests[i], /*out*/&captureRequests[i],
3886 /*out*/&handlesCreated, /*out*/&inflightBuffers);
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003887 }
3888 if (res != OK) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003889 mBufferRecords.popInflightBuffers(inflightBuffers);
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003890 cleanupNativeHandles(&handlesCreated);
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003891 return res;
Emilian Peevaebbe412018-01-15 13:53:24 +00003892 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003893 }
3894
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003895 std::vector<device::V3_2::BufferCache> cachesToRemove;
3896 {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003897 std::lock_guard<std::mutex> lock(mFreedBuffersLock);
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003898 for (auto& pair : mFreedBuffers) {
3899 // The stream might have been removed since onBufferFreed
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003900 if (mBufferRecords.isStreamCached(pair.first)) {
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003901 cachesToRemove.push_back({pair.first, pair.second});
3902 }
3903 }
3904 mFreedBuffers.clear();
3905 }
3906
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003907 common::V1_0::Status status = common::V1_0::Status::INTERNAL_ERROR;
3908 *numRequestProcessed = 0;
Yifan Hongf79b5542017-04-11 14:44:25 -07003909
3910 // Write metadata to FMQ.
3911 for (size_t i = 0; i < batchSize; i++) {
Emilian Peevf4816702020-04-03 15:44:51 -07003912 camera_capture_request_t* request = requests[i];
Emilian Peevaebbe412018-01-15 13:53:24 +00003913 device::V3_2::CaptureRequest* captureRequest;
Shuzhen Wang83bff122020-11-20 15:51:39 -08003914 if (hidlSession_3_7 != nullptr) {
3915 captureRequest = &captureRequests_3_7[i].v3_4.v3_2;
3916 } else if (hidlSession_3_4 != nullptr) {
Emilian Peevaebbe412018-01-15 13:53:24 +00003917 captureRequest = &captureRequests_3_4[i].v3_2;
3918 } else {
3919 captureRequest = &captureRequests[i];
3920 }
Yifan Hongf79b5542017-04-11 14:44:25 -07003921
3922 if (request->settings != nullptr) {
3923 size_t settingsSize = get_camera_metadata_size(request->settings);
3924 if (mRequestMetadataQueue != nullptr && mRequestMetadataQueue->write(
3925 reinterpret_cast<const uint8_t*>(request->settings), settingsSize)) {
3926 captureRequest->settings.resize(0);
3927 captureRequest->fmqSettingsSize = settingsSize;
3928 } else {
3929 if (mRequestMetadataQueue != nullptr) {
3930 ALOGW("%s: couldn't utilize fmq, fallback to hwbinder", __FUNCTION__);
3931 }
3932 captureRequest->settings.setToExternal(
3933 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(request->settings)),
3934 get_camera_metadata_size(request->settings));
3935 captureRequest->fmqSettingsSize = 0u;
3936 }
3937 } else {
3938 // A null request settings maps to a size-0 CameraMetadata
3939 captureRequest->settings.resize(0);
3940 captureRequest->fmqSettingsSize = 0u;
3941 }
Emilian Peevaebbe412018-01-15 13:53:24 +00003942
Shuzhen Wang83bff122020-11-20 15:51:39 -08003943 // hidl session 3.7 specific handling.
3944 if (hidlSession_3_7 != nullptr) {
3945 captureRequests_3_7[i].inputWidth = request->input_width;
3946 captureRequests_3_7[i].inputHeight = request->input_height;
3947 }
3948
3949 // hidl session 3.7 and 3.4 specific handling.
3950 if (hidlSession_3_7 != nullptr || hidlSession_3_4 != nullptr) {
3951 hardware::hidl_vec<device::V3_4::PhysicalCameraSetting>& physicalCameraSettings =
3952 (hidlSession_3_7 != nullptr) ?
3953 captureRequests_3_7[i].v3_4.physicalCameraSettings :
3954 captureRequests_3_4[i].physicalCameraSettings;
3955 physicalCameraSettings.resize(request->num_physcam_settings);
Emilian Peevaebbe412018-01-15 13:53:24 +00003956 for (size_t j = 0; j < request->num_physcam_settings; j++) {
Emilian Peev00420d22018-02-05 21:33:13 +00003957 if (request->physcam_settings != nullptr) {
3958 size_t settingsSize = get_camera_metadata_size(request->physcam_settings[j]);
3959 if (mRequestMetadataQueue != nullptr && mRequestMetadataQueue->write(
3960 reinterpret_cast<const uint8_t*>(request->physcam_settings[j]),
3961 settingsSize)) {
Shuzhen Wang83bff122020-11-20 15:51:39 -08003962 physicalCameraSettings[j].settings.resize(0);
3963 physicalCameraSettings[j].fmqSettingsSize = settingsSize;
Emilian Peev00420d22018-02-05 21:33:13 +00003964 } else {
3965 if (mRequestMetadataQueue != nullptr) {
3966 ALOGW("%s: couldn't utilize fmq, fallback to hwbinder", __FUNCTION__);
3967 }
Shuzhen Wang83bff122020-11-20 15:51:39 -08003968 physicalCameraSettings[j].settings.setToExternal(
Emilian Peev00420d22018-02-05 21:33:13 +00003969 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(
3970 request->physcam_settings[j])),
3971 get_camera_metadata_size(request->physcam_settings[j]));
Shuzhen Wang83bff122020-11-20 15:51:39 -08003972 physicalCameraSettings[j].fmqSettingsSize = 0u;
Emilian Peevaebbe412018-01-15 13:53:24 +00003973 }
Emilian Peev00420d22018-02-05 21:33:13 +00003974 } else {
Yin-Chia Yeha2849702021-03-10 10:11:33 -08003975 physicalCameraSettings[j].fmqSettingsSize = 0u;
3976 physicalCameraSettings[j].settings.resize(0);
Emilian Peevaebbe412018-01-15 13:53:24 +00003977 }
Shuzhen Wang83bff122020-11-20 15:51:39 -08003978 physicalCameraSettings[j].physicalCameraId = request->physcam_id[j];
Emilian Peevaebbe412018-01-15 13:53:24 +00003979 }
3980 }
Yifan Hongf79b5542017-04-11 14:44:25 -07003981 }
Emilian Peevaebbe412018-01-15 13:53:24 +00003982
3983 hardware::details::return_status err;
Jayant Chowdharyc8d581e2018-07-16 14:46:23 -07003984 auto resultCallback =
3985 [&status, &numRequestProcessed] (auto s, uint32_t n) {
3986 status = s;
3987 *numRequestProcessed = n;
3988 };
Shuzhen Wang83bff122020-11-20 15:51:39 -08003989 if (hidlSession_3_7 != nullptr) {
3990 err = hidlSession_3_7->processCaptureRequest_3_7(captureRequests_3_7, cachesToRemove,
3991 resultCallback);
3992 } else if (hidlSession_3_4 != nullptr) {
Emilian Peevaebbe412018-01-15 13:53:24 +00003993 err = hidlSession_3_4->processCaptureRequest_3_4(captureRequests_3_4, cachesToRemove,
Jayant Chowdharyc8d581e2018-07-16 14:46:23 -07003994 resultCallback);
Emilian Peevaebbe412018-01-15 13:53:24 +00003995 } else {
3996 err = mHidlSession->processCaptureRequest(captureRequests, cachesToRemove,
Jayant Chowdharyc8d581e2018-07-16 14:46:23 -07003997 resultCallback);
Emilian Peevaebbe412018-01-15 13:53:24 +00003998 }
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -07003999 if (!err.isOk()) {
4000 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07004001 status = common::V1_0::Status::CAMERA_DISCONNECTED;
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -07004002 }
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07004003
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004004 if (status == common::V1_0::Status::OK && *numRequestProcessed != batchSize) {
4005 ALOGE("%s: processCaptureRequest returns OK but processed %d/%zu requests",
4006 __FUNCTION__, *numRequestProcessed, batchSize);
4007 status = common::V1_0::Status::INTERNAL_ERROR;
4008 }
4009
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07004010 res = CameraProviderManager::mapToStatusT(status);
4011 if (res == OK) {
4012 if (mHidlSession->isRemote()) {
4013 // Only close acquire fence FDs when the HIDL transaction succeeds (so the FDs have been
4014 // sent to camera HAL processes)
4015 cleanupNativeHandles(&handlesCreated, /*closeFd*/true);
4016 } else {
4017 // In passthrough mode the FDs are now owned by HAL
4018 cleanupNativeHandles(&handlesCreated);
4019 }
4020 } else {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004021 mBufferRecords.popInflightBuffers(inflightBuffers);
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07004022 cleanupNativeHandles(&handlesCreated);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004023 }
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07004024 return res;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004025}
4026
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004027status_t Camera3Device::HalInterface::flush() {
4028 ATRACE_NAME("CameraHal::flush");
4029 if (!valid()) return INVALID_OPERATION;
4030 status_t res = OK;
4031
Emilian Peev31abd0a2017-05-11 18:37:46 +01004032 auto err = mHidlSession->flush();
4033 if (!err.isOk()) {
4034 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
4035 res = DEAD_OBJECT;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004036 } else {
Emilian Peev31abd0a2017-05-11 18:37:46 +01004037 res = CameraProviderManager::mapToStatusT(err);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004038 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01004039
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004040 return res;
4041}
4042
Emilian Peev31abd0a2017-05-11 18:37:46 +01004043status_t Camera3Device::HalInterface::dump(int /*fd*/) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004044 ATRACE_NAME("CameraHal::dump");
4045 if (!valid()) return INVALID_OPERATION;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004046
Emilian Peev31abd0a2017-05-11 18:37:46 +01004047 // Handled by CameraProviderManager::dump
4048
4049 return OK;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004050}
4051
4052status_t Camera3Device::HalInterface::close() {
4053 ATRACE_NAME("CameraHal::close()");
4054 if (!valid()) return INVALID_OPERATION;
4055 status_t res = OK;
4056
Emilian Peev31abd0a2017-05-11 18:37:46 +01004057 auto err = mHidlSession->close();
4058 // Interface will be dead shortly anyway, so don't log errors
4059 if (!err.isOk()) {
4060 res = DEAD_OBJECT;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004061 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01004062
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004063 return res;
4064}
4065
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004066void Camera3Device::HalInterface::signalPipelineDrain(const std::vector<int>& streamIds) {
4067 ATRACE_NAME("CameraHal::signalPipelineDrain");
4068 if (!valid() || mHidlSession_3_5 == nullptr) {
4069 ALOGE("%s called on invalid camera!", __FUNCTION__);
4070 return;
4071 }
4072
Yin-Chia Yehc300a072019-02-13 14:56:57 -08004073 auto err = mHidlSession_3_5->signalStreamFlush(streamIds, mNextStreamConfigCounter - 1);
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004074 if (!err.isOk()) {
4075 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
4076 return;
4077 }
4078}
4079
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004080status_t Camera3Device::HalInterface::switchToOffline(
4081 const std::vector<int32_t>& streamsToKeep,
4082 /*out*/hardware::camera::device::V3_6::CameraOfflineSessionInfo* offlineSessionInfo,
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004083 /*out*/sp<hardware::camera::device::V3_6::ICameraOfflineSession>* offlineSession,
4084 /*out*/camera3::BufferRecords* bufferRecords) {
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004085 ATRACE_NAME("CameraHal::switchToOffline");
4086 if (!valid() || mHidlSession_3_6 == nullptr) {
4087 ALOGE("%s called on invalid camera!", __FUNCTION__);
4088 return INVALID_OPERATION;
4089 }
4090
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004091 if (offlineSessionInfo == nullptr || offlineSession == nullptr || bufferRecords == nullptr) {
4092 ALOGE("%s: output arguments must not be null!", __FUNCTION__);
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004093 return INVALID_OPERATION;
4094 }
4095
4096 common::V1_0::Status status = common::V1_0::Status::INTERNAL_ERROR;
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004097 auto resultCallback =
4098 [&status, &offlineSessionInfo, &offlineSession] (auto s, auto info, auto session) {
4099 status = s;
4100 *offlineSessionInfo = info;
4101 *offlineSession = session;
4102 };
4103 auto err = mHidlSession_3_6->switchToOffline(streamsToKeep, resultCallback);
4104
4105 if (!err.isOk()) {
4106 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
4107 return DEAD_OBJECT;
4108 }
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004109
4110 status_t ret = CameraProviderManager::mapToStatusT(status);
4111 if (ret != OK) {
4112 return ret;
4113 }
4114
4115 // TODO: assert no ongoing requestBuffer/returnBuffer call here
4116 // TODO: update RequestBufferStateMachine to block requestBuffer/returnBuffer once HAL
4117 // returns from switchToOffline.
4118
4119
4120 // Validate buffer caches
4121 std::vector<int32_t> streams;
4122 streams.reserve(offlineSessionInfo->offlineStreams.size());
4123 for (auto offlineStream : offlineSessionInfo->offlineStreams) {
4124 int32_t id = offlineStream.id;
4125 streams.push_back(id);
4126 // Verify buffer caches
4127 std::vector<uint64_t> bufIds(offlineStream.circulatingBufferIds.begin(),
4128 offlineStream.circulatingBufferIds.end());
4129 if (!verifyBufferIds(id, bufIds)) {
4130 ALOGE("%s: stream ID %d buffer cache records mismatch!", __FUNCTION__, id);
4131 return UNKNOWN_ERROR;
4132 }
4133 }
4134
4135 // Move buffer records
4136 bufferRecords->takeBufferCaches(mBufferRecords, streams);
4137 bufferRecords->takeInflightBufferMap(mBufferRecords);
4138 bufferRecords->takeRequestedBufferMap(mBufferRecords);
4139 return ret;
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004140}
4141
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07004142void Camera3Device::HalInterface::getInflightBufferKeys(
4143 std::vector<std::pair<int32_t, int32_t>>* out) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004144 mBufferRecords.getInflightBufferKeys(out);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07004145 return;
4146}
4147
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08004148void Camera3Device::HalInterface::getInflightRequestBufferKeys(
4149 std::vector<uint64_t>* out) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004150 mBufferRecords.getInflightRequestBufferKeys(out);
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08004151 return;
4152}
4153
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004154bool Camera3Device::HalInterface::verifyBufferIds(
4155 int32_t streamId, std::vector<uint64_t>& bufIds) {
4156 return mBufferRecords.verifyBufferIds(streamId, bufIds);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004157}
4158
4159status_t Camera3Device::HalInterface::popInflightBuffer(
Yin-Chia Yehf4650602017-01-10 13:13:39 -08004160 int32_t frameNumber, int32_t streamId,
4161 /*out*/ buffer_handle_t **buffer) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004162 return mBufferRecords.popInflightBuffer(frameNumber, streamId, buffer);
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07004163}
4164
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004165status_t Camera3Device::HalInterface::pushInflightRequestBuffer(
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08004166 uint64_t bufferId, buffer_handle_t* buf, int32_t streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004167 return mBufferRecords.pushInflightRequestBuffer(bufferId, buf, streamId);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004168}
4169
4170// Find and pop a buffer_handle_t based on bufferId
4171status_t Camera3Device::HalInterface::popInflightRequestBuffer(
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08004172 uint64_t bufferId,
4173 /*out*/ buffer_handle_t** buffer,
4174 /*optional out*/ int32_t* streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004175 return mBufferRecords.popInflightRequestBuffer(bufferId, buffer, streamId);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004176}
4177
Yin-Chia Yeh77327052017-01-09 18:23:07 -08004178std::pair<bool, uint64_t> Camera3Device::HalInterface::getBufferId(
4179 const buffer_handle_t& buf, int streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004180 return mBufferRecords.getBufferId(buf, streamId);
Yin-Chia Yeh77327052017-01-09 18:23:07 -08004181}
4182
Shuzhen Wangcd5b1822021-09-07 11:52:48 -07004183uint64_t Camera3Device::HalInterface::removeOneBufferCache(int streamId,
4184 const native_handle_t* handle) {
4185 return mBufferRecords.removeOneBufferCache(streamId, handle);
4186}
4187
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07004188void Camera3Device::HalInterface::onBufferFreed(
4189 int streamId, const native_handle_t* handle) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004190 uint32_t bufferId = mBufferRecords.removeOneBufferCache(streamId, handle);
4191 std::lock_guard<std::mutex> lock(mFreedBuffersLock);
4192 if (bufferId != BUFFER_ID_NO_BUFFER) {
4193 mFreedBuffers.push_back(std::make_pair(streamId, bufferId));
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07004194 }
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07004195}
4196
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07004197void Camera3Device::HalInterface::onStreamReConfigured(int streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004198 std::vector<uint64_t> bufIds = mBufferRecords.clearBufferCaches(streamId);
4199 std::lock_guard<std::mutex> lock(mFreedBuffersLock);
4200 for (auto bufferId : bufIds) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07004201 mFreedBuffers.push_back(std::make_pair(streamId, bufferId));
4202 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07004203}
4204
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004205/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004206 * RequestThread inner class methods
4207 */
4208
4209Camera3Device::RequestThread::RequestThread(wp<Camera3Device> parent,
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004210 sp<StatusTracker> statusTracker,
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004211 sp<HalInterface> interface, const Vector<int32_t>& sessionParamKeys,
Eino-Ville Talvala1646c3c2021-07-29 13:48:40 -07004212 bool useHalBufManager,
4213 bool supportCameraMute) :
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004214 Thread(/*canCallJava*/false),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004215 mParent(parent),
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004216 mStatusTracker(statusTracker),
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004217 mInterface(interface),
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07004218 mListener(nullptr),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004219 mId(getId(parent)),
Shuzhen Wang316781a2020-08-18 18:11:01 -07004220 mFirstRepeating(false),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004221 mReconfigured(false),
4222 mDoPause(false),
4223 mPaused(true),
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004224 mNotifyPipelineDrain(false),
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004225 mFrameNumber(0),
Jianing Weicb0652e2014-03-12 18:29:36 -07004226 mLatestRequestId(NAME_NOT_FOUND),
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07004227 mCurrentAfTriggerId(0),
4228 mCurrentPreCaptureTriggerId(0),
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004229 mRotateAndCropOverride(ANDROID_SCALER_ROTATE_AND_CROP_NONE),
Emilian Peeve23f1d92021-09-20 14:56:01 -07004230 mComposerOutput(false),
Eino-Ville Talvala11afe4f2021-05-27 14:45:31 -07004231 mCameraMute(ANDROID_SENSOR_TEST_PATTERN_MODE_OFF),
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004232 mCameraMuteChanged(false),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004233 mRepeatingLastFrameNumber(
4234 hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES),
Shuzhen Wang686f6442017-06-20 16:16:04 -07004235 mPrepareVideoStream(false),
Emilian Peeva14b4dd2018-05-15 11:00:31 +01004236 mConstrainedMode(false),
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004237 mRequestLatency(kRequestLatencyBinSize),
4238 mSessionParamKeys(sessionParamKeys),
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004239 mLatestSessionParams(sessionParamKeys.size()),
Eino-Ville Talvala1646c3c2021-07-29 13:48:40 -07004240 mUseHalBufManager(useHalBufManager),
4241 mSupportCameraMute(supportCameraMute){
Yin-Chia Yeh87b3ec02019-06-03 10:44:39 -07004242 mStatusId = statusTracker->addComponent("RequestThread");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004243}
4244
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004245Camera3Device::RequestThread::~RequestThread() {}
4246
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004247void Camera3Device::RequestThread::setNotificationListener(
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004248 wp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004249 ATRACE_CALL();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004250 Mutex::Autolock l(mRequestLock);
4251 mListener = listener;
4252}
4253
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004254void Camera3Device::RequestThread::configurationComplete(bool isConstrainedHighSpeed,
Shuzhen Wang99080502021-03-07 21:08:20 -08004255 const CameraMetadata& sessionParams,
4256 const std::map<int32_t, std::set<String8>>& groupIdPhysicalCameraMap) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004257 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004258 Mutex::Autolock l(mRequestLock);
4259 mReconfigured = true;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004260 mLatestSessionParams = sessionParams;
Shuzhen Wang99080502021-03-07 21:08:20 -08004261 mGroupIdPhysicalCameraMap = groupIdPhysicalCameraMap;
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07004262 // Prepare video stream for high speed recording.
4263 mPrepareVideoStream = isConstrainedHighSpeed;
Emilian Peeva14b4dd2018-05-15 11:00:31 +01004264 mConstrainedMode = isConstrainedHighSpeed;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004265}
4266
Jianing Wei90e59c92014-03-12 18:29:36 -07004267status_t Camera3Device::RequestThread::queueRequestList(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004268 List<sp<CaptureRequest> > &requests,
4269 /*out*/
4270 int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004271 ATRACE_CALL();
Jianing Wei90e59c92014-03-12 18:29:36 -07004272 Mutex::Autolock l(mRequestLock);
4273 for (List<sp<CaptureRequest> >::iterator it = requests.begin(); it != requests.end();
4274 ++it) {
4275 mRequestQueue.push_back(*it);
4276 }
4277
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004278 if (lastFrameNumber != NULL) {
4279 *lastFrameNumber = mFrameNumber + mRequestQueue.size() - 1;
4280 ALOGV("%s: requestId %d, mFrameNumber %" PRId32 ", lastFrameNumber %" PRId64 ".",
4281 __FUNCTION__, (*(requests.begin()))->mResultExtras.requestId, mFrameNumber,
4282 *lastFrameNumber);
4283 }
Jianing Weicb0652e2014-03-12 18:29:36 -07004284
Jianing Wei90e59c92014-03-12 18:29:36 -07004285 unpauseForNewRequests();
4286
4287 return OK;
4288}
4289
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004290
4291status_t Camera3Device::RequestThread::queueTrigger(
4292 RequestTrigger trigger[],
4293 size_t count) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004294 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004295 Mutex::Autolock l(mTriggerMutex);
4296 status_t ret;
4297
4298 for (size_t i = 0; i < count; ++i) {
4299 ret = queueTriggerLocked(trigger[i]);
4300
4301 if (ret != OK) {
4302 return ret;
4303 }
4304 }
4305
4306 return OK;
4307}
4308
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004309const String8& Camera3Device::RequestThread::getId(const wp<Camera3Device> &device) {
4310 static String8 deadId("<DeadDevice>");
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004311 sp<Camera3Device> d = device.promote();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004312 if (d != nullptr) return d->mId;
4313 return deadId;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004314}
4315
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004316status_t Camera3Device::RequestThread::queueTriggerLocked(
4317 RequestTrigger trigger) {
4318
4319 uint32_t tag = trigger.metadataTag;
4320 ssize_t index = mTriggerMap.indexOfKey(tag);
4321
4322 switch (trigger.getTagType()) {
4323 case TYPE_BYTE:
4324 // fall-through
4325 case TYPE_INT32:
4326 break;
4327 default:
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004328 ALOGE("%s: Type not supported: 0x%x", __FUNCTION__,
4329 trigger.getTagType());
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004330 return INVALID_OPERATION;
4331 }
4332
4333 /**
4334 * Collect only the latest trigger, since we only have 1 field
4335 * in the request settings per trigger tag, and can't send more than 1
4336 * trigger per request.
4337 */
4338 if (index != NAME_NOT_FOUND) {
4339 mTriggerMap.editValueAt(index) = trigger;
4340 } else {
4341 mTriggerMap.add(tag, trigger);
4342 }
4343
4344 return OK;
4345}
4346
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004347status_t Camera3Device::RequestThread::setRepeatingRequests(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004348 const RequestList &requests,
4349 /*out*/
4350 int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004351 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004352 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004353 if (lastFrameNumber != NULL) {
4354 *lastFrameNumber = mRepeatingLastFrameNumber;
4355 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004356 mRepeatingRequests.clear();
Shuzhen Wang316781a2020-08-18 18:11:01 -07004357 mFirstRepeating = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004358 mRepeatingRequests.insert(mRepeatingRequests.begin(),
4359 requests.begin(), requests.end());
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004360
4361 unpauseForNewRequests();
4362
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004363 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004364 return OK;
4365}
4366
Chih-Hung Hsieh8b0b9712016-08-09 14:25:53 -07004367bool Camera3Device::RequestThread::isRepeatingRequestLocked(const sp<CaptureRequest>& requestIn) {
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07004368 if (mRepeatingRequests.empty()) {
4369 return false;
4370 }
4371 int32_t requestId = requestIn->mResultExtras.requestId;
4372 const RequestList &repeatRequests = mRepeatingRequests;
4373 // All repeating requests are guaranteed to have same id so only check first quest
4374 const sp<CaptureRequest> firstRequest = *repeatRequests.begin();
4375 return (firstRequest->mResultExtras.requestId == requestId);
4376}
4377
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004378status_t Camera3Device::RequestThread::clearRepeatingRequests(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004379 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004380 Mutex::Autolock l(mRequestLock);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004381 return clearRepeatingRequestsLocked(lastFrameNumber);
4382
4383}
4384
4385status_t Camera3Device::RequestThread::clearRepeatingRequestsLocked(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004386 mRepeatingRequests.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004387 if (lastFrameNumber != NULL) {
4388 *lastFrameNumber = mRepeatingLastFrameNumber;
4389 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004390 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004391 return OK;
4392}
4393
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004394status_t Camera3Device::RequestThread::clear(
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004395 /*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004396 ATRACE_CALL();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004397 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004398 ALOGV("RequestThread::%s:", __FUNCTION__);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004399
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004400 mRepeatingRequests.clear();
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07004401
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004402 // Send errors for all requests pending in the request queue, including
4403 // pending repeating requests
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004404 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004405 if (listener != NULL) {
4406 for (RequestList::iterator it = mRequestQueue.begin();
4407 it != mRequestQueue.end(); ++it) {
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004408 // Abort the input buffers for reprocess requests.
4409 if ((*it)->mInputStream != NULL) {
Emilian Peevf4816702020-04-03 15:44:51 -07004410 camera_stream_buffer_t inputBuffer;
Shuzhen Wang83bff122020-11-20 15:51:39 -08004411 camera3::Size inputBufferSize;
Eino-Ville Talvalaba435252017-06-21 16:07:25 -07004412 status_t res = (*it)->mInputStream->getInputBuffer(&inputBuffer,
Shuzhen Wang83bff122020-11-20 15:51:39 -08004413 &inputBufferSize, /*respectHalLimit*/ false);
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004414 if (res != OK) {
4415 ALOGW("%s: %d: couldn't get input buffer while clearing the request "
4416 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
4417 } else {
Emilian Peevf4816702020-04-03 15:44:51 -07004418 inputBuffer.status = CAMERA_BUFFER_STATUS_ERROR;
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004419 res = (*it)->mInputStream->returnInputBuffer(inputBuffer);
4420 if (res != OK) {
4421 ALOGE("%s: %d: couldn't return input buffer while clearing the request "
4422 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
4423 }
4424 }
4425 }
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004426 // Set the frame number this request would have had, if it
4427 // had been submitted; this frame number will not be reused.
4428 // The requestId and burstId fields were set when the request was
4429 // submitted originally (in convertMetadataListToRequestListLocked)
4430 (*it)->mResultExtras.frameNumber = mFrameNumber++;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004431 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004432 (*it)->mResultExtras);
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07004433 }
4434 }
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004435 mRequestQueue.clear();
Jinguang Dongb26e7a02016-11-14 16:04:02 +08004436
4437 Mutex::Autolock al(mTriggerMutex);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004438 mTriggerMap.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004439 if (lastFrameNumber != NULL) {
4440 *lastFrameNumber = mRepeatingLastFrameNumber;
4441 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004442 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Emilian Peev8dae54c2019-12-02 15:17:17 -08004443 mRequestSignal.signal();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004444 return OK;
4445}
4446
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004447status_t Camera3Device::RequestThread::flush() {
4448 ATRACE_CALL();
4449 Mutex::Autolock l(mFlushLock);
4450
Emilian Peev08dd2452017-04-06 16:55:14 +01004451 return mInterface->flush();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004452}
4453
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004454void Camera3Device::RequestThread::setPaused(bool paused) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004455 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004456 Mutex::Autolock l(mPauseLock);
4457 mDoPause = paused;
4458 mDoPauseSignal.signal();
4459}
4460
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004461status_t Camera3Device::RequestThread::waitUntilRequestProcessed(
4462 int32_t requestId, nsecs_t timeout) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004463 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004464 Mutex::Autolock l(mLatestRequestMutex);
4465 status_t res;
4466 while (mLatestRequestId != requestId) {
4467 nsecs_t startTime = systemTime();
4468
4469 res = mLatestRequestSignal.waitRelative(mLatestRequestMutex, timeout);
4470 if (res != OK) return res;
4471
4472 timeout -= (systemTime() - startTime);
4473 }
4474
4475 return OK;
4476}
4477
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004478void Camera3Device::RequestThread::requestExit() {
4479 // Call parent to set up shutdown
4480 Thread::requestExit();
4481 // The exit from any possible waits
4482 mDoPauseSignal.signal();
4483 mRequestSignal.signal();
Shuzhen Wang686f6442017-06-20 16:16:04 -07004484
4485 mRequestLatency.log("ProcessCaptureRequest latency histogram");
4486 mRequestLatency.reset();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004487}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004488
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004489void Camera3Device::RequestThread::checkAndStopRepeatingRequest() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004490 ATRACE_CALL();
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07004491 bool surfaceAbandoned = false;
4492 int64_t lastFrameNumber = 0;
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004493 sp<NotificationListener> listener;
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07004494 {
4495 Mutex::Autolock l(mRequestLock);
4496 // Check all streams needed by repeating requests are still valid. Otherwise, stop
4497 // repeating requests.
4498 for (const auto& request : mRepeatingRequests) {
4499 for (const auto& s : request->mOutputStreams) {
4500 if (s->isAbandoned()) {
4501 surfaceAbandoned = true;
4502 clearRepeatingRequestsLocked(&lastFrameNumber);
4503 break;
4504 }
4505 }
4506 if (surfaceAbandoned) {
4507 break;
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004508 }
4509 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004510 listener = mListener.promote();
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004511 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004512
4513 if (listener != NULL && surfaceAbandoned) {
4514 listener->notifyRepeatingRequestError(lastFrameNumber);
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07004515 }
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004516}
4517
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004518bool Camera3Device::RequestThread::sendRequestsBatch() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004519 ATRACE_CALL();
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004520 status_t res;
4521 size_t batchSize = mNextRequests.size();
Emilian Peevf4816702020-04-03 15:44:51 -07004522 std::vector<camera_capture_request_t*> requests(batchSize);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004523 uint32_t numRequestProcessed = 0;
4524 for (size_t i = 0; i < batchSize; i++) {
4525 requests[i] = &mNextRequests.editItemAt(i).halRequest;
Yin-Chia Yeh885691c2018-05-01 15:54:24 -07004526 ATRACE_ASYNC_BEGIN("frame capture", mNextRequests[i].halRequest.frame_number);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004527 }
4528
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004529 res = mInterface->processBatchCaptureRequests(requests, &numRequestProcessed);
4530
4531 bool triggerRemoveFailed = false;
4532 NextRequest& triggerFailedRequest = mNextRequests.editItemAt(0);
4533 for (size_t i = 0; i < numRequestProcessed; i++) {
4534 NextRequest& nextRequest = mNextRequests.editItemAt(i);
4535 nextRequest.submitted = true;
4536
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004537 updateNextRequest(nextRequest);
Emilian Peevaebbe412018-01-15 13:53:24 +00004538
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004539 if (!triggerRemoveFailed) {
4540 // Remove any previously queued triggers (after unlock)
4541 status_t removeTriggerRes = removeTriggers(mPrevRequest);
4542 if (removeTriggerRes != OK) {
4543 triggerRemoveFailed = true;
4544 triggerFailedRequest = nextRequest;
4545 }
4546 }
4547 }
4548
4549 if (triggerRemoveFailed) {
4550 SET_ERR("RequestThread: Unable to remove triggers "
4551 "(capture request %d, HAL device: %s (%d)",
4552 triggerFailedRequest.halRequest.frame_number, strerror(-res), res);
4553 cleanUpFailedRequests(/*sendRequestError*/ false);
4554 return false;
4555 }
4556
4557 if (res != OK) {
4558 // Should only get a failure here for malformed requests or device-level
4559 // errors, so consider all errors fatal. Bad metadata failures should
4560 // come through notify.
4561 SET_ERR("RequestThread: Unable to submit capture request %d to HAL device: %s (%d)",
4562 mNextRequests[numRequestProcessed].halRequest.frame_number,
4563 strerror(-res), res);
4564 cleanUpFailedRequests(/*sendRequestError*/ false);
4565 return false;
4566 }
4567 return true;
4568}
4569
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07004570nsecs_t Camera3Device::RequestThread::calculateMaxExpectedDuration(const camera_metadata_t *request) {
4571 nsecs_t maxExpectedDuration = kDefaultExpectedDuration;
4572 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
4573 find_camera_metadata_ro_entry(request,
4574 ANDROID_CONTROL_AE_MODE,
4575 &e);
4576 if (e.count == 0) return maxExpectedDuration;
4577
4578 switch (e.data.u8[0]) {
4579 case ANDROID_CONTROL_AE_MODE_OFF:
4580 find_camera_metadata_ro_entry(request,
4581 ANDROID_SENSOR_EXPOSURE_TIME,
4582 &e);
4583 if (e.count > 0) {
4584 maxExpectedDuration = e.data.i64[0];
4585 }
4586 find_camera_metadata_ro_entry(request,
4587 ANDROID_SENSOR_FRAME_DURATION,
4588 &e);
4589 if (e.count > 0) {
4590 maxExpectedDuration = std::max(e.data.i64[0], maxExpectedDuration);
4591 }
4592 break;
4593 default:
4594 find_camera_metadata_ro_entry(request,
4595 ANDROID_CONTROL_AE_TARGET_FPS_RANGE,
4596 &e);
4597 if (e.count > 1) {
4598 maxExpectedDuration = 1e9 / e.data.u8[0];
4599 }
4600 break;
4601 }
4602
4603 return maxExpectedDuration;
4604}
4605
Emilian Peeva14b4dd2018-05-15 11:00:31 +01004606bool Camera3Device::RequestThread::skipHFRTargetFPSUpdate(int32_t tag,
4607 const camera_metadata_ro_entry_t& newEntry, const camera_metadata_entry_t& currentEntry) {
4608 if (mConstrainedMode && (ANDROID_CONTROL_AE_TARGET_FPS_RANGE == tag) &&
4609 (newEntry.count == currentEntry.count) && (currentEntry.count == 2) &&
4610 (currentEntry.data.i32[1] == newEntry.data.i32[1])) {
4611 return true;
4612 }
4613
4614 return false;
4615}
4616
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004617void Camera3Device::RequestThread::updateNextRequest(NextRequest& nextRequest) {
4618 // Update the latest request sent to HAL
Shuzhen Wang83bff122020-11-20 15:51:39 -08004619 camera_capture_request_t& halRequest = nextRequest.halRequest;
4620 if (halRequest.settings != NULL) { // Don't update if they were unchanged
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004621 Mutex::Autolock al(mLatestRequestMutex);
4622
Shuzhen Wang83bff122020-11-20 15:51:39 -08004623 camera_metadata_t* cloned = clone_camera_metadata(halRequest.settings);
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004624 mLatestRequest.acquire(cloned);
4625
4626 mLatestPhysicalRequest.clear();
Shuzhen Wang83bff122020-11-20 15:51:39 -08004627 for (uint32_t i = 0; i < halRequest.num_physcam_settings; i++) {
4628 cloned = clone_camera_metadata(halRequest.physcam_settings[i]);
4629 mLatestPhysicalRequest.emplace(halRequest.physcam_id[i],
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004630 CameraMetadata(cloned));
4631 }
4632
4633 sp<Camera3Device> parent = mParent.promote();
4634 if (parent != NULL) {
Jayant Chowdharycd277cd2021-08-11 15:48:40 -07004635 int32_t inputStreamId = -1;
4636 if (halRequest.input_buffer != nullptr) {
4637 inputStreamId = Camera3Stream::cast(halRequest.input_buffer->stream)->getId();
4638 }
4639
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004640 parent->monitorMetadata(TagMonitor::REQUEST,
Shuzhen Wang83bff122020-11-20 15:51:39 -08004641 halRequest.frame_number,
Jayant Chowdharyc30b4c32021-08-18 11:43:16 -07004642 0, mLatestRequest, mLatestPhysicalRequest, halRequest.output_buffers,
4643 halRequest.num_output_buffers, inputStreamId);
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004644 }
4645 }
4646
Shuzhen Wang83bff122020-11-20 15:51:39 -08004647 if (halRequest.settings != NULL) {
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004648 nextRequest.captureRequest->mSettingsList.begin()->metadata.unlock(
Shuzhen Wang83bff122020-11-20 15:51:39 -08004649 halRequest.settings);
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004650 }
4651
Shuzhen Wang83bff122020-11-20 15:51:39 -08004652 cleanupPhysicalSettings(nextRequest.captureRequest, &halRequest);
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004653}
4654
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004655bool Camera3Device::RequestThread::updateSessionParameters(const CameraMetadata& settings) {
4656 ATRACE_CALL();
4657 bool updatesDetected = false;
4658
Emilian Peev4ec17882019-01-24 17:16:58 -08004659 CameraMetadata updatedParams(mLatestSessionParams);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004660 for (auto tag : mSessionParamKeys) {
4661 camera_metadata_ro_entry entry = settings.find(tag);
Emilian Peev4ec17882019-01-24 17:16:58 -08004662 camera_metadata_entry lastEntry = updatedParams.find(tag);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004663
4664 if (entry.count > 0) {
4665 bool isDifferent = false;
4666 if (lastEntry.count > 0) {
4667 // Have a last value, compare to see if changed
4668 if (lastEntry.type == entry.type &&
4669 lastEntry.count == entry.count) {
4670 // Same type and count, compare values
4671 size_t bytesPerValue = camera_metadata_type_size[lastEntry.type];
4672 size_t entryBytes = bytesPerValue * lastEntry.count;
4673 int cmp = memcmp(entry.data.u8, lastEntry.data.u8, entryBytes);
4674 if (cmp != 0) {
4675 isDifferent = true;
4676 }
4677 } else {
4678 // Count or type has changed
4679 isDifferent = true;
4680 }
4681 } else {
4682 // No last entry, so always consider to be different
4683 isDifferent = true;
4684 }
4685
4686 if (isDifferent) {
4687 ALOGV("%s: Session parameter tag id %d changed", __FUNCTION__, tag);
Emilian Peeva14b4dd2018-05-15 11:00:31 +01004688 if (!skipHFRTargetFPSUpdate(tag, entry, lastEntry)) {
4689 updatesDetected = true;
4690 }
Emilian Peev4ec17882019-01-24 17:16:58 -08004691 updatedParams.update(entry);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004692 }
4693 } else if (lastEntry.count > 0) {
4694 // Value has been removed
4695 ALOGV("%s: Session parameter tag id %d removed", __FUNCTION__, tag);
Emilian Peev4ec17882019-01-24 17:16:58 -08004696 updatedParams.erase(tag);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004697 updatesDetected = true;
4698 }
4699 }
4700
Emilian Peev4ec17882019-01-24 17:16:58 -08004701 bool reconfigureRequired;
4702 if (updatesDetected) {
4703 reconfigureRequired = mInterface->isReconfigurationRequired(mLatestSessionParams,
4704 updatedParams);
4705 mLatestSessionParams = updatedParams;
4706 } else {
4707 reconfigureRequired = false;
4708 }
4709
4710 return reconfigureRequired;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004711}
4712
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004713bool Camera3Device::RequestThread::threadLoop() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004714 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004715 status_t res;
Jayant Chowdhary37eca242019-11-18 08:55:56 -08004716 // Any function called from threadLoop() must not hold mInterfaceLock since
4717 // it could lead to deadlocks (disconnect() -> hold mInterfaceMutex -> wait for request thread
4718 // to finish -> request thread waits on mInterfaceMutex) http://b/143513518
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004719
4720 // Handle paused state.
4721 if (waitIfPaused()) {
4722 return true;
4723 }
4724
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004725 // Wait for the next batch of requests.
4726 waitForNextRequestBatch();
4727 if (mNextRequests.size() == 0) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004728 return true;
4729 }
4730
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004731 // Get the latest request ID, if any
4732 int latestRequestId;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004733 camera_metadata_entry_t requestIdEntry = mNextRequests[mNextRequests.size() - 1].
Emilian Peevaebbe412018-01-15 13:53:24 +00004734 captureRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_ID);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004735 if (requestIdEntry.count > 0) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004736 latestRequestId = requestIdEntry.data.i32[0];
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004737 } else {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004738 ALOGW("%s: Did not have android.request.id set in the request.", __FUNCTION__);
4739 latestRequestId = NAME_NOT_FOUND;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004740 }
4741
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004742 // 'mNextRequests' will at this point contain either a set of HFR batched requests
4743 // or a single request from streaming or burst. In either case the first element
4744 // should contain the latest camera settings that we need to check for any session
4745 // parameter updates.
Emilian Peevaebbe412018-01-15 13:53:24 +00004746 if (updateSessionParameters(mNextRequests[0].captureRequest->mSettingsList.begin()->metadata)) {
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004747 res = OK;
4748
4749 //Input stream buffers are already acquired at this point so an input stream
4750 //will not be able to move to idle state unless we force it.
4751 if (mNextRequests[0].captureRequest->mInputStream != nullptr) {
4752 res = mNextRequests[0].captureRequest->mInputStream->forceToIdle();
4753 if (res != OK) {
4754 ALOGE("%s: Failed to force idle input stream: %d", __FUNCTION__, res);
4755 cleanUpFailedRequests(/*sendRequestError*/ false);
4756 return false;
4757 }
4758 }
4759
4760 if (res == OK) {
Emilian Peev3bead5f2020-05-28 17:29:08 -07004761 sp<Camera3Device> parent = mParent.promote();
4762 if (parent != nullptr) {
4763 mReconfigured |= parent->reconfigureCamera(mLatestSessionParams, mStatusId);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004764 }
Emilian Peev3bead5f2020-05-28 17:29:08 -07004765 setPaused(false);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004766
4767 if (mNextRequests[0].captureRequest->mInputStream != nullptr) {
4768 mNextRequests[0].captureRequest->mInputStream->restoreConfiguredState();
4769 if (res != OK) {
4770 ALOGE("%s: Failed to restore configured input stream: %d", __FUNCTION__, res);
4771 cleanUpFailedRequests(/*sendRequestError*/ false);
4772 return false;
4773 }
4774 }
4775 }
4776 }
4777
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004778 // Prepare a batch of HAL requests and output buffers.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004779 res = prepareHalRequests();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004780 if (res == TIMED_OUT) {
4781 // Not a fatal error if getting output buffers time out.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004782 cleanUpFailedRequests(/*sendRequestError*/ true);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004783 // Check if any stream is abandoned.
4784 checkAndStopRepeatingRequest();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004785 return true;
4786 } else if (res != OK) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004787 cleanUpFailedRequests(/*sendRequestError*/ false);
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004788 return false;
4789 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004790
Zhijun Hecc27e112013-10-03 16:12:43 -07004791 // Inform waitUntilRequestProcessed thread of a new request ID
4792 {
4793 Mutex::Autolock al(mLatestRequestMutex);
4794
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004795 mLatestRequestId = latestRequestId;
Zhijun Hecc27e112013-10-03 16:12:43 -07004796 mLatestRequestSignal.signal();
4797 }
4798
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004799 // Submit a batch of requests to HAL.
4800 // Use flush lock only when submitting multilple requests in a batch.
4801 // TODO: The problem with flush lock is flush() will be blocked by process_capture_request()
4802 // which may take a long time to finish so synchronizing flush() and
4803 // process_capture_request() defeats the purpose of cancelling requests ASAP with flush().
4804 // For now, only synchronize for high speed recording and we should figure something out for
4805 // removing the synchronization.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004806 bool useFlushLock = mNextRequests.size() > 1;
Eino-Ville Talvala17a61ad2013-06-03 16:53:32 -07004807
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004808 if (useFlushLock) {
4809 mFlushLock.lock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004810 }
4811
Zhijun Hef0645c12016-08-02 00:58:11 -07004812 ALOGVV("%s: %d: submitting %zu requests in a batch.", __FUNCTION__, __LINE__,
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004813 mNextRequests.size());
Igor Murashkin1e479c02013-09-06 16:55:14 -07004814
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08004815 sp<Camera3Device> parent = mParent.promote();
4816 if (parent != nullptr) {
4817 parent->mRequestBufferSM.onSubmittingRequest();
4818 }
4819
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004820 bool submitRequestSuccess = false;
Shuzhen Wang686f6442017-06-20 16:16:04 -07004821 nsecs_t tRequestStart = systemTime(SYSTEM_TIME_MONOTONIC);
Yin-Chia Yeh11648852019-05-16 10:42:54 -07004822 submitRequestSuccess = sendRequestsBatch();
4823
Shuzhen Wang686f6442017-06-20 16:16:04 -07004824 nsecs_t tRequestEnd = systemTime(SYSTEM_TIME_MONOTONIC);
4825 mRequestLatency.add(tRequestStart, tRequestEnd);
Igor Murashkin1e479c02013-09-06 16:55:14 -07004826
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004827 if (useFlushLock) {
4828 mFlushLock.unlock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004829 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004830
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004831 // Unset as current request
4832 {
4833 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004834 mNextRequests.clear();
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004835 }
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004836 mRequestSubmittedSignal.signal();
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004837
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004838 return submitRequestSuccess;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004839}
4840
Jayant Chowdhary65c9bf02021-09-03 16:44:16 +00004841status_t Camera3Device::removeFwkOnlyRegionKeys(CameraMetadata *request) {
4842 static const std::array<uint32_t, 4> kFwkOnlyRegionKeys = {ANDROID_CONTROL_AF_REGIONS_SET,
4843 ANDROID_CONTROL_AE_REGIONS_SET, ANDROID_CONTROL_AWB_REGIONS_SET,
4844 ANDROID_SCALER_CROP_REGION_SET};
4845 if (request == nullptr) {
4846 ALOGE("%s request metadata nullptr", __FUNCTION__);
4847 return BAD_VALUE;
4848 }
4849 status_t res = OK;
4850 for (const auto &key : kFwkOnlyRegionKeys) {
4851 if (request->exists(key)) {
4852 res = request->erase(key);
4853 if (res != OK) {
4854 return res;
4855 }
4856 }
4857 }
4858 return OK;
4859}
4860
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004861status_t Camera3Device::RequestThread::prepareHalRequests() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004862 ATRACE_CALL();
4863
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07004864 bool batchedRequest = mNextRequests[0].captureRequest->mBatchSize > 1;
Shuzhen Wang4a472662017-02-26 23:29:04 -08004865 for (size_t i = 0; i < mNextRequests.size(); i++) {
4866 auto& nextRequest = mNextRequests.editItemAt(i);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004867 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
Emilian Peevf4816702020-04-03 15:44:51 -07004868 camera_capture_request_t* halRequest = &nextRequest.halRequest;
4869 Vector<camera_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004870
4871 // Prepare a request to HAL
4872 halRequest->frame_number = captureRequest->mResultExtras.frameNumber;
4873
4874 // Insert any queued triggers (before metadata is locked)
4875 status_t res = insertTriggers(captureRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004876 if (res < 0) {
4877 SET_ERR("RequestThread: Unable to insert triggers "
4878 "(capture request %d, HAL device: %s (%d)",
4879 halRequest->frame_number, strerror(-res), res);
4880 return INVALID_OPERATION;
4881 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07004882
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004883 int triggerCount = res;
4884 bool triggersMixedIn = (triggerCount > 0 || mPrevTriggers > 0);
4885 mPrevTriggers = triggerCount;
4886
Emilian Peeve23f1d92021-09-20 14:56:01 -07004887 // Do not override rotate&crop for stream configurations that include
4888 // SurfaceViews(HW_COMPOSER) output. The display rotation there will be
4889 // compensated by NATIVE_WINDOW_TRANSFORM_INVERSE_DISPLAY
4890 bool rotateAndCropChanged = mComposerOutput ? false :
4891 overrideAutoRotateAndCrop(captureRequest);
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004892 bool testPatternChanged = overrideTestPattern(captureRequest);
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004893
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004894 // If the request is the same as last, or we had triggers now or last time or
4895 // changing overrides this time
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004896 bool newRequest =
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004897 (mPrevRequest != captureRequest || triggersMixedIn ||
4898 rotateAndCropChanged || testPatternChanged) &&
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07004899 // Request settings are all the same within one batch, so only treat the first
4900 // request in a batch as new
Zhijun He54c36822018-07-18 09:33:39 -07004901 !(batchedRequest && i > 0);
Emilian Peev00420d22018-02-05 21:33:13 +00004902 if (newRequest) {
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08004903 std::set<std::string> cameraIdsWithZoom;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004904 /**
4905 * HAL workaround:
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004906 * Insert a fake trigger ID if a trigger is set but no trigger ID is
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004907 */
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004908 res = addFakeTriggerIds(captureRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004909 if (res != OK) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004910 SET_ERR("RequestThread: Unable to insert fake trigger IDs "
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004911 "(capture request %d, HAL device: %s (%d)",
4912 halRequest->frame_number, strerror(-res), res);
4913 return INVALID_OPERATION;
4914 }
4915
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07004916 {
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07004917 sp<Camera3Device> parent = mParent.promote();
4918 if (parent != nullptr) {
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -07004919 List<PhysicalCameraSettings>::iterator it;
4920 for (it = captureRequest->mSettingsList.begin();
4921 it != captureRequest->mSettingsList.end(); it++) {
Jayant Chowdhary9255ce02021-07-15 11:18:17 -07004922 if (parent->mUHRCropAndMeteringRegionMappers.find(it->cameraId) ==
4923 parent->mUHRCropAndMeteringRegionMappers.end()) {
Jayant Chowdhary65c9bf02021-09-03 16:44:16 +00004924 if (removeFwkOnlyRegionKeys(&(it->metadata)) != OK) {
4925 SET_ERR("RequestThread: Unable to remove fwk-only keys from request"
4926 "%d: %s (%d)", halRequest->frame_number, strerror(-res),
4927 res);
4928 return INVALID_OPERATION;
4929 }
Jayant Chowdhary9255ce02021-07-15 11:18:17 -07004930 continue;
4931 }
4932
4933 if (!captureRequest->mUHRCropAndMeteringRegionsUpdated) {
4934 res = parent->mUHRCropAndMeteringRegionMappers[it->cameraId].
4935 updateCaptureRequest(&(it->metadata));
4936 if (res != OK) {
4937 SET_ERR("RequestThread: Unable to correct capture requests "
4938 "for scaler crop region and metering regions for request "
4939 "%d: %s (%d)", halRequest->frame_number, strerror(-res),
4940 res);
4941 return INVALID_OPERATION;
4942 }
4943 captureRequest->mUHRCropAndMeteringRegionsUpdated = true;
Jayant Chowdhary65c9bf02021-09-03 16:44:16 +00004944 if (removeFwkOnlyRegionKeys(&(it->metadata)) != OK) {
4945 SET_ERR("RequestThread: Unable to remove fwk-only keys from request"
4946 "%d: %s (%d)", halRequest->frame_number, strerror(-res),
4947 res);
4948 return INVALID_OPERATION;
4949 }
Jayant Chowdhary9255ce02021-07-15 11:18:17 -07004950 }
4951 }
4952
4953 // Correct metadata regions for distortion correction if enabled
4954 for (it = captureRequest->mSettingsList.begin();
4955 it != captureRequest->mSettingsList.end(); it++) {
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -07004956 if (parent->mDistortionMappers.find(it->cameraId) ==
4957 parent->mDistortionMappers.end()) {
4958 continue;
4959 }
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07004960
4961 if (!captureRequest->mDistortionCorrectionUpdated) {
4962 res = parent->mDistortionMappers[it->cameraId].correctCaptureRequest(
4963 &(it->metadata));
4964 if (res != OK) {
4965 SET_ERR("RequestThread: Unable to correct capture requests "
4966 "for lens distortion for request %d: %s (%d)",
4967 halRequest->frame_number, strerror(-res), res);
4968 return INVALID_OPERATION;
4969 }
4970 captureRequest->mDistortionCorrectionUpdated = true;
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -07004971 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07004972 }
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08004973
4974 for (it = captureRequest->mSettingsList.begin();
4975 it != captureRequest->mSettingsList.end(); it++) {
4976 if (parent->mZoomRatioMappers.find(it->cameraId) ==
4977 parent->mZoomRatioMappers.end()) {
4978 continue;
4979 }
4980
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07004981 if (!captureRequest->mZoomRatioIs1x) {
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08004982 cameraIdsWithZoom.insert(it->cameraId);
4983 }
4984
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07004985 if (!captureRequest->mZoomRatioUpdated) {
4986 res = parent->mZoomRatioMappers[it->cameraId].updateCaptureRequest(
4987 &(it->metadata));
4988 if (res != OK) {
4989 SET_ERR("RequestThread: Unable to correct capture requests "
4990 "for zoom ratio for request %d: %s (%d)",
4991 halRequest->frame_number, strerror(-res), res);
4992 return INVALID_OPERATION;
4993 }
4994 captureRequest->mZoomRatioUpdated = true;
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08004995 }
4996 }
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07004997 if (captureRequest->mRotateAndCropAuto &&
4998 !captureRequest->mRotationAndCropUpdated) {
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004999 for (it = captureRequest->mSettingsList.begin();
5000 it != captureRequest->mSettingsList.end(); it++) {
5001 auto mapper = parent->mRotateAndCropMappers.find(it->cameraId);
5002 if (mapper != parent->mRotateAndCropMappers.end()) {
5003 res = mapper->second.updateCaptureRequest(&(it->metadata));
5004 if (res != OK) {
5005 SET_ERR("RequestThread: Unable to correct capture requests "
5006 "for rotate-and-crop for request %d: %s (%d)",
5007 halRequest->frame_number, strerror(-res), res);
5008 return INVALID_OPERATION;
5009 }
5010 }
5011 }
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07005012 captureRequest->mRotationAndCropUpdated = true;
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005013 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07005014 }
5015 }
5016
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005017 /**
5018 * The request should be presorted so accesses in HAL
5019 * are O(logn). Sidenote, sorting a sorted metadata is nop.
5020 */
Emilian Peevaebbe412018-01-15 13:53:24 +00005021 captureRequest->mSettingsList.begin()->metadata.sort();
5022 halRequest->settings = captureRequest->mSettingsList.begin()->metadata.getAndLock();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005023 mPrevRequest = captureRequest;
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08005024 mPrevCameraIdsWithZoom = cameraIdsWithZoom;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005025 ALOGVV("%s: Request settings are NEW", __FUNCTION__);
5026
5027 IF_ALOGV() {
5028 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
5029 find_camera_metadata_ro_entry(
5030 halRequest->settings,
5031 ANDROID_CONTROL_AF_TRIGGER,
5032 &e
5033 );
5034 if (e.count > 0) {
5035 ALOGV("%s: Request (frame num %d) had AF trigger 0x%x",
5036 __FUNCTION__,
5037 halRequest->frame_number,
5038 e.data.u8[0]);
5039 }
5040 }
5041 } else {
5042 // leave request.settings NULL to indicate 'reuse latest given'
5043 ALOGVV("%s: Request settings are REUSED",
5044 __FUNCTION__);
5045 }
5046
Emilian Peevaebbe412018-01-15 13:53:24 +00005047 if (captureRequest->mSettingsList.size() > 1) {
5048 halRequest->num_physcam_settings = captureRequest->mSettingsList.size() - 1;
5049 halRequest->physcam_id = new const char* [halRequest->num_physcam_settings];
Emilian Peev00420d22018-02-05 21:33:13 +00005050 if (newRequest) {
5051 halRequest->physcam_settings =
5052 new const camera_metadata* [halRequest->num_physcam_settings];
5053 } else {
5054 halRequest->physcam_settings = nullptr;
5055 }
Emilian Peevaebbe412018-01-15 13:53:24 +00005056 auto it = ++captureRequest->mSettingsList.begin();
5057 size_t i = 0;
5058 for (; it != captureRequest->mSettingsList.end(); it++, i++) {
5059 halRequest->physcam_id[i] = it->cameraId.c_str();
Emilian Peev00420d22018-02-05 21:33:13 +00005060 if (newRequest) {
5061 it->metadata.sort();
5062 halRequest->physcam_settings[i] = it->metadata.getAndLock();
5063 }
Emilian Peevaebbe412018-01-15 13:53:24 +00005064 }
5065 }
5066
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005067 uint32_t totalNumBuffers = 0;
5068
5069 // Fill in buffers
5070 if (captureRequest->mInputStream != NULL) {
5071 halRequest->input_buffer = &captureRequest->mInputBuffer;
Shuzhen Wang83bff122020-11-20 15:51:39 -08005072
5073 halRequest->input_width = captureRequest->mInputBufferSize.width;
5074 halRequest->input_height = captureRequest->mInputBufferSize.height;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005075 totalNumBuffers += 1;
5076 } else {
5077 halRequest->input_buffer = NULL;
5078 }
5079
Emilian Peevf4816702020-04-03 15:44:51 -07005080 outputBuffers->insertAt(camera_stream_buffer_t(), 0,
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005081 captureRequest->mOutputStreams.size());
5082 halRequest->output_buffers = outputBuffers->array();
Shuzhen Wang99080502021-03-07 21:08:20 -08005083 std::set<std::set<String8>> requestedPhysicalCameras;
Yin-Chia Yehb3a80b12018-09-04 12:13:05 -07005084
5085 sp<Camera3Device> parent = mParent.promote();
5086 if (parent == NULL) {
5087 // Should not happen, and nowhere to send errors to, so just log it
5088 CLOGE("RequestThread: Parent is gone");
5089 return INVALID_OPERATION;
5090 }
5091 nsecs_t waitDuration = kBaseGetBufferWait + parent->getExpectedInFlightDuration();
5092
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005093 SurfaceMap uniqueSurfaceIdMap;
Shuzhen Wang4a472662017-02-26 23:29:04 -08005094 for (size_t j = 0; j < captureRequest->mOutputStreams.size(); j++) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005095 sp<Camera3OutputStreamInterface> outputStream =
5096 captureRequest->mOutputStreams.editItemAt(j);
5097 int streamId = outputStream->getId();
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07005098
5099 // Prepare video buffers for high speed recording on the first video request.
5100 if (mPrepareVideoStream && outputStream->isVideoStream()) {
5101 // Only try to prepare video stream on the first video request.
5102 mPrepareVideoStream = false;
5103
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07005104 res = outputStream->startPrepare(Camera3StreamInterface::ALLOCATE_PIPELINE_MAX,
5105 false /*blockRequest*/);
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07005106 while (res == NOT_ENOUGH_DATA) {
5107 res = outputStream->prepareNextBuffer();
5108 }
5109 if (res != OK) {
5110 ALOGW("%s: Preparing video buffers for high speed failed: %s (%d)",
5111 __FUNCTION__, strerror(-res), res);
5112 outputStream->cancelPrepare();
5113 }
5114 }
5115
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005116 std::vector<size_t> uniqueSurfaceIds;
5117 res = outputStream->getUniqueSurfaceIds(
5118 captureRequest->mOutputSurfaces[streamId],
5119 &uniqueSurfaceIds);
5120 // INVALID_OPERATION is normal output for streams not supporting surfaceIds
5121 if (res != OK && res != INVALID_OPERATION) {
5122 ALOGE("%s: failed to query stream %d unique surface IDs",
5123 __FUNCTION__, streamId);
5124 return res;
5125 }
5126 if (res == OK) {
5127 uniqueSurfaceIdMap.insert({streamId, std::move(uniqueSurfaceIds)});
5128 }
5129
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07005130 if (mUseHalBufManager) {
Yin-Chia Yeh110342b2018-11-19 11:47:46 -08005131 if (outputStream->isAbandoned()) {
Yin-Chia Yeha1b56c82019-03-27 15:50:39 -07005132 ALOGV("%s: stream %d is abandoned, skipping request", __FUNCTION__, streamId);
Yin-Chia Yeh110342b2018-11-19 11:47:46 -08005133 return TIMED_OUT;
5134 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07005135 // HAL will request buffer through requestStreamBuffer API
Emilian Peevf4816702020-04-03 15:44:51 -07005136 camera_stream_buffer_t& buffer = outputBuffers->editItemAt(j);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07005137 buffer.stream = outputStream->asHalStream();
5138 buffer.buffer = nullptr;
Emilian Peevf4816702020-04-03 15:44:51 -07005139 buffer.status = CAMERA_BUFFER_STATUS_OK;
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07005140 buffer.acquire_fence = -1;
5141 buffer.release_fence = -1;
Emilian Peevf0348ae2021-01-13 13:39:45 -08005142 // Mark the output stream as unpreparable to block clients from calling
5143 // 'prepare' after this request reaches CameraHal and before the respective
5144 // buffers are requested.
5145 outputStream->markUnpreparable();
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07005146 } else {
5147 res = outputStream->getBuffer(&outputBuffers->editItemAt(j),
5148 waitDuration,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005149 captureRequest->mOutputSurfaces[streamId]);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07005150 if (res != OK) {
5151 // Can't get output buffer from gralloc queue - this could be due to
5152 // abandoned queue or other consumer misbehavior, so not a fatal
5153 // error
Yin-Chia Yeha1b56c82019-03-27 15:50:39 -07005154 ALOGV("RequestThread: Can't get output buffer, skipping request:"
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07005155 " %s (%d)", strerror(-res), res);
5156
5157 return TIMED_OUT;
5158 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005159 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08005160
5161 {
5162 sp<Camera3Device> parent = mParent.promote();
5163 if (parent != nullptr) {
5164 const String8& streamCameraId = outputStream->getPhysicalCameraId();
5165 for (const auto& settings : captureRequest->mSettingsList) {
5166 if ((streamCameraId.isEmpty() &&
5167 parent->getId() == settings.cameraId.c_str()) ||
5168 streamCameraId == settings.cameraId.c_str()) {
5169 outputStream->fireBufferRequestForFrameNumber(
5170 captureRequest->mResultExtras.frameNumber,
5171 settings.metadata);
5172 }
5173 }
5174 }
5175 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07005176
Shuzhen Wang5c22c152017-12-31 17:12:25 -08005177 String8 physicalCameraId = outputStream->getPhysicalCameraId();
Shuzhen Wang99080502021-03-07 21:08:20 -08005178 int32_t streamGroupId = outputStream->getHalStreamGroupId();
5179 if (streamGroupId != -1 && mGroupIdPhysicalCameraMap.count(streamGroupId) == 1) {
5180 requestedPhysicalCameras.insert(mGroupIdPhysicalCameraMap[streamGroupId]);
5181 } else if (!physicalCameraId.isEmpty()) {
5182 requestedPhysicalCameras.insert(std::set<String8>({physicalCameraId}));
Shuzhen Wang5c22c152017-12-31 17:12:25 -08005183 }
5184 halRequest->num_output_buffers++;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005185 }
5186 totalNumBuffers += halRequest->num_output_buffers;
5187
5188 // Log request in the in-flight queue
Shuzhen Wang4a472662017-02-26 23:29:04 -08005189 // If this request list is for constrained high speed recording (not
5190 // preview), and the current request is not the last one in the batch,
5191 // do not send callback to the app.
5192 bool hasCallback = true;
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07005193 if (batchedRequest && i != mNextRequests.size()-1) {
Shuzhen Wang4a472662017-02-26 23:29:04 -08005194 hasCallback = false;
5195 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01005196 bool isStillCapture = false;
Shuzhen Wang26abaf42018-08-28 15:41:20 -07005197 bool isZslCapture = false;
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08005198 const camera_metadata_t* settings = halRequest->settings;
5199 bool shouldUnlockSettings = false;
5200 if (settings == nullptr) {
5201 shouldUnlockSettings = true;
5202 settings = captureRequest->mSettingsList.begin()->metadata.getAndLock();
5203 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01005204 if (!mNextRequests[0].captureRequest->mSettingsList.begin()->metadata.isEmpty()) {
5205 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08005206 find_camera_metadata_ro_entry(settings, ANDROID_CONTROL_CAPTURE_INTENT, &e);
Emilian Peev9dd21f42018-08-03 13:39:29 +01005207 if ((e.count > 0) && (e.data.u8[0] == ANDROID_CONTROL_CAPTURE_INTENT_STILL_CAPTURE)) {
5208 isStillCapture = true;
5209 ATRACE_ASYNC_BEGIN("still capture", mNextRequests[i].halRequest.frame_number);
5210 }
Shuzhen Wang26abaf42018-08-28 15:41:20 -07005211
Emilian Peevaf8416e2021-02-04 17:52:43 -08005212 e = camera_metadata_ro_entry_t();
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08005213 find_camera_metadata_ro_entry(settings, ANDROID_CONTROL_ENABLE_ZSL, &e);
Shuzhen Wang26abaf42018-08-28 15:41:20 -07005214 if ((e.count > 0) && (e.data.u8[0] == ANDROID_CONTROL_ENABLE_ZSL_TRUE)) {
5215 isZslCapture = true;
5216 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01005217 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005218 res = parent->registerInFlight(halRequest->frame_number,
5219 totalNumBuffers, captureRequest->mResultExtras,
5220 /*hasInput*/halRequest->input_buffer != NULL,
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07005221 hasCallback,
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08005222 calculateMaxExpectedDuration(settings),
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005223 requestedPhysicalCameras, isStillCapture, isZslCapture,
5224 captureRequest->mRotateAndCropAuto, mPrevCameraIdsWithZoom,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005225 (mUseHalBufManager) ? uniqueSurfaceIdMap :
Shuzhen Wang316781a2020-08-18 18:11:01 -07005226 SurfaceMap{}, captureRequest->mRequestTimeNs);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005227 ALOGVV("%s: registered in flight requestId = %" PRId32 ", frameNumber = %" PRId64
5228 ", burstId = %" PRId32 ".",
5229 __FUNCTION__,
5230 captureRequest->mResultExtras.requestId, captureRequest->mResultExtras.frameNumber,
5231 captureRequest->mResultExtras.burstId);
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08005232
5233 if (shouldUnlockSettings) {
5234 captureRequest->mSettingsList.begin()->metadata.unlock(settings);
5235 }
5236
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005237 if (res != OK) {
5238 SET_ERR("RequestThread: Unable to register new in-flight request:"
5239 " %s (%d)", strerror(-res), res);
5240 return INVALID_OPERATION;
5241 }
5242 }
5243
5244 return OK;
5245}
5246
Igor Murashkin1e479c02013-09-06 16:55:14 -07005247CameraMetadata Camera3Device::RequestThread::getLatestRequest() const {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005248 ATRACE_CALL();
Igor Murashkin1e479c02013-09-06 16:55:14 -07005249 Mutex::Autolock al(mLatestRequestMutex);
5250
5251 ALOGV("RequestThread::%s", __FUNCTION__);
5252
5253 return mLatestRequest;
5254}
5255
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005256bool Camera3Device::RequestThread::isStreamPending(
5257 sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005258 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005259 Mutex::Autolock l(mRequestLock);
5260
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005261 for (const auto& nextRequest : mNextRequests) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005262 if (!nextRequest.submitted) {
5263 for (const auto& s : nextRequest.captureRequest->mOutputStreams) {
5264 if (stream == s) return true;
5265 }
5266 if (stream == nextRequest.captureRequest->mInputStream) return true;
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07005267 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07005268 }
5269
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005270 for (const auto& request : mRequestQueue) {
5271 for (const auto& s : request->mOutputStreams) {
5272 if (stream == s) return true;
5273 }
5274 if (stream == request->mInputStream) return true;
5275 }
5276
5277 for (const auto& request : mRepeatingRequests) {
5278 for (const auto& s : request->mOutputStreams) {
5279 if (stream == s) return true;
5280 }
5281 if (stream == request->mInputStream) return true;
5282 }
5283
5284 return false;
5285}
Jianing Weicb0652e2014-03-12 18:29:36 -07005286
Emilian Peev40ead602017-09-26 15:46:36 +01005287bool Camera3Device::RequestThread::isOutputSurfacePending(int streamId, size_t surfaceId) {
5288 ATRACE_CALL();
5289 Mutex::Autolock l(mRequestLock);
5290
5291 for (const auto& nextRequest : mNextRequests) {
5292 for (const auto& s : nextRequest.captureRequest->mOutputSurfaces) {
5293 if (s.first == streamId) {
5294 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
5295 if (it != s.second.end()) {
5296 return true;
5297 }
5298 }
5299 }
5300 }
5301
5302 for (const auto& request : mRequestQueue) {
5303 for (const auto& s : request->mOutputSurfaces) {
5304 if (s.first == streamId) {
5305 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
5306 if (it != s.second.end()) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005307 return true;
Emilian Peev40ead602017-09-26 15:46:36 +01005308 }
5309 }
5310 }
5311 }
5312
5313 for (const auto& request : mRepeatingRequests) {
5314 for (const auto& s : request->mOutputSurfaces) {
5315 if (s.first == streamId) {
5316 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
5317 if (it != s.second.end()) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005318 return true;
Emilian Peev40ead602017-09-26 15:46:36 +01005319 }
5320 }
5321 }
5322 }
5323
5324 return false;
5325}
5326
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07005327void Camera3Device::RequestThread::signalPipelineDrain(const std::vector<int>& streamIds) {
5328 if (!mUseHalBufManager) {
5329 ALOGE("%s called for camera device not supporting HAL buffer management", __FUNCTION__);
5330 return;
5331 }
5332
5333 Mutex::Autolock pl(mPauseLock);
5334 if (mPaused) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005335 mInterface->signalPipelineDrain(streamIds);
5336 return;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07005337 }
5338 // If request thread is still busy, wait until paused then notify HAL
5339 mNotifyPipelineDrain = true;
5340 mStreamIdsToBeDrained = streamIds;
5341}
5342
Yin-Chia Yehe52b8fa2020-07-28 00:17:58 -07005343void Camera3Device::RequestThread::resetPipelineDrain() {
5344 Mutex::Autolock pl(mPauseLock);
5345 mNotifyPipelineDrain = false;
5346 mStreamIdsToBeDrained.clear();
5347}
5348
Emilian Peevc0fe54c2020-03-11 14:05:07 -07005349void Camera3Device::RequestThread::clearPreviousRequest() {
5350 Mutex::Autolock l(mRequestLock);
5351 mPrevRequest.clear();
5352}
5353
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005354status_t Camera3Device::RequestThread::switchToOffline(
5355 const std::vector<int32_t>& streamsToKeep,
5356 /*out*/hardware::camera::device::V3_6::CameraOfflineSessionInfo* offlineSessionInfo,
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005357 /*out*/sp<hardware::camera::device::V3_6::ICameraOfflineSession>* offlineSession,
5358 /*out*/camera3::BufferRecords* bufferRecords) {
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005359 Mutex::Autolock l(mRequestLock);
5360 clearRepeatingRequestsLocked(/*lastFrameNumber*/nullptr);
5361
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005362 // Wait until request thread is fully stopped
5363 // TBD: check if request thread is being paused by other APIs (shouldn't be)
5364
5365 // We could also check for mRepeatingRequests.empty(), but the API interface
5366 // is serialized by Camera3Device::mInterfaceLock so no one should be able to submit any
5367 // new requests during the call; hence skip that check.
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005368 bool queueEmpty = mNextRequests.empty() && mRequestQueue.empty();
5369 while (!queueEmpty) {
5370 status_t res = mRequestSubmittedSignal.waitRelative(mRequestLock, kRequestSubmitTimeout);
5371 if (res == TIMED_OUT) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005372 ALOGE("%s: request thread failed to submit one request within timeout!", __FUNCTION__);
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005373 return res;
5374 } else if (res != OK) {
5375 ALOGE("%s: request thread failed to submit a request: %s (%d)!",
5376 __FUNCTION__, strerror(-res), res);
5377 return res;
5378 }
5379 queueEmpty = mNextRequests.empty() && mRequestQueue.empty();
5380 }
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005381
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005382 return mInterface->switchToOffline(
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005383 streamsToKeep, offlineSessionInfo, offlineSession, bufferRecords);
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005384}
5385
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005386status_t Camera3Device::RequestThread::setRotateAndCropAutoBehavior(
5387 camera_metadata_enum_android_scaler_rotate_and_crop_t rotateAndCropValue) {
5388 ATRACE_CALL();
5389 Mutex::Autolock l(mTriggerMutex);
5390 if (rotateAndCropValue == ANDROID_SCALER_ROTATE_AND_CROP_AUTO) {
5391 return BAD_VALUE;
5392 }
5393 mRotateAndCropOverride = rotateAndCropValue;
5394 return OK;
5395}
5396
Emilian Peeve23f1d92021-09-20 14:56:01 -07005397status_t Camera3Device::RequestThread::setComposerSurface(bool composerSurfacePresent) {
5398 ATRACE_CALL();
5399 Mutex::Autolock l(mTriggerMutex);
5400 mComposerOutput = composerSurfacePresent;
5401 return OK;
5402}
5403
Eino-Ville Talvala11afe4f2021-05-27 14:45:31 -07005404status_t Camera3Device::RequestThread::setCameraMute(int32_t muteMode) {
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005405 ATRACE_CALL();
5406 Mutex::Autolock l(mTriggerMutex);
Eino-Ville Talvala11afe4f2021-05-27 14:45:31 -07005407 if (muteMode != mCameraMute) {
5408 mCameraMute = muteMode;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005409 mCameraMuteChanged = true;
5410 }
5411 return OK;
5412}
5413
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07005414nsecs_t Camera3Device::getExpectedInFlightDuration() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005415 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005416 std::lock_guard<std::mutex> l(mInFlightLock);
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07005417 return mExpectedInflightDuration > kMinInflightDuration ?
5418 mExpectedInflightDuration : kMinInflightDuration;
5419}
5420
Emilian Peevaebbe412018-01-15 13:53:24 +00005421void Camera3Device::RequestThread::cleanupPhysicalSettings(sp<CaptureRequest> request,
Emilian Peevf4816702020-04-03 15:44:51 -07005422 camera_capture_request_t *halRequest) {
Emilian Peevaebbe412018-01-15 13:53:24 +00005423 if ((request == nullptr) || (halRequest == nullptr)) {
5424 ALOGE("%s: Invalid request!", __FUNCTION__);
5425 return;
5426 }
5427
5428 if (halRequest->num_physcam_settings > 0) {
5429 if (halRequest->physcam_id != nullptr) {
5430 delete [] halRequest->physcam_id;
5431 halRequest->physcam_id = nullptr;
5432 }
5433 if (halRequest->physcam_settings != nullptr) {
5434 auto it = ++(request->mSettingsList.begin());
5435 size_t i = 0;
5436 for (; it != request->mSettingsList.end(); it++, i++) {
5437 it->metadata.unlock(halRequest->physcam_settings[i]);
5438 }
5439 delete [] halRequest->physcam_settings;
5440 halRequest->physcam_settings = nullptr;
5441 }
5442 }
5443}
5444
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005445void Camera3Device::RequestThread::cleanUpFailedRequests(bool sendRequestError) {
5446 if (mNextRequests.empty()) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005447 return;
5448 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005449
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005450 for (auto& nextRequest : mNextRequests) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005451 // Skip the ones that have been submitted successfully.
5452 if (nextRequest.submitted) {
5453 continue;
5454 }
5455
5456 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
Emilian Peevf4816702020-04-03 15:44:51 -07005457 camera_capture_request_t* halRequest = &nextRequest.halRequest;
5458 Vector<camera_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005459
5460 if (halRequest->settings != NULL) {
Emilian Peevaebbe412018-01-15 13:53:24 +00005461 captureRequest->mSettingsList.begin()->metadata.unlock(halRequest->settings);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005462 }
5463
Emilian Peevaebbe412018-01-15 13:53:24 +00005464 cleanupPhysicalSettings(captureRequest, halRequest);
5465
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005466 if (captureRequest->mInputStream != NULL) {
Emilian Peevf4816702020-04-03 15:44:51 -07005467 captureRequest->mInputBuffer.status = CAMERA_BUFFER_STATUS_ERROR;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005468 captureRequest->mInputStream->returnInputBuffer(captureRequest->mInputBuffer);
5469 }
5470
Yin-Chia Yeh21cb47b2019-01-18 15:08:17 -08005471 // No output buffer can be returned when using HAL buffer manager
5472 if (!mUseHalBufManager) {
5473 for (size_t i = 0; i < halRequest->num_output_buffers; i++) {
5474 //Buffers that failed processing could still have
5475 //valid acquire fence.
5476 int acquireFence = (*outputBuffers)[i].acquire_fence;
5477 if (0 <= acquireFence) {
5478 close(acquireFence);
5479 outputBuffers->editItemAt(i).acquire_fence = -1;
5480 }
Emilian Peevf4816702020-04-03 15:44:51 -07005481 outputBuffers->editItemAt(i).status = CAMERA_BUFFER_STATUS_ERROR;
Shuzhen Wang90708ea2021-11-04 11:40:49 -07005482 captureRequest->mOutputStreams.editItemAt(i)->returnBuffer((*outputBuffers)[i],
5483 /*timestamp*/0, /*readoutTimestamp*/0,
Yin-Chia Yeh21cb47b2019-01-18 15:08:17 -08005484 /*timestampIncreasing*/true, std::vector<size_t> (),
5485 captureRequest->mResultExtras.frameNumber);
Emilian Peevc58cf4c2017-05-11 17:23:41 +01005486 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005487 }
5488
5489 if (sendRequestError) {
5490 Mutex::Autolock l(mRequestLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005491 sp<NotificationListener> listener = mListener.promote();
5492 if (listener != NULL) {
5493 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08005494 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005495 captureRequest->mResultExtras);
5496 }
5497 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07005498
5499 // Remove yet-to-be submitted inflight request from inflightMap
5500 {
5501 sp<Camera3Device> parent = mParent.promote();
5502 if (parent != NULL) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005503 std::lock_guard<std::mutex> l(parent->mInFlightLock);
Shuzhen Wangcadb3302016-11-04 14:17:56 -07005504 ssize_t idx = parent->mInFlightMap.indexOfKey(captureRequest->mResultExtras.frameNumber);
5505 if (idx >= 0) {
5506 ALOGV("%s: Remove inflight request from queue: frameNumber %" PRId64,
5507 __FUNCTION__, captureRequest->mResultExtras.frameNumber);
5508 parent->removeInFlightMapEntryLocked(idx);
5509 }
5510 }
5511 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005512 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07005513
5514 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005515 mNextRequests.clear();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005516}
5517
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005518void Camera3Device::RequestThread::waitForNextRequestBatch() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005519 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005520 // Optimized a bit for the simple steady-state case (single repeating
5521 // request), to avoid putting that request in the queue temporarily.
5522 Mutex::Autolock l(mRequestLock);
5523
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005524 assert(mNextRequests.empty());
5525
5526 NextRequest nextRequest;
5527 nextRequest.captureRequest = waitForNextRequestLocked();
5528 if (nextRequest.captureRequest == nullptr) {
5529 return;
5530 }
5531
Emilian Peevf4816702020-04-03 15:44:51 -07005532 nextRequest.halRequest = camera_capture_request_t();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005533 nextRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005534 mNextRequests.add(nextRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005535
5536 // Wait for additional requests
5537 const size_t batchSize = nextRequest.captureRequest->mBatchSize;
5538
5539 for (size_t i = 1; i < batchSize; i++) {
5540 NextRequest additionalRequest;
5541 additionalRequest.captureRequest = waitForNextRequestLocked();
5542 if (additionalRequest.captureRequest == nullptr) {
5543 break;
5544 }
5545
Emilian Peevf4816702020-04-03 15:44:51 -07005546 additionalRequest.halRequest = camera_capture_request_t();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005547 additionalRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005548 mNextRequests.add(additionalRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005549 }
5550
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005551 if (mNextRequests.size() < batchSize) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08005552 ALOGE("RequestThread: only get %zu out of %zu requests. Skipping requests.",
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005553 mNextRequests.size(), batchSize);
5554 cleanUpFailedRequests(/*sendRequestError*/true);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005555 }
5556
5557 return;
5558}
5559
5560sp<Camera3Device::CaptureRequest>
5561 Camera3Device::RequestThread::waitForNextRequestLocked() {
5562 status_t res;
5563 sp<CaptureRequest> nextRequest;
5564
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005565 while (mRequestQueue.empty()) {
5566 if (!mRepeatingRequests.empty()) {
5567 // Always atomically enqueue all requests in a repeating request
5568 // list. Guarantees a complete in-sequence set of captures to
5569 // application.
5570 const RequestList &requests = mRepeatingRequests;
Shuzhen Wang316781a2020-08-18 18:11:01 -07005571 if (mFirstRepeating) {
5572 mFirstRepeating = false;
5573 } else {
5574 for (auto& request : requests) {
5575 // For repeating requests, override timestamp request using
5576 // the time a request is inserted into the request queue,
5577 // because the original repeating request will have an old
5578 // fixed timestamp.
5579 request->mRequestTimeNs = systemTime();
5580 }
5581 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005582 RequestList::const_iterator firstRequest =
5583 requests.begin();
5584 nextRequest = *firstRequest;
5585 mRequestQueue.insert(mRequestQueue.end(),
5586 ++firstRequest,
5587 requests.end());
5588 // No need to wait any longer
Jianing Weicb0652e2014-03-12 18:29:36 -07005589
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005590 mRepeatingLastFrameNumber = mFrameNumber + requests.size() - 1;
Jianing Weicb0652e2014-03-12 18:29:36 -07005591
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005592 break;
5593 }
5594
5595 res = mRequestSignal.waitRelative(mRequestLock, kRequestTimeout);
5596
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005597 if ((mRequestQueue.empty() && mRepeatingRequests.empty()) ||
5598 exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005599 Mutex::Autolock pl(mPauseLock);
5600 if (mPaused == false) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005601 ALOGV("%s: RequestThread: Going idle", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005602 mPaused = true;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07005603 if (mNotifyPipelineDrain) {
5604 mInterface->signalPipelineDrain(mStreamIdsToBeDrained);
5605 mNotifyPipelineDrain = false;
5606 mStreamIdsToBeDrained.clear();
5607 }
Yin-Chia Yehc300a072019-02-13 14:56:57 -08005608 // Let the tracker know
5609 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5610 if (statusTracker != 0) {
5611 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
5612 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005613 sp<Camera3Device> parent = mParent.promote();
5614 if (parent != nullptr) {
5615 parent->mRequestBufferSM.onRequestThreadPaused();
5616 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005617 }
5618 // Stop waiting for now and let thread management happen
5619 return NULL;
5620 }
5621 }
5622
5623 if (nextRequest == NULL) {
5624 // Don't have a repeating request already in hand, so queue
5625 // must have an entry now.
5626 RequestList::iterator firstRequest =
5627 mRequestQueue.begin();
5628 nextRequest = *firstRequest;
5629 mRequestQueue.erase(firstRequest);
Shuzhen Wang9d066012016-09-30 11:30:20 -07005630 if (mRequestQueue.empty() && !nextRequest->mRepeating) {
5631 sp<NotificationListener> listener = mListener.promote();
5632 if (listener != NULL) {
5633 listener->notifyRequestQueueEmpty();
5634 }
5635 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005636 }
5637
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005638 // In case we've been unpaused by setPaused clearing mDoPause, need to
5639 // update internal pause state (capture/setRepeatingRequest unpause
5640 // directly).
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005641 Mutex::Autolock pl(mPauseLock);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005642 if (mPaused) {
5643 ALOGV("%s: RequestThread: Unpaused", __FUNCTION__);
5644 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5645 if (statusTracker != 0) {
5646 statusTracker->markComponentActive(mStatusId);
5647 }
5648 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005649 mPaused = false;
5650
5651 // Check if we've reconfigured since last time, and reset the preview
5652 // request if so. Can't use 'NULL request == repeat' across configure calls.
5653 if (mReconfigured) {
5654 mPrevRequest.clear();
5655 mReconfigured = false;
5656 }
5657
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005658 if (nextRequest != NULL) {
5659 nextRequest->mResultExtras.frameNumber = mFrameNumber++;
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07005660 nextRequest->mResultExtras.afTriggerId = mCurrentAfTriggerId;
5661 nextRequest->mResultExtras.precaptureTriggerId = mCurrentPreCaptureTriggerId;
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07005662
5663 // Since RequestThread::clear() removes buffers from the input stream,
5664 // get the right buffer here before unlocking mRequestLock
5665 if (nextRequest->mInputStream != NULL) {
Shuzhen Wang83bff122020-11-20 15:51:39 -08005666 res = nextRequest->mInputStream->getInputBuffer(&nextRequest->mInputBuffer,
5667 &nextRequest->mInputBufferSize);
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07005668 if (res != OK) {
5669 // Can't get input buffer from gralloc queue - this could be due to
5670 // disconnected queue or other producer misbehavior, so not a fatal
5671 // error
5672 ALOGE("%s: Can't get input buffer, skipping request:"
5673 " %s (%d)", __FUNCTION__, strerror(-res), res);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005674
5675 sp<NotificationListener> listener = mListener.promote();
5676 if (listener != NULL) {
5677 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08005678 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07005679 nextRequest->mResultExtras);
5680 }
5681 return NULL;
5682 }
5683 }
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005684 }
Chien-Yu Chend196d612015-06-22 19:49:01 -07005685
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005686 return nextRequest;
5687}
5688
5689bool Camera3Device::RequestThread::waitIfPaused() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005690 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005691 status_t res;
5692 Mutex::Autolock l(mPauseLock);
5693 while (mDoPause) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005694 if (mPaused == false) {
5695 mPaused = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005696 ALOGV("%s: RequestThread: Paused", __FUNCTION__);
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07005697 if (mNotifyPipelineDrain) {
5698 mInterface->signalPipelineDrain(mStreamIdsToBeDrained);
5699 mNotifyPipelineDrain = false;
5700 mStreamIdsToBeDrained.clear();
5701 }
Yin-Chia Yehc300a072019-02-13 14:56:57 -08005702 // Let the tracker know
5703 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5704 if (statusTracker != 0) {
5705 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
5706 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005707 sp<Camera3Device> parent = mParent.promote();
5708 if (parent != nullptr) {
5709 parent->mRequestBufferSM.onRequestThreadPaused();
5710 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005711 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005712
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005713 res = mDoPauseSignal.waitRelative(mPauseLock, kRequestTimeout);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005714 if (res == TIMED_OUT || exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005715 return true;
5716 }
5717 }
5718 // We don't set mPaused to false here, because waitForNextRequest needs
5719 // to further manage the paused state in case of starvation.
5720 return false;
5721}
5722
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005723void Camera3Device::RequestThread::unpauseForNewRequests() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005724 ATRACE_CALL();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005725 // With work to do, mark thread as unpaused.
5726 // If paused by request (setPaused), don't resume, to avoid
5727 // extra signaling/waiting overhead to waitUntilPaused
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005728 mRequestSignal.signal();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005729 Mutex::Autolock p(mPauseLock);
5730 if (!mDoPause) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005731 ALOGV("%s: RequestThread: Going active", __FUNCTION__);
5732 if (mPaused) {
5733 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5734 if (statusTracker != 0) {
5735 statusTracker->markComponentActive(mStatusId);
5736 }
5737 }
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005738 mPaused = false;
5739 }
5740}
5741
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07005742void Camera3Device::RequestThread::setErrorState(const char *fmt, ...) {
5743 sp<Camera3Device> parent = mParent.promote();
5744 if (parent != NULL) {
5745 va_list args;
5746 va_start(args, fmt);
5747
5748 parent->setErrorStateV(fmt, args);
5749
5750 va_end(args);
5751 }
5752}
5753
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005754status_t Camera3Device::RequestThread::insertTriggers(
5755 const sp<CaptureRequest> &request) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005756 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005757 Mutex::Autolock al(mTriggerMutex);
5758
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07005759 sp<Camera3Device> parent = mParent.promote();
5760 if (parent == NULL) {
5761 CLOGE("RequestThread: Parent is gone");
5762 return DEAD_OBJECT;
5763 }
5764
Emilian Peevaebbe412018-01-15 13:53:24 +00005765 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005766 size_t count = mTriggerMap.size();
5767
5768 for (size_t i = 0; i < count; ++i) {
5769 RequestTrigger trigger = mTriggerMap.valueAt(i);
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005770 uint32_t tag = trigger.metadataTag;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07005771
5772 if (tag == ANDROID_CONTROL_AF_TRIGGER_ID || tag == ANDROID_CONTROL_AE_PRECAPTURE_ID) {
5773 bool isAeTrigger = (trigger.metadataTag == ANDROID_CONTROL_AE_PRECAPTURE_ID);
5774 uint32_t triggerId = static_cast<uint32_t>(trigger.entryValue);
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07005775 if (isAeTrigger) {
5776 request->mResultExtras.precaptureTriggerId = triggerId;
5777 mCurrentPreCaptureTriggerId = triggerId;
5778 } else {
5779 request->mResultExtras.afTriggerId = triggerId;
5780 mCurrentAfTriggerId = triggerId;
5781 }
Emilian Peev7e25e5e2017-04-07 15:48:49 +01005782 continue;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07005783 }
5784
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005785 camera_metadata_entry entry = metadata.find(tag);
5786
5787 if (entry.count > 0) {
5788 /**
5789 * Already has an entry for this trigger in the request.
5790 * Rewrite it with our requested trigger value.
5791 */
5792 RequestTrigger oldTrigger = trigger;
5793
5794 oldTrigger.entryValue = entry.data.u8[0];
5795
5796 mTriggerReplacedMap.add(tag, oldTrigger);
5797 } else {
5798 /**
5799 * More typical, no trigger entry, so we just add it
5800 */
5801 mTriggerRemovedMap.add(tag, trigger);
5802 }
5803
5804 status_t res;
5805
5806 switch (trigger.getTagType()) {
5807 case TYPE_BYTE: {
5808 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
5809 res = metadata.update(tag,
5810 &entryValue,
5811 /*count*/1);
5812 break;
5813 }
5814 case TYPE_INT32:
5815 res = metadata.update(tag,
5816 &trigger.entryValue,
5817 /*count*/1);
5818 break;
5819 default:
5820 ALOGE("%s: Type not supported: 0x%x",
5821 __FUNCTION__,
5822 trigger.getTagType());
5823 return INVALID_OPERATION;
5824 }
5825
5826 if (res != OK) {
5827 ALOGE("%s: Failed to update request metadata with trigger tag %s"
5828 ", value %d", __FUNCTION__, trigger.getTagName(),
5829 trigger.entryValue);
5830 return res;
5831 }
5832
5833 ALOGV("%s: Mixed in trigger %s, value %d", __FUNCTION__,
5834 trigger.getTagName(),
5835 trigger.entryValue);
5836 }
5837
5838 mTriggerMap.clear();
5839
5840 return count;
5841}
5842
5843status_t Camera3Device::RequestThread::removeTriggers(
5844 const sp<CaptureRequest> &request) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005845 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005846 Mutex::Autolock al(mTriggerMutex);
5847
Emilian Peevaebbe412018-01-15 13:53:24 +00005848 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005849
5850 /**
5851 * Replace all old entries with their old values.
5852 */
5853 for (size_t i = 0; i < mTriggerReplacedMap.size(); ++i) {
5854 RequestTrigger trigger = mTriggerReplacedMap.valueAt(i);
5855
5856 status_t res;
5857
5858 uint32_t tag = trigger.metadataTag;
5859 switch (trigger.getTagType()) {
5860 case TYPE_BYTE: {
5861 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
5862 res = metadata.update(tag,
5863 &entryValue,
5864 /*count*/1);
5865 break;
5866 }
5867 case TYPE_INT32:
5868 res = metadata.update(tag,
5869 &trigger.entryValue,
5870 /*count*/1);
5871 break;
5872 default:
5873 ALOGE("%s: Type not supported: 0x%x",
5874 __FUNCTION__,
5875 trigger.getTagType());
5876 return INVALID_OPERATION;
5877 }
5878
5879 if (res != OK) {
5880 ALOGE("%s: Failed to restore request metadata with trigger tag %s"
5881 ", trigger value %d", __FUNCTION__,
5882 trigger.getTagName(), trigger.entryValue);
5883 return res;
5884 }
5885 }
5886 mTriggerReplacedMap.clear();
5887
5888 /**
5889 * Remove all new entries.
5890 */
5891 for (size_t i = 0; i < mTriggerRemovedMap.size(); ++i) {
5892 RequestTrigger trigger = mTriggerRemovedMap.valueAt(i);
5893 status_t res = metadata.erase(trigger.metadataTag);
5894
5895 if (res != OK) {
5896 ALOGE("%s: Failed to erase metadata with trigger tag %s"
5897 ", trigger value %d", __FUNCTION__,
5898 trigger.getTagName(), trigger.entryValue);
5899 return res;
5900 }
5901 }
5902 mTriggerRemovedMap.clear();
5903
5904 return OK;
5905}
5906
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04005907status_t Camera3Device::RequestThread::addFakeTriggerIds(
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005908 const sp<CaptureRequest> &request) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08005909 // Trigger ID 0 had special meaning in the HAL2 spec, so avoid it here
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04005910 static const int32_t fakeTriggerId = 1;
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005911 status_t res;
5912
Emilian Peevaebbe412018-01-15 13:53:24 +00005913 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005914
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04005915 // If AF trigger is active, insert a fake AF trigger ID if none already
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005916 // exists
5917 camera_metadata_entry afTrigger = metadata.find(ANDROID_CONTROL_AF_TRIGGER);
5918 camera_metadata_entry afId = metadata.find(ANDROID_CONTROL_AF_TRIGGER_ID);
5919 if (afTrigger.count > 0 &&
5920 afTrigger.data.u8[0] != ANDROID_CONTROL_AF_TRIGGER_IDLE &&
5921 afId.count == 0) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04005922 res = metadata.update(ANDROID_CONTROL_AF_TRIGGER_ID, &fakeTriggerId, 1);
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005923 if (res != OK) return res;
5924 }
5925
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04005926 // If AE precapture trigger is active, insert a fake precapture trigger ID
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005927 // if none already exists
5928 camera_metadata_entry pcTrigger =
5929 metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER);
5930 camera_metadata_entry pcId = metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_ID);
5931 if (pcTrigger.count > 0 &&
5932 pcTrigger.data.u8[0] != ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_IDLE &&
5933 pcId.count == 0) {
5934 res = metadata.update(ANDROID_CONTROL_AE_PRECAPTURE_ID,
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04005935 &fakeTriggerId, 1);
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005936 if (res != OK) return res;
5937 }
5938
5939 return OK;
5940}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005941
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005942bool Camera3Device::RequestThread::overrideAutoRotateAndCrop(
5943 const sp<CaptureRequest> &request) {
5944 ATRACE_CALL();
5945
5946 if (request->mRotateAndCropAuto) {
5947 Mutex::Autolock l(mTriggerMutex);
5948 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
5949
5950 auto rotateAndCropEntry = metadata.find(ANDROID_SCALER_ROTATE_AND_CROP);
5951 if (rotateAndCropEntry.count > 0) {
5952 if (rotateAndCropEntry.data.u8[0] == mRotateAndCropOverride) {
5953 return false;
5954 } else {
5955 rotateAndCropEntry.data.u8[0] = mRotateAndCropOverride;
5956 return true;
5957 }
5958 } else {
5959 uint8_t rotateAndCrop_u8 = mRotateAndCropOverride;
5960 metadata.update(ANDROID_SCALER_ROTATE_AND_CROP,
5961 &rotateAndCrop_u8, 1);
5962 return true;
5963 }
5964 }
5965 return false;
5966}
5967
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005968bool Camera3Device::RequestThread::overrideTestPattern(
5969 const sp<CaptureRequest> &request) {
5970 ATRACE_CALL();
5971
Eino-Ville Talvala1646c3c2021-07-29 13:48:40 -07005972 if (!mSupportCameraMute) return false;
Eino-Ville Talvalac2459842021-07-22 16:36:36 -07005973
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005974 Mutex::Autolock l(mTriggerMutex);
5975
5976 bool changed = false;
5977
Shuzhen Wang911c6a32021-10-27 13:36:03 -07005978 // For a multi-camera, the physical cameras support the same set of
5979 // test pattern modes as the logical camera.
5980 for (auto& settings : request->mSettingsList) {
5981 CameraMetadata &metadata = settings.metadata;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005982
Shuzhen Wang911c6a32021-10-27 13:36:03 -07005983 int32_t testPatternMode = settings.mOriginalTestPatternMode;
5984 int32_t testPatternData[4] = {
5985 settings.mOriginalTestPatternData[0],
5986 settings.mOriginalTestPatternData[1],
5987 settings.mOriginalTestPatternData[2],
5988 settings.mOriginalTestPatternData[3]
5989 };
5990 if (mCameraMute != ANDROID_SENSOR_TEST_PATTERN_MODE_OFF) {
5991 testPatternMode = mCameraMute;
5992 testPatternData[0] = 0;
5993 testPatternData[1] = 0;
5994 testPatternData[2] = 0;
5995 testPatternData[3] = 0;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005996 }
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005997
Shuzhen Wang911c6a32021-10-27 13:36:03 -07005998 auto testPatternEntry = metadata.find(ANDROID_SENSOR_TEST_PATTERN_MODE);
5999 bool supportTestPatternModeKey = settings.mHasTestPatternModeTag;
6000 if (testPatternEntry.count > 0) {
6001 if (testPatternEntry.data.i32[0] != testPatternMode) {
6002 testPatternEntry.data.i32[0] = testPatternMode;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08006003 changed = true;
6004 }
Shuzhen Wang911c6a32021-10-27 13:36:03 -07006005 } else if (supportTestPatternModeKey) {
6006 metadata.update(ANDROID_SENSOR_TEST_PATTERN_MODE,
6007 &testPatternMode, 1);
6008 changed = true;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08006009 }
Shuzhen Wang911c6a32021-10-27 13:36:03 -07006010
6011 auto testPatternColor = metadata.find(ANDROID_SENSOR_TEST_PATTERN_DATA);
6012 bool supportTestPatternDataKey = settings.mHasTestPatternDataTag;
6013 if (testPatternColor.count >= 4) {
6014 for (size_t i = 0; i < 4; i++) {
6015 if (testPatternColor.data.i32[i] != testPatternData[i]) {
6016 testPatternColor.data.i32[i] = testPatternData[i];
6017 changed = true;
6018 }
6019 }
6020 } else if (supportTestPatternDataKey) {
6021 metadata.update(ANDROID_SENSOR_TEST_PATTERN_DATA,
6022 testPatternData, 4);
6023 changed = true;
6024 }
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08006025 }
6026
6027 return changed;
6028}
6029
Cliff Wuc2ad9c82021-04-21 00:58:58 +08006030status_t Camera3Device::RequestThread::setHalInterface(
6031 sp<HalInterface> newHalInterface) {
6032 if (newHalInterface.get() == nullptr) {
6033 ALOGE("%s: The newHalInterface does not exist!", __FUNCTION__);
6034 return DEAD_OBJECT;
6035 }
6036
6037 mInterface = newHalInterface;
6038
6039 return OK;
6040}
6041
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006042/**
6043 * PreparerThread inner class methods
6044 */
6045
6046Camera3Device::PreparerThread::PreparerThread() :
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07006047 Thread(/*canCallJava*/false), mListener(nullptr),
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006048 mActive(false), mCancelNow(false), mCurrentMaxCount(0), mCurrentPrepareComplete(false) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006049}
6050
6051Camera3Device::PreparerThread::~PreparerThread() {
6052 Thread::requestExitAndWait();
6053 if (mCurrentStream != nullptr) {
6054 mCurrentStream->cancelPrepare();
6055 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
6056 mCurrentStream.clear();
6057 }
6058 clear();
6059}
6060
Ruben Brunkc78ac262015-08-13 17:58:46 -07006061status_t Camera3Device::PreparerThread::prepare(int maxCount, sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07006062 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006063 status_t res;
6064
6065 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006066 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006067
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07006068 res = stream->startPrepare(maxCount, true /*blockRequest*/);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006069 if (res == OK) {
6070 // No preparation needed, fire listener right off
6071 ALOGV("%s: Stream %d already prepared", __FUNCTION__, stream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006072 if (listener != NULL) {
6073 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006074 }
6075 return OK;
6076 } else if (res != NOT_ENOUGH_DATA) {
6077 return res;
6078 }
6079
6080 // Need to prepare, start up thread if necessary
6081 if (!mActive) {
6082 // mRunning will change to false before the thread fully shuts down, so wait to be sure it
6083 // isn't running
6084 Thread::requestExitAndWait();
6085 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
6086 if (res != OK) {
6087 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__, res, strerror(-res));
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006088 if (listener != NULL) {
6089 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006090 }
6091 return res;
6092 }
6093 mCancelNow = false;
6094 mActive = true;
6095 ALOGV("%s: Preparer stream started", __FUNCTION__);
6096 }
6097
6098 // queue up the work
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006099 mPendingStreams.emplace(maxCount, stream);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006100 ALOGV("%s: Stream %d queued for preparing", __FUNCTION__, stream->getId());
6101
6102 return OK;
6103}
6104
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006105void Camera3Device::PreparerThread::pause() {
6106 ATRACE_CALL();
6107
6108 Mutex::Autolock l(mLock);
6109
6110 std::unordered_map<int, sp<camera3::Camera3StreamInterface> > pendingStreams;
6111 pendingStreams.insert(mPendingStreams.begin(), mPendingStreams.end());
6112 sp<camera3::Camera3StreamInterface> currentStream = mCurrentStream;
6113 int currentMaxCount = mCurrentMaxCount;
6114 mPendingStreams.clear();
6115 mCancelNow = true;
6116 while (mActive) {
6117 auto res = mThreadActiveSignal.waitRelative(mLock, kActiveTimeout);
6118 if (res == TIMED_OUT) {
6119 ALOGE("%s: Timed out waiting on prepare thread!", __FUNCTION__);
6120 return;
6121 } else if (res != OK) {
6122 ALOGE("%s: Encountered an error: %d waiting on prepare thread!", __FUNCTION__, res);
6123 return;
6124 }
6125 }
6126
6127 //Check whether the prepare thread was able to complete the current
6128 //stream. In case work is still pending emplace it along with the rest
6129 //of the streams in the pending list.
6130 if (currentStream != nullptr) {
6131 if (!mCurrentPrepareComplete) {
6132 pendingStreams.emplace(currentMaxCount, currentStream);
6133 }
6134 }
6135
6136 mPendingStreams.insert(pendingStreams.begin(), pendingStreams.end());
6137 for (const auto& it : mPendingStreams) {
6138 it.second->cancelPrepare();
6139 }
6140}
6141
6142status_t Camera3Device::PreparerThread::resume() {
6143 ATRACE_CALL();
6144 status_t res;
6145
6146 Mutex::Autolock l(mLock);
6147 sp<NotificationListener> listener = mListener.promote();
6148
6149 if (mActive) {
6150 ALOGE("%s: Trying to resume an already active prepare thread!", __FUNCTION__);
6151 return NO_INIT;
6152 }
6153
6154 auto it = mPendingStreams.begin();
6155 for (; it != mPendingStreams.end();) {
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07006156 res = it->second->startPrepare(it->first, true /*blockRequest*/);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006157 if (res == OK) {
6158 if (listener != NULL) {
6159 listener->notifyPrepared(it->second->getId());
6160 }
6161 it = mPendingStreams.erase(it);
6162 } else if (res != NOT_ENOUGH_DATA) {
6163 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__,
6164 res, strerror(-res));
6165 it = mPendingStreams.erase(it);
6166 } else {
6167 it++;
6168 }
6169 }
6170
6171 if (mPendingStreams.empty()) {
6172 return OK;
6173 }
6174
6175 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
6176 if (res != OK) {
6177 ALOGE("%s: Unable to start preparer stream: %d (%s)",
6178 __FUNCTION__, res, strerror(-res));
6179 return res;
6180 }
6181 mCancelNow = false;
6182 mActive = true;
6183 ALOGV("%s: Preparer stream started", __FUNCTION__);
6184
6185 return OK;
6186}
6187
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006188status_t Camera3Device::PreparerThread::clear() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07006189 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006190 Mutex::Autolock l(mLock);
6191
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006192 for (const auto& it : mPendingStreams) {
6193 it.second->cancelPrepare();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006194 }
6195 mPendingStreams.clear();
6196 mCancelNow = true;
6197
6198 return OK;
6199}
6200
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006201void Camera3Device::PreparerThread::setNotificationListener(wp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07006202 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006203 Mutex::Autolock l(mLock);
6204 mListener = listener;
6205}
6206
6207bool Camera3Device::PreparerThread::threadLoop() {
6208 status_t res;
6209 {
6210 Mutex::Autolock l(mLock);
6211 if (mCurrentStream == nullptr) {
6212 // End thread if done with work
6213 if (mPendingStreams.empty()) {
6214 ALOGV("%s: Preparer stream out of work", __FUNCTION__);
6215 // threadLoop _must not_ re-acquire mLock after it sets mActive to false; would
6216 // cause deadlock with prepare()'s requestExitAndWait triggered by !mActive.
6217 mActive = false;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006218 mThreadActiveSignal.signal();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006219 return false;
6220 }
6221
6222 // Get next stream to prepare
6223 auto it = mPendingStreams.begin();
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006224 mCurrentStream = it->second;
6225 mCurrentMaxCount = it->first;
6226 mCurrentPrepareComplete = false;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006227 mPendingStreams.erase(it);
6228 ATRACE_ASYNC_BEGIN("stream prepare", mCurrentStream->getId());
6229 ALOGV("%s: Preparing stream %d", __FUNCTION__, mCurrentStream->getId());
6230 } else if (mCancelNow) {
6231 mCurrentStream->cancelPrepare();
6232 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
6233 ALOGV("%s: Cancelling stream %d prepare", __FUNCTION__, mCurrentStream->getId());
6234 mCurrentStream.clear();
6235 mCancelNow = false;
6236 return true;
6237 }
6238 }
6239
6240 res = mCurrentStream->prepareNextBuffer();
6241 if (res == NOT_ENOUGH_DATA) return true;
6242 if (res != OK) {
6243 // Something bad happened; try to recover by cancelling prepare and
6244 // signalling listener anyway
6245 ALOGE("%s: Stream %d returned error %d (%s) during prepare", __FUNCTION__,
6246 mCurrentStream->getId(), res, strerror(-res));
6247 mCurrentStream->cancelPrepare();
6248 }
6249
6250 // This stream has finished, notify listener
6251 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006252 sp<NotificationListener> listener = mListener.promote();
6253 if (listener != NULL) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006254 ALOGV("%s: Stream %d prepare done, signaling listener", __FUNCTION__,
6255 mCurrentStream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006256 listener->notifyPrepared(mCurrentStream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006257 }
6258
6259 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
6260 mCurrentStream.clear();
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006261 mCurrentPrepareComplete = true;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006262
6263 return true;
6264}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07006265
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006266status_t Camera3Device::RequestBufferStateMachine::initialize(
6267 sp<camera3::StatusTracker> statusTracker) {
6268 if (statusTracker == nullptr) {
6269 ALOGE("%s: statusTracker is null", __FUNCTION__);
6270 return BAD_VALUE;
6271 }
6272
6273 std::lock_guard<std::mutex> lock(mLock);
6274 mStatusTracker = statusTracker;
Yin-Chia Yeh87b3ec02019-06-03 10:44:39 -07006275 mRequestBufferStatusId = statusTracker->addComponent("BufferRequestSM");
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006276 return OK;
6277}
6278
6279bool Camera3Device::RequestBufferStateMachine::startRequestBuffer() {
6280 std::lock_guard<std::mutex> lock(mLock);
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08006281 if (mStatus == RB_STATUS_READY || mStatus == RB_STATUS_PENDING_STOP) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006282 mRequestBufferOngoing = true;
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08006283 notifyTrackerLocked(/*active*/true);
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006284 return true;
6285 }
6286 return false;
6287}
6288
6289void Camera3Device::RequestBufferStateMachine::endRequestBuffer() {
6290 std::lock_guard<std::mutex> lock(mLock);
6291 if (!mRequestBufferOngoing) {
6292 ALOGE("%s called without a successful startRequestBuffer call first!", __FUNCTION__);
6293 return;
6294 }
6295 mRequestBufferOngoing = false;
6296 if (mStatus == RB_STATUS_PENDING_STOP) {
6297 checkSwitchToStopLocked();
6298 }
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08006299 notifyTrackerLocked(/*active*/false);
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006300}
6301
6302void Camera3Device::RequestBufferStateMachine::onStreamsConfigured() {
6303 std::lock_guard<std::mutex> lock(mLock);
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006304 mSwitchedToOffline = false;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006305 mStatus = RB_STATUS_READY;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006306 return;
6307}
6308
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08006309void Camera3Device::RequestBufferStateMachine::onSubmittingRequest() {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006310 std::lock_guard<std::mutex> lock(mLock);
6311 mRequestThreadPaused = false;
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08006312 // inflight map register actually happens in prepareHalRequest now, but it is close enough
6313 // approximation.
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006314 mInflightMapEmpty = false;
6315 if (mStatus == RB_STATUS_STOPPED) {
6316 mStatus = RB_STATUS_READY;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006317 }
6318 return;
6319}
6320
6321void Camera3Device::RequestBufferStateMachine::onRequestThreadPaused() {
6322 std::lock_guard<std::mutex> lock(mLock);
6323 mRequestThreadPaused = true;
6324 if (mStatus == RB_STATUS_PENDING_STOP) {
6325 checkSwitchToStopLocked();
6326 }
6327 return;
6328}
6329
6330void Camera3Device::RequestBufferStateMachine::onInflightMapEmpty() {
6331 std::lock_guard<std::mutex> lock(mLock);
6332 mInflightMapEmpty = true;
6333 if (mStatus == RB_STATUS_PENDING_STOP) {
6334 checkSwitchToStopLocked();
6335 }
6336 return;
6337}
6338
6339void Camera3Device::RequestBufferStateMachine::onWaitUntilIdle() {
6340 std::lock_guard<std::mutex> lock(mLock);
6341 if (!checkSwitchToStopLocked()) {
6342 mStatus = RB_STATUS_PENDING_STOP;
6343 }
6344 return;
6345}
6346
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006347bool Camera3Device::RequestBufferStateMachine::onSwitchToOfflineSuccess() {
6348 std::lock_guard<std::mutex> lock(mLock);
6349 if (mRequestBufferOngoing) {
6350 ALOGE("%s: HAL must not be requesting buffer after HAL returns switchToOffline!",
6351 __FUNCTION__);
6352 return false;
6353 }
6354 mSwitchedToOffline = true;
6355 mInflightMapEmpty = true;
6356 mRequestThreadPaused = true;
6357 mStatus = RB_STATUS_STOPPED;
6358 return true;
6359}
6360
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006361void Camera3Device::RequestBufferStateMachine::notifyTrackerLocked(bool active) {
6362 sp<StatusTracker> statusTracker = mStatusTracker.promote();
6363 if (statusTracker != nullptr) {
6364 if (active) {
6365 statusTracker->markComponentActive(mRequestBufferStatusId);
6366 } else {
6367 statusTracker->markComponentIdle(mRequestBufferStatusId, Fence::NO_FENCE);
6368 }
6369 }
6370}
6371
6372bool Camera3Device::RequestBufferStateMachine::checkSwitchToStopLocked() {
6373 if (mInflightMapEmpty && mRequestThreadPaused && !mRequestBufferOngoing) {
6374 mStatus = RB_STATUS_STOPPED;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006375 return true;
6376 }
6377 return false;
6378}
6379
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006380bool Camera3Device::startRequestBuffer() {
6381 return mRequestBufferSM.startRequestBuffer();
6382}
Shuzhen Wang268a1362018-10-16 16:32:59 -07006383
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006384void Camera3Device::endRequestBuffer() {
6385 mRequestBufferSM.endRequestBuffer();
6386}
Shuzhen Wang268a1362018-10-16 16:32:59 -07006387
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006388nsecs_t Camera3Device::getWaitDuration() {
6389 return kBaseGetBufferWait + getExpectedInFlightDuration();
6390}
Shuzhen Wang268a1362018-10-16 16:32:59 -07006391
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006392void Camera3Device::getInflightBufferKeys(std::vector<std::pair<int32_t, int32_t>>* out) {
6393 mInterface->getInflightBufferKeys(out);
6394}
Shuzhen Wang268a1362018-10-16 16:32:59 -07006395
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006396void Camera3Device::getInflightRequestBufferKeys(std::vector<uint64_t>* out) {
6397 mInterface->getInflightRequestBufferKeys(out);
6398}
Shuzhen Wang268a1362018-10-16 16:32:59 -07006399
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006400std::vector<sp<Camera3StreamInterface>> Camera3Device::getAllStreams() {
6401 std::vector<sp<Camera3StreamInterface>> ret;
6402 bool hasInputStream = mInputStream != nullptr;
6403 ret.reserve(mOutputStreams.size() + mDeletedStreams.size() + ((hasInputStream) ? 1 : 0));
6404 if (hasInputStream) {
6405 ret.push_back(mInputStream);
Shuzhen Wang268a1362018-10-16 16:32:59 -07006406 }
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006407 for (size_t i = 0; i < mOutputStreams.size(); i++) {
6408 ret.push_back(mOutputStreams[i]);
6409 }
6410 for (size_t i = 0; i < mDeletedStreams.size(); i++) {
6411 ret.push_back(mDeletedStreams[i]);
6412 }
6413 return ret;
Shuzhen Wang268a1362018-10-16 16:32:59 -07006414}
6415
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006416status_t Camera3Device::switchToOffline(
6417 const std::vector<int32_t>& streamsToKeep,
6418 /*out*/ sp<CameraOfflineSessionBase>* session) {
6419 ATRACE_CALL();
6420 if (session == nullptr) {
6421 ALOGE("%s: session must not be null", __FUNCTION__);
6422 return BAD_VALUE;
6423 }
6424
6425 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006426
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006427 bool hasInputStream = mInputStream != nullptr;
6428 int32_t inputStreamId = hasInputStream ? mInputStream->getId() : -1;
6429 bool inputStreamSupportsOffline = hasInputStream ?
6430 mInputStream->getOfflineProcessingSupport() : false;
6431 auto outputStreamIds = mOutputStreams.getStreamIds();
6432 auto streamIds = outputStreamIds;
6433 if (hasInputStream) {
6434 streamIds.push_back(mInputStream->getId());
6435 }
6436
6437 // Check all streams in streamsToKeep supports offline mode
6438 for (auto id : streamsToKeep) {
6439 if (std::find(streamIds.begin(), streamIds.end(), id) == streamIds.end()) {
6440 ALOGE("%s: Unknown stream ID %d", __FUNCTION__, id);
6441 return BAD_VALUE;
6442 } else if (id == inputStreamId) {
6443 if (!inputStreamSupportsOffline) {
6444 ALOGE("%s: input stream %d cannot be switched to offline",
6445 __FUNCTION__, id);
6446 return BAD_VALUE;
6447 }
6448 } else {
6449 sp<camera3::Camera3OutputStreamInterface> stream = mOutputStreams.get(id);
6450 if (!stream->getOfflineProcessingSupport()) {
6451 ALOGE("%s: output stream %d cannot be switched to offline",
6452 __FUNCTION__, id);
6453 return BAD_VALUE;
6454 }
6455 }
6456 }
6457
6458 // TODO: block surface sharing and surface group streams until we can support them
6459
6460 // Stop repeating request, wait until all remaining requests are submitted, then call into
6461 // HAL switchToOffline
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006462 hardware::camera::device::V3_6::CameraOfflineSessionInfo offlineSessionInfo;
6463 sp<hardware::camera::device::V3_6::ICameraOfflineSession> offlineSession;
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006464 camera3::BufferRecords bufferRecords;
6465 status_t ret = mRequestThread->switchToOffline(
6466 streamsToKeep, &offlineSessionInfo, &offlineSession, &bufferRecords);
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006467
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006468 if (ret != OK) {
6469 SET_ERR("Switch to offline failed: %s (%d)", strerror(-ret), ret);
6470 return ret;
6471 }
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006472
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006473 bool succ = mRequestBufferSM.onSwitchToOfflineSuccess();
6474 if (!succ) {
6475 SET_ERR("HAL must not be calling requestStreamBuffers call");
6476 // TODO: block ALL callbacks from HAL till app configured new streams?
6477 return UNKNOWN_ERROR;
6478 }
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006479
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006480 // Verify offlineSessionInfo
6481 std::vector<int32_t> offlineStreamIds;
6482 offlineStreamIds.reserve(offlineSessionInfo.offlineStreams.size());
6483 for (auto offlineStream : offlineSessionInfo.offlineStreams) {
6484 // verify stream IDs
6485 int32_t id = offlineStream.id;
6486 if (std::find(streamIds.begin(), streamIds.end(), id) == streamIds.end()) {
6487 SET_ERR("stream ID %d not found!", id);
6488 return UNKNOWN_ERROR;
6489 }
6490
6491 // When not using HAL buf manager, only allow streams requested by app to be preserved
6492 if (!mUseHalBufManager) {
6493 if (std::find(streamsToKeep.begin(), streamsToKeep.end(), id) == streamsToKeep.end()) {
6494 SET_ERR("stream ID %d must not be switched to offline!", id);
6495 return UNKNOWN_ERROR;
6496 }
6497 }
6498
6499 offlineStreamIds.push_back(id);
6500 sp<Camera3StreamInterface> stream = (id == inputStreamId) ?
6501 static_cast<sp<Camera3StreamInterface>>(mInputStream) :
6502 static_cast<sp<Camera3StreamInterface>>(mOutputStreams.get(id));
6503 // Verify number of outstanding buffers
6504 if (stream->getOutstandingBuffersCount() != offlineStream.numOutstandingBuffers) {
6505 SET_ERR("Offline stream %d # of remaining buffer mismatch: (%zu,%d) (service/HAL)",
6506 id, stream->getOutstandingBuffersCount(), offlineStream.numOutstandingBuffers);
6507 return UNKNOWN_ERROR;
6508 }
6509 }
6510
6511 // Verify all streams to be deleted don't have any outstanding buffers
6512 if (hasInputStream && std::find(offlineStreamIds.begin(), offlineStreamIds.end(),
6513 inputStreamId) == offlineStreamIds.end()) {
6514 if (mInputStream->hasOutstandingBuffers()) {
6515 SET_ERR("Input stream %d still has %zu outstanding buffer!",
6516 inputStreamId, mInputStream->getOutstandingBuffersCount());
6517 return UNKNOWN_ERROR;
6518 }
6519 }
6520
6521 for (const auto& outStreamId : outputStreamIds) {
6522 if (std::find(offlineStreamIds.begin(), offlineStreamIds.end(),
6523 outStreamId) == offlineStreamIds.end()) {
6524 auto outStream = mOutputStreams.get(outStreamId);
6525 if (outStream->hasOutstandingBuffers()) {
6526 SET_ERR("Output stream %d still has %zu outstanding buffer!",
6527 outStreamId, outStream->getOutstandingBuffersCount());
6528 return UNKNOWN_ERROR;
6529 }
6530 }
6531 }
6532
6533 InFlightRequestMap offlineReqs;
6534 // Verify inflight requests and their pending buffers
6535 {
6536 std::lock_guard<std::mutex> l(mInFlightLock);
6537 for (auto offlineReq : offlineSessionInfo.offlineRequests) {
6538 int idx = mInFlightMap.indexOfKey(offlineReq.frameNumber);
6539 if (idx == NAME_NOT_FOUND) {
6540 SET_ERR("Offline request frame number %d not found!", offlineReq.frameNumber);
6541 return UNKNOWN_ERROR;
6542 }
6543
6544 const auto& inflightReq = mInFlightMap.valueAt(idx);
6545 // TODO: check specific stream IDs
6546 size_t numBuffersLeft = static_cast<size_t>(inflightReq.numBuffersLeft);
6547 if (numBuffersLeft != offlineReq.pendingStreams.size()) {
6548 SET_ERR("Offline request # of remaining buffer mismatch: (%d,%d) (service/HAL)",
6549 inflightReq.numBuffersLeft, offlineReq.pendingStreams.size());
6550 return UNKNOWN_ERROR;
6551 }
6552 offlineReqs.add(offlineReq.frameNumber, inflightReq);
6553 }
6554 }
6555
6556 // Create Camera3OfflineSession and transfer object ownership
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006557 // (streams, inflight requests, buffer caches)
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006558 camera3::StreamSet offlineStreamSet;
6559 sp<camera3::Camera3Stream> inputStream;
6560 for (auto offlineStream : offlineSessionInfo.offlineStreams) {
6561 int32_t id = offlineStream.id;
6562 if (mInputStream != nullptr && id == mInputStream->getId()) {
6563 inputStream = mInputStream;
6564 } else {
6565 offlineStreamSet.add(id, mOutputStreams.get(id));
6566 }
6567 }
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006568
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006569 // TODO: check if we need to lock before copying states
6570 // though technically no other thread should be talking to Camera3Device at this point
6571 Camera3OfflineStates offlineStates(
6572 mTagMonitor, mVendorTagId, mUseHalBufManager, mNeedFixupMonochromeTags,
Shuzhen Wangb7b42652020-05-07 11:59:02 -07006573 mUsePartialResult, mNumPartialResults, mLastCompletedRegularFrameNumber,
6574 mLastCompletedReprocessFrameNumber, mLastCompletedZslFrameNumber,
6575 mNextResultFrameNumber, mNextReprocessResultFrameNumber,
6576 mNextZslStillResultFrameNumber, mNextShutterFrameNumber,
6577 mNextReprocessShutterFrameNumber, mNextZslStillShutterFrameNumber,
6578 mDeviceInfo, mPhysicalDeviceInfoMap, mDistortionMappers,
6579 mZoomRatioMappers, mRotateAndCropMappers);
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006580
6581 *session = new Camera3OfflineSession(mId, inputStream, offlineStreamSet,
6582 std::move(bufferRecords), offlineReqs, offlineStates, offlineSession);
6583
6584 // Delete all streams that has been transferred to offline session
6585 Mutex::Autolock l(mLock);
6586 for (auto offlineStream : offlineSessionInfo.offlineStreams) {
6587 int32_t id = offlineStream.id;
6588 if (mInputStream != nullptr && id == mInputStream->getId()) {
6589 mInputStream.clear();
6590 } else {
6591 mOutputStreams.remove(id);
6592 }
6593 }
6594
6595 // disconnect all other streams and switch to UNCONFIGURED state
6596 if (mInputStream != nullptr) {
6597 ret = mInputStream->disconnect();
6598 if (ret != OK) {
6599 SET_ERR_L("disconnect input stream failed!");
6600 return UNKNOWN_ERROR;
6601 }
6602 }
6603
6604 for (auto streamId : mOutputStreams.getStreamIds()) {
6605 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
6606 ret = stream->disconnect();
6607 if (ret != OK) {
6608 SET_ERR_L("disconnect output stream %d failed!", streamId);
6609 return UNKNOWN_ERROR;
6610 }
6611 }
6612
6613 mInputStream.clear();
6614 mOutputStreams.clear();
6615 mNeedConfig = true;
6616 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
6617 mOperatingMode = NO_MODE;
6618 mIsConstrainedHighSpeedConfiguration = false;
Emilian Peevc0fe54c2020-03-11 14:05:07 -07006619 mRequestThread->clearPreviousRequest();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006620
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006621 return OK;
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006622 // TO be done by CameraDeviceClient/Camera3OfflineSession
6623 // register the offline client to camera service
6624 // Setup result passthing threads etc
6625 // Initialize offline session so HAL can start sending callback to it (result Fmq)
6626 // TODO: check how many onIdle callback will be sent
6627 // Java side to make sure the CameraCaptureSession is properly closed
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006628}
6629
Emilian Peevcc0b7952020-01-07 13:54:47 -08006630void Camera3Device::getOfflineStreamIds(std::vector<int> *offlineStreamIds) {
6631 ATRACE_CALL();
6632
6633 if (offlineStreamIds == nullptr) {
6634 return;
6635 }
6636
6637 Mutex::Autolock il(mInterfaceLock);
6638
6639 auto streamIds = mOutputStreams.getStreamIds();
6640 bool hasInputStream = mInputStream != nullptr;
6641 if (hasInputStream && mInputStream->getOfflineProcessingSupport()) {
6642 offlineStreamIds->push_back(mInputStream->getId());
6643 }
6644
6645 for (const auto & streamId : streamIds) {
6646 sp<camera3::Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
6647 // Streams that use the camera buffer manager are currently not supported in
6648 // offline mode
6649 if (stream->getOfflineProcessingSupport() &&
6650 (stream->getStreamSetId() == CAMERA3_STREAM_SET_ID_INVALID)) {
6651 offlineStreamIds->push_back(streamId);
6652 }
6653 }
6654}
6655
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08006656status_t Camera3Device::setRotateAndCropAutoBehavior(
6657 camera_metadata_enum_android_scaler_rotate_and_crop_t rotateAndCropValue) {
6658 ATRACE_CALL();
6659 Mutex::Autolock il(mInterfaceLock);
6660 Mutex::Autolock l(mLock);
6661 if (mRequestThread == nullptr) {
6662 return INVALID_OPERATION;
6663 }
6664 return mRequestThread->setRotateAndCropAutoBehavior(rotateAndCropValue);
6665}
6666
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08006667bool Camera3Device::supportsCameraMute() {
6668 Mutex::Autolock il(mInterfaceLock);
6669 Mutex::Autolock l(mLock);
6670
6671 return mSupportCameraMute;
6672}
6673
6674status_t Camera3Device::setCameraMute(bool enabled) {
6675 ATRACE_CALL();
6676 Mutex::Autolock il(mInterfaceLock);
6677 Mutex::Autolock l(mLock);
6678
6679 if (mRequestThread == nullptr || !mSupportCameraMute) {
6680 return INVALID_OPERATION;
6681 }
Eino-Ville Talvala11afe4f2021-05-27 14:45:31 -07006682 int32_t muteMode =
6683 !enabled ? ANDROID_SENSOR_TEST_PATTERN_MODE_OFF :
6684 mSupportTestPatternSolidColor ? ANDROID_SENSOR_TEST_PATTERN_MODE_SOLID_COLOR :
6685 ANDROID_SENSOR_TEST_PATTERN_MODE_BLACK;
6686 return mRequestThread->setCameraMute(muteMode);
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08006687}
6688
Cliff Wuc2ad9c82021-04-21 00:58:58 +08006689status_t Camera3Device::injectCamera(const String8& injectedCamId,
6690 sp<CameraProviderManager> manager) {
6691 ALOGI("%s Injection camera: injectedCamId = %s", __FUNCTION__, injectedCamId.string());
6692 ATRACE_CALL();
6693 Mutex::Autolock il(mInterfaceLock);
Cliff Wu3b268182021-07-06 15:44:43 +08006694 // When the camera device is active, injectCamera() and stopInjection() will call
6695 // internalPauseAndWaitLocked() and internalResumeLocked(), and then they will call
6696 // mStatusChanged.waitRelative(mLock, timeout) of waitUntilStateThenRelock(). But
6697 // mStatusChanged.waitRelative(mLock, timeout)'s parameter: mutex "mLock" must be in the locked
6698 // state, so we need to add "Mutex::Autolock l(mLock)" to lock the "mLock" before calling
6699 // waitUntilStateThenRelock().
6700 Mutex::Autolock l(mLock);
Cliff Wuc2ad9c82021-04-21 00:58:58 +08006701
6702 status_t res = NO_ERROR;
6703 if (mInjectionMethods->isInjecting()) {
6704 if (injectedCamId == mInjectionMethods->getInjectedCamId()) {
6705 return OK;
6706 } else {
6707 res = mInjectionMethods->stopInjection();
6708 if (res != OK) {
6709 ALOGE("%s: Failed to stop the injection camera! ret != NO_ERROR: %d",
6710 __FUNCTION__, res);
6711 return res;
6712 }
6713 }
6714 }
6715
6716 res = mInjectionMethods->injectionInitialize(injectedCamId, manager, this);
6717 if (res != OK) {
6718 ALOGE("%s: Failed to initialize the injection camera! ret != NO_ERROR: %d",
6719 __FUNCTION__, res);
6720 return res;
6721 }
6722
Cliff Wuc2ad9c82021-04-21 00:58:58 +08006723 // When the second display of android is cast to the remote device, and the opened camera is
6724 // also cast to the second display, in this case, because the camera has configured the streams
6725 // at this time, we can directly call injectCamera() to replace the internal camera with
6726 // injection camera.
Cliff Wu3b268182021-07-06 15:44:43 +08006727 if (mInjectionMethods->isStreamConfigCompleteButNotInjected()) {
6728 ALOGD("%s: The opened camera is directly cast to the remote device.", __FUNCTION__);
6729
6730 camera3::camera_stream_configuration injectionConfig;
6731 std::vector<uint32_t> injectionBufferSizes;
6732 mInjectionMethods->getInjectionConfig(&injectionConfig, &injectionBufferSizes);
6733 if (mOperatingMode < 0 || injectionConfig.num_streams <= 0
6734 || injectionBufferSizes.size() <= 0) {
6735 ALOGE("Failed to inject camera due to abandoned configuration! "
6736 "mOperatingMode: %d injectionConfig.num_streams: %d "
6737 "injectionBufferSizes.size(): %zu", mOperatingMode,
6738 injectionConfig.num_streams, injectionBufferSizes.size());
6739 return DEAD_OBJECT;
6740 }
6741
Cliff Wuc2ad9c82021-04-21 00:58:58 +08006742 res = mInjectionMethods->injectCamera(
6743 injectionConfig, injectionBufferSizes);
6744 if (res != OK) {
6745 ALOGE("Can't finish inject camera process!");
6746 return res;
6747 }
6748 }
6749
6750 return OK;
6751}
6752
6753status_t Camera3Device::stopInjection() {
6754 ALOGI("%s: Injection camera: stopInjection", __FUNCTION__);
6755 Mutex::Autolock il(mInterfaceLock);
Cliff Wu3b268182021-07-06 15:44:43 +08006756 Mutex::Autolock l(mLock);
Cliff Wuc2ad9c82021-04-21 00:58:58 +08006757 return mInjectionMethods->stopInjection();
6758}
6759
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08006760}; // namespace android