blob: cbea9a269c0ad439e4fd830eaa574e446031ed4a [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) {
Yin-Chia Yeh657c1872017-07-18 18:09:57 -07001179 // Ideally we should grab mLock, but that can lead to deadlock, and
1180 // it's not super important to get up to date value of mStatus for this
1181 // warning print, hence skipping the lock here
1182 if (mStatus == STATUS_ERROR) {
1183 // Per API contract, HAL should act as closed after device error
1184 // But mStatus can be set to error by framework as well, so just log
1185 // a warning here.
1186 ALOGW("%s: received notify message in error state.", __FUNCTION__);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07001187 }
Yin-Chia Yeh657c1872017-07-18 18:09:57 -07001188
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001189 sp<NotificationListener> listener;
1190 {
1191 std::lock_guard<std::mutex> l(mOutputLock);
1192 listener = mListener.promote();
1193 }
1194
1195 CaptureOutputStates states {
1196 mId,
Shuzhen Wangb7b42652020-05-07 11:59:02 -07001197 mInFlightLock, mLastCompletedRegularFrameNumber,
1198 mLastCompletedReprocessFrameNumber, mLastCompletedZslFrameNumber,
1199 mInFlightMap, mOutputLock, mResultQueue, mResultSignal,
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001200 mNextShutterFrameNumber,
1201 mNextReprocessShutterFrameNumber, mNextZslStillShutterFrameNumber,
1202 mNextResultFrameNumber,
1203 mNextReprocessResultFrameNumber, mNextZslStillResultFrameNumber,
1204 mUseHalBufManager, mUsePartialResult, mNeedFixupMonochromeTags,
1205 mNumPartialResults, mVendorTagId, mDeviceInfo, mPhysicalDeviceInfoMap,
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08001206 mResultMetadataQueue, mDistortionMappers, mZoomRatioMappers, mRotateAndCropMappers,
Shuzhen Wang316781a2020-08-18 18:11:01 -07001207 mTagMonitor, mInputStream, mOutputStreams, mSessionStatsBuilder, listener, *this, *this,
Emilian Peev5104fe92021-10-21 14:27:09 -07001208 *mInterface, mLegacyClient
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001209 };
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001210 for (const auto& msg : msgs) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001211 camera3::notify(states, msg);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001212 }
1213 return hardware::Void();
1214}
1215
Emilian Peevaebbe412018-01-15 13:53:24 +00001216status_t Camera3Device::captureList(const List<const PhysicalCameraSettingsList> &requestsList,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001217 const std::list<const SurfaceMap> &surfaceMaps,
Jianing Weicb0652e2014-03-12 18:29:36 -07001218 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -07001219 ATRACE_CALL();
1220
Emilian Peevaebbe412018-01-15 13:53:24 +00001221 return submitRequestsHelper(requestsList, surfaceMaps, /*repeating*/false, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -07001222}
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001223
Jianing Weicb0652e2014-03-12 18:29:36 -07001224status_t Camera3Device::setStreamingRequest(const CameraMetadata &request,
1225 int64_t* /*lastFrameNumber*/) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001226 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001227
Emilian Peevaebbe412018-01-15 13:53:24 +00001228 List<const PhysicalCameraSettingsList> requestsList;
Shuzhen Wang0129d522016-10-30 22:43:41 -07001229 std::list<const SurfaceMap> surfaceMaps;
Emilian Peevaebbe412018-01-15 13:53:24 +00001230 convertToRequestList(requestsList, surfaceMaps, request);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001231
Emilian Peevaebbe412018-01-15 13:53:24 +00001232 return setStreamingRequestList(requestsList, /*surfaceMap*/surfaceMaps,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001233 /*lastFrameNumber*/NULL);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001234}
1235
Emilian Peevaebbe412018-01-15 13:53:24 +00001236status_t Camera3Device::setStreamingRequestList(
1237 const List<const PhysicalCameraSettingsList> &requestsList,
1238 const std::list<const SurfaceMap> &surfaceMaps, int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -07001239 ATRACE_CALL();
1240
Emilian Peevaebbe412018-01-15 13:53:24 +00001241 return submitRequestsHelper(requestsList, surfaceMaps, /*repeating*/true, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -07001242}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001243
1244sp<Camera3Device::CaptureRequest> Camera3Device::setUpRequestLocked(
Emilian Peevaebbe412018-01-15 13:53:24 +00001245 const PhysicalCameraSettingsList &request, const SurfaceMap &surfaceMap) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001246 status_t res;
1247
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001248 if (mStatus == STATUS_UNCONFIGURED || mNeedConfig) {
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08001249 // This point should only be reached via API1 (API2 must explicitly call configureStreams)
1250 // so unilaterally select normal operating mode.
Emilian Peevaebbe412018-01-15 13:53:24 +00001251 res = filterParamsAndConfigureLocked(request.begin()->metadata,
Emilian Peevf4816702020-04-03 15:44:51 -07001252 CAMERA_STREAM_CONFIGURATION_NORMAL_MODE);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001253 // Stream configuration failed. Client might try other configuraitons.
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001254 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001255 CLOGE("Can't set up streams: %s (%d)", strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001256 return NULL;
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001257 } else if (mStatus == STATUS_UNCONFIGURED) {
1258 // Stream configuration successfully configure to empty stream configuration.
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001259 CLOGE("No streams configured");
1260 return NULL;
1261 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001262 }
1263
Shuzhen Wang0129d522016-10-30 22:43:41 -07001264 sp<CaptureRequest> newRequest = createCaptureRequest(request, surfaceMap);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001265 return newRequest;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001266}
1267
Jianing Weicb0652e2014-03-12 18:29:36 -07001268status_t Camera3Device::clearStreamingRequest(int64_t *lastFrameNumber) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001269 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001270 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001271 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001272
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001273 switch (mStatus) {
1274 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001275 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001276 return INVALID_OPERATION;
1277 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001278 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001279 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001280 case STATUS_UNCONFIGURED:
1281 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001282 case STATUS_ACTIVE:
1283 // OK
1284 break;
1285 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001286 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001287 return INVALID_OPERATION;
1288 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001289 ALOGV("Camera %s: Clearing repeating request", mId.string());
Jianing Weicb0652e2014-03-12 18:29:36 -07001290
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07001291 return mRequestThread->clearRepeatingRequests(lastFrameNumber);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001292}
1293
1294status_t Camera3Device::waitUntilRequestReceived(int32_t requestId, nsecs_t timeout) {
1295 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001296 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001297
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001298 return mRequestThread->waitUntilRequestProcessed(requestId, timeout);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001299}
1300
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001301status_t Camera3Device::createInputStream(
Shuzhen Wang83bff122020-11-20 15:51:39 -08001302 uint32_t width, uint32_t height, int format, bool isMultiResolution, int *id) {
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001303 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001304 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001305 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001306 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001307 ALOGV("Camera %s: Creating new input stream %d: %d x %d, format %d",
1308 mId.string(), mNextStreamId, width, height, format);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001309
1310 status_t res;
1311 bool wasActive = false;
1312
1313 switch (mStatus) {
1314 case STATUS_ERROR:
1315 ALOGE("%s: Device has encountered a serious error", __FUNCTION__);
1316 return INVALID_OPERATION;
1317 case STATUS_UNINITIALIZED:
1318 ALOGE("%s: Device not initialized", __FUNCTION__);
1319 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001320 case STATUS_UNCONFIGURED:
1321 case STATUS_CONFIGURED:
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001322 // OK
1323 break;
1324 case STATUS_ACTIVE:
1325 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001326 res = internalPauseAndWaitLocked(maxExpectedDuration);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001327 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001328 SET_ERR_L("Can't pause captures to reconfigure streams!");
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001329 return res;
1330 }
1331 wasActive = true;
1332 break;
1333 default:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001334 SET_ERR_L("%s: Unexpected status: %d", mStatus);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001335 return INVALID_OPERATION;
1336 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001337 assert(mStatus != STATUS_ACTIVE);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001338
1339 if (mInputStream != 0) {
1340 ALOGE("%s: Cannot create more than 1 input stream", __FUNCTION__);
1341 return INVALID_OPERATION;
1342 }
1343
1344 sp<Camera3InputStream> newStream = new Camera3InputStream(mNextStreamId,
1345 width, height, format);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001346 newStream->setStatusTracker(mStatusTracker);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001347
1348 mInputStream = newStream;
Shuzhen Wang83bff122020-11-20 15:51:39 -08001349 mIsInputStreamMultiResolution = isMultiResolution;
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001350
1351 *id = mNextStreamId++;
1352
1353 // Continue captures if active at start
1354 if (wasActive) {
1355 ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001356 // Reuse current operating mode and session parameters for new stream config
1357 res = configureStreamsLocked(mOperatingMode, mSessionParams);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001358 if (res != OK) {
1359 ALOGE("%s: Can't reconfigure device for new stream %d: %s (%d)",
1360 __FUNCTION__, mNextStreamId, strerror(-res), res);
1361 return res;
1362 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001363 internalResumeLocked();
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001364 }
1365
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001366 ALOGV("Camera %s: Created input stream", mId.string());
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001367 return OK;
1368}
1369
Eino-Ville Talvala727d1722015-06-09 13:44:19 -07001370status_t Camera3Device::createStream(sp<Surface> consumer,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001371 uint32_t width, uint32_t height, int format,
Emilian Peevf4816702020-04-03 15:44:51 -07001372 android_dataspace dataSpace, camera_stream_rotation_t rotation, int *id,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001373 const String8& physicalCameraId,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001374 const std::unordered_set<int32_t> &sensorPixelModesUsed,
1375 std::vector<int> *surfaceIds, int streamSetId, bool isShared, bool isMultiResolution,
1376 uint64_t consumerUsage) {
Shuzhen Wang0129d522016-10-30 22:43:41 -07001377 ATRACE_CALL();
1378
1379 if (consumer == nullptr) {
1380 ALOGE("%s: consumer must not be null", __FUNCTION__);
1381 return BAD_VALUE;
1382 }
1383
1384 std::vector<sp<Surface>> consumers;
1385 consumers.push_back(consumer);
1386
1387 return createStream(consumers, /*hasDeferredConsumer*/ false, width, height,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001388 format, dataSpace, rotation, id, physicalCameraId, sensorPixelModesUsed, surfaceIds,
1389 streamSetId, isShared, isMultiResolution, consumerUsage);
1390}
1391
1392static bool isRawFormat(int format) {
1393 switch (format) {
1394 case HAL_PIXEL_FORMAT_RAW16:
1395 case HAL_PIXEL_FORMAT_RAW12:
1396 case HAL_PIXEL_FORMAT_RAW10:
1397 case HAL_PIXEL_FORMAT_RAW_OPAQUE:
1398 return true;
1399 default:
1400 return false;
1401 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001402}
1403
1404status_t Camera3Device::createStream(const std::vector<sp<Surface>>& consumers,
1405 bool hasDeferredConsumer, uint32_t width, uint32_t height, int format,
Emilian Peevf4816702020-04-03 15:44:51 -07001406 android_dataspace dataSpace, camera_stream_rotation_t rotation, int *id,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001407 const String8& physicalCameraId, const std::unordered_set<int32_t> &sensorPixelModesUsed,
Shuzhen Wang83bff122020-11-20 15:51:39 -08001408 std::vector<int> *surfaceIds, int streamSetId, bool isShared, bool isMultiResolution,
1409 uint64_t consumerUsage) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001410 ATRACE_CALL();
Emilian Peev40ead602017-09-26 15:46:36 +01001411
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001412 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001413 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001414 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001415 ALOGV("Camera %s: Creating new stream %d: %d x %d, format %d, dataspace %d rotation %d"
Shuzhen Wang83bff122020-11-20 15:51:39 -08001416 " consumer usage %" PRIu64 ", isShared %d, physicalCameraId %s, isMultiResolution %d",
1417 mId.string(), mNextStreamId, width, height, format, dataSpace, rotation,
1418 consumerUsage, isShared, physicalCameraId.string(), isMultiResolution);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001419
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001420 status_t res;
1421 bool wasActive = false;
1422
1423 switch (mStatus) {
1424 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001425 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001426 return INVALID_OPERATION;
1427 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001428 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001429 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001430 case STATUS_UNCONFIGURED:
1431 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001432 // OK
1433 break;
1434 case STATUS_ACTIVE:
1435 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001436 res = internalPauseAndWaitLocked(maxExpectedDuration);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001437 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001438 SET_ERR_L("Can't pause captures to reconfigure streams!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001439 return res;
1440 }
1441 wasActive = true;
1442 break;
1443 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001444 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001445 return INVALID_OPERATION;
1446 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001447 assert(mStatus != STATUS_ACTIVE);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001448
1449 sp<Camera3OutputStream> newStream;
Zhijun He5d677d12016-05-29 16:52:39 -07001450
Shuzhen Wang0129d522016-10-30 22:43:41 -07001451 if (consumers.size() == 0 && !hasDeferredConsumer) {
1452 ALOGE("%s: Number of consumers cannot be smaller than 1", __FUNCTION__);
1453 return BAD_VALUE;
1454 }
Zhijun He5d677d12016-05-29 16:52:39 -07001455
Shuzhen Wang0129d522016-10-30 22:43:41 -07001456 if (hasDeferredConsumer && format != HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
Zhijun He5d677d12016-05-29 16:52:39 -07001457 ALOGE("Deferred consumer stream creation only support IMPLEMENTATION_DEFINED format");
1458 return BAD_VALUE;
1459 }
1460
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001461 if (isRawFormat(format) && sensorPixelModesUsed.size() > 1) {
1462 // We can't use one stream with a raw format in both sensor pixel modes since its going to
1463 // be found in only one sensor pixel mode.
1464 ALOGE("%s: RAW opaque stream cannot be used with > 1 sensor pixel modes", __FUNCTION__);
1465 return BAD_VALUE;
1466 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001467 if (format == HAL_PIXEL_FORMAT_BLOB) {
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -07001468 ssize_t blobBufferSize;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001469 if (dataSpace == HAL_DATASPACE_DEPTH) {
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -07001470 blobBufferSize = getPointCloudBufferSize();
1471 if (blobBufferSize <= 0) {
1472 SET_ERR_L("Invalid point cloud buffer size %zd", blobBufferSize);
1473 return BAD_VALUE;
1474 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001475 } else if (dataSpace == static_cast<android_dataspace>(HAL_DATASPACE_JPEG_APP_SEGMENTS)) {
1476 blobBufferSize = width * height;
1477 } else {
1478 blobBufferSize = getJpegBufferSize(width, height);
1479 if (blobBufferSize <= 0) {
1480 SET_ERR_L("Invalid jpeg buffer size %zd", blobBufferSize);
1481 return BAD_VALUE;
1482 }
Zhijun Hef7da0962014-04-24 13:27:56 -07001483 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001484 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001485 width, height, blobBufferSize, format, dataSpace, rotation,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001486 mTimestampOffset, physicalCameraId, sensorPixelModesUsed, streamSetId,
1487 isMultiResolution);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -08001488 } else if (format == HAL_PIXEL_FORMAT_RAW_OPAQUE) {
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001489 bool maxResolution =
1490 sensorPixelModesUsed.find(ANDROID_SENSOR_PIXEL_MODE_MAXIMUM_RESOLUTION) !=
1491 sensorPixelModesUsed.end();
1492 ssize_t rawOpaqueBufferSize = getRawOpaqueBufferSize(width, height, maxResolution);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -08001493 if (rawOpaqueBufferSize <= 0) {
1494 SET_ERR_L("Invalid RAW opaque buffer size %zd", rawOpaqueBufferSize);
1495 return BAD_VALUE;
1496 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001497 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001498 width, height, rawOpaqueBufferSize, format, dataSpace, rotation,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001499 mTimestampOffset, physicalCameraId, sensorPixelModesUsed, streamSetId,
1500 isMultiResolution);
Shuzhen Wang758c2152017-01-10 18:26:18 -08001501 } else if (isShared) {
1502 newStream = new Camera3SharedOutputStream(mNextStreamId, consumers,
1503 width, height, format, consumerUsage, dataSpace, rotation,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001504 mTimestampOffset, physicalCameraId, sensorPixelModesUsed, streamSetId,
1505 mUseHalBufManager);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001506 } else if (consumers.size() == 0 && hasDeferredConsumer) {
Zhijun He5d677d12016-05-29 16:52:39 -07001507 newStream = new Camera3OutputStream(mNextStreamId,
1508 width, height, format, consumerUsage, dataSpace, rotation,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001509 mTimestampOffset, physicalCameraId, sensorPixelModesUsed, streamSetId,
1510 isMultiResolution);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001511 } else {
Shuzhen Wang0129d522016-10-30 22:43:41 -07001512 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001513 width, height, format, dataSpace, rotation,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001514 mTimestampOffset, physicalCameraId, sensorPixelModesUsed, streamSetId,
1515 isMultiResolution);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001516 }
Emilian Peev40ead602017-09-26 15:46:36 +01001517
1518 size_t consumerCount = consumers.size();
1519 for (size_t i = 0; i < consumerCount; i++) {
1520 int id = newStream->getSurfaceId(consumers[i]);
1521 if (id < 0) {
1522 SET_ERR_L("Invalid surface id");
1523 return BAD_VALUE;
1524 }
1525 if (surfaceIds != nullptr) {
1526 surfaceIds->push_back(id);
1527 }
1528 }
1529
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001530 newStream->setStatusTracker(mStatusTracker);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001531
Emilian Peev08dd2452017-04-06 16:55:14 +01001532 newStream->setBufferManager(mBufferManager);
Zhijun He125684a2015-12-26 15:07:30 -08001533
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08001534 newStream->setImageDumpMask(mImageDumpMask);
1535
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001536 res = mOutputStreams.add(mNextStreamId, newStream);
1537 if (res < 0) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001538 SET_ERR_L("Can't add new stream to set: %s (%d)", strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001539 return res;
1540 }
1541
Shuzhen Wang316781a2020-08-18 18:11:01 -07001542 mSessionStatsBuilder.addStream(mNextStreamId);
1543
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001544 *id = mNextStreamId++;
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07001545 mNeedConfig = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001546
1547 // Continue captures if active at start
1548 if (wasActive) {
1549 ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001550 // Reuse current operating mode and session parameters for new stream config
1551 res = configureStreamsLocked(mOperatingMode, mSessionParams);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001552 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001553 CLOGE("Can't reconfigure device for new stream %d: %s (%d)",
1554 mNextStreamId, strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001555 return res;
1556 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001557 internalResumeLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001558 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001559 ALOGV("Camera %s: Created new stream", mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001560 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001561}
1562
Emilian Peev710c1422017-08-30 11:19:38 +01001563status_t Camera3Device::getStreamInfo(int id, StreamInfo *streamInfo) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001564 ATRACE_CALL();
Emilian Peev710c1422017-08-30 11:19:38 +01001565 if (nullptr == streamInfo) {
1566 return BAD_VALUE;
1567 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001568 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001569 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001570
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001571 switch (mStatus) {
1572 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001573 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001574 return INVALID_OPERATION;
1575 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001576 CLOGE("Device not initialized!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001577 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001578 case STATUS_UNCONFIGURED:
1579 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001580 case STATUS_ACTIVE:
1581 // OK
1582 break;
1583 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001584 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001585 return INVALID_OPERATION;
1586 }
1587
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001588 sp<Camera3StreamInterface> stream = mOutputStreams.get(id);
1589 if (stream == nullptr) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001590 CLOGE("Stream %d is unknown", id);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001591 return BAD_VALUE;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001592 }
1593
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001594 streamInfo->width = stream->getWidth();
1595 streamInfo->height = stream->getHeight();
1596 streamInfo->format = stream->getFormat();
1597 streamInfo->dataSpace = stream->getDataSpace();
1598 streamInfo->formatOverridden = stream->isFormatOverridden();
1599 streamInfo->originalFormat = stream->getOriginalFormat();
1600 streamInfo->dataSpaceOverridden = stream->isDataSpaceOverridden();
1601 streamInfo->originalDataSpace = stream->getOriginalDataSpace();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001602 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001603}
1604
1605status_t Camera3Device::setStreamTransform(int id,
1606 int transform) {
1607 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001608 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001609 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001610
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001611 switch (mStatus) {
1612 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001613 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001614 return INVALID_OPERATION;
1615 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001616 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001617 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001618 case STATUS_UNCONFIGURED:
1619 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001620 case STATUS_ACTIVE:
1621 // OK
1622 break;
1623 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001624 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001625 return INVALID_OPERATION;
1626 }
1627
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001628 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(id);
1629 if (stream == nullptr) {
1630 CLOGE("Stream %d does not exist", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001631 return BAD_VALUE;
1632 }
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001633 return stream->setTransform(transform);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001634}
1635
1636status_t Camera3Device::deleteStream(int id) {
1637 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001638 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001639 Mutex::Autolock l(mLock);
1640 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001641
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001642 ALOGV("%s: Camera %s: Deleting stream %d", __FUNCTION__, mId.string(), id);
Igor Murashkine2172be2013-05-28 15:31:39 -07001643
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001644 // CameraDevice semantics require device to already be idle before
1645 // deleteStream is called, unlike for createStream.
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001646 if (mStatus == STATUS_ACTIVE) {
Yin-Chia Yeh693047d2018-03-08 12:14:19 -08001647 ALOGW("%s: Camera %s: Device not idle", __FUNCTION__, mId.string());
Igor Murashkin52827132013-05-13 14:53:44 -07001648 return -EBUSY;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001649 }
1650
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07001651 if (mStatus == STATUS_ERROR) {
1652 ALOGW("%s: Camera %s: deleteStream not allowed in ERROR state",
1653 __FUNCTION__, mId.string());
1654 return -EBUSY;
1655 }
1656
Igor Murashkin2fba5842013-04-22 14:03:54 -07001657 sp<Camera3StreamInterface> deletedStream;
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001658 sp<Camera3StreamInterface> stream = mOutputStreams.get(id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001659 if (mInputStream != NULL && id == mInputStream->getId()) {
1660 deletedStream = mInputStream;
1661 mInputStream.clear();
1662 } else {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001663 if (stream == nullptr) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001664 CLOGE("Stream %d does not exist", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001665 return BAD_VALUE;
1666 }
Shuzhen Wang316781a2020-08-18 18:11:01 -07001667 mSessionStatsBuilder.removeStream(id);
Zhijun He5f446352014-01-22 09:49:33 -08001668 }
1669
1670 // Delete output stream or the output part of a bi-directional stream.
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001671 if (stream != nullptr) {
1672 deletedStream = stream;
1673 mOutputStreams.remove(id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001674 }
1675
1676 // Free up the stream endpoint so that it can be used by some other stream
1677 res = deletedStream->disconnect();
1678 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001679 SET_ERR_L("Can't disconnect deleted stream %d", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001680 // fall through since we want to still list the stream as deleted.
1681 }
1682 mDeletedStreams.add(deletedStream);
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07001683 mNeedConfig = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001684
1685 return res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001686}
1687
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001688status_t Camera3Device::configureStreams(const CameraMetadata& sessionParams, int operatingMode) {
Igor Murashkine2d167e2014-08-19 16:19:59 -07001689 ATRACE_CALL();
1690 ALOGV("%s: E", __FUNCTION__);
1691
1692 Mutex::Autolock il(mInterfaceLock);
1693 Mutex::Autolock l(mLock);
Chien-Yu Chen17338fc2015-06-18 16:30:12 -07001694
Emilian Peev811d2952018-05-25 11:08:40 +01001695 // In case the client doesn't include any session parameter, try a
1696 // speculative configuration using the values from the last cached
1697 // default request.
1698 if (sessionParams.isEmpty() &&
Emilian Peevf4816702020-04-03 15:44:51 -07001699 ((mLastTemplateId > 0) && (mLastTemplateId < CAMERA_TEMPLATE_COUNT)) &&
Emilian Peev811d2952018-05-25 11:08:40 +01001700 (!mRequestTemplateCache[mLastTemplateId].isEmpty())) {
1701 ALOGV("%s: Speculative session param configuration with template id: %d", __func__,
1702 mLastTemplateId);
1703 return filterParamsAndConfigureLocked(mRequestTemplateCache[mLastTemplateId],
1704 operatingMode);
1705 }
1706
Emilian Peevac3ce6c2017-12-12 15:27:02 +00001707 return filterParamsAndConfigureLocked(sessionParams, operatingMode);
1708}
1709
1710status_t Camera3Device::filterParamsAndConfigureLocked(const CameraMetadata& sessionParams,
1711 int operatingMode) {
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001712 //Filter out any incoming session parameters
1713 const CameraMetadata params(sessionParams);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001714 camera_metadata_entry_t availableSessionKeys = mDeviceInfo.find(
1715 ANDROID_REQUEST_AVAILABLE_SESSION_KEYS);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00001716 CameraMetadata filteredParams(availableSessionKeys.count);
1717 camera_metadata_t *meta = const_cast<camera_metadata_t *>(
1718 filteredParams.getAndLock());
1719 set_camera_metadata_vendor_id(meta, mVendorTagId);
1720 filteredParams.unlock(meta);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001721 if (availableSessionKeys.count > 0) {
1722 for (size_t i = 0; i < availableSessionKeys.count; i++) {
1723 camera_metadata_ro_entry entry = params.find(
1724 availableSessionKeys.data.i32[i]);
1725 if (entry.count > 0) {
1726 filteredParams.update(entry);
1727 }
1728 }
1729 }
1730
1731 return configureStreamsLocked(operatingMode, filteredParams);
Igor Murashkine2d167e2014-08-19 16:19:59 -07001732}
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001733
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07001734status_t Camera3Device::getInputBufferProducer(
1735 sp<IGraphicBufferProducer> *producer) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07001736 ATRACE_CALL();
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07001737 Mutex::Autolock il(mInterfaceLock);
1738 Mutex::Autolock l(mLock);
1739
1740 if (producer == NULL) {
1741 return BAD_VALUE;
1742 } else if (mInputStream == NULL) {
1743 return INVALID_OPERATION;
1744 }
1745
1746 return mInputStream->getInputBufferProducer(producer);
1747}
1748
Emilian Peevf4816702020-04-03 15:44:51 -07001749status_t Camera3Device::createDefaultRequest(camera_request_template_t templateId,
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001750 CameraMetadata *request) {
1751 ATRACE_CALL();
Alex Rayfe7e0c62013-05-30 00:12:13 -07001752 ALOGV("%s: for template %d", __FUNCTION__, templateId);
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08001753
Emilian Peevf4816702020-04-03 15:44:51 -07001754 if (templateId <= 0 || templateId >= CAMERA_TEMPLATE_COUNT) {
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08001755 android_errorWriteWithInfoLog(CameraService::SN_EVENT_LOG_ID, "26866110",
Jayant Chowdhary12361932018-08-27 14:46:13 -07001756 CameraThreadState::getCallingUid(), nullptr, 0);
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08001757 return BAD_VALUE;
1758 }
1759
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001760 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001761
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001762 {
1763 Mutex::Autolock l(mLock);
1764 switch (mStatus) {
1765 case STATUS_ERROR:
1766 CLOGE("Device has encountered a serious error");
1767 return INVALID_OPERATION;
1768 case STATUS_UNINITIALIZED:
1769 CLOGE("Device is not initialized!");
1770 return INVALID_OPERATION;
1771 case STATUS_UNCONFIGURED:
1772 case STATUS_CONFIGURED:
1773 case STATUS_ACTIVE:
1774 // OK
1775 break;
1776 default:
1777 SET_ERR_L("Unexpected status: %d", mStatus);
1778 return INVALID_OPERATION;
1779 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001780
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001781 if (!mRequestTemplateCache[templateId].isEmpty()) {
1782 *request = mRequestTemplateCache[templateId];
Emilian Peev811d2952018-05-25 11:08:40 +01001783 mLastTemplateId = templateId;
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001784 return OK;
1785 }
Zhijun Hea1530f12014-09-14 12:44:20 -07001786 }
1787
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001788 camera_metadata_t *rawRequest;
1789 status_t res = mInterface->constructDefaultRequestSettings(
Emilian Peevf4816702020-04-03 15:44:51 -07001790 (camera_request_template_t) templateId, &rawRequest);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001791
1792 {
1793 Mutex::Autolock l(mLock);
1794 if (res == BAD_VALUE) {
1795 ALOGI("%s: template %d is not supported on this camera device",
1796 __FUNCTION__, templateId);
1797 return res;
1798 } else if (res != OK) {
1799 CLOGE("Unable to construct request template %d: %s (%d)",
1800 templateId, strerror(-res), res);
1801 return res;
1802 }
1803
1804 set_camera_metadata_vendor_id(rawRequest, mVendorTagId);
1805 mRequestTemplateCache[templateId].acquire(rawRequest);
1806
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08001807 // Override the template request with zoomRatioMapper
1808 res = mZoomRatioMappers[mId.c_str()].initZoomRatioInTemplate(
1809 &mRequestTemplateCache[templateId]);
1810 if (res != OK) {
1811 CLOGE("Failed to update zoom ratio for template %d: %s (%d)",
1812 templateId, strerror(-res), res);
1813 return res;
1814 }
1815
Shuzhen Wangd25dc972020-03-24 17:11:43 -07001816 // Fill in JPEG_QUALITY if not available
1817 if (!mRequestTemplateCache[templateId].exists(ANDROID_JPEG_QUALITY)) {
1818 static const uint8_t kDefaultJpegQuality = 95;
1819 mRequestTemplateCache[templateId].update(ANDROID_JPEG_QUALITY,
1820 &kDefaultJpegQuality, 1);
1821 }
1822
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001823 *request = mRequestTemplateCache[templateId];
Emilian Peev811d2952018-05-25 11:08:40 +01001824 mLastTemplateId = templateId;
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001825 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001826 return OK;
1827}
1828
1829status_t Camera3Device::waitUntilDrained() {
1830 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001831 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001832 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001833 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001834
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001835 return waitUntilDrainedLocked(maxExpectedDuration);
Zhijun He69a37482014-03-23 18:44:49 -07001836}
1837
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001838status_t Camera3Device::waitUntilDrainedLocked(nsecs_t maxExpectedDuration) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001839 switch (mStatus) {
1840 case STATUS_UNINITIALIZED:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001841 case STATUS_UNCONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001842 ALOGV("%s: Already idle", __FUNCTION__);
1843 return OK;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001844 case STATUS_CONFIGURED:
1845 // To avoid race conditions, check with tracker to be sure
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001846 case STATUS_ERROR:
1847 case STATUS_ACTIVE:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001848 // Need to verify shut down
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001849 break;
1850 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001851 SET_ERR_L("Unexpected status: %d",mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001852 return INVALID_OPERATION;
1853 }
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07001854 ALOGV("%s: Camera %s: Waiting until idle (%" PRIi64 "ns)", __FUNCTION__, mId.string(),
1855 maxExpectedDuration);
1856 status_t res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
Eino-Ville Talvala9c8a0912014-09-14 14:52:19 -07001857 if (res != OK) {
Yin-Chia Yeh87b3ec02019-06-03 10:44:39 -07001858 mStatusTracker->dumpActiveComponents();
Eino-Ville Talvala9c8a0912014-09-14 14:52:19 -07001859 SET_ERR_L("Error waiting for HAL to drain: %s (%d)", strerror(-res),
1860 res);
1861 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001862 return res;
1863}
1864
Ruben Brunk183f0562015-08-12 12:55:02 -07001865void Camera3Device::internalUpdateStatusLocked(Status status) {
1866 mStatus = status;
1867 mRecentStatusUpdates.add(mStatus);
1868 mStatusChanged.broadcast();
1869}
1870
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001871// Pause to reconfigure
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001872status_t Camera3Device::internalPauseAndWaitLocked(nsecs_t maxExpectedDuration) {
Emilian Peeve86358b2019-02-15 13:51:39 -08001873 if (mRequestThread.get() != nullptr) {
1874 mRequestThread->setPaused(true);
1875 } else {
1876 return NO_INIT;
1877 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001878
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07001879 ALOGV("%s: Camera %s: Internal wait until idle (% " PRIi64 " ns)", __FUNCTION__, mId.string(),
1880 maxExpectedDuration);
1881 status_t res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001882 if (res != OK) {
1883 SET_ERR_L("Can't idle device in %f seconds!",
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07001884 maxExpectedDuration/1e9);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001885 }
1886
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001887 return res;
1888}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001889
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001890// Resume after internalPauseAndWaitLocked
1891status_t Camera3Device::internalResumeLocked() {
1892 status_t res;
1893
1894 mRequestThread->setPaused(false);
1895
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08001896 ALOGV("%s: Camera %s: Internal wait until active (% " PRIi64 " ns)", __FUNCTION__, mId.string(),
1897 kActiveTimeout);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001898 res = waitUntilStateThenRelock(/*active*/ true, kActiveTimeout);
1899 if (res != OK) {
1900 SET_ERR_L("Can't transition to active in %f seconds!",
1901 kActiveTimeout/1e9);
1902 }
1903 mPauseStateNotify = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001904 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001905}
1906
Ruben Brunk183f0562015-08-12 12:55:02 -07001907status_t Camera3Device::waitUntilStateThenRelock(bool active, nsecs_t timeout) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001908 status_t res = OK;
Ruben Brunk183f0562015-08-12 12:55:02 -07001909
1910 size_t startIndex = 0;
1911 if (mStatusWaiters == 0) {
1912 // Clear the list of recent statuses if there are no existing threads waiting on updates to
1913 // this status list
1914 mRecentStatusUpdates.clear();
1915 } else {
1916 // If other threads are waiting on updates to this status list, set the position of the
1917 // first element that this list will check rather than clearing the list.
1918 startIndex = mRecentStatusUpdates.size();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001919 }
1920
Ruben Brunk183f0562015-08-12 12:55:02 -07001921 mStatusWaiters++;
1922
Yin-Chia Yehe52b8fa2020-07-28 00:17:58 -07001923 bool signalPipelineDrain = false;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07001924 if (!active && mUseHalBufManager) {
1925 auto streamIds = mOutputStreams.getStreamIds();
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08001926 if (mStatus == STATUS_ACTIVE) {
1927 mRequestThread->signalPipelineDrain(streamIds);
Yin-Chia Yehe52b8fa2020-07-28 00:17:58 -07001928 signalPipelineDrain = true;
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08001929 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07001930 mRequestBufferSM.onWaitUntilIdle();
1931 }
1932
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001933 bool stateSeen = false;
1934 do {
Ruben Brunk183f0562015-08-12 12:55:02 -07001935 if (active == (mStatus == STATUS_ACTIVE)) {
1936 // Desired state is current
1937 break;
1938 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001939
1940 res = mStatusChanged.waitRelative(mLock, timeout);
1941 if (res != OK) break;
1942
Ruben Brunk183f0562015-08-12 12:55:02 -07001943 // This is impossible, but if not, could result in subtle deadlocks and invalid state
1944 // transitions.
1945 LOG_ALWAYS_FATAL_IF(startIndex > mRecentStatusUpdates.size(),
1946 "%s: Skipping status updates in Camera3Device, may result in deadlock.",
1947 __FUNCTION__);
1948
1949 // Encountered desired state since we began waiting
1950 for (size_t i = startIndex; i < mRecentStatusUpdates.size(); i++) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001951 if (active == (mRecentStatusUpdates[i] == STATUS_ACTIVE) ) {
1952 stateSeen = true;
1953 break;
1954 }
1955 }
1956 } while (!stateSeen);
1957
Yin-Chia Yehe52b8fa2020-07-28 00:17:58 -07001958 if (signalPipelineDrain) {
1959 mRequestThread->resetPipelineDrain();
1960 }
1961
Ruben Brunk183f0562015-08-12 12:55:02 -07001962 mStatusWaiters--;
1963
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001964 return res;
1965}
1966
1967
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001968status_t Camera3Device::setNotifyCallback(wp<NotificationListener> listener) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001969 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001970 std::lock_guard<std::mutex> l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001971
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001972 if (listener != NULL && mListener != NULL) {
1973 ALOGW("%s: Replacing old callback listener", __FUNCTION__);
1974 }
1975 mListener = listener;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001976 mRequestThread->setNotificationListener(listener);
1977 mPreparerThread->setNotificationListener(listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001978
1979 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001980}
1981
Eino-Ville Talvala46910bd2013-07-18 19:15:17 -07001982bool Camera3Device::willNotify3A() {
1983 return false;
1984}
1985
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001986status_t Camera3Device::waitForNextFrame(nsecs_t timeout) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07001987 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001988 std::unique_lock<std::mutex> l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001989
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001990 while (mResultQueue.empty()) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001991 auto st = mResultSignal.wait_for(l, std::chrono::nanoseconds(timeout));
1992 if (st == std::cv_status::timeout) {
1993 return TIMED_OUT;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001994 }
1995 }
1996 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001997}
1998
Jianing Weicb0652e2014-03-12 18:29:36 -07001999status_t Camera3Device::getNextResult(CaptureResult *frame) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002000 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002001 std::lock_guard<std::mutex> l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002002
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002003 if (mResultQueue.empty()) {
2004 return NOT_ENOUGH_DATA;
2005 }
2006
Jianing Weicb0652e2014-03-12 18:29:36 -07002007 if (frame == NULL) {
2008 ALOGE("%s: argument cannot be NULL", __FUNCTION__);
2009 return BAD_VALUE;
2010 }
2011
2012 CaptureResult &result = *(mResultQueue.begin());
2013 frame->mResultExtras = result.mResultExtras;
2014 frame->mMetadata.acquire(result.mMetadata);
Shuzhen Wang5c22c152017-12-31 17:12:25 -08002015 frame->mPhysicalMetadatas = std::move(result.mPhysicalMetadatas);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002016 mResultQueue.erase(mResultQueue.begin());
2017
2018 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002019}
2020
2021status_t Camera3Device::triggerAutofocus(uint32_t id) {
2022 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002023 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002024
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002025 ALOGV("%s: Triggering autofocus, id %d", __FUNCTION__, id);
2026 // Mix-in this trigger into the next request and only the next request.
2027 RequestTrigger trigger[] = {
2028 {
2029 ANDROID_CONTROL_AF_TRIGGER,
2030 ANDROID_CONTROL_AF_TRIGGER_START
2031 },
2032 {
2033 ANDROID_CONTROL_AF_TRIGGER_ID,
2034 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07002035 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002036 };
2037
2038 return mRequestThread->queueTrigger(trigger,
2039 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002040}
2041
2042status_t Camera3Device::triggerCancelAutofocus(uint32_t id) {
2043 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002044 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002045
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002046 ALOGV("%s: Triggering cancel autofocus, id %d", __FUNCTION__, id);
2047 // Mix-in this trigger into the next request and only the next request.
2048 RequestTrigger trigger[] = {
2049 {
2050 ANDROID_CONTROL_AF_TRIGGER,
2051 ANDROID_CONTROL_AF_TRIGGER_CANCEL
2052 },
2053 {
2054 ANDROID_CONTROL_AF_TRIGGER_ID,
2055 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07002056 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002057 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002058
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002059 return mRequestThread->queueTrigger(trigger,
2060 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002061}
2062
2063status_t Camera3Device::triggerPrecaptureMetering(uint32_t id) {
2064 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002065 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002066
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002067 ALOGV("%s: Triggering precapture metering, id %d", __FUNCTION__, id);
2068 // Mix-in this trigger into the next request and only the next request.
2069 RequestTrigger trigger[] = {
2070 {
2071 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER,
2072 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_START
2073 },
2074 {
2075 ANDROID_CONTROL_AE_PRECAPTURE_ID,
2076 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07002077 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002078 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002079
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002080 return mRequestThread->queueTrigger(trigger,
2081 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002082}
2083
Jianing Weicb0652e2014-03-12 18:29:36 -07002084status_t Camera3Device::flush(int64_t *frameNumber) {
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07002085 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002086 ALOGV("%s: Camera %s: Flushing all requests", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002087 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07002088
Zhijun He7ef20392014-04-21 16:04:17 -07002089 {
2090 Mutex::Autolock l(mLock);
Emilian Peeved2ebe42018-09-25 16:59:09 +01002091
2092 // b/116514106 "disconnect()" can get called twice for the same device. The
2093 // camera device will not be initialized during the second run.
2094 if (mStatus == STATUS_UNINITIALIZED) {
2095 return OK;
2096 }
2097
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002098 mRequestThread->clear(/*out*/frameNumber);
Shuzhen Wang316781a2020-08-18 18:11:01 -07002099
2100 // Stop session and stream counter
2101 mSessionStatsBuilder.stopCounter();
Zhijun He7ef20392014-04-21 16:04:17 -07002102 }
2103
Emilian Peev08dd2452017-04-06 16:55:14 +01002104 return mRequestThread->flush();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07002105}
2106
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002107status_t Camera3Device::prepare(int streamId) {
Ruben Brunkc78ac262015-08-13 17:58:46 -07002108 return prepare(camera3::Camera3StreamInterface::ALLOCATE_PIPELINE_MAX, streamId);
2109}
2110
2111status_t Camera3Device::prepare(int maxCount, int streamId) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002112 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002113 ALOGV("%s: Camera %s: Preparing stream %d", __FUNCTION__, mId.string(), streamId);
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07002114 Mutex::Autolock il(mInterfaceLock);
2115 Mutex::Autolock l(mLock);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002116
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002117 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
2118 if (stream == nullptr) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002119 CLOGE("Stream %d does not exist", streamId);
2120 return BAD_VALUE;
2121 }
2122
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002123 if (stream->isUnpreparable() || stream->hasOutstandingBuffers() ) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07002124 CLOGE("Stream %d has already been a request target", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002125 return BAD_VALUE;
2126 }
2127
2128 if (mRequestThread->isStreamPending(stream)) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07002129 CLOGE("Stream %d is already a target in a pending request", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002130 return BAD_VALUE;
2131 }
2132
Ruben Brunkc78ac262015-08-13 17:58:46 -07002133 return mPreparerThread->prepare(maxCount, stream);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002134}
2135
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002136status_t Camera3Device::tearDown(int streamId) {
2137 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002138 ALOGV("%s: Camera %s: Tearing down stream %d", __FUNCTION__, mId.string(), streamId);
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002139 Mutex::Autolock il(mInterfaceLock);
2140 Mutex::Autolock l(mLock);
2141
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002142 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
2143 if (stream == nullptr) {
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002144 CLOGE("Stream %d does not exist", streamId);
2145 return BAD_VALUE;
2146 }
2147
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002148 if (stream->hasOutstandingBuffers() || mRequestThread->isStreamPending(stream)) {
2149 CLOGE("Stream %d is a target of a in-progress request", streamId);
2150 return BAD_VALUE;
2151 }
2152
2153 return stream->tearDown();
2154}
2155
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002156status_t Camera3Device::addBufferListenerForStream(int streamId,
2157 wp<Camera3StreamBufferListener> listener) {
2158 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002159 ALOGV("%s: Camera %s: Adding buffer listener for stream %d", __FUNCTION__, mId.string(), streamId);
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002160 Mutex::Autolock il(mInterfaceLock);
2161 Mutex::Autolock l(mLock);
2162
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002163 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
2164 if (stream == nullptr) {
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002165 CLOGE("Stream %d does not exist", streamId);
2166 return BAD_VALUE;
2167 }
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002168 stream->addBufferListener(listener);
2169
2170 return OK;
2171}
2172
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002173/**
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002174 * Methods called by subclasses
2175 */
2176
2177void Camera3Device::notifyStatus(bool idle) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002178 ATRACE_CALL();
Shuzhen Wang316781a2020-08-18 18:11:01 -07002179 std::vector<int> streamIds;
2180 std::vector<hardware::CameraStreamStats> streamStats;
2181
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002182 {
2183 // Need mLock to safely update state and synchronize to current
2184 // state of methods in flight.
2185 Mutex::Autolock l(mLock);
2186 // We can get various system-idle notices from the status tracker
2187 // while starting up. Only care about them if we've actually sent
2188 // in some requests recently.
2189 if (mStatus != STATUS_ACTIVE && mStatus != STATUS_CONFIGURED) {
2190 return;
2191 }
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08002192 ALOGV("%s: Camera %s: Now %s, pauseState: %s", __FUNCTION__, mId.string(),
2193 idle ? "idle" : "active", mPauseStateNotify ? "true" : "false");
Ruben Brunk183f0562015-08-12 12:55:02 -07002194 internalUpdateStatusLocked(idle ? STATUS_CONFIGURED : STATUS_ACTIVE);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002195
2196 // Skip notifying listener if we're doing some user-transparent
2197 // state changes
2198 if (mPauseStateNotify) return;
Shuzhen Wang316781a2020-08-18 18:11:01 -07002199
2200 // Populate stream statistics in case of Idle
2201 if (idle) {
2202 for (size_t i = 0; i < mOutputStreams.size(); i++) {
2203 auto stream = mOutputStreams[i];
2204 if (stream.get() == nullptr) continue;
2205 streamIds.push_back(stream->getId());
2206 Camera3Stream* camera3Stream = Camera3Stream::cast(stream->asHalStream());
2207 int64_t usage = 0LL;
2208 if (camera3Stream != nullptr) {
2209 usage = camera3Stream->getUsage();
2210 }
2211 streamStats.emplace_back(stream->getWidth(), stream->getHeight(),
2212 stream->getFormat(), stream->getDataSpace(), usage,
2213 stream->getMaxHalBuffers(),
2214 stream->getMaxTotalBuffers() - stream->getMaxHalBuffers());
2215 }
2216 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002217 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002218
2219 sp<NotificationListener> listener;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002220 {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002221 std::lock_guard<std::mutex> l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002222 listener = mListener.promote();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002223 }
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07002224 status_t res = OK;
2225 if (listener != nullptr) {
2226 if (idle) {
2227 // Get session stats from the builder, and notify the listener.
2228 int64_t requestCount, resultErrorCount;
2229 bool deviceError;
2230 std::map<int, StreamStats> streamStatsMap;
2231 mSessionStatsBuilder.buildAndReset(&requestCount, &resultErrorCount,
2232 &deviceError, &streamStatsMap);
2233 for (size_t i = 0; i < streamIds.size(); i++) {
2234 int streamId = streamIds[i];
2235 auto stats = streamStatsMap.find(streamId);
2236 if (stats != streamStatsMap.end()) {
2237 streamStats[i].mRequestCount = stats->second.mRequestedFrameCount;
2238 streamStats[i].mErrorCount = stats->second.mDroppedFrameCount;
2239 streamStats[i].mStartLatencyMs = stats->second.mStartLatencyMs;
2240 streamStats[i].mHistogramType =
2241 hardware::CameraStreamStats::HISTOGRAM_TYPE_CAPTURE_LATENCY;
2242 streamStats[i].mHistogramBins.assign(
2243 stats->second.mCaptureLatencyBins.begin(),
2244 stats->second.mCaptureLatencyBins.end());
2245 streamStats[i].mHistogramCounts.assign(
2246 stats->second.mCaptureLatencyHistogram.begin(),
2247 stats->second.mCaptureLatencyHistogram.end());
2248 }
Shuzhen Wang316781a2020-08-18 18:11:01 -07002249 }
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07002250 listener->notifyIdle(requestCount, resultErrorCount, deviceError, streamStats);
2251 } else {
2252 res = listener->notifyActive();
Shuzhen Wang316781a2020-08-18 18:11:01 -07002253 }
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07002254 }
2255 if (res != OK) {
2256 SET_ERR("Camera access permission lost mid-operation: %s (%d)",
2257 strerror(-res), res);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002258 }
2259}
2260
Shuzhen Wang758c2152017-01-10 18:26:18 -08002261status_t Camera3Device::setConsumerSurfaces(int streamId,
Emilian Peev40ead602017-09-26 15:46:36 +01002262 const std::vector<sp<Surface>>& consumers, std::vector<int> *surfaceIds) {
Zhijun He5d677d12016-05-29 16:52:39 -07002263 ATRACE_CALL();
Shuzhen Wang758c2152017-01-10 18:26:18 -08002264 ALOGV("%s: Camera %s: set consumer surface for stream %d",
2265 __FUNCTION__, mId.string(), streamId);
Emilian Peev40ead602017-09-26 15:46:36 +01002266
2267 if (surfaceIds == nullptr) {
2268 return BAD_VALUE;
2269 }
2270
Zhijun He5d677d12016-05-29 16:52:39 -07002271 Mutex::Autolock il(mInterfaceLock);
2272 Mutex::Autolock l(mLock);
2273
Shuzhen Wang758c2152017-01-10 18:26:18 -08002274 if (consumers.size() == 0) {
2275 CLOGE("No consumer is passed!");
Zhijun He5d677d12016-05-29 16:52:39 -07002276 return BAD_VALUE;
2277 }
2278
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002279 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
2280 if (stream == nullptr) {
Zhijun He5d677d12016-05-29 16:52:39 -07002281 CLOGE("Stream %d is unknown", streamId);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002282 return BAD_VALUE;
Zhijun He5d677d12016-05-29 16:52:39 -07002283 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002284
2285 // isConsumerConfigurationDeferred will be off after setConsumers
2286 bool isDeferred = stream->isConsumerConfigurationDeferred();
Shuzhen Wang758c2152017-01-10 18:26:18 -08002287 status_t res = stream->setConsumers(consumers);
Zhijun He5d677d12016-05-29 16:52:39 -07002288 if (res != OK) {
2289 CLOGE("Stream %d set consumer failed (error %d %s) ", streamId, res, strerror(-res));
2290 return res;
2291 }
2292
Emilian Peev40ead602017-09-26 15:46:36 +01002293 for (auto &consumer : consumers) {
2294 int id = stream->getSurfaceId(consumer);
2295 if (id < 0) {
2296 CLOGE("Invalid surface id!");
2297 return BAD_VALUE;
2298 }
2299 surfaceIds->push_back(id);
2300 }
2301
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002302 if (isDeferred) {
Shuzhen Wang0129d522016-10-30 22:43:41 -07002303 if (!stream->isConfiguring()) {
2304 CLOGE("Stream %d was already fully configured.", streamId);
2305 return INVALID_OPERATION;
2306 }
Zhijun He5d677d12016-05-29 16:52:39 -07002307
Shuzhen Wang0129d522016-10-30 22:43:41 -07002308 res = stream->finishConfiguration();
2309 if (res != OK) {
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002310 // If finishConfiguration fails due to abandoned surface, do not set
2311 // device to error state.
2312 bool isSurfaceAbandoned =
2313 (res == NO_INIT || res == DEAD_OBJECT) && stream->isAbandoned();
2314 if (!isSurfaceAbandoned) {
2315 SET_ERR_L("Can't finish configuring output stream %d: %s (%d)",
2316 stream->getId(), strerror(-res), res);
2317 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07002318 return res;
2319 }
Zhijun He5d677d12016-05-29 16:52:39 -07002320 }
2321
2322 return OK;
2323}
2324
Emilian Peev40ead602017-09-26 15:46:36 +01002325status_t Camera3Device::updateStream(int streamId, const std::vector<sp<Surface>> &newSurfaces,
2326 const std::vector<OutputStreamInfo> &outputInfo,
2327 const std::vector<size_t> &removedSurfaceIds, KeyedVector<sp<Surface>, size_t> *outputMap) {
2328 Mutex::Autolock il(mInterfaceLock);
2329 Mutex::Autolock l(mLock);
2330
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002331 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
2332 if (stream == nullptr) {
Emilian Peev40ead602017-09-26 15:46:36 +01002333 CLOGE("Stream %d is unknown", streamId);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002334 return BAD_VALUE;
Emilian Peev40ead602017-09-26 15:46:36 +01002335 }
2336
2337 for (const auto &it : removedSurfaceIds) {
2338 if (mRequestThread->isOutputSurfacePending(streamId, it)) {
2339 CLOGE("Shared surface still part of a pending request!");
2340 return -EBUSY;
2341 }
2342 }
2343
Emilian Peev40ead602017-09-26 15:46:36 +01002344 status_t res = stream->updateStream(newSurfaces, outputInfo, removedSurfaceIds, outputMap);
2345 if (res != OK) {
2346 CLOGE("Stream %d failed to update stream (error %d %s) ",
2347 streamId, res, strerror(-res));
2348 if (res == UNKNOWN_ERROR) {
2349 SET_ERR_L("%s: Stream update failed to revert to previous output configuration!",
2350 __FUNCTION__);
2351 }
2352 return res;
2353 }
2354
2355 return res;
2356}
2357
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002358status_t Camera3Device::dropStreamBuffers(bool dropping, int streamId) {
2359 Mutex::Autolock il(mInterfaceLock);
2360 Mutex::Autolock l(mLock);
2361
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002362 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
2363 if (stream == nullptr) {
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002364 ALOGE("%s: Stream %d is not found.", __FUNCTION__, streamId);
2365 return BAD_VALUE;
2366 }
Shuzhen Wang316781a2020-08-18 18:11:01 -07002367
2368 if (dropping) {
2369 mSessionStatsBuilder.stopCounter(streamId);
2370 } else {
2371 mSessionStatsBuilder.startCounter(streamId);
2372 }
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002373 return stream->dropBuffers(dropping);
2374}
2375
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002376/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002377 * Camera3Device private methods
2378 */
2379
2380sp<Camera3Device::CaptureRequest> Camera3Device::createCaptureRequest(
Emilian Peevaebbe412018-01-15 13:53:24 +00002381 const PhysicalCameraSettingsList &request, const SurfaceMap &surfaceMap) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002382 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002383
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08002384 sp<CaptureRequest> newRequest = new CaptureRequest();
Emilian Peevaebbe412018-01-15 13:53:24 +00002385 newRequest->mSettingsList = request;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002386
2387 camera_metadata_entry_t inputStreams =
Emilian Peevaebbe412018-01-15 13:53:24 +00002388 newRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_INPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002389 if (inputStreams.count > 0) {
2390 if (mInputStream == NULL ||
Zhijun Hed1d64672013-09-06 15:00:01 -07002391 mInputStream->getId() != inputStreams.data.i32[0]) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002392 CLOGE("Request references unknown input stream %d",
2393 inputStreams.data.u8[0]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002394 return NULL;
2395 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002396
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002397 if (mInputStream->isConfiguring()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002398 SET_ERR_L("%s: input stream %d is not configured!",
2399 __FUNCTION__, mInputStream->getId());
2400 return NULL;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002401 }
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07002402 // Check if stream prepare is blocking requests.
2403 if (mInputStream->isBlockedByPrepare()) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002404 CLOGE("Request references an input stream that's being prepared!");
2405 return NULL;
2406 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002407
2408 newRequest->mInputStream = mInputStream;
Emilian Peevaebbe412018-01-15 13:53:24 +00002409 newRequest->mSettingsList.begin()->metadata.erase(ANDROID_REQUEST_INPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002410 }
2411
2412 camera_metadata_entry_t streams =
Emilian Peevaebbe412018-01-15 13:53:24 +00002413 newRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_OUTPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002414 if (streams.count == 0) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002415 CLOGE("Zero output streams specified!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002416 return NULL;
2417 }
2418
2419 for (size_t i = 0; i < streams.count; i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002420 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streams.data.i32[i]);
2421 if (stream == nullptr) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002422 CLOGE("Request references unknown stream %d",
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002423 streams.data.i32[i]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002424 return NULL;
2425 }
Zhijun He5d677d12016-05-29 16:52:39 -07002426 // It is illegal to include a deferred consumer output stream into a request
Shuzhen Wang0129d522016-10-30 22:43:41 -07002427 auto iter = surfaceMap.find(streams.data.i32[i]);
2428 if (iter != surfaceMap.end()) {
2429 const std::vector<size_t>& surfaces = iter->second;
2430 for (const auto& surface : surfaces) {
2431 if (stream->isConsumerConfigurationDeferred(surface)) {
2432 CLOGE("Stream %d surface %zu hasn't finished configuration yet "
2433 "due to deferred consumer", stream->getId(), surface);
2434 return NULL;
2435 }
2436 }
Yin-Chia Yeh0b287572018-10-15 12:38:13 -07002437 newRequest->mOutputSurfaces[streams.data.i32[i]] = surfaces;
Zhijun He5d677d12016-05-29 16:52:39 -07002438 }
2439
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002440 if (stream->isConfiguring()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002441 SET_ERR_L("%s: stream %d is not configured!", __FUNCTION__, stream->getId());
2442 return NULL;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002443 }
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07002444 // Check if stream prepare is blocking requests.
2445 if (stream->isBlockedByPrepare()) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002446 CLOGE("Request references an output stream that's being prepared!");
2447 return NULL;
2448 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002449
2450 newRequest->mOutputStreams.push(stream);
2451 }
Emilian Peevaebbe412018-01-15 13:53:24 +00002452 newRequest->mSettingsList.begin()->metadata.erase(ANDROID_REQUEST_OUTPUT_STREAMS);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07002453 newRequest->mBatchSize = 1;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002454
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08002455 auto rotateAndCropEntry =
2456 newRequest->mSettingsList.begin()->metadata.find(ANDROID_SCALER_ROTATE_AND_CROP);
2457 if (rotateAndCropEntry.count > 0 &&
2458 rotateAndCropEntry.data.u8[0] == ANDROID_SCALER_ROTATE_AND_CROP_AUTO) {
2459 newRequest->mRotateAndCropAuto = true;
2460 } else {
2461 newRequest->mRotateAndCropAuto = false;
2462 }
2463
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07002464 auto zoomRatioEntry =
2465 newRequest->mSettingsList.begin()->metadata.find(ANDROID_CONTROL_ZOOM_RATIO);
2466 if (zoomRatioEntry.count > 0 &&
2467 zoomRatioEntry.data.f[0] == 1.0f) {
2468 newRequest->mZoomRatioIs1x = true;
2469 } else {
2470 newRequest->mZoomRatioIs1x = false;
2471 }
2472
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08002473 if (mSupportCameraMute) {
Shuzhen Wang911c6a32021-10-27 13:36:03 -07002474 for (auto& settings : newRequest->mSettingsList) {
2475 auto testPatternModeEntry =
2476 settings.metadata.find(ANDROID_SENSOR_TEST_PATTERN_MODE);
2477 settings.mOriginalTestPatternMode = testPatternModeEntry.count > 0 ?
2478 testPatternModeEntry.data.i32[0] :
2479 ANDROID_SENSOR_TEST_PATTERN_MODE_OFF;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08002480
Shuzhen Wang911c6a32021-10-27 13:36:03 -07002481 auto testPatternDataEntry =
2482 settings.metadata.find(ANDROID_SENSOR_TEST_PATTERN_DATA);
2483 if (testPatternDataEntry.count >= 4) {
2484 memcpy(settings.mOriginalTestPatternData, testPatternDataEntry.data.i32,
2485 sizeof(PhysicalCameraSettings::mOriginalTestPatternData));
2486 } else {
2487 settings.mOriginalTestPatternData[0] = 0;
2488 settings.mOriginalTestPatternData[1] = 0;
2489 settings.mOriginalTestPatternData[2] = 0;
2490 settings.mOriginalTestPatternData[3] = 0;
2491 }
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08002492 }
2493 }
2494
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002495 return newRequest;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002496}
2497
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002498void Camera3Device::cancelStreamsConfigurationLocked() {
2499 int res = OK;
2500 if (mInputStream != NULL && mInputStream->isConfiguring()) {
2501 res = mInputStream->cancelConfiguration();
2502 if (res != OK) {
2503 CLOGE("Can't cancel configuring input stream %d: %s (%d)",
2504 mInputStream->getId(), strerror(-res), res);
2505 }
2506 }
2507
2508 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002509 sp<Camera3OutputStreamInterface> outputStream = mOutputStreams[i];
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002510 if (outputStream->isConfiguring()) {
2511 res = outputStream->cancelConfiguration();
2512 if (res != OK) {
2513 CLOGE("Can't cancel configuring output stream %d: %s (%d)",
2514 outputStream->getId(), strerror(-res), res);
2515 }
2516 }
2517 }
2518
2519 // Return state to that at start of call, so that future configures
2520 // properly clean things up
2521 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
2522 mNeedConfig = true;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002523
2524 res = mPreparerThread->resume();
2525 if (res != OK) {
2526 ALOGE("%s: Camera %s: Preparer thread failed to resume!", __FUNCTION__, mId.string());
2527 }
2528}
2529
Emilian Peev0d0191e2020-04-21 17:01:18 -07002530bool Camera3Device::checkAbandonedStreamsLocked() {
2531 if ((mInputStream.get() != nullptr) && (mInputStream->isAbandoned())) {
2532 return true;
2533 }
2534
2535 for (size_t i = 0; i < mOutputStreams.size(); i++) {
2536 auto stream = mOutputStreams[i];
2537 if ((stream.get() != nullptr) && (stream->isAbandoned())) {
2538 return true;
2539 }
2540 }
2541
2542 return false;
2543}
2544
Emilian Peev3bead5f2020-05-28 17:29:08 -07002545bool Camera3Device::reconfigureCamera(const CameraMetadata& sessionParams, int clientStatusId) {
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002546 ATRACE_CALL();
2547 bool ret = false;
2548
Shuzhen Wang316781a2020-08-18 18:11:01 -07002549 nsecs_t startTime = systemTime();
2550
Jayant Chowdhary646c31b2020-01-30 13:09:59 -08002551 Mutex::Autolock il(mInterfaceLock);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002552 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
2553
2554 Mutex::Autolock l(mLock);
Emilian Peev0d0191e2020-04-21 17:01:18 -07002555 if (checkAbandonedStreamsLocked()) {
2556 ALOGW("%s: Abandoned stream detected, session parameters can't be applied correctly!",
2557 __FUNCTION__);
2558 return true;
2559 }
2560
Emilian Peev3bead5f2020-05-28 17:29:08 -07002561 status_t rc = NO_ERROR;
2562 bool markClientActive = false;
2563 if (mStatus == STATUS_ACTIVE) {
2564 markClientActive = true;
2565 mPauseStateNotify = true;
2566 mStatusTracker->markComponentIdle(clientStatusId, Fence::NO_FENCE);
2567
2568 rc = internalPauseAndWaitLocked(maxExpectedDuration);
2569 }
2570
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002571 if (rc == NO_ERROR) {
2572 mNeedConfig = true;
2573 rc = configureStreamsLocked(mOperatingMode, sessionParams, /*notifyRequestThread*/ false);
2574 if (rc == NO_ERROR) {
2575 ret = true;
2576 mPauseStateNotify = false;
2577 //Moving to active state while holding 'mLock' is important.
2578 //There could be pending calls to 'create-/deleteStream' which
2579 //will trigger another stream configuration while the already
2580 //present streams end up with outstanding buffers that will
2581 //not get drained.
2582 internalUpdateStatusLocked(STATUS_ACTIVE);
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002583 } else if (rc == DEAD_OBJECT) {
2584 // DEAD_OBJECT can be returned if either the consumer surface is
2585 // abandoned, or the HAL has died.
2586 // - If the HAL has died, configureStreamsLocked call will set
2587 // device to error state,
2588 // - If surface is abandoned, we should not set device to error
2589 // state.
2590 ALOGE("Failed to re-configure camera due to abandoned surface");
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002591 } else {
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002592 SET_ERR_L("Failed to re-configure camera: %d", rc);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002593 }
2594 } else {
2595 ALOGE("%s: Failed to pause streaming: %d", __FUNCTION__, rc);
2596 }
2597
Shuzhen Wang316781a2020-08-18 18:11:01 -07002598 CameraServiceProxyWrapper::logStreamConfigured(mId, mOperatingMode, true /*internalReconfig*/,
2599 ns2ms(systemTime() - startTime));
2600
Emilian Peev3bead5f2020-05-28 17:29:08 -07002601 if (markClientActive) {
2602 mStatusTracker->markComponentActive(clientStatusId);
2603 }
2604
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002605 return ret;
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002606}
2607
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002608status_t Camera3Device::configureStreamsLocked(int operatingMode,
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002609 const CameraMetadata& sessionParams, bool notifyRequestThread) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002610 ATRACE_CALL();
2611 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002612
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002613 if (mStatus != STATUS_UNCONFIGURED && mStatus != STATUS_CONFIGURED) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002614 CLOGE("Not idle");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002615 return INVALID_OPERATION;
2616 }
2617
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08002618 if (operatingMode < 0) {
2619 CLOGE("Invalid operating mode: %d", operatingMode);
2620 return BAD_VALUE;
2621 }
2622
2623 bool isConstrainedHighSpeed =
2624 static_cast<int>(StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE) ==
2625 operatingMode;
2626
2627 if (mOperatingMode != operatingMode) {
2628 mNeedConfig = true;
2629 mIsConstrainedHighSpeedConfiguration = isConstrainedHighSpeed;
2630 mOperatingMode = operatingMode;
2631 }
2632
Shuzhen Wang0cf01cb2019-09-05 13:33:06 -07002633 // In case called from configureStreams, abort queued input buffers not belonging to
2634 // any pending requests.
2635 if (mInputStream != NULL && notifyRequestThread) {
2636 while (true) {
Emilian Peevf4816702020-04-03 15:44:51 -07002637 camera_stream_buffer_t inputBuffer;
Shuzhen Wang83bff122020-11-20 15:51:39 -08002638 camera3::Size inputBufferSize;
Shuzhen Wang0cf01cb2019-09-05 13:33:06 -07002639 status_t res = mInputStream->getInputBuffer(&inputBuffer,
Shuzhen Wang83bff122020-11-20 15:51:39 -08002640 &inputBufferSize, /*respectHalLimit*/ false);
Shuzhen Wang0cf01cb2019-09-05 13:33:06 -07002641 if (res != OK) {
2642 // Exhausted acquiring all input buffers.
2643 break;
2644 }
2645
Emilian Peevf4816702020-04-03 15:44:51 -07002646 inputBuffer.status = CAMERA_BUFFER_STATUS_ERROR;
Shuzhen Wang0cf01cb2019-09-05 13:33:06 -07002647 res = mInputStream->returnInputBuffer(inputBuffer);
2648 if (res != OK) {
2649 ALOGE("%s: %d: couldn't return input buffer while clearing input queue: "
2650 "%s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
2651 }
2652 }
2653 }
2654
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002655 if (!mNeedConfig) {
2656 ALOGV("%s: Skipping config, no stream changes", __FUNCTION__);
2657 return OK;
2658 }
2659
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002660 // Workaround for device HALv3.2 or older spec bug - zero streams requires
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002661 // adding a fake stream instead.
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002662 // TODO: Bug: 17321404 for fixing the HAL spec and removing this workaround.
2663 if (mOutputStreams.size() == 0) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002664 addFakeStreamLocked();
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002665 } else {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002666 tryRemoveFakeStreamLocked();
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002667 }
2668
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002669 // Start configuring the streams
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002670 ALOGV("%s: Camera %s: Starting stream configuration", __FUNCTION__, mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002671
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002672 mPreparerThread->pause();
2673
Emilian Peevf4816702020-04-03 15:44:51 -07002674 camera_stream_configuration config;
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -08002675 config.operation_mode = mOperatingMode;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002676 config.num_streams = (mInputStream != NULL) + mOutputStreams.size();
Shuzhen Wang83bff122020-11-20 15:51:39 -08002677 config.input_is_multi_resolution = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002678
Emilian Peevf4816702020-04-03 15:44:51 -07002679 Vector<camera3::camera_stream_t*> streams;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002680 streams.setCapacity(config.num_streams);
Emilian Peev192ee832018-01-31 14:46:47 +00002681 std::vector<uint32_t> bufferSizes(config.num_streams, 0);
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002682
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002683
2684 if (mInputStream != NULL) {
Emilian Peevf4816702020-04-03 15:44:51 -07002685 camera3::camera_stream_t *inputStream;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002686 inputStream = mInputStream->startConfiguration();
2687 if (inputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002688 CLOGE("Can't start input stream configuration");
2689 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002690 return INVALID_OPERATION;
2691 }
2692 streams.add(inputStream);
Shuzhen Wang83bff122020-11-20 15:51:39 -08002693
2694 config.input_is_multi_resolution = mIsInputStreamMultiResolution;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002695 }
2696
Shuzhen Wang99080502021-03-07 21:08:20 -08002697 mGroupIdPhysicalCameraMap.clear();
Emilian Peeve23f1d92021-09-20 14:56:01 -07002698 bool composerSurfacePresent = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002699 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Igor Murashkin2fba5842013-04-22 14:03:54 -07002700
2701 // Don't configure bidi streams twice, nor add them twice to the list
2702 if (mOutputStreams[i].get() ==
2703 static_cast<Camera3StreamInterface*>(mInputStream.get())) {
2704
2705 config.num_streams--;
2706 continue;
2707 }
2708
Emilian Peevf4816702020-04-03 15:44:51 -07002709 camera3::camera_stream_t *outputStream;
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002710 outputStream = mOutputStreams[i]->startConfiguration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002711 if (outputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002712 CLOGE("Can't start output stream configuration");
2713 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002714 return INVALID_OPERATION;
2715 }
2716 streams.add(outputStream);
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002717
Shuzhen Wangb7ab1e42019-02-20 15:42:23 -08002718 if (outputStream->format == HAL_PIXEL_FORMAT_BLOB) {
Emilian Peev192ee832018-01-31 14:46:47 +00002719 size_t k = i + ((mInputStream != nullptr) ? 1 : 0); // Input stream if present should
2720 // always occupy the initial entry.
Shuzhen Wangb7ab1e42019-02-20 15:42:23 -08002721 if (outputStream->data_space == HAL_DATASPACE_V0_JFIF) {
2722 bufferSizes[k] = static_cast<uint32_t>(
2723 getJpegBufferSize(outputStream->width, outputStream->height));
2724 } else if (outputStream->data_space ==
2725 static_cast<android_dataspace>(HAL_DATASPACE_JPEG_APP_SEGMENTS)) {
2726 bufferSizes[k] = outputStream->width * outputStream->height;
2727 } else {
2728 ALOGW("%s: Blob dataSpace %d not supported",
2729 __FUNCTION__, outputStream->data_space);
2730 }
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002731 }
Shuzhen Wang99080502021-03-07 21:08:20 -08002732
2733 if (mOutputStreams[i]->isMultiResolution()) {
2734 int32_t streamGroupId = mOutputStreams[i]->getHalStreamGroupId();
2735 const String8& physicalCameraId = mOutputStreams[i]->getPhysicalCameraId();
2736 mGroupIdPhysicalCameraMap[streamGroupId].insert(physicalCameraId);
2737 }
Emilian Peeve23f1d92021-09-20 14:56:01 -07002738
2739 if (outputStream->usage & GraphicBuffer::USAGE_HW_COMPOSER) {
2740 composerSurfacePresent = true;
2741 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002742 }
2743
2744 config.streams = streams.editArray();
2745
2746 // Do the HAL configuration; will potentially touch stream
Shuzhen Wang92653952019-05-07 15:11:43 -07002747 // max_buffers, usage, and priv fields, as well as data_space and format
2748 // fields for IMPLEMENTATION_DEFINED formats.
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002749
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002750 const camera_metadata_t *sessionBuffer = sessionParams.getAndLock();
Emilian Peev192ee832018-01-31 14:46:47 +00002751 res = mInterface->configureStreams(sessionBuffer, &config, bufferSizes);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002752 sessionParams.unlock(sessionBuffer);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002753
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002754 if (res == BAD_VALUE) {
2755 // HAL rejected this set of streams as unsupported, clean up config
2756 // attempt and return to unconfigured state
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002757 CLOGE("Set of requested inputs/outputs not supported by HAL");
2758 cancelStreamsConfigurationLocked();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002759 return BAD_VALUE;
2760 } else if (res != OK) {
2761 // Some other kind of error from configure_streams - this is not
2762 // expected
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002763 SET_ERR_L("Unable to configure streams with HAL: %s (%d)",
2764 strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002765 return res;
2766 }
2767
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002768 // Finish all stream configuration immediately.
2769 // TODO: Try to relax this later back to lazy completion, which should be
2770 // faster
2771
Igor Murashkin073f8572013-05-02 14:59:28 -07002772 if (mInputStream != NULL && mInputStream->isConfiguring()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002773 bool streamReConfigured = false;
2774 res = mInputStream->finishConfiguration(&streamReConfigured);
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002775 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002776 CLOGE("Can't finish configuring input stream %d: %s (%d)",
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002777 mInputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002778 cancelStreamsConfigurationLocked();
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002779 if ((res == NO_INIT || res == DEAD_OBJECT) && mInputStream->isAbandoned()) {
2780 return DEAD_OBJECT;
2781 }
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002782 return BAD_VALUE;
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002783 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002784 if (streamReConfigured) {
2785 mInterface->onStreamReConfigured(mInputStream->getId());
2786 }
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002787 }
2788
2789 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002790 sp<Camera3OutputStreamInterface> outputStream = mOutputStreams[i];
Zhijun He5d677d12016-05-29 16:52:39 -07002791 if (outputStream->isConfiguring() && !outputStream->isConsumerConfigurationDeferred()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002792 bool streamReConfigured = false;
2793 res = outputStream->finishConfiguration(&streamReConfigured);
Igor Murashkin073f8572013-05-02 14:59:28 -07002794 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002795 CLOGE("Can't finish configuring output stream %d: %s (%d)",
Igor Murashkin073f8572013-05-02 14:59:28 -07002796 outputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002797 cancelStreamsConfigurationLocked();
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002798 if ((res == NO_INIT || res == DEAD_OBJECT) && outputStream->isAbandoned()) {
2799 return DEAD_OBJECT;
2800 }
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002801 return BAD_VALUE;
Igor Murashkin073f8572013-05-02 14:59:28 -07002802 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002803 if (streamReConfigured) {
2804 mInterface->onStreamReConfigured(outputStream->getId());
2805 }
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002806 }
2807 }
2808
Emilian Peeve23f1d92021-09-20 14:56:01 -07002809 mRequestThread->setComposerSurface(composerSurfacePresent);
2810
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002811 // Request thread needs to know to avoid using repeat-last-settings protocol
2812 // across configure_streams() calls
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002813 if (notifyRequestThread) {
Shuzhen Wang99080502021-03-07 21:08:20 -08002814 mRequestThread->configurationComplete(mIsConstrainedHighSpeedConfiguration,
2815 sessionParams, mGroupIdPhysicalCameraMap);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002816 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002817
Zhijun He90f7c372016-08-16 16:19:43 -07002818 char value[PROPERTY_VALUE_MAX];
2819 property_get("camera.fifo.disable", value, "0");
2820 int32_t disableFifo = atoi(value);
2821 if (disableFifo != 1) {
2822 // Boost priority of request thread to SCHED_FIFO.
2823 pid_t requestThreadTid = mRequestThread->getTid();
2824 res = requestPriority(getpid(), requestThreadTid,
Mikhail Naganov83f04272017-02-07 10:45:09 -08002825 kRequestThreadPriority, /*isForApp*/ false, /*asynchronous*/ false);
Zhijun He90f7c372016-08-16 16:19:43 -07002826 if (res != OK) {
2827 ALOGW("Can't set realtime priority for request processing thread: %s (%d)",
2828 strerror(-res), res);
2829 } else {
2830 ALOGD("Set real time priority for request queue thread (tid %d)", requestThreadTid);
2831 }
Eino-Ville Talvalaf99498e2015-09-25 16:52:55 -07002832 }
2833
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002834 // Update device state
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002835 const camera_metadata_t *newSessionParams = sessionParams.getAndLock();
2836 const camera_metadata_t *currentSessionParams = mSessionParams.getAndLock();
2837 bool updateSessionParams = (newSessionParams != currentSessionParams) ? true : false;
2838 sessionParams.unlock(newSessionParams);
2839 mSessionParams.unlock(currentSessionParams);
2840 if (updateSessionParams) {
2841 mSessionParams = sessionParams;
2842 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002843
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002844 mNeedConfig = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002845
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002846 internalUpdateStatusLocked((mFakeStreamId == NO_STREAM) ?
Ruben Brunk183f0562015-08-12 12:55:02 -07002847 STATUS_CONFIGURED : STATUS_UNCONFIGURED);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002848
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002849 ALOGV("%s: Camera %s: Stream configuration complete", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002850
Zhijun He0a210512014-07-24 13:45:15 -07002851 // tear down the deleted streams after configure streams.
2852 mDeletedStreams.clear();
2853
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002854 auto rc = mPreparerThread->resume();
2855 if (rc != OK) {
2856 SET_ERR_L("%s: Camera %s: Preparer thread failed to resume!", __FUNCTION__, mId.string());
2857 return rc;
2858 }
2859
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002860 if (mFakeStreamId == NO_STREAM) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07002861 mRequestBufferSM.onStreamsConfigured();
2862 }
2863
Cliff Wu3b268182021-07-06 15:44:43 +08002864 // First call injectCamera() and then run configureStreamsLocked() case:
Cliff Wuc2ad9c82021-04-21 00:58:58 +08002865 // Since the streams configuration of the injection camera is based on the internal camera, we
Cliff Wu3b268182021-07-06 15:44:43 +08002866 // must wait until the internal camera configure streams before running the injection job to
Cliff Wuc2ad9c82021-04-21 00:58:58 +08002867 // configure the injection streams.
2868 if (mInjectionMethods->isInjecting()) {
Cliff Wu3b268182021-07-06 15:44:43 +08002869 ALOGD("%s: Injection camera %s: Start to configure streams.",
Cliff Wuc2ad9c82021-04-21 00:58:58 +08002870 __FUNCTION__, mInjectionMethods->getInjectedCamId().string());
2871 res = mInjectionMethods->injectCamera(config, bufferSizes);
2872 if (res != OK) {
2873 ALOGE("Can't finish inject camera process!");
2874 return res;
2875 }
Cliff Wu3b268182021-07-06 15:44:43 +08002876 } else {
2877 // First run configureStreamsLocked() and then call injectCamera() case:
2878 // If the stream configuration has been completed and camera deive is active, but the
2879 // injection camera has not been injected yet, we need to store the stream configuration of
2880 // the internal camera (because the stream configuration of the injection camera is based
2881 // on the internal camera). When injecting occurs later, this configuration can be used by
2882 // the injection camera.
2883 ALOGV("%s: The stream configuration is complete and the camera device is active, but the"
2884 " injection camera has not been injected yet.", __FUNCTION__);
2885 mInjectionMethods->storeInjectionConfig(config, bufferSizes);
Cliff Wuc2ad9c82021-04-21 00:58:58 +08002886 }
2887
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002888 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002889}
2890
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002891status_t Camera3Device::addFakeStreamLocked() {
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002892 ATRACE_CALL();
2893 status_t res;
2894
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002895 if (mFakeStreamId != NO_STREAM) {
2896 // Should never be adding a second fake stream when one is already
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002897 // active
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002898 SET_ERR_L("%s: Camera %s: A fake stream already exists!",
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002899 __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002900 return INVALID_OPERATION;
2901 }
2902
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002903 ALOGV("%s: Camera %s: Adding a fake stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002904
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002905 sp<Camera3OutputStreamInterface> fakeStream =
2906 new Camera3FakeStream(mNextStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002907
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002908 res = mOutputStreams.add(mNextStreamId, fakeStream);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002909 if (res < 0) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002910 SET_ERR_L("Can't add fake stream to set: %s (%d)", strerror(-res), res);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002911 return res;
2912 }
2913
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002914 mFakeStreamId = mNextStreamId;
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002915 mNextStreamId++;
2916
2917 return OK;
2918}
2919
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002920status_t Camera3Device::tryRemoveFakeStreamLocked() {
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002921 ATRACE_CALL();
2922 status_t res;
2923
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002924 if (mFakeStreamId == NO_STREAM) return OK;
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002925 if (mOutputStreams.size() == 1) return OK;
2926
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002927 ALOGV("%s: Camera %s: Removing the fake stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002928
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002929 // Ok, have a fake stream and there's at least one other output stream,
2930 // so remove the fake
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002931
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002932 sp<Camera3StreamInterface> deletedStream = mOutputStreams.get(mFakeStreamId);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002933 if (deletedStream == nullptr) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002934 SET_ERR_L("Fake stream %d does not appear to exist", mFakeStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002935 return INVALID_OPERATION;
2936 }
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002937 mOutputStreams.remove(mFakeStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002938
2939 // Free up the stream endpoint so that it can be used by some other stream
2940 res = deletedStream->disconnect();
2941 if (res != OK) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002942 SET_ERR_L("Can't disconnect deleted fake stream %d", mFakeStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002943 // fall through since we want to still list the stream as deleted.
2944 }
2945 mDeletedStreams.add(deletedStream);
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002946 mFakeStreamId = NO_STREAM;
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002947
2948 return res;
2949}
2950
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002951void Camera3Device::setErrorState(const char *fmt, ...) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002952 ATRACE_CALL();
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002953 Mutex::Autolock l(mLock);
2954 va_list args;
2955 va_start(args, fmt);
2956
2957 setErrorStateLockedV(fmt, args);
2958
2959 va_end(args);
2960}
2961
2962void Camera3Device::setErrorStateV(const char *fmt, va_list args) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002963 ATRACE_CALL();
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002964 Mutex::Autolock l(mLock);
2965 setErrorStateLockedV(fmt, args);
2966}
2967
2968void Camera3Device::setErrorStateLocked(const char *fmt, ...) {
2969 va_list args;
2970 va_start(args, fmt);
2971
2972 setErrorStateLockedV(fmt, args);
2973
2974 va_end(args);
2975}
2976
2977void Camera3Device::setErrorStateLockedV(const char *fmt, va_list args) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002978 // Print out all error messages to log
2979 String8 errorCause = String8::formatV(fmt, args);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002980 ALOGE("Camera %s: %s", mId.string(), errorCause.string());
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002981
2982 // But only do error state transition steps for the first error
Zhijun Heb05eeae2013-06-06 13:51:22 -07002983 if (mStatus == STATUS_ERROR || mStatus == STATUS_UNINITIALIZED) return;
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002984
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002985 mErrorCause = errorCause;
2986
Yin-Chia Yeh3d145ae2017-07-27 12:47:03 -07002987 if (mRequestThread != nullptr) {
2988 mRequestThread->setPaused(true);
2989 }
Ruben Brunk183f0562015-08-12 12:55:02 -07002990 internalUpdateStatusLocked(STATUS_ERROR);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002991
2992 // Notify upstream about a device error
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002993 sp<NotificationListener> listener = mListener.promote();
2994 if (listener != NULL) {
2995 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002996 CaptureResultExtras());
Shuzhen Wang316781a2020-08-18 18:11:01 -07002997 mSessionStatsBuilder.onDeviceError();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002998 }
2999
3000 // Save stack trace. View by dumping it later.
3001 CameraTraces::saveTrace();
3002 // TODO: consider adding errorCause and client pid/procname
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07003003}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003004
3005/**
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003006 * In-flight request management
3007 */
3008
Jianing Weicb0652e2014-03-12 18:29:36 -07003009status_t Camera3Device::registerInFlight(uint32_t frameNumber,
Chien-Yu Chend196d612015-06-22 19:49:01 -07003010 int32_t numBuffers, CaptureResultExtras resultExtras, bool hasInput,
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003011 bool hasAppCallback, nsecs_t maxExpectedDuration,
Shuzhen Wang99080502021-03-07 21:08:20 -08003012 const std::set<std::set<String8>>& physicalCameraIds,
3013 bool isStillCapture, bool isZslCapture, bool rotateAndCropAuto,
3014 const std::set<std::string>& cameraIdsWithZoom,
Shuzhen Wang316781a2020-08-18 18:11:01 -07003015 const SurfaceMap& outputSurfaces, nsecs_t requestTimeNs) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003016 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003017 std::lock_guard<std::mutex> l(mInFlightLock);
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003018
3019 ssize_t res;
Chien-Yu Chend196d612015-06-22 19:49:01 -07003020 res = mInFlightMap.add(frameNumber, InFlightRequest(numBuffers, resultExtras, hasInput,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003021 hasAppCallback, maxExpectedDuration, physicalCameraIds, isStillCapture, isZslCapture,
Shuzhen Wang316781a2020-08-18 18:11:01 -07003022 rotateAndCropAuto, cameraIdsWithZoom, requestTimeNs, outputSurfaces));
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003023 if (res < 0) return res;
3024
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07003025 if (mInFlightMap.size() == 1) {
Emilian Peev26d975d2018-07-05 14:52:57 +01003026 // Hold a separate dedicated tracker lock to prevent race with disconnect and also
3027 // avoid a deadlock during reprocess requests.
3028 Mutex::Autolock l(mTrackerLock);
Yin-Chia Yeh38dfde52017-06-27 17:13:33 -07003029 if (mStatusTracker != nullptr) {
3030 mStatusTracker->markComponentActive(mInFlightStatusId);
3031 }
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07003032 }
3033
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003034 mExpectedInflightDuration += maxExpectedDuration;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003035 return OK;
3036}
3037
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003038void Camera3Device::onInflightEntryRemovedLocked(nsecs_t duration) {
Shuzhen Wangcadb3302016-11-04 14:17:56 -07003039 // Indicate idle inFlightMap to the status tracker
3040 if (mInFlightMap.size() == 0) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07003041 mRequestBufferSM.onInflightMapEmpty();
Emilian Peev26d975d2018-07-05 14:52:57 +01003042 // Hold a separate dedicated tracker lock to prevent race with disconnect and also
3043 // avoid a deadlock during reprocess requests.
3044 Mutex::Autolock l(mTrackerLock);
Yin-Chia Yeh38dfde52017-06-27 17:13:33 -07003045 if (mStatusTracker != nullptr) {
3046 mStatusTracker->markComponentIdle(mInFlightStatusId, Fence::NO_FENCE);
3047 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07003048 }
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003049 mExpectedInflightDuration -= duration;
Shuzhen Wangcadb3302016-11-04 14:17:56 -07003050}
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003051
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003052void Camera3Device::checkInflightMapLengthLocked() {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04003053 // Validation check - if we have too many in-flight frames with long total inflight duration,
Yin-Chia Yeh99fd0972019-06-27 14:22:44 -07003054 // something has likely gone wrong. This might still be legit only if application send in
3055 // a long burst of long exposure requests.
3056 if (mExpectedInflightDuration > kMinWarnInflightDuration) {
3057 if (!mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() > kInFlightWarnLimit) {
3058 CLOGW("In-flight list too large: %zu, total inflight duration %" PRIu64,
3059 mInFlightMap.size(), mExpectedInflightDuration);
3060 } else if (mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() >
3061 kInFlightWarnLimitHighSpeed) {
3062 CLOGW("In-flight list too large for high speed configuration: %zu,"
3063 "total inflight duration %" PRIu64,
3064 mInFlightMap.size(), mExpectedInflightDuration);
3065 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003066 }
3067}
3068
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003069void Camera3Device::onInflightMapFlushedLocked() {
3070 mExpectedInflightDuration = 0;
3071}
3072
3073void Camera3Device::removeInFlightMapEntryLocked(int idx) {
Jayant Chowdharyd4776262020-06-23 23:45:57 -07003074 ATRACE_HFR_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003075 nsecs_t duration = mInFlightMap.valueAt(idx).maxExpectedDuration;
3076 mInFlightMap.removeItemsAt(idx, 1);
3077
3078 onInflightEntryRemovedLocked(duration);
3079}
3080
3081
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003082void Camera3Device::flushInflightRequests() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003083 ATRACE_CALL();
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003084 sp<NotificationListener> listener;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003085 {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003086 std::lock_guard<std::mutex> l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003087 listener = mListener.promote();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003088 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003089
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003090 FlushInflightReqStates states {
3091 mId, mInFlightLock, mInFlightMap, mUseHalBufManager,
Shuzhen Wang316781a2020-08-18 18:11:01 -07003092 listener, *this, *mInterface, *this, mSessionStatsBuilder};
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003093
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003094 camera3::flushInflightRequests(states);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003095}
3096
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003097CameraMetadata Camera3Device::getLatestRequestLocked() {
Igor Murashkin1e479c02013-09-06 16:55:14 -07003098 ALOGV("%s", __FUNCTION__);
3099
Igor Murashkin1e479c02013-09-06 16:55:14 -07003100 CameraMetadata retVal;
3101
3102 if (mRequestThread != NULL) {
3103 retVal = mRequestThread->getLatestRequest();
3104 }
3105
Igor Murashkin1e479c02013-09-06 16:55:14 -07003106 return retVal;
3107}
3108
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07003109void Camera3Device::monitorMetadata(TagMonitor::eventSource source,
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003110 int64_t frameNumber, nsecs_t timestamp, const CameraMetadata& metadata,
Jayant Chowdharycd277cd2021-08-11 15:48:40 -07003111 const std::unordered_map<std::string, CameraMetadata>& physicalMetadata,
Jayant Chowdharyc30b4c32021-08-18 11:43:16 -07003112 const camera_stream_buffer_t *outputBuffers, uint32_t numOutputBuffers,
3113 int32_t inputStreamId) {
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003114
3115 mTagMonitor.monitorMetadata(source, frameNumber, timestamp, metadata,
Jayant Chowdharyc30b4c32021-08-18 11:43:16 -07003116 physicalMetadata, outputBuffers, numOutputBuffers, inputStreamId);
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07003117}
3118
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003119/**
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003120 * HalInterface inner class methods
3121 */
3122
Yifan Hongf79b5542017-04-11 14:44:25 -07003123Camera3Device::HalInterface::HalInterface(
3124 sp<ICameraDeviceSession> &session,
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003125 std::shared_ptr<RequestMetadataQueue> queue,
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003126 bool useHalBufManager, bool supportOfflineProcessing) :
Yifan Hongf79b5542017-04-11 14:44:25 -07003127 mHidlSession(session),
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003128 mRequestMetadataQueue(queue),
Emilian Peev4ec17882019-01-24 17:16:58 -08003129 mUseHalBufManager(useHalBufManager),
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003130 mIsReconfigurationQuerySupported(true),
3131 mSupportOfflineProcessing(supportOfflineProcessing) {
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003132 // Check with hardware service manager if we can downcast these interfaces
3133 // Somewhat expensive, so cache the results at startup
Shuzhen Wang83bff122020-11-20 15:51:39 -08003134 auto castResult_3_7 = device::V3_7::ICameraDeviceSession::castFrom(mHidlSession);
3135 if (castResult_3_7.isOk()) {
3136 mHidlSession_3_7 = castResult_3_7;
3137 }
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003138 auto castResult_3_6 = device::V3_6::ICameraDeviceSession::castFrom(mHidlSession);
3139 if (castResult_3_6.isOk()) {
3140 mHidlSession_3_6 = castResult_3_6;
3141 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003142 auto castResult_3_5 = device::V3_5::ICameraDeviceSession::castFrom(mHidlSession);
3143 if (castResult_3_5.isOk()) {
3144 mHidlSession_3_5 = castResult_3_5;
3145 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003146 auto castResult_3_4 = device::V3_4::ICameraDeviceSession::castFrom(mHidlSession);
3147 if (castResult_3_4.isOk()) {
3148 mHidlSession_3_4 = castResult_3_4;
3149 }
3150 auto castResult_3_3 = device::V3_3::ICameraDeviceSession::castFrom(mHidlSession);
3151 if (castResult_3_3.isOk()) {
3152 mHidlSession_3_3 = castResult_3_3;
3153 }
3154}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003155
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003156Camera3Device::HalInterface::HalInterface() :
3157 mUseHalBufManager(false),
3158 mSupportOfflineProcessing(false) {}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003159
3160Camera3Device::HalInterface::HalInterface(const HalInterface& other) :
Yifan Hongf79b5542017-04-11 14:44:25 -07003161 mHidlSession(other.mHidlSession),
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003162 mRequestMetadataQueue(other.mRequestMetadataQueue),
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003163 mUseHalBufManager(other.mUseHalBufManager),
3164 mSupportOfflineProcessing(other.mSupportOfflineProcessing) {}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003165
3166bool Camera3Device::HalInterface::valid() {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003167 return (mHidlSession != nullptr);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003168}
3169
3170void Camera3Device::HalInterface::clear() {
Shuzhen Wang83bff122020-11-20 15:51:39 -08003171 mHidlSession_3_7.clear();
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003172 mHidlSession_3_6.clear();
Emilian Peev644a3e12018-11-23 13:52:39 +00003173 mHidlSession_3_5.clear();
Emilian Peev9e740b02018-01-30 18:28:03 +00003174 mHidlSession_3_4.clear();
3175 mHidlSession_3_3.clear();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003176 mHidlSession.clear();
3177}
3178
3179status_t Camera3Device::HalInterface::constructDefaultRequestSettings(
Emilian Peevf4816702020-04-03 15:44:51 -07003180 camera_request_template_t templateId,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003181 /*out*/ camera_metadata_t **requestTemplate) {
3182 ATRACE_NAME("CameraHal::constructDefaultRequestSettings");
3183 if (!valid()) return INVALID_OPERATION;
3184 status_t res = OK;
3185
Emilian Peev31abd0a2017-05-11 18:37:46 +01003186 common::V1_0::Status status;
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003187
3188 auto requestCallback = [&status, &requestTemplate]
Emilian Peev31abd0a2017-05-11 18:37:46 +01003189 (common::V1_0::Status s, const device::V3_2::CameraMetadata& request) {
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003190 status = s;
3191 if (status == common::V1_0::Status::OK) {
3192 const camera_metadata *r =
3193 reinterpret_cast<const camera_metadata_t*>(request.data());
3194 size_t expectedSize = request.size();
3195 int ret = validate_camera_metadata_structure(r, &expectedSize);
3196 if (ret == OK || ret == CAMERA_METADATA_VALIDATION_SHIFTED) {
3197 *requestTemplate = clone_camera_metadata(r);
3198 if (*requestTemplate == nullptr) {
3199 ALOGE("%s: Unable to clone camera metadata received from HAL",
3200 __FUNCTION__);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003201 status = common::V1_0::Status::INTERNAL_ERROR;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003202 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003203 } else {
3204 ALOGE("%s: Malformed camera metadata received from HAL", __FUNCTION__);
3205 status = common::V1_0::Status::INTERNAL_ERROR;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003206 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003207 }
3208 };
3209 hardware::Return<void> err;
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003210 RequestTemplate id;
3211 switch (templateId) {
Emilian Peevf4816702020-04-03 15:44:51 -07003212 case CAMERA_TEMPLATE_PREVIEW:
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003213 id = RequestTemplate::PREVIEW;
3214 break;
Emilian Peevf4816702020-04-03 15:44:51 -07003215 case CAMERA_TEMPLATE_STILL_CAPTURE:
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003216 id = RequestTemplate::STILL_CAPTURE;
3217 break;
Emilian Peevf4816702020-04-03 15:44:51 -07003218 case CAMERA_TEMPLATE_VIDEO_RECORD:
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003219 id = RequestTemplate::VIDEO_RECORD;
3220 break;
Emilian Peevf4816702020-04-03 15:44:51 -07003221 case CAMERA_TEMPLATE_VIDEO_SNAPSHOT:
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003222 id = RequestTemplate::VIDEO_SNAPSHOT;
3223 break;
Emilian Peevf4816702020-04-03 15:44:51 -07003224 case CAMERA_TEMPLATE_ZERO_SHUTTER_LAG:
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003225 id = RequestTemplate::ZERO_SHUTTER_LAG;
3226 break;
Emilian Peevf4816702020-04-03 15:44:51 -07003227 case CAMERA_TEMPLATE_MANUAL:
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003228 id = RequestTemplate::MANUAL;
3229 break;
3230 default:
3231 // Unknown template ID, or this HAL is too old to support it
3232 return BAD_VALUE;
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003233 }
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003234 err = mHidlSession->constructDefaultRequestSettings(id, requestCallback);
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003235
Emilian Peev31abd0a2017-05-11 18:37:46 +01003236 if (!err.isOk()) {
3237 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3238 res = DEAD_OBJECT;
3239 } else {
3240 res = CameraProviderManager::mapToStatusT(status);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003241 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003242
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003243 return res;
3244}
3245
Emilian Peev4ec17882019-01-24 17:16:58 -08003246bool Camera3Device::HalInterface::isReconfigurationRequired(CameraMetadata& oldSessionParams,
3247 CameraMetadata& newSessionParams) {
3248 // We do reconfiguration by default;
3249 bool ret = true;
3250 if ((mHidlSession_3_5 != nullptr) && mIsReconfigurationQuerySupported) {
3251 android::hardware::hidl_vec<uint8_t> oldParams, newParams;
3252 camera_metadata_t* oldSessioMeta = const_cast<camera_metadata_t*>(
3253 oldSessionParams.getAndLock());
3254 camera_metadata_t* newSessioMeta = const_cast<camera_metadata_t*>(
3255 newSessionParams.getAndLock());
3256 oldParams.setToExternal(reinterpret_cast<uint8_t*>(oldSessioMeta),
3257 get_camera_metadata_size(oldSessioMeta));
3258 newParams.setToExternal(reinterpret_cast<uint8_t*>(newSessioMeta),
3259 get_camera_metadata_size(newSessioMeta));
3260 hardware::camera::common::V1_0::Status callStatus;
3261 bool required;
3262 auto hidlCb = [&callStatus, &required] (hardware::camera::common::V1_0::Status s,
3263 bool requiredFlag) {
3264 callStatus = s;
3265 required = requiredFlag;
3266 };
3267 auto err = mHidlSession_3_5->isReconfigurationRequired(oldParams, newParams, hidlCb);
3268 oldSessionParams.unlock(oldSessioMeta);
3269 newSessionParams.unlock(newSessioMeta);
3270 if (err.isOk()) {
3271 switch (callStatus) {
3272 case hardware::camera::common::V1_0::Status::OK:
3273 ret = required;
3274 break;
3275 case hardware::camera::common::V1_0::Status::METHOD_NOT_SUPPORTED:
3276 mIsReconfigurationQuerySupported = false;
3277 ret = true;
3278 break;
3279 default:
3280 ALOGV("%s: Reconfiguration query failed: %d", __FUNCTION__, callStatus);
3281 ret = true;
3282 }
3283 } else {
3284 ALOGE("%s: Unexpected binder error: %s", __FUNCTION__, err.description().c_str());
3285 ret = true;
3286 }
3287 }
3288
3289 return ret;
3290}
3291
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003292status_t Camera3Device::HalInterface::configureStreams(const camera_metadata_t *sessionParams,
Emilian Peevf4816702020-04-03 15:44:51 -07003293 camera_stream_configuration *config, const std::vector<uint32_t>& bufferSizes) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003294 ATRACE_NAME("CameraHal::configureStreams");
3295 if (!valid()) return INVALID_OPERATION;
3296 status_t res = OK;
3297
Shuzhen Wang83bff122020-11-20 15:51:39 -08003298 if (config->input_is_multi_resolution && mHidlSession_3_7 == nullptr) {
3299 ALOGE("%s: Camera device doesn't support multi-resolution input stream", __FUNCTION__);
3300 return BAD_VALUE;
3301 }
3302
Emilian Peev31abd0a2017-05-11 18:37:46 +01003303 // Convert stream config to HIDL
3304 std::set<int> activeStreams;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003305 device::V3_2::StreamConfiguration requestedConfiguration3_2;
3306 device::V3_4::StreamConfiguration requestedConfiguration3_4;
Shuzhen Wang83bff122020-11-20 15:51:39 -08003307 device::V3_7::StreamConfiguration requestedConfiguration3_7;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003308 requestedConfiguration3_2.streams.resize(config->num_streams);
3309 requestedConfiguration3_4.streams.resize(config->num_streams);
Shuzhen Wang83bff122020-11-20 15:51:39 -08003310 requestedConfiguration3_7.streams.resize(config->num_streams);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003311 for (size_t i = 0; i < config->num_streams; i++) {
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003312 device::V3_2::Stream &dst3_2 = requestedConfiguration3_2.streams[i];
3313 device::V3_4::Stream &dst3_4 = requestedConfiguration3_4.streams[i];
Shuzhen Wang83bff122020-11-20 15:51:39 -08003314 device::V3_7::Stream &dst3_7 = requestedConfiguration3_7.streams[i];
Emilian Peevf4816702020-04-03 15:44:51 -07003315 camera3::camera_stream_t *src = config->streams[i];
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003316
Emilian Peev31abd0a2017-05-11 18:37:46 +01003317 Camera3Stream* cam3stream = Camera3Stream::cast(src);
3318 cam3stream->setBufferFreedListener(this);
3319 int streamId = cam3stream->getId();
3320 StreamType streamType;
3321 switch (src->stream_type) {
Emilian Peevf4816702020-04-03 15:44:51 -07003322 case CAMERA_STREAM_OUTPUT:
Emilian Peev31abd0a2017-05-11 18:37:46 +01003323 streamType = StreamType::OUTPUT;
3324 break;
Emilian Peevf4816702020-04-03 15:44:51 -07003325 case CAMERA_STREAM_INPUT:
Emilian Peev31abd0a2017-05-11 18:37:46 +01003326 streamType = StreamType::INPUT;
3327 break;
3328 default:
3329 ALOGE("%s: Stream %d: Unsupported stream type %d",
3330 __FUNCTION__, streamId, config->streams[i]->stream_type);
3331 return BAD_VALUE;
3332 }
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003333 dst3_2.id = streamId;
3334 dst3_2.streamType = streamType;
3335 dst3_2.width = src->width;
3336 dst3_2.height = src->height;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003337 dst3_2.usage = mapToConsumerUsage(cam3stream->getUsage());
Emilian Peevf4816702020-04-03 15:44:51 -07003338 dst3_2.rotation = mapToStreamRotation((camera_stream_rotation_t) src->rotation);
Shuzhen Wang92653952019-05-07 15:11:43 -07003339 // For HidlSession version 3.5 or newer, the format and dataSpace sent
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08003340 // to HAL are original, not the overridden ones.
Shuzhen Wang92653952019-05-07 15:11:43 -07003341 if (mHidlSession_3_5 != nullptr) {
3342 dst3_2.format = mapToPixelFormat(cam3stream->isFormatOverridden() ?
3343 cam3stream->getOriginalFormat() : src->format);
3344 dst3_2.dataSpace = mapToHidlDataspace(cam3stream->isDataSpaceOverridden() ?
3345 cam3stream->getOriginalDataSpace() : src->data_space);
3346 } else {
3347 dst3_2.format = mapToPixelFormat(src->format);
3348 dst3_2.dataSpace = mapToHidlDataspace(src->data_space);
3349 }
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003350 dst3_4.v3_2 = dst3_2;
Emilian Peev192ee832018-01-31 14:46:47 +00003351 dst3_4.bufferSize = bufferSizes[i];
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003352 if (src->physical_camera_id != nullptr) {
3353 dst3_4.physicalCameraId = src->physical_camera_id;
3354 }
Shuzhen Wang83bff122020-11-20 15:51:39 -08003355 dst3_7.v3_4 = dst3_4;
3356 dst3_7.groupId = cam3stream->getHalStreamGroupId();
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08003357 dst3_7.sensorPixelModesUsed.resize(src->sensor_pixel_modes_used.size());
3358 size_t j = 0;
3359 for (int mode : src->sensor_pixel_modes_used) {
3360 dst3_7.sensorPixelModesUsed[j++] =
3361 static_cast<CameraMetadataEnumAndroidSensorPixelMode>(mode);
3362 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003363 activeStreams.insert(streamId);
3364 // Create Buffer ID map if necessary
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003365 mBufferRecords.tryCreateBufferCache(streamId);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003366 }
3367 // remove BufferIdMap for deleted streams
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003368 mBufferRecords.removeInactiveBufferCaches(activeStreams);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003369
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003370 StreamConfigurationMode operationMode;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003371 res = mapToStreamConfigurationMode(
Emilian Peevf4816702020-04-03 15:44:51 -07003372 (camera_stream_configuration_mode_t) config->operation_mode,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003373 /*out*/ &operationMode);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003374 if (res != OK) {
3375 return res;
3376 }
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003377 requestedConfiguration3_2.operationMode = operationMode;
3378 requestedConfiguration3_4.operationMode = operationMode;
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08003379 requestedConfiguration3_7.operationMode = operationMode;
3380 size_t sessionParamSize = get_camera_metadata_size(sessionParams);
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003381 requestedConfiguration3_4.sessionParams.setToExternal(
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003382 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(sessionParams)),
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08003383 sessionParamSize);
Shuzhen Wang83bff122020-11-20 15:51:39 -08003384 requestedConfiguration3_7.operationMode = operationMode;
3385 requestedConfiguration3_7.sessionParams.setToExternal(
3386 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(sessionParams)),
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08003387 sessionParamSize);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003388
Emilian Peev31abd0a2017-05-11 18:37:46 +01003389 // Invoke configureStreams
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003390 device::V3_3::HalStreamConfiguration finalConfiguration;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003391 device::V3_4::HalStreamConfiguration finalConfiguration3_4;
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003392 device::V3_6::HalStreamConfiguration finalConfiguration3_6;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003393 common::V1_0::Status status;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003394
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003395 auto configStream34Cb = [&status, &finalConfiguration3_4]
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003396 (common::V1_0::Status s, const device::V3_4::HalStreamConfiguration& halConfiguration) {
3397 finalConfiguration3_4 = halConfiguration;
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003398 status = s;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003399 };
3400
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003401 auto configStream36Cb = [&status, &finalConfiguration3_6]
3402 (common::V1_0::Status s, const device::V3_6::HalStreamConfiguration& halConfiguration) {
3403 finalConfiguration3_6 = halConfiguration;
3404 status = s;
3405 };
3406
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003407 auto postprocConfigStream34 = [&finalConfiguration, &finalConfiguration3_4]
3408 (hardware::Return<void>& err) -> status_t {
3409 if (!err.isOk()) {
3410 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3411 return DEAD_OBJECT;
3412 }
3413 finalConfiguration.streams.resize(finalConfiguration3_4.streams.size());
3414 for (size_t i = 0; i < finalConfiguration3_4.streams.size(); i++) {
3415 finalConfiguration.streams[i] = finalConfiguration3_4.streams[i].v3_3;
3416 }
3417 return OK;
3418 };
3419
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003420 auto postprocConfigStream36 = [&finalConfiguration, &finalConfiguration3_6]
3421 (hardware::Return<void>& err) -> status_t {
3422 if (!err.isOk()) {
3423 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3424 return DEAD_OBJECT;
3425 }
3426 finalConfiguration.streams.resize(finalConfiguration3_6.streams.size());
3427 for (size_t i = 0; i < finalConfiguration3_6.streams.size(); i++) {
3428 finalConfiguration.streams[i] = finalConfiguration3_6.streams[i].v3_4.v3_3;
3429 }
3430 return OK;
3431 };
3432
Shuzhen Wang92653952019-05-07 15:11:43 -07003433 // See which version of HAL we have
Shuzhen Wang83bff122020-11-20 15:51:39 -08003434 if (mHidlSession_3_7 != nullptr) {
3435 ALOGV("%s: v3.7 device found", __FUNCTION__);
3436 requestedConfiguration3_7.streamConfigCounter = mNextStreamConfigCounter++;
3437 requestedConfiguration3_7.multiResolutionInputImage = config->input_is_multi_resolution;
3438 auto err = mHidlSession_3_7->configureStreams_3_7(
3439 requestedConfiguration3_7, configStream36Cb);
3440 res = postprocConfigStream36(err);
3441 if (res != OK) {
3442 return res;
3443 }
3444 } else if (mHidlSession_3_6 != nullptr) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003445 ALOGV("%s: v3.6 device found", __FUNCTION__);
3446 device::V3_5::StreamConfiguration requestedConfiguration3_5;
3447 requestedConfiguration3_5.v3_4 = requestedConfiguration3_4;
3448 requestedConfiguration3_5.streamConfigCounter = mNextStreamConfigCounter++;
3449 auto err = mHidlSession_3_6->configureStreams_3_6(
3450 requestedConfiguration3_5, configStream36Cb);
3451 res = postprocConfigStream36(err);
3452 if (res != OK) {
3453 return res;
3454 }
3455 } else if (mHidlSession_3_5 != nullptr) {
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003456 ALOGV("%s: v3.5 device found", __FUNCTION__);
3457 device::V3_5::StreamConfiguration requestedConfiguration3_5;
3458 requestedConfiguration3_5.v3_4 = requestedConfiguration3_4;
3459 requestedConfiguration3_5.streamConfigCounter = mNextStreamConfigCounter++;
3460 auto err = mHidlSession_3_5->configureStreams_3_5(
3461 requestedConfiguration3_5, configStream34Cb);
3462 res = postprocConfigStream34(err);
3463 if (res != OK) {
3464 return res;
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003465 }
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003466 } else if (mHidlSession_3_4 != nullptr) {
3467 // We do; use v3.4 for the call
3468 ALOGV("%s: v3.4 device found", __FUNCTION__);
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003469 auto err = mHidlSession_3_4->configureStreams_3_4(
3470 requestedConfiguration3_4, configStream34Cb);
3471 res = postprocConfigStream34(err);
3472 if (res != OK) {
3473 return res;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003474 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003475 } else if (mHidlSession_3_3 != nullptr) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003476 // We do; use v3.3 for the call
3477 ALOGV("%s: v3.3 device found", __FUNCTION__);
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003478 auto err = mHidlSession_3_3->configureStreams_3_3(requestedConfiguration3_2,
Emilian Peev31abd0a2017-05-11 18:37:46 +01003479 [&status, &finalConfiguration]
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003480 (common::V1_0::Status s, const device::V3_3::HalStreamConfiguration& halConfiguration) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003481 finalConfiguration = halConfiguration;
3482 status = s;
3483 });
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003484 if (!err.isOk()) {
3485 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3486 return DEAD_OBJECT;
3487 }
3488 } else {
3489 // We don't; use v3.2 call and construct a v3.3 HalStreamConfiguration
3490 ALOGV("%s: v3.2 device found", __FUNCTION__);
3491 HalStreamConfiguration finalConfiguration_3_2;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003492 auto err = mHidlSession->configureStreams(requestedConfiguration3_2,
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003493 [&status, &finalConfiguration_3_2]
3494 (common::V1_0::Status s, const HalStreamConfiguration& halConfiguration) {
3495 finalConfiguration_3_2 = halConfiguration;
3496 status = s;
3497 });
3498 if (!err.isOk()) {
3499 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3500 return DEAD_OBJECT;
3501 }
3502 finalConfiguration.streams.resize(finalConfiguration_3_2.streams.size());
3503 for (size_t i = 0; i < finalConfiguration_3_2.streams.size(); i++) {
3504 finalConfiguration.streams[i].v3_2 = finalConfiguration_3_2.streams[i];
3505 finalConfiguration.streams[i].overrideDataSpace =
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003506 requestedConfiguration3_2.streams[i].dataSpace;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003507 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003508 }
3509
3510 if (status != common::V1_0::Status::OK ) {
3511 return CameraProviderManager::mapToStatusT(status);
3512 }
3513
3514 // And convert output stream configuration from HIDL
3515
3516 for (size_t i = 0; i < config->num_streams; i++) {
Emilian Peevf4816702020-04-03 15:44:51 -07003517 camera3::camera_stream_t *dst = config->streams[i];
Emilian Peev31abd0a2017-05-11 18:37:46 +01003518 int streamId = Camera3Stream::cast(dst)->getId();
3519
3520 // Start scan at i, with the assumption that the stream order matches
3521 size_t realIdx = i;
3522 bool found = false;
Eino-Ville Talvala370875f2019-04-12 12:40:27 -07003523 size_t halStreamCount = finalConfiguration.streams.size();
3524 for (size_t idx = 0; idx < halStreamCount; idx++) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003525 if (finalConfiguration.streams[realIdx].v3_2.id == streamId) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003526 found = true;
3527 break;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003528 }
Eino-Ville Talvala370875f2019-04-12 12:40:27 -07003529 realIdx = (realIdx >= halStreamCount - 1) ? 0 : realIdx + 1;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003530 }
3531 if (!found) {
3532 ALOGE("%s: Stream %d not found in stream configuration response from HAL",
3533 __FUNCTION__, streamId);
3534 return INVALID_OPERATION;
3535 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003536 device::V3_3::HalStream &src = finalConfiguration.streams[realIdx];
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003537 device::V3_6::HalStream &src_36 = finalConfiguration3_6.streams[realIdx];
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003538
Emilian Peev710c1422017-08-30 11:19:38 +01003539 Camera3Stream* dstStream = Camera3Stream::cast(dst);
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003540 int overrideFormat = mapToFrameworkFormat(src.v3_2.overrideFormat);
3541 android_dataspace overrideDataSpace = mapToFrameworkDataspace(src.overrideDataSpace);
3542
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003543 if (mHidlSession_3_6 != nullptr) {
3544 dstStream->setOfflineProcessingSupport(src_36.supportOffline);
3545 }
3546
Yin-Chia Yeh90667662019-07-01 15:45:00 -07003547 if (dstStream->getOriginalFormat() != HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
Shuzhen Wang92653952019-05-07 15:11:43 -07003548 dstStream->setFormatOverride(false);
3549 dstStream->setDataSpaceOverride(false);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003550 if (dst->format != overrideFormat) {
3551 ALOGE("%s: Stream %d: Format override not allowed for format 0x%x", __FUNCTION__,
3552 streamId, dst->format);
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003553 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003554 if (dst->data_space != overrideDataSpace) {
3555 ALOGE("%s: Stream %d: DataSpace override not allowed for format 0x%x", __FUNCTION__,
3556 streamId, dst->format);
3557 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003558 } else {
Shuzhen Wang92653952019-05-07 15:11:43 -07003559 bool needFormatOverride =
3560 requestedConfiguration3_2.streams[i].format != src.v3_2.overrideFormat;
3561 bool needDataspaceOverride =
3562 requestedConfiguration3_2.streams[i].dataSpace != src.overrideDataSpace;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003563 // Override allowed with IMPLEMENTATION_DEFINED
Shuzhen Wang92653952019-05-07 15:11:43 -07003564 dstStream->setFormatOverride(needFormatOverride);
3565 dstStream->setDataSpaceOverride(needDataspaceOverride);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003566 dst->format = overrideFormat;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003567 dst->data_space = overrideDataSpace;
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003568 }
3569
Emilian Peevf4816702020-04-03 15:44:51 -07003570 if (dst->stream_type == CAMERA_STREAM_INPUT) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003571 if (src.v3_2.producerUsage != 0) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003572 ALOGE("%s: Stream %d: INPUT streams must have 0 for producer usage",
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003573 __FUNCTION__, streamId);
3574 return INVALID_OPERATION;
3575 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003576 dstStream->setUsage(
3577 mapConsumerToFrameworkUsage(src.v3_2.consumerUsage));
Emilian Peev31abd0a2017-05-11 18:37:46 +01003578 } else {
3579 // OUTPUT
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003580 if (src.v3_2.consumerUsage != 0) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003581 ALOGE("%s: Stream %d: OUTPUT streams must have 0 for consumer usage",
3582 __FUNCTION__, streamId);
3583 return INVALID_OPERATION;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003584 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003585 dstStream->setUsage(
3586 mapProducerToFrameworkUsage(src.v3_2.producerUsage));
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003587 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003588 dst->max_buffers = src.v3_2.maxBuffers;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003589 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003590
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003591 return res;
3592}
3593
Cliff Wuc2ad9c82021-04-21 00:58:58 +08003594status_t Camera3Device::HalInterface::configureInjectedStreams(
3595 const camera_metadata_t* sessionParams, camera_stream_configuration* config,
3596 const std::vector<uint32_t>& bufferSizes,
3597 const CameraMetadata& cameraCharacteristics) {
3598 ATRACE_NAME("InjectionCameraHal::configureStreams");
3599 if (!valid()) return INVALID_OPERATION;
3600 status_t res = OK;
3601
3602 if (config->input_is_multi_resolution) {
3603 ALOGE("%s: Injection camera device doesn't support multi-resolution input "
3604 "stream", __FUNCTION__);
3605 return BAD_VALUE;
3606 }
3607
3608 // Convert stream config to HIDL
3609 std::set<int> activeStreams;
3610 device::V3_2::StreamConfiguration requestedConfiguration3_2;
3611 device::V3_4::StreamConfiguration requestedConfiguration3_4;
3612 device::V3_7::StreamConfiguration requestedConfiguration3_7;
3613 requestedConfiguration3_2.streams.resize(config->num_streams);
3614 requestedConfiguration3_4.streams.resize(config->num_streams);
3615 requestedConfiguration3_7.streams.resize(config->num_streams);
3616 for (size_t i = 0; i < config->num_streams; i++) {
3617 device::V3_2::Stream& dst3_2 = requestedConfiguration3_2.streams[i];
3618 device::V3_4::Stream& dst3_4 = requestedConfiguration3_4.streams[i];
3619 device::V3_7::Stream& dst3_7 = requestedConfiguration3_7.streams[i];
3620 camera3::camera_stream_t* src = config->streams[i];
3621
3622 Camera3Stream* cam3stream = Camera3Stream::cast(src);
3623 cam3stream->setBufferFreedListener(this);
3624 int streamId = cam3stream->getId();
3625 StreamType streamType;
3626 switch (src->stream_type) {
3627 case CAMERA_STREAM_OUTPUT:
3628 streamType = StreamType::OUTPUT;
3629 break;
3630 case CAMERA_STREAM_INPUT:
3631 streamType = StreamType::INPUT;
3632 break;
3633 default:
3634 ALOGE("%s: Stream %d: Unsupported stream type %d", __FUNCTION__,
3635 streamId, config->streams[i]->stream_type);
3636 return BAD_VALUE;
3637 }
3638 dst3_2.id = streamId;
3639 dst3_2.streamType = streamType;
3640 dst3_2.width = src->width;
3641 dst3_2.height = src->height;
3642 dst3_2.usage = mapToConsumerUsage(cam3stream->getUsage());
3643 dst3_2.rotation =
3644 mapToStreamRotation((camera_stream_rotation_t)src->rotation);
3645 // For HidlSession version 3.5 or newer, the format and dataSpace sent
3646 // to HAL are original, not the overridden ones.
3647 if (mHidlSession_3_5 != nullptr) {
3648 dst3_2.format = mapToPixelFormat(cam3stream->isFormatOverridden()
3649 ? cam3stream->getOriginalFormat()
3650 : src->format);
3651 dst3_2.dataSpace =
3652 mapToHidlDataspace(cam3stream->isDataSpaceOverridden()
3653 ? cam3stream->getOriginalDataSpace()
3654 : src->data_space);
3655 } else {
3656 dst3_2.format = mapToPixelFormat(src->format);
3657 dst3_2.dataSpace = mapToHidlDataspace(src->data_space);
3658 }
3659 dst3_4.v3_2 = dst3_2;
3660 dst3_4.bufferSize = bufferSizes[i];
3661 if (src->physical_camera_id != nullptr) {
3662 dst3_4.physicalCameraId = src->physical_camera_id;
3663 }
3664 dst3_7.v3_4 = dst3_4;
3665 dst3_7.groupId = cam3stream->getHalStreamGroupId();
3666 dst3_7.sensorPixelModesUsed.resize(src->sensor_pixel_modes_used.size());
3667 size_t j = 0;
3668 for (int mode : src->sensor_pixel_modes_used) {
3669 dst3_7.sensorPixelModesUsed[j++] =
3670 static_cast<CameraMetadataEnumAndroidSensorPixelMode>(mode);
3671 }
3672 activeStreams.insert(streamId);
3673 // Create Buffer ID map if necessary
3674 mBufferRecords.tryCreateBufferCache(streamId);
3675 }
3676 // remove BufferIdMap for deleted streams
3677 mBufferRecords.removeInactiveBufferCaches(activeStreams);
3678
3679 StreamConfigurationMode operationMode;
3680 res = mapToStreamConfigurationMode(
3681 (camera_stream_configuration_mode_t)config->operation_mode,
3682 /*out*/ &operationMode);
3683 if (res != OK) {
3684 return res;
3685 }
3686 requestedConfiguration3_7.operationMode = operationMode;
3687 size_t sessionParamSize = get_camera_metadata_size(sessionParams);
3688 requestedConfiguration3_7.operationMode = operationMode;
3689 requestedConfiguration3_7.sessionParams.setToExternal(
3690 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(sessionParams)),
3691 sessionParamSize);
3692
3693 // See which version of HAL we have
3694 if (mHidlSession_3_7 != nullptr) {
3695 requestedConfiguration3_7.streamConfigCounter = mNextStreamConfigCounter++;
3696 requestedConfiguration3_7.multiResolutionInputImage =
3697 config->input_is_multi_resolution;
3698
3699 const camera_metadata_t* rawMetadata = cameraCharacteristics.getAndLock();
3700 ::android::hardware::camera::device::V3_2::CameraMetadata hidlChars = {};
3701 hidlChars.setToExternal(
3702 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(rawMetadata)),
3703 get_camera_metadata_size(rawMetadata));
3704 cameraCharacteristics.unlock(rawMetadata);
3705
3706 sp<hardware::camera::device::V3_7::ICameraInjectionSession>
3707 hidlInjectionSession_3_7;
3708 auto castInjectionResult_3_7 =
3709 device::V3_7::ICameraInjectionSession::castFrom(mHidlSession_3_7);
3710 if (castInjectionResult_3_7.isOk()) {
3711 hidlInjectionSession_3_7 = castInjectionResult_3_7;
3712 } else {
3713 ALOGE("%s: Transaction error: %s", __FUNCTION__,
3714 castInjectionResult_3_7.description().c_str());
3715 return DEAD_OBJECT;
3716 }
3717
3718 auto err = hidlInjectionSession_3_7->configureInjectionStreams(
3719 requestedConfiguration3_7, hidlChars);
3720 if (!err.isOk()) {
3721 ALOGE("%s: Transaction error: %s", __FUNCTION__,
3722 err.description().c_str());
3723 return DEAD_OBJECT;
3724 }
3725 } else {
3726 ALOGE("%s: mHidlSession_3_7 does not exist, the lowest version of injection "
3727 "session is 3.7", __FUNCTION__);
3728 return DEAD_OBJECT;
3729 }
3730
3731 return res;
3732}
3733
Emilian Peevf4816702020-04-03 15:44:51 -07003734status_t Camera3Device::HalInterface::wrapAsHidlRequest(camera_capture_request_t* request,
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003735 /*out*/device::V3_2::CaptureRequest* captureRequest,
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003736 /*out*/std::vector<native_handle_t*>* handlesCreated,
3737 /*out*/std::vector<std::pair<int32_t, int32_t>>* inflightBuffers) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003738 ATRACE_CALL();
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003739 if (captureRequest == nullptr || handlesCreated == nullptr || inflightBuffers == nullptr) {
3740 ALOGE("%s: captureRequest (%p), handlesCreated (%p), and inflightBuffers(%p) "
3741 "must not be null", __FUNCTION__, captureRequest, handlesCreated, inflightBuffers);
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003742 return BAD_VALUE;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003743 }
3744
3745 captureRequest->frameNumber = request->frame_number;
Yifan Hongf79b5542017-04-11 14:44:25 -07003746
3747 captureRequest->fmqSettingsSize = 0;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003748
3749 {
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003750 if (request->input_buffer != nullptr) {
3751 int32_t streamId = Camera3Stream::cast(request->input_buffer->stream)->getId();
3752 buffer_handle_t buf = *(request->input_buffer->buffer);
3753 auto pair = getBufferId(buf, streamId);
3754 bool isNewBuffer = pair.first;
3755 uint64_t bufferId = pair.second;
3756 captureRequest->inputBuffer.streamId = streamId;
3757 captureRequest->inputBuffer.bufferId = bufferId;
3758 captureRequest->inputBuffer.buffer = (isNewBuffer) ? buf : nullptr;
3759 captureRequest->inputBuffer.status = BufferStatus::OK;
3760 native_handle_t *acquireFence = nullptr;
3761 if (request->input_buffer->acquire_fence != -1) {
3762 acquireFence = native_handle_create(1,0);
3763 acquireFence->data[0] = request->input_buffer->acquire_fence;
3764 handlesCreated->push_back(acquireFence);
3765 }
3766 captureRequest->inputBuffer.acquireFence = acquireFence;
3767 captureRequest->inputBuffer.releaseFence = nullptr;
3768
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003769 mBufferRecords.pushInflightBuffer(captureRequest->frameNumber, streamId,
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003770 request->input_buffer->buffer);
3771 inflightBuffers->push_back(std::make_pair(captureRequest->frameNumber, streamId));
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003772 } else {
3773 captureRequest->inputBuffer.streamId = -1;
3774 captureRequest->inputBuffer.bufferId = BUFFER_ID_NO_BUFFER;
3775 }
3776
3777 captureRequest->outputBuffers.resize(request->num_output_buffers);
3778 for (size_t i = 0; i < request->num_output_buffers; i++) {
Emilian Peevf4816702020-04-03 15:44:51 -07003779 const camera_stream_buffer_t *src = request->output_buffers + i;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003780 StreamBuffer &dst = captureRequest->outputBuffers[i];
3781 int32_t streamId = Camera3Stream::cast(src->stream)->getId();
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003782 if (src->buffer != nullptr) {
3783 buffer_handle_t buf = *(src->buffer);
3784 auto pair = getBufferId(buf, streamId);
3785 bool isNewBuffer = pair.first;
3786 dst.bufferId = pair.second;
3787 dst.buffer = isNewBuffer ? buf : nullptr;
3788 native_handle_t *acquireFence = nullptr;
3789 if (src->acquire_fence != -1) {
3790 acquireFence = native_handle_create(1,0);
3791 acquireFence->data[0] = src->acquire_fence;
3792 handlesCreated->push_back(acquireFence);
3793 }
3794 dst.acquireFence = acquireFence;
3795 } else if (mUseHalBufManager) {
3796 // HAL buffer management path
3797 dst.bufferId = BUFFER_ID_NO_BUFFER;
3798 dst.buffer = nullptr;
3799 dst.acquireFence = nullptr;
3800 } else {
3801 ALOGE("%s: cannot send a null buffer in capture request!", __FUNCTION__);
3802 return BAD_VALUE;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003803 }
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003804 dst.streamId = streamId;
3805 dst.status = BufferStatus::OK;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003806 dst.releaseFence = nullptr;
3807
Yin-Chia Yeh5f840f82019-03-05 11:59:04 -08003808 // Output buffers are empty when using HAL buffer manager
3809 if (!mUseHalBufManager) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003810 mBufferRecords.pushInflightBuffer(
3811 captureRequest->frameNumber, streamId, src->buffer);
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003812 inflightBuffers->push_back(std::make_pair(captureRequest->frameNumber, streamId));
Yin-Chia Yeh5f840f82019-03-05 11:59:04 -08003813 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003814 }
3815 }
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003816 return OK;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003817}
3818
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003819void Camera3Device::HalInterface::cleanupNativeHandles(
3820 std::vector<native_handle_t*> *handles, bool closeFd) {
3821 if (handles == nullptr) {
3822 return;
3823 }
3824 if (closeFd) {
3825 for (auto& handle : *handles) {
3826 native_handle_close(handle);
3827 }
3828 }
3829 for (auto& handle : *handles) {
3830 native_handle_delete(handle);
3831 }
3832 handles->clear();
3833 return;
3834}
3835
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003836status_t Camera3Device::HalInterface::processBatchCaptureRequests(
Emilian Peevf4816702020-04-03 15:44:51 -07003837 std::vector<camera_capture_request_t*>& requests,/*out*/uint32_t* numRequestProcessed) {
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003838 ATRACE_NAME("CameraHal::processBatchCaptureRequests");
3839 if (!valid()) return INVALID_OPERATION;
3840
Emilian Peevaebbe412018-01-15 13:53:24 +00003841 sp<device::V3_4::ICameraDeviceSession> hidlSession_3_4;
Shuzhen Wang83bff122020-11-20 15:51:39 -08003842 sp<device::V3_7::ICameraDeviceSession> hidlSession_3_7;
3843 auto castResult_3_7 = device::V3_7::ICameraDeviceSession::castFrom(mHidlSession);
3844 if (castResult_3_7.isOk()) {
3845 hidlSession_3_7 = castResult_3_7;
3846 }
Emilian Peevaebbe412018-01-15 13:53:24 +00003847 auto castResult_3_4 = device::V3_4::ICameraDeviceSession::castFrom(mHidlSession);
3848 if (castResult_3_4.isOk()) {
3849 hidlSession_3_4 = castResult_3_4;
3850 }
3851
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003852 hardware::hidl_vec<device::V3_2::CaptureRequest> captureRequests;
Emilian Peevaebbe412018-01-15 13:53:24 +00003853 hardware::hidl_vec<device::V3_4::CaptureRequest> captureRequests_3_4;
Shuzhen Wang83bff122020-11-20 15:51:39 -08003854 hardware::hidl_vec<device::V3_7::CaptureRequest> captureRequests_3_7;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003855 size_t batchSize = requests.size();
Shuzhen Wang83bff122020-11-20 15:51:39 -08003856 if (hidlSession_3_7 != nullptr) {
3857 captureRequests_3_7.resize(batchSize);
3858 } else if (hidlSession_3_4 != nullptr) {
Emilian Peevaebbe412018-01-15 13:53:24 +00003859 captureRequests_3_4.resize(batchSize);
3860 } else {
3861 captureRequests.resize(batchSize);
3862 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003863 std::vector<native_handle_t*> handlesCreated;
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003864 std::vector<std::pair<int32_t, int32_t>> inflightBuffers;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003865
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003866 status_t res = OK;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003867 for (size_t i = 0; i < batchSize; i++) {
Shuzhen Wang83bff122020-11-20 15:51:39 -08003868 if (hidlSession_3_7 != nullptr) {
3869 res = wrapAsHidlRequest(requests[i], /*out*/&captureRequests_3_7[i].v3_4.v3_2,
3870 /*out*/&handlesCreated, /*out*/&inflightBuffers);
3871 } else if (hidlSession_3_4 != nullptr) {
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003872 res = wrapAsHidlRequest(requests[i], /*out*/&captureRequests_3_4[i].v3_2,
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003873 /*out*/&handlesCreated, /*out*/&inflightBuffers);
Emilian Peevaebbe412018-01-15 13:53:24 +00003874 } else {
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003875 res = wrapAsHidlRequest(requests[i], /*out*/&captureRequests[i],
3876 /*out*/&handlesCreated, /*out*/&inflightBuffers);
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003877 }
3878 if (res != OK) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003879 mBufferRecords.popInflightBuffers(inflightBuffers);
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003880 cleanupNativeHandles(&handlesCreated);
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003881 return res;
Emilian Peevaebbe412018-01-15 13:53:24 +00003882 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003883 }
3884
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003885 std::vector<device::V3_2::BufferCache> cachesToRemove;
3886 {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003887 std::lock_guard<std::mutex> lock(mFreedBuffersLock);
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003888 for (auto& pair : mFreedBuffers) {
3889 // The stream might have been removed since onBufferFreed
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003890 if (mBufferRecords.isStreamCached(pair.first)) {
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003891 cachesToRemove.push_back({pair.first, pair.second});
3892 }
3893 }
3894 mFreedBuffers.clear();
3895 }
3896
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003897 common::V1_0::Status status = common::V1_0::Status::INTERNAL_ERROR;
3898 *numRequestProcessed = 0;
Yifan Hongf79b5542017-04-11 14:44:25 -07003899
3900 // Write metadata to FMQ.
3901 for (size_t i = 0; i < batchSize; i++) {
Emilian Peevf4816702020-04-03 15:44:51 -07003902 camera_capture_request_t* request = requests[i];
Emilian Peevaebbe412018-01-15 13:53:24 +00003903 device::V3_2::CaptureRequest* captureRequest;
Shuzhen Wang83bff122020-11-20 15:51:39 -08003904 if (hidlSession_3_7 != nullptr) {
3905 captureRequest = &captureRequests_3_7[i].v3_4.v3_2;
3906 } else if (hidlSession_3_4 != nullptr) {
Emilian Peevaebbe412018-01-15 13:53:24 +00003907 captureRequest = &captureRequests_3_4[i].v3_2;
3908 } else {
3909 captureRequest = &captureRequests[i];
3910 }
Yifan Hongf79b5542017-04-11 14:44:25 -07003911
3912 if (request->settings != nullptr) {
3913 size_t settingsSize = get_camera_metadata_size(request->settings);
3914 if (mRequestMetadataQueue != nullptr && mRequestMetadataQueue->write(
3915 reinterpret_cast<const uint8_t*>(request->settings), settingsSize)) {
3916 captureRequest->settings.resize(0);
3917 captureRequest->fmqSettingsSize = settingsSize;
3918 } else {
3919 if (mRequestMetadataQueue != nullptr) {
3920 ALOGW("%s: couldn't utilize fmq, fallback to hwbinder", __FUNCTION__);
3921 }
3922 captureRequest->settings.setToExternal(
3923 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(request->settings)),
3924 get_camera_metadata_size(request->settings));
3925 captureRequest->fmqSettingsSize = 0u;
3926 }
3927 } else {
3928 // A null request settings maps to a size-0 CameraMetadata
3929 captureRequest->settings.resize(0);
3930 captureRequest->fmqSettingsSize = 0u;
3931 }
Emilian Peevaebbe412018-01-15 13:53:24 +00003932
Shuzhen Wang83bff122020-11-20 15:51:39 -08003933 // hidl session 3.7 specific handling.
3934 if (hidlSession_3_7 != nullptr) {
3935 captureRequests_3_7[i].inputWidth = request->input_width;
3936 captureRequests_3_7[i].inputHeight = request->input_height;
3937 }
3938
3939 // hidl session 3.7 and 3.4 specific handling.
3940 if (hidlSession_3_7 != nullptr || hidlSession_3_4 != nullptr) {
3941 hardware::hidl_vec<device::V3_4::PhysicalCameraSetting>& physicalCameraSettings =
3942 (hidlSession_3_7 != nullptr) ?
3943 captureRequests_3_7[i].v3_4.physicalCameraSettings :
3944 captureRequests_3_4[i].physicalCameraSettings;
3945 physicalCameraSettings.resize(request->num_physcam_settings);
Emilian Peevaebbe412018-01-15 13:53:24 +00003946 for (size_t j = 0; j < request->num_physcam_settings; j++) {
Emilian Peev00420d22018-02-05 21:33:13 +00003947 if (request->physcam_settings != nullptr) {
3948 size_t settingsSize = get_camera_metadata_size(request->physcam_settings[j]);
3949 if (mRequestMetadataQueue != nullptr && mRequestMetadataQueue->write(
3950 reinterpret_cast<const uint8_t*>(request->physcam_settings[j]),
3951 settingsSize)) {
Shuzhen Wang83bff122020-11-20 15:51:39 -08003952 physicalCameraSettings[j].settings.resize(0);
3953 physicalCameraSettings[j].fmqSettingsSize = settingsSize;
Emilian Peev00420d22018-02-05 21:33:13 +00003954 } else {
3955 if (mRequestMetadataQueue != nullptr) {
3956 ALOGW("%s: couldn't utilize fmq, fallback to hwbinder", __FUNCTION__);
3957 }
Shuzhen Wang83bff122020-11-20 15:51:39 -08003958 physicalCameraSettings[j].settings.setToExternal(
Emilian Peev00420d22018-02-05 21:33:13 +00003959 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(
3960 request->physcam_settings[j])),
3961 get_camera_metadata_size(request->physcam_settings[j]));
Shuzhen Wang83bff122020-11-20 15:51:39 -08003962 physicalCameraSettings[j].fmqSettingsSize = 0u;
Emilian Peevaebbe412018-01-15 13:53:24 +00003963 }
Emilian Peev00420d22018-02-05 21:33:13 +00003964 } else {
Yin-Chia Yeha2849702021-03-10 10:11:33 -08003965 physicalCameraSettings[j].fmqSettingsSize = 0u;
3966 physicalCameraSettings[j].settings.resize(0);
Emilian Peevaebbe412018-01-15 13:53:24 +00003967 }
Shuzhen Wang83bff122020-11-20 15:51:39 -08003968 physicalCameraSettings[j].physicalCameraId = request->physcam_id[j];
Emilian Peevaebbe412018-01-15 13:53:24 +00003969 }
3970 }
Yifan Hongf79b5542017-04-11 14:44:25 -07003971 }
Emilian Peevaebbe412018-01-15 13:53:24 +00003972
3973 hardware::details::return_status err;
Jayant Chowdharyc8d581e2018-07-16 14:46:23 -07003974 auto resultCallback =
3975 [&status, &numRequestProcessed] (auto s, uint32_t n) {
3976 status = s;
3977 *numRequestProcessed = n;
3978 };
Shuzhen Wang83bff122020-11-20 15:51:39 -08003979 if (hidlSession_3_7 != nullptr) {
3980 err = hidlSession_3_7->processCaptureRequest_3_7(captureRequests_3_7, cachesToRemove,
3981 resultCallback);
3982 } else if (hidlSession_3_4 != nullptr) {
Emilian Peevaebbe412018-01-15 13:53:24 +00003983 err = hidlSession_3_4->processCaptureRequest_3_4(captureRequests_3_4, cachesToRemove,
Jayant Chowdharyc8d581e2018-07-16 14:46:23 -07003984 resultCallback);
Emilian Peevaebbe412018-01-15 13:53:24 +00003985 } else {
3986 err = mHidlSession->processCaptureRequest(captureRequests, cachesToRemove,
Jayant Chowdharyc8d581e2018-07-16 14:46:23 -07003987 resultCallback);
Emilian Peevaebbe412018-01-15 13:53:24 +00003988 }
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -07003989 if (!err.isOk()) {
3990 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003991 status = common::V1_0::Status::CAMERA_DISCONNECTED;
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -07003992 }
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003993
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003994 if (status == common::V1_0::Status::OK && *numRequestProcessed != batchSize) {
3995 ALOGE("%s: processCaptureRequest returns OK but processed %d/%zu requests",
3996 __FUNCTION__, *numRequestProcessed, batchSize);
3997 status = common::V1_0::Status::INTERNAL_ERROR;
3998 }
3999
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07004000 res = CameraProviderManager::mapToStatusT(status);
4001 if (res == OK) {
4002 if (mHidlSession->isRemote()) {
4003 // Only close acquire fence FDs when the HIDL transaction succeeds (so the FDs have been
4004 // sent to camera HAL processes)
4005 cleanupNativeHandles(&handlesCreated, /*closeFd*/true);
4006 } else {
4007 // In passthrough mode the FDs are now owned by HAL
4008 cleanupNativeHandles(&handlesCreated);
4009 }
4010 } else {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004011 mBufferRecords.popInflightBuffers(inflightBuffers);
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07004012 cleanupNativeHandles(&handlesCreated);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004013 }
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07004014 return res;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004015}
4016
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004017status_t Camera3Device::HalInterface::flush() {
4018 ATRACE_NAME("CameraHal::flush");
4019 if (!valid()) return INVALID_OPERATION;
4020 status_t res = OK;
4021
Emilian Peev31abd0a2017-05-11 18:37:46 +01004022 auto err = mHidlSession->flush();
4023 if (!err.isOk()) {
4024 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
4025 res = DEAD_OBJECT;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004026 } else {
Emilian Peev31abd0a2017-05-11 18:37:46 +01004027 res = CameraProviderManager::mapToStatusT(err);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004028 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01004029
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004030 return res;
4031}
4032
Emilian Peev31abd0a2017-05-11 18:37:46 +01004033status_t Camera3Device::HalInterface::dump(int /*fd*/) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004034 ATRACE_NAME("CameraHal::dump");
4035 if (!valid()) return INVALID_OPERATION;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004036
Emilian Peev31abd0a2017-05-11 18:37:46 +01004037 // Handled by CameraProviderManager::dump
4038
4039 return OK;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004040}
4041
4042status_t Camera3Device::HalInterface::close() {
4043 ATRACE_NAME("CameraHal::close()");
4044 if (!valid()) return INVALID_OPERATION;
4045 status_t res = OK;
4046
Emilian Peev31abd0a2017-05-11 18:37:46 +01004047 auto err = mHidlSession->close();
4048 // Interface will be dead shortly anyway, so don't log errors
4049 if (!err.isOk()) {
4050 res = DEAD_OBJECT;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004051 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01004052
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004053 return res;
4054}
4055
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004056void Camera3Device::HalInterface::signalPipelineDrain(const std::vector<int>& streamIds) {
4057 ATRACE_NAME("CameraHal::signalPipelineDrain");
4058 if (!valid() || mHidlSession_3_5 == nullptr) {
4059 ALOGE("%s called on invalid camera!", __FUNCTION__);
4060 return;
4061 }
4062
Yin-Chia Yehc300a072019-02-13 14:56:57 -08004063 auto err = mHidlSession_3_5->signalStreamFlush(streamIds, mNextStreamConfigCounter - 1);
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004064 if (!err.isOk()) {
4065 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
4066 return;
4067 }
4068}
4069
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004070status_t Camera3Device::HalInterface::switchToOffline(
4071 const std::vector<int32_t>& streamsToKeep,
4072 /*out*/hardware::camera::device::V3_6::CameraOfflineSessionInfo* offlineSessionInfo,
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004073 /*out*/sp<hardware::camera::device::V3_6::ICameraOfflineSession>* offlineSession,
4074 /*out*/camera3::BufferRecords* bufferRecords) {
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004075 ATRACE_NAME("CameraHal::switchToOffline");
4076 if (!valid() || mHidlSession_3_6 == nullptr) {
4077 ALOGE("%s called on invalid camera!", __FUNCTION__);
4078 return INVALID_OPERATION;
4079 }
4080
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004081 if (offlineSessionInfo == nullptr || offlineSession == nullptr || bufferRecords == nullptr) {
4082 ALOGE("%s: output arguments must not be null!", __FUNCTION__);
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004083 return INVALID_OPERATION;
4084 }
4085
4086 common::V1_0::Status status = common::V1_0::Status::INTERNAL_ERROR;
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004087 auto resultCallback =
4088 [&status, &offlineSessionInfo, &offlineSession] (auto s, auto info, auto session) {
4089 status = s;
4090 *offlineSessionInfo = info;
4091 *offlineSession = session;
4092 };
4093 auto err = mHidlSession_3_6->switchToOffline(streamsToKeep, resultCallback);
4094
4095 if (!err.isOk()) {
4096 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
4097 return DEAD_OBJECT;
4098 }
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004099
4100 status_t ret = CameraProviderManager::mapToStatusT(status);
4101 if (ret != OK) {
4102 return ret;
4103 }
4104
4105 // TODO: assert no ongoing requestBuffer/returnBuffer call here
4106 // TODO: update RequestBufferStateMachine to block requestBuffer/returnBuffer once HAL
4107 // returns from switchToOffline.
4108
4109
4110 // Validate buffer caches
4111 std::vector<int32_t> streams;
4112 streams.reserve(offlineSessionInfo->offlineStreams.size());
4113 for (auto offlineStream : offlineSessionInfo->offlineStreams) {
4114 int32_t id = offlineStream.id;
4115 streams.push_back(id);
4116 // Verify buffer caches
4117 std::vector<uint64_t> bufIds(offlineStream.circulatingBufferIds.begin(),
4118 offlineStream.circulatingBufferIds.end());
4119 if (!verifyBufferIds(id, bufIds)) {
4120 ALOGE("%s: stream ID %d buffer cache records mismatch!", __FUNCTION__, id);
4121 return UNKNOWN_ERROR;
4122 }
4123 }
4124
4125 // Move buffer records
4126 bufferRecords->takeBufferCaches(mBufferRecords, streams);
4127 bufferRecords->takeInflightBufferMap(mBufferRecords);
4128 bufferRecords->takeRequestedBufferMap(mBufferRecords);
4129 return ret;
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004130}
4131
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07004132void Camera3Device::HalInterface::getInflightBufferKeys(
4133 std::vector<std::pair<int32_t, int32_t>>* out) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004134 mBufferRecords.getInflightBufferKeys(out);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07004135 return;
4136}
4137
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08004138void Camera3Device::HalInterface::getInflightRequestBufferKeys(
4139 std::vector<uint64_t>* out) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004140 mBufferRecords.getInflightRequestBufferKeys(out);
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08004141 return;
4142}
4143
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004144bool Camera3Device::HalInterface::verifyBufferIds(
4145 int32_t streamId, std::vector<uint64_t>& bufIds) {
4146 return mBufferRecords.verifyBufferIds(streamId, bufIds);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004147}
4148
4149status_t Camera3Device::HalInterface::popInflightBuffer(
Yin-Chia Yehf4650602017-01-10 13:13:39 -08004150 int32_t frameNumber, int32_t streamId,
4151 /*out*/ buffer_handle_t **buffer) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004152 return mBufferRecords.popInflightBuffer(frameNumber, streamId, buffer);
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07004153}
4154
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004155status_t Camera3Device::HalInterface::pushInflightRequestBuffer(
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08004156 uint64_t bufferId, buffer_handle_t* buf, int32_t streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004157 return mBufferRecords.pushInflightRequestBuffer(bufferId, buf, streamId);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004158}
4159
4160// Find and pop a buffer_handle_t based on bufferId
4161status_t Camera3Device::HalInterface::popInflightRequestBuffer(
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08004162 uint64_t bufferId,
4163 /*out*/ buffer_handle_t** buffer,
4164 /*optional out*/ int32_t* streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004165 return mBufferRecords.popInflightRequestBuffer(bufferId, buffer, streamId);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004166}
4167
Yin-Chia Yeh77327052017-01-09 18:23:07 -08004168std::pair<bool, uint64_t> Camera3Device::HalInterface::getBufferId(
4169 const buffer_handle_t& buf, int streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004170 return mBufferRecords.getBufferId(buf, streamId);
Yin-Chia Yeh77327052017-01-09 18:23:07 -08004171}
4172
Shuzhen Wangcd5b1822021-09-07 11:52:48 -07004173uint64_t Camera3Device::HalInterface::removeOneBufferCache(int streamId,
4174 const native_handle_t* handle) {
4175 return mBufferRecords.removeOneBufferCache(streamId, handle);
4176}
4177
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07004178void Camera3Device::HalInterface::onBufferFreed(
4179 int streamId, const native_handle_t* handle) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004180 uint32_t bufferId = mBufferRecords.removeOneBufferCache(streamId, handle);
4181 std::lock_guard<std::mutex> lock(mFreedBuffersLock);
4182 if (bufferId != BUFFER_ID_NO_BUFFER) {
4183 mFreedBuffers.push_back(std::make_pair(streamId, bufferId));
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07004184 }
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07004185}
4186
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07004187void Camera3Device::HalInterface::onStreamReConfigured(int streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004188 std::vector<uint64_t> bufIds = mBufferRecords.clearBufferCaches(streamId);
4189 std::lock_guard<std::mutex> lock(mFreedBuffersLock);
4190 for (auto bufferId : bufIds) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07004191 mFreedBuffers.push_back(std::make_pair(streamId, bufferId));
4192 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07004193}
4194
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004195/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004196 * RequestThread inner class methods
4197 */
4198
4199Camera3Device::RequestThread::RequestThread(wp<Camera3Device> parent,
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004200 sp<StatusTracker> statusTracker,
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004201 sp<HalInterface> interface, const Vector<int32_t>& sessionParamKeys,
Eino-Ville Talvala1646c3c2021-07-29 13:48:40 -07004202 bool useHalBufManager,
4203 bool supportCameraMute) :
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004204 Thread(/*canCallJava*/false),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004205 mParent(parent),
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004206 mStatusTracker(statusTracker),
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004207 mInterface(interface),
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07004208 mListener(nullptr),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004209 mId(getId(parent)),
Shuzhen Wang316781a2020-08-18 18:11:01 -07004210 mFirstRepeating(false),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004211 mReconfigured(false),
4212 mDoPause(false),
4213 mPaused(true),
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004214 mNotifyPipelineDrain(false),
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004215 mFrameNumber(0),
Jianing Weicb0652e2014-03-12 18:29:36 -07004216 mLatestRequestId(NAME_NOT_FOUND),
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07004217 mCurrentAfTriggerId(0),
4218 mCurrentPreCaptureTriggerId(0),
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004219 mRotateAndCropOverride(ANDROID_SCALER_ROTATE_AND_CROP_NONE),
Emilian Peeve23f1d92021-09-20 14:56:01 -07004220 mComposerOutput(false),
Eino-Ville Talvala11afe4f2021-05-27 14:45:31 -07004221 mCameraMute(ANDROID_SENSOR_TEST_PATTERN_MODE_OFF),
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004222 mCameraMuteChanged(false),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004223 mRepeatingLastFrameNumber(
4224 hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES),
Shuzhen Wang686f6442017-06-20 16:16:04 -07004225 mPrepareVideoStream(false),
Emilian Peeva14b4dd2018-05-15 11:00:31 +01004226 mConstrainedMode(false),
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004227 mRequestLatency(kRequestLatencyBinSize),
4228 mSessionParamKeys(sessionParamKeys),
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004229 mLatestSessionParams(sessionParamKeys.size()),
Eino-Ville Talvala1646c3c2021-07-29 13:48:40 -07004230 mUseHalBufManager(useHalBufManager),
4231 mSupportCameraMute(supportCameraMute){
Yin-Chia Yeh87b3ec02019-06-03 10:44:39 -07004232 mStatusId = statusTracker->addComponent("RequestThread");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004233}
4234
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004235Camera3Device::RequestThread::~RequestThread() {}
4236
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004237void Camera3Device::RequestThread::setNotificationListener(
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004238 wp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004239 ATRACE_CALL();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004240 Mutex::Autolock l(mRequestLock);
4241 mListener = listener;
4242}
4243
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004244void Camera3Device::RequestThread::configurationComplete(bool isConstrainedHighSpeed,
Shuzhen Wang99080502021-03-07 21:08:20 -08004245 const CameraMetadata& sessionParams,
4246 const std::map<int32_t, std::set<String8>>& groupIdPhysicalCameraMap) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004247 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004248 Mutex::Autolock l(mRequestLock);
4249 mReconfigured = true;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004250 mLatestSessionParams = sessionParams;
Shuzhen Wang99080502021-03-07 21:08:20 -08004251 mGroupIdPhysicalCameraMap = groupIdPhysicalCameraMap;
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07004252 // Prepare video stream for high speed recording.
4253 mPrepareVideoStream = isConstrainedHighSpeed;
Emilian Peeva14b4dd2018-05-15 11:00:31 +01004254 mConstrainedMode = isConstrainedHighSpeed;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004255}
4256
Jianing Wei90e59c92014-03-12 18:29:36 -07004257status_t Camera3Device::RequestThread::queueRequestList(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004258 List<sp<CaptureRequest> > &requests,
4259 /*out*/
4260 int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004261 ATRACE_CALL();
Jianing Wei90e59c92014-03-12 18:29:36 -07004262 Mutex::Autolock l(mRequestLock);
4263 for (List<sp<CaptureRequest> >::iterator it = requests.begin(); it != requests.end();
4264 ++it) {
4265 mRequestQueue.push_back(*it);
4266 }
4267
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004268 if (lastFrameNumber != NULL) {
4269 *lastFrameNumber = mFrameNumber + mRequestQueue.size() - 1;
4270 ALOGV("%s: requestId %d, mFrameNumber %" PRId32 ", lastFrameNumber %" PRId64 ".",
4271 __FUNCTION__, (*(requests.begin()))->mResultExtras.requestId, mFrameNumber,
4272 *lastFrameNumber);
4273 }
Jianing Weicb0652e2014-03-12 18:29:36 -07004274
Jianing Wei90e59c92014-03-12 18:29:36 -07004275 unpauseForNewRequests();
4276
4277 return OK;
4278}
4279
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004280
4281status_t Camera3Device::RequestThread::queueTrigger(
4282 RequestTrigger trigger[],
4283 size_t count) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004284 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004285 Mutex::Autolock l(mTriggerMutex);
4286 status_t ret;
4287
4288 for (size_t i = 0; i < count; ++i) {
4289 ret = queueTriggerLocked(trigger[i]);
4290
4291 if (ret != OK) {
4292 return ret;
4293 }
4294 }
4295
4296 return OK;
4297}
4298
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004299const String8& Camera3Device::RequestThread::getId(const wp<Camera3Device> &device) {
4300 static String8 deadId("<DeadDevice>");
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004301 sp<Camera3Device> d = device.promote();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004302 if (d != nullptr) return d->mId;
4303 return deadId;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004304}
4305
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004306status_t Camera3Device::RequestThread::queueTriggerLocked(
4307 RequestTrigger trigger) {
4308
4309 uint32_t tag = trigger.metadataTag;
4310 ssize_t index = mTriggerMap.indexOfKey(tag);
4311
4312 switch (trigger.getTagType()) {
4313 case TYPE_BYTE:
4314 // fall-through
4315 case TYPE_INT32:
4316 break;
4317 default:
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004318 ALOGE("%s: Type not supported: 0x%x", __FUNCTION__,
4319 trigger.getTagType());
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004320 return INVALID_OPERATION;
4321 }
4322
4323 /**
4324 * Collect only the latest trigger, since we only have 1 field
4325 * in the request settings per trigger tag, and can't send more than 1
4326 * trigger per request.
4327 */
4328 if (index != NAME_NOT_FOUND) {
4329 mTriggerMap.editValueAt(index) = trigger;
4330 } else {
4331 mTriggerMap.add(tag, trigger);
4332 }
4333
4334 return OK;
4335}
4336
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004337status_t Camera3Device::RequestThread::setRepeatingRequests(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004338 const RequestList &requests,
4339 /*out*/
4340 int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004341 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004342 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004343 if (lastFrameNumber != NULL) {
4344 *lastFrameNumber = mRepeatingLastFrameNumber;
4345 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004346 mRepeatingRequests.clear();
Shuzhen Wang316781a2020-08-18 18:11:01 -07004347 mFirstRepeating = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004348 mRepeatingRequests.insert(mRepeatingRequests.begin(),
4349 requests.begin(), requests.end());
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004350
4351 unpauseForNewRequests();
4352
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004353 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004354 return OK;
4355}
4356
Chih-Hung Hsieh8b0b9712016-08-09 14:25:53 -07004357bool Camera3Device::RequestThread::isRepeatingRequestLocked(const sp<CaptureRequest>& requestIn) {
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07004358 if (mRepeatingRequests.empty()) {
4359 return false;
4360 }
4361 int32_t requestId = requestIn->mResultExtras.requestId;
4362 const RequestList &repeatRequests = mRepeatingRequests;
4363 // All repeating requests are guaranteed to have same id so only check first quest
4364 const sp<CaptureRequest> firstRequest = *repeatRequests.begin();
4365 return (firstRequest->mResultExtras.requestId == requestId);
4366}
4367
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004368status_t Camera3Device::RequestThread::clearRepeatingRequests(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004369 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004370 Mutex::Autolock l(mRequestLock);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004371 return clearRepeatingRequestsLocked(lastFrameNumber);
4372
4373}
4374
4375status_t Camera3Device::RequestThread::clearRepeatingRequestsLocked(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004376 mRepeatingRequests.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004377 if (lastFrameNumber != NULL) {
4378 *lastFrameNumber = mRepeatingLastFrameNumber;
4379 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004380 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004381 return OK;
4382}
4383
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004384status_t Camera3Device::RequestThread::clear(
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004385 /*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004386 ATRACE_CALL();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004387 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004388 ALOGV("RequestThread::%s:", __FUNCTION__);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004389
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004390 mRepeatingRequests.clear();
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07004391
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004392 // Send errors for all requests pending in the request queue, including
4393 // pending repeating requests
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004394 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004395 if (listener != NULL) {
4396 for (RequestList::iterator it = mRequestQueue.begin();
4397 it != mRequestQueue.end(); ++it) {
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004398 // Abort the input buffers for reprocess requests.
4399 if ((*it)->mInputStream != NULL) {
Emilian Peevf4816702020-04-03 15:44:51 -07004400 camera_stream_buffer_t inputBuffer;
Shuzhen Wang83bff122020-11-20 15:51:39 -08004401 camera3::Size inputBufferSize;
Eino-Ville Talvalaba435252017-06-21 16:07:25 -07004402 status_t res = (*it)->mInputStream->getInputBuffer(&inputBuffer,
Shuzhen Wang83bff122020-11-20 15:51:39 -08004403 &inputBufferSize, /*respectHalLimit*/ false);
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004404 if (res != OK) {
4405 ALOGW("%s: %d: couldn't get input buffer while clearing the request "
4406 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
4407 } else {
Emilian Peevf4816702020-04-03 15:44:51 -07004408 inputBuffer.status = CAMERA_BUFFER_STATUS_ERROR;
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004409 res = (*it)->mInputStream->returnInputBuffer(inputBuffer);
4410 if (res != OK) {
4411 ALOGE("%s: %d: couldn't return input buffer while clearing the request "
4412 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
4413 }
4414 }
4415 }
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004416 // Set the frame number this request would have had, if it
4417 // had been submitted; this frame number will not be reused.
4418 // The requestId and burstId fields were set when the request was
4419 // submitted originally (in convertMetadataListToRequestListLocked)
4420 (*it)->mResultExtras.frameNumber = mFrameNumber++;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004421 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004422 (*it)->mResultExtras);
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07004423 }
4424 }
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004425 mRequestQueue.clear();
Jinguang Dongb26e7a02016-11-14 16:04:02 +08004426
4427 Mutex::Autolock al(mTriggerMutex);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004428 mTriggerMap.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004429 if (lastFrameNumber != NULL) {
4430 *lastFrameNumber = mRepeatingLastFrameNumber;
4431 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004432 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Emilian Peev8dae54c2019-12-02 15:17:17 -08004433 mRequestSignal.signal();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004434 return OK;
4435}
4436
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004437status_t Camera3Device::RequestThread::flush() {
4438 ATRACE_CALL();
4439 Mutex::Autolock l(mFlushLock);
4440
Emilian Peev08dd2452017-04-06 16:55:14 +01004441 return mInterface->flush();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004442}
4443
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004444void Camera3Device::RequestThread::setPaused(bool paused) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004445 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004446 Mutex::Autolock l(mPauseLock);
4447 mDoPause = paused;
4448 mDoPauseSignal.signal();
4449}
4450
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004451status_t Camera3Device::RequestThread::waitUntilRequestProcessed(
4452 int32_t requestId, nsecs_t timeout) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004453 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004454 Mutex::Autolock l(mLatestRequestMutex);
4455 status_t res;
4456 while (mLatestRequestId != requestId) {
4457 nsecs_t startTime = systemTime();
4458
4459 res = mLatestRequestSignal.waitRelative(mLatestRequestMutex, timeout);
4460 if (res != OK) return res;
4461
4462 timeout -= (systemTime() - startTime);
4463 }
4464
4465 return OK;
4466}
4467
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004468void Camera3Device::RequestThread::requestExit() {
4469 // Call parent to set up shutdown
4470 Thread::requestExit();
4471 // The exit from any possible waits
4472 mDoPauseSignal.signal();
4473 mRequestSignal.signal();
Shuzhen Wang686f6442017-06-20 16:16:04 -07004474
4475 mRequestLatency.log("ProcessCaptureRequest latency histogram");
4476 mRequestLatency.reset();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004477}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004478
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004479void Camera3Device::RequestThread::checkAndStopRepeatingRequest() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004480 ATRACE_CALL();
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07004481 bool surfaceAbandoned = false;
4482 int64_t lastFrameNumber = 0;
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004483 sp<NotificationListener> listener;
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07004484 {
4485 Mutex::Autolock l(mRequestLock);
4486 // Check all streams needed by repeating requests are still valid. Otherwise, stop
4487 // repeating requests.
4488 for (const auto& request : mRepeatingRequests) {
4489 for (const auto& s : request->mOutputStreams) {
4490 if (s->isAbandoned()) {
4491 surfaceAbandoned = true;
4492 clearRepeatingRequestsLocked(&lastFrameNumber);
4493 break;
4494 }
4495 }
4496 if (surfaceAbandoned) {
4497 break;
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004498 }
4499 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004500 listener = mListener.promote();
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004501 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004502
4503 if (listener != NULL && surfaceAbandoned) {
4504 listener->notifyRepeatingRequestError(lastFrameNumber);
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07004505 }
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004506}
4507
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004508bool Camera3Device::RequestThread::sendRequestsBatch() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004509 ATRACE_CALL();
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004510 status_t res;
4511 size_t batchSize = mNextRequests.size();
Emilian Peevf4816702020-04-03 15:44:51 -07004512 std::vector<camera_capture_request_t*> requests(batchSize);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004513 uint32_t numRequestProcessed = 0;
4514 for (size_t i = 0; i < batchSize; i++) {
4515 requests[i] = &mNextRequests.editItemAt(i).halRequest;
Yin-Chia Yeh885691c2018-05-01 15:54:24 -07004516 ATRACE_ASYNC_BEGIN("frame capture", mNextRequests[i].halRequest.frame_number);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004517 }
4518
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004519 res = mInterface->processBatchCaptureRequests(requests, &numRequestProcessed);
4520
4521 bool triggerRemoveFailed = false;
4522 NextRequest& triggerFailedRequest = mNextRequests.editItemAt(0);
4523 for (size_t i = 0; i < numRequestProcessed; i++) {
4524 NextRequest& nextRequest = mNextRequests.editItemAt(i);
4525 nextRequest.submitted = true;
4526
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004527 updateNextRequest(nextRequest);
Emilian Peevaebbe412018-01-15 13:53:24 +00004528
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004529 if (!triggerRemoveFailed) {
4530 // Remove any previously queued triggers (after unlock)
4531 status_t removeTriggerRes = removeTriggers(mPrevRequest);
4532 if (removeTriggerRes != OK) {
4533 triggerRemoveFailed = true;
4534 triggerFailedRequest = nextRequest;
4535 }
4536 }
4537 }
4538
4539 if (triggerRemoveFailed) {
4540 SET_ERR("RequestThread: Unable to remove triggers "
4541 "(capture request %d, HAL device: %s (%d)",
4542 triggerFailedRequest.halRequest.frame_number, strerror(-res), res);
4543 cleanUpFailedRequests(/*sendRequestError*/ false);
4544 return false;
4545 }
4546
4547 if (res != OK) {
4548 // Should only get a failure here for malformed requests or device-level
4549 // errors, so consider all errors fatal. Bad metadata failures should
4550 // come through notify.
4551 SET_ERR("RequestThread: Unable to submit capture request %d to HAL device: %s (%d)",
4552 mNextRequests[numRequestProcessed].halRequest.frame_number,
4553 strerror(-res), res);
4554 cleanUpFailedRequests(/*sendRequestError*/ false);
4555 return false;
4556 }
4557 return true;
4558}
4559
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07004560nsecs_t Camera3Device::RequestThread::calculateMaxExpectedDuration(const camera_metadata_t *request) {
4561 nsecs_t maxExpectedDuration = kDefaultExpectedDuration;
4562 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
4563 find_camera_metadata_ro_entry(request,
4564 ANDROID_CONTROL_AE_MODE,
4565 &e);
4566 if (e.count == 0) return maxExpectedDuration;
4567
4568 switch (e.data.u8[0]) {
4569 case ANDROID_CONTROL_AE_MODE_OFF:
4570 find_camera_metadata_ro_entry(request,
4571 ANDROID_SENSOR_EXPOSURE_TIME,
4572 &e);
4573 if (e.count > 0) {
4574 maxExpectedDuration = e.data.i64[0];
4575 }
4576 find_camera_metadata_ro_entry(request,
4577 ANDROID_SENSOR_FRAME_DURATION,
4578 &e);
4579 if (e.count > 0) {
4580 maxExpectedDuration = std::max(e.data.i64[0], maxExpectedDuration);
4581 }
4582 break;
4583 default:
4584 find_camera_metadata_ro_entry(request,
4585 ANDROID_CONTROL_AE_TARGET_FPS_RANGE,
4586 &e);
4587 if (e.count > 1) {
4588 maxExpectedDuration = 1e9 / e.data.u8[0];
4589 }
4590 break;
4591 }
4592
4593 return maxExpectedDuration;
4594}
4595
Emilian Peeva14b4dd2018-05-15 11:00:31 +01004596bool Camera3Device::RequestThread::skipHFRTargetFPSUpdate(int32_t tag,
4597 const camera_metadata_ro_entry_t& newEntry, const camera_metadata_entry_t& currentEntry) {
4598 if (mConstrainedMode && (ANDROID_CONTROL_AE_TARGET_FPS_RANGE == tag) &&
4599 (newEntry.count == currentEntry.count) && (currentEntry.count == 2) &&
4600 (currentEntry.data.i32[1] == newEntry.data.i32[1])) {
4601 return true;
4602 }
4603
4604 return false;
4605}
4606
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004607void Camera3Device::RequestThread::updateNextRequest(NextRequest& nextRequest) {
4608 // Update the latest request sent to HAL
Shuzhen Wang83bff122020-11-20 15:51:39 -08004609 camera_capture_request_t& halRequest = nextRequest.halRequest;
4610 if (halRequest.settings != NULL) { // Don't update if they were unchanged
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004611 Mutex::Autolock al(mLatestRequestMutex);
4612
Shuzhen Wang83bff122020-11-20 15:51:39 -08004613 camera_metadata_t* cloned = clone_camera_metadata(halRequest.settings);
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004614 mLatestRequest.acquire(cloned);
4615
4616 mLatestPhysicalRequest.clear();
Shuzhen Wang83bff122020-11-20 15:51:39 -08004617 for (uint32_t i = 0; i < halRequest.num_physcam_settings; i++) {
4618 cloned = clone_camera_metadata(halRequest.physcam_settings[i]);
4619 mLatestPhysicalRequest.emplace(halRequest.physcam_id[i],
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004620 CameraMetadata(cloned));
4621 }
4622
4623 sp<Camera3Device> parent = mParent.promote();
4624 if (parent != NULL) {
Jayant Chowdharycd277cd2021-08-11 15:48:40 -07004625 int32_t inputStreamId = -1;
4626 if (halRequest.input_buffer != nullptr) {
4627 inputStreamId = Camera3Stream::cast(halRequest.input_buffer->stream)->getId();
4628 }
4629
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004630 parent->monitorMetadata(TagMonitor::REQUEST,
Shuzhen Wang83bff122020-11-20 15:51:39 -08004631 halRequest.frame_number,
Jayant Chowdharyc30b4c32021-08-18 11:43:16 -07004632 0, mLatestRequest, mLatestPhysicalRequest, halRequest.output_buffers,
4633 halRequest.num_output_buffers, inputStreamId);
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004634 }
4635 }
4636
Shuzhen Wang83bff122020-11-20 15:51:39 -08004637 if (halRequest.settings != NULL) {
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004638 nextRequest.captureRequest->mSettingsList.begin()->metadata.unlock(
Shuzhen Wang83bff122020-11-20 15:51:39 -08004639 halRequest.settings);
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004640 }
4641
Shuzhen Wang83bff122020-11-20 15:51:39 -08004642 cleanupPhysicalSettings(nextRequest.captureRequest, &halRequest);
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004643}
4644
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004645bool Camera3Device::RequestThread::updateSessionParameters(const CameraMetadata& settings) {
4646 ATRACE_CALL();
4647 bool updatesDetected = false;
4648
Emilian Peev4ec17882019-01-24 17:16:58 -08004649 CameraMetadata updatedParams(mLatestSessionParams);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004650 for (auto tag : mSessionParamKeys) {
4651 camera_metadata_ro_entry entry = settings.find(tag);
Emilian Peev4ec17882019-01-24 17:16:58 -08004652 camera_metadata_entry lastEntry = updatedParams.find(tag);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004653
4654 if (entry.count > 0) {
4655 bool isDifferent = false;
4656 if (lastEntry.count > 0) {
4657 // Have a last value, compare to see if changed
4658 if (lastEntry.type == entry.type &&
4659 lastEntry.count == entry.count) {
4660 // Same type and count, compare values
4661 size_t bytesPerValue = camera_metadata_type_size[lastEntry.type];
4662 size_t entryBytes = bytesPerValue * lastEntry.count;
4663 int cmp = memcmp(entry.data.u8, lastEntry.data.u8, entryBytes);
4664 if (cmp != 0) {
4665 isDifferent = true;
4666 }
4667 } else {
4668 // Count or type has changed
4669 isDifferent = true;
4670 }
4671 } else {
4672 // No last entry, so always consider to be different
4673 isDifferent = true;
4674 }
4675
4676 if (isDifferent) {
4677 ALOGV("%s: Session parameter tag id %d changed", __FUNCTION__, tag);
Emilian Peeva14b4dd2018-05-15 11:00:31 +01004678 if (!skipHFRTargetFPSUpdate(tag, entry, lastEntry)) {
4679 updatesDetected = true;
4680 }
Emilian Peev4ec17882019-01-24 17:16:58 -08004681 updatedParams.update(entry);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004682 }
4683 } else if (lastEntry.count > 0) {
4684 // Value has been removed
4685 ALOGV("%s: Session parameter tag id %d removed", __FUNCTION__, tag);
Emilian Peev4ec17882019-01-24 17:16:58 -08004686 updatedParams.erase(tag);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004687 updatesDetected = true;
4688 }
4689 }
4690
Emilian Peev4ec17882019-01-24 17:16:58 -08004691 bool reconfigureRequired;
4692 if (updatesDetected) {
4693 reconfigureRequired = mInterface->isReconfigurationRequired(mLatestSessionParams,
4694 updatedParams);
4695 mLatestSessionParams = updatedParams;
4696 } else {
4697 reconfigureRequired = false;
4698 }
4699
4700 return reconfigureRequired;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004701}
4702
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004703bool Camera3Device::RequestThread::threadLoop() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004704 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004705 status_t res;
Jayant Chowdhary37eca242019-11-18 08:55:56 -08004706 // Any function called from threadLoop() must not hold mInterfaceLock since
4707 // it could lead to deadlocks (disconnect() -> hold mInterfaceMutex -> wait for request thread
4708 // to finish -> request thread waits on mInterfaceMutex) http://b/143513518
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004709
4710 // Handle paused state.
4711 if (waitIfPaused()) {
4712 return true;
4713 }
4714
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004715 // Wait for the next batch of requests.
4716 waitForNextRequestBatch();
4717 if (mNextRequests.size() == 0) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004718 return true;
4719 }
4720
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004721 // Get the latest request ID, if any
4722 int latestRequestId;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004723 camera_metadata_entry_t requestIdEntry = mNextRequests[mNextRequests.size() - 1].
Emilian Peevaebbe412018-01-15 13:53:24 +00004724 captureRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_ID);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004725 if (requestIdEntry.count > 0) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004726 latestRequestId = requestIdEntry.data.i32[0];
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004727 } else {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004728 ALOGW("%s: Did not have android.request.id set in the request.", __FUNCTION__);
4729 latestRequestId = NAME_NOT_FOUND;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004730 }
4731
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004732 // 'mNextRequests' will at this point contain either a set of HFR batched requests
4733 // or a single request from streaming or burst. In either case the first element
4734 // should contain the latest camera settings that we need to check for any session
4735 // parameter updates.
Emilian Peevaebbe412018-01-15 13:53:24 +00004736 if (updateSessionParameters(mNextRequests[0].captureRequest->mSettingsList.begin()->metadata)) {
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004737 res = OK;
4738
4739 //Input stream buffers are already acquired at this point so an input stream
4740 //will not be able to move to idle state unless we force it.
4741 if (mNextRequests[0].captureRequest->mInputStream != nullptr) {
4742 res = mNextRequests[0].captureRequest->mInputStream->forceToIdle();
4743 if (res != OK) {
4744 ALOGE("%s: Failed to force idle input stream: %d", __FUNCTION__, res);
4745 cleanUpFailedRequests(/*sendRequestError*/ false);
4746 return false;
4747 }
4748 }
4749
4750 if (res == OK) {
Emilian Peev3bead5f2020-05-28 17:29:08 -07004751 sp<Camera3Device> parent = mParent.promote();
4752 if (parent != nullptr) {
4753 mReconfigured |= parent->reconfigureCamera(mLatestSessionParams, mStatusId);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004754 }
Emilian Peev3bead5f2020-05-28 17:29:08 -07004755 setPaused(false);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004756
4757 if (mNextRequests[0].captureRequest->mInputStream != nullptr) {
4758 mNextRequests[0].captureRequest->mInputStream->restoreConfiguredState();
4759 if (res != OK) {
4760 ALOGE("%s: Failed to restore configured input stream: %d", __FUNCTION__, res);
4761 cleanUpFailedRequests(/*sendRequestError*/ false);
4762 return false;
4763 }
4764 }
4765 }
4766 }
4767
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004768 // Prepare a batch of HAL requests and output buffers.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004769 res = prepareHalRequests();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004770 if (res == TIMED_OUT) {
4771 // Not a fatal error if getting output buffers time out.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004772 cleanUpFailedRequests(/*sendRequestError*/ true);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004773 // Check if any stream is abandoned.
4774 checkAndStopRepeatingRequest();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004775 return true;
4776 } else if (res != OK) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004777 cleanUpFailedRequests(/*sendRequestError*/ false);
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004778 return false;
4779 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004780
Zhijun Hecc27e112013-10-03 16:12:43 -07004781 // Inform waitUntilRequestProcessed thread of a new request ID
4782 {
4783 Mutex::Autolock al(mLatestRequestMutex);
4784
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004785 mLatestRequestId = latestRequestId;
Zhijun Hecc27e112013-10-03 16:12:43 -07004786 mLatestRequestSignal.signal();
4787 }
4788
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004789 // Submit a batch of requests to HAL.
4790 // Use flush lock only when submitting multilple requests in a batch.
4791 // TODO: The problem with flush lock is flush() will be blocked by process_capture_request()
4792 // which may take a long time to finish so synchronizing flush() and
4793 // process_capture_request() defeats the purpose of cancelling requests ASAP with flush().
4794 // For now, only synchronize for high speed recording and we should figure something out for
4795 // removing the synchronization.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004796 bool useFlushLock = mNextRequests.size() > 1;
Eino-Ville Talvala17a61ad2013-06-03 16:53:32 -07004797
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004798 if (useFlushLock) {
4799 mFlushLock.lock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004800 }
4801
Zhijun Hef0645c12016-08-02 00:58:11 -07004802 ALOGVV("%s: %d: submitting %zu requests in a batch.", __FUNCTION__, __LINE__,
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004803 mNextRequests.size());
Igor Murashkin1e479c02013-09-06 16:55:14 -07004804
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08004805 sp<Camera3Device> parent = mParent.promote();
4806 if (parent != nullptr) {
4807 parent->mRequestBufferSM.onSubmittingRequest();
4808 }
4809
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004810 bool submitRequestSuccess = false;
Shuzhen Wang686f6442017-06-20 16:16:04 -07004811 nsecs_t tRequestStart = systemTime(SYSTEM_TIME_MONOTONIC);
Yin-Chia Yeh11648852019-05-16 10:42:54 -07004812 submitRequestSuccess = sendRequestsBatch();
4813
Shuzhen Wang686f6442017-06-20 16:16:04 -07004814 nsecs_t tRequestEnd = systemTime(SYSTEM_TIME_MONOTONIC);
4815 mRequestLatency.add(tRequestStart, tRequestEnd);
Igor Murashkin1e479c02013-09-06 16:55:14 -07004816
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004817 if (useFlushLock) {
4818 mFlushLock.unlock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004819 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004820
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004821 // Unset as current request
4822 {
4823 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004824 mNextRequests.clear();
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004825 }
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004826 mRequestSubmittedSignal.signal();
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004827
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004828 return submitRequestSuccess;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004829}
4830
Jayant Chowdhary65c9bf02021-09-03 16:44:16 +00004831status_t Camera3Device::removeFwkOnlyRegionKeys(CameraMetadata *request) {
4832 static const std::array<uint32_t, 4> kFwkOnlyRegionKeys = {ANDROID_CONTROL_AF_REGIONS_SET,
4833 ANDROID_CONTROL_AE_REGIONS_SET, ANDROID_CONTROL_AWB_REGIONS_SET,
4834 ANDROID_SCALER_CROP_REGION_SET};
4835 if (request == nullptr) {
4836 ALOGE("%s request metadata nullptr", __FUNCTION__);
4837 return BAD_VALUE;
4838 }
4839 status_t res = OK;
4840 for (const auto &key : kFwkOnlyRegionKeys) {
4841 if (request->exists(key)) {
4842 res = request->erase(key);
4843 if (res != OK) {
4844 return res;
4845 }
4846 }
4847 }
4848 return OK;
4849}
4850
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004851status_t Camera3Device::RequestThread::prepareHalRequests() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004852 ATRACE_CALL();
4853
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07004854 bool batchedRequest = mNextRequests[0].captureRequest->mBatchSize > 1;
Shuzhen Wang4a472662017-02-26 23:29:04 -08004855 for (size_t i = 0; i < mNextRequests.size(); i++) {
4856 auto& nextRequest = mNextRequests.editItemAt(i);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004857 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
Emilian Peevf4816702020-04-03 15:44:51 -07004858 camera_capture_request_t* halRequest = &nextRequest.halRequest;
4859 Vector<camera_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004860
4861 // Prepare a request to HAL
4862 halRequest->frame_number = captureRequest->mResultExtras.frameNumber;
4863
4864 // Insert any queued triggers (before metadata is locked)
4865 status_t res = insertTriggers(captureRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004866 if (res < 0) {
4867 SET_ERR("RequestThread: Unable to insert triggers "
4868 "(capture request %d, HAL device: %s (%d)",
4869 halRequest->frame_number, strerror(-res), res);
4870 return INVALID_OPERATION;
4871 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07004872
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004873 int triggerCount = res;
4874 bool triggersMixedIn = (triggerCount > 0 || mPrevTriggers > 0);
4875 mPrevTriggers = triggerCount;
4876
Emilian Peeve23f1d92021-09-20 14:56:01 -07004877 // Do not override rotate&crop for stream configurations that include
4878 // SurfaceViews(HW_COMPOSER) output. The display rotation there will be
4879 // compensated by NATIVE_WINDOW_TRANSFORM_INVERSE_DISPLAY
4880 bool rotateAndCropChanged = mComposerOutput ? false :
4881 overrideAutoRotateAndCrop(captureRequest);
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004882 bool testPatternChanged = overrideTestPattern(captureRequest);
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004883
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004884 // If the request is the same as last, or we had triggers now or last time or
4885 // changing overrides this time
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004886 bool newRequest =
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004887 (mPrevRequest != captureRequest || triggersMixedIn ||
4888 rotateAndCropChanged || testPatternChanged) &&
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07004889 // Request settings are all the same within one batch, so only treat the first
4890 // request in a batch as new
Zhijun He54c36822018-07-18 09:33:39 -07004891 !(batchedRequest && i > 0);
Emilian Peev00420d22018-02-05 21:33:13 +00004892 if (newRequest) {
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08004893 std::set<std::string> cameraIdsWithZoom;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004894 /**
4895 * HAL workaround:
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004896 * Insert a fake trigger ID if a trigger is set but no trigger ID is
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004897 */
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004898 res = addFakeTriggerIds(captureRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004899 if (res != OK) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004900 SET_ERR("RequestThread: Unable to insert fake trigger IDs "
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004901 "(capture request %d, HAL device: %s (%d)",
4902 halRequest->frame_number, strerror(-res), res);
4903 return INVALID_OPERATION;
4904 }
4905
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07004906 {
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07004907 sp<Camera3Device> parent = mParent.promote();
4908 if (parent != nullptr) {
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -07004909 List<PhysicalCameraSettings>::iterator it;
4910 for (it = captureRequest->mSettingsList.begin();
4911 it != captureRequest->mSettingsList.end(); it++) {
Jayant Chowdhary9255ce02021-07-15 11:18:17 -07004912 if (parent->mUHRCropAndMeteringRegionMappers.find(it->cameraId) ==
4913 parent->mUHRCropAndMeteringRegionMappers.end()) {
Jayant Chowdhary65c9bf02021-09-03 16:44:16 +00004914 if (removeFwkOnlyRegionKeys(&(it->metadata)) != OK) {
4915 SET_ERR("RequestThread: Unable to remove fwk-only keys from request"
4916 "%d: %s (%d)", halRequest->frame_number, strerror(-res),
4917 res);
4918 return INVALID_OPERATION;
4919 }
Jayant Chowdhary9255ce02021-07-15 11:18:17 -07004920 continue;
4921 }
4922
4923 if (!captureRequest->mUHRCropAndMeteringRegionsUpdated) {
4924 res = parent->mUHRCropAndMeteringRegionMappers[it->cameraId].
4925 updateCaptureRequest(&(it->metadata));
4926 if (res != OK) {
4927 SET_ERR("RequestThread: Unable to correct capture requests "
4928 "for scaler crop region and metering regions for request "
4929 "%d: %s (%d)", halRequest->frame_number, strerror(-res),
4930 res);
4931 return INVALID_OPERATION;
4932 }
4933 captureRequest->mUHRCropAndMeteringRegionsUpdated = true;
Jayant Chowdhary65c9bf02021-09-03 16:44:16 +00004934 if (removeFwkOnlyRegionKeys(&(it->metadata)) != OK) {
4935 SET_ERR("RequestThread: Unable to remove fwk-only keys from request"
4936 "%d: %s (%d)", halRequest->frame_number, strerror(-res),
4937 res);
4938 return INVALID_OPERATION;
4939 }
Jayant Chowdhary9255ce02021-07-15 11:18:17 -07004940 }
4941 }
4942
4943 // Correct metadata regions for distortion correction if enabled
4944 for (it = captureRequest->mSettingsList.begin();
4945 it != captureRequest->mSettingsList.end(); it++) {
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -07004946 if (parent->mDistortionMappers.find(it->cameraId) ==
4947 parent->mDistortionMappers.end()) {
4948 continue;
4949 }
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07004950
4951 if (!captureRequest->mDistortionCorrectionUpdated) {
4952 res = parent->mDistortionMappers[it->cameraId].correctCaptureRequest(
4953 &(it->metadata));
4954 if (res != OK) {
4955 SET_ERR("RequestThread: Unable to correct capture requests "
4956 "for lens distortion for request %d: %s (%d)",
4957 halRequest->frame_number, strerror(-res), res);
4958 return INVALID_OPERATION;
4959 }
4960 captureRequest->mDistortionCorrectionUpdated = true;
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -07004961 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07004962 }
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08004963
4964 for (it = captureRequest->mSettingsList.begin();
4965 it != captureRequest->mSettingsList.end(); it++) {
4966 if (parent->mZoomRatioMappers.find(it->cameraId) ==
4967 parent->mZoomRatioMappers.end()) {
4968 continue;
4969 }
4970
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07004971 if (!captureRequest->mZoomRatioIs1x) {
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08004972 cameraIdsWithZoom.insert(it->cameraId);
4973 }
4974
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07004975 if (!captureRequest->mZoomRatioUpdated) {
4976 res = parent->mZoomRatioMappers[it->cameraId].updateCaptureRequest(
4977 &(it->metadata));
4978 if (res != OK) {
4979 SET_ERR("RequestThread: Unable to correct capture requests "
4980 "for zoom ratio for request %d: %s (%d)",
4981 halRequest->frame_number, strerror(-res), res);
4982 return INVALID_OPERATION;
4983 }
4984 captureRequest->mZoomRatioUpdated = true;
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08004985 }
4986 }
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07004987 if (captureRequest->mRotateAndCropAuto &&
4988 !captureRequest->mRotationAndCropUpdated) {
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004989 for (it = captureRequest->mSettingsList.begin();
4990 it != captureRequest->mSettingsList.end(); it++) {
4991 auto mapper = parent->mRotateAndCropMappers.find(it->cameraId);
4992 if (mapper != parent->mRotateAndCropMappers.end()) {
4993 res = mapper->second.updateCaptureRequest(&(it->metadata));
4994 if (res != OK) {
4995 SET_ERR("RequestThread: Unable to correct capture requests "
4996 "for rotate-and-crop for request %d: %s (%d)",
4997 halRequest->frame_number, strerror(-res), res);
4998 return INVALID_OPERATION;
4999 }
5000 }
5001 }
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07005002 captureRequest->mRotationAndCropUpdated = true;
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005003 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07005004 }
5005 }
5006
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005007 /**
5008 * The request should be presorted so accesses in HAL
5009 * are O(logn). Sidenote, sorting a sorted metadata is nop.
5010 */
Emilian Peevaebbe412018-01-15 13:53:24 +00005011 captureRequest->mSettingsList.begin()->metadata.sort();
5012 halRequest->settings = captureRequest->mSettingsList.begin()->metadata.getAndLock();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005013 mPrevRequest = captureRequest;
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08005014 mPrevCameraIdsWithZoom = cameraIdsWithZoom;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005015 ALOGVV("%s: Request settings are NEW", __FUNCTION__);
5016
5017 IF_ALOGV() {
5018 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
5019 find_camera_metadata_ro_entry(
5020 halRequest->settings,
5021 ANDROID_CONTROL_AF_TRIGGER,
5022 &e
5023 );
5024 if (e.count > 0) {
5025 ALOGV("%s: Request (frame num %d) had AF trigger 0x%x",
5026 __FUNCTION__,
5027 halRequest->frame_number,
5028 e.data.u8[0]);
5029 }
5030 }
5031 } else {
5032 // leave request.settings NULL to indicate 'reuse latest given'
5033 ALOGVV("%s: Request settings are REUSED",
5034 __FUNCTION__);
5035 }
5036
Emilian Peevaebbe412018-01-15 13:53:24 +00005037 if (captureRequest->mSettingsList.size() > 1) {
5038 halRequest->num_physcam_settings = captureRequest->mSettingsList.size() - 1;
5039 halRequest->physcam_id = new const char* [halRequest->num_physcam_settings];
Emilian Peev00420d22018-02-05 21:33:13 +00005040 if (newRequest) {
5041 halRequest->physcam_settings =
5042 new const camera_metadata* [halRequest->num_physcam_settings];
5043 } else {
5044 halRequest->physcam_settings = nullptr;
5045 }
Emilian Peevaebbe412018-01-15 13:53:24 +00005046 auto it = ++captureRequest->mSettingsList.begin();
5047 size_t i = 0;
5048 for (; it != captureRequest->mSettingsList.end(); it++, i++) {
5049 halRequest->physcam_id[i] = it->cameraId.c_str();
Emilian Peev00420d22018-02-05 21:33:13 +00005050 if (newRequest) {
5051 it->metadata.sort();
5052 halRequest->physcam_settings[i] = it->metadata.getAndLock();
5053 }
Emilian Peevaebbe412018-01-15 13:53:24 +00005054 }
5055 }
5056
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005057 uint32_t totalNumBuffers = 0;
5058
5059 // Fill in buffers
5060 if (captureRequest->mInputStream != NULL) {
5061 halRequest->input_buffer = &captureRequest->mInputBuffer;
Shuzhen Wang83bff122020-11-20 15:51:39 -08005062
5063 halRequest->input_width = captureRequest->mInputBufferSize.width;
5064 halRequest->input_height = captureRequest->mInputBufferSize.height;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005065 totalNumBuffers += 1;
5066 } else {
5067 halRequest->input_buffer = NULL;
5068 }
5069
Emilian Peevf4816702020-04-03 15:44:51 -07005070 outputBuffers->insertAt(camera_stream_buffer_t(), 0,
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005071 captureRequest->mOutputStreams.size());
5072 halRequest->output_buffers = outputBuffers->array();
Shuzhen Wang99080502021-03-07 21:08:20 -08005073 std::set<std::set<String8>> requestedPhysicalCameras;
Yin-Chia Yehb3a80b12018-09-04 12:13:05 -07005074
5075 sp<Camera3Device> parent = mParent.promote();
5076 if (parent == NULL) {
5077 // Should not happen, and nowhere to send errors to, so just log it
5078 CLOGE("RequestThread: Parent is gone");
5079 return INVALID_OPERATION;
5080 }
5081 nsecs_t waitDuration = kBaseGetBufferWait + parent->getExpectedInFlightDuration();
5082
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005083 SurfaceMap uniqueSurfaceIdMap;
Shuzhen Wang4a472662017-02-26 23:29:04 -08005084 for (size_t j = 0; j < captureRequest->mOutputStreams.size(); j++) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005085 sp<Camera3OutputStreamInterface> outputStream =
5086 captureRequest->mOutputStreams.editItemAt(j);
5087 int streamId = outputStream->getId();
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07005088
5089 // Prepare video buffers for high speed recording on the first video request.
5090 if (mPrepareVideoStream && outputStream->isVideoStream()) {
5091 // Only try to prepare video stream on the first video request.
5092 mPrepareVideoStream = false;
5093
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07005094 res = outputStream->startPrepare(Camera3StreamInterface::ALLOCATE_PIPELINE_MAX,
5095 false /*blockRequest*/);
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07005096 while (res == NOT_ENOUGH_DATA) {
5097 res = outputStream->prepareNextBuffer();
5098 }
5099 if (res != OK) {
5100 ALOGW("%s: Preparing video buffers for high speed failed: %s (%d)",
5101 __FUNCTION__, strerror(-res), res);
5102 outputStream->cancelPrepare();
5103 }
5104 }
5105
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005106 std::vector<size_t> uniqueSurfaceIds;
5107 res = outputStream->getUniqueSurfaceIds(
5108 captureRequest->mOutputSurfaces[streamId],
5109 &uniqueSurfaceIds);
5110 // INVALID_OPERATION is normal output for streams not supporting surfaceIds
5111 if (res != OK && res != INVALID_OPERATION) {
5112 ALOGE("%s: failed to query stream %d unique surface IDs",
5113 __FUNCTION__, streamId);
5114 return res;
5115 }
5116 if (res == OK) {
5117 uniqueSurfaceIdMap.insert({streamId, std::move(uniqueSurfaceIds)});
5118 }
5119
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07005120 if (mUseHalBufManager) {
Yin-Chia Yeh110342b2018-11-19 11:47:46 -08005121 if (outputStream->isAbandoned()) {
Yin-Chia Yeha1b56c82019-03-27 15:50:39 -07005122 ALOGV("%s: stream %d is abandoned, skipping request", __FUNCTION__, streamId);
Yin-Chia Yeh110342b2018-11-19 11:47:46 -08005123 return TIMED_OUT;
5124 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07005125 // HAL will request buffer through requestStreamBuffer API
Emilian Peevf4816702020-04-03 15:44:51 -07005126 camera_stream_buffer_t& buffer = outputBuffers->editItemAt(j);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07005127 buffer.stream = outputStream->asHalStream();
5128 buffer.buffer = nullptr;
Emilian Peevf4816702020-04-03 15:44:51 -07005129 buffer.status = CAMERA_BUFFER_STATUS_OK;
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07005130 buffer.acquire_fence = -1;
5131 buffer.release_fence = -1;
Emilian Peevf0348ae2021-01-13 13:39:45 -08005132 // Mark the output stream as unpreparable to block clients from calling
5133 // 'prepare' after this request reaches CameraHal and before the respective
5134 // buffers are requested.
5135 outputStream->markUnpreparable();
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07005136 } else {
5137 res = outputStream->getBuffer(&outputBuffers->editItemAt(j),
5138 waitDuration,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005139 captureRequest->mOutputSurfaces[streamId]);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07005140 if (res != OK) {
5141 // Can't get output buffer from gralloc queue - this could be due to
5142 // abandoned queue or other consumer misbehavior, so not a fatal
5143 // error
Yin-Chia Yeha1b56c82019-03-27 15:50:39 -07005144 ALOGV("RequestThread: Can't get output buffer, skipping request:"
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07005145 " %s (%d)", strerror(-res), res);
5146
5147 return TIMED_OUT;
5148 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005149 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08005150
5151 {
5152 sp<Camera3Device> parent = mParent.promote();
5153 if (parent != nullptr) {
5154 const String8& streamCameraId = outputStream->getPhysicalCameraId();
5155 for (const auto& settings : captureRequest->mSettingsList) {
5156 if ((streamCameraId.isEmpty() &&
5157 parent->getId() == settings.cameraId.c_str()) ||
5158 streamCameraId == settings.cameraId.c_str()) {
5159 outputStream->fireBufferRequestForFrameNumber(
5160 captureRequest->mResultExtras.frameNumber,
5161 settings.metadata);
5162 }
5163 }
5164 }
5165 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07005166
Shuzhen Wang5c22c152017-12-31 17:12:25 -08005167 String8 physicalCameraId = outputStream->getPhysicalCameraId();
Shuzhen Wang99080502021-03-07 21:08:20 -08005168 int32_t streamGroupId = outputStream->getHalStreamGroupId();
5169 if (streamGroupId != -1 && mGroupIdPhysicalCameraMap.count(streamGroupId) == 1) {
5170 requestedPhysicalCameras.insert(mGroupIdPhysicalCameraMap[streamGroupId]);
5171 } else if (!physicalCameraId.isEmpty()) {
5172 requestedPhysicalCameras.insert(std::set<String8>({physicalCameraId}));
Shuzhen Wang5c22c152017-12-31 17:12:25 -08005173 }
5174 halRequest->num_output_buffers++;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005175 }
5176 totalNumBuffers += halRequest->num_output_buffers;
5177
5178 // Log request in the in-flight queue
Shuzhen Wang4a472662017-02-26 23:29:04 -08005179 // If this request list is for constrained high speed recording (not
5180 // preview), and the current request is not the last one in the batch,
5181 // do not send callback to the app.
5182 bool hasCallback = true;
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07005183 if (batchedRequest && i != mNextRequests.size()-1) {
Shuzhen Wang4a472662017-02-26 23:29:04 -08005184 hasCallback = false;
5185 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01005186 bool isStillCapture = false;
Shuzhen Wang26abaf42018-08-28 15:41:20 -07005187 bool isZslCapture = false;
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08005188 const camera_metadata_t* settings = halRequest->settings;
5189 bool shouldUnlockSettings = false;
5190 if (settings == nullptr) {
5191 shouldUnlockSettings = true;
5192 settings = captureRequest->mSettingsList.begin()->metadata.getAndLock();
5193 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01005194 if (!mNextRequests[0].captureRequest->mSettingsList.begin()->metadata.isEmpty()) {
5195 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08005196 find_camera_metadata_ro_entry(settings, ANDROID_CONTROL_CAPTURE_INTENT, &e);
Emilian Peev9dd21f42018-08-03 13:39:29 +01005197 if ((e.count > 0) && (e.data.u8[0] == ANDROID_CONTROL_CAPTURE_INTENT_STILL_CAPTURE)) {
5198 isStillCapture = true;
5199 ATRACE_ASYNC_BEGIN("still capture", mNextRequests[i].halRequest.frame_number);
5200 }
Shuzhen Wang26abaf42018-08-28 15:41:20 -07005201
Emilian Peevaf8416e2021-02-04 17:52:43 -08005202 e = camera_metadata_ro_entry_t();
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08005203 find_camera_metadata_ro_entry(settings, ANDROID_CONTROL_ENABLE_ZSL, &e);
Shuzhen Wang26abaf42018-08-28 15:41:20 -07005204 if ((e.count > 0) && (e.data.u8[0] == ANDROID_CONTROL_ENABLE_ZSL_TRUE)) {
5205 isZslCapture = true;
5206 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01005207 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005208 res = parent->registerInFlight(halRequest->frame_number,
5209 totalNumBuffers, captureRequest->mResultExtras,
5210 /*hasInput*/halRequest->input_buffer != NULL,
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07005211 hasCallback,
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08005212 calculateMaxExpectedDuration(settings),
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005213 requestedPhysicalCameras, isStillCapture, isZslCapture,
5214 captureRequest->mRotateAndCropAuto, mPrevCameraIdsWithZoom,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005215 (mUseHalBufManager) ? uniqueSurfaceIdMap :
Shuzhen Wang316781a2020-08-18 18:11:01 -07005216 SurfaceMap{}, captureRequest->mRequestTimeNs);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005217 ALOGVV("%s: registered in flight requestId = %" PRId32 ", frameNumber = %" PRId64
5218 ", burstId = %" PRId32 ".",
5219 __FUNCTION__,
5220 captureRequest->mResultExtras.requestId, captureRequest->mResultExtras.frameNumber,
5221 captureRequest->mResultExtras.burstId);
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08005222
5223 if (shouldUnlockSettings) {
5224 captureRequest->mSettingsList.begin()->metadata.unlock(settings);
5225 }
5226
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005227 if (res != OK) {
5228 SET_ERR("RequestThread: Unable to register new in-flight request:"
5229 " %s (%d)", strerror(-res), res);
5230 return INVALID_OPERATION;
5231 }
5232 }
5233
5234 return OK;
5235}
5236
Igor Murashkin1e479c02013-09-06 16:55:14 -07005237CameraMetadata Camera3Device::RequestThread::getLatestRequest() const {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005238 ATRACE_CALL();
Igor Murashkin1e479c02013-09-06 16:55:14 -07005239 Mutex::Autolock al(mLatestRequestMutex);
5240
5241 ALOGV("RequestThread::%s", __FUNCTION__);
5242
5243 return mLatestRequest;
5244}
5245
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005246bool Camera3Device::RequestThread::isStreamPending(
5247 sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005248 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005249 Mutex::Autolock l(mRequestLock);
5250
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005251 for (const auto& nextRequest : mNextRequests) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005252 if (!nextRequest.submitted) {
5253 for (const auto& s : nextRequest.captureRequest->mOutputStreams) {
5254 if (stream == s) return true;
5255 }
5256 if (stream == nextRequest.captureRequest->mInputStream) return true;
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07005257 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07005258 }
5259
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005260 for (const auto& request : mRequestQueue) {
5261 for (const auto& s : request->mOutputStreams) {
5262 if (stream == s) return true;
5263 }
5264 if (stream == request->mInputStream) return true;
5265 }
5266
5267 for (const auto& request : mRepeatingRequests) {
5268 for (const auto& s : request->mOutputStreams) {
5269 if (stream == s) return true;
5270 }
5271 if (stream == request->mInputStream) return true;
5272 }
5273
5274 return false;
5275}
Jianing Weicb0652e2014-03-12 18:29:36 -07005276
Emilian Peev40ead602017-09-26 15:46:36 +01005277bool Camera3Device::RequestThread::isOutputSurfacePending(int streamId, size_t surfaceId) {
5278 ATRACE_CALL();
5279 Mutex::Autolock l(mRequestLock);
5280
5281 for (const auto& nextRequest : mNextRequests) {
5282 for (const auto& s : nextRequest.captureRequest->mOutputSurfaces) {
5283 if (s.first == streamId) {
5284 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
5285 if (it != s.second.end()) {
5286 return true;
5287 }
5288 }
5289 }
5290 }
5291
5292 for (const auto& request : mRequestQueue) {
5293 for (const auto& s : request->mOutputSurfaces) {
5294 if (s.first == streamId) {
5295 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
5296 if (it != s.second.end()) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005297 return true;
Emilian Peev40ead602017-09-26 15:46:36 +01005298 }
5299 }
5300 }
5301 }
5302
5303 for (const auto& request : mRepeatingRequests) {
5304 for (const auto& s : request->mOutputSurfaces) {
5305 if (s.first == streamId) {
5306 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
5307 if (it != s.second.end()) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005308 return true;
Emilian Peev40ead602017-09-26 15:46:36 +01005309 }
5310 }
5311 }
5312 }
5313
5314 return false;
5315}
5316
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07005317void Camera3Device::RequestThread::signalPipelineDrain(const std::vector<int>& streamIds) {
5318 if (!mUseHalBufManager) {
5319 ALOGE("%s called for camera device not supporting HAL buffer management", __FUNCTION__);
5320 return;
5321 }
5322
5323 Mutex::Autolock pl(mPauseLock);
5324 if (mPaused) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005325 mInterface->signalPipelineDrain(streamIds);
5326 return;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07005327 }
5328 // If request thread is still busy, wait until paused then notify HAL
5329 mNotifyPipelineDrain = true;
5330 mStreamIdsToBeDrained = streamIds;
5331}
5332
Yin-Chia Yehe52b8fa2020-07-28 00:17:58 -07005333void Camera3Device::RequestThread::resetPipelineDrain() {
5334 Mutex::Autolock pl(mPauseLock);
5335 mNotifyPipelineDrain = false;
5336 mStreamIdsToBeDrained.clear();
5337}
5338
Emilian Peevc0fe54c2020-03-11 14:05:07 -07005339void Camera3Device::RequestThread::clearPreviousRequest() {
5340 Mutex::Autolock l(mRequestLock);
5341 mPrevRequest.clear();
5342}
5343
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005344status_t Camera3Device::RequestThread::switchToOffline(
5345 const std::vector<int32_t>& streamsToKeep,
5346 /*out*/hardware::camera::device::V3_6::CameraOfflineSessionInfo* offlineSessionInfo,
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005347 /*out*/sp<hardware::camera::device::V3_6::ICameraOfflineSession>* offlineSession,
5348 /*out*/camera3::BufferRecords* bufferRecords) {
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005349 Mutex::Autolock l(mRequestLock);
5350 clearRepeatingRequestsLocked(/*lastFrameNumber*/nullptr);
5351
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005352 // Wait until request thread is fully stopped
5353 // TBD: check if request thread is being paused by other APIs (shouldn't be)
5354
5355 // We could also check for mRepeatingRequests.empty(), but the API interface
5356 // is serialized by Camera3Device::mInterfaceLock so no one should be able to submit any
5357 // new requests during the call; hence skip that check.
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005358 bool queueEmpty = mNextRequests.empty() && mRequestQueue.empty();
5359 while (!queueEmpty) {
5360 status_t res = mRequestSubmittedSignal.waitRelative(mRequestLock, kRequestSubmitTimeout);
5361 if (res == TIMED_OUT) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005362 ALOGE("%s: request thread failed to submit one request within timeout!", __FUNCTION__);
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005363 return res;
5364 } else if (res != OK) {
5365 ALOGE("%s: request thread failed to submit a request: %s (%d)!",
5366 __FUNCTION__, strerror(-res), res);
5367 return res;
5368 }
5369 queueEmpty = mNextRequests.empty() && mRequestQueue.empty();
5370 }
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005371
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005372 return mInterface->switchToOffline(
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005373 streamsToKeep, offlineSessionInfo, offlineSession, bufferRecords);
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005374}
5375
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005376status_t Camera3Device::RequestThread::setRotateAndCropAutoBehavior(
5377 camera_metadata_enum_android_scaler_rotate_and_crop_t rotateAndCropValue) {
5378 ATRACE_CALL();
5379 Mutex::Autolock l(mTriggerMutex);
5380 if (rotateAndCropValue == ANDROID_SCALER_ROTATE_AND_CROP_AUTO) {
5381 return BAD_VALUE;
5382 }
5383 mRotateAndCropOverride = rotateAndCropValue;
5384 return OK;
5385}
5386
Emilian Peeve23f1d92021-09-20 14:56:01 -07005387status_t Camera3Device::RequestThread::setComposerSurface(bool composerSurfacePresent) {
5388 ATRACE_CALL();
5389 Mutex::Autolock l(mTriggerMutex);
5390 mComposerOutput = composerSurfacePresent;
5391 return OK;
5392}
5393
Eino-Ville Talvala11afe4f2021-05-27 14:45:31 -07005394status_t Camera3Device::RequestThread::setCameraMute(int32_t muteMode) {
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005395 ATRACE_CALL();
5396 Mutex::Autolock l(mTriggerMutex);
Eino-Ville Talvala11afe4f2021-05-27 14:45:31 -07005397 if (muteMode != mCameraMute) {
5398 mCameraMute = muteMode;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005399 mCameraMuteChanged = true;
5400 }
5401 return OK;
5402}
5403
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07005404nsecs_t Camera3Device::getExpectedInFlightDuration() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005405 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005406 std::lock_guard<std::mutex> l(mInFlightLock);
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07005407 return mExpectedInflightDuration > kMinInflightDuration ?
5408 mExpectedInflightDuration : kMinInflightDuration;
5409}
5410
Emilian Peevaebbe412018-01-15 13:53:24 +00005411void Camera3Device::RequestThread::cleanupPhysicalSettings(sp<CaptureRequest> request,
Emilian Peevf4816702020-04-03 15:44:51 -07005412 camera_capture_request_t *halRequest) {
Emilian Peevaebbe412018-01-15 13:53:24 +00005413 if ((request == nullptr) || (halRequest == nullptr)) {
5414 ALOGE("%s: Invalid request!", __FUNCTION__);
5415 return;
5416 }
5417
5418 if (halRequest->num_physcam_settings > 0) {
5419 if (halRequest->physcam_id != nullptr) {
5420 delete [] halRequest->physcam_id;
5421 halRequest->physcam_id = nullptr;
5422 }
5423 if (halRequest->physcam_settings != nullptr) {
5424 auto it = ++(request->mSettingsList.begin());
5425 size_t i = 0;
5426 for (; it != request->mSettingsList.end(); it++, i++) {
5427 it->metadata.unlock(halRequest->physcam_settings[i]);
5428 }
5429 delete [] halRequest->physcam_settings;
5430 halRequest->physcam_settings = nullptr;
5431 }
5432 }
5433}
5434
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005435void Camera3Device::RequestThread::cleanUpFailedRequests(bool sendRequestError) {
5436 if (mNextRequests.empty()) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005437 return;
5438 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005439
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005440 for (auto& nextRequest : mNextRequests) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005441 // Skip the ones that have been submitted successfully.
5442 if (nextRequest.submitted) {
5443 continue;
5444 }
5445
5446 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
Emilian Peevf4816702020-04-03 15:44:51 -07005447 camera_capture_request_t* halRequest = &nextRequest.halRequest;
5448 Vector<camera_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005449
5450 if (halRequest->settings != NULL) {
Emilian Peevaebbe412018-01-15 13:53:24 +00005451 captureRequest->mSettingsList.begin()->metadata.unlock(halRequest->settings);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005452 }
5453
Emilian Peevaebbe412018-01-15 13:53:24 +00005454 cleanupPhysicalSettings(captureRequest, halRequest);
5455
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005456 if (captureRequest->mInputStream != NULL) {
Emilian Peevf4816702020-04-03 15:44:51 -07005457 captureRequest->mInputBuffer.status = CAMERA_BUFFER_STATUS_ERROR;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005458 captureRequest->mInputStream->returnInputBuffer(captureRequest->mInputBuffer);
5459 }
5460
Yin-Chia Yeh21cb47b2019-01-18 15:08:17 -08005461 // No output buffer can be returned when using HAL buffer manager
5462 if (!mUseHalBufManager) {
5463 for (size_t i = 0; i < halRequest->num_output_buffers; i++) {
5464 //Buffers that failed processing could still have
5465 //valid acquire fence.
5466 int acquireFence = (*outputBuffers)[i].acquire_fence;
5467 if (0 <= acquireFence) {
5468 close(acquireFence);
5469 outputBuffers->editItemAt(i).acquire_fence = -1;
5470 }
Emilian Peevf4816702020-04-03 15:44:51 -07005471 outputBuffers->editItemAt(i).status = CAMERA_BUFFER_STATUS_ERROR;
Yin-Chia Yeh21cb47b2019-01-18 15:08:17 -08005472 captureRequest->mOutputStreams.editItemAt(i)->returnBuffer((*outputBuffers)[i], 0,
5473 /*timestampIncreasing*/true, std::vector<size_t> (),
5474 captureRequest->mResultExtras.frameNumber);
Emilian Peevc58cf4c2017-05-11 17:23:41 +01005475 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005476 }
5477
5478 if (sendRequestError) {
5479 Mutex::Autolock l(mRequestLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005480 sp<NotificationListener> listener = mListener.promote();
5481 if (listener != NULL) {
5482 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08005483 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005484 captureRequest->mResultExtras);
5485 }
5486 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07005487
5488 // Remove yet-to-be submitted inflight request from inflightMap
5489 {
5490 sp<Camera3Device> parent = mParent.promote();
5491 if (parent != NULL) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005492 std::lock_guard<std::mutex> l(parent->mInFlightLock);
Shuzhen Wangcadb3302016-11-04 14:17:56 -07005493 ssize_t idx = parent->mInFlightMap.indexOfKey(captureRequest->mResultExtras.frameNumber);
5494 if (idx >= 0) {
5495 ALOGV("%s: Remove inflight request from queue: frameNumber %" PRId64,
5496 __FUNCTION__, captureRequest->mResultExtras.frameNumber);
5497 parent->removeInFlightMapEntryLocked(idx);
5498 }
5499 }
5500 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005501 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07005502
5503 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005504 mNextRequests.clear();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005505}
5506
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005507void Camera3Device::RequestThread::waitForNextRequestBatch() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005508 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005509 // Optimized a bit for the simple steady-state case (single repeating
5510 // request), to avoid putting that request in the queue temporarily.
5511 Mutex::Autolock l(mRequestLock);
5512
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005513 assert(mNextRequests.empty());
5514
5515 NextRequest nextRequest;
5516 nextRequest.captureRequest = waitForNextRequestLocked();
5517 if (nextRequest.captureRequest == nullptr) {
5518 return;
5519 }
5520
Emilian Peevf4816702020-04-03 15:44:51 -07005521 nextRequest.halRequest = camera_capture_request_t();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005522 nextRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005523 mNextRequests.add(nextRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005524
5525 // Wait for additional requests
5526 const size_t batchSize = nextRequest.captureRequest->mBatchSize;
5527
5528 for (size_t i = 1; i < batchSize; i++) {
5529 NextRequest additionalRequest;
5530 additionalRequest.captureRequest = waitForNextRequestLocked();
5531 if (additionalRequest.captureRequest == nullptr) {
5532 break;
5533 }
5534
Emilian Peevf4816702020-04-03 15:44:51 -07005535 additionalRequest.halRequest = camera_capture_request_t();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005536 additionalRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005537 mNextRequests.add(additionalRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005538 }
5539
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005540 if (mNextRequests.size() < batchSize) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08005541 ALOGE("RequestThread: only get %zu out of %zu requests. Skipping requests.",
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005542 mNextRequests.size(), batchSize);
5543 cleanUpFailedRequests(/*sendRequestError*/true);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005544 }
5545
5546 return;
5547}
5548
5549sp<Camera3Device::CaptureRequest>
5550 Camera3Device::RequestThread::waitForNextRequestLocked() {
5551 status_t res;
5552 sp<CaptureRequest> nextRequest;
5553
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005554 while (mRequestQueue.empty()) {
5555 if (!mRepeatingRequests.empty()) {
5556 // Always atomically enqueue all requests in a repeating request
5557 // list. Guarantees a complete in-sequence set of captures to
5558 // application.
5559 const RequestList &requests = mRepeatingRequests;
Shuzhen Wang316781a2020-08-18 18:11:01 -07005560 if (mFirstRepeating) {
5561 mFirstRepeating = false;
5562 } else {
5563 for (auto& request : requests) {
5564 // For repeating requests, override timestamp request using
5565 // the time a request is inserted into the request queue,
5566 // because the original repeating request will have an old
5567 // fixed timestamp.
5568 request->mRequestTimeNs = systemTime();
5569 }
5570 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005571 RequestList::const_iterator firstRequest =
5572 requests.begin();
5573 nextRequest = *firstRequest;
5574 mRequestQueue.insert(mRequestQueue.end(),
5575 ++firstRequest,
5576 requests.end());
5577 // No need to wait any longer
Jianing Weicb0652e2014-03-12 18:29:36 -07005578
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005579 mRepeatingLastFrameNumber = mFrameNumber + requests.size() - 1;
Jianing Weicb0652e2014-03-12 18:29:36 -07005580
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005581 break;
5582 }
5583
5584 res = mRequestSignal.waitRelative(mRequestLock, kRequestTimeout);
5585
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005586 if ((mRequestQueue.empty() && mRepeatingRequests.empty()) ||
5587 exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005588 Mutex::Autolock pl(mPauseLock);
5589 if (mPaused == false) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005590 ALOGV("%s: RequestThread: Going idle", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005591 mPaused = true;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07005592 if (mNotifyPipelineDrain) {
5593 mInterface->signalPipelineDrain(mStreamIdsToBeDrained);
5594 mNotifyPipelineDrain = false;
5595 mStreamIdsToBeDrained.clear();
5596 }
Yin-Chia Yehc300a072019-02-13 14:56:57 -08005597 // Let the tracker know
5598 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5599 if (statusTracker != 0) {
5600 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
5601 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005602 sp<Camera3Device> parent = mParent.promote();
5603 if (parent != nullptr) {
5604 parent->mRequestBufferSM.onRequestThreadPaused();
5605 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005606 }
5607 // Stop waiting for now and let thread management happen
5608 return NULL;
5609 }
5610 }
5611
5612 if (nextRequest == NULL) {
5613 // Don't have a repeating request already in hand, so queue
5614 // must have an entry now.
5615 RequestList::iterator firstRequest =
5616 mRequestQueue.begin();
5617 nextRequest = *firstRequest;
5618 mRequestQueue.erase(firstRequest);
Shuzhen Wang9d066012016-09-30 11:30:20 -07005619 if (mRequestQueue.empty() && !nextRequest->mRepeating) {
5620 sp<NotificationListener> listener = mListener.promote();
5621 if (listener != NULL) {
5622 listener->notifyRequestQueueEmpty();
5623 }
5624 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005625 }
5626
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005627 // In case we've been unpaused by setPaused clearing mDoPause, need to
5628 // update internal pause state (capture/setRepeatingRequest unpause
5629 // directly).
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005630 Mutex::Autolock pl(mPauseLock);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005631 if (mPaused) {
5632 ALOGV("%s: RequestThread: Unpaused", __FUNCTION__);
5633 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5634 if (statusTracker != 0) {
5635 statusTracker->markComponentActive(mStatusId);
5636 }
5637 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005638 mPaused = false;
5639
5640 // Check if we've reconfigured since last time, and reset the preview
5641 // request if so. Can't use 'NULL request == repeat' across configure calls.
5642 if (mReconfigured) {
5643 mPrevRequest.clear();
5644 mReconfigured = false;
5645 }
5646
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005647 if (nextRequest != NULL) {
5648 nextRequest->mResultExtras.frameNumber = mFrameNumber++;
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07005649 nextRequest->mResultExtras.afTriggerId = mCurrentAfTriggerId;
5650 nextRequest->mResultExtras.precaptureTriggerId = mCurrentPreCaptureTriggerId;
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07005651
5652 // Since RequestThread::clear() removes buffers from the input stream,
5653 // get the right buffer here before unlocking mRequestLock
5654 if (nextRequest->mInputStream != NULL) {
Shuzhen Wang83bff122020-11-20 15:51:39 -08005655 res = nextRequest->mInputStream->getInputBuffer(&nextRequest->mInputBuffer,
5656 &nextRequest->mInputBufferSize);
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07005657 if (res != OK) {
5658 // Can't get input buffer from gralloc queue - this could be due to
5659 // disconnected queue or other producer misbehavior, so not a fatal
5660 // error
5661 ALOGE("%s: Can't get input buffer, skipping request:"
5662 " %s (%d)", __FUNCTION__, strerror(-res), res);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005663
5664 sp<NotificationListener> listener = mListener.promote();
5665 if (listener != NULL) {
5666 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08005667 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07005668 nextRequest->mResultExtras);
5669 }
5670 return NULL;
5671 }
5672 }
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005673 }
Chien-Yu Chend196d612015-06-22 19:49:01 -07005674
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005675 return nextRequest;
5676}
5677
5678bool Camera3Device::RequestThread::waitIfPaused() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005679 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005680 status_t res;
5681 Mutex::Autolock l(mPauseLock);
5682 while (mDoPause) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005683 if (mPaused == false) {
5684 mPaused = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005685 ALOGV("%s: RequestThread: Paused", __FUNCTION__);
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07005686 if (mNotifyPipelineDrain) {
5687 mInterface->signalPipelineDrain(mStreamIdsToBeDrained);
5688 mNotifyPipelineDrain = false;
5689 mStreamIdsToBeDrained.clear();
5690 }
Yin-Chia Yehc300a072019-02-13 14:56:57 -08005691 // Let the tracker know
5692 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5693 if (statusTracker != 0) {
5694 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
5695 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005696 sp<Camera3Device> parent = mParent.promote();
5697 if (parent != nullptr) {
5698 parent->mRequestBufferSM.onRequestThreadPaused();
5699 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005700 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005701
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005702 res = mDoPauseSignal.waitRelative(mPauseLock, kRequestTimeout);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005703 if (res == TIMED_OUT || exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005704 return true;
5705 }
5706 }
5707 // We don't set mPaused to false here, because waitForNextRequest needs
5708 // to further manage the paused state in case of starvation.
5709 return false;
5710}
5711
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005712void Camera3Device::RequestThread::unpauseForNewRequests() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005713 ATRACE_CALL();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005714 // With work to do, mark thread as unpaused.
5715 // If paused by request (setPaused), don't resume, to avoid
5716 // extra signaling/waiting overhead to waitUntilPaused
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005717 mRequestSignal.signal();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005718 Mutex::Autolock p(mPauseLock);
5719 if (!mDoPause) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005720 ALOGV("%s: RequestThread: Going active", __FUNCTION__);
5721 if (mPaused) {
5722 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5723 if (statusTracker != 0) {
5724 statusTracker->markComponentActive(mStatusId);
5725 }
5726 }
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005727 mPaused = false;
5728 }
5729}
5730
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07005731void Camera3Device::RequestThread::setErrorState(const char *fmt, ...) {
5732 sp<Camera3Device> parent = mParent.promote();
5733 if (parent != NULL) {
5734 va_list args;
5735 va_start(args, fmt);
5736
5737 parent->setErrorStateV(fmt, args);
5738
5739 va_end(args);
5740 }
5741}
5742
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005743status_t Camera3Device::RequestThread::insertTriggers(
5744 const sp<CaptureRequest> &request) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005745 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005746 Mutex::Autolock al(mTriggerMutex);
5747
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07005748 sp<Camera3Device> parent = mParent.promote();
5749 if (parent == NULL) {
5750 CLOGE("RequestThread: Parent is gone");
5751 return DEAD_OBJECT;
5752 }
5753
Emilian Peevaebbe412018-01-15 13:53:24 +00005754 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005755 size_t count = mTriggerMap.size();
5756
5757 for (size_t i = 0; i < count; ++i) {
5758 RequestTrigger trigger = mTriggerMap.valueAt(i);
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005759 uint32_t tag = trigger.metadataTag;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07005760
5761 if (tag == ANDROID_CONTROL_AF_TRIGGER_ID || tag == ANDROID_CONTROL_AE_PRECAPTURE_ID) {
5762 bool isAeTrigger = (trigger.metadataTag == ANDROID_CONTROL_AE_PRECAPTURE_ID);
5763 uint32_t triggerId = static_cast<uint32_t>(trigger.entryValue);
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07005764 if (isAeTrigger) {
5765 request->mResultExtras.precaptureTriggerId = triggerId;
5766 mCurrentPreCaptureTriggerId = triggerId;
5767 } else {
5768 request->mResultExtras.afTriggerId = triggerId;
5769 mCurrentAfTriggerId = triggerId;
5770 }
Emilian Peev7e25e5e2017-04-07 15:48:49 +01005771 continue;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07005772 }
5773
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005774 camera_metadata_entry entry = metadata.find(tag);
5775
5776 if (entry.count > 0) {
5777 /**
5778 * Already has an entry for this trigger in the request.
5779 * Rewrite it with our requested trigger value.
5780 */
5781 RequestTrigger oldTrigger = trigger;
5782
5783 oldTrigger.entryValue = entry.data.u8[0];
5784
5785 mTriggerReplacedMap.add(tag, oldTrigger);
5786 } else {
5787 /**
5788 * More typical, no trigger entry, so we just add it
5789 */
5790 mTriggerRemovedMap.add(tag, trigger);
5791 }
5792
5793 status_t res;
5794
5795 switch (trigger.getTagType()) {
5796 case TYPE_BYTE: {
5797 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
5798 res = metadata.update(tag,
5799 &entryValue,
5800 /*count*/1);
5801 break;
5802 }
5803 case TYPE_INT32:
5804 res = metadata.update(tag,
5805 &trigger.entryValue,
5806 /*count*/1);
5807 break;
5808 default:
5809 ALOGE("%s: Type not supported: 0x%x",
5810 __FUNCTION__,
5811 trigger.getTagType());
5812 return INVALID_OPERATION;
5813 }
5814
5815 if (res != OK) {
5816 ALOGE("%s: Failed to update request metadata with trigger tag %s"
5817 ", value %d", __FUNCTION__, trigger.getTagName(),
5818 trigger.entryValue);
5819 return res;
5820 }
5821
5822 ALOGV("%s: Mixed in trigger %s, value %d", __FUNCTION__,
5823 trigger.getTagName(),
5824 trigger.entryValue);
5825 }
5826
5827 mTriggerMap.clear();
5828
5829 return count;
5830}
5831
5832status_t Camera3Device::RequestThread::removeTriggers(
5833 const sp<CaptureRequest> &request) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005834 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005835 Mutex::Autolock al(mTriggerMutex);
5836
Emilian Peevaebbe412018-01-15 13:53:24 +00005837 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005838
5839 /**
5840 * Replace all old entries with their old values.
5841 */
5842 for (size_t i = 0; i < mTriggerReplacedMap.size(); ++i) {
5843 RequestTrigger trigger = mTriggerReplacedMap.valueAt(i);
5844
5845 status_t res;
5846
5847 uint32_t tag = trigger.metadataTag;
5848 switch (trigger.getTagType()) {
5849 case TYPE_BYTE: {
5850 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
5851 res = metadata.update(tag,
5852 &entryValue,
5853 /*count*/1);
5854 break;
5855 }
5856 case TYPE_INT32:
5857 res = metadata.update(tag,
5858 &trigger.entryValue,
5859 /*count*/1);
5860 break;
5861 default:
5862 ALOGE("%s: Type not supported: 0x%x",
5863 __FUNCTION__,
5864 trigger.getTagType());
5865 return INVALID_OPERATION;
5866 }
5867
5868 if (res != OK) {
5869 ALOGE("%s: Failed to restore request metadata with trigger tag %s"
5870 ", trigger value %d", __FUNCTION__,
5871 trigger.getTagName(), trigger.entryValue);
5872 return res;
5873 }
5874 }
5875 mTriggerReplacedMap.clear();
5876
5877 /**
5878 * Remove all new entries.
5879 */
5880 for (size_t i = 0; i < mTriggerRemovedMap.size(); ++i) {
5881 RequestTrigger trigger = mTriggerRemovedMap.valueAt(i);
5882 status_t res = metadata.erase(trigger.metadataTag);
5883
5884 if (res != OK) {
5885 ALOGE("%s: Failed to erase metadata with trigger tag %s"
5886 ", trigger value %d", __FUNCTION__,
5887 trigger.getTagName(), trigger.entryValue);
5888 return res;
5889 }
5890 }
5891 mTriggerRemovedMap.clear();
5892
5893 return OK;
5894}
5895
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04005896status_t Camera3Device::RequestThread::addFakeTriggerIds(
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005897 const sp<CaptureRequest> &request) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08005898 // Trigger ID 0 had special meaning in the HAL2 spec, so avoid it here
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04005899 static const int32_t fakeTriggerId = 1;
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005900 status_t res;
5901
Emilian Peevaebbe412018-01-15 13:53:24 +00005902 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005903
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04005904 // If AF trigger is active, insert a fake AF trigger ID if none already
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005905 // exists
5906 camera_metadata_entry afTrigger = metadata.find(ANDROID_CONTROL_AF_TRIGGER);
5907 camera_metadata_entry afId = metadata.find(ANDROID_CONTROL_AF_TRIGGER_ID);
5908 if (afTrigger.count > 0 &&
5909 afTrigger.data.u8[0] != ANDROID_CONTROL_AF_TRIGGER_IDLE &&
5910 afId.count == 0) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04005911 res = metadata.update(ANDROID_CONTROL_AF_TRIGGER_ID, &fakeTriggerId, 1);
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005912 if (res != OK) return res;
5913 }
5914
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04005915 // If AE precapture trigger is active, insert a fake precapture trigger ID
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005916 // if none already exists
5917 camera_metadata_entry pcTrigger =
5918 metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER);
5919 camera_metadata_entry pcId = metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_ID);
5920 if (pcTrigger.count > 0 &&
5921 pcTrigger.data.u8[0] != ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_IDLE &&
5922 pcId.count == 0) {
5923 res = metadata.update(ANDROID_CONTROL_AE_PRECAPTURE_ID,
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04005924 &fakeTriggerId, 1);
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005925 if (res != OK) return res;
5926 }
5927
5928 return OK;
5929}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005930
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005931bool Camera3Device::RequestThread::overrideAutoRotateAndCrop(
5932 const sp<CaptureRequest> &request) {
5933 ATRACE_CALL();
5934
5935 if (request->mRotateAndCropAuto) {
5936 Mutex::Autolock l(mTriggerMutex);
5937 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
5938
5939 auto rotateAndCropEntry = metadata.find(ANDROID_SCALER_ROTATE_AND_CROP);
5940 if (rotateAndCropEntry.count > 0) {
5941 if (rotateAndCropEntry.data.u8[0] == mRotateAndCropOverride) {
5942 return false;
5943 } else {
5944 rotateAndCropEntry.data.u8[0] = mRotateAndCropOverride;
5945 return true;
5946 }
5947 } else {
5948 uint8_t rotateAndCrop_u8 = mRotateAndCropOverride;
5949 metadata.update(ANDROID_SCALER_ROTATE_AND_CROP,
5950 &rotateAndCrop_u8, 1);
5951 return true;
5952 }
5953 }
5954 return false;
5955}
5956
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005957bool Camera3Device::RequestThread::overrideTestPattern(
5958 const sp<CaptureRequest> &request) {
5959 ATRACE_CALL();
5960
Eino-Ville Talvala1646c3c2021-07-29 13:48:40 -07005961 if (!mSupportCameraMute) return false;
Eino-Ville Talvalac2459842021-07-22 16:36:36 -07005962
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005963 Mutex::Autolock l(mTriggerMutex);
5964
5965 bool changed = false;
5966
Shuzhen Wang911c6a32021-10-27 13:36:03 -07005967 // For a multi-camera, the physical cameras support the same set of
5968 // test pattern modes as the logical camera.
5969 for (auto& settings : request->mSettingsList) {
5970 CameraMetadata &metadata = settings.metadata;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005971
Shuzhen Wang911c6a32021-10-27 13:36:03 -07005972 int32_t testPatternMode = settings.mOriginalTestPatternMode;
5973 int32_t testPatternData[4] = {
5974 settings.mOriginalTestPatternData[0],
5975 settings.mOriginalTestPatternData[1],
5976 settings.mOriginalTestPatternData[2],
5977 settings.mOriginalTestPatternData[3]
5978 };
5979 if (mCameraMute != ANDROID_SENSOR_TEST_PATTERN_MODE_OFF) {
5980 testPatternMode = mCameraMute;
5981 testPatternData[0] = 0;
5982 testPatternData[1] = 0;
5983 testPatternData[2] = 0;
5984 testPatternData[3] = 0;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005985 }
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005986
Shuzhen Wang911c6a32021-10-27 13:36:03 -07005987 auto testPatternEntry = metadata.find(ANDROID_SENSOR_TEST_PATTERN_MODE);
5988 bool supportTestPatternModeKey = settings.mHasTestPatternModeTag;
5989 if (testPatternEntry.count > 0) {
5990 if (testPatternEntry.data.i32[0] != testPatternMode) {
5991 testPatternEntry.data.i32[0] = testPatternMode;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005992 changed = true;
5993 }
Shuzhen Wang911c6a32021-10-27 13:36:03 -07005994 } else if (supportTestPatternModeKey) {
5995 metadata.update(ANDROID_SENSOR_TEST_PATTERN_MODE,
5996 &testPatternMode, 1);
5997 changed = true;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005998 }
Shuzhen Wang911c6a32021-10-27 13:36:03 -07005999
6000 auto testPatternColor = metadata.find(ANDROID_SENSOR_TEST_PATTERN_DATA);
6001 bool supportTestPatternDataKey = settings.mHasTestPatternDataTag;
6002 if (testPatternColor.count >= 4) {
6003 for (size_t i = 0; i < 4; i++) {
6004 if (testPatternColor.data.i32[i] != testPatternData[i]) {
6005 testPatternColor.data.i32[i] = testPatternData[i];
6006 changed = true;
6007 }
6008 }
6009 } else if (supportTestPatternDataKey) {
6010 metadata.update(ANDROID_SENSOR_TEST_PATTERN_DATA,
6011 testPatternData, 4);
6012 changed = true;
6013 }
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08006014 }
6015
6016 return changed;
6017}
6018
Cliff Wuc2ad9c82021-04-21 00:58:58 +08006019status_t Camera3Device::RequestThread::setHalInterface(
6020 sp<HalInterface> newHalInterface) {
6021 if (newHalInterface.get() == nullptr) {
6022 ALOGE("%s: The newHalInterface does not exist!", __FUNCTION__);
6023 return DEAD_OBJECT;
6024 }
6025
6026 mInterface = newHalInterface;
6027
6028 return OK;
6029}
6030
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006031/**
6032 * PreparerThread inner class methods
6033 */
6034
6035Camera3Device::PreparerThread::PreparerThread() :
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07006036 Thread(/*canCallJava*/false), mListener(nullptr),
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006037 mActive(false), mCancelNow(false), mCurrentMaxCount(0), mCurrentPrepareComplete(false) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006038}
6039
6040Camera3Device::PreparerThread::~PreparerThread() {
6041 Thread::requestExitAndWait();
6042 if (mCurrentStream != nullptr) {
6043 mCurrentStream->cancelPrepare();
6044 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
6045 mCurrentStream.clear();
6046 }
6047 clear();
6048}
6049
Ruben Brunkc78ac262015-08-13 17:58:46 -07006050status_t Camera3Device::PreparerThread::prepare(int maxCount, sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07006051 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006052 status_t res;
6053
6054 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006055 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006056
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07006057 res = stream->startPrepare(maxCount, true /*blockRequest*/);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006058 if (res == OK) {
6059 // No preparation needed, fire listener right off
6060 ALOGV("%s: Stream %d already prepared", __FUNCTION__, stream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006061 if (listener != NULL) {
6062 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006063 }
6064 return OK;
6065 } else if (res != NOT_ENOUGH_DATA) {
6066 return res;
6067 }
6068
6069 // Need to prepare, start up thread if necessary
6070 if (!mActive) {
6071 // mRunning will change to false before the thread fully shuts down, so wait to be sure it
6072 // isn't running
6073 Thread::requestExitAndWait();
6074 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
6075 if (res != OK) {
6076 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__, res, strerror(-res));
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006077 if (listener != NULL) {
6078 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006079 }
6080 return res;
6081 }
6082 mCancelNow = false;
6083 mActive = true;
6084 ALOGV("%s: Preparer stream started", __FUNCTION__);
6085 }
6086
6087 // queue up the work
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006088 mPendingStreams.emplace(maxCount, stream);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006089 ALOGV("%s: Stream %d queued for preparing", __FUNCTION__, stream->getId());
6090
6091 return OK;
6092}
6093
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006094void Camera3Device::PreparerThread::pause() {
6095 ATRACE_CALL();
6096
6097 Mutex::Autolock l(mLock);
6098
6099 std::unordered_map<int, sp<camera3::Camera3StreamInterface> > pendingStreams;
6100 pendingStreams.insert(mPendingStreams.begin(), mPendingStreams.end());
6101 sp<camera3::Camera3StreamInterface> currentStream = mCurrentStream;
6102 int currentMaxCount = mCurrentMaxCount;
6103 mPendingStreams.clear();
6104 mCancelNow = true;
6105 while (mActive) {
6106 auto res = mThreadActiveSignal.waitRelative(mLock, kActiveTimeout);
6107 if (res == TIMED_OUT) {
6108 ALOGE("%s: Timed out waiting on prepare thread!", __FUNCTION__);
6109 return;
6110 } else if (res != OK) {
6111 ALOGE("%s: Encountered an error: %d waiting on prepare thread!", __FUNCTION__, res);
6112 return;
6113 }
6114 }
6115
6116 //Check whether the prepare thread was able to complete the current
6117 //stream. In case work is still pending emplace it along with the rest
6118 //of the streams in the pending list.
6119 if (currentStream != nullptr) {
6120 if (!mCurrentPrepareComplete) {
6121 pendingStreams.emplace(currentMaxCount, currentStream);
6122 }
6123 }
6124
6125 mPendingStreams.insert(pendingStreams.begin(), pendingStreams.end());
6126 for (const auto& it : mPendingStreams) {
6127 it.second->cancelPrepare();
6128 }
6129}
6130
6131status_t Camera3Device::PreparerThread::resume() {
6132 ATRACE_CALL();
6133 status_t res;
6134
6135 Mutex::Autolock l(mLock);
6136 sp<NotificationListener> listener = mListener.promote();
6137
6138 if (mActive) {
6139 ALOGE("%s: Trying to resume an already active prepare thread!", __FUNCTION__);
6140 return NO_INIT;
6141 }
6142
6143 auto it = mPendingStreams.begin();
6144 for (; it != mPendingStreams.end();) {
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07006145 res = it->second->startPrepare(it->first, true /*blockRequest*/);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006146 if (res == OK) {
6147 if (listener != NULL) {
6148 listener->notifyPrepared(it->second->getId());
6149 }
6150 it = mPendingStreams.erase(it);
6151 } else if (res != NOT_ENOUGH_DATA) {
6152 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__,
6153 res, strerror(-res));
6154 it = mPendingStreams.erase(it);
6155 } else {
6156 it++;
6157 }
6158 }
6159
6160 if (mPendingStreams.empty()) {
6161 return OK;
6162 }
6163
6164 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
6165 if (res != OK) {
6166 ALOGE("%s: Unable to start preparer stream: %d (%s)",
6167 __FUNCTION__, res, strerror(-res));
6168 return res;
6169 }
6170 mCancelNow = false;
6171 mActive = true;
6172 ALOGV("%s: Preparer stream started", __FUNCTION__);
6173
6174 return OK;
6175}
6176
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006177status_t Camera3Device::PreparerThread::clear() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07006178 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006179 Mutex::Autolock l(mLock);
6180
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006181 for (const auto& it : mPendingStreams) {
6182 it.second->cancelPrepare();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006183 }
6184 mPendingStreams.clear();
6185 mCancelNow = true;
6186
6187 return OK;
6188}
6189
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006190void Camera3Device::PreparerThread::setNotificationListener(wp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07006191 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006192 Mutex::Autolock l(mLock);
6193 mListener = listener;
6194}
6195
6196bool Camera3Device::PreparerThread::threadLoop() {
6197 status_t res;
6198 {
6199 Mutex::Autolock l(mLock);
6200 if (mCurrentStream == nullptr) {
6201 // End thread if done with work
6202 if (mPendingStreams.empty()) {
6203 ALOGV("%s: Preparer stream out of work", __FUNCTION__);
6204 // threadLoop _must not_ re-acquire mLock after it sets mActive to false; would
6205 // cause deadlock with prepare()'s requestExitAndWait triggered by !mActive.
6206 mActive = false;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006207 mThreadActiveSignal.signal();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006208 return false;
6209 }
6210
6211 // Get next stream to prepare
6212 auto it = mPendingStreams.begin();
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006213 mCurrentStream = it->second;
6214 mCurrentMaxCount = it->first;
6215 mCurrentPrepareComplete = false;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006216 mPendingStreams.erase(it);
6217 ATRACE_ASYNC_BEGIN("stream prepare", mCurrentStream->getId());
6218 ALOGV("%s: Preparing stream %d", __FUNCTION__, mCurrentStream->getId());
6219 } else if (mCancelNow) {
6220 mCurrentStream->cancelPrepare();
6221 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
6222 ALOGV("%s: Cancelling stream %d prepare", __FUNCTION__, mCurrentStream->getId());
6223 mCurrentStream.clear();
6224 mCancelNow = false;
6225 return true;
6226 }
6227 }
6228
6229 res = mCurrentStream->prepareNextBuffer();
6230 if (res == NOT_ENOUGH_DATA) return true;
6231 if (res != OK) {
6232 // Something bad happened; try to recover by cancelling prepare and
6233 // signalling listener anyway
6234 ALOGE("%s: Stream %d returned error %d (%s) during prepare", __FUNCTION__,
6235 mCurrentStream->getId(), res, strerror(-res));
6236 mCurrentStream->cancelPrepare();
6237 }
6238
6239 // This stream has finished, notify listener
6240 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006241 sp<NotificationListener> listener = mListener.promote();
6242 if (listener != NULL) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006243 ALOGV("%s: Stream %d prepare done, signaling listener", __FUNCTION__,
6244 mCurrentStream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006245 listener->notifyPrepared(mCurrentStream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006246 }
6247
6248 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
6249 mCurrentStream.clear();
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006250 mCurrentPrepareComplete = true;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006251
6252 return true;
6253}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07006254
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006255status_t Camera3Device::RequestBufferStateMachine::initialize(
6256 sp<camera3::StatusTracker> statusTracker) {
6257 if (statusTracker == nullptr) {
6258 ALOGE("%s: statusTracker is null", __FUNCTION__);
6259 return BAD_VALUE;
6260 }
6261
6262 std::lock_guard<std::mutex> lock(mLock);
6263 mStatusTracker = statusTracker;
Yin-Chia Yeh87b3ec02019-06-03 10:44:39 -07006264 mRequestBufferStatusId = statusTracker->addComponent("BufferRequestSM");
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006265 return OK;
6266}
6267
6268bool Camera3Device::RequestBufferStateMachine::startRequestBuffer() {
6269 std::lock_guard<std::mutex> lock(mLock);
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08006270 if (mStatus == RB_STATUS_READY || mStatus == RB_STATUS_PENDING_STOP) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006271 mRequestBufferOngoing = true;
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08006272 notifyTrackerLocked(/*active*/true);
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006273 return true;
6274 }
6275 return false;
6276}
6277
6278void Camera3Device::RequestBufferStateMachine::endRequestBuffer() {
6279 std::lock_guard<std::mutex> lock(mLock);
6280 if (!mRequestBufferOngoing) {
6281 ALOGE("%s called without a successful startRequestBuffer call first!", __FUNCTION__);
6282 return;
6283 }
6284 mRequestBufferOngoing = false;
6285 if (mStatus == RB_STATUS_PENDING_STOP) {
6286 checkSwitchToStopLocked();
6287 }
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08006288 notifyTrackerLocked(/*active*/false);
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006289}
6290
6291void Camera3Device::RequestBufferStateMachine::onStreamsConfigured() {
6292 std::lock_guard<std::mutex> lock(mLock);
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006293 mSwitchedToOffline = false;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006294 mStatus = RB_STATUS_READY;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006295 return;
6296}
6297
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08006298void Camera3Device::RequestBufferStateMachine::onSubmittingRequest() {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006299 std::lock_guard<std::mutex> lock(mLock);
6300 mRequestThreadPaused = false;
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08006301 // inflight map register actually happens in prepareHalRequest now, but it is close enough
6302 // approximation.
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006303 mInflightMapEmpty = false;
6304 if (mStatus == RB_STATUS_STOPPED) {
6305 mStatus = RB_STATUS_READY;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006306 }
6307 return;
6308}
6309
6310void Camera3Device::RequestBufferStateMachine::onRequestThreadPaused() {
6311 std::lock_guard<std::mutex> lock(mLock);
6312 mRequestThreadPaused = true;
6313 if (mStatus == RB_STATUS_PENDING_STOP) {
6314 checkSwitchToStopLocked();
6315 }
6316 return;
6317}
6318
6319void Camera3Device::RequestBufferStateMachine::onInflightMapEmpty() {
6320 std::lock_guard<std::mutex> lock(mLock);
6321 mInflightMapEmpty = true;
6322 if (mStatus == RB_STATUS_PENDING_STOP) {
6323 checkSwitchToStopLocked();
6324 }
6325 return;
6326}
6327
6328void Camera3Device::RequestBufferStateMachine::onWaitUntilIdle() {
6329 std::lock_guard<std::mutex> lock(mLock);
6330 if (!checkSwitchToStopLocked()) {
6331 mStatus = RB_STATUS_PENDING_STOP;
6332 }
6333 return;
6334}
6335
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006336bool Camera3Device::RequestBufferStateMachine::onSwitchToOfflineSuccess() {
6337 std::lock_guard<std::mutex> lock(mLock);
6338 if (mRequestBufferOngoing) {
6339 ALOGE("%s: HAL must not be requesting buffer after HAL returns switchToOffline!",
6340 __FUNCTION__);
6341 return false;
6342 }
6343 mSwitchedToOffline = true;
6344 mInflightMapEmpty = true;
6345 mRequestThreadPaused = true;
6346 mStatus = RB_STATUS_STOPPED;
6347 return true;
6348}
6349
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006350void Camera3Device::RequestBufferStateMachine::notifyTrackerLocked(bool active) {
6351 sp<StatusTracker> statusTracker = mStatusTracker.promote();
6352 if (statusTracker != nullptr) {
6353 if (active) {
6354 statusTracker->markComponentActive(mRequestBufferStatusId);
6355 } else {
6356 statusTracker->markComponentIdle(mRequestBufferStatusId, Fence::NO_FENCE);
6357 }
6358 }
6359}
6360
6361bool Camera3Device::RequestBufferStateMachine::checkSwitchToStopLocked() {
6362 if (mInflightMapEmpty && mRequestThreadPaused && !mRequestBufferOngoing) {
6363 mStatus = RB_STATUS_STOPPED;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006364 return true;
6365 }
6366 return false;
6367}
6368
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006369bool Camera3Device::startRequestBuffer() {
6370 return mRequestBufferSM.startRequestBuffer();
6371}
Shuzhen Wang268a1362018-10-16 16:32:59 -07006372
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006373void Camera3Device::endRequestBuffer() {
6374 mRequestBufferSM.endRequestBuffer();
6375}
Shuzhen Wang268a1362018-10-16 16:32:59 -07006376
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006377nsecs_t Camera3Device::getWaitDuration() {
6378 return kBaseGetBufferWait + getExpectedInFlightDuration();
6379}
Shuzhen Wang268a1362018-10-16 16:32:59 -07006380
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006381void Camera3Device::getInflightBufferKeys(std::vector<std::pair<int32_t, int32_t>>* out) {
6382 mInterface->getInflightBufferKeys(out);
6383}
Shuzhen Wang268a1362018-10-16 16:32:59 -07006384
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006385void Camera3Device::getInflightRequestBufferKeys(std::vector<uint64_t>* out) {
6386 mInterface->getInflightRequestBufferKeys(out);
6387}
Shuzhen Wang268a1362018-10-16 16:32:59 -07006388
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006389std::vector<sp<Camera3StreamInterface>> Camera3Device::getAllStreams() {
6390 std::vector<sp<Camera3StreamInterface>> ret;
6391 bool hasInputStream = mInputStream != nullptr;
6392 ret.reserve(mOutputStreams.size() + mDeletedStreams.size() + ((hasInputStream) ? 1 : 0));
6393 if (hasInputStream) {
6394 ret.push_back(mInputStream);
Shuzhen Wang268a1362018-10-16 16:32:59 -07006395 }
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006396 for (size_t i = 0; i < mOutputStreams.size(); i++) {
6397 ret.push_back(mOutputStreams[i]);
6398 }
6399 for (size_t i = 0; i < mDeletedStreams.size(); i++) {
6400 ret.push_back(mDeletedStreams[i]);
6401 }
6402 return ret;
Shuzhen Wang268a1362018-10-16 16:32:59 -07006403}
6404
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006405status_t Camera3Device::switchToOffline(
6406 const std::vector<int32_t>& streamsToKeep,
6407 /*out*/ sp<CameraOfflineSessionBase>* session) {
6408 ATRACE_CALL();
6409 if (session == nullptr) {
6410 ALOGE("%s: session must not be null", __FUNCTION__);
6411 return BAD_VALUE;
6412 }
6413
6414 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006415
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006416 bool hasInputStream = mInputStream != nullptr;
6417 int32_t inputStreamId = hasInputStream ? mInputStream->getId() : -1;
6418 bool inputStreamSupportsOffline = hasInputStream ?
6419 mInputStream->getOfflineProcessingSupport() : false;
6420 auto outputStreamIds = mOutputStreams.getStreamIds();
6421 auto streamIds = outputStreamIds;
6422 if (hasInputStream) {
6423 streamIds.push_back(mInputStream->getId());
6424 }
6425
6426 // Check all streams in streamsToKeep supports offline mode
6427 for (auto id : streamsToKeep) {
6428 if (std::find(streamIds.begin(), streamIds.end(), id) == streamIds.end()) {
6429 ALOGE("%s: Unknown stream ID %d", __FUNCTION__, id);
6430 return BAD_VALUE;
6431 } else if (id == inputStreamId) {
6432 if (!inputStreamSupportsOffline) {
6433 ALOGE("%s: input stream %d cannot be switched to offline",
6434 __FUNCTION__, id);
6435 return BAD_VALUE;
6436 }
6437 } else {
6438 sp<camera3::Camera3OutputStreamInterface> stream = mOutputStreams.get(id);
6439 if (!stream->getOfflineProcessingSupport()) {
6440 ALOGE("%s: output stream %d cannot be switched to offline",
6441 __FUNCTION__, id);
6442 return BAD_VALUE;
6443 }
6444 }
6445 }
6446
6447 // TODO: block surface sharing and surface group streams until we can support them
6448
6449 // Stop repeating request, wait until all remaining requests are submitted, then call into
6450 // HAL switchToOffline
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006451 hardware::camera::device::V3_6::CameraOfflineSessionInfo offlineSessionInfo;
6452 sp<hardware::camera::device::V3_6::ICameraOfflineSession> offlineSession;
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006453 camera3::BufferRecords bufferRecords;
6454 status_t ret = mRequestThread->switchToOffline(
6455 streamsToKeep, &offlineSessionInfo, &offlineSession, &bufferRecords);
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006456
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006457 if (ret != OK) {
6458 SET_ERR("Switch to offline failed: %s (%d)", strerror(-ret), ret);
6459 return ret;
6460 }
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006461
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006462 bool succ = mRequestBufferSM.onSwitchToOfflineSuccess();
6463 if (!succ) {
6464 SET_ERR("HAL must not be calling requestStreamBuffers call");
6465 // TODO: block ALL callbacks from HAL till app configured new streams?
6466 return UNKNOWN_ERROR;
6467 }
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006468
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006469 // Verify offlineSessionInfo
6470 std::vector<int32_t> offlineStreamIds;
6471 offlineStreamIds.reserve(offlineSessionInfo.offlineStreams.size());
6472 for (auto offlineStream : offlineSessionInfo.offlineStreams) {
6473 // verify stream IDs
6474 int32_t id = offlineStream.id;
6475 if (std::find(streamIds.begin(), streamIds.end(), id) == streamIds.end()) {
6476 SET_ERR("stream ID %d not found!", id);
6477 return UNKNOWN_ERROR;
6478 }
6479
6480 // When not using HAL buf manager, only allow streams requested by app to be preserved
6481 if (!mUseHalBufManager) {
6482 if (std::find(streamsToKeep.begin(), streamsToKeep.end(), id) == streamsToKeep.end()) {
6483 SET_ERR("stream ID %d must not be switched to offline!", id);
6484 return UNKNOWN_ERROR;
6485 }
6486 }
6487
6488 offlineStreamIds.push_back(id);
6489 sp<Camera3StreamInterface> stream = (id == inputStreamId) ?
6490 static_cast<sp<Camera3StreamInterface>>(mInputStream) :
6491 static_cast<sp<Camera3StreamInterface>>(mOutputStreams.get(id));
6492 // Verify number of outstanding buffers
6493 if (stream->getOutstandingBuffersCount() != offlineStream.numOutstandingBuffers) {
6494 SET_ERR("Offline stream %d # of remaining buffer mismatch: (%zu,%d) (service/HAL)",
6495 id, stream->getOutstandingBuffersCount(), offlineStream.numOutstandingBuffers);
6496 return UNKNOWN_ERROR;
6497 }
6498 }
6499
6500 // Verify all streams to be deleted don't have any outstanding buffers
6501 if (hasInputStream && std::find(offlineStreamIds.begin(), offlineStreamIds.end(),
6502 inputStreamId) == offlineStreamIds.end()) {
6503 if (mInputStream->hasOutstandingBuffers()) {
6504 SET_ERR("Input stream %d still has %zu outstanding buffer!",
6505 inputStreamId, mInputStream->getOutstandingBuffersCount());
6506 return UNKNOWN_ERROR;
6507 }
6508 }
6509
6510 for (const auto& outStreamId : outputStreamIds) {
6511 if (std::find(offlineStreamIds.begin(), offlineStreamIds.end(),
6512 outStreamId) == offlineStreamIds.end()) {
6513 auto outStream = mOutputStreams.get(outStreamId);
6514 if (outStream->hasOutstandingBuffers()) {
6515 SET_ERR("Output stream %d still has %zu outstanding buffer!",
6516 outStreamId, outStream->getOutstandingBuffersCount());
6517 return UNKNOWN_ERROR;
6518 }
6519 }
6520 }
6521
6522 InFlightRequestMap offlineReqs;
6523 // Verify inflight requests and their pending buffers
6524 {
6525 std::lock_guard<std::mutex> l(mInFlightLock);
6526 for (auto offlineReq : offlineSessionInfo.offlineRequests) {
6527 int idx = mInFlightMap.indexOfKey(offlineReq.frameNumber);
6528 if (idx == NAME_NOT_FOUND) {
6529 SET_ERR("Offline request frame number %d not found!", offlineReq.frameNumber);
6530 return UNKNOWN_ERROR;
6531 }
6532
6533 const auto& inflightReq = mInFlightMap.valueAt(idx);
6534 // TODO: check specific stream IDs
6535 size_t numBuffersLeft = static_cast<size_t>(inflightReq.numBuffersLeft);
6536 if (numBuffersLeft != offlineReq.pendingStreams.size()) {
6537 SET_ERR("Offline request # of remaining buffer mismatch: (%d,%d) (service/HAL)",
6538 inflightReq.numBuffersLeft, offlineReq.pendingStreams.size());
6539 return UNKNOWN_ERROR;
6540 }
6541 offlineReqs.add(offlineReq.frameNumber, inflightReq);
6542 }
6543 }
6544
6545 // Create Camera3OfflineSession and transfer object ownership
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006546 // (streams, inflight requests, buffer caches)
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006547 camera3::StreamSet offlineStreamSet;
6548 sp<camera3::Camera3Stream> inputStream;
6549 for (auto offlineStream : offlineSessionInfo.offlineStreams) {
6550 int32_t id = offlineStream.id;
6551 if (mInputStream != nullptr && id == mInputStream->getId()) {
6552 inputStream = mInputStream;
6553 } else {
6554 offlineStreamSet.add(id, mOutputStreams.get(id));
6555 }
6556 }
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006557
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006558 // TODO: check if we need to lock before copying states
6559 // though technically no other thread should be talking to Camera3Device at this point
6560 Camera3OfflineStates offlineStates(
6561 mTagMonitor, mVendorTagId, mUseHalBufManager, mNeedFixupMonochromeTags,
Shuzhen Wangb7b42652020-05-07 11:59:02 -07006562 mUsePartialResult, mNumPartialResults, mLastCompletedRegularFrameNumber,
6563 mLastCompletedReprocessFrameNumber, mLastCompletedZslFrameNumber,
6564 mNextResultFrameNumber, mNextReprocessResultFrameNumber,
6565 mNextZslStillResultFrameNumber, mNextShutterFrameNumber,
6566 mNextReprocessShutterFrameNumber, mNextZslStillShutterFrameNumber,
6567 mDeviceInfo, mPhysicalDeviceInfoMap, mDistortionMappers,
6568 mZoomRatioMappers, mRotateAndCropMappers);
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006569
6570 *session = new Camera3OfflineSession(mId, inputStream, offlineStreamSet,
6571 std::move(bufferRecords), offlineReqs, offlineStates, offlineSession);
6572
6573 // Delete all streams that has been transferred to offline session
6574 Mutex::Autolock l(mLock);
6575 for (auto offlineStream : offlineSessionInfo.offlineStreams) {
6576 int32_t id = offlineStream.id;
6577 if (mInputStream != nullptr && id == mInputStream->getId()) {
6578 mInputStream.clear();
6579 } else {
6580 mOutputStreams.remove(id);
6581 }
6582 }
6583
6584 // disconnect all other streams and switch to UNCONFIGURED state
6585 if (mInputStream != nullptr) {
6586 ret = mInputStream->disconnect();
6587 if (ret != OK) {
6588 SET_ERR_L("disconnect input stream failed!");
6589 return UNKNOWN_ERROR;
6590 }
6591 }
6592
6593 for (auto streamId : mOutputStreams.getStreamIds()) {
6594 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
6595 ret = stream->disconnect();
6596 if (ret != OK) {
6597 SET_ERR_L("disconnect output stream %d failed!", streamId);
6598 return UNKNOWN_ERROR;
6599 }
6600 }
6601
6602 mInputStream.clear();
6603 mOutputStreams.clear();
6604 mNeedConfig = true;
6605 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
6606 mOperatingMode = NO_MODE;
6607 mIsConstrainedHighSpeedConfiguration = false;
Emilian Peevc0fe54c2020-03-11 14:05:07 -07006608 mRequestThread->clearPreviousRequest();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006609
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006610 return OK;
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006611 // TO be done by CameraDeviceClient/Camera3OfflineSession
6612 // register the offline client to camera service
6613 // Setup result passthing threads etc
6614 // Initialize offline session so HAL can start sending callback to it (result Fmq)
6615 // TODO: check how many onIdle callback will be sent
6616 // Java side to make sure the CameraCaptureSession is properly closed
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006617}
6618
Emilian Peevcc0b7952020-01-07 13:54:47 -08006619void Camera3Device::getOfflineStreamIds(std::vector<int> *offlineStreamIds) {
6620 ATRACE_CALL();
6621
6622 if (offlineStreamIds == nullptr) {
6623 return;
6624 }
6625
6626 Mutex::Autolock il(mInterfaceLock);
6627
6628 auto streamIds = mOutputStreams.getStreamIds();
6629 bool hasInputStream = mInputStream != nullptr;
6630 if (hasInputStream && mInputStream->getOfflineProcessingSupport()) {
6631 offlineStreamIds->push_back(mInputStream->getId());
6632 }
6633
6634 for (const auto & streamId : streamIds) {
6635 sp<camera3::Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
6636 // Streams that use the camera buffer manager are currently not supported in
6637 // offline mode
6638 if (stream->getOfflineProcessingSupport() &&
6639 (stream->getStreamSetId() == CAMERA3_STREAM_SET_ID_INVALID)) {
6640 offlineStreamIds->push_back(streamId);
6641 }
6642 }
6643}
6644
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08006645status_t Camera3Device::setRotateAndCropAutoBehavior(
6646 camera_metadata_enum_android_scaler_rotate_and_crop_t rotateAndCropValue) {
6647 ATRACE_CALL();
6648 Mutex::Autolock il(mInterfaceLock);
6649 Mutex::Autolock l(mLock);
6650 if (mRequestThread == nullptr) {
6651 return INVALID_OPERATION;
6652 }
6653 return mRequestThread->setRotateAndCropAutoBehavior(rotateAndCropValue);
6654}
6655
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08006656bool Camera3Device::supportsCameraMute() {
6657 Mutex::Autolock il(mInterfaceLock);
6658 Mutex::Autolock l(mLock);
6659
6660 return mSupportCameraMute;
6661}
6662
6663status_t Camera3Device::setCameraMute(bool enabled) {
6664 ATRACE_CALL();
6665 Mutex::Autolock il(mInterfaceLock);
6666 Mutex::Autolock l(mLock);
6667
6668 if (mRequestThread == nullptr || !mSupportCameraMute) {
6669 return INVALID_OPERATION;
6670 }
Eino-Ville Talvala11afe4f2021-05-27 14:45:31 -07006671 int32_t muteMode =
6672 !enabled ? ANDROID_SENSOR_TEST_PATTERN_MODE_OFF :
6673 mSupportTestPatternSolidColor ? ANDROID_SENSOR_TEST_PATTERN_MODE_SOLID_COLOR :
6674 ANDROID_SENSOR_TEST_PATTERN_MODE_BLACK;
6675 return mRequestThread->setCameraMute(muteMode);
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08006676}
6677
Cliff Wuc2ad9c82021-04-21 00:58:58 +08006678status_t Camera3Device::injectCamera(const String8& injectedCamId,
6679 sp<CameraProviderManager> manager) {
6680 ALOGI("%s Injection camera: injectedCamId = %s", __FUNCTION__, injectedCamId.string());
6681 ATRACE_CALL();
6682 Mutex::Autolock il(mInterfaceLock);
Cliff Wu3b268182021-07-06 15:44:43 +08006683 // When the camera device is active, injectCamera() and stopInjection() will call
6684 // internalPauseAndWaitLocked() and internalResumeLocked(), and then they will call
6685 // mStatusChanged.waitRelative(mLock, timeout) of waitUntilStateThenRelock(). But
6686 // mStatusChanged.waitRelative(mLock, timeout)'s parameter: mutex "mLock" must be in the locked
6687 // state, so we need to add "Mutex::Autolock l(mLock)" to lock the "mLock" before calling
6688 // waitUntilStateThenRelock().
6689 Mutex::Autolock l(mLock);
Cliff Wuc2ad9c82021-04-21 00:58:58 +08006690
6691 status_t res = NO_ERROR;
6692 if (mInjectionMethods->isInjecting()) {
6693 if (injectedCamId == mInjectionMethods->getInjectedCamId()) {
6694 return OK;
6695 } else {
6696 res = mInjectionMethods->stopInjection();
6697 if (res != OK) {
6698 ALOGE("%s: Failed to stop the injection camera! ret != NO_ERROR: %d",
6699 __FUNCTION__, res);
6700 return res;
6701 }
6702 }
6703 }
6704
6705 res = mInjectionMethods->injectionInitialize(injectedCamId, manager, this);
6706 if (res != OK) {
6707 ALOGE("%s: Failed to initialize the injection camera! ret != NO_ERROR: %d",
6708 __FUNCTION__, res);
6709 return res;
6710 }
6711
Cliff Wuc2ad9c82021-04-21 00:58:58 +08006712 // When the second display of android is cast to the remote device, and the opened camera is
6713 // also cast to the second display, in this case, because the camera has configured the streams
6714 // at this time, we can directly call injectCamera() to replace the internal camera with
6715 // injection camera.
Cliff Wu3b268182021-07-06 15:44:43 +08006716 if (mInjectionMethods->isStreamConfigCompleteButNotInjected()) {
6717 ALOGD("%s: The opened camera is directly cast to the remote device.", __FUNCTION__);
6718
6719 camera3::camera_stream_configuration injectionConfig;
6720 std::vector<uint32_t> injectionBufferSizes;
6721 mInjectionMethods->getInjectionConfig(&injectionConfig, &injectionBufferSizes);
6722 if (mOperatingMode < 0 || injectionConfig.num_streams <= 0
6723 || injectionBufferSizes.size() <= 0) {
6724 ALOGE("Failed to inject camera due to abandoned configuration! "
6725 "mOperatingMode: %d injectionConfig.num_streams: %d "
6726 "injectionBufferSizes.size(): %zu", mOperatingMode,
6727 injectionConfig.num_streams, injectionBufferSizes.size());
6728 return DEAD_OBJECT;
6729 }
6730
Cliff Wuc2ad9c82021-04-21 00:58:58 +08006731 res = mInjectionMethods->injectCamera(
6732 injectionConfig, injectionBufferSizes);
6733 if (res != OK) {
6734 ALOGE("Can't finish inject camera process!");
6735 return res;
6736 }
6737 }
6738
6739 return OK;
6740}
6741
6742status_t Camera3Device::stopInjection() {
6743 ALOGI("%s: Injection camera: stopInjection", __FUNCTION__);
6744 Mutex::Autolock il(mInterfaceLock);
Cliff Wu3b268182021-07-06 15:44:43 +08006745 Mutex::Autolock l(mLock);
Cliff Wuc2ad9c82021-04-21 00:58:58 +08006746 return mInjectionMethods->stopInjection();
6747}
6748
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08006749}; // namespace android