blob: de418da6cc79e3de643a4f9dd89f88945612f85c [file] [log] [blame]
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001/*
Shuzhen Wangc28189a2017-11-27 23:05:10 -08002 * Copyright (C) 2013-2018 The Android Open Source Project
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#define LOG_TAG "Camera3-Device"
18#define ATRACE_TAG ATRACE_TAG_CAMERA
19//#define LOG_NDEBUG 0
20//#define LOG_NNDEBUG 0 // Per-frame verbose logging
21
22#ifdef LOG_NNDEBUG
23#define ALOGVV(...) ALOGV(__VA_ARGS__)
24#else
25#define ALOGVV(...) ((void)0)
26#endif
27
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -070028// Convenience macro for transient errors
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080029#define CLOGE(fmt, ...) ALOGE("Camera %s: %s: " fmt, mId.string(), __FUNCTION__, \
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -070030 ##__VA_ARGS__)
31
Yin-Chia Yeh99fd0972019-06-27 14:22:44 -070032#define CLOGW(fmt, ...) ALOGW("Camera %s: %s: " fmt, mId.string(), __FUNCTION__, \
33 ##__VA_ARGS__)
34
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -070035// Convenience macros for transitioning to the error state
36#define SET_ERR(fmt, ...) setErrorState( \
37 "%s: " fmt, __FUNCTION__, \
38 ##__VA_ARGS__)
39#define SET_ERR_L(fmt, ...) setErrorStateLocked( \
40 "%s: " fmt, __FUNCTION__, \
41 ##__VA_ARGS__)
42
Colin Crosse5729fa2014-03-21 15:04:25 -070043#include <inttypes.h>
44
Shuzhen Wang5c22c152017-12-31 17:12:25 -080045#include <utility>
46
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080047#include <utils/Log.h>
48#include <utils/Trace.h>
49#include <utils/Timers.h>
Zhijun He90f7c372016-08-16 16:19:43 -070050#include <cutils/properties.h>
Eino-Ville Talvala7b82efe2013-07-25 17:12:35 -070051
Cliff Wuc2ad9c82021-04-21 00:58:58 +080052#include <android/hardware/camera/device/3.7/ICameraInjectionSession.h>
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -080053#include <android/hardware/camera2/ICameraDeviceUser.h>
54
Igor Murashkinff3e31d2013-10-23 16:40:06 -070055#include "utils/CameraTraces.h"
Eino-Ville Talvalaf99498e2015-09-25 16:52:55 -070056#include "mediautils/SchedulingPolicyService.h"
Eino-Ville Talvala7b82efe2013-07-25 17:12:35 -070057#include "device3/Camera3Device.h"
58#include "device3/Camera3OutputStream.h"
59#include "device3/Camera3InputStream.h"
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -040060#include "device3/Camera3FakeStream.h"
Shuzhen Wang0129d522016-10-30 22:43:41 -070061#include "device3/Camera3SharedOutputStream.h"
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -070062#include "CameraService.h"
Jayant Chowdhary12361932018-08-27 14:46:13 -070063#include "utils/CameraThreadState.h"
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -080064#include "utils/SessionConfigurationUtils.h"
Jayant Chowdharyd4776262020-06-23 23:45:57 -070065#include "utils/TraceHFR.h"
Shuzhen Wang316781a2020-08-18 18:11:01 -070066#include "utils/CameraServiceProxyWrapper.h"
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -080067
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -080068#include <algorithm>
Yin-Chia Yeh84be5782019-03-01 11:47:02 -080069#include <tuple>
70
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -080071using namespace android::camera3;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080072using namespace android::hardware::camera;
73using namespace android::hardware::camera::device::V3_2;
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -080074using android::hardware::camera::metadata::V3_6::CameraMetadataEnumAndroidSensorPixelMode;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080075
76namespace android {
77
Emilian Peev5104fe92021-10-21 14:27:09 -070078Camera3Device::Camera3Device(const String8 &id, bool overrideForPerfClass, bool legacyClient):
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080079 mId(id),
Emilian Peev5104fe92021-10-21 14:27:09 -070080 mLegacyClient(legacyClient),
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -080081 mOperatingMode(NO_MODE),
Eino-Ville Talvala9a179412015-06-09 13:15:16 -070082 mIsConstrainedHighSpeedConfiguration(false),
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -070083 mStatus(STATUS_UNINITIALIZED),
Ruben Brunk183f0562015-08-12 12:55:02 -070084 mStatusWaiters(0),
Zhijun He204e3292014-07-14 17:09:23 -070085 mUsePartialResult(false),
86 mNumPartialResults(1),
Shuzhen Wangc28dccc2016-02-11 23:48:46 -080087 mTimestampOffset(0),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -070088 mNextResultFrameNumber(0),
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -070089 mNextReprocessResultFrameNumber(0),
Shuzhen Wang5ee99842019-04-12 11:55:48 -070090 mNextZslStillResultFrameNumber(0),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -070091 mNextShutterFrameNumber(0),
Chien-Yu Chen3df11ce2015-09-30 14:13:30 -070092 mNextReprocessShutterFrameNumber(0),
Shuzhen Wang5ee99842019-04-12 11:55:48 -070093 mNextZslStillShutterFrameNumber(0),
Emilian Peev71c73a22017-03-21 16:35:51 +000094 mListener(NULL),
Emilian Peev811d2952018-05-25 11:08:40 +010095 mVendorTagId(CAMERA_METADATA_INVALID_VENDOR_ID),
Shuzhen Wang268a1362018-10-16 16:32:59 -070096 mLastTemplateId(-1),
Shuzhen Wangd4abdf72021-05-28 11:22:50 -070097 mNeedFixupMonochromeTags(false),
98 mOverrideForPerfClass(overrideForPerfClass)
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080099{
100 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800101 ALOGV("%s: Created device for camera %s", __FUNCTION__, mId.string());
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800102}
103
104Camera3Device::~Camera3Device()
105{
106 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800107 ALOGV("%s: Tearing down for camera id %s", __FUNCTION__, mId.string());
Yin-Chia Yehc5248132018-08-15 12:19:20 -0700108 disconnectImpl();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800109}
110
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800111const String8& Camera3Device::getId() const {
Igor Murashkin71381052013-03-04 14:53:08 -0800112 return mId;
113}
114
Emilian Peevbd8c5032018-02-14 23:05:40 +0000115status_t Camera3Device::initialize(sp<CameraProviderManager> manager, const String8& monitorTags) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800116 ATRACE_CALL();
117 Mutex::Autolock il(mInterfaceLock);
118 Mutex::Autolock l(mLock);
119
120 ALOGV("%s: Initializing HIDL device for camera %s", __FUNCTION__, mId.string());
121 if (mStatus != STATUS_UNINITIALIZED) {
122 CLOGE("Already initialized!");
123 return INVALID_OPERATION;
124 }
125 if (manager == nullptr) return INVALID_OPERATION;
126
127 sp<ICameraDeviceSession> session;
128 ATRACE_BEGIN("CameraHal::openSession");
Steven Moreland5ff9c912017-03-09 23:13:00 -0800129 status_t res = manager->openSession(mId.string(), this,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800130 /*out*/ &session);
131 ATRACE_END();
132 if (res != OK) {
133 SET_ERR_L("Could not open camera session: %s (%d)", strerror(-res), res);
134 return res;
135 }
136
Shuzhen Wangd4abdf72021-05-28 11:22:50 -0700137 res = manager->getCameraCharacteristics(mId.string(), mOverrideForPerfClass, &mDeviceInfo);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800138 if (res != OK) {
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700139 SET_ERR_L("Could not retrieve camera characteristics: %s (%d)", strerror(-res), res);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800140 session->close();
141 return res;
142 }
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800143 mSupportNativeZoomRatio = manager->supportNativeZoomRatio(mId.string());
Yin-Chia Yeh52778d42016-12-22 18:20:43 -0800144
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700145 std::vector<std::string> physicalCameraIds;
Shuzhen Wang03d8cc12018-09-12 14:17:09 -0700146 bool isLogical = manager->isLogicalCamera(mId.string(), &physicalCameraIds);
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700147 if (isLogical) {
148 for (auto& physicalId : physicalCameraIds) {
Shuzhen Wangd4abdf72021-05-28 11:22:50 -0700149 // Do not override characteristics for physical cameras
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -0700150 res = manager->getCameraCharacteristics(
Shuzhen Wangd4abdf72021-05-28 11:22:50 -0700151 physicalId, /*overrideForPerfClass*/false, &mPhysicalDeviceInfoMap[physicalId]);
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700152 if (res != OK) {
153 SET_ERR_L("Could not retrieve camera %s characteristics: %s (%d)",
154 physicalId.c_str(), strerror(-res), res);
155 session->close();
156 return res;
157 }
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -0700158
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800159 bool usePrecorrectArray =
160 DistortionMapper::isDistortionSupported(mPhysicalDeviceInfoMap[physicalId]);
161 if (usePrecorrectArray) {
162 res = mDistortionMappers[physicalId].setupStaticInfo(
163 mPhysicalDeviceInfoMap[physicalId]);
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -0700164 if (res != OK) {
165 SET_ERR_L("Unable to read camera %s's calibration fields for distortion "
166 "correction", physicalId.c_str());
167 session->close();
168 return res;
169 }
170 }
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800171
Shuzhen Wang1c834da2019-12-18 11:17:03 -0800172 mZoomRatioMappers[physicalId] = ZoomRatioMapper(
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800173 &mPhysicalDeviceInfoMap[physicalId],
174 mSupportNativeZoomRatio, usePrecorrectArray);
Jayant Chowdhary9255ce02021-07-15 11:18:17 -0700175
176 if (SessionConfigurationUtils::isUltraHighResolutionSensor(
177 mPhysicalDeviceInfoMap[physicalId])) {
178 mUHRCropAndMeteringRegionMappers[physicalId] =
179 UHRCropAndMeteringRegionMapper(mPhysicalDeviceInfoMap[physicalId],
180 usePrecorrectArray);
181 }
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700182 }
183 }
184
Yifan Hongf79b5542017-04-11 14:44:25 -0700185 std::shared_ptr<RequestMetadataQueue> queue;
Yifan Honga640c5a2017-04-12 16:30:31 -0700186 auto requestQueueRet = session->getCaptureRequestMetadataQueue(
187 [&queue](const auto& descriptor) {
188 queue = std::make_shared<RequestMetadataQueue>(descriptor);
189 if (!queue->isValid() || queue->availableToWrite() <= 0) {
190 ALOGE("HAL returns empty request metadata fmq, not use it");
191 queue = nullptr;
192 // don't use the queue onwards.
193 }
194 });
195 if (!requestQueueRet.isOk()) {
196 ALOGE("Transaction error when getting request metadata fmq: %s, not use it",
197 requestQueueRet.description().c_str());
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -0700198 return DEAD_OBJECT;
Yifan Hongf79b5542017-04-11 14:44:25 -0700199 }
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700200
201 std::unique_ptr<ResultMetadataQueue>& resQueue = mResultMetadataQueue;
Yifan Honga640c5a2017-04-12 16:30:31 -0700202 auto resultQueueRet = session->getCaptureResultMetadataQueue(
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700203 [&resQueue](const auto& descriptor) {
204 resQueue = std::make_unique<ResultMetadataQueue>(descriptor);
205 if (!resQueue->isValid() || resQueue->availableToWrite() <= 0) {
Yifan Honga640c5a2017-04-12 16:30:31 -0700206 ALOGE("HAL returns empty result metadata fmq, not use it");
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700207 resQueue = nullptr;
208 // Don't use the resQueue onwards.
Yifan Honga640c5a2017-04-12 16:30:31 -0700209 }
210 });
211 if (!resultQueueRet.isOk()) {
212 ALOGE("Transaction error when getting result metadata queue from camera session: %s",
213 resultQueueRet.description().c_str());
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -0700214 return DEAD_OBJECT;
Yifan Honga640c5a2017-04-12 16:30:31 -0700215 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -0700216 IF_ALOGV() {
217 session->interfaceChain([](
218 ::android::hardware::hidl_vec<::android::hardware::hidl_string> interfaceChain) {
219 ALOGV("Session interface chain:");
Chih-Hung Hsieh3ef324d2018-12-11 11:48:12 -0800220 for (const auto& iface : interfaceChain) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -0700221 ALOGV(" %s", iface.c_str());
222 }
223 });
224 }
Yifan Hongf79b5542017-04-11 14:44:25 -0700225
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -0800226 camera_metadata_entry bufMgrMode =
227 mDeviceInfo.find(ANDROID_INFO_SUPPORTED_BUFFER_MANAGEMENT_VERSION);
228 if (bufMgrMode.count > 0) {
229 mUseHalBufManager = (bufMgrMode.data.u8[0] ==
230 ANDROID_INFO_SUPPORTED_BUFFER_MANAGEMENT_VERSION_HIDL_DEVICE_3_5);
231 }
232
Yin-Chia Yehb978c382019-10-30 00:22:37 -0700233 camera_metadata_entry_t capabilities = mDeviceInfo.find(ANDROID_REQUEST_AVAILABLE_CAPABILITIES);
234 for (size_t i = 0; i < capabilities.count; i++) {
235 uint8_t capability = capabilities.data.u8[i];
236 if (capability == ANDROID_REQUEST_AVAILABLE_CAPABILITIES_OFFLINE_PROCESSING) {
237 mSupportOfflineProcessing = true;
238 }
239 }
240
241 mInterface = new HalInterface(session, queue, mUseHalBufManager, mSupportOfflineProcessing);
Emilian Peev71c73a22017-03-21 16:35:51 +0000242 std::string providerType;
243 mVendorTagId = manager->getProviderTagIdLocked(mId.string());
Emilian Peevbd8c5032018-02-14 23:05:40 +0000244 mTagMonitor.initialize(mVendorTagId);
245 if (!monitorTags.isEmpty()) {
246 mTagMonitor.parseTagsToMonitor(String8(monitorTags));
247 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800248
Shuzhen Wang268a1362018-10-16 16:32:59 -0700249 // Metadata tags needs fixup for monochrome camera device version less
250 // than 3.5.
251 hardware::hidl_version maxVersion{0,0};
252 res = manager->getHighestSupportedVersion(mId.string(), &maxVersion);
253 if (res != OK) {
254 ALOGE("%s: Error in getting camera device version id: %s (%d)",
255 __FUNCTION__, strerror(-res), res);
256 return res;
257 }
258 int deviceVersion = HARDWARE_DEVICE_API_VERSION(
259 maxVersion.get_major(), maxVersion.get_minor());
260
261 bool isMonochrome = false;
Yin-Chia Yehb978c382019-10-30 00:22:37 -0700262 for (size_t i = 0; i < capabilities.count; i++) {
263 uint8_t capability = capabilities.data.u8[i];
Shuzhen Wang268a1362018-10-16 16:32:59 -0700264 if (capability == ANDROID_REQUEST_AVAILABLE_CAPABILITIES_MONOCHROME) {
265 isMonochrome = true;
266 }
267 }
268 mNeedFixupMonochromeTags = (isMonochrome && deviceVersion < CAMERA_DEVICE_API_VERSION_3_5);
269
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800270 return initializeCommonLocked();
271}
272
273status_t Camera3Device::initializeCommonLocked() {
274
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700275 /** Start up status tracker thread */
276 mStatusTracker = new StatusTracker(this);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800277 status_t res = mStatusTracker->run(String8::format("C3Dev-%s-Status", mId.string()).string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700278 if (res != OK) {
279 SET_ERR_L("Unable to start status tracking thread: %s (%d)",
280 strerror(-res), res);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800281 mInterface->close();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700282 mStatusTracker.clear();
283 return res;
284 }
285
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -0700286 /** Register in-flight map to the status tracker */
Yin-Chia Yeh87b3ec02019-06-03 10:44:39 -0700287 mInFlightStatusId = mStatusTracker->addComponent("InflightRequests");
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -0700288
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -0700289 if (mUseHalBufManager) {
290 res = mRequestBufferSM.initialize(mStatusTracker);
291 if (res != OK) {
292 SET_ERR_L("Unable to start request buffer state machine: %s (%d)",
293 strerror(-res), res);
294 mInterface->close();
295 mStatusTracker.clear();
296 return res;
297 }
298 }
299
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -0800300 /** Create buffer manager */
301 mBufferManager = new Camera3BufferManager();
302
303 Vector<int32_t> sessionParamKeys;
304 camera_metadata_entry_t sessionKeysEntry = mDeviceInfo.find(
305 ANDROID_REQUEST_AVAILABLE_SESSION_KEYS);
306 if (sessionKeysEntry.count > 0) {
307 sessionParamKeys.insertArrayAt(sessionKeysEntry.data.i32, 0, sessionKeysEntry.count);
308 }
309
Eino-Ville Talvala1646c3c2021-07-29 13:48:40 -0700310 camera_metadata_entry_t availableTestPatternModes = mDeviceInfo.find(
311 ANDROID_SENSOR_AVAILABLE_TEST_PATTERN_MODES);
312 for (size_t i = 0; i < availableTestPatternModes.count; i++) {
313 if (availableTestPatternModes.data.i32[i] ==
314 ANDROID_SENSOR_TEST_PATTERN_MODE_SOLID_COLOR) {
315 mSupportCameraMute = true;
316 mSupportTestPatternSolidColor = true;
317 break;
318 } else if (availableTestPatternModes.data.i32[i] ==
319 ANDROID_SENSOR_TEST_PATTERN_MODE_BLACK) {
320 mSupportCameraMute = true;
321 mSupportTestPatternSolidColor = false;
322 }
323 }
324
Chien-Yu Chenab5135b2015-06-30 11:20:58 -0700325 /** Start up request queue thread */
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -0700326 mRequestThread = new RequestThread(
Eino-Ville Talvala1646c3c2021-07-29 13:48:40 -0700327 this, mStatusTracker, mInterface, sessionParamKeys,
328 mUseHalBufManager, mSupportCameraMute);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800329 res = mRequestThread->run(String8::format("C3Dev-%s-ReqQueue", mId.string()).string());
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800330 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700331 SET_ERR_L("Unable to start request queue thread: %s (%d)",
332 strerror(-res), res);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800333 mInterface->close();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800334 mRequestThread.clear();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800335 return res;
336 }
337
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -0700338 mPreparerThread = new PreparerThread();
339
Ruben Brunk183f0562015-08-12 12:55:02 -0700340 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800341 mNextStreamId = 0;
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -0400342 mFakeStreamId = NO_STREAM;
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -0700343 mNeedConfig = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700344 mPauseStateNotify = false;
Shuzhen Wang83bff122020-11-20 15:51:39 -0800345 mIsInputStreamMultiResolution = false;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800346
Shuzhen Wangc28dccc2016-02-11 23:48:46 -0800347 // Measure the clock domain offset between camera and video/hw_composer
348 camera_metadata_entry timestampSource =
349 mDeviceInfo.find(ANDROID_SENSOR_INFO_TIMESTAMP_SOURCE);
350 if (timestampSource.count > 0 && timestampSource.data.u8[0] ==
351 ANDROID_SENSOR_INFO_TIMESTAMP_SOURCE_REALTIME) {
352 mTimestampOffset = getMonoToBoottimeOffset();
353 }
354
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -0700355 // Will the HAL be sending in early partial result metadata?
Emilian Peev08dd2452017-04-06 16:55:14 +0100356 camera_metadata_entry partialResultsCount =
357 mDeviceInfo.find(ANDROID_REQUEST_PARTIAL_RESULT_COUNT);
358 if (partialResultsCount.count > 0) {
359 mNumPartialResults = partialResultsCount.data.i32[0];
360 mUsePartialResult = (mNumPartialResults > 1);
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -0700361 }
362
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800363 bool usePrecorrectArray = DistortionMapper::isDistortionSupported(mDeviceInfo);
364 if (usePrecorrectArray) {
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -0700365 res = mDistortionMappers[mId.c_str()].setupStaticInfo(mDeviceInfo);
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -0700366 if (res != OK) {
367 SET_ERR_L("Unable to read necessary calibration fields for distortion correction");
368 return res;
369 }
370 }
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800371
Shuzhen Wang1c834da2019-12-18 11:17:03 -0800372 mZoomRatioMappers[mId.c_str()] = ZoomRatioMapper(&mDeviceInfo,
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800373 mSupportNativeZoomRatio, usePrecorrectArray);
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800374
Jayant Chowdhary9255ce02021-07-15 11:18:17 -0700375 if (SessionConfigurationUtils::isUltraHighResolutionSensor(mDeviceInfo)) {
376 mUHRCropAndMeteringRegionMappers[mId.c_str()] =
377 UHRCropAndMeteringRegionMapper(mDeviceInfo, usePrecorrectArray);
378 }
379
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -0800380 if (RotateAndCropMapper::isNeeded(&mDeviceInfo)) {
381 mRotateAndCropMappers.emplace(mId.c_str(), &mDeviceInfo);
382 }
383
Cliff Wuc2ad9c82021-04-21 00:58:58 +0800384 mInjectionMethods = new Camera3DeviceInjectionMethods(this);
385
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800386 return OK;
387}
388
389status_t Camera3Device::disconnect() {
Yin-Chia Yehc5248132018-08-15 12:19:20 -0700390 return disconnectImpl();
391}
392
393status_t Camera3Device::disconnectImpl() {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800394 ATRACE_CALL();
Yin-Chia Yehe1c80632016-08-08 14:48:05 -0700395 ALOGI("%s: E", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800396
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700397 status_t res = OK;
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700398 std::vector<wp<Camera3StreamInterface>> streams;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700399 {
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800400 Mutex::Autolock il(mInterfaceLock);
401 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
402 {
403 Mutex::Autolock l(mLock);
404 if (mStatus == STATUS_UNINITIALIZED) return res;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700405
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800406 if (mStatus == STATUS_ACTIVE ||
407 (mStatus == STATUS_ERROR && mRequestThread != NULL)) {
408 res = mRequestThread->clearRepeatingRequests();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700409 if (res != OK) {
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800410 SET_ERR_L("Can't stop streaming");
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700411 // Continue to close device even in case of error
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800412 } else {
413 res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
414 if (res != OK) {
415 SET_ERR_L("Timeout waiting for HAL to drain (% " PRIi64 " ns)",
416 maxExpectedDuration);
417 // Continue to close device even in case of error
418 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700419 }
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700420 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800421
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800422 if (mStatus == STATUS_ERROR) {
423 CLOGE("Shutting down in an error state");
424 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700425
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800426 if (mStatusTracker != NULL) {
427 mStatusTracker->requestExit();
428 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700429
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800430 if (mRequestThread != NULL) {
431 mRequestThread->requestExit();
432 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700433
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800434 streams.reserve(mOutputStreams.size() + (mInputStream != nullptr ? 1 : 0));
435 for (size_t i = 0; i < mOutputStreams.size(); i++) {
436 streams.push_back(mOutputStreams[i]);
437 }
438 if (mInputStream != nullptr) {
439 streams.push_back(mInputStream);
440 }
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700441 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700442 }
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800443 // Joining done without holding mLock and mInterfaceLock, otherwise deadlocks may ensue
444 // as the threads try to access parent state (b/143513518)
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700445 if (mRequestThread != NULL && mStatus != STATUS_ERROR) {
446 // HAL may be in a bad state, so waiting for request thread
447 // (which may be stuck in the HAL processCaptureRequest call)
448 // could be dangerous.
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800449 // give up mInterfaceLock here and then lock it again. Could this lead
450 // to other deadlocks
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700451 mRequestThread->join();
452 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700453 {
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800454 Mutex::Autolock il(mInterfaceLock);
455 if (mStatusTracker != NULL) {
456 mStatusTracker->join();
457 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800458
Cliff Wuc2ad9c82021-04-21 00:58:58 +0800459 if (mInjectionMethods->isInjecting()) {
460 mInjectionMethods->stopInjection();
461 }
462
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800463 HalInterface* interface;
464 {
465 Mutex::Autolock l(mLock);
466 mRequestThread.clear();
467 Mutex::Autolock stLock(mTrackerLock);
468 mStatusTracker.clear();
469 interface = mInterface.get();
470 }
Eino-Ville Talvalaefff1c42015-08-28 16:27:27 -0700471
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800472 // Call close without internal mutex held, as the HAL close may need to
473 // wait on assorted callbacks,etc, to complete before it can return.
474 interface->close();
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700475
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800476 flushInflightRequests();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800477
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800478 {
479 Mutex::Autolock l(mLock);
480 mInterface->clear();
481 mOutputStreams.clear();
482 mInputStream.clear();
483 mDeletedStreams.clear();
484 mBufferManager.clear();
485 internalUpdateStatusLocked(STATUS_UNINITIALIZED);
486 }
487
488 for (auto& weakStream : streams) {
489 sp<Camera3StreamInterface> stream = weakStream.promote();
490 if (stream != nullptr) {
491 ALOGE("%s: Stream %d leaked! strong reference (%d)!",
492 __FUNCTION__, stream->getId(), stream->getStrongCount() - 1);
493 }
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700494 }
495 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -0700496 ALOGI("%s: X", __FUNCTION__);
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700497 return res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800498}
499
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700500// For dumping/debugging only -
501// try to acquire a lock a few times, eventually give up to proceed with
502// debug/dump operations
503bool Camera3Device::tryLockSpinRightRound(Mutex& lock) {
504 bool gotLock = false;
505 for (size_t i = 0; i < kDumpLockAttempts; ++i) {
506 if (lock.tryLock() == NO_ERROR) {
507 gotLock = true;
508 break;
509 } else {
510 usleep(kDumpSleepDuration);
511 }
512 }
513 return gotLock;
514}
515
Shuzhen Wangc28dccc2016-02-11 23:48:46 -0800516nsecs_t Camera3Device::getMonoToBoottimeOffset() {
517 // try three times to get the clock offset, choose the one
518 // with the minimum gap in measurements.
519 const int tries = 3;
520 nsecs_t bestGap, measured;
521 for (int i = 0; i < tries; ++i) {
522 const nsecs_t tmono = systemTime(SYSTEM_TIME_MONOTONIC);
523 const nsecs_t tbase = systemTime(SYSTEM_TIME_BOOTTIME);
524 const nsecs_t tmono2 = systemTime(SYSTEM_TIME_MONOTONIC);
525 const nsecs_t gap = tmono2 - tmono;
526 if (i == 0 || gap < bestGap) {
527 bestGap = gap;
528 measured = tbase - ((tmono + tmono2) >> 1);
529 }
530 }
531 return measured;
532}
533
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800534hardware::graphics::common::V1_0::PixelFormat Camera3Device::mapToPixelFormat(
535 int frameworkFormat) {
536 return (hardware::graphics::common::V1_0::PixelFormat) frameworkFormat;
537}
538
539DataspaceFlags Camera3Device::mapToHidlDataspace(
540 android_dataspace dataSpace) {
541 return dataSpace;
542}
543
Chia-I Wu67a0c0e2017-04-06 13:37:01 -0700544BufferUsageFlags Camera3Device::mapToConsumerUsage(
Emilian Peev050f5dc2017-05-18 14:43:56 +0100545 uint64_t usage) {
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -0700546 return usage;
547}
548
Emilian Peevf4816702020-04-03 15:44:51 -0700549StreamRotation Camera3Device::mapToStreamRotation(camera_stream_rotation_t rotation) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800550 switch (rotation) {
Emilian Peevf4816702020-04-03 15:44:51 -0700551 case CAMERA_STREAM_ROTATION_0:
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800552 return StreamRotation::ROTATION_0;
Emilian Peevf4816702020-04-03 15:44:51 -0700553 case CAMERA_STREAM_ROTATION_90:
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800554 return StreamRotation::ROTATION_90;
Emilian Peevf4816702020-04-03 15:44:51 -0700555 case CAMERA_STREAM_ROTATION_180:
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800556 return StreamRotation::ROTATION_180;
Emilian Peevf4816702020-04-03 15:44:51 -0700557 case CAMERA_STREAM_ROTATION_270:
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800558 return StreamRotation::ROTATION_270;
559 }
560 ALOGE("%s: Unknown stream rotation %d", __FUNCTION__, rotation);
561 return StreamRotation::ROTATION_0;
562}
563
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800564status_t Camera3Device::mapToStreamConfigurationMode(
Emilian Peevf4816702020-04-03 15:44:51 -0700565 camera_stream_configuration_mode_t operationMode, StreamConfigurationMode *mode) {
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800566 if (mode == nullptr) return BAD_VALUE;
Emilian Peevf4816702020-04-03 15:44:51 -0700567 if (operationMode < CAMERA_VENDOR_STREAM_CONFIGURATION_MODE_START) {
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800568 switch(operationMode) {
Emilian Peevf4816702020-04-03 15:44:51 -0700569 case CAMERA_STREAM_CONFIGURATION_NORMAL_MODE:
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800570 *mode = StreamConfigurationMode::NORMAL_MODE;
571 break;
Emilian Peevf4816702020-04-03 15:44:51 -0700572 case CAMERA_STREAM_CONFIGURATION_CONSTRAINED_HIGH_SPEED_MODE:
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800573 *mode = StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE;
574 break;
575 default:
576 ALOGE("%s: Unknown stream configuration mode %d", __FUNCTION__, operationMode);
577 return BAD_VALUE;
578 }
579 } else {
580 *mode = static_cast<StreamConfigurationMode>(operationMode);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800581 }
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800582 return OK;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800583}
584
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800585int Camera3Device::mapToFrameworkFormat(
586 hardware::graphics::common::V1_0::PixelFormat pixelFormat) {
587 return static_cast<uint32_t>(pixelFormat);
588}
589
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -0700590android_dataspace Camera3Device::mapToFrameworkDataspace(
591 DataspaceFlags dataSpace) {
592 return static_cast<android_dataspace>(dataSpace);
593}
594
Emilian Peev050f5dc2017-05-18 14:43:56 +0100595uint64_t Camera3Device::mapConsumerToFrameworkUsage(
Chia-I Wu67a0c0e2017-04-06 13:37:01 -0700596 BufferUsageFlags usage) {
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -0700597 return usage;
598}
599
Emilian Peev050f5dc2017-05-18 14:43:56 +0100600uint64_t Camera3Device::mapProducerToFrameworkUsage(
Chia-I Wu67a0c0e2017-04-06 13:37:01 -0700601 BufferUsageFlags usage) {
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -0700602 return usage;
603}
604
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -0800605ssize_t Camera3Device::getJpegBufferSize(const CameraMetadata &info, uint32_t width,
606 uint32_t height) const {
Jayant Chowdharycd3d36b2021-07-10 10:53:53 -0700607 // Get max jpeg size (area-wise) for default sensor pixel mode
608 camera3::Size maxDefaultJpegResolution =
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -0800609 SessionConfigurationUtils::getMaxJpegResolution(info,
Jayant Chowdharycd3d36b2021-07-10 10:53:53 -0700610 /*isUltraHighResolutionSensor*/false);
611 // Get max jpeg size (area-wise) for max resolution sensor pixel mode / 0 if
612 // not ultra high res sensor
613 camera3::Size uhrMaxJpegResolution =
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -0800614 SessionConfigurationUtils::getMaxJpegResolution(info,
Jayant Chowdharycd3d36b2021-07-10 10:53:53 -0700615 /*isUltraHighResolution*/true);
616 if (maxDefaultJpegResolution.width == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800617 ALOGE("%s: Camera %s: Can't find valid available jpeg sizes in static metadata!",
618 __FUNCTION__, mId.string());
Zhijun Hef7da0962014-04-24 13:27:56 -0700619 return BAD_VALUE;
620 }
Jayant Chowdharycd3d36b2021-07-10 10:53:53 -0700621 bool useMaxSensorPixelModeThreshold = false;
622 if (uhrMaxJpegResolution.width != 0 &&
623 width * height > maxDefaultJpegResolution.width * maxDefaultJpegResolution.height) {
624 // Use the ultra high res max jpeg size and max jpeg buffer size
625 useMaxSensorPixelModeThreshold = true;
626 }
Zhijun Hef7da0962014-04-24 13:27:56 -0700627
Zhijun Hef7da0962014-04-24 13:27:56 -0700628 // Get max jpeg buffer size
629 ssize_t maxJpegBufferSize = 0;
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -0800630 camera_metadata_ro_entry jpegBufMaxSize = info.find(ANDROID_JPEG_MAX_SIZE);
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700631 if (jpegBufMaxSize.count == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800632 ALOGE("%s: Camera %s: Can't find maximum JPEG size in static metadata!", __FUNCTION__,
633 mId.string());
Zhijun Hef7da0962014-04-24 13:27:56 -0700634 return BAD_VALUE;
635 }
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700636 maxJpegBufferSize = jpegBufMaxSize.data.i32[0];
Jayant Chowdharycd3d36b2021-07-10 10:53:53 -0700637
638 camera3::Size chosenMaxJpegResolution = maxDefaultJpegResolution;
639 if (useMaxSensorPixelModeThreshold) {
640 maxJpegBufferSize =
641 SessionConfigurationUtils::getUHRMaxJpegBufferSize(uhrMaxJpegResolution,
642 maxDefaultJpegResolution, maxJpegBufferSize);
643 chosenMaxJpegResolution = uhrMaxJpegResolution;
644 }
Yin-Chia Yeh0c4e56d2015-01-09 15:21:27 -0800645 assert(kMinJpegBufferSize < maxJpegBufferSize);
Zhijun Hef7da0962014-04-24 13:27:56 -0700646
647 // Calculate final jpeg buffer size for the given resolution.
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700648 float scaleFactor = ((float) (width * height)) /
Jayant Chowdharycd3d36b2021-07-10 10:53:53 -0700649 (chosenMaxJpegResolution.width * chosenMaxJpegResolution.height);
Yin-Chia Yeh0c4e56d2015-01-09 15:21:27 -0800650 ssize_t jpegBufferSize = scaleFactor * (maxJpegBufferSize - kMinJpegBufferSize) +
651 kMinJpegBufferSize;
Zhijun Hef7da0962014-04-24 13:27:56 -0700652 if (jpegBufferSize > maxJpegBufferSize) {
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -0800653 ALOGI("%s: jpeg buffer size calculated is > maxJpeg bufferSize(%zd), clamping",
654 __FUNCTION__, maxJpegBufferSize);
Zhijun Hef7da0962014-04-24 13:27:56 -0700655 jpegBufferSize = maxJpegBufferSize;
Zhijun Hef7da0962014-04-24 13:27:56 -0700656 }
Zhijun Hef7da0962014-04-24 13:27:56 -0700657 return jpegBufferSize;
658}
659
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -0800660ssize_t Camera3Device::getPointCloudBufferSize(const CameraMetadata &info) const {
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700661 const int FLOATS_PER_POINT=4;
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -0800662 camera_metadata_ro_entry maxPointCount = info.find(ANDROID_DEPTH_MAX_DEPTH_SAMPLES);
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700663 if (maxPointCount.count == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800664 ALOGE("%s: Camera %s: Can't find maximum depth point cloud size in static metadata!",
665 __FUNCTION__, mId.string());
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700666 return BAD_VALUE;
667 }
668 ssize_t maxBytesForPointCloud = sizeof(android_depth_points) +
669 maxPointCount.data.i32[0] * sizeof(float) * FLOATS_PER_POINT;
670 return maxBytesForPointCloud;
671}
672
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -0800673ssize_t Camera3Device::getRawOpaqueBufferSize(const CameraMetadata &info, int32_t width,
674 int32_t height, bool maxResolution) const {
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800675 const int PER_CONFIGURATION_SIZE = 3;
676 const int WIDTH_OFFSET = 0;
677 const int HEIGHT_OFFSET = 1;
678 const int SIZE_OFFSET = 2;
679 camera_metadata_ro_entry rawOpaqueSizes =
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -0800680 info.find(
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -0800681 camera3::SessionConfigurationUtils::getAppropriateModeTag(
682 ANDROID_SENSOR_OPAQUE_RAW_SIZE,
683 maxResolution));
Aurimas Liutikasbc57b122016-02-16 09:59:16 -0800684 size_t count = rawOpaqueSizes.count;
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800685 if (count == 0 || (count % PER_CONFIGURATION_SIZE)) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800686 ALOGE("%s: Camera %s: bad opaque RAW size static metadata length(%zu)!",
687 __FUNCTION__, mId.string(), count);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800688 return BAD_VALUE;
689 }
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700690
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800691 for (size_t i = 0; i < count; i += PER_CONFIGURATION_SIZE) {
692 if (width == rawOpaqueSizes.data.i32[i + WIDTH_OFFSET] &&
693 height == rawOpaqueSizes.data.i32[i + HEIGHT_OFFSET]) {
694 return rawOpaqueSizes.data.i32[i + SIZE_OFFSET];
695 }
696 }
697
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800698 ALOGE("%s: Camera %s: cannot find size for %dx%d opaque RAW image!",
699 __FUNCTION__, mId.string(), width, height);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800700 return BAD_VALUE;
701}
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700702
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800703status_t Camera3Device::dump(int fd, const Vector<String16> &args) {
704 ATRACE_CALL();
705 (void)args;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700706
707 // Try to lock, but continue in case of failure (to avoid blocking in
708 // deadlocks)
709 bool gotInterfaceLock = tryLockSpinRightRound(mInterfaceLock);
710 bool gotLock = tryLockSpinRightRound(mLock);
711
712 ALOGW_IF(!gotInterfaceLock,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800713 "Camera %s: %s: Unable to lock interface lock, proceeding anyway",
714 mId.string(), __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700715 ALOGW_IF(!gotLock,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800716 "Camera %s: %s: Unable to lock main lock, proceeding anyway",
717 mId.string(), __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700718
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800719 bool dumpTemplates = false;
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700720
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800721 String16 templatesOption("-t");
722 int n = args.size();
723 for (int i = 0; i < n; i++) {
724 if (args[i] == templatesOption) {
725 dumpTemplates = true;
726 }
Emilian Peevbd8c5032018-02-14 23:05:40 +0000727 if (args[i] == TagMonitor::kMonitorOption) {
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700728 if (i + 1 < n) {
729 String8 monitorTags = String8(args[i + 1]);
730 if (monitorTags == "off") {
731 mTagMonitor.disableMonitoring();
732 } else {
733 mTagMonitor.parseTagsToMonitor(monitorTags);
734 }
735 } else {
736 mTagMonitor.disableMonitoring();
737 }
738 }
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800739 }
740
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800741 String8 lines;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800742
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800743 const char *status =
744 mStatus == STATUS_ERROR ? "ERROR" :
745 mStatus == STATUS_UNINITIALIZED ? "UNINITIALIZED" :
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700746 mStatus == STATUS_UNCONFIGURED ? "UNCONFIGURED" :
747 mStatus == STATUS_CONFIGURED ? "CONFIGURED" :
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800748 mStatus == STATUS_ACTIVE ? "ACTIVE" :
749 "Unknown";
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700750
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800751 lines.appendFormat(" Device status: %s\n", status);
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700752 if (mStatus == STATUS_ERROR) {
753 lines.appendFormat(" Error cause: %s\n", mErrorCause.string());
754 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800755 lines.appendFormat(" Stream configuration:\n");
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800756 const char *mode =
757 mOperatingMode == static_cast<int>(StreamConfigurationMode::NORMAL_MODE) ? "NORMAL" :
758 mOperatingMode == static_cast<int>(
759 StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE) ? "CONSTRAINED_HIGH_SPEED" :
760 "CUSTOM";
761 lines.appendFormat(" Operation mode: %s (%d) \n", mode, mOperatingMode);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800762
763 if (mInputStream != NULL) {
764 write(fd, lines.string(), lines.size());
765 mInputStream->dump(fd, args);
766 } else {
767 lines.appendFormat(" No input stream.\n");
768 write(fd, lines.string(), lines.size());
769 }
770 for (size_t i = 0; i < mOutputStreams.size(); i++) {
771 mOutputStreams[i]->dump(fd,args);
772 }
773
Zhijun He431503c2016-03-07 17:30:16 -0800774 if (mBufferManager != NULL) {
775 lines = String8(" Camera3 Buffer Manager:\n");
776 write(fd, lines.string(), lines.size());
777 mBufferManager->dump(fd, args);
778 }
Zhijun He125684a2015-12-26 15:07:30 -0800779
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700780 lines = String8(" In-flight requests:\n");
Emilian Peeva6138c52021-06-24 12:52:38 -0700781 if (mInFlightLock.try_lock()) {
782 if (mInFlightMap.size() == 0) {
783 lines.append(" None\n");
784 } else {
785 for (size_t i = 0; i < mInFlightMap.size(); i++) {
786 InFlightRequest r = mInFlightMap.valueAt(i);
787 lines.appendFormat(" Frame %d | Timestamp: %" PRId64 ", metadata"
788 " arrived: %s, buffers left: %d\n", mInFlightMap.keyAt(i),
789 r.shutterTimestamp, r.haveResultMetadata ? "true" : "false",
790 r.numBuffersLeft);
791 }
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700792 }
Emilian Peeva6138c52021-06-24 12:52:38 -0700793 mInFlightLock.unlock();
794 } else {
795 lines.append(" Failed to acquire In-flight lock!\n");
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700796 }
797 write(fd, lines.string(), lines.size());
798
Shuzhen Wang686f6442017-06-20 16:16:04 -0700799 if (mRequestThread != NULL) {
800 mRequestThread->dumpCaptureRequestLatency(fd,
801 " ProcessCaptureRequest latency histogram:");
802 }
803
Igor Murashkin1e479c02013-09-06 16:55:14 -0700804 {
805 lines = String8(" Last request sent:\n");
806 write(fd, lines.string(), lines.size());
807
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700808 CameraMetadata lastRequest = getLatestRequestLocked();
Igor Murashkin1e479c02013-09-06 16:55:14 -0700809 lastRequest.dump(fd, /*verbosity*/2, /*indentation*/6);
810 }
811
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800812 if (dumpTemplates) {
Emilian Peevf4816702020-04-03 15:44:51 -0700813 const char *templateNames[CAMERA_TEMPLATE_COUNT] = {
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800814 "TEMPLATE_PREVIEW",
815 "TEMPLATE_STILL_CAPTURE",
816 "TEMPLATE_VIDEO_RECORD",
817 "TEMPLATE_VIDEO_SNAPSHOT",
818 "TEMPLATE_ZERO_SHUTTER_LAG",
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -0800819 "TEMPLATE_MANUAL",
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800820 };
821
Emilian Peevf4816702020-04-03 15:44:51 -0700822 for (int i = 1; i < CAMERA_TEMPLATE_COUNT; i++) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800823 camera_metadata_t *templateRequest = nullptr;
824 mInterface->constructDefaultRequestSettings(
Emilian Peevf4816702020-04-03 15:44:51 -0700825 (camera_request_template_t) i, &templateRequest);
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800826 lines = String8::format(" HAL Request %s:\n", templateNames[i-1]);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800827 if (templateRequest == nullptr) {
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800828 lines.append(" Not supported\n");
829 write(fd, lines.string(), lines.size());
830 } else {
831 write(fd, lines.string(), lines.size());
832 dump_indented_camera_metadata(templateRequest,
833 fd, /*verbosity*/2, /*indentation*/8);
834 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800835 free_camera_metadata(templateRequest);
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800836 }
837 }
838
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700839 mTagMonitor.dumpMonitoredMetadata(fd);
840
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800841 if (mInterface->valid()) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -0800842 lines = String8(" HAL device dump:\n");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800843 write(fd, lines.string(), lines.size());
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800844 mInterface->dump(fd);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800845 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800846
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700847 if (gotLock) mLock.unlock();
848 if (gotInterfaceLock) mInterfaceLock.unlock();
849
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800850 return OK;
851}
852
Emilian Peevfaa4bde2020-01-23 12:19:37 -0800853const CameraMetadata& Camera3Device::infoPhysical(const String8& physicalId) const {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800854 ALOGVV("%s: E", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800855 if (CC_UNLIKELY(mStatus == STATUS_UNINITIALIZED ||
856 mStatus == STATUS_ERROR)) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700857 ALOGW("%s: Access to static info %s!", __FUNCTION__,
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800858 mStatus == STATUS_ERROR ?
859 "when in error state" : "before init");
860 }
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700861 if (physicalId.isEmpty()) {
862 return mDeviceInfo;
863 } else {
864 std::string id(physicalId.c_str());
865 if (mPhysicalDeviceInfoMap.find(id) != mPhysicalDeviceInfoMap.end()) {
866 return mPhysicalDeviceInfoMap.at(id);
867 } else {
868 ALOGE("%s: Invalid physical camera id %s", __FUNCTION__, physicalId.c_str());
869 return mDeviceInfo;
870 }
871 }
872}
873
874const CameraMetadata& Camera3Device::info() const {
875 String8 emptyId;
Emilian Peevfaa4bde2020-01-23 12:19:37 -0800876 return infoPhysical(emptyId);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800877}
878
Jianing Wei90e59c92014-03-12 18:29:36 -0700879status_t Camera3Device::checkStatusOkToCaptureLocked() {
880 switch (mStatus) {
881 case STATUS_ERROR:
882 CLOGE("Device has encountered a serious error");
883 return INVALID_OPERATION;
884 case STATUS_UNINITIALIZED:
885 CLOGE("Device not initialized");
886 return INVALID_OPERATION;
887 case STATUS_UNCONFIGURED:
888 case STATUS_CONFIGURED:
889 case STATUS_ACTIVE:
890 // OK
891 break;
892 default:
893 SET_ERR_L("Unexpected status: %d", mStatus);
894 return INVALID_OPERATION;
895 }
896 return OK;
897}
898
899status_t Camera3Device::convertMetadataListToRequestListLocked(
Emilian Peevaebbe412018-01-15 13:53:24 +0000900 const List<const PhysicalCameraSettingsList> &metadataList,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700901 const std::list<const SurfaceMap> &surfaceMaps,
Shuzhen Wang316781a2020-08-18 18:11:01 -0700902 bool repeating, nsecs_t requestTimeNs,
Shuzhen Wang9d066012016-09-30 11:30:20 -0700903 RequestList *requestList) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700904 if (requestList == NULL) {
905 CLOGE("requestList cannot be NULL.");
906 return BAD_VALUE;
907 }
908
Jianing Weicb0652e2014-03-12 18:29:36 -0700909 int32_t burstId = 0;
Emilian Peevaebbe412018-01-15 13:53:24 +0000910 List<const PhysicalCameraSettingsList>::const_iterator metadataIt = metadataList.begin();
Shuzhen Wang0129d522016-10-30 22:43:41 -0700911 std::list<const SurfaceMap>::const_iterator surfaceMapIt = surfaceMaps.begin();
912 for (; metadataIt != metadataList.end() && surfaceMapIt != surfaceMaps.end();
913 ++metadataIt, ++surfaceMapIt) {
914 sp<CaptureRequest> newRequest = setUpRequestLocked(*metadataIt, *surfaceMapIt);
Jianing Wei90e59c92014-03-12 18:29:36 -0700915 if (newRequest == 0) {
916 CLOGE("Can't create capture request");
917 return BAD_VALUE;
918 }
Jianing Weicb0652e2014-03-12 18:29:36 -0700919
Shuzhen Wang9d066012016-09-30 11:30:20 -0700920 newRequest->mRepeating = repeating;
Shuzhen Wang316781a2020-08-18 18:11:01 -0700921 newRequest->mRequestTimeNs = requestTimeNs;
Shuzhen Wang9d066012016-09-30 11:30:20 -0700922
Jianing Weicb0652e2014-03-12 18:29:36 -0700923 // Setup burst Id and request Id
924 newRequest->mResultExtras.burstId = burstId++;
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -0800925 auto requestIdEntry = metadataIt->begin()->metadata.find(ANDROID_REQUEST_ID);
926 if (requestIdEntry.count == 0) {
Jianing Weicb0652e2014-03-12 18:29:36 -0700927 CLOGE("RequestID does not exist in metadata");
928 return BAD_VALUE;
929 }
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -0800930 newRequest->mResultExtras.requestId = requestIdEntry.data.i32[0];
Jianing Weicb0652e2014-03-12 18:29:36 -0700931
Jianing Wei90e59c92014-03-12 18:29:36 -0700932 requestList->push_back(newRequest);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700933
934 ALOGV("%s: requestId = %" PRId32, __FUNCTION__, newRequest->mResultExtras.requestId);
Jianing Wei90e59c92014-03-12 18:29:36 -0700935 }
Shuzhen Wang0129d522016-10-30 22:43:41 -0700936 if (metadataIt != metadataList.end() || surfaceMapIt != surfaceMaps.end()) {
937 ALOGE("%s: metadataList and surfaceMaps are not the same size!", __FUNCTION__);
938 return BAD_VALUE;
939 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -0700940
941 // Setup batch size if this is a high speed video recording request.
942 if (mIsConstrainedHighSpeedConfiguration && requestList->size() > 0) {
943 auto firstRequest = requestList->begin();
944 for (auto& outputStream : (*firstRequest)->mOutputStreams) {
945 if (outputStream->isVideoStream()) {
946 (*firstRequest)->mBatchSize = requestList->size();
Yin-Chia Yeh14ef48d2020-02-10 15:06:37 -0800947 outputStream->setBatchSize(requestList->size());
Chien-Yu Chen85a64552015-08-28 15:46:12 -0700948 break;
949 }
950 }
951 }
952
Jianing Wei90e59c92014-03-12 18:29:36 -0700953 return OK;
954}
955
Yin-Chia Yeh7e5a2042019-02-06 16:01:06 -0800956status_t Camera3Device::capture(CameraMetadata &request, int64_t* lastFrameNumber) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800957 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800958
Emilian Peevaebbe412018-01-15 13:53:24 +0000959 List<const PhysicalCameraSettingsList> requestsList;
Shuzhen Wang0129d522016-10-30 22:43:41 -0700960 std::list<const SurfaceMap> surfaceMaps;
Emilian Peevaebbe412018-01-15 13:53:24 +0000961 convertToRequestList(requestsList, surfaceMaps, request);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700962
Yin-Chia Yeh7e5a2042019-02-06 16:01:06 -0800963 return captureList(requestsList, surfaceMaps, lastFrameNumber);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700964}
965
Emilian Peevaebbe412018-01-15 13:53:24 +0000966void Camera3Device::convertToRequestList(List<const PhysicalCameraSettingsList>& requestsList,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700967 std::list<const SurfaceMap>& surfaceMaps,
968 const CameraMetadata& request) {
Emilian Peevaebbe412018-01-15 13:53:24 +0000969 PhysicalCameraSettingsList requestList;
970 requestList.push_back({std::string(getId().string()), request});
971 requestsList.push_back(requestList);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700972
973 SurfaceMap surfaceMap;
974 camera_metadata_ro_entry streams = request.find(ANDROID_REQUEST_OUTPUT_STREAMS);
975 // With no surface list passed in, stream and surface will have 1-to-1
976 // mapping. So the surface index is 0 for each stream in the surfaceMap.
977 for (size_t i = 0; i < streams.count; i++) {
978 surfaceMap[streams.data.i32[i]].push_back(0);
979 }
980 surfaceMaps.push_back(surfaceMap);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800981}
982
Jianing Wei90e59c92014-03-12 18:29:36 -0700983status_t Camera3Device::submitRequestsHelper(
Emilian Peevaebbe412018-01-15 13:53:24 +0000984 const List<const PhysicalCameraSettingsList> &requests,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700985 const std::list<const SurfaceMap> &surfaceMaps,
986 bool repeating,
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700987 /*out*/
988 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700989 ATRACE_CALL();
Shuzhen Wang316781a2020-08-18 18:11:01 -0700990 nsecs_t requestTimeNs = systemTime();
991
Jianing Wei90e59c92014-03-12 18:29:36 -0700992 Mutex::Autolock il(mInterfaceLock);
993 Mutex::Autolock l(mLock);
994
995 status_t res = checkStatusOkToCaptureLocked();
996 if (res != OK) {
997 // error logged by previous call
998 return res;
999 }
1000
1001 RequestList requestList;
1002
Shuzhen Wang0129d522016-10-30 22:43:41 -07001003 res = convertMetadataListToRequestListLocked(requests, surfaceMaps,
Shuzhen Wang316781a2020-08-18 18:11:01 -07001004 repeating, requestTimeNs, /*out*/&requestList);
Jianing Wei90e59c92014-03-12 18:29:36 -07001005 if (res != OK) {
1006 // error logged by previous call
1007 return res;
1008 }
1009
1010 if (repeating) {
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07001011 res = mRequestThread->setRepeatingRequests(requestList, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -07001012 } else {
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07001013 res = mRequestThread->queueRequestList(requestList, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -07001014 }
1015
1016 if (res == OK) {
1017 waitUntilStateThenRelock(/*active*/true, kActiveTimeout);
1018 if (res != OK) {
1019 SET_ERR_L("Can't transition to active in %f seconds!",
1020 kActiveTimeout/1e9);
1021 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001022 ALOGV("Camera %s: Capture request %" PRId32 " enqueued", mId.string(),
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07001023 (*(requestList.begin()))->mResultExtras.requestId);
Jianing Wei90e59c92014-03-12 18:29:36 -07001024 } else {
1025 CLOGE("Cannot queue request. Impossible.");
1026 return BAD_VALUE;
1027 }
1028
1029 return res;
1030}
1031
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001032hardware::Return<void> Camera3Device::requestStreamBuffers(
1033 const hardware::hidl_vec<hardware::camera::device::V3_5::BufferRequest>& bufReqs,
1034 requestStreamBuffers_cb _hidl_cb) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001035 RequestBufferStates states {
Shuzhen Wang316781a2020-08-18 18:11:01 -07001036 mId, mRequestBufferInterfaceLock, mUseHalBufManager, mOutputStreams, mSessionStatsBuilder,
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001037 *this, *mInterface, *this};
1038 camera3::requestStreamBuffers(states, bufReqs, _hidl_cb);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001039 return hardware::Void();
1040}
1041
1042hardware::Return<void> Camera3Device::returnStreamBuffers(
1043 const hardware::hidl_vec<hardware::camera::device::V3_2::StreamBuffer>& buffers) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001044 ReturnBufferStates states {
Shuzhen Wang316781a2020-08-18 18:11:01 -07001045 mId, mUseHalBufManager, mOutputStreams, mSessionStatsBuilder, *mInterface};
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001046 camera3::returnStreamBuffers(states, buffers);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001047 return hardware::Void();
1048}
1049
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001050hardware::Return<void> Camera3Device::processCaptureResult_3_4(
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001051 const hardware::hidl_vec<
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001052 hardware::camera::device::V3_4::CaptureResult>& results) {
Yin-Chia Yeh657c1872017-07-18 18:09:57 -07001053 // Ideally we should grab mLock, but that can lead to deadlock, and
1054 // it's not super important to get up to date value of mStatus for this
1055 // warning print, hence skipping the lock here
1056 if (mStatus == STATUS_ERROR) {
1057 // Per API contract, HAL should act as closed after device error
1058 // But mStatus can be set to error by framework as well, so just log
1059 // a warning here.
1060 ALOGW("%s: received capture result in error state.", __FUNCTION__);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07001061 }
Yifan Honga640c5a2017-04-12 16:30:31 -07001062
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001063 sp<NotificationListener> listener;
1064 {
1065 std::lock_guard<std::mutex> l(mOutputLock);
1066 listener = mListener.promote();
1067 }
1068
Yifan Honga640c5a2017-04-12 16:30:31 -07001069 if (mProcessCaptureResultLock.tryLock() != OK) {
1070 // This should never happen; it indicates a wrong client implementation
1071 // that doesn't follow the contract. But, we can be tolerant here.
1072 ALOGE("%s: callback overlapped! waiting 1s...",
1073 __FUNCTION__);
1074 if (mProcessCaptureResultLock.timedLock(1000000000 /* 1s */) != OK) {
1075 ALOGE("%s: cannot acquire lock in 1s, dropping results",
1076 __FUNCTION__);
1077 // really don't know what to do, so bail out.
1078 return hardware::Void();
1079 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001080 }
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001081 CaptureOutputStates states {
1082 mId,
Shuzhen Wangb7b42652020-05-07 11:59:02 -07001083 mInFlightLock, mLastCompletedRegularFrameNumber,
1084 mLastCompletedReprocessFrameNumber, mLastCompletedZslFrameNumber,
1085 mInFlightMap, mOutputLock, mResultQueue, mResultSignal,
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001086 mNextShutterFrameNumber,
1087 mNextReprocessShutterFrameNumber, mNextZslStillShutterFrameNumber,
1088 mNextResultFrameNumber,
1089 mNextReprocessResultFrameNumber, mNextZslStillResultFrameNumber,
1090 mUseHalBufManager, mUsePartialResult, mNeedFixupMonochromeTags,
1091 mNumPartialResults, mVendorTagId, mDeviceInfo, mPhysicalDeviceInfoMap,
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08001092 mResultMetadataQueue, mDistortionMappers, mZoomRatioMappers, mRotateAndCropMappers,
Shuzhen Wang316781a2020-08-18 18:11:01 -07001093 mTagMonitor, mInputStream, mOutputStreams, mSessionStatsBuilder, listener, *this, *this,
Emilian Peev5104fe92021-10-21 14:27:09 -07001094 *mInterface, mLegacyClient
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001095 };
1096
Yifan Honga640c5a2017-04-12 16:30:31 -07001097 for (const auto& result : results) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001098 processOneCaptureResultLocked(states, result.v3_2, result.physicalCameraMetadata);
Yifan Honga640c5a2017-04-12 16:30:31 -07001099 }
1100 mProcessCaptureResultLock.unlock();
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001101 return hardware::Void();
1102}
1103
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001104// Only one processCaptureResult should be called at a time, so
1105// the locks won't block. The locks are present here simply to enforce this.
1106hardware::Return<void> Camera3Device::processCaptureResult(
1107 const hardware::hidl_vec<
1108 hardware::camera::device::V3_2::CaptureResult>& results) {
1109 hardware::hidl_vec<hardware::camera::device::V3_4::PhysicalCameraMetadata> noPhysMetadata;
1110
1111 // Ideally we should grab mLock, but that can lead to deadlock, and
1112 // it's not super important to get up to date value of mStatus for this
1113 // warning print, hence skipping the lock here
1114 if (mStatus == STATUS_ERROR) {
1115 // Per API contract, HAL should act as closed after device error
1116 // But mStatus can be set to error by framework as well, so just log
1117 // a warning here.
1118 ALOGW("%s: received capture result in error state.", __FUNCTION__);
1119 }
1120
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001121 sp<NotificationListener> listener;
1122 {
1123 std::lock_guard<std::mutex> l(mOutputLock);
1124 listener = mListener.promote();
1125 }
1126
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001127 if (mProcessCaptureResultLock.tryLock() != OK) {
1128 // This should never happen; it indicates a wrong client implementation
1129 // that doesn't follow the contract. But, we can be tolerant here.
1130 ALOGE("%s: callback overlapped! waiting 1s...",
1131 __FUNCTION__);
1132 if (mProcessCaptureResultLock.timedLock(1000000000 /* 1s */) != OK) {
1133 ALOGE("%s: cannot acquire lock in 1s, dropping results",
1134 __FUNCTION__);
1135 // really don't know what to do, so bail out.
1136 return hardware::Void();
1137 }
1138 }
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001139
1140 CaptureOutputStates states {
1141 mId,
Shuzhen Wangb7b42652020-05-07 11:59:02 -07001142 mInFlightLock, mLastCompletedRegularFrameNumber,
1143 mLastCompletedReprocessFrameNumber, mLastCompletedZslFrameNumber,
1144 mInFlightMap, mOutputLock, mResultQueue, mResultSignal,
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001145 mNextShutterFrameNumber,
1146 mNextReprocessShutterFrameNumber, mNextZslStillShutterFrameNumber,
1147 mNextResultFrameNumber,
1148 mNextReprocessResultFrameNumber, mNextZslStillResultFrameNumber,
1149 mUseHalBufManager, mUsePartialResult, mNeedFixupMonochromeTags,
1150 mNumPartialResults, mVendorTagId, mDeviceInfo, mPhysicalDeviceInfoMap,
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08001151 mResultMetadataQueue, mDistortionMappers, mZoomRatioMappers, mRotateAndCropMappers,
Shuzhen Wang316781a2020-08-18 18:11:01 -07001152 mTagMonitor, mInputStream, mOutputStreams, mSessionStatsBuilder, listener, *this, *this,
Emilian Peev5104fe92021-10-21 14:27:09 -07001153 *mInterface, mLegacyClient
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001154 };
1155
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001156 for (const auto& result : results) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001157 processOneCaptureResultLocked(states, result, noPhysMetadata);
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001158 }
1159 mProcessCaptureResultLock.unlock();
1160 return hardware::Void();
1161}
1162
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001163hardware::Return<void> Camera3Device::notify(
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001164 const hardware::hidl_vec<hardware::camera::device::V3_2::NotifyMsg>& msgs) {
Yin-Chia Yeh657c1872017-07-18 18:09:57 -07001165 // Ideally we should grab mLock, but that can lead to deadlock, and
1166 // it's not super important to get up to date value of mStatus for this
1167 // warning print, hence skipping the lock here
1168 if (mStatus == STATUS_ERROR) {
1169 // Per API contract, HAL should act as closed after device error
1170 // But mStatus can be set to error by framework as well, so just log
1171 // a warning here.
1172 ALOGW("%s: received notify message in error state.", __FUNCTION__);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07001173 }
Yin-Chia Yeh657c1872017-07-18 18:09:57 -07001174
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001175 sp<NotificationListener> listener;
1176 {
1177 std::lock_guard<std::mutex> l(mOutputLock);
1178 listener = mListener.promote();
1179 }
1180
1181 CaptureOutputStates states {
1182 mId,
Shuzhen Wangb7b42652020-05-07 11:59:02 -07001183 mInFlightLock, mLastCompletedRegularFrameNumber,
1184 mLastCompletedReprocessFrameNumber, mLastCompletedZslFrameNumber,
1185 mInFlightMap, mOutputLock, mResultQueue, mResultSignal,
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001186 mNextShutterFrameNumber,
1187 mNextReprocessShutterFrameNumber, mNextZslStillShutterFrameNumber,
1188 mNextResultFrameNumber,
1189 mNextReprocessResultFrameNumber, mNextZslStillResultFrameNumber,
1190 mUseHalBufManager, mUsePartialResult, mNeedFixupMonochromeTags,
1191 mNumPartialResults, mVendorTagId, mDeviceInfo, mPhysicalDeviceInfoMap,
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08001192 mResultMetadataQueue, mDistortionMappers, mZoomRatioMappers, mRotateAndCropMappers,
Shuzhen Wang316781a2020-08-18 18:11:01 -07001193 mTagMonitor, mInputStream, mOutputStreams, mSessionStatsBuilder, listener, *this, *this,
Emilian Peev5104fe92021-10-21 14:27:09 -07001194 *mInterface, mLegacyClient
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001195 };
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001196 for (const auto& msg : msgs) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001197 camera3::notify(states, msg);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001198 }
1199 return hardware::Void();
1200}
1201
Emilian Peevaebbe412018-01-15 13:53:24 +00001202status_t Camera3Device::captureList(const List<const PhysicalCameraSettingsList> &requestsList,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001203 const std::list<const SurfaceMap> &surfaceMaps,
Jianing Weicb0652e2014-03-12 18:29:36 -07001204 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -07001205 ATRACE_CALL();
1206
Emilian Peevaebbe412018-01-15 13:53:24 +00001207 return submitRequestsHelper(requestsList, surfaceMaps, /*repeating*/false, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -07001208}
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001209
Jianing Weicb0652e2014-03-12 18:29:36 -07001210status_t Camera3Device::setStreamingRequest(const CameraMetadata &request,
1211 int64_t* /*lastFrameNumber*/) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001212 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001213
Emilian Peevaebbe412018-01-15 13:53:24 +00001214 List<const PhysicalCameraSettingsList> requestsList;
Shuzhen Wang0129d522016-10-30 22:43:41 -07001215 std::list<const SurfaceMap> surfaceMaps;
Emilian Peevaebbe412018-01-15 13:53:24 +00001216 convertToRequestList(requestsList, surfaceMaps, request);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001217
Emilian Peevaebbe412018-01-15 13:53:24 +00001218 return setStreamingRequestList(requestsList, /*surfaceMap*/surfaceMaps,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001219 /*lastFrameNumber*/NULL);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001220}
1221
Emilian Peevaebbe412018-01-15 13:53:24 +00001222status_t Camera3Device::setStreamingRequestList(
1223 const List<const PhysicalCameraSettingsList> &requestsList,
1224 const std::list<const SurfaceMap> &surfaceMaps, int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -07001225 ATRACE_CALL();
1226
Emilian Peevaebbe412018-01-15 13:53:24 +00001227 return submitRequestsHelper(requestsList, surfaceMaps, /*repeating*/true, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -07001228}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001229
1230sp<Camera3Device::CaptureRequest> Camera3Device::setUpRequestLocked(
Emilian Peevaebbe412018-01-15 13:53:24 +00001231 const PhysicalCameraSettingsList &request, const SurfaceMap &surfaceMap) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001232 status_t res;
1233
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001234 if (mStatus == STATUS_UNCONFIGURED || mNeedConfig) {
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08001235 // This point should only be reached via API1 (API2 must explicitly call configureStreams)
1236 // so unilaterally select normal operating mode.
Emilian Peevaebbe412018-01-15 13:53:24 +00001237 res = filterParamsAndConfigureLocked(request.begin()->metadata,
Emilian Peevf4816702020-04-03 15:44:51 -07001238 CAMERA_STREAM_CONFIGURATION_NORMAL_MODE);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001239 // Stream configuration failed. Client might try other configuraitons.
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001240 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001241 CLOGE("Can't set up streams: %s (%d)", strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001242 return NULL;
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001243 } else if (mStatus == STATUS_UNCONFIGURED) {
1244 // Stream configuration successfully configure to empty stream configuration.
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001245 CLOGE("No streams configured");
1246 return NULL;
1247 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001248 }
1249
Shuzhen Wang0129d522016-10-30 22:43:41 -07001250 sp<CaptureRequest> newRequest = createCaptureRequest(request, surfaceMap);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001251 return newRequest;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001252}
1253
Jianing Weicb0652e2014-03-12 18:29:36 -07001254status_t Camera3Device::clearStreamingRequest(int64_t *lastFrameNumber) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001255 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001256 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001257 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001258
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001259 switch (mStatus) {
1260 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001261 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001262 return INVALID_OPERATION;
1263 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001264 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001265 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001266 case STATUS_UNCONFIGURED:
1267 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001268 case STATUS_ACTIVE:
1269 // OK
1270 break;
1271 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001272 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001273 return INVALID_OPERATION;
1274 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001275 ALOGV("Camera %s: Clearing repeating request", mId.string());
Jianing Weicb0652e2014-03-12 18:29:36 -07001276
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07001277 return mRequestThread->clearRepeatingRequests(lastFrameNumber);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001278}
1279
1280status_t Camera3Device::waitUntilRequestReceived(int32_t requestId, nsecs_t timeout) {
1281 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001282 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001283
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001284 return mRequestThread->waitUntilRequestProcessed(requestId, timeout);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001285}
1286
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001287status_t Camera3Device::createInputStream(
Shuzhen Wang83bff122020-11-20 15:51:39 -08001288 uint32_t width, uint32_t height, int format, bool isMultiResolution, int *id) {
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001289 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001290 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001291 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001292 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001293 ALOGV("Camera %s: Creating new input stream %d: %d x %d, format %d",
1294 mId.string(), mNextStreamId, width, height, format);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001295
1296 status_t res;
1297 bool wasActive = false;
1298
1299 switch (mStatus) {
1300 case STATUS_ERROR:
1301 ALOGE("%s: Device has encountered a serious error", __FUNCTION__);
1302 return INVALID_OPERATION;
1303 case STATUS_UNINITIALIZED:
1304 ALOGE("%s: Device not initialized", __FUNCTION__);
1305 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001306 case STATUS_UNCONFIGURED:
1307 case STATUS_CONFIGURED:
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001308 // OK
1309 break;
1310 case STATUS_ACTIVE:
1311 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001312 res = internalPauseAndWaitLocked(maxExpectedDuration);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001313 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001314 SET_ERR_L("Can't pause captures to reconfigure streams!");
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001315 return res;
1316 }
1317 wasActive = true;
1318 break;
1319 default:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001320 SET_ERR_L("%s: Unexpected status: %d", mStatus);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001321 return INVALID_OPERATION;
1322 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001323 assert(mStatus != STATUS_ACTIVE);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001324
1325 if (mInputStream != 0) {
1326 ALOGE("%s: Cannot create more than 1 input stream", __FUNCTION__);
1327 return INVALID_OPERATION;
1328 }
1329
1330 sp<Camera3InputStream> newStream = new Camera3InputStream(mNextStreamId,
1331 width, height, format);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001332 newStream->setStatusTracker(mStatusTracker);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001333
1334 mInputStream = newStream;
Shuzhen Wang83bff122020-11-20 15:51:39 -08001335 mIsInputStreamMultiResolution = isMultiResolution;
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001336
1337 *id = mNextStreamId++;
1338
1339 // Continue captures if active at start
1340 if (wasActive) {
1341 ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001342 // Reuse current operating mode and session parameters for new stream config
1343 res = configureStreamsLocked(mOperatingMode, mSessionParams);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001344 if (res != OK) {
1345 ALOGE("%s: Can't reconfigure device for new stream %d: %s (%d)",
1346 __FUNCTION__, mNextStreamId, strerror(-res), res);
1347 return res;
1348 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001349 internalResumeLocked();
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001350 }
1351
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001352 ALOGV("Camera %s: Created input stream", mId.string());
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001353 return OK;
1354}
1355
Eino-Ville Talvala727d1722015-06-09 13:44:19 -07001356status_t Camera3Device::createStream(sp<Surface> consumer,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001357 uint32_t width, uint32_t height, int format,
Emilian Peevf4816702020-04-03 15:44:51 -07001358 android_dataspace dataSpace, camera_stream_rotation_t rotation, int *id,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001359 const String8& physicalCameraId,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001360 const std::unordered_set<int32_t> &sensorPixelModesUsed,
1361 std::vector<int> *surfaceIds, int streamSetId, bool isShared, bool isMultiResolution,
1362 uint64_t consumerUsage) {
Shuzhen Wang0129d522016-10-30 22:43:41 -07001363 ATRACE_CALL();
1364
1365 if (consumer == nullptr) {
1366 ALOGE("%s: consumer must not be null", __FUNCTION__);
1367 return BAD_VALUE;
1368 }
1369
1370 std::vector<sp<Surface>> consumers;
1371 consumers.push_back(consumer);
1372
1373 return createStream(consumers, /*hasDeferredConsumer*/ false, width, height,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001374 format, dataSpace, rotation, id, physicalCameraId, sensorPixelModesUsed, surfaceIds,
1375 streamSetId, isShared, isMultiResolution, consumerUsage);
1376}
1377
1378static bool isRawFormat(int format) {
1379 switch (format) {
1380 case HAL_PIXEL_FORMAT_RAW16:
1381 case HAL_PIXEL_FORMAT_RAW12:
1382 case HAL_PIXEL_FORMAT_RAW10:
1383 case HAL_PIXEL_FORMAT_RAW_OPAQUE:
1384 return true;
1385 default:
1386 return false;
1387 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001388}
1389
1390status_t Camera3Device::createStream(const std::vector<sp<Surface>>& consumers,
1391 bool hasDeferredConsumer, uint32_t width, uint32_t height, int format,
Emilian Peevf4816702020-04-03 15:44:51 -07001392 android_dataspace dataSpace, camera_stream_rotation_t rotation, int *id,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001393 const String8& physicalCameraId, const std::unordered_set<int32_t> &sensorPixelModesUsed,
Shuzhen Wang83bff122020-11-20 15:51:39 -08001394 std::vector<int> *surfaceIds, int streamSetId, bool isShared, bool isMultiResolution,
1395 uint64_t consumerUsage) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001396 ATRACE_CALL();
Emilian Peev40ead602017-09-26 15:46:36 +01001397
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001398 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001399 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001400 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001401 ALOGV("Camera %s: Creating new stream %d: %d x %d, format %d, dataspace %d rotation %d"
Shuzhen Wang83bff122020-11-20 15:51:39 -08001402 " consumer usage %" PRIu64 ", isShared %d, physicalCameraId %s, isMultiResolution %d",
1403 mId.string(), mNextStreamId, width, height, format, dataSpace, rotation,
1404 consumerUsage, isShared, physicalCameraId.string(), isMultiResolution);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001405
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001406 status_t res;
1407 bool wasActive = false;
1408
1409 switch (mStatus) {
1410 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001411 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001412 return INVALID_OPERATION;
1413 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001414 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001415 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001416 case STATUS_UNCONFIGURED:
1417 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001418 // OK
1419 break;
1420 case STATUS_ACTIVE:
1421 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001422 res = internalPauseAndWaitLocked(maxExpectedDuration);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001423 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001424 SET_ERR_L("Can't pause captures to reconfigure streams!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001425 return res;
1426 }
1427 wasActive = true;
1428 break;
1429 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001430 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001431 return INVALID_OPERATION;
1432 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001433 assert(mStatus != STATUS_ACTIVE);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001434
1435 sp<Camera3OutputStream> newStream;
Zhijun He5d677d12016-05-29 16:52:39 -07001436
Shuzhen Wang0129d522016-10-30 22:43:41 -07001437 if (consumers.size() == 0 && !hasDeferredConsumer) {
1438 ALOGE("%s: Number of consumers cannot be smaller than 1", __FUNCTION__);
1439 return BAD_VALUE;
1440 }
Zhijun He5d677d12016-05-29 16:52:39 -07001441
Shuzhen Wang0129d522016-10-30 22:43:41 -07001442 if (hasDeferredConsumer && format != HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
Zhijun He5d677d12016-05-29 16:52:39 -07001443 ALOGE("Deferred consumer stream creation only support IMPLEMENTATION_DEFINED format");
1444 return BAD_VALUE;
1445 }
1446
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001447 if (isRawFormat(format) && sensorPixelModesUsed.size() > 1) {
1448 // We can't use one stream with a raw format in both sensor pixel modes since its going to
1449 // be found in only one sensor pixel mode.
1450 ALOGE("%s: RAW opaque stream cannot be used with > 1 sensor pixel modes", __FUNCTION__);
1451 return BAD_VALUE;
1452 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001453 if (format == HAL_PIXEL_FORMAT_BLOB) {
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -07001454 ssize_t blobBufferSize;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001455 if (dataSpace == HAL_DATASPACE_DEPTH) {
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -08001456 blobBufferSize = getPointCloudBufferSize(infoPhysical(physicalCameraId));
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -07001457 if (blobBufferSize <= 0) {
1458 SET_ERR_L("Invalid point cloud buffer size %zd", blobBufferSize);
1459 return BAD_VALUE;
1460 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001461 } else if (dataSpace == static_cast<android_dataspace>(HAL_DATASPACE_JPEG_APP_SEGMENTS)) {
1462 blobBufferSize = width * height;
1463 } else {
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -08001464 blobBufferSize = getJpegBufferSize(infoPhysical(physicalCameraId), width, height);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001465 if (blobBufferSize <= 0) {
1466 SET_ERR_L("Invalid jpeg buffer size %zd", blobBufferSize);
1467 return BAD_VALUE;
1468 }
Zhijun Hef7da0962014-04-24 13:27:56 -07001469 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001470 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001471 width, height, blobBufferSize, format, dataSpace, rotation,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001472 mTimestampOffset, physicalCameraId, sensorPixelModesUsed, streamSetId,
1473 isMultiResolution);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -08001474 } else if (format == HAL_PIXEL_FORMAT_RAW_OPAQUE) {
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001475 bool maxResolution =
1476 sensorPixelModesUsed.find(ANDROID_SENSOR_PIXEL_MODE_MAXIMUM_RESOLUTION) !=
1477 sensorPixelModesUsed.end();
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -08001478 ssize_t rawOpaqueBufferSize = getRawOpaqueBufferSize(infoPhysical(physicalCameraId), width,
1479 height, maxResolution);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -08001480 if (rawOpaqueBufferSize <= 0) {
1481 SET_ERR_L("Invalid RAW opaque buffer size %zd", rawOpaqueBufferSize);
1482 return BAD_VALUE;
1483 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001484 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001485 width, height, rawOpaqueBufferSize, format, dataSpace, rotation,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001486 mTimestampOffset, physicalCameraId, sensorPixelModesUsed, streamSetId,
1487 isMultiResolution);
Shuzhen Wang758c2152017-01-10 18:26:18 -08001488 } else if (isShared) {
1489 newStream = new Camera3SharedOutputStream(mNextStreamId, consumers,
1490 width, height, format, consumerUsage, dataSpace, rotation,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001491 mTimestampOffset, physicalCameraId, sensorPixelModesUsed, streamSetId,
1492 mUseHalBufManager);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001493 } else if (consumers.size() == 0 && hasDeferredConsumer) {
Zhijun He5d677d12016-05-29 16:52:39 -07001494 newStream = new Camera3OutputStream(mNextStreamId,
1495 width, height, format, consumerUsage, dataSpace, rotation,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001496 mTimestampOffset, physicalCameraId, sensorPixelModesUsed, streamSetId,
1497 isMultiResolution);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001498 } else {
Shuzhen Wang0129d522016-10-30 22:43:41 -07001499 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001500 width, height, format, dataSpace, rotation,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001501 mTimestampOffset, physicalCameraId, sensorPixelModesUsed, streamSetId,
1502 isMultiResolution);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001503 }
Emilian Peev40ead602017-09-26 15:46:36 +01001504
1505 size_t consumerCount = consumers.size();
1506 for (size_t i = 0; i < consumerCount; i++) {
1507 int id = newStream->getSurfaceId(consumers[i]);
1508 if (id < 0) {
1509 SET_ERR_L("Invalid surface id");
1510 return BAD_VALUE;
1511 }
1512 if (surfaceIds != nullptr) {
1513 surfaceIds->push_back(id);
1514 }
1515 }
1516
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001517 newStream->setStatusTracker(mStatusTracker);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001518
Emilian Peev08dd2452017-04-06 16:55:14 +01001519 newStream->setBufferManager(mBufferManager);
Zhijun He125684a2015-12-26 15:07:30 -08001520
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08001521 newStream->setImageDumpMask(mImageDumpMask);
1522
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001523 res = mOutputStreams.add(mNextStreamId, newStream);
1524 if (res < 0) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001525 SET_ERR_L("Can't add new stream to set: %s (%d)", strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001526 return res;
1527 }
1528
Shuzhen Wang316781a2020-08-18 18:11:01 -07001529 mSessionStatsBuilder.addStream(mNextStreamId);
1530
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001531 *id = mNextStreamId++;
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07001532 mNeedConfig = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001533
1534 // Continue captures if active at start
1535 if (wasActive) {
1536 ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001537 // Reuse current operating mode and session parameters for new stream config
1538 res = configureStreamsLocked(mOperatingMode, mSessionParams);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001539 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001540 CLOGE("Can't reconfigure device for new stream %d: %s (%d)",
1541 mNextStreamId, strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001542 return res;
1543 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001544 internalResumeLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001545 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001546 ALOGV("Camera %s: Created new stream", mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001547 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001548}
1549
Emilian Peev710c1422017-08-30 11:19:38 +01001550status_t Camera3Device::getStreamInfo(int id, StreamInfo *streamInfo) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001551 ATRACE_CALL();
Emilian Peev710c1422017-08-30 11:19:38 +01001552 if (nullptr == streamInfo) {
1553 return BAD_VALUE;
1554 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001555 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001556 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001557
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001558 switch (mStatus) {
1559 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001560 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001561 return INVALID_OPERATION;
1562 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001563 CLOGE("Device not initialized!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001564 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001565 case STATUS_UNCONFIGURED:
1566 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001567 case STATUS_ACTIVE:
1568 // OK
1569 break;
1570 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001571 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001572 return INVALID_OPERATION;
1573 }
1574
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001575 sp<Camera3StreamInterface> stream = mOutputStreams.get(id);
1576 if (stream == nullptr) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001577 CLOGE("Stream %d is unknown", id);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001578 return BAD_VALUE;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001579 }
1580
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001581 streamInfo->width = stream->getWidth();
1582 streamInfo->height = stream->getHeight();
1583 streamInfo->format = stream->getFormat();
1584 streamInfo->dataSpace = stream->getDataSpace();
1585 streamInfo->formatOverridden = stream->isFormatOverridden();
1586 streamInfo->originalFormat = stream->getOriginalFormat();
1587 streamInfo->dataSpaceOverridden = stream->isDataSpaceOverridden();
1588 streamInfo->originalDataSpace = stream->getOriginalDataSpace();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001589 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001590}
1591
1592status_t Camera3Device::setStreamTransform(int id,
1593 int transform) {
1594 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001595 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001596 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001597
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001598 switch (mStatus) {
1599 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001600 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001601 return INVALID_OPERATION;
1602 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001603 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001604 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001605 case STATUS_UNCONFIGURED:
1606 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001607 case STATUS_ACTIVE:
1608 // OK
1609 break;
1610 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001611 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001612 return INVALID_OPERATION;
1613 }
1614
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001615 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(id);
1616 if (stream == nullptr) {
1617 CLOGE("Stream %d does not exist", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001618 return BAD_VALUE;
1619 }
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001620 return stream->setTransform(transform);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001621}
1622
1623status_t Camera3Device::deleteStream(int id) {
1624 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001625 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001626 Mutex::Autolock l(mLock);
1627 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001628
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001629 ALOGV("%s: Camera %s: Deleting stream %d", __FUNCTION__, mId.string(), id);
Igor Murashkine2172be2013-05-28 15:31:39 -07001630
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001631 // CameraDevice semantics require device to already be idle before
1632 // deleteStream is called, unlike for createStream.
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001633 if (mStatus == STATUS_ACTIVE) {
Yin-Chia Yeh693047d2018-03-08 12:14:19 -08001634 ALOGW("%s: Camera %s: Device not idle", __FUNCTION__, mId.string());
Igor Murashkin52827132013-05-13 14:53:44 -07001635 return -EBUSY;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001636 }
1637
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07001638 if (mStatus == STATUS_ERROR) {
1639 ALOGW("%s: Camera %s: deleteStream not allowed in ERROR state",
1640 __FUNCTION__, mId.string());
1641 return -EBUSY;
1642 }
1643
Igor Murashkin2fba5842013-04-22 14:03:54 -07001644 sp<Camera3StreamInterface> deletedStream;
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001645 sp<Camera3StreamInterface> stream = mOutputStreams.get(id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001646 if (mInputStream != NULL && id == mInputStream->getId()) {
1647 deletedStream = mInputStream;
1648 mInputStream.clear();
1649 } else {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001650 if (stream == nullptr) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001651 CLOGE("Stream %d does not exist", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001652 return BAD_VALUE;
1653 }
Shuzhen Wang316781a2020-08-18 18:11:01 -07001654 mSessionStatsBuilder.removeStream(id);
Zhijun He5f446352014-01-22 09:49:33 -08001655 }
1656
1657 // Delete output stream or the output part of a bi-directional stream.
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001658 if (stream != nullptr) {
1659 deletedStream = stream;
1660 mOutputStreams.remove(id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001661 }
1662
1663 // Free up the stream endpoint so that it can be used by some other stream
1664 res = deletedStream->disconnect();
1665 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001666 SET_ERR_L("Can't disconnect deleted stream %d", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001667 // fall through since we want to still list the stream as deleted.
1668 }
1669 mDeletedStreams.add(deletedStream);
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07001670 mNeedConfig = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001671
1672 return res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001673}
1674
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001675status_t Camera3Device::configureStreams(const CameraMetadata& sessionParams, int operatingMode) {
Igor Murashkine2d167e2014-08-19 16:19:59 -07001676 ATRACE_CALL();
1677 ALOGV("%s: E", __FUNCTION__);
1678
1679 Mutex::Autolock il(mInterfaceLock);
1680 Mutex::Autolock l(mLock);
Chien-Yu Chen17338fc2015-06-18 16:30:12 -07001681
Emilian Peev811d2952018-05-25 11:08:40 +01001682 // In case the client doesn't include any session parameter, try a
1683 // speculative configuration using the values from the last cached
1684 // default request.
1685 if (sessionParams.isEmpty() &&
Emilian Peevf4816702020-04-03 15:44:51 -07001686 ((mLastTemplateId > 0) && (mLastTemplateId < CAMERA_TEMPLATE_COUNT)) &&
Emilian Peev811d2952018-05-25 11:08:40 +01001687 (!mRequestTemplateCache[mLastTemplateId].isEmpty())) {
1688 ALOGV("%s: Speculative session param configuration with template id: %d", __func__,
1689 mLastTemplateId);
1690 return filterParamsAndConfigureLocked(mRequestTemplateCache[mLastTemplateId],
1691 operatingMode);
1692 }
1693
Emilian Peevac3ce6c2017-12-12 15:27:02 +00001694 return filterParamsAndConfigureLocked(sessionParams, operatingMode);
1695}
1696
1697status_t Camera3Device::filterParamsAndConfigureLocked(const CameraMetadata& sessionParams,
1698 int operatingMode) {
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001699 //Filter out any incoming session parameters
1700 const CameraMetadata params(sessionParams);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001701 camera_metadata_entry_t availableSessionKeys = mDeviceInfo.find(
1702 ANDROID_REQUEST_AVAILABLE_SESSION_KEYS);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00001703 CameraMetadata filteredParams(availableSessionKeys.count);
1704 camera_metadata_t *meta = const_cast<camera_metadata_t *>(
1705 filteredParams.getAndLock());
1706 set_camera_metadata_vendor_id(meta, mVendorTagId);
1707 filteredParams.unlock(meta);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001708 if (availableSessionKeys.count > 0) {
1709 for (size_t i = 0; i < availableSessionKeys.count; i++) {
1710 camera_metadata_ro_entry entry = params.find(
1711 availableSessionKeys.data.i32[i]);
1712 if (entry.count > 0) {
1713 filteredParams.update(entry);
1714 }
1715 }
1716 }
1717
1718 return configureStreamsLocked(operatingMode, filteredParams);
Igor Murashkine2d167e2014-08-19 16:19:59 -07001719}
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001720
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07001721status_t Camera3Device::getInputBufferProducer(
1722 sp<IGraphicBufferProducer> *producer) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07001723 ATRACE_CALL();
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07001724 Mutex::Autolock il(mInterfaceLock);
1725 Mutex::Autolock l(mLock);
1726
1727 if (producer == NULL) {
1728 return BAD_VALUE;
1729 } else if (mInputStream == NULL) {
1730 return INVALID_OPERATION;
1731 }
1732
1733 return mInputStream->getInputBufferProducer(producer);
1734}
1735
Emilian Peevf4816702020-04-03 15:44:51 -07001736status_t Camera3Device::createDefaultRequest(camera_request_template_t templateId,
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001737 CameraMetadata *request) {
1738 ATRACE_CALL();
Alex Rayfe7e0c62013-05-30 00:12:13 -07001739 ALOGV("%s: for template %d", __FUNCTION__, templateId);
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08001740
Emilian Peevf4816702020-04-03 15:44:51 -07001741 if (templateId <= 0 || templateId >= CAMERA_TEMPLATE_COUNT) {
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08001742 android_errorWriteWithInfoLog(CameraService::SN_EVENT_LOG_ID, "26866110",
Jayant Chowdhary12361932018-08-27 14:46:13 -07001743 CameraThreadState::getCallingUid(), nullptr, 0);
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08001744 return BAD_VALUE;
1745 }
1746
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001747 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001748
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001749 {
1750 Mutex::Autolock l(mLock);
1751 switch (mStatus) {
1752 case STATUS_ERROR:
1753 CLOGE("Device has encountered a serious error");
1754 return INVALID_OPERATION;
1755 case STATUS_UNINITIALIZED:
1756 CLOGE("Device is not initialized!");
1757 return INVALID_OPERATION;
1758 case STATUS_UNCONFIGURED:
1759 case STATUS_CONFIGURED:
1760 case STATUS_ACTIVE:
1761 // OK
1762 break;
1763 default:
1764 SET_ERR_L("Unexpected status: %d", mStatus);
1765 return INVALID_OPERATION;
1766 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001767
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001768 if (!mRequestTemplateCache[templateId].isEmpty()) {
1769 *request = mRequestTemplateCache[templateId];
Emilian Peev811d2952018-05-25 11:08:40 +01001770 mLastTemplateId = templateId;
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001771 return OK;
1772 }
Zhijun Hea1530f12014-09-14 12:44:20 -07001773 }
1774
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001775 camera_metadata_t *rawRequest;
1776 status_t res = mInterface->constructDefaultRequestSettings(
Emilian Peevf4816702020-04-03 15:44:51 -07001777 (camera_request_template_t) templateId, &rawRequest);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001778
1779 {
1780 Mutex::Autolock l(mLock);
1781 if (res == BAD_VALUE) {
1782 ALOGI("%s: template %d is not supported on this camera device",
1783 __FUNCTION__, templateId);
1784 return res;
1785 } else if (res != OK) {
1786 CLOGE("Unable to construct request template %d: %s (%d)",
1787 templateId, strerror(-res), res);
1788 return res;
1789 }
1790
1791 set_camera_metadata_vendor_id(rawRequest, mVendorTagId);
1792 mRequestTemplateCache[templateId].acquire(rawRequest);
1793
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08001794 // Override the template request with zoomRatioMapper
1795 res = mZoomRatioMappers[mId.c_str()].initZoomRatioInTemplate(
1796 &mRequestTemplateCache[templateId]);
1797 if (res != OK) {
1798 CLOGE("Failed to update zoom ratio for template %d: %s (%d)",
1799 templateId, strerror(-res), res);
1800 return res;
1801 }
1802
Shuzhen Wangd25dc972020-03-24 17:11:43 -07001803 // Fill in JPEG_QUALITY if not available
1804 if (!mRequestTemplateCache[templateId].exists(ANDROID_JPEG_QUALITY)) {
1805 static const uint8_t kDefaultJpegQuality = 95;
1806 mRequestTemplateCache[templateId].update(ANDROID_JPEG_QUALITY,
1807 &kDefaultJpegQuality, 1);
1808 }
1809
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001810 *request = mRequestTemplateCache[templateId];
Emilian Peev811d2952018-05-25 11:08:40 +01001811 mLastTemplateId = templateId;
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001812 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001813 return OK;
1814}
1815
1816status_t Camera3Device::waitUntilDrained() {
1817 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001818 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001819 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001820 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001821
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001822 return waitUntilDrainedLocked(maxExpectedDuration);
Zhijun He69a37482014-03-23 18:44:49 -07001823}
1824
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001825status_t Camera3Device::waitUntilDrainedLocked(nsecs_t maxExpectedDuration) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001826 switch (mStatus) {
1827 case STATUS_UNINITIALIZED:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001828 case STATUS_UNCONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001829 ALOGV("%s: Already idle", __FUNCTION__);
1830 return OK;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001831 case STATUS_CONFIGURED:
1832 // To avoid race conditions, check with tracker to be sure
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001833 case STATUS_ERROR:
1834 case STATUS_ACTIVE:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001835 // Need to verify shut down
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001836 break;
1837 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001838 SET_ERR_L("Unexpected status: %d",mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001839 return INVALID_OPERATION;
1840 }
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07001841 ALOGV("%s: Camera %s: Waiting until idle (%" PRIi64 "ns)", __FUNCTION__, mId.string(),
1842 maxExpectedDuration);
1843 status_t res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
Eino-Ville Talvala9c8a0912014-09-14 14:52:19 -07001844 if (res != OK) {
Yin-Chia Yeh87b3ec02019-06-03 10:44:39 -07001845 mStatusTracker->dumpActiveComponents();
Eino-Ville Talvala9c8a0912014-09-14 14:52:19 -07001846 SET_ERR_L("Error waiting for HAL to drain: %s (%d)", strerror(-res),
1847 res);
1848 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001849 return res;
1850}
1851
Ruben Brunk183f0562015-08-12 12:55:02 -07001852void Camera3Device::internalUpdateStatusLocked(Status status) {
1853 mStatus = status;
1854 mRecentStatusUpdates.add(mStatus);
1855 mStatusChanged.broadcast();
1856}
1857
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001858// Pause to reconfigure
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001859status_t Camera3Device::internalPauseAndWaitLocked(nsecs_t maxExpectedDuration) {
Emilian Peeve86358b2019-02-15 13:51:39 -08001860 if (mRequestThread.get() != nullptr) {
1861 mRequestThread->setPaused(true);
1862 } else {
1863 return NO_INIT;
1864 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001865
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07001866 ALOGV("%s: Camera %s: Internal wait until idle (% " PRIi64 " ns)", __FUNCTION__, mId.string(),
1867 maxExpectedDuration);
1868 status_t res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001869 if (res != OK) {
1870 SET_ERR_L("Can't idle device in %f seconds!",
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07001871 maxExpectedDuration/1e9);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001872 }
1873
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001874 return res;
1875}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001876
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001877// Resume after internalPauseAndWaitLocked
1878status_t Camera3Device::internalResumeLocked() {
1879 status_t res;
1880
1881 mRequestThread->setPaused(false);
1882
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08001883 ALOGV("%s: Camera %s: Internal wait until active (% " PRIi64 " ns)", __FUNCTION__, mId.string(),
1884 kActiveTimeout);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001885 res = waitUntilStateThenRelock(/*active*/ true, kActiveTimeout);
1886 if (res != OK) {
1887 SET_ERR_L("Can't transition to active in %f seconds!",
1888 kActiveTimeout/1e9);
1889 }
1890 mPauseStateNotify = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001891 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001892}
1893
Ruben Brunk183f0562015-08-12 12:55:02 -07001894status_t Camera3Device::waitUntilStateThenRelock(bool active, nsecs_t timeout) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001895 status_t res = OK;
Ruben Brunk183f0562015-08-12 12:55:02 -07001896
1897 size_t startIndex = 0;
1898 if (mStatusWaiters == 0) {
1899 // Clear the list of recent statuses if there are no existing threads waiting on updates to
1900 // this status list
1901 mRecentStatusUpdates.clear();
1902 } else {
1903 // If other threads are waiting on updates to this status list, set the position of the
1904 // first element that this list will check rather than clearing the list.
1905 startIndex = mRecentStatusUpdates.size();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001906 }
1907
Ruben Brunk183f0562015-08-12 12:55:02 -07001908 mStatusWaiters++;
1909
Yin-Chia Yehe52b8fa2020-07-28 00:17:58 -07001910 bool signalPipelineDrain = false;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07001911 if (!active && mUseHalBufManager) {
1912 auto streamIds = mOutputStreams.getStreamIds();
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08001913 if (mStatus == STATUS_ACTIVE) {
1914 mRequestThread->signalPipelineDrain(streamIds);
Yin-Chia Yehe52b8fa2020-07-28 00:17:58 -07001915 signalPipelineDrain = true;
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08001916 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07001917 mRequestBufferSM.onWaitUntilIdle();
1918 }
1919
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001920 bool stateSeen = false;
1921 do {
Ruben Brunk183f0562015-08-12 12:55:02 -07001922 if (active == (mStatus == STATUS_ACTIVE)) {
1923 // Desired state is current
1924 break;
1925 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001926
1927 res = mStatusChanged.waitRelative(mLock, timeout);
1928 if (res != OK) break;
1929
Ruben Brunk183f0562015-08-12 12:55:02 -07001930 // This is impossible, but if not, could result in subtle deadlocks and invalid state
1931 // transitions.
1932 LOG_ALWAYS_FATAL_IF(startIndex > mRecentStatusUpdates.size(),
1933 "%s: Skipping status updates in Camera3Device, may result in deadlock.",
1934 __FUNCTION__);
1935
1936 // Encountered desired state since we began waiting
1937 for (size_t i = startIndex; i < mRecentStatusUpdates.size(); i++) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001938 if (active == (mRecentStatusUpdates[i] == STATUS_ACTIVE) ) {
1939 stateSeen = true;
1940 break;
1941 }
1942 }
1943 } while (!stateSeen);
1944
Yin-Chia Yehe52b8fa2020-07-28 00:17:58 -07001945 if (signalPipelineDrain) {
1946 mRequestThread->resetPipelineDrain();
1947 }
1948
Ruben Brunk183f0562015-08-12 12:55:02 -07001949 mStatusWaiters--;
1950
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001951 return res;
1952}
1953
1954
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001955status_t Camera3Device::setNotifyCallback(wp<NotificationListener> listener) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001956 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001957 std::lock_guard<std::mutex> l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001958
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001959 if (listener != NULL && mListener != NULL) {
1960 ALOGW("%s: Replacing old callback listener", __FUNCTION__);
1961 }
1962 mListener = listener;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001963 mRequestThread->setNotificationListener(listener);
1964 mPreparerThread->setNotificationListener(listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001965
1966 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001967}
1968
Eino-Ville Talvala46910bd2013-07-18 19:15:17 -07001969bool Camera3Device::willNotify3A() {
1970 return false;
1971}
1972
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001973status_t Camera3Device::waitForNextFrame(nsecs_t timeout) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07001974 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001975 std::unique_lock<std::mutex> l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001976
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001977 while (mResultQueue.empty()) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001978 auto st = mResultSignal.wait_for(l, std::chrono::nanoseconds(timeout));
1979 if (st == std::cv_status::timeout) {
1980 return TIMED_OUT;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001981 }
1982 }
1983 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001984}
1985
Jianing Weicb0652e2014-03-12 18:29:36 -07001986status_t Camera3Device::getNextResult(CaptureResult *frame) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001987 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001988 std::lock_guard<std::mutex> l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001989
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001990 if (mResultQueue.empty()) {
1991 return NOT_ENOUGH_DATA;
1992 }
1993
Jianing Weicb0652e2014-03-12 18:29:36 -07001994 if (frame == NULL) {
1995 ALOGE("%s: argument cannot be NULL", __FUNCTION__);
1996 return BAD_VALUE;
1997 }
1998
1999 CaptureResult &result = *(mResultQueue.begin());
2000 frame->mResultExtras = result.mResultExtras;
2001 frame->mMetadata.acquire(result.mMetadata);
Shuzhen Wang5c22c152017-12-31 17:12:25 -08002002 frame->mPhysicalMetadatas = std::move(result.mPhysicalMetadatas);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002003 mResultQueue.erase(mResultQueue.begin());
2004
2005 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002006}
2007
2008status_t Camera3Device::triggerAutofocus(uint32_t id) {
2009 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002010 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002011
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002012 ALOGV("%s: Triggering autofocus, id %d", __FUNCTION__, id);
2013 // Mix-in this trigger into the next request and only the next request.
2014 RequestTrigger trigger[] = {
2015 {
2016 ANDROID_CONTROL_AF_TRIGGER,
2017 ANDROID_CONTROL_AF_TRIGGER_START
2018 },
2019 {
2020 ANDROID_CONTROL_AF_TRIGGER_ID,
2021 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07002022 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002023 };
2024
2025 return mRequestThread->queueTrigger(trigger,
2026 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002027}
2028
2029status_t Camera3Device::triggerCancelAutofocus(uint32_t id) {
2030 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002031 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002032
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002033 ALOGV("%s: Triggering cancel autofocus, id %d", __FUNCTION__, id);
2034 // Mix-in this trigger into the next request and only the next request.
2035 RequestTrigger trigger[] = {
2036 {
2037 ANDROID_CONTROL_AF_TRIGGER,
2038 ANDROID_CONTROL_AF_TRIGGER_CANCEL
2039 },
2040 {
2041 ANDROID_CONTROL_AF_TRIGGER_ID,
2042 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07002043 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002044 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002045
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002046 return mRequestThread->queueTrigger(trigger,
2047 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002048}
2049
2050status_t Camera3Device::triggerPrecaptureMetering(uint32_t id) {
2051 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002052 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002053
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002054 ALOGV("%s: Triggering precapture metering, id %d", __FUNCTION__, id);
2055 // Mix-in this trigger into the next request and only the next request.
2056 RequestTrigger trigger[] = {
2057 {
2058 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER,
2059 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_START
2060 },
2061 {
2062 ANDROID_CONTROL_AE_PRECAPTURE_ID,
2063 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07002064 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002065 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002066
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002067 return mRequestThread->queueTrigger(trigger,
2068 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002069}
2070
Jianing Weicb0652e2014-03-12 18:29:36 -07002071status_t Camera3Device::flush(int64_t *frameNumber) {
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07002072 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002073 ALOGV("%s: Camera %s: Flushing all requests", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002074 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07002075
Zhijun He7ef20392014-04-21 16:04:17 -07002076 {
2077 Mutex::Autolock l(mLock);
Emilian Peeved2ebe42018-09-25 16:59:09 +01002078
2079 // b/116514106 "disconnect()" can get called twice for the same device. The
2080 // camera device will not be initialized during the second run.
2081 if (mStatus == STATUS_UNINITIALIZED) {
2082 return OK;
2083 }
2084
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002085 mRequestThread->clear(/*out*/frameNumber);
Shuzhen Wang316781a2020-08-18 18:11:01 -07002086
2087 // Stop session and stream counter
2088 mSessionStatsBuilder.stopCounter();
Zhijun He7ef20392014-04-21 16:04:17 -07002089 }
2090
Emilian Peev08dd2452017-04-06 16:55:14 +01002091 return mRequestThread->flush();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07002092}
2093
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002094status_t Camera3Device::prepare(int streamId) {
Ruben Brunkc78ac262015-08-13 17:58:46 -07002095 return prepare(camera3::Camera3StreamInterface::ALLOCATE_PIPELINE_MAX, streamId);
2096}
2097
2098status_t Camera3Device::prepare(int maxCount, int streamId) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002099 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002100 ALOGV("%s: Camera %s: Preparing stream %d", __FUNCTION__, mId.string(), streamId);
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07002101 Mutex::Autolock il(mInterfaceLock);
2102 Mutex::Autolock l(mLock);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002103
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002104 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
2105 if (stream == nullptr) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002106 CLOGE("Stream %d does not exist", streamId);
2107 return BAD_VALUE;
2108 }
2109
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002110 if (stream->isUnpreparable() || stream->hasOutstandingBuffers() ) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07002111 CLOGE("Stream %d has already been a request target", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002112 return BAD_VALUE;
2113 }
2114
2115 if (mRequestThread->isStreamPending(stream)) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07002116 CLOGE("Stream %d is already a target in a pending request", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002117 return BAD_VALUE;
2118 }
2119
Ruben Brunkc78ac262015-08-13 17:58:46 -07002120 return mPreparerThread->prepare(maxCount, stream);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002121}
2122
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002123status_t Camera3Device::tearDown(int streamId) {
2124 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002125 ALOGV("%s: Camera %s: Tearing down stream %d", __FUNCTION__, mId.string(), streamId);
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002126 Mutex::Autolock il(mInterfaceLock);
2127 Mutex::Autolock l(mLock);
2128
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002129 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
2130 if (stream == nullptr) {
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002131 CLOGE("Stream %d does not exist", streamId);
2132 return BAD_VALUE;
2133 }
2134
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002135 if (stream->hasOutstandingBuffers() || mRequestThread->isStreamPending(stream)) {
2136 CLOGE("Stream %d is a target of a in-progress request", streamId);
2137 return BAD_VALUE;
2138 }
2139
2140 return stream->tearDown();
2141}
2142
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002143status_t Camera3Device::addBufferListenerForStream(int streamId,
2144 wp<Camera3StreamBufferListener> listener) {
2145 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002146 ALOGV("%s: Camera %s: Adding buffer listener for stream %d", __FUNCTION__, mId.string(), streamId);
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002147 Mutex::Autolock il(mInterfaceLock);
2148 Mutex::Autolock l(mLock);
2149
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002150 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
2151 if (stream == nullptr) {
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002152 CLOGE("Stream %d does not exist", streamId);
2153 return BAD_VALUE;
2154 }
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002155 stream->addBufferListener(listener);
2156
2157 return OK;
2158}
2159
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002160/**
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002161 * Methods called by subclasses
2162 */
2163
2164void Camera3Device::notifyStatus(bool idle) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002165 ATRACE_CALL();
Shuzhen Wang316781a2020-08-18 18:11:01 -07002166 std::vector<int> streamIds;
2167 std::vector<hardware::CameraStreamStats> streamStats;
2168
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002169 {
2170 // Need mLock to safely update state and synchronize to current
2171 // state of methods in flight.
2172 Mutex::Autolock l(mLock);
2173 // We can get various system-idle notices from the status tracker
2174 // while starting up. Only care about them if we've actually sent
2175 // in some requests recently.
2176 if (mStatus != STATUS_ACTIVE && mStatus != STATUS_CONFIGURED) {
2177 return;
2178 }
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08002179 ALOGV("%s: Camera %s: Now %s, pauseState: %s", __FUNCTION__, mId.string(),
2180 idle ? "idle" : "active", mPauseStateNotify ? "true" : "false");
Ruben Brunk183f0562015-08-12 12:55:02 -07002181 internalUpdateStatusLocked(idle ? STATUS_CONFIGURED : STATUS_ACTIVE);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002182
2183 // Skip notifying listener if we're doing some user-transparent
2184 // state changes
2185 if (mPauseStateNotify) return;
Shuzhen Wang316781a2020-08-18 18:11:01 -07002186
2187 // Populate stream statistics in case of Idle
2188 if (idle) {
2189 for (size_t i = 0; i < mOutputStreams.size(); i++) {
2190 auto stream = mOutputStreams[i];
2191 if (stream.get() == nullptr) continue;
2192 streamIds.push_back(stream->getId());
2193 Camera3Stream* camera3Stream = Camera3Stream::cast(stream->asHalStream());
2194 int64_t usage = 0LL;
2195 if (camera3Stream != nullptr) {
2196 usage = camera3Stream->getUsage();
2197 }
2198 streamStats.emplace_back(stream->getWidth(), stream->getHeight(),
2199 stream->getFormat(), stream->getDataSpace(), usage,
2200 stream->getMaxHalBuffers(),
2201 stream->getMaxTotalBuffers() - stream->getMaxHalBuffers());
2202 }
2203 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002204 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002205
2206 sp<NotificationListener> listener;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002207 {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002208 std::lock_guard<std::mutex> l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002209 listener = mListener.promote();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002210 }
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07002211 status_t res = OK;
2212 if (listener != nullptr) {
2213 if (idle) {
2214 // Get session stats from the builder, and notify the listener.
2215 int64_t requestCount, resultErrorCount;
2216 bool deviceError;
2217 std::map<int, StreamStats> streamStatsMap;
2218 mSessionStatsBuilder.buildAndReset(&requestCount, &resultErrorCount,
2219 &deviceError, &streamStatsMap);
2220 for (size_t i = 0; i < streamIds.size(); i++) {
2221 int streamId = streamIds[i];
2222 auto stats = streamStatsMap.find(streamId);
2223 if (stats != streamStatsMap.end()) {
2224 streamStats[i].mRequestCount = stats->second.mRequestedFrameCount;
2225 streamStats[i].mErrorCount = stats->second.mDroppedFrameCount;
2226 streamStats[i].mStartLatencyMs = stats->second.mStartLatencyMs;
2227 streamStats[i].mHistogramType =
2228 hardware::CameraStreamStats::HISTOGRAM_TYPE_CAPTURE_LATENCY;
2229 streamStats[i].mHistogramBins.assign(
2230 stats->second.mCaptureLatencyBins.begin(),
2231 stats->second.mCaptureLatencyBins.end());
2232 streamStats[i].mHistogramCounts.assign(
2233 stats->second.mCaptureLatencyHistogram.begin(),
2234 stats->second.mCaptureLatencyHistogram.end());
2235 }
Shuzhen Wang316781a2020-08-18 18:11:01 -07002236 }
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07002237 listener->notifyIdle(requestCount, resultErrorCount, deviceError, streamStats);
2238 } else {
2239 res = listener->notifyActive();
Shuzhen Wang316781a2020-08-18 18:11:01 -07002240 }
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07002241 }
2242 if (res != OK) {
2243 SET_ERR("Camera access permission lost mid-operation: %s (%d)",
2244 strerror(-res), res);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002245 }
2246}
2247
Shuzhen Wang758c2152017-01-10 18:26:18 -08002248status_t Camera3Device::setConsumerSurfaces(int streamId,
Emilian Peev40ead602017-09-26 15:46:36 +01002249 const std::vector<sp<Surface>>& consumers, std::vector<int> *surfaceIds) {
Zhijun He5d677d12016-05-29 16:52:39 -07002250 ATRACE_CALL();
Shuzhen Wang758c2152017-01-10 18:26:18 -08002251 ALOGV("%s: Camera %s: set consumer surface for stream %d",
2252 __FUNCTION__, mId.string(), streamId);
Emilian Peev40ead602017-09-26 15:46:36 +01002253
2254 if (surfaceIds == nullptr) {
2255 return BAD_VALUE;
2256 }
2257
Zhijun He5d677d12016-05-29 16:52:39 -07002258 Mutex::Autolock il(mInterfaceLock);
2259 Mutex::Autolock l(mLock);
2260
Shuzhen Wang758c2152017-01-10 18:26:18 -08002261 if (consumers.size() == 0) {
2262 CLOGE("No consumer is passed!");
Zhijun He5d677d12016-05-29 16:52:39 -07002263 return BAD_VALUE;
2264 }
2265
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002266 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
2267 if (stream == nullptr) {
Zhijun He5d677d12016-05-29 16:52:39 -07002268 CLOGE("Stream %d is unknown", streamId);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002269 return BAD_VALUE;
Zhijun He5d677d12016-05-29 16:52:39 -07002270 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002271
2272 // isConsumerConfigurationDeferred will be off after setConsumers
2273 bool isDeferred = stream->isConsumerConfigurationDeferred();
Shuzhen Wang758c2152017-01-10 18:26:18 -08002274 status_t res = stream->setConsumers(consumers);
Zhijun He5d677d12016-05-29 16:52:39 -07002275 if (res != OK) {
2276 CLOGE("Stream %d set consumer failed (error %d %s) ", streamId, res, strerror(-res));
2277 return res;
2278 }
2279
Emilian Peev40ead602017-09-26 15:46:36 +01002280 for (auto &consumer : consumers) {
2281 int id = stream->getSurfaceId(consumer);
2282 if (id < 0) {
2283 CLOGE("Invalid surface id!");
2284 return BAD_VALUE;
2285 }
2286 surfaceIds->push_back(id);
2287 }
2288
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002289 if (isDeferred) {
Shuzhen Wang0129d522016-10-30 22:43:41 -07002290 if (!stream->isConfiguring()) {
2291 CLOGE("Stream %d was already fully configured.", streamId);
2292 return INVALID_OPERATION;
2293 }
Zhijun He5d677d12016-05-29 16:52:39 -07002294
Shuzhen Wang0129d522016-10-30 22:43:41 -07002295 res = stream->finishConfiguration();
2296 if (res != OK) {
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002297 // If finishConfiguration fails due to abandoned surface, do not set
2298 // device to error state.
2299 bool isSurfaceAbandoned =
2300 (res == NO_INIT || res == DEAD_OBJECT) && stream->isAbandoned();
2301 if (!isSurfaceAbandoned) {
2302 SET_ERR_L("Can't finish configuring output stream %d: %s (%d)",
2303 stream->getId(), strerror(-res), res);
2304 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07002305 return res;
2306 }
Zhijun He5d677d12016-05-29 16:52:39 -07002307 }
2308
2309 return OK;
2310}
2311
Emilian Peev40ead602017-09-26 15:46:36 +01002312status_t Camera3Device::updateStream(int streamId, const std::vector<sp<Surface>> &newSurfaces,
2313 const std::vector<OutputStreamInfo> &outputInfo,
2314 const std::vector<size_t> &removedSurfaceIds, KeyedVector<sp<Surface>, size_t> *outputMap) {
2315 Mutex::Autolock il(mInterfaceLock);
2316 Mutex::Autolock l(mLock);
2317
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002318 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
2319 if (stream == nullptr) {
Emilian Peev40ead602017-09-26 15:46:36 +01002320 CLOGE("Stream %d is unknown", streamId);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002321 return BAD_VALUE;
Emilian Peev40ead602017-09-26 15:46:36 +01002322 }
2323
2324 for (const auto &it : removedSurfaceIds) {
2325 if (mRequestThread->isOutputSurfacePending(streamId, it)) {
2326 CLOGE("Shared surface still part of a pending request!");
2327 return -EBUSY;
2328 }
2329 }
2330
Emilian Peev40ead602017-09-26 15:46:36 +01002331 status_t res = stream->updateStream(newSurfaces, outputInfo, removedSurfaceIds, outputMap);
2332 if (res != OK) {
2333 CLOGE("Stream %d failed to update stream (error %d %s) ",
2334 streamId, res, strerror(-res));
2335 if (res == UNKNOWN_ERROR) {
2336 SET_ERR_L("%s: Stream update failed to revert to previous output configuration!",
2337 __FUNCTION__);
2338 }
2339 return res;
2340 }
2341
2342 return res;
2343}
2344
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002345status_t Camera3Device::dropStreamBuffers(bool dropping, int streamId) {
2346 Mutex::Autolock il(mInterfaceLock);
2347 Mutex::Autolock l(mLock);
2348
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002349 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
2350 if (stream == nullptr) {
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002351 ALOGE("%s: Stream %d is not found.", __FUNCTION__, streamId);
2352 return BAD_VALUE;
2353 }
Shuzhen Wang316781a2020-08-18 18:11:01 -07002354
2355 if (dropping) {
2356 mSessionStatsBuilder.stopCounter(streamId);
2357 } else {
2358 mSessionStatsBuilder.startCounter(streamId);
2359 }
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002360 return stream->dropBuffers(dropping);
2361}
2362
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002363/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002364 * Camera3Device private methods
2365 */
2366
2367sp<Camera3Device::CaptureRequest> Camera3Device::createCaptureRequest(
Emilian Peevaebbe412018-01-15 13:53:24 +00002368 const PhysicalCameraSettingsList &request, const SurfaceMap &surfaceMap) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002369 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002370
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08002371 sp<CaptureRequest> newRequest = new CaptureRequest();
Emilian Peevaebbe412018-01-15 13:53:24 +00002372 newRequest->mSettingsList = request;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002373
2374 camera_metadata_entry_t inputStreams =
Emilian Peevaebbe412018-01-15 13:53:24 +00002375 newRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_INPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002376 if (inputStreams.count > 0) {
2377 if (mInputStream == NULL ||
Zhijun Hed1d64672013-09-06 15:00:01 -07002378 mInputStream->getId() != inputStreams.data.i32[0]) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002379 CLOGE("Request references unknown input stream %d",
2380 inputStreams.data.u8[0]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002381 return NULL;
2382 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002383
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002384 if (mInputStream->isConfiguring()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002385 SET_ERR_L("%s: input stream %d is not configured!",
2386 __FUNCTION__, mInputStream->getId());
2387 return NULL;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002388 }
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07002389 // Check if stream prepare is blocking requests.
2390 if (mInputStream->isBlockedByPrepare()) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002391 CLOGE("Request references an input stream that's being prepared!");
2392 return NULL;
2393 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002394
2395 newRequest->mInputStream = mInputStream;
Emilian Peevaebbe412018-01-15 13:53:24 +00002396 newRequest->mSettingsList.begin()->metadata.erase(ANDROID_REQUEST_INPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002397 }
2398
2399 camera_metadata_entry_t streams =
Emilian Peevaebbe412018-01-15 13:53:24 +00002400 newRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_OUTPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002401 if (streams.count == 0) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002402 CLOGE("Zero output streams specified!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002403 return NULL;
2404 }
2405
2406 for (size_t i = 0; i < streams.count; i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002407 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streams.data.i32[i]);
2408 if (stream == nullptr) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002409 CLOGE("Request references unknown stream %d",
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002410 streams.data.i32[i]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002411 return NULL;
2412 }
Zhijun He5d677d12016-05-29 16:52:39 -07002413 // It is illegal to include a deferred consumer output stream into a request
Shuzhen Wang0129d522016-10-30 22:43:41 -07002414 auto iter = surfaceMap.find(streams.data.i32[i]);
2415 if (iter != surfaceMap.end()) {
2416 const std::vector<size_t>& surfaces = iter->second;
2417 for (const auto& surface : surfaces) {
2418 if (stream->isConsumerConfigurationDeferred(surface)) {
2419 CLOGE("Stream %d surface %zu hasn't finished configuration yet "
2420 "due to deferred consumer", stream->getId(), surface);
2421 return NULL;
2422 }
2423 }
Yin-Chia Yeh0b287572018-10-15 12:38:13 -07002424 newRequest->mOutputSurfaces[streams.data.i32[i]] = surfaces;
Zhijun He5d677d12016-05-29 16:52:39 -07002425 }
2426
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002427 if (stream->isConfiguring()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002428 SET_ERR_L("%s: stream %d is not configured!", __FUNCTION__, stream->getId());
2429 return NULL;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002430 }
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07002431 // Check if stream prepare is blocking requests.
2432 if (stream->isBlockedByPrepare()) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002433 CLOGE("Request references an output stream that's being prepared!");
2434 return NULL;
2435 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002436
2437 newRequest->mOutputStreams.push(stream);
2438 }
Emilian Peevaebbe412018-01-15 13:53:24 +00002439 newRequest->mSettingsList.begin()->metadata.erase(ANDROID_REQUEST_OUTPUT_STREAMS);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07002440 newRequest->mBatchSize = 1;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002441
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08002442 auto rotateAndCropEntry =
2443 newRequest->mSettingsList.begin()->metadata.find(ANDROID_SCALER_ROTATE_AND_CROP);
2444 if (rotateAndCropEntry.count > 0 &&
2445 rotateAndCropEntry.data.u8[0] == ANDROID_SCALER_ROTATE_AND_CROP_AUTO) {
2446 newRequest->mRotateAndCropAuto = true;
2447 } else {
2448 newRequest->mRotateAndCropAuto = false;
2449 }
2450
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07002451 auto zoomRatioEntry =
2452 newRequest->mSettingsList.begin()->metadata.find(ANDROID_CONTROL_ZOOM_RATIO);
2453 if (zoomRatioEntry.count > 0 &&
2454 zoomRatioEntry.data.f[0] == 1.0f) {
2455 newRequest->mZoomRatioIs1x = true;
2456 } else {
2457 newRequest->mZoomRatioIs1x = false;
2458 }
2459
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08002460 if (mSupportCameraMute) {
Shuzhen Wang911c6a32021-10-27 13:36:03 -07002461 for (auto& settings : newRequest->mSettingsList) {
2462 auto testPatternModeEntry =
2463 settings.metadata.find(ANDROID_SENSOR_TEST_PATTERN_MODE);
2464 settings.mOriginalTestPatternMode = testPatternModeEntry.count > 0 ?
2465 testPatternModeEntry.data.i32[0] :
2466 ANDROID_SENSOR_TEST_PATTERN_MODE_OFF;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08002467
Shuzhen Wang911c6a32021-10-27 13:36:03 -07002468 auto testPatternDataEntry =
2469 settings.metadata.find(ANDROID_SENSOR_TEST_PATTERN_DATA);
2470 if (testPatternDataEntry.count >= 4) {
2471 memcpy(settings.mOriginalTestPatternData, testPatternDataEntry.data.i32,
2472 sizeof(PhysicalCameraSettings::mOriginalTestPatternData));
2473 } else {
2474 settings.mOriginalTestPatternData[0] = 0;
2475 settings.mOriginalTestPatternData[1] = 0;
2476 settings.mOriginalTestPatternData[2] = 0;
2477 settings.mOriginalTestPatternData[3] = 0;
2478 }
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08002479 }
2480 }
2481
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002482 return newRequest;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002483}
2484
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002485void Camera3Device::cancelStreamsConfigurationLocked() {
2486 int res = OK;
2487 if (mInputStream != NULL && mInputStream->isConfiguring()) {
2488 res = mInputStream->cancelConfiguration();
2489 if (res != OK) {
2490 CLOGE("Can't cancel configuring input stream %d: %s (%d)",
2491 mInputStream->getId(), strerror(-res), res);
2492 }
2493 }
2494
2495 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002496 sp<Camera3OutputStreamInterface> outputStream = mOutputStreams[i];
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002497 if (outputStream->isConfiguring()) {
2498 res = outputStream->cancelConfiguration();
2499 if (res != OK) {
2500 CLOGE("Can't cancel configuring output stream %d: %s (%d)",
2501 outputStream->getId(), strerror(-res), res);
2502 }
2503 }
2504 }
2505
2506 // Return state to that at start of call, so that future configures
2507 // properly clean things up
2508 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
2509 mNeedConfig = true;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002510
2511 res = mPreparerThread->resume();
2512 if (res != OK) {
2513 ALOGE("%s: Camera %s: Preparer thread failed to resume!", __FUNCTION__, mId.string());
2514 }
2515}
2516
Emilian Peev0d0191e2020-04-21 17:01:18 -07002517bool Camera3Device::checkAbandonedStreamsLocked() {
2518 if ((mInputStream.get() != nullptr) && (mInputStream->isAbandoned())) {
2519 return true;
2520 }
2521
2522 for (size_t i = 0; i < mOutputStreams.size(); i++) {
2523 auto stream = mOutputStreams[i];
2524 if ((stream.get() != nullptr) && (stream->isAbandoned())) {
2525 return true;
2526 }
2527 }
2528
2529 return false;
2530}
2531
Emilian Peev3bead5f2020-05-28 17:29:08 -07002532bool Camera3Device::reconfigureCamera(const CameraMetadata& sessionParams, int clientStatusId) {
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002533 ATRACE_CALL();
2534 bool ret = false;
2535
Shuzhen Wang316781a2020-08-18 18:11:01 -07002536 nsecs_t startTime = systemTime();
2537
Jayant Chowdhary646c31b2020-01-30 13:09:59 -08002538 Mutex::Autolock il(mInterfaceLock);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002539 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
2540
2541 Mutex::Autolock l(mLock);
Emilian Peev0d0191e2020-04-21 17:01:18 -07002542 if (checkAbandonedStreamsLocked()) {
2543 ALOGW("%s: Abandoned stream detected, session parameters can't be applied correctly!",
2544 __FUNCTION__);
2545 return true;
2546 }
2547
Emilian Peev3bead5f2020-05-28 17:29:08 -07002548 status_t rc = NO_ERROR;
2549 bool markClientActive = false;
2550 if (mStatus == STATUS_ACTIVE) {
2551 markClientActive = true;
2552 mPauseStateNotify = true;
2553 mStatusTracker->markComponentIdle(clientStatusId, Fence::NO_FENCE);
2554
2555 rc = internalPauseAndWaitLocked(maxExpectedDuration);
2556 }
2557
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002558 if (rc == NO_ERROR) {
2559 mNeedConfig = true;
2560 rc = configureStreamsLocked(mOperatingMode, sessionParams, /*notifyRequestThread*/ false);
2561 if (rc == NO_ERROR) {
2562 ret = true;
2563 mPauseStateNotify = false;
2564 //Moving to active state while holding 'mLock' is important.
2565 //There could be pending calls to 'create-/deleteStream' which
2566 //will trigger another stream configuration while the already
2567 //present streams end up with outstanding buffers that will
2568 //not get drained.
2569 internalUpdateStatusLocked(STATUS_ACTIVE);
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002570 } else if (rc == DEAD_OBJECT) {
2571 // DEAD_OBJECT can be returned if either the consumer surface is
2572 // abandoned, or the HAL has died.
2573 // - If the HAL has died, configureStreamsLocked call will set
2574 // device to error state,
2575 // - If surface is abandoned, we should not set device to error
2576 // state.
2577 ALOGE("Failed to re-configure camera due to abandoned surface");
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002578 } else {
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002579 SET_ERR_L("Failed to re-configure camera: %d", rc);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002580 }
2581 } else {
2582 ALOGE("%s: Failed to pause streaming: %d", __FUNCTION__, rc);
2583 }
2584
Shuzhen Wang316781a2020-08-18 18:11:01 -07002585 CameraServiceProxyWrapper::logStreamConfigured(mId, mOperatingMode, true /*internalReconfig*/,
2586 ns2ms(systemTime() - startTime));
2587
Emilian Peev3bead5f2020-05-28 17:29:08 -07002588 if (markClientActive) {
2589 mStatusTracker->markComponentActive(clientStatusId);
2590 }
2591
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002592 return ret;
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002593}
2594
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002595status_t Camera3Device::configureStreamsLocked(int operatingMode,
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002596 const CameraMetadata& sessionParams, bool notifyRequestThread) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002597 ATRACE_CALL();
2598 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002599
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002600 if (mStatus != STATUS_UNCONFIGURED && mStatus != STATUS_CONFIGURED) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002601 CLOGE("Not idle");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002602 return INVALID_OPERATION;
2603 }
2604
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08002605 if (operatingMode < 0) {
2606 CLOGE("Invalid operating mode: %d", operatingMode);
2607 return BAD_VALUE;
2608 }
2609
2610 bool isConstrainedHighSpeed =
2611 static_cast<int>(StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE) ==
2612 operatingMode;
2613
2614 if (mOperatingMode != operatingMode) {
2615 mNeedConfig = true;
2616 mIsConstrainedHighSpeedConfiguration = isConstrainedHighSpeed;
2617 mOperatingMode = operatingMode;
2618 }
2619
Shuzhen Wang0cf01cb2019-09-05 13:33:06 -07002620 // In case called from configureStreams, abort queued input buffers not belonging to
2621 // any pending requests.
2622 if (mInputStream != NULL && notifyRequestThread) {
2623 while (true) {
Emilian Peevf4816702020-04-03 15:44:51 -07002624 camera_stream_buffer_t inputBuffer;
Shuzhen Wang83bff122020-11-20 15:51:39 -08002625 camera3::Size inputBufferSize;
Shuzhen Wang0cf01cb2019-09-05 13:33:06 -07002626 status_t res = mInputStream->getInputBuffer(&inputBuffer,
Shuzhen Wang83bff122020-11-20 15:51:39 -08002627 &inputBufferSize, /*respectHalLimit*/ false);
Shuzhen Wang0cf01cb2019-09-05 13:33:06 -07002628 if (res != OK) {
2629 // Exhausted acquiring all input buffers.
2630 break;
2631 }
2632
Emilian Peevf4816702020-04-03 15:44:51 -07002633 inputBuffer.status = CAMERA_BUFFER_STATUS_ERROR;
Shuzhen Wang0cf01cb2019-09-05 13:33:06 -07002634 res = mInputStream->returnInputBuffer(inputBuffer);
2635 if (res != OK) {
2636 ALOGE("%s: %d: couldn't return input buffer while clearing input queue: "
2637 "%s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
2638 }
2639 }
2640 }
2641
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002642 if (!mNeedConfig) {
2643 ALOGV("%s: Skipping config, no stream changes", __FUNCTION__);
2644 return OK;
2645 }
2646
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002647 // Workaround for device HALv3.2 or older spec bug - zero streams requires
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002648 // adding a fake stream instead.
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002649 // TODO: Bug: 17321404 for fixing the HAL spec and removing this workaround.
2650 if (mOutputStreams.size() == 0) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002651 addFakeStreamLocked();
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002652 } else {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002653 tryRemoveFakeStreamLocked();
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002654 }
2655
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002656 // Start configuring the streams
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002657 ALOGV("%s: Camera %s: Starting stream configuration", __FUNCTION__, mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002658
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002659 mPreparerThread->pause();
2660
Emilian Peevf4816702020-04-03 15:44:51 -07002661 camera_stream_configuration config;
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -08002662 config.operation_mode = mOperatingMode;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002663 config.num_streams = (mInputStream != NULL) + mOutputStreams.size();
Shuzhen Wang83bff122020-11-20 15:51:39 -08002664 config.input_is_multi_resolution = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002665
Emilian Peevf4816702020-04-03 15:44:51 -07002666 Vector<camera3::camera_stream_t*> streams;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002667 streams.setCapacity(config.num_streams);
Emilian Peev192ee832018-01-31 14:46:47 +00002668 std::vector<uint32_t> bufferSizes(config.num_streams, 0);
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002669
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002670
2671 if (mInputStream != NULL) {
Emilian Peevf4816702020-04-03 15:44:51 -07002672 camera3::camera_stream_t *inputStream;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002673 inputStream = mInputStream->startConfiguration();
2674 if (inputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002675 CLOGE("Can't start input stream configuration");
2676 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002677 return INVALID_OPERATION;
2678 }
2679 streams.add(inputStream);
Shuzhen Wang83bff122020-11-20 15:51:39 -08002680
2681 config.input_is_multi_resolution = mIsInputStreamMultiResolution;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002682 }
2683
Shuzhen Wang99080502021-03-07 21:08:20 -08002684 mGroupIdPhysicalCameraMap.clear();
Emilian Peeve23f1d92021-09-20 14:56:01 -07002685 bool composerSurfacePresent = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002686 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Igor Murashkin2fba5842013-04-22 14:03:54 -07002687
2688 // Don't configure bidi streams twice, nor add them twice to the list
2689 if (mOutputStreams[i].get() ==
2690 static_cast<Camera3StreamInterface*>(mInputStream.get())) {
2691
2692 config.num_streams--;
2693 continue;
2694 }
2695
Emilian Peevf4816702020-04-03 15:44:51 -07002696 camera3::camera_stream_t *outputStream;
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002697 outputStream = mOutputStreams[i]->startConfiguration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002698 if (outputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002699 CLOGE("Can't start output stream configuration");
2700 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002701 return INVALID_OPERATION;
2702 }
2703 streams.add(outputStream);
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002704
Shuzhen Wangb7ab1e42019-02-20 15:42:23 -08002705 if (outputStream->format == HAL_PIXEL_FORMAT_BLOB) {
Emilian Peev192ee832018-01-31 14:46:47 +00002706 size_t k = i + ((mInputStream != nullptr) ? 1 : 0); // Input stream if present should
2707 // always occupy the initial entry.
Shuzhen Wangb7ab1e42019-02-20 15:42:23 -08002708 if (outputStream->data_space == HAL_DATASPACE_V0_JFIF) {
2709 bufferSizes[k] = static_cast<uint32_t>(
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -08002710 getJpegBufferSize(infoPhysical(String8(outputStream->physical_camera_id)),
2711 outputStream->width, outputStream->height));
Shuzhen Wangb7ab1e42019-02-20 15:42:23 -08002712 } else if (outputStream->data_space ==
2713 static_cast<android_dataspace>(HAL_DATASPACE_JPEG_APP_SEGMENTS)) {
2714 bufferSizes[k] = outputStream->width * outputStream->height;
2715 } else {
2716 ALOGW("%s: Blob dataSpace %d not supported",
2717 __FUNCTION__, outputStream->data_space);
2718 }
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002719 }
Shuzhen Wang99080502021-03-07 21:08:20 -08002720
2721 if (mOutputStreams[i]->isMultiResolution()) {
2722 int32_t streamGroupId = mOutputStreams[i]->getHalStreamGroupId();
2723 const String8& physicalCameraId = mOutputStreams[i]->getPhysicalCameraId();
2724 mGroupIdPhysicalCameraMap[streamGroupId].insert(physicalCameraId);
2725 }
Emilian Peeve23f1d92021-09-20 14:56:01 -07002726
2727 if (outputStream->usage & GraphicBuffer::USAGE_HW_COMPOSER) {
2728 composerSurfacePresent = true;
2729 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002730 }
2731
2732 config.streams = streams.editArray();
2733
2734 // Do the HAL configuration; will potentially touch stream
Shuzhen Wang92653952019-05-07 15:11:43 -07002735 // max_buffers, usage, and priv fields, as well as data_space and format
2736 // fields for IMPLEMENTATION_DEFINED formats.
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002737
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002738 const camera_metadata_t *sessionBuffer = sessionParams.getAndLock();
Emilian Peev192ee832018-01-31 14:46:47 +00002739 res = mInterface->configureStreams(sessionBuffer, &config, bufferSizes);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002740 sessionParams.unlock(sessionBuffer);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002741
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002742 if (res == BAD_VALUE) {
2743 // HAL rejected this set of streams as unsupported, clean up config
2744 // attempt and return to unconfigured state
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002745 CLOGE("Set of requested inputs/outputs not supported by HAL");
2746 cancelStreamsConfigurationLocked();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002747 return BAD_VALUE;
2748 } else if (res != OK) {
2749 // Some other kind of error from configure_streams - this is not
2750 // expected
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002751 SET_ERR_L("Unable to configure streams with HAL: %s (%d)",
2752 strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002753 return res;
2754 }
2755
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002756 // Finish all stream configuration immediately.
2757 // TODO: Try to relax this later back to lazy completion, which should be
2758 // faster
2759
Igor Murashkin073f8572013-05-02 14:59:28 -07002760 if (mInputStream != NULL && mInputStream->isConfiguring()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002761 bool streamReConfigured = false;
2762 res = mInputStream->finishConfiguration(&streamReConfigured);
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002763 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002764 CLOGE("Can't finish configuring input stream %d: %s (%d)",
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002765 mInputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002766 cancelStreamsConfigurationLocked();
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002767 if ((res == NO_INIT || res == DEAD_OBJECT) && mInputStream->isAbandoned()) {
2768 return DEAD_OBJECT;
2769 }
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002770 return BAD_VALUE;
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002771 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002772 if (streamReConfigured) {
2773 mInterface->onStreamReConfigured(mInputStream->getId());
2774 }
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002775 }
2776
2777 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002778 sp<Camera3OutputStreamInterface> outputStream = mOutputStreams[i];
Zhijun He5d677d12016-05-29 16:52:39 -07002779 if (outputStream->isConfiguring() && !outputStream->isConsumerConfigurationDeferred()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002780 bool streamReConfigured = false;
2781 res = outputStream->finishConfiguration(&streamReConfigured);
Igor Murashkin073f8572013-05-02 14:59:28 -07002782 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002783 CLOGE("Can't finish configuring output stream %d: %s (%d)",
Igor Murashkin073f8572013-05-02 14:59:28 -07002784 outputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002785 cancelStreamsConfigurationLocked();
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002786 if ((res == NO_INIT || res == DEAD_OBJECT) && outputStream->isAbandoned()) {
2787 return DEAD_OBJECT;
2788 }
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002789 return BAD_VALUE;
Igor Murashkin073f8572013-05-02 14:59:28 -07002790 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002791 if (streamReConfigured) {
2792 mInterface->onStreamReConfigured(outputStream->getId());
2793 }
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002794 }
2795 }
2796
Emilian Peeve23f1d92021-09-20 14:56:01 -07002797 mRequestThread->setComposerSurface(composerSurfacePresent);
2798
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002799 // Request thread needs to know to avoid using repeat-last-settings protocol
2800 // across configure_streams() calls
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002801 if (notifyRequestThread) {
Shuzhen Wang99080502021-03-07 21:08:20 -08002802 mRequestThread->configurationComplete(mIsConstrainedHighSpeedConfiguration,
2803 sessionParams, mGroupIdPhysicalCameraMap);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002804 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002805
Zhijun He90f7c372016-08-16 16:19:43 -07002806 char value[PROPERTY_VALUE_MAX];
2807 property_get("camera.fifo.disable", value, "0");
2808 int32_t disableFifo = atoi(value);
2809 if (disableFifo != 1) {
2810 // Boost priority of request thread to SCHED_FIFO.
2811 pid_t requestThreadTid = mRequestThread->getTid();
2812 res = requestPriority(getpid(), requestThreadTid,
Mikhail Naganov83f04272017-02-07 10:45:09 -08002813 kRequestThreadPriority, /*isForApp*/ false, /*asynchronous*/ false);
Zhijun He90f7c372016-08-16 16:19:43 -07002814 if (res != OK) {
2815 ALOGW("Can't set realtime priority for request processing thread: %s (%d)",
2816 strerror(-res), res);
2817 } else {
2818 ALOGD("Set real time priority for request queue thread (tid %d)", requestThreadTid);
2819 }
Eino-Ville Talvalaf99498e2015-09-25 16:52:55 -07002820 }
2821
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002822 // Update device state
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002823 const camera_metadata_t *newSessionParams = sessionParams.getAndLock();
2824 const camera_metadata_t *currentSessionParams = mSessionParams.getAndLock();
2825 bool updateSessionParams = (newSessionParams != currentSessionParams) ? true : false;
2826 sessionParams.unlock(newSessionParams);
2827 mSessionParams.unlock(currentSessionParams);
2828 if (updateSessionParams) {
2829 mSessionParams = sessionParams;
2830 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002831
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002832 mNeedConfig = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002833
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002834 internalUpdateStatusLocked((mFakeStreamId == NO_STREAM) ?
Ruben Brunk183f0562015-08-12 12:55:02 -07002835 STATUS_CONFIGURED : STATUS_UNCONFIGURED);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002836
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002837 ALOGV("%s: Camera %s: Stream configuration complete", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002838
Zhijun He0a210512014-07-24 13:45:15 -07002839 // tear down the deleted streams after configure streams.
2840 mDeletedStreams.clear();
2841
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002842 auto rc = mPreparerThread->resume();
2843 if (rc != OK) {
2844 SET_ERR_L("%s: Camera %s: Preparer thread failed to resume!", __FUNCTION__, mId.string());
2845 return rc;
2846 }
2847
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002848 if (mFakeStreamId == NO_STREAM) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07002849 mRequestBufferSM.onStreamsConfigured();
2850 }
2851
Cliff Wuc2ad9c82021-04-21 00:58:58 +08002852 // Since the streams configuration of the injection camera is based on the internal camera, we
2853 // must wait until the internal camera configure streams before calling injectCamera() to
2854 // configure the injection streams.
2855 if (mInjectionMethods->isInjecting()) {
2856 ALOGV("%s: Injection camera %s: Start to configure streams.",
2857 __FUNCTION__, mInjectionMethods->getInjectedCamId().string());
2858 res = mInjectionMethods->injectCamera(config, bufferSizes);
2859 if (res != OK) {
2860 ALOGE("Can't finish inject camera process!");
2861 return res;
2862 }
2863 }
2864
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002865 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002866}
2867
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002868status_t Camera3Device::addFakeStreamLocked() {
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002869 ATRACE_CALL();
2870 status_t res;
2871
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002872 if (mFakeStreamId != NO_STREAM) {
2873 // Should never be adding a second fake stream when one is already
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002874 // active
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002875 SET_ERR_L("%s: Camera %s: A fake stream already exists!",
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002876 __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002877 return INVALID_OPERATION;
2878 }
2879
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002880 ALOGV("%s: Camera %s: Adding a fake stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002881
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002882 sp<Camera3OutputStreamInterface> fakeStream =
2883 new Camera3FakeStream(mNextStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002884
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002885 res = mOutputStreams.add(mNextStreamId, fakeStream);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002886 if (res < 0) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002887 SET_ERR_L("Can't add fake stream to set: %s (%d)", strerror(-res), res);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002888 return res;
2889 }
2890
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002891 mFakeStreamId = mNextStreamId;
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002892 mNextStreamId++;
2893
2894 return OK;
2895}
2896
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002897status_t Camera3Device::tryRemoveFakeStreamLocked() {
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002898 ATRACE_CALL();
2899 status_t res;
2900
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002901 if (mFakeStreamId == NO_STREAM) return OK;
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002902 if (mOutputStreams.size() == 1) return OK;
2903
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002904 ALOGV("%s: Camera %s: Removing the fake stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002905
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002906 // Ok, have a fake stream and there's at least one other output stream,
2907 // so remove the fake
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002908
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002909 sp<Camera3StreamInterface> deletedStream = mOutputStreams.get(mFakeStreamId);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002910 if (deletedStream == nullptr) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002911 SET_ERR_L("Fake stream %d does not appear to exist", mFakeStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002912 return INVALID_OPERATION;
2913 }
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002914 mOutputStreams.remove(mFakeStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002915
2916 // Free up the stream endpoint so that it can be used by some other stream
2917 res = deletedStream->disconnect();
2918 if (res != OK) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002919 SET_ERR_L("Can't disconnect deleted fake stream %d", mFakeStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002920 // fall through since we want to still list the stream as deleted.
2921 }
2922 mDeletedStreams.add(deletedStream);
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002923 mFakeStreamId = NO_STREAM;
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002924
2925 return res;
2926}
2927
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002928void Camera3Device::setErrorState(const char *fmt, ...) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002929 ATRACE_CALL();
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002930 Mutex::Autolock l(mLock);
2931 va_list args;
2932 va_start(args, fmt);
2933
2934 setErrorStateLockedV(fmt, args);
2935
2936 va_end(args);
2937}
2938
2939void Camera3Device::setErrorStateV(const char *fmt, va_list args) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002940 ATRACE_CALL();
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002941 Mutex::Autolock l(mLock);
2942 setErrorStateLockedV(fmt, args);
2943}
2944
2945void Camera3Device::setErrorStateLocked(const char *fmt, ...) {
2946 va_list args;
2947 va_start(args, fmt);
2948
2949 setErrorStateLockedV(fmt, args);
2950
2951 va_end(args);
2952}
2953
2954void Camera3Device::setErrorStateLockedV(const char *fmt, va_list args) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002955 // Print out all error messages to log
2956 String8 errorCause = String8::formatV(fmt, args);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002957 ALOGE("Camera %s: %s", mId.string(), errorCause.string());
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002958
2959 // But only do error state transition steps for the first error
Zhijun Heb05eeae2013-06-06 13:51:22 -07002960 if (mStatus == STATUS_ERROR || mStatus == STATUS_UNINITIALIZED) return;
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002961
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002962 mErrorCause = errorCause;
2963
Yin-Chia Yeh3d145ae2017-07-27 12:47:03 -07002964 if (mRequestThread != nullptr) {
2965 mRequestThread->setPaused(true);
2966 }
Ruben Brunk183f0562015-08-12 12:55:02 -07002967 internalUpdateStatusLocked(STATUS_ERROR);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002968
2969 // Notify upstream about a device error
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002970 sp<NotificationListener> listener = mListener.promote();
2971 if (listener != NULL) {
2972 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002973 CaptureResultExtras());
Shuzhen Wang316781a2020-08-18 18:11:01 -07002974 mSessionStatsBuilder.onDeviceError();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002975 }
2976
2977 // Save stack trace. View by dumping it later.
2978 CameraTraces::saveTrace();
2979 // TODO: consider adding errorCause and client pid/procname
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002980}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002981
2982/**
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002983 * In-flight request management
2984 */
2985
Jianing Weicb0652e2014-03-12 18:29:36 -07002986status_t Camera3Device::registerInFlight(uint32_t frameNumber,
Chien-Yu Chend196d612015-06-22 19:49:01 -07002987 int32_t numBuffers, CaptureResultExtras resultExtras, bool hasInput,
Shuzhen Wang5c22c152017-12-31 17:12:25 -08002988 bool hasAppCallback, nsecs_t maxExpectedDuration,
Shuzhen Wang99080502021-03-07 21:08:20 -08002989 const std::set<std::set<String8>>& physicalCameraIds,
2990 bool isStillCapture, bool isZslCapture, bool rotateAndCropAuto,
2991 const std::set<std::string>& cameraIdsWithZoom,
Shuzhen Wang316781a2020-08-18 18:11:01 -07002992 const SurfaceMap& outputSurfaces, nsecs_t requestTimeNs) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002993 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002994 std::lock_guard<std::mutex> l(mInFlightLock);
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002995
2996 ssize_t res;
Chien-Yu Chend196d612015-06-22 19:49:01 -07002997 res = mInFlightMap.add(frameNumber, InFlightRequest(numBuffers, resultExtras, hasInput,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07002998 hasAppCallback, maxExpectedDuration, physicalCameraIds, isStillCapture, isZslCapture,
Shuzhen Wang316781a2020-08-18 18:11:01 -07002999 rotateAndCropAuto, cameraIdsWithZoom, requestTimeNs, outputSurfaces));
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003000 if (res < 0) return res;
3001
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07003002 if (mInFlightMap.size() == 1) {
Emilian Peev26d975d2018-07-05 14:52:57 +01003003 // Hold a separate dedicated tracker lock to prevent race with disconnect and also
3004 // avoid a deadlock during reprocess requests.
3005 Mutex::Autolock l(mTrackerLock);
Yin-Chia Yeh38dfde52017-06-27 17:13:33 -07003006 if (mStatusTracker != nullptr) {
3007 mStatusTracker->markComponentActive(mInFlightStatusId);
3008 }
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07003009 }
3010
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003011 mExpectedInflightDuration += maxExpectedDuration;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003012 return OK;
3013}
3014
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003015void Camera3Device::onInflightEntryRemovedLocked(nsecs_t duration) {
Shuzhen Wangcadb3302016-11-04 14:17:56 -07003016 // Indicate idle inFlightMap to the status tracker
3017 if (mInFlightMap.size() == 0) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07003018 mRequestBufferSM.onInflightMapEmpty();
Emilian Peev26d975d2018-07-05 14:52:57 +01003019 // Hold a separate dedicated tracker lock to prevent race with disconnect and also
3020 // avoid a deadlock during reprocess requests.
3021 Mutex::Autolock l(mTrackerLock);
Yin-Chia Yeh38dfde52017-06-27 17:13:33 -07003022 if (mStatusTracker != nullptr) {
3023 mStatusTracker->markComponentIdle(mInFlightStatusId, Fence::NO_FENCE);
3024 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07003025 }
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003026 mExpectedInflightDuration -= duration;
Shuzhen Wangcadb3302016-11-04 14:17:56 -07003027}
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003028
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003029void Camera3Device::checkInflightMapLengthLocked() {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04003030 // Validation check - if we have too many in-flight frames with long total inflight duration,
Yin-Chia Yeh99fd0972019-06-27 14:22:44 -07003031 // something has likely gone wrong. This might still be legit only if application send in
3032 // a long burst of long exposure requests.
3033 if (mExpectedInflightDuration > kMinWarnInflightDuration) {
3034 if (!mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() > kInFlightWarnLimit) {
3035 CLOGW("In-flight list too large: %zu, total inflight duration %" PRIu64,
3036 mInFlightMap.size(), mExpectedInflightDuration);
3037 } else if (mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() >
3038 kInFlightWarnLimitHighSpeed) {
3039 CLOGW("In-flight list too large for high speed configuration: %zu,"
3040 "total inflight duration %" PRIu64,
3041 mInFlightMap.size(), mExpectedInflightDuration);
3042 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003043 }
3044}
3045
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003046void Camera3Device::onInflightMapFlushedLocked() {
3047 mExpectedInflightDuration = 0;
3048}
3049
3050void Camera3Device::removeInFlightMapEntryLocked(int idx) {
Jayant Chowdharyd4776262020-06-23 23:45:57 -07003051 ATRACE_HFR_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003052 nsecs_t duration = mInFlightMap.valueAt(idx).maxExpectedDuration;
3053 mInFlightMap.removeItemsAt(idx, 1);
3054
3055 onInflightEntryRemovedLocked(duration);
3056}
3057
3058
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003059void Camera3Device::flushInflightRequests() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003060 ATRACE_CALL();
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003061 sp<NotificationListener> listener;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003062 {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003063 std::lock_guard<std::mutex> l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003064 listener = mListener.promote();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003065 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003066
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003067 FlushInflightReqStates states {
3068 mId, mInFlightLock, mInFlightMap, mUseHalBufManager,
Shuzhen Wang316781a2020-08-18 18:11:01 -07003069 listener, *this, *mInterface, *this, mSessionStatsBuilder};
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003070
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003071 camera3::flushInflightRequests(states);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003072}
3073
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003074CameraMetadata Camera3Device::getLatestRequestLocked() {
Igor Murashkin1e479c02013-09-06 16:55:14 -07003075 ALOGV("%s", __FUNCTION__);
3076
Igor Murashkin1e479c02013-09-06 16:55:14 -07003077 CameraMetadata retVal;
3078
3079 if (mRequestThread != NULL) {
3080 retVal = mRequestThread->getLatestRequest();
3081 }
3082
Igor Murashkin1e479c02013-09-06 16:55:14 -07003083 return retVal;
3084}
3085
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07003086void Camera3Device::monitorMetadata(TagMonitor::eventSource source,
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003087 int64_t frameNumber, nsecs_t timestamp, const CameraMetadata& metadata,
3088 const std::unordered_map<std::string, CameraMetadata>& physicalMetadata) {
3089
3090 mTagMonitor.monitorMetadata(source, frameNumber, timestamp, metadata,
3091 physicalMetadata);
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07003092}
3093
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003094/**
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003095 * HalInterface inner class methods
3096 */
3097
Yifan Hongf79b5542017-04-11 14:44:25 -07003098Camera3Device::HalInterface::HalInterface(
3099 sp<ICameraDeviceSession> &session,
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003100 std::shared_ptr<RequestMetadataQueue> queue,
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003101 bool useHalBufManager, bool supportOfflineProcessing) :
Yifan Hongf79b5542017-04-11 14:44:25 -07003102 mHidlSession(session),
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003103 mRequestMetadataQueue(queue),
Emilian Peev4ec17882019-01-24 17:16:58 -08003104 mUseHalBufManager(useHalBufManager),
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003105 mIsReconfigurationQuerySupported(true),
3106 mSupportOfflineProcessing(supportOfflineProcessing) {
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003107 // Check with hardware service manager if we can downcast these interfaces
3108 // Somewhat expensive, so cache the results at startup
Shuzhen Wang83bff122020-11-20 15:51:39 -08003109 auto castResult_3_7 = device::V3_7::ICameraDeviceSession::castFrom(mHidlSession);
3110 if (castResult_3_7.isOk()) {
3111 mHidlSession_3_7 = castResult_3_7;
3112 }
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003113 auto castResult_3_6 = device::V3_6::ICameraDeviceSession::castFrom(mHidlSession);
3114 if (castResult_3_6.isOk()) {
3115 mHidlSession_3_6 = castResult_3_6;
3116 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003117 auto castResult_3_5 = device::V3_5::ICameraDeviceSession::castFrom(mHidlSession);
3118 if (castResult_3_5.isOk()) {
3119 mHidlSession_3_5 = castResult_3_5;
3120 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003121 auto castResult_3_4 = device::V3_4::ICameraDeviceSession::castFrom(mHidlSession);
3122 if (castResult_3_4.isOk()) {
3123 mHidlSession_3_4 = castResult_3_4;
3124 }
3125 auto castResult_3_3 = device::V3_3::ICameraDeviceSession::castFrom(mHidlSession);
3126 if (castResult_3_3.isOk()) {
3127 mHidlSession_3_3 = castResult_3_3;
3128 }
3129}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003130
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003131Camera3Device::HalInterface::HalInterface() :
3132 mUseHalBufManager(false),
3133 mSupportOfflineProcessing(false) {}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003134
3135Camera3Device::HalInterface::HalInterface(const HalInterface& other) :
Yifan Hongf79b5542017-04-11 14:44:25 -07003136 mHidlSession(other.mHidlSession),
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003137 mRequestMetadataQueue(other.mRequestMetadataQueue),
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003138 mUseHalBufManager(other.mUseHalBufManager),
3139 mSupportOfflineProcessing(other.mSupportOfflineProcessing) {}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003140
3141bool Camera3Device::HalInterface::valid() {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003142 return (mHidlSession != nullptr);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003143}
3144
3145void Camera3Device::HalInterface::clear() {
Shuzhen Wang83bff122020-11-20 15:51:39 -08003146 mHidlSession_3_7.clear();
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003147 mHidlSession_3_6.clear();
Emilian Peev644a3e12018-11-23 13:52:39 +00003148 mHidlSession_3_5.clear();
Emilian Peev9e740b02018-01-30 18:28:03 +00003149 mHidlSession_3_4.clear();
3150 mHidlSession_3_3.clear();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003151 mHidlSession.clear();
3152}
3153
3154status_t Camera3Device::HalInterface::constructDefaultRequestSettings(
Emilian Peevf4816702020-04-03 15:44:51 -07003155 camera_request_template_t templateId,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003156 /*out*/ camera_metadata_t **requestTemplate) {
3157 ATRACE_NAME("CameraHal::constructDefaultRequestSettings");
3158 if (!valid()) return INVALID_OPERATION;
3159 status_t res = OK;
3160
Emilian Peev31abd0a2017-05-11 18:37:46 +01003161 common::V1_0::Status status;
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003162
3163 auto requestCallback = [&status, &requestTemplate]
Emilian Peev31abd0a2017-05-11 18:37:46 +01003164 (common::V1_0::Status s, const device::V3_2::CameraMetadata& request) {
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003165 status = s;
3166 if (status == common::V1_0::Status::OK) {
3167 const camera_metadata *r =
3168 reinterpret_cast<const camera_metadata_t*>(request.data());
3169 size_t expectedSize = request.size();
3170 int ret = validate_camera_metadata_structure(r, &expectedSize);
3171 if (ret == OK || ret == CAMERA_METADATA_VALIDATION_SHIFTED) {
3172 *requestTemplate = clone_camera_metadata(r);
3173 if (*requestTemplate == nullptr) {
3174 ALOGE("%s: Unable to clone camera metadata received from HAL",
3175 __FUNCTION__);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003176 status = common::V1_0::Status::INTERNAL_ERROR;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003177 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003178 } else {
3179 ALOGE("%s: Malformed camera metadata received from HAL", __FUNCTION__);
3180 status = common::V1_0::Status::INTERNAL_ERROR;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003181 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003182 }
3183 };
3184 hardware::Return<void> err;
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003185 RequestTemplate id;
3186 switch (templateId) {
Emilian Peevf4816702020-04-03 15:44:51 -07003187 case CAMERA_TEMPLATE_PREVIEW:
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003188 id = RequestTemplate::PREVIEW;
3189 break;
Emilian Peevf4816702020-04-03 15:44:51 -07003190 case CAMERA_TEMPLATE_STILL_CAPTURE:
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003191 id = RequestTemplate::STILL_CAPTURE;
3192 break;
Emilian Peevf4816702020-04-03 15:44:51 -07003193 case CAMERA_TEMPLATE_VIDEO_RECORD:
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003194 id = RequestTemplate::VIDEO_RECORD;
3195 break;
Emilian Peevf4816702020-04-03 15:44:51 -07003196 case CAMERA_TEMPLATE_VIDEO_SNAPSHOT:
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003197 id = RequestTemplate::VIDEO_SNAPSHOT;
3198 break;
Emilian Peevf4816702020-04-03 15:44:51 -07003199 case CAMERA_TEMPLATE_ZERO_SHUTTER_LAG:
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003200 id = RequestTemplate::ZERO_SHUTTER_LAG;
3201 break;
Emilian Peevf4816702020-04-03 15:44:51 -07003202 case CAMERA_TEMPLATE_MANUAL:
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003203 id = RequestTemplate::MANUAL;
3204 break;
3205 default:
3206 // Unknown template ID, or this HAL is too old to support it
3207 return BAD_VALUE;
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003208 }
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003209 err = mHidlSession->constructDefaultRequestSettings(id, requestCallback);
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003210
Emilian Peev31abd0a2017-05-11 18:37:46 +01003211 if (!err.isOk()) {
3212 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3213 res = DEAD_OBJECT;
3214 } else {
3215 res = CameraProviderManager::mapToStatusT(status);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003216 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003217
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003218 return res;
3219}
3220
Emilian Peev4ec17882019-01-24 17:16:58 -08003221bool Camera3Device::HalInterface::isReconfigurationRequired(CameraMetadata& oldSessionParams,
3222 CameraMetadata& newSessionParams) {
3223 // We do reconfiguration by default;
3224 bool ret = true;
3225 if ((mHidlSession_3_5 != nullptr) && mIsReconfigurationQuerySupported) {
3226 android::hardware::hidl_vec<uint8_t> oldParams, newParams;
3227 camera_metadata_t* oldSessioMeta = const_cast<camera_metadata_t*>(
3228 oldSessionParams.getAndLock());
3229 camera_metadata_t* newSessioMeta = const_cast<camera_metadata_t*>(
3230 newSessionParams.getAndLock());
3231 oldParams.setToExternal(reinterpret_cast<uint8_t*>(oldSessioMeta),
3232 get_camera_metadata_size(oldSessioMeta));
3233 newParams.setToExternal(reinterpret_cast<uint8_t*>(newSessioMeta),
3234 get_camera_metadata_size(newSessioMeta));
3235 hardware::camera::common::V1_0::Status callStatus;
3236 bool required;
3237 auto hidlCb = [&callStatus, &required] (hardware::camera::common::V1_0::Status s,
3238 bool requiredFlag) {
3239 callStatus = s;
3240 required = requiredFlag;
3241 };
3242 auto err = mHidlSession_3_5->isReconfigurationRequired(oldParams, newParams, hidlCb);
3243 oldSessionParams.unlock(oldSessioMeta);
3244 newSessionParams.unlock(newSessioMeta);
3245 if (err.isOk()) {
3246 switch (callStatus) {
3247 case hardware::camera::common::V1_0::Status::OK:
3248 ret = required;
3249 break;
3250 case hardware::camera::common::V1_0::Status::METHOD_NOT_SUPPORTED:
3251 mIsReconfigurationQuerySupported = false;
3252 ret = true;
3253 break;
3254 default:
3255 ALOGV("%s: Reconfiguration query failed: %d", __FUNCTION__, callStatus);
3256 ret = true;
3257 }
3258 } else {
3259 ALOGE("%s: Unexpected binder error: %s", __FUNCTION__, err.description().c_str());
3260 ret = true;
3261 }
3262 }
3263
3264 return ret;
3265}
3266
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003267status_t Camera3Device::HalInterface::configureStreams(const camera_metadata_t *sessionParams,
Emilian Peevf4816702020-04-03 15:44:51 -07003268 camera_stream_configuration *config, const std::vector<uint32_t>& bufferSizes) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003269 ATRACE_NAME("CameraHal::configureStreams");
3270 if (!valid()) return INVALID_OPERATION;
3271 status_t res = OK;
3272
Shuzhen Wang83bff122020-11-20 15:51:39 -08003273 if (config->input_is_multi_resolution && mHidlSession_3_7 == nullptr) {
3274 ALOGE("%s: Camera device doesn't support multi-resolution input stream", __FUNCTION__);
3275 return BAD_VALUE;
3276 }
3277
Emilian Peev31abd0a2017-05-11 18:37:46 +01003278 // Convert stream config to HIDL
3279 std::set<int> activeStreams;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003280 device::V3_2::StreamConfiguration requestedConfiguration3_2;
3281 device::V3_4::StreamConfiguration requestedConfiguration3_4;
Shuzhen Wang83bff122020-11-20 15:51:39 -08003282 device::V3_7::StreamConfiguration requestedConfiguration3_7;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003283 requestedConfiguration3_2.streams.resize(config->num_streams);
3284 requestedConfiguration3_4.streams.resize(config->num_streams);
Shuzhen Wang83bff122020-11-20 15:51:39 -08003285 requestedConfiguration3_7.streams.resize(config->num_streams);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003286 for (size_t i = 0; i < config->num_streams; i++) {
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003287 device::V3_2::Stream &dst3_2 = requestedConfiguration3_2.streams[i];
3288 device::V3_4::Stream &dst3_4 = requestedConfiguration3_4.streams[i];
Shuzhen Wang83bff122020-11-20 15:51:39 -08003289 device::V3_7::Stream &dst3_7 = requestedConfiguration3_7.streams[i];
Emilian Peevf4816702020-04-03 15:44:51 -07003290 camera3::camera_stream_t *src = config->streams[i];
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003291
Emilian Peev31abd0a2017-05-11 18:37:46 +01003292 Camera3Stream* cam3stream = Camera3Stream::cast(src);
3293 cam3stream->setBufferFreedListener(this);
3294 int streamId = cam3stream->getId();
3295 StreamType streamType;
3296 switch (src->stream_type) {
Emilian Peevf4816702020-04-03 15:44:51 -07003297 case CAMERA_STREAM_OUTPUT:
Emilian Peev31abd0a2017-05-11 18:37:46 +01003298 streamType = StreamType::OUTPUT;
3299 break;
Emilian Peevf4816702020-04-03 15:44:51 -07003300 case CAMERA_STREAM_INPUT:
Emilian Peev31abd0a2017-05-11 18:37:46 +01003301 streamType = StreamType::INPUT;
3302 break;
3303 default:
3304 ALOGE("%s: Stream %d: Unsupported stream type %d",
3305 __FUNCTION__, streamId, config->streams[i]->stream_type);
3306 return BAD_VALUE;
3307 }
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003308 dst3_2.id = streamId;
3309 dst3_2.streamType = streamType;
3310 dst3_2.width = src->width;
3311 dst3_2.height = src->height;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003312 dst3_2.usage = mapToConsumerUsage(cam3stream->getUsage());
Emilian Peevf4816702020-04-03 15:44:51 -07003313 dst3_2.rotation = mapToStreamRotation((camera_stream_rotation_t) src->rotation);
Shuzhen Wang92653952019-05-07 15:11:43 -07003314 // For HidlSession version 3.5 or newer, the format and dataSpace sent
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08003315 // to HAL are original, not the overridden ones.
Shuzhen Wang92653952019-05-07 15:11:43 -07003316 if (mHidlSession_3_5 != nullptr) {
3317 dst3_2.format = mapToPixelFormat(cam3stream->isFormatOverridden() ?
3318 cam3stream->getOriginalFormat() : src->format);
3319 dst3_2.dataSpace = mapToHidlDataspace(cam3stream->isDataSpaceOverridden() ?
3320 cam3stream->getOriginalDataSpace() : src->data_space);
3321 } else {
3322 dst3_2.format = mapToPixelFormat(src->format);
3323 dst3_2.dataSpace = mapToHidlDataspace(src->data_space);
3324 }
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003325 dst3_4.v3_2 = dst3_2;
Emilian Peev192ee832018-01-31 14:46:47 +00003326 dst3_4.bufferSize = bufferSizes[i];
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003327 if (src->physical_camera_id != nullptr) {
3328 dst3_4.physicalCameraId = src->physical_camera_id;
3329 }
Shuzhen Wang83bff122020-11-20 15:51:39 -08003330 dst3_7.v3_4 = dst3_4;
3331 dst3_7.groupId = cam3stream->getHalStreamGroupId();
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08003332 dst3_7.sensorPixelModesUsed.resize(src->sensor_pixel_modes_used.size());
3333 size_t j = 0;
3334 for (int mode : src->sensor_pixel_modes_used) {
3335 dst3_7.sensorPixelModesUsed[j++] =
3336 static_cast<CameraMetadataEnumAndroidSensorPixelMode>(mode);
3337 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003338 activeStreams.insert(streamId);
3339 // Create Buffer ID map if necessary
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003340 mBufferRecords.tryCreateBufferCache(streamId);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003341 }
3342 // remove BufferIdMap for deleted streams
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003343 mBufferRecords.removeInactiveBufferCaches(activeStreams);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003344
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003345 StreamConfigurationMode operationMode;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003346 res = mapToStreamConfigurationMode(
Emilian Peevf4816702020-04-03 15:44:51 -07003347 (camera_stream_configuration_mode_t) config->operation_mode,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003348 /*out*/ &operationMode);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003349 if (res != OK) {
3350 return res;
3351 }
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003352 requestedConfiguration3_2.operationMode = operationMode;
3353 requestedConfiguration3_4.operationMode = operationMode;
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08003354 requestedConfiguration3_7.operationMode = operationMode;
3355 size_t sessionParamSize = get_camera_metadata_size(sessionParams);
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003356 requestedConfiguration3_4.sessionParams.setToExternal(
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003357 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(sessionParams)),
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08003358 sessionParamSize);
Shuzhen Wang83bff122020-11-20 15:51:39 -08003359 requestedConfiguration3_7.operationMode = operationMode;
3360 requestedConfiguration3_7.sessionParams.setToExternal(
3361 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(sessionParams)),
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08003362 sessionParamSize);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003363
Emilian Peev31abd0a2017-05-11 18:37:46 +01003364 // Invoke configureStreams
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003365 device::V3_3::HalStreamConfiguration finalConfiguration;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003366 device::V3_4::HalStreamConfiguration finalConfiguration3_4;
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003367 device::V3_6::HalStreamConfiguration finalConfiguration3_6;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003368 common::V1_0::Status status;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003369
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003370 auto configStream34Cb = [&status, &finalConfiguration3_4]
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003371 (common::V1_0::Status s, const device::V3_4::HalStreamConfiguration& halConfiguration) {
3372 finalConfiguration3_4 = halConfiguration;
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003373 status = s;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003374 };
3375
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003376 auto configStream36Cb = [&status, &finalConfiguration3_6]
3377 (common::V1_0::Status s, const device::V3_6::HalStreamConfiguration& halConfiguration) {
3378 finalConfiguration3_6 = halConfiguration;
3379 status = s;
3380 };
3381
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003382 auto postprocConfigStream34 = [&finalConfiguration, &finalConfiguration3_4]
3383 (hardware::Return<void>& err) -> status_t {
3384 if (!err.isOk()) {
3385 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3386 return DEAD_OBJECT;
3387 }
3388 finalConfiguration.streams.resize(finalConfiguration3_4.streams.size());
3389 for (size_t i = 0; i < finalConfiguration3_4.streams.size(); i++) {
3390 finalConfiguration.streams[i] = finalConfiguration3_4.streams[i].v3_3;
3391 }
3392 return OK;
3393 };
3394
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003395 auto postprocConfigStream36 = [&finalConfiguration, &finalConfiguration3_6]
3396 (hardware::Return<void>& err) -> status_t {
3397 if (!err.isOk()) {
3398 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3399 return DEAD_OBJECT;
3400 }
3401 finalConfiguration.streams.resize(finalConfiguration3_6.streams.size());
3402 for (size_t i = 0; i < finalConfiguration3_6.streams.size(); i++) {
3403 finalConfiguration.streams[i] = finalConfiguration3_6.streams[i].v3_4.v3_3;
3404 }
3405 return OK;
3406 };
3407
Shuzhen Wang92653952019-05-07 15:11:43 -07003408 // See which version of HAL we have
Shuzhen Wang83bff122020-11-20 15:51:39 -08003409 if (mHidlSession_3_7 != nullptr) {
3410 ALOGV("%s: v3.7 device found", __FUNCTION__);
3411 requestedConfiguration3_7.streamConfigCounter = mNextStreamConfigCounter++;
3412 requestedConfiguration3_7.multiResolutionInputImage = config->input_is_multi_resolution;
3413 auto err = mHidlSession_3_7->configureStreams_3_7(
3414 requestedConfiguration3_7, configStream36Cb);
3415 res = postprocConfigStream36(err);
3416 if (res != OK) {
3417 return res;
3418 }
3419 } else if (mHidlSession_3_6 != nullptr) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003420 ALOGV("%s: v3.6 device found", __FUNCTION__);
3421 device::V3_5::StreamConfiguration requestedConfiguration3_5;
3422 requestedConfiguration3_5.v3_4 = requestedConfiguration3_4;
3423 requestedConfiguration3_5.streamConfigCounter = mNextStreamConfigCounter++;
3424 auto err = mHidlSession_3_6->configureStreams_3_6(
3425 requestedConfiguration3_5, configStream36Cb);
3426 res = postprocConfigStream36(err);
3427 if (res != OK) {
3428 return res;
3429 }
3430 } else if (mHidlSession_3_5 != nullptr) {
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003431 ALOGV("%s: v3.5 device found", __FUNCTION__);
3432 device::V3_5::StreamConfiguration requestedConfiguration3_5;
3433 requestedConfiguration3_5.v3_4 = requestedConfiguration3_4;
3434 requestedConfiguration3_5.streamConfigCounter = mNextStreamConfigCounter++;
3435 auto err = mHidlSession_3_5->configureStreams_3_5(
3436 requestedConfiguration3_5, configStream34Cb);
3437 res = postprocConfigStream34(err);
3438 if (res != OK) {
3439 return res;
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003440 }
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003441 } else if (mHidlSession_3_4 != nullptr) {
3442 // We do; use v3.4 for the call
3443 ALOGV("%s: v3.4 device found", __FUNCTION__);
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003444 auto err = mHidlSession_3_4->configureStreams_3_4(
3445 requestedConfiguration3_4, configStream34Cb);
3446 res = postprocConfigStream34(err);
3447 if (res != OK) {
3448 return res;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003449 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003450 } else if (mHidlSession_3_3 != nullptr) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003451 // We do; use v3.3 for the call
3452 ALOGV("%s: v3.3 device found", __FUNCTION__);
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003453 auto err = mHidlSession_3_3->configureStreams_3_3(requestedConfiguration3_2,
Emilian Peev31abd0a2017-05-11 18:37:46 +01003454 [&status, &finalConfiguration]
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003455 (common::V1_0::Status s, const device::V3_3::HalStreamConfiguration& halConfiguration) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003456 finalConfiguration = halConfiguration;
3457 status = s;
3458 });
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003459 if (!err.isOk()) {
3460 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3461 return DEAD_OBJECT;
3462 }
3463 } else {
3464 // We don't; use v3.2 call and construct a v3.3 HalStreamConfiguration
3465 ALOGV("%s: v3.2 device found", __FUNCTION__);
3466 HalStreamConfiguration finalConfiguration_3_2;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003467 auto err = mHidlSession->configureStreams(requestedConfiguration3_2,
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003468 [&status, &finalConfiguration_3_2]
3469 (common::V1_0::Status s, const HalStreamConfiguration& halConfiguration) {
3470 finalConfiguration_3_2 = halConfiguration;
3471 status = s;
3472 });
3473 if (!err.isOk()) {
3474 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3475 return DEAD_OBJECT;
3476 }
3477 finalConfiguration.streams.resize(finalConfiguration_3_2.streams.size());
3478 for (size_t i = 0; i < finalConfiguration_3_2.streams.size(); i++) {
3479 finalConfiguration.streams[i].v3_2 = finalConfiguration_3_2.streams[i];
3480 finalConfiguration.streams[i].overrideDataSpace =
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003481 requestedConfiguration3_2.streams[i].dataSpace;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003482 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003483 }
3484
3485 if (status != common::V1_0::Status::OK ) {
3486 return CameraProviderManager::mapToStatusT(status);
3487 }
3488
3489 // And convert output stream configuration from HIDL
3490
3491 for (size_t i = 0; i < config->num_streams; i++) {
Emilian Peevf4816702020-04-03 15:44:51 -07003492 camera3::camera_stream_t *dst = config->streams[i];
Emilian Peev31abd0a2017-05-11 18:37:46 +01003493 int streamId = Camera3Stream::cast(dst)->getId();
3494
3495 // Start scan at i, with the assumption that the stream order matches
3496 size_t realIdx = i;
3497 bool found = false;
Eino-Ville Talvala370875f2019-04-12 12:40:27 -07003498 size_t halStreamCount = finalConfiguration.streams.size();
3499 for (size_t idx = 0; idx < halStreamCount; idx++) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003500 if (finalConfiguration.streams[realIdx].v3_2.id == streamId) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003501 found = true;
3502 break;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003503 }
Eino-Ville Talvala370875f2019-04-12 12:40:27 -07003504 realIdx = (realIdx >= halStreamCount - 1) ? 0 : realIdx + 1;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003505 }
3506 if (!found) {
3507 ALOGE("%s: Stream %d not found in stream configuration response from HAL",
3508 __FUNCTION__, streamId);
3509 return INVALID_OPERATION;
3510 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003511 device::V3_3::HalStream &src = finalConfiguration.streams[realIdx];
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003512 device::V3_6::HalStream &src_36 = finalConfiguration3_6.streams[realIdx];
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003513
Emilian Peev710c1422017-08-30 11:19:38 +01003514 Camera3Stream* dstStream = Camera3Stream::cast(dst);
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003515 int overrideFormat = mapToFrameworkFormat(src.v3_2.overrideFormat);
3516 android_dataspace overrideDataSpace = mapToFrameworkDataspace(src.overrideDataSpace);
3517
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003518 if (mHidlSession_3_6 != nullptr) {
3519 dstStream->setOfflineProcessingSupport(src_36.supportOffline);
3520 }
3521
Yin-Chia Yeh90667662019-07-01 15:45:00 -07003522 if (dstStream->getOriginalFormat() != HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
Shuzhen Wang92653952019-05-07 15:11:43 -07003523 dstStream->setFormatOverride(false);
3524 dstStream->setDataSpaceOverride(false);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003525 if (dst->format != overrideFormat) {
3526 ALOGE("%s: Stream %d: Format override not allowed for format 0x%x", __FUNCTION__,
3527 streamId, dst->format);
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003528 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003529 if (dst->data_space != overrideDataSpace) {
3530 ALOGE("%s: Stream %d: DataSpace override not allowed for format 0x%x", __FUNCTION__,
3531 streamId, dst->format);
3532 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003533 } else {
Shuzhen Wang92653952019-05-07 15:11:43 -07003534 bool needFormatOverride =
3535 requestedConfiguration3_2.streams[i].format != src.v3_2.overrideFormat;
3536 bool needDataspaceOverride =
3537 requestedConfiguration3_2.streams[i].dataSpace != src.overrideDataSpace;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003538 // Override allowed with IMPLEMENTATION_DEFINED
Shuzhen Wang92653952019-05-07 15:11:43 -07003539 dstStream->setFormatOverride(needFormatOverride);
3540 dstStream->setDataSpaceOverride(needDataspaceOverride);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003541 dst->format = overrideFormat;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003542 dst->data_space = overrideDataSpace;
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003543 }
3544
Emilian Peevf4816702020-04-03 15:44:51 -07003545 if (dst->stream_type == CAMERA_STREAM_INPUT) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003546 if (src.v3_2.producerUsage != 0) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003547 ALOGE("%s: Stream %d: INPUT streams must have 0 for producer usage",
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003548 __FUNCTION__, streamId);
3549 return INVALID_OPERATION;
3550 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003551 dstStream->setUsage(
3552 mapConsumerToFrameworkUsage(src.v3_2.consumerUsage));
Emilian Peev31abd0a2017-05-11 18:37:46 +01003553 } else {
3554 // OUTPUT
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003555 if (src.v3_2.consumerUsage != 0) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003556 ALOGE("%s: Stream %d: OUTPUT streams must have 0 for consumer usage",
3557 __FUNCTION__, streamId);
3558 return INVALID_OPERATION;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003559 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003560 dstStream->setUsage(
3561 mapProducerToFrameworkUsage(src.v3_2.producerUsage));
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003562 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003563 dst->max_buffers = src.v3_2.maxBuffers;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003564 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003565
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003566 return res;
3567}
3568
Cliff Wuc2ad9c82021-04-21 00:58:58 +08003569status_t Camera3Device::HalInterface::configureInjectedStreams(
3570 const camera_metadata_t* sessionParams, camera_stream_configuration* config,
3571 const std::vector<uint32_t>& bufferSizes,
3572 const CameraMetadata& cameraCharacteristics) {
3573 ATRACE_NAME("InjectionCameraHal::configureStreams");
3574 if (!valid()) return INVALID_OPERATION;
3575 status_t res = OK;
3576
3577 if (config->input_is_multi_resolution) {
3578 ALOGE("%s: Injection camera device doesn't support multi-resolution input "
3579 "stream", __FUNCTION__);
3580 return BAD_VALUE;
3581 }
3582
3583 // Convert stream config to HIDL
3584 std::set<int> activeStreams;
3585 device::V3_2::StreamConfiguration requestedConfiguration3_2;
3586 device::V3_4::StreamConfiguration requestedConfiguration3_4;
3587 device::V3_7::StreamConfiguration requestedConfiguration3_7;
3588 requestedConfiguration3_2.streams.resize(config->num_streams);
3589 requestedConfiguration3_4.streams.resize(config->num_streams);
3590 requestedConfiguration3_7.streams.resize(config->num_streams);
3591 for (size_t i = 0; i < config->num_streams; i++) {
3592 device::V3_2::Stream& dst3_2 = requestedConfiguration3_2.streams[i];
3593 device::V3_4::Stream& dst3_4 = requestedConfiguration3_4.streams[i];
3594 device::V3_7::Stream& dst3_7 = requestedConfiguration3_7.streams[i];
3595 camera3::camera_stream_t* src = config->streams[i];
3596
3597 Camera3Stream* cam3stream = Camera3Stream::cast(src);
3598 cam3stream->setBufferFreedListener(this);
3599 int streamId = cam3stream->getId();
3600 StreamType streamType;
3601 switch (src->stream_type) {
3602 case CAMERA_STREAM_OUTPUT:
3603 streamType = StreamType::OUTPUT;
3604 break;
3605 case CAMERA_STREAM_INPUT:
3606 streamType = StreamType::INPUT;
3607 break;
3608 default:
3609 ALOGE("%s: Stream %d: Unsupported stream type %d", __FUNCTION__,
3610 streamId, config->streams[i]->stream_type);
3611 return BAD_VALUE;
3612 }
3613 dst3_2.id = streamId;
3614 dst3_2.streamType = streamType;
3615 dst3_2.width = src->width;
3616 dst3_2.height = src->height;
3617 dst3_2.usage = mapToConsumerUsage(cam3stream->getUsage());
3618 dst3_2.rotation =
3619 mapToStreamRotation((camera_stream_rotation_t)src->rotation);
3620 // For HidlSession version 3.5 or newer, the format and dataSpace sent
3621 // to HAL are original, not the overridden ones.
3622 if (mHidlSession_3_5 != nullptr) {
3623 dst3_2.format = mapToPixelFormat(cam3stream->isFormatOverridden()
3624 ? cam3stream->getOriginalFormat()
3625 : src->format);
3626 dst3_2.dataSpace =
3627 mapToHidlDataspace(cam3stream->isDataSpaceOverridden()
3628 ? cam3stream->getOriginalDataSpace()
3629 : src->data_space);
3630 } else {
3631 dst3_2.format = mapToPixelFormat(src->format);
3632 dst3_2.dataSpace = mapToHidlDataspace(src->data_space);
3633 }
3634 dst3_4.v3_2 = dst3_2;
3635 dst3_4.bufferSize = bufferSizes[i];
3636 if (src->physical_camera_id != nullptr) {
3637 dst3_4.physicalCameraId = src->physical_camera_id;
3638 }
3639 dst3_7.v3_4 = dst3_4;
3640 dst3_7.groupId = cam3stream->getHalStreamGroupId();
3641 dst3_7.sensorPixelModesUsed.resize(src->sensor_pixel_modes_used.size());
3642 size_t j = 0;
3643 for (int mode : src->sensor_pixel_modes_used) {
3644 dst3_7.sensorPixelModesUsed[j++] =
3645 static_cast<CameraMetadataEnumAndroidSensorPixelMode>(mode);
3646 }
3647 activeStreams.insert(streamId);
3648 // Create Buffer ID map if necessary
3649 mBufferRecords.tryCreateBufferCache(streamId);
3650 }
3651 // remove BufferIdMap for deleted streams
3652 mBufferRecords.removeInactiveBufferCaches(activeStreams);
3653
3654 StreamConfigurationMode operationMode;
3655 res = mapToStreamConfigurationMode(
3656 (camera_stream_configuration_mode_t)config->operation_mode,
3657 /*out*/ &operationMode);
3658 if (res != OK) {
3659 return res;
3660 }
3661 requestedConfiguration3_7.operationMode = operationMode;
3662 size_t sessionParamSize = get_camera_metadata_size(sessionParams);
3663 requestedConfiguration3_7.operationMode = operationMode;
3664 requestedConfiguration3_7.sessionParams.setToExternal(
3665 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(sessionParams)),
3666 sessionParamSize);
3667
3668 // See which version of HAL we have
3669 if (mHidlSession_3_7 != nullptr) {
3670 requestedConfiguration3_7.streamConfigCounter = mNextStreamConfigCounter++;
3671 requestedConfiguration3_7.multiResolutionInputImage =
3672 config->input_is_multi_resolution;
3673
3674 const camera_metadata_t* rawMetadata = cameraCharacteristics.getAndLock();
3675 ::android::hardware::camera::device::V3_2::CameraMetadata hidlChars = {};
3676 hidlChars.setToExternal(
3677 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(rawMetadata)),
3678 get_camera_metadata_size(rawMetadata));
3679 cameraCharacteristics.unlock(rawMetadata);
3680
3681 sp<hardware::camera::device::V3_7::ICameraInjectionSession>
3682 hidlInjectionSession_3_7;
3683 auto castInjectionResult_3_7 =
3684 device::V3_7::ICameraInjectionSession::castFrom(mHidlSession_3_7);
3685 if (castInjectionResult_3_7.isOk()) {
3686 hidlInjectionSession_3_7 = castInjectionResult_3_7;
3687 } else {
3688 ALOGE("%s: Transaction error: %s", __FUNCTION__,
3689 castInjectionResult_3_7.description().c_str());
3690 return DEAD_OBJECT;
3691 }
3692
3693 auto err = hidlInjectionSession_3_7->configureInjectionStreams(
3694 requestedConfiguration3_7, hidlChars);
3695 if (!err.isOk()) {
3696 ALOGE("%s: Transaction error: %s", __FUNCTION__,
3697 err.description().c_str());
3698 return DEAD_OBJECT;
3699 }
3700 } else {
3701 ALOGE("%s: mHidlSession_3_7 does not exist, the lowest version of injection "
3702 "session is 3.7", __FUNCTION__);
3703 return DEAD_OBJECT;
3704 }
3705
3706 return res;
3707}
3708
Emilian Peevf4816702020-04-03 15:44:51 -07003709status_t Camera3Device::HalInterface::wrapAsHidlRequest(camera_capture_request_t* request,
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003710 /*out*/device::V3_2::CaptureRequest* captureRequest,
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003711 /*out*/std::vector<native_handle_t*>* handlesCreated,
3712 /*out*/std::vector<std::pair<int32_t, int32_t>>* inflightBuffers) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003713 ATRACE_CALL();
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003714 if (captureRequest == nullptr || handlesCreated == nullptr || inflightBuffers == nullptr) {
3715 ALOGE("%s: captureRequest (%p), handlesCreated (%p), and inflightBuffers(%p) "
3716 "must not be null", __FUNCTION__, captureRequest, handlesCreated, inflightBuffers);
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003717 return BAD_VALUE;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003718 }
3719
3720 captureRequest->frameNumber = request->frame_number;
Yifan Hongf79b5542017-04-11 14:44:25 -07003721
3722 captureRequest->fmqSettingsSize = 0;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003723
3724 {
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003725 if (request->input_buffer != nullptr) {
3726 int32_t streamId = Camera3Stream::cast(request->input_buffer->stream)->getId();
3727 buffer_handle_t buf = *(request->input_buffer->buffer);
3728 auto pair = getBufferId(buf, streamId);
3729 bool isNewBuffer = pair.first;
3730 uint64_t bufferId = pair.second;
3731 captureRequest->inputBuffer.streamId = streamId;
3732 captureRequest->inputBuffer.bufferId = bufferId;
3733 captureRequest->inputBuffer.buffer = (isNewBuffer) ? buf : nullptr;
3734 captureRequest->inputBuffer.status = BufferStatus::OK;
3735 native_handle_t *acquireFence = nullptr;
3736 if (request->input_buffer->acquire_fence != -1) {
3737 acquireFence = native_handle_create(1,0);
3738 acquireFence->data[0] = request->input_buffer->acquire_fence;
3739 handlesCreated->push_back(acquireFence);
3740 }
3741 captureRequest->inputBuffer.acquireFence = acquireFence;
3742 captureRequest->inputBuffer.releaseFence = nullptr;
3743
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003744 mBufferRecords.pushInflightBuffer(captureRequest->frameNumber, streamId,
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003745 request->input_buffer->buffer);
3746 inflightBuffers->push_back(std::make_pair(captureRequest->frameNumber, streamId));
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003747 } else {
3748 captureRequest->inputBuffer.streamId = -1;
3749 captureRequest->inputBuffer.bufferId = BUFFER_ID_NO_BUFFER;
3750 }
3751
3752 captureRequest->outputBuffers.resize(request->num_output_buffers);
3753 for (size_t i = 0; i < request->num_output_buffers; i++) {
Emilian Peevf4816702020-04-03 15:44:51 -07003754 const camera_stream_buffer_t *src = request->output_buffers + i;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003755 StreamBuffer &dst = captureRequest->outputBuffers[i];
3756 int32_t streamId = Camera3Stream::cast(src->stream)->getId();
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003757 if (src->buffer != nullptr) {
3758 buffer_handle_t buf = *(src->buffer);
3759 auto pair = getBufferId(buf, streamId);
3760 bool isNewBuffer = pair.first;
3761 dst.bufferId = pair.second;
3762 dst.buffer = isNewBuffer ? buf : nullptr;
3763 native_handle_t *acquireFence = nullptr;
3764 if (src->acquire_fence != -1) {
3765 acquireFence = native_handle_create(1,0);
3766 acquireFence->data[0] = src->acquire_fence;
3767 handlesCreated->push_back(acquireFence);
3768 }
3769 dst.acquireFence = acquireFence;
3770 } else if (mUseHalBufManager) {
3771 // HAL buffer management path
3772 dst.bufferId = BUFFER_ID_NO_BUFFER;
3773 dst.buffer = nullptr;
3774 dst.acquireFence = nullptr;
3775 } else {
3776 ALOGE("%s: cannot send a null buffer in capture request!", __FUNCTION__);
3777 return BAD_VALUE;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003778 }
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003779 dst.streamId = streamId;
3780 dst.status = BufferStatus::OK;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003781 dst.releaseFence = nullptr;
3782
Yin-Chia Yeh5f840f82019-03-05 11:59:04 -08003783 // Output buffers are empty when using HAL buffer manager
3784 if (!mUseHalBufManager) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003785 mBufferRecords.pushInflightBuffer(
3786 captureRequest->frameNumber, streamId, src->buffer);
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003787 inflightBuffers->push_back(std::make_pair(captureRequest->frameNumber, streamId));
Yin-Chia Yeh5f840f82019-03-05 11:59:04 -08003788 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003789 }
3790 }
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003791 return OK;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003792}
3793
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003794void Camera3Device::HalInterface::cleanupNativeHandles(
3795 std::vector<native_handle_t*> *handles, bool closeFd) {
3796 if (handles == nullptr) {
3797 return;
3798 }
3799 if (closeFd) {
3800 for (auto& handle : *handles) {
3801 native_handle_close(handle);
3802 }
3803 }
3804 for (auto& handle : *handles) {
3805 native_handle_delete(handle);
3806 }
3807 handles->clear();
3808 return;
3809}
3810
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003811status_t Camera3Device::HalInterface::processBatchCaptureRequests(
Emilian Peevf4816702020-04-03 15:44:51 -07003812 std::vector<camera_capture_request_t*>& requests,/*out*/uint32_t* numRequestProcessed) {
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003813 ATRACE_NAME("CameraHal::processBatchCaptureRequests");
3814 if (!valid()) return INVALID_OPERATION;
3815
Emilian Peevaebbe412018-01-15 13:53:24 +00003816 sp<device::V3_4::ICameraDeviceSession> hidlSession_3_4;
Shuzhen Wang83bff122020-11-20 15:51:39 -08003817 sp<device::V3_7::ICameraDeviceSession> hidlSession_3_7;
3818 auto castResult_3_7 = device::V3_7::ICameraDeviceSession::castFrom(mHidlSession);
3819 if (castResult_3_7.isOk()) {
3820 hidlSession_3_7 = castResult_3_7;
3821 }
Emilian Peevaebbe412018-01-15 13:53:24 +00003822 auto castResult_3_4 = device::V3_4::ICameraDeviceSession::castFrom(mHidlSession);
3823 if (castResult_3_4.isOk()) {
3824 hidlSession_3_4 = castResult_3_4;
3825 }
3826
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003827 hardware::hidl_vec<device::V3_2::CaptureRequest> captureRequests;
Emilian Peevaebbe412018-01-15 13:53:24 +00003828 hardware::hidl_vec<device::V3_4::CaptureRequest> captureRequests_3_4;
Shuzhen Wang83bff122020-11-20 15:51:39 -08003829 hardware::hidl_vec<device::V3_7::CaptureRequest> captureRequests_3_7;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003830 size_t batchSize = requests.size();
Shuzhen Wang83bff122020-11-20 15:51:39 -08003831 if (hidlSession_3_7 != nullptr) {
3832 captureRequests_3_7.resize(batchSize);
3833 } else if (hidlSession_3_4 != nullptr) {
Emilian Peevaebbe412018-01-15 13:53:24 +00003834 captureRequests_3_4.resize(batchSize);
3835 } else {
3836 captureRequests.resize(batchSize);
3837 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003838 std::vector<native_handle_t*> handlesCreated;
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003839 std::vector<std::pair<int32_t, int32_t>> inflightBuffers;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003840
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003841 status_t res = OK;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003842 for (size_t i = 0; i < batchSize; i++) {
Shuzhen Wang83bff122020-11-20 15:51:39 -08003843 if (hidlSession_3_7 != nullptr) {
3844 res = wrapAsHidlRequest(requests[i], /*out*/&captureRequests_3_7[i].v3_4.v3_2,
3845 /*out*/&handlesCreated, /*out*/&inflightBuffers);
3846 } else if (hidlSession_3_4 != nullptr) {
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003847 res = wrapAsHidlRequest(requests[i], /*out*/&captureRequests_3_4[i].v3_2,
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003848 /*out*/&handlesCreated, /*out*/&inflightBuffers);
Emilian Peevaebbe412018-01-15 13:53:24 +00003849 } else {
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003850 res = wrapAsHidlRequest(requests[i], /*out*/&captureRequests[i],
3851 /*out*/&handlesCreated, /*out*/&inflightBuffers);
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003852 }
3853 if (res != OK) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003854 mBufferRecords.popInflightBuffers(inflightBuffers);
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003855 cleanupNativeHandles(&handlesCreated);
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003856 return res;
Emilian Peevaebbe412018-01-15 13:53:24 +00003857 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003858 }
3859
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003860 std::vector<device::V3_2::BufferCache> cachesToRemove;
3861 {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003862 std::lock_guard<std::mutex> lock(mFreedBuffersLock);
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003863 for (auto& pair : mFreedBuffers) {
3864 // The stream might have been removed since onBufferFreed
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003865 if (mBufferRecords.isStreamCached(pair.first)) {
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003866 cachesToRemove.push_back({pair.first, pair.second});
3867 }
3868 }
3869 mFreedBuffers.clear();
3870 }
3871
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003872 common::V1_0::Status status = common::V1_0::Status::INTERNAL_ERROR;
3873 *numRequestProcessed = 0;
Yifan Hongf79b5542017-04-11 14:44:25 -07003874
3875 // Write metadata to FMQ.
3876 for (size_t i = 0; i < batchSize; i++) {
Emilian Peevf4816702020-04-03 15:44:51 -07003877 camera_capture_request_t* request = requests[i];
Emilian Peevaebbe412018-01-15 13:53:24 +00003878 device::V3_2::CaptureRequest* captureRequest;
Shuzhen Wang83bff122020-11-20 15:51:39 -08003879 if (hidlSession_3_7 != nullptr) {
3880 captureRequest = &captureRequests_3_7[i].v3_4.v3_2;
3881 } else if (hidlSession_3_4 != nullptr) {
Emilian Peevaebbe412018-01-15 13:53:24 +00003882 captureRequest = &captureRequests_3_4[i].v3_2;
3883 } else {
3884 captureRequest = &captureRequests[i];
3885 }
Yifan Hongf79b5542017-04-11 14:44:25 -07003886
3887 if (request->settings != nullptr) {
3888 size_t settingsSize = get_camera_metadata_size(request->settings);
3889 if (mRequestMetadataQueue != nullptr && mRequestMetadataQueue->write(
3890 reinterpret_cast<const uint8_t*>(request->settings), settingsSize)) {
3891 captureRequest->settings.resize(0);
3892 captureRequest->fmqSettingsSize = settingsSize;
3893 } else {
3894 if (mRequestMetadataQueue != nullptr) {
3895 ALOGW("%s: couldn't utilize fmq, fallback to hwbinder", __FUNCTION__);
3896 }
3897 captureRequest->settings.setToExternal(
3898 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(request->settings)),
3899 get_camera_metadata_size(request->settings));
3900 captureRequest->fmqSettingsSize = 0u;
3901 }
3902 } else {
3903 // A null request settings maps to a size-0 CameraMetadata
3904 captureRequest->settings.resize(0);
3905 captureRequest->fmqSettingsSize = 0u;
3906 }
Emilian Peevaebbe412018-01-15 13:53:24 +00003907
Shuzhen Wang83bff122020-11-20 15:51:39 -08003908 // hidl session 3.7 specific handling.
3909 if (hidlSession_3_7 != nullptr) {
3910 captureRequests_3_7[i].inputWidth = request->input_width;
3911 captureRequests_3_7[i].inputHeight = request->input_height;
3912 }
3913
3914 // hidl session 3.7 and 3.4 specific handling.
3915 if (hidlSession_3_7 != nullptr || hidlSession_3_4 != nullptr) {
3916 hardware::hidl_vec<device::V3_4::PhysicalCameraSetting>& physicalCameraSettings =
3917 (hidlSession_3_7 != nullptr) ?
3918 captureRequests_3_7[i].v3_4.physicalCameraSettings :
3919 captureRequests_3_4[i].physicalCameraSettings;
3920 physicalCameraSettings.resize(request->num_physcam_settings);
Emilian Peevaebbe412018-01-15 13:53:24 +00003921 for (size_t j = 0; j < request->num_physcam_settings; j++) {
Emilian Peev00420d22018-02-05 21:33:13 +00003922 if (request->physcam_settings != nullptr) {
3923 size_t settingsSize = get_camera_metadata_size(request->physcam_settings[j]);
3924 if (mRequestMetadataQueue != nullptr && mRequestMetadataQueue->write(
3925 reinterpret_cast<const uint8_t*>(request->physcam_settings[j]),
3926 settingsSize)) {
Shuzhen Wang83bff122020-11-20 15:51:39 -08003927 physicalCameraSettings[j].settings.resize(0);
3928 physicalCameraSettings[j].fmqSettingsSize = settingsSize;
Emilian Peev00420d22018-02-05 21:33:13 +00003929 } else {
3930 if (mRequestMetadataQueue != nullptr) {
3931 ALOGW("%s: couldn't utilize fmq, fallback to hwbinder", __FUNCTION__);
3932 }
Shuzhen Wang83bff122020-11-20 15:51:39 -08003933 physicalCameraSettings[j].settings.setToExternal(
Emilian Peev00420d22018-02-05 21:33:13 +00003934 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(
3935 request->physcam_settings[j])),
3936 get_camera_metadata_size(request->physcam_settings[j]));
Shuzhen Wang83bff122020-11-20 15:51:39 -08003937 physicalCameraSettings[j].fmqSettingsSize = 0u;
Emilian Peevaebbe412018-01-15 13:53:24 +00003938 }
Emilian Peev00420d22018-02-05 21:33:13 +00003939 } else {
Yin-Chia Yeha2849702021-03-10 10:11:33 -08003940 physicalCameraSettings[j].fmqSettingsSize = 0u;
3941 physicalCameraSettings[j].settings.resize(0);
Emilian Peevaebbe412018-01-15 13:53:24 +00003942 }
Shuzhen Wang83bff122020-11-20 15:51:39 -08003943 physicalCameraSettings[j].physicalCameraId = request->physcam_id[j];
Emilian Peevaebbe412018-01-15 13:53:24 +00003944 }
3945 }
Yifan Hongf79b5542017-04-11 14:44:25 -07003946 }
Emilian Peevaebbe412018-01-15 13:53:24 +00003947
3948 hardware::details::return_status err;
Jayant Chowdharyc8d581e2018-07-16 14:46:23 -07003949 auto resultCallback =
3950 [&status, &numRequestProcessed] (auto s, uint32_t n) {
3951 status = s;
3952 *numRequestProcessed = n;
3953 };
Shuzhen Wang83bff122020-11-20 15:51:39 -08003954 if (hidlSession_3_7 != nullptr) {
3955 err = hidlSession_3_7->processCaptureRequest_3_7(captureRequests_3_7, cachesToRemove,
3956 resultCallback);
3957 } else if (hidlSession_3_4 != nullptr) {
Emilian Peevaebbe412018-01-15 13:53:24 +00003958 err = hidlSession_3_4->processCaptureRequest_3_4(captureRequests_3_4, cachesToRemove,
Jayant Chowdharyc8d581e2018-07-16 14:46:23 -07003959 resultCallback);
Emilian Peevaebbe412018-01-15 13:53:24 +00003960 } else {
3961 err = mHidlSession->processCaptureRequest(captureRequests, cachesToRemove,
Jayant Chowdharyc8d581e2018-07-16 14:46:23 -07003962 resultCallback);
Emilian Peevaebbe412018-01-15 13:53:24 +00003963 }
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -07003964 if (!err.isOk()) {
3965 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003966 status = common::V1_0::Status::CAMERA_DISCONNECTED;
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -07003967 }
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003968
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003969 if (status == common::V1_0::Status::OK && *numRequestProcessed != batchSize) {
3970 ALOGE("%s: processCaptureRequest returns OK but processed %d/%zu requests",
3971 __FUNCTION__, *numRequestProcessed, batchSize);
3972 status = common::V1_0::Status::INTERNAL_ERROR;
3973 }
3974
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003975 res = CameraProviderManager::mapToStatusT(status);
3976 if (res == OK) {
3977 if (mHidlSession->isRemote()) {
3978 // Only close acquire fence FDs when the HIDL transaction succeeds (so the FDs have been
3979 // sent to camera HAL processes)
3980 cleanupNativeHandles(&handlesCreated, /*closeFd*/true);
3981 } else {
3982 // In passthrough mode the FDs are now owned by HAL
3983 cleanupNativeHandles(&handlesCreated);
3984 }
3985 } else {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003986 mBufferRecords.popInflightBuffers(inflightBuffers);
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003987 cleanupNativeHandles(&handlesCreated);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003988 }
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003989 return res;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003990}
3991
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003992status_t Camera3Device::HalInterface::flush() {
3993 ATRACE_NAME("CameraHal::flush");
3994 if (!valid()) return INVALID_OPERATION;
3995 status_t res = OK;
3996
Emilian Peev31abd0a2017-05-11 18:37:46 +01003997 auto err = mHidlSession->flush();
3998 if (!err.isOk()) {
3999 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
4000 res = DEAD_OBJECT;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004001 } else {
Emilian Peev31abd0a2017-05-11 18:37:46 +01004002 res = CameraProviderManager::mapToStatusT(err);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004003 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01004004
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004005 return res;
4006}
4007
Emilian Peev31abd0a2017-05-11 18:37:46 +01004008status_t Camera3Device::HalInterface::dump(int /*fd*/) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004009 ATRACE_NAME("CameraHal::dump");
4010 if (!valid()) return INVALID_OPERATION;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004011
Emilian Peev31abd0a2017-05-11 18:37:46 +01004012 // Handled by CameraProviderManager::dump
4013
4014 return OK;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004015}
4016
4017status_t Camera3Device::HalInterface::close() {
4018 ATRACE_NAME("CameraHal::close()");
4019 if (!valid()) return INVALID_OPERATION;
4020 status_t res = OK;
4021
Emilian Peev31abd0a2017-05-11 18:37:46 +01004022 auto err = mHidlSession->close();
4023 // Interface will be dead shortly anyway, so don't log errors
4024 if (!err.isOk()) {
4025 res = DEAD_OBJECT;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004026 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01004027
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004028 return res;
4029}
4030
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004031void Camera3Device::HalInterface::signalPipelineDrain(const std::vector<int>& streamIds) {
4032 ATRACE_NAME("CameraHal::signalPipelineDrain");
4033 if (!valid() || mHidlSession_3_5 == nullptr) {
4034 ALOGE("%s called on invalid camera!", __FUNCTION__);
4035 return;
4036 }
4037
Yin-Chia Yehc300a072019-02-13 14:56:57 -08004038 auto err = mHidlSession_3_5->signalStreamFlush(streamIds, mNextStreamConfigCounter - 1);
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004039 if (!err.isOk()) {
4040 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
4041 return;
4042 }
4043}
4044
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004045status_t Camera3Device::HalInterface::switchToOffline(
4046 const std::vector<int32_t>& streamsToKeep,
4047 /*out*/hardware::camera::device::V3_6::CameraOfflineSessionInfo* offlineSessionInfo,
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004048 /*out*/sp<hardware::camera::device::V3_6::ICameraOfflineSession>* offlineSession,
4049 /*out*/camera3::BufferRecords* bufferRecords) {
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004050 ATRACE_NAME("CameraHal::switchToOffline");
4051 if (!valid() || mHidlSession_3_6 == nullptr) {
4052 ALOGE("%s called on invalid camera!", __FUNCTION__);
4053 return INVALID_OPERATION;
4054 }
4055
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004056 if (offlineSessionInfo == nullptr || offlineSession == nullptr || bufferRecords == nullptr) {
4057 ALOGE("%s: output arguments must not be null!", __FUNCTION__);
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004058 return INVALID_OPERATION;
4059 }
4060
4061 common::V1_0::Status status = common::V1_0::Status::INTERNAL_ERROR;
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004062 auto resultCallback =
4063 [&status, &offlineSessionInfo, &offlineSession] (auto s, auto info, auto session) {
4064 status = s;
4065 *offlineSessionInfo = info;
4066 *offlineSession = session;
4067 };
4068 auto err = mHidlSession_3_6->switchToOffline(streamsToKeep, resultCallback);
4069
4070 if (!err.isOk()) {
4071 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
4072 return DEAD_OBJECT;
4073 }
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004074
4075 status_t ret = CameraProviderManager::mapToStatusT(status);
4076 if (ret != OK) {
4077 return ret;
4078 }
4079
4080 // TODO: assert no ongoing requestBuffer/returnBuffer call here
4081 // TODO: update RequestBufferStateMachine to block requestBuffer/returnBuffer once HAL
4082 // returns from switchToOffline.
4083
4084
4085 // Validate buffer caches
4086 std::vector<int32_t> streams;
4087 streams.reserve(offlineSessionInfo->offlineStreams.size());
4088 for (auto offlineStream : offlineSessionInfo->offlineStreams) {
4089 int32_t id = offlineStream.id;
4090 streams.push_back(id);
4091 // Verify buffer caches
4092 std::vector<uint64_t> bufIds(offlineStream.circulatingBufferIds.begin(),
4093 offlineStream.circulatingBufferIds.end());
4094 if (!verifyBufferIds(id, bufIds)) {
4095 ALOGE("%s: stream ID %d buffer cache records mismatch!", __FUNCTION__, id);
4096 return UNKNOWN_ERROR;
4097 }
4098 }
4099
4100 // Move buffer records
4101 bufferRecords->takeBufferCaches(mBufferRecords, streams);
4102 bufferRecords->takeInflightBufferMap(mBufferRecords);
4103 bufferRecords->takeRequestedBufferMap(mBufferRecords);
4104 return ret;
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004105}
4106
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07004107void Camera3Device::HalInterface::getInflightBufferKeys(
4108 std::vector<std::pair<int32_t, int32_t>>* out) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004109 mBufferRecords.getInflightBufferKeys(out);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07004110 return;
4111}
4112
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08004113void Camera3Device::HalInterface::getInflightRequestBufferKeys(
4114 std::vector<uint64_t>* out) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004115 mBufferRecords.getInflightRequestBufferKeys(out);
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08004116 return;
4117}
4118
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004119bool Camera3Device::HalInterface::verifyBufferIds(
4120 int32_t streamId, std::vector<uint64_t>& bufIds) {
4121 return mBufferRecords.verifyBufferIds(streamId, bufIds);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004122}
4123
4124status_t Camera3Device::HalInterface::popInflightBuffer(
Yin-Chia Yehf4650602017-01-10 13:13:39 -08004125 int32_t frameNumber, int32_t streamId,
4126 /*out*/ buffer_handle_t **buffer) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004127 return mBufferRecords.popInflightBuffer(frameNumber, streamId, buffer);
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07004128}
4129
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004130status_t Camera3Device::HalInterface::pushInflightRequestBuffer(
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08004131 uint64_t bufferId, buffer_handle_t* buf, int32_t streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004132 return mBufferRecords.pushInflightRequestBuffer(bufferId, buf, streamId);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004133}
4134
4135// Find and pop a buffer_handle_t based on bufferId
4136status_t Camera3Device::HalInterface::popInflightRequestBuffer(
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08004137 uint64_t bufferId,
4138 /*out*/ buffer_handle_t** buffer,
4139 /*optional out*/ int32_t* streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004140 return mBufferRecords.popInflightRequestBuffer(bufferId, buffer, streamId);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004141}
4142
Yin-Chia Yeh77327052017-01-09 18:23:07 -08004143std::pair<bool, uint64_t> Camera3Device::HalInterface::getBufferId(
4144 const buffer_handle_t& buf, int streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004145 return mBufferRecords.getBufferId(buf, streamId);
Yin-Chia Yeh77327052017-01-09 18:23:07 -08004146}
4147
Shuzhen Wangcd5b1822021-09-07 11:52:48 -07004148uint64_t Camera3Device::HalInterface::removeOneBufferCache(int streamId,
4149 const native_handle_t* handle) {
4150 return mBufferRecords.removeOneBufferCache(streamId, handle);
4151}
4152
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07004153void Camera3Device::HalInterface::onBufferFreed(
4154 int streamId, const native_handle_t* handle) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004155 uint32_t bufferId = mBufferRecords.removeOneBufferCache(streamId, handle);
4156 std::lock_guard<std::mutex> lock(mFreedBuffersLock);
4157 if (bufferId != BUFFER_ID_NO_BUFFER) {
4158 mFreedBuffers.push_back(std::make_pair(streamId, bufferId));
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07004159 }
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07004160}
4161
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07004162void Camera3Device::HalInterface::onStreamReConfigured(int streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004163 std::vector<uint64_t> bufIds = mBufferRecords.clearBufferCaches(streamId);
4164 std::lock_guard<std::mutex> lock(mFreedBuffersLock);
4165 for (auto bufferId : bufIds) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07004166 mFreedBuffers.push_back(std::make_pair(streamId, bufferId));
4167 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07004168}
4169
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004170/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004171 * RequestThread inner class methods
4172 */
4173
4174Camera3Device::RequestThread::RequestThread(wp<Camera3Device> parent,
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004175 sp<StatusTracker> statusTracker,
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004176 sp<HalInterface> interface, const Vector<int32_t>& sessionParamKeys,
Eino-Ville Talvala1646c3c2021-07-29 13:48:40 -07004177 bool useHalBufManager,
4178 bool supportCameraMute) :
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004179 Thread(/*canCallJava*/false),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004180 mParent(parent),
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004181 mStatusTracker(statusTracker),
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004182 mInterface(interface),
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07004183 mListener(nullptr),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004184 mId(getId(parent)),
Shuzhen Wang316781a2020-08-18 18:11:01 -07004185 mFirstRepeating(false),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004186 mReconfigured(false),
4187 mDoPause(false),
4188 mPaused(true),
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004189 mNotifyPipelineDrain(false),
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004190 mFrameNumber(0),
Jianing Weicb0652e2014-03-12 18:29:36 -07004191 mLatestRequestId(NAME_NOT_FOUND),
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07004192 mCurrentAfTriggerId(0),
4193 mCurrentPreCaptureTriggerId(0),
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004194 mRotateAndCropOverride(ANDROID_SCALER_ROTATE_AND_CROP_NONE),
Emilian Peeve23f1d92021-09-20 14:56:01 -07004195 mComposerOutput(false),
Eino-Ville Talvala11afe4f2021-05-27 14:45:31 -07004196 mCameraMute(ANDROID_SENSOR_TEST_PATTERN_MODE_OFF),
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004197 mCameraMuteChanged(false),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004198 mRepeatingLastFrameNumber(
4199 hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES),
Shuzhen Wang686f6442017-06-20 16:16:04 -07004200 mPrepareVideoStream(false),
Emilian Peeva14b4dd2018-05-15 11:00:31 +01004201 mConstrainedMode(false),
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004202 mRequestLatency(kRequestLatencyBinSize),
4203 mSessionParamKeys(sessionParamKeys),
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004204 mLatestSessionParams(sessionParamKeys.size()),
Eino-Ville Talvala1646c3c2021-07-29 13:48:40 -07004205 mUseHalBufManager(useHalBufManager),
4206 mSupportCameraMute(supportCameraMute){
Yin-Chia Yeh87b3ec02019-06-03 10:44:39 -07004207 mStatusId = statusTracker->addComponent("RequestThread");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004208}
4209
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004210Camera3Device::RequestThread::~RequestThread() {}
4211
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004212void Camera3Device::RequestThread::setNotificationListener(
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004213 wp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004214 ATRACE_CALL();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004215 Mutex::Autolock l(mRequestLock);
4216 mListener = listener;
4217}
4218
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004219void Camera3Device::RequestThread::configurationComplete(bool isConstrainedHighSpeed,
Shuzhen Wang99080502021-03-07 21:08:20 -08004220 const CameraMetadata& sessionParams,
4221 const std::map<int32_t, std::set<String8>>& groupIdPhysicalCameraMap) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004222 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004223 Mutex::Autolock l(mRequestLock);
4224 mReconfigured = true;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004225 mLatestSessionParams = sessionParams;
Shuzhen Wang99080502021-03-07 21:08:20 -08004226 mGroupIdPhysicalCameraMap = groupIdPhysicalCameraMap;
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07004227 // Prepare video stream for high speed recording.
4228 mPrepareVideoStream = isConstrainedHighSpeed;
Emilian Peeva14b4dd2018-05-15 11:00:31 +01004229 mConstrainedMode = isConstrainedHighSpeed;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004230}
4231
Jianing Wei90e59c92014-03-12 18:29:36 -07004232status_t Camera3Device::RequestThread::queueRequestList(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004233 List<sp<CaptureRequest> > &requests,
4234 /*out*/
4235 int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004236 ATRACE_CALL();
Jianing Wei90e59c92014-03-12 18:29:36 -07004237 Mutex::Autolock l(mRequestLock);
4238 for (List<sp<CaptureRequest> >::iterator it = requests.begin(); it != requests.end();
4239 ++it) {
4240 mRequestQueue.push_back(*it);
4241 }
4242
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004243 if (lastFrameNumber != NULL) {
4244 *lastFrameNumber = mFrameNumber + mRequestQueue.size() - 1;
4245 ALOGV("%s: requestId %d, mFrameNumber %" PRId32 ", lastFrameNumber %" PRId64 ".",
4246 __FUNCTION__, (*(requests.begin()))->mResultExtras.requestId, mFrameNumber,
4247 *lastFrameNumber);
4248 }
Jianing Weicb0652e2014-03-12 18:29:36 -07004249
Jianing Wei90e59c92014-03-12 18:29:36 -07004250 unpauseForNewRequests();
4251
4252 return OK;
4253}
4254
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004255
4256status_t Camera3Device::RequestThread::queueTrigger(
4257 RequestTrigger trigger[],
4258 size_t count) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004259 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004260 Mutex::Autolock l(mTriggerMutex);
4261 status_t ret;
4262
4263 for (size_t i = 0; i < count; ++i) {
4264 ret = queueTriggerLocked(trigger[i]);
4265
4266 if (ret != OK) {
4267 return ret;
4268 }
4269 }
4270
4271 return OK;
4272}
4273
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004274const String8& Camera3Device::RequestThread::getId(const wp<Camera3Device> &device) {
4275 static String8 deadId("<DeadDevice>");
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004276 sp<Camera3Device> d = device.promote();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004277 if (d != nullptr) return d->mId;
4278 return deadId;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004279}
4280
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004281status_t Camera3Device::RequestThread::queueTriggerLocked(
4282 RequestTrigger trigger) {
4283
4284 uint32_t tag = trigger.metadataTag;
4285 ssize_t index = mTriggerMap.indexOfKey(tag);
4286
4287 switch (trigger.getTagType()) {
4288 case TYPE_BYTE:
4289 // fall-through
4290 case TYPE_INT32:
4291 break;
4292 default:
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004293 ALOGE("%s: Type not supported: 0x%x", __FUNCTION__,
4294 trigger.getTagType());
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004295 return INVALID_OPERATION;
4296 }
4297
4298 /**
4299 * Collect only the latest trigger, since we only have 1 field
4300 * in the request settings per trigger tag, and can't send more than 1
4301 * trigger per request.
4302 */
4303 if (index != NAME_NOT_FOUND) {
4304 mTriggerMap.editValueAt(index) = trigger;
4305 } else {
4306 mTriggerMap.add(tag, trigger);
4307 }
4308
4309 return OK;
4310}
4311
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004312status_t Camera3Device::RequestThread::setRepeatingRequests(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004313 const RequestList &requests,
4314 /*out*/
4315 int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004316 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004317 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004318 if (lastFrameNumber != NULL) {
4319 *lastFrameNumber = mRepeatingLastFrameNumber;
4320 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004321 mRepeatingRequests.clear();
Shuzhen Wang316781a2020-08-18 18:11:01 -07004322 mFirstRepeating = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004323 mRepeatingRequests.insert(mRepeatingRequests.begin(),
4324 requests.begin(), requests.end());
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004325
4326 unpauseForNewRequests();
4327
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004328 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004329 return OK;
4330}
4331
Chih-Hung Hsieh8b0b9712016-08-09 14:25:53 -07004332bool Camera3Device::RequestThread::isRepeatingRequestLocked(const sp<CaptureRequest>& requestIn) {
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07004333 if (mRepeatingRequests.empty()) {
4334 return false;
4335 }
4336 int32_t requestId = requestIn->mResultExtras.requestId;
4337 const RequestList &repeatRequests = mRepeatingRequests;
4338 // All repeating requests are guaranteed to have same id so only check first quest
4339 const sp<CaptureRequest> firstRequest = *repeatRequests.begin();
4340 return (firstRequest->mResultExtras.requestId == requestId);
4341}
4342
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004343status_t Camera3Device::RequestThread::clearRepeatingRequests(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004344 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004345 Mutex::Autolock l(mRequestLock);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004346 return clearRepeatingRequestsLocked(lastFrameNumber);
4347
4348}
4349
4350status_t Camera3Device::RequestThread::clearRepeatingRequestsLocked(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004351 mRepeatingRequests.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004352 if (lastFrameNumber != NULL) {
4353 *lastFrameNumber = mRepeatingLastFrameNumber;
4354 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004355 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004356 return OK;
4357}
4358
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004359status_t Camera3Device::RequestThread::clear(
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004360 /*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004361 ATRACE_CALL();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004362 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004363 ALOGV("RequestThread::%s:", __FUNCTION__);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004364
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004365 mRepeatingRequests.clear();
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07004366
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004367 // Send errors for all requests pending in the request queue, including
4368 // pending repeating requests
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004369 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004370 if (listener != NULL) {
4371 for (RequestList::iterator it = mRequestQueue.begin();
4372 it != mRequestQueue.end(); ++it) {
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004373 // Abort the input buffers for reprocess requests.
4374 if ((*it)->mInputStream != NULL) {
Emilian Peevf4816702020-04-03 15:44:51 -07004375 camera_stream_buffer_t inputBuffer;
Shuzhen Wang83bff122020-11-20 15:51:39 -08004376 camera3::Size inputBufferSize;
Eino-Ville Talvalaba435252017-06-21 16:07:25 -07004377 status_t res = (*it)->mInputStream->getInputBuffer(&inputBuffer,
Shuzhen Wang83bff122020-11-20 15:51:39 -08004378 &inputBufferSize, /*respectHalLimit*/ false);
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004379 if (res != OK) {
4380 ALOGW("%s: %d: couldn't get input buffer while clearing the request "
4381 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
4382 } else {
Emilian Peevf4816702020-04-03 15:44:51 -07004383 inputBuffer.status = CAMERA_BUFFER_STATUS_ERROR;
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004384 res = (*it)->mInputStream->returnInputBuffer(inputBuffer);
4385 if (res != OK) {
4386 ALOGE("%s: %d: couldn't return input buffer while clearing the request "
4387 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
4388 }
4389 }
4390 }
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004391 // Set the frame number this request would have had, if it
4392 // had been submitted; this frame number will not be reused.
4393 // The requestId and burstId fields were set when the request was
4394 // submitted originally (in convertMetadataListToRequestListLocked)
4395 (*it)->mResultExtras.frameNumber = mFrameNumber++;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004396 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004397 (*it)->mResultExtras);
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07004398 }
4399 }
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004400 mRequestQueue.clear();
Jinguang Dongb26e7a02016-11-14 16:04:02 +08004401
4402 Mutex::Autolock al(mTriggerMutex);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004403 mTriggerMap.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004404 if (lastFrameNumber != NULL) {
4405 *lastFrameNumber = mRepeatingLastFrameNumber;
4406 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004407 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Emilian Peev8dae54c2019-12-02 15:17:17 -08004408 mRequestSignal.signal();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004409 return OK;
4410}
4411
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004412status_t Camera3Device::RequestThread::flush() {
4413 ATRACE_CALL();
4414 Mutex::Autolock l(mFlushLock);
4415
Emilian Peev08dd2452017-04-06 16:55:14 +01004416 return mInterface->flush();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004417}
4418
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004419void Camera3Device::RequestThread::setPaused(bool paused) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004420 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004421 Mutex::Autolock l(mPauseLock);
4422 mDoPause = paused;
4423 mDoPauseSignal.signal();
4424}
4425
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004426status_t Camera3Device::RequestThread::waitUntilRequestProcessed(
4427 int32_t requestId, nsecs_t timeout) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004428 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004429 Mutex::Autolock l(mLatestRequestMutex);
4430 status_t res;
4431 while (mLatestRequestId != requestId) {
4432 nsecs_t startTime = systemTime();
4433
4434 res = mLatestRequestSignal.waitRelative(mLatestRequestMutex, timeout);
4435 if (res != OK) return res;
4436
4437 timeout -= (systemTime() - startTime);
4438 }
4439
4440 return OK;
4441}
4442
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004443void Camera3Device::RequestThread::requestExit() {
4444 // Call parent to set up shutdown
4445 Thread::requestExit();
4446 // The exit from any possible waits
4447 mDoPauseSignal.signal();
4448 mRequestSignal.signal();
Shuzhen Wang686f6442017-06-20 16:16:04 -07004449
4450 mRequestLatency.log("ProcessCaptureRequest latency histogram");
4451 mRequestLatency.reset();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004452}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004453
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004454void Camera3Device::RequestThread::checkAndStopRepeatingRequest() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004455 ATRACE_CALL();
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07004456 bool surfaceAbandoned = false;
4457 int64_t lastFrameNumber = 0;
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004458 sp<NotificationListener> listener;
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07004459 {
4460 Mutex::Autolock l(mRequestLock);
4461 // Check all streams needed by repeating requests are still valid. Otherwise, stop
4462 // repeating requests.
4463 for (const auto& request : mRepeatingRequests) {
4464 for (const auto& s : request->mOutputStreams) {
4465 if (s->isAbandoned()) {
4466 surfaceAbandoned = true;
4467 clearRepeatingRequestsLocked(&lastFrameNumber);
4468 break;
4469 }
4470 }
4471 if (surfaceAbandoned) {
4472 break;
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004473 }
4474 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004475 listener = mListener.promote();
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004476 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004477
4478 if (listener != NULL && surfaceAbandoned) {
4479 listener->notifyRepeatingRequestError(lastFrameNumber);
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07004480 }
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004481}
4482
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004483bool Camera3Device::RequestThread::sendRequestsBatch() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004484 ATRACE_CALL();
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004485 status_t res;
4486 size_t batchSize = mNextRequests.size();
Emilian Peevf4816702020-04-03 15:44:51 -07004487 std::vector<camera_capture_request_t*> requests(batchSize);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004488 uint32_t numRequestProcessed = 0;
4489 for (size_t i = 0; i < batchSize; i++) {
4490 requests[i] = &mNextRequests.editItemAt(i).halRequest;
Yin-Chia Yeh885691c2018-05-01 15:54:24 -07004491 ATRACE_ASYNC_BEGIN("frame capture", mNextRequests[i].halRequest.frame_number);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004492 }
4493
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004494 res = mInterface->processBatchCaptureRequests(requests, &numRequestProcessed);
4495
4496 bool triggerRemoveFailed = false;
4497 NextRequest& triggerFailedRequest = mNextRequests.editItemAt(0);
4498 for (size_t i = 0; i < numRequestProcessed; i++) {
4499 NextRequest& nextRequest = mNextRequests.editItemAt(i);
4500 nextRequest.submitted = true;
4501
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004502 updateNextRequest(nextRequest);
Emilian Peevaebbe412018-01-15 13:53:24 +00004503
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004504 if (!triggerRemoveFailed) {
4505 // Remove any previously queued triggers (after unlock)
4506 status_t removeTriggerRes = removeTriggers(mPrevRequest);
4507 if (removeTriggerRes != OK) {
4508 triggerRemoveFailed = true;
4509 triggerFailedRequest = nextRequest;
4510 }
4511 }
4512 }
4513
4514 if (triggerRemoveFailed) {
4515 SET_ERR("RequestThread: Unable to remove triggers "
4516 "(capture request %d, HAL device: %s (%d)",
4517 triggerFailedRequest.halRequest.frame_number, strerror(-res), res);
4518 cleanUpFailedRequests(/*sendRequestError*/ false);
4519 return false;
4520 }
4521
4522 if (res != OK) {
4523 // Should only get a failure here for malformed requests or device-level
4524 // errors, so consider all errors fatal. Bad metadata failures should
4525 // come through notify.
4526 SET_ERR("RequestThread: Unable to submit capture request %d to HAL device: %s (%d)",
4527 mNextRequests[numRequestProcessed].halRequest.frame_number,
4528 strerror(-res), res);
4529 cleanUpFailedRequests(/*sendRequestError*/ false);
4530 return false;
4531 }
4532 return true;
4533}
4534
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07004535nsecs_t Camera3Device::RequestThread::calculateMaxExpectedDuration(const camera_metadata_t *request) {
4536 nsecs_t maxExpectedDuration = kDefaultExpectedDuration;
4537 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
4538 find_camera_metadata_ro_entry(request,
4539 ANDROID_CONTROL_AE_MODE,
4540 &e);
4541 if (e.count == 0) return maxExpectedDuration;
4542
4543 switch (e.data.u8[0]) {
4544 case ANDROID_CONTROL_AE_MODE_OFF:
4545 find_camera_metadata_ro_entry(request,
4546 ANDROID_SENSOR_EXPOSURE_TIME,
4547 &e);
4548 if (e.count > 0) {
4549 maxExpectedDuration = e.data.i64[0];
4550 }
4551 find_camera_metadata_ro_entry(request,
4552 ANDROID_SENSOR_FRAME_DURATION,
4553 &e);
4554 if (e.count > 0) {
4555 maxExpectedDuration = std::max(e.data.i64[0], maxExpectedDuration);
4556 }
4557 break;
4558 default:
4559 find_camera_metadata_ro_entry(request,
4560 ANDROID_CONTROL_AE_TARGET_FPS_RANGE,
4561 &e);
4562 if (e.count > 1) {
4563 maxExpectedDuration = 1e9 / e.data.u8[0];
4564 }
4565 break;
4566 }
4567
4568 return maxExpectedDuration;
4569}
4570
Emilian Peeva14b4dd2018-05-15 11:00:31 +01004571bool Camera3Device::RequestThread::skipHFRTargetFPSUpdate(int32_t tag,
4572 const camera_metadata_ro_entry_t& newEntry, const camera_metadata_entry_t& currentEntry) {
4573 if (mConstrainedMode && (ANDROID_CONTROL_AE_TARGET_FPS_RANGE == tag) &&
4574 (newEntry.count == currentEntry.count) && (currentEntry.count == 2) &&
4575 (currentEntry.data.i32[1] == newEntry.data.i32[1])) {
4576 return true;
4577 }
4578
4579 return false;
4580}
4581
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004582void Camera3Device::RequestThread::updateNextRequest(NextRequest& nextRequest) {
4583 // Update the latest request sent to HAL
Shuzhen Wang83bff122020-11-20 15:51:39 -08004584 camera_capture_request_t& halRequest = nextRequest.halRequest;
4585 if (halRequest.settings != NULL) { // Don't update if they were unchanged
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004586 Mutex::Autolock al(mLatestRequestMutex);
4587
Shuzhen Wang83bff122020-11-20 15:51:39 -08004588 camera_metadata_t* cloned = clone_camera_metadata(halRequest.settings);
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004589 mLatestRequest.acquire(cloned);
4590
4591 mLatestPhysicalRequest.clear();
Shuzhen Wang83bff122020-11-20 15:51:39 -08004592 for (uint32_t i = 0; i < halRequest.num_physcam_settings; i++) {
4593 cloned = clone_camera_metadata(halRequest.physcam_settings[i]);
4594 mLatestPhysicalRequest.emplace(halRequest.physcam_id[i],
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004595 CameraMetadata(cloned));
4596 }
4597
4598 sp<Camera3Device> parent = mParent.promote();
4599 if (parent != NULL) {
4600 parent->monitorMetadata(TagMonitor::REQUEST,
Shuzhen Wang83bff122020-11-20 15:51:39 -08004601 halRequest.frame_number,
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004602 0, mLatestRequest, mLatestPhysicalRequest);
4603 }
4604 }
4605
Shuzhen Wang83bff122020-11-20 15:51:39 -08004606 if (halRequest.settings != NULL) {
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004607 nextRequest.captureRequest->mSettingsList.begin()->metadata.unlock(
Shuzhen Wang83bff122020-11-20 15:51:39 -08004608 halRequest.settings);
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004609 }
4610
Shuzhen Wang83bff122020-11-20 15:51:39 -08004611 cleanupPhysicalSettings(nextRequest.captureRequest, &halRequest);
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004612}
4613
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004614bool Camera3Device::RequestThread::updateSessionParameters(const CameraMetadata& settings) {
4615 ATRACE_CALL();
4616 bool updatesDetected = false;
4617
Emilian Peev4ec17882019-01-24 17:16:58 -08004618 CameraMetadata updatedParams(mLatestSessionParams);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004619 for (auto tag : mSessionParamKeys) {
4620 camera_metadata_ro_entry entry = settings.find(tag);
Emilian Peev4ec17882019-01-24 17:16:58 -08004621 camera_metadata_entry lastEntry = updatedParams.find(tag);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004622
4623 if (entry.count > 0) {
4624 bool isDifferent = false;
4625 if (lastEntry.count > 0) {
4626 // Have a last value, compare to see if changed
4627 if (lastEntry.type == entry.type &&
4628 lastEntry.count == entry.count) {
4629 // Same type and count, compare values
4630 size_t bytesPerValue = camera_metadata_type_size[lastEntry.type];
4631 size_t entryBytes = bytesPerValue * lastEntry.count;
4632 int cmp = memcmp(entry.data.u8, lastEntry.data.u8, entryBytes);
4633 if (cmp != 0) {
4634 isDifferent = true;
4635 }
4636 } else {
4637 // Count or type has changed
4638 isDifferent = true;
4639 }
4640 } else {
4641 // No last entry, so always consider to be different
4642 isDifferent = true;
4643 }
4644
4645 if (isDifferent) {
4646 ALOGV("%s: Session parameter tag id %d changed", __FUNCTION__, tag);
Emilian Peeva14b4dd2018-05-15 11:00:31 +01004647 if (!skipHFRTargetFPSUpdate(tag, entry, lastEntry)) {
4648 updatesDetected = true;
4649 }
Emilian Peev4ec17882019-01-24 17:16:58 -08004650 updatedParams.update(entry);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004651 }
4652 } else if (lastEntry.count > 0) {
4653 // Value has been removed
4654 ALOGV("%s: Session parameter tag id %d removed", __FUNCTION__, tag);
Emilian Peev4ec17882019-01-24 17:16:58 -08004655 updatedParams.erase(tag);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004656 updatesDetected = true;
4657 }
4658 }
4659
Emilian Peev4ec17882019-01-24 17:16:58 -08004660 bool reconfigureRequired;
4661 if (updatesDetected) {
4662 reconfigureRequired = mInterface->isReconfigurationRequired(mLatestSessionParams,
4663 updatedParams);
4664 mLatestSessionParams = updatedParams;
4665 } else {
4666 reconfigureRequired = false;
4667 }
4668
4669 return reconfigureRequired;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004670}
4671
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004672bool Camera3Device::RequestThread::threadLoop() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004673 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004674 status_t res;
Jayant Chowdhary37eca242019-11-18 08:55:56 -08004675 // Any function called from threadLoop() must not hold mInterfaceLock since
4676 // it could lead to deadlocks (disconnect() -> hold mInterfaceMutex -> wait for request thread
4677 // to finish -> request thread waits on mInterfaceMutex) http://b/143513518
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004678
4679 // Handle paused state.
4680 if (waitIfPaused()) {
4681 return true;
4682 }
4683
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004684 // Wait for the next batch of requests.
4685 waitForNextRequestBatch();
4686 if (mNextRequests.size() == 0) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004687 return true;
4688 }
4689
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004690 // Get the latest request ID, if any
4691 int latestRequestId;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004692 camera_metadata_entry_t requestIdEntry = mNextRequests[mNextRequests.size() - 1].
Emilian Peevaebbe412018-01-15 13:53:24 +00004693 captureRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_ID);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004694 if (requestIdEntry.count > 0) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004695 latestRequestId = requestIdEntry.data.i32[0];
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004696 } else {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004697 ALOGW("%s: Did not have android.request.id set in the request.", __FUNCTION__);
4698 latestRequestId = NAME_NOT_FOUND;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004699 }
4700
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004701 // 'mNextRequests' will at this point contain either a set of HFR batched requests
4702 // or a single request from streaming or burst. In either case the first element
4703 // should contain the latest camera settings that we need to check for any session
4704 // parameter updates.
Emilian Peevaebbe412018-01-15 13:53:24 +00004705 if (updateSessionParameters(mNextRequests[0].captureRequest->mSettingsList.begin()->metadata)) {
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004706 res = OK;
4707
4708 //Input stream buffers are already acquired at this point so an input stream
4709 //will not be able to move to idle state unless we force it.
4710 if (mNextRequests[0].captureRequest->mInputStream != nullptr) {
4711 res = mNextRequests[0].captureRequest->mInputStream->forceToIdle();
4712 if (res != OK) {
4713 ALOGE("%s: Failed to force idle input stream: %d", __FUNCTION__, res);
4714 cleanUpFailedRequests(/*sendRequestError*/ false);
4715 return false;
4716 }
4717 }
4718
4719 if (res == OK) {
Emilian Peev3bead5f2020-05-28 17:29:08 -07004720 sp<Camera3Device> parent = mParent.promote();
4721 if (parent != nullptr) {
4722 mReconfigured |= parent->reconfigureCamera(mLatestSessionParams, mStatusId);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004723 }
Emilian Peev3bead5f2020-05-28 17:29:08 -07004724 setPaused(false);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004725
4726 if (mNextRequests[0].captureRequest->mInputStream != nullptr) {
4727 mNextRequests[0].captureRequest->mInputStream->restoreConfiguredState();
4728 if (res != OK) {
4729 ALOGE("%s: Failed to restore configured input stream: %d", __FUNCTION__, res);
4730 cleanUpFailedRequests(/*sendRequestError*/ false);
4731 return false;
4732 }
4733 }
4734 }
4735 }
4736
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004737 // Prepare a batch of HAL requests and output buffers.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004738 res = prepareHalRequests();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004739 if (res == TIMED_OUT) {
4740 // Not a fatal error if getting output buffers time out.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004741 cleanUpFailedRequests(/*sendRequestError*/ true);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004742 // Check if any stream is abandoned.
4743 checkAndStopRepeatingRequest();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004744 return true;
4745 } else if (res != OK) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004746 cleanUpFailedRequests(/*sendRequestError*/ false);
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004747 return false;
4748 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004749
Zhijun Hecc27e112013-10-03 16:12:43 -07004750 // Inform waitUntilRequestProcessed thread of a new request ID
4751 {
4752 Mutex::Autolock al(mLatestRequestMutex);
4753
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004754 mLatestRequestId = latestRequestId;
Zhijun Hecc27e112013-10-03 16:12:43 -07004755 mLatestRequestSignal.signal();
4756 }
4757
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004758 // Submit a batch of requests to HAL.
4759 // Use flush lock only when submitting multilple requests in a batch.
4760 // TODO: The problem with flush lock is flush() will be blocked by process_capture_request()
4761 // which may take a long time to finish so synchronizing flush() and
4762 // process_capture_request() defeats the purpose of cancelling requests ASAP with flush().
4763 // For now, only synchronize for high speed recording and we should figure something out for
4764 // removing the synchronization.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004765 bool useFlushLock = mNextRequests.size() > 1;
Eino-Ville Talvala17a61ad2013-06-03 16:53:32 -07004766
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004767 if (useFlushLock) {
4768 mFlushLock.lock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004769 }
4770
Zhijun Hef0645c12016-08-02 00:58:11 -07004771 ALOGVV("%s: %d: submitting %zu requests in a batch.", __FUNCTION__, __LINE__,
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004772 mNextRequests.size());
Igor Murashkin1e479c02013-09-06 16:55:14 -07004773
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08004774 sp<Camera3Device> parent = mParent.promote();
4775 if (parent != nullptr) {
4776 parent->mRequestBufferSM.onSubmittingRequest();
4777 }
4778
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004779 bool submitRequestSuccess = false;
Shuzhen Wang686f6442017-06-20 16:16:04 -07004780 nsecs_t tRequestStart = systemTime(SYSTEM_TIME_MONOTONIC);
Yin-Chia Yeh11648852019-05-16 10:42:54 -07004781 submitRequestSuccess = sendRequestsBatch();
4782
Shuzhen Wang686f6442017-06-20 16:16:04 -07004783 nsecs_t tRequestEnd = systemTime(SYSTEM_TIME_MONOTONIC);
4784 mRequestLatency.add(tRequestStart, tRequestEnd);
Igor Murashkin1e479c02013-09-06 16:55:14 -07004785
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004786 if (useFlushLock) {
4787 mFlushLock.unlock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004788 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004789
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004790 // Unset as current request
4791 {
4792 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004793 mNextRequests.clear();
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004794 }
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004795 mRequestSubmittedSignal.signal();
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004796
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004797 return submitRequestSuccess;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004798}
4799
Jayant Chowdhary65c9bf02021-09-03 16:44:16 +00004800status_t Camera3Device::removeFwkOnlyRegionKeys(CameraMetadata *request) {
4801 static const std::array<uint32_t, 4> kFwkOnlyRegionKeys = {ANDROID_CONTROL_AF_REGIONS_SET,
4802 ANDROID_CONTROL_AE_REGIONS_SET, ANDROID_CONTROL_AWB_REGIONS_SET,
4803 ANDROID_SCALER_CROP_REGION_SET};
4804 if (request == nullptr) {
4805 ALOGE("%s request metadata nullptr", __FUNCTION__);
4806 return BAD_VALUE;
4807 }
4808 status_t res = OK;
4809 for (const auto &key : kFwkOnlyRegionKeys) {
4810 if (request->exists(key)) {
4811 res = request->erase(key);
4812 if (res != OK) {
4813 return res;
4814 }
4815 }
4816 }
4817 return OK;
4818}
4819
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004820status_t Camera3Device::RequestThread::prepareHalRequests() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004821 ATRACE_CALL();
4822
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07004823 bool batchedRequest = mNextRequests[0].captureRequest->mBatchSize > 1;
Shuzhen Wang4a472662017-02-26 23:29:04 -08004824 for (size_t i = 0; i < mNextRequests.size(); i++) {
4825 auto& nextRequest = mNextRequests.editItemAt(i);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004826 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
Emilian Peevf4816702020-04-03 15:44:51 -07004827 camera_capture_request_t* halRequest = &nextRequest.halRequest;
4828 Vector<camera_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004829
4830 // Prepare a request to HAL
4831 halRequest->frame_number = captureRequest->mResultExtras.frameNumber;
4832
4833 // Insert any queued triggers (before metadata is locked)
4834 status_t res = insertTriggers(captureRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004835 if (res < 0) {
4836 SET_ERR("RequestThread: Unable to insert triggers "
4837 "(capture request %d, HAL device: %s (%d)",
4838 halRequest->frame_number, strerror(-res), res);
4839 return INVALID_OPERATION;
4840 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07004841
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004842 int triggerCount = res;
4843 bool triggersMixedIn = (triggerCount > 0 || mPrevTriggers > 0);
4844 mPrevTriggers = triggerCount;
4845
Emilian Peeve23f1d92021-09-20 14:56:01 -07004846 // Do not override rotate&crop for stream configurations that include
4847 // SurfaceViews(HW_COMPOSER) output. The display rotation there will be
4848 // compensated by NATIVE_WINDOW_TRANSFORM_INVERSE_DISPLAY
4849 bool rotateAndCropChanged = mComposerOutput ? false :
4850 overrideAutoRotateAndCrop(captureRequest);
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004851 bool testPatternChanged = overrideTestPattern(captureRequest);
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004852
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004853 // If the request is the same as last, or we had triggers now or last time or
4854 // changing overrides this time
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004855 bool newRequest =
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004856 (mPrevRequest != captureRequest || triggersMixedIn ||
4857 rotateAndCropChanged || testPatternChanged) &&
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07004858 // Request settings are all the same within one batch, so only treat the first
4859 // request in a batch as new
Zhijun He54c36822018-07-18 09:33:39 -07004860 !(batchedRequest && i > 0);
Emilian Peev00420d22018-02-05 21:33:13 +00004861 if (newRequest) {
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08004862 std::set<std::string> cameraIdsWithZoom;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004863 /**
4864 * HAL workaround:
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004865 * Insert a fake trigger ID if a trigger is set but no trigger ID is
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004866 */
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004867 res = addFakeTriggerIds(captureRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004868 if (res != OK) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004869 SET_ERR("RequestThread: Unable to insert fake trigger IDs "
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004870 "(capture request %d, HAL device: %s (%d)",
4871 halRequest->frame_number, strerror(-res), res);
4872 return INVALID_OPERATION;
4873 }
4874
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07004875 {
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07004876 sp<Camera3Device> parent = mParent.promote();
4877 if (parent != nullptr) {
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -07004878 List<PhysicalCameraSettings>::iterator it;
4879 for (it = captureRequest->mSettingsList.begin();
4880 it != captureRequest->mSettingsList.end(); it++) {
Jayant Chowdhary9255ce02021-07-15 11:18:17 -07004881 if (parent->mUHRCropAndMeteringRegionMappers.find(it->cameraId) ==
4882 parent->mUHRCropAndMeteringRegionMappers.end()) {
Jayant Chowdhary65c9bf02021-09-03 16:44:16 +00004883 if (removeFwkOnlyRegionKeys(&(it->metadata)) != OK) {
4884 SET_ERR("RequestThread: Unable to remove fwk-only keys from request"
4885 "%d: %s (%d)", halRequest->frame_number, strerror(-res),
4886 res);
4887 return INVALID_OPERATION;
4888 }
Jayant Chowdhary9255ce02021-07-15 11:18:17 -07004889 continue;
4890 }
4891
4892 if (!captureRequest->mUHRCropAndMeteringRegionsUpdated) {
4893 res = parent->mUHRCropAndMeteringRegionMappers[it->cameraId].
4894 updateCaptureRequest(&(it->metadata));
4895 if (res != OK) {
4896 SET_ERR("RequestThread: Unable to correct capture requests "
4897 "for scaler crop region and metering regions for request "
4898 "%d: %s (%d)", halRequest->frame_number, strerror(-res),
4899 res);
4900 return INVALID_OPERATION;
4901 }
4902 captureRequest->mUHRCropAndMeteringRegionsUpdated = true;
Jayant Chowdhary65c9bf02021-09-03 16:44:16 +00004903 if (removeFwkOnlyRegionKeys(&(it->metadata)) != OK) {
4904 SET_ERR("RequestThread: Unable to remove fwk-only keys from request"
4905 "%d: %s (%d)", halRequest->frame_number, strerror(-res),
4906 res);
4907 return INVALID_OPERATION;
4908 }
Jayant Chowdhary9255ce02021-07-15 11:18:17 -07004909 }
4910 }
4911
4912 // Correct metadata regions for distortion correction if enabled
4913 for (it = captureRequest->mSettingsList.begin();
4914 it != captureRequest->mSettingsList.end(); it++) {
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -07004915 if (parent->mDistortionMappers.find(it->cameraId) ==
4916 parent->mDistortionMappers.end()) {
4917 continue;
4918 }
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07004919
4920 if (!captureRequest->mDistortionCorrectionUpdated) {
4921 res = parent->mDistortionMappers[it->cameraId].correctCaptureRequest(
4922 &(it->metadata));
4923 if (res != OK) {
4924 SET_ERR("RequestThread: Unable to correct capture requests "
4925 "for lens distortion for request %d: %s (%d)",
4926 halRequest->frame_number, strerror(-res), res);
4927 return INVALID_OPERATION;
4928 }
4929 captureRequest->mDistortionCorrectionUpdated = true;
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -07004930 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07004931 }
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08004932
4933 for (it = captureRequest->mSettingsList.begin();
4934 it != captureRequest->mSettingsList.end(); it++) {
4935 if (parent->mZoomRatioMappers.find(it->cameraId) ==
4936 parent->mZoomRatioMappers.end()) {
4937 continue;
4938 }
4939
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07004940 if (!captureRequest->mZoomRatioIs1x) {
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08004941 cameraIdsWithZoom.insert(it->cameraId);
4942 }
4943
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07004944 if (!captureRequest->mZoomRatioUpdated) {
4945 res = parent->mZoomRatioMappers[it->cameraId].updateCaptureRequest(
4946 &(it->metadata));
4947 if (res != OK) {
4948 SET_ERR("RequestThread: Unable to correct capture requests "
4949 "for zoom ratio for request %d: %s (%d)",
4950 halRequest->frame_number, strerror(-res), res);
4951 return INVALID_OPERATION;
4952 }
4953 captureRequest->mZoomRatioUpdated = true;
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08004954 }
4955 }
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07004956 if (captureRequest->mRotateAndCropAuto &&
4957 !captureRequest->mRotationAndCropUpdated) {
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004958 for (it = captureRequest->mSettingsList.begin();
4959 it != captureRequest->mSettingsList.end(); it++) {
4960 auto mapper = parent->mRotateAndCropMappers.find(it->cameraId);
4961 if (mapper != parent->mRotateAndCropMappers.end()) {
4962 res = mapper->second.updateCaptureRequest(&(it->metadata));
4963 if (res != OK) {
4964 SET_ERR("RequestThread: Unable to correct capture requests "
4965 "for rotate-and-crop for request %d: %s (%d)",
4966 halRequest->frame_number, strerror(-res), res);
4967 return INVALID_OPERATION;
4968 }
4969 }
4970 }
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07004971 captureRequest->mRotationAndCropUpdated = true;
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004972 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07004973 }
4974 }
4975
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004976 /**
4977 * The request should be presorted so accesses in HAL
4978 * are O(logn). Sidenote, sorting a sorted metadata is nop.
4979 */
Emilian Peevaebbe412018-01-15 13:53:24 +00004980 captureRequest->mSettingsList.begin()->metadata.sort();
4981 halRequest->settings = captureRequest->mSettingsList.begin()->metadata.getAndLock();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004982 mPrevRequest = captureRequest;
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08004983 mPrevCameraIdsWithZoom = cameraIdsWithZoom;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004984 ALOGVV("%s: Request settings are NEW", __FUNCTION__);
4985
4986 IF_ALOGV() {
4987 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
4988 find_camera_metadata_ro_entry(
4989 halRequest->settings,
4990 ANDROID_CONTROL_AF_TRIGGER,
4991 &e
4992 );
4993 if (e.count > 0) {
4994 ALOGV("%s: Request (frame num %d) had AF trigger 0x%x",
4995 __FUNCTION__,
4996 halRequest->frame_number,
4997 e.data.u8[0]);
4998 }
4999 }
5000 } else {
5001 // leave request.settings NULL to indicate 'reuse latest given'
5002 ALOGVV("%s: Request settings are REUSED",
5003 __FUNCTION__);
5004 }
5005
Emilian Peevaebbe412018-01-15 13:53:24 +00005006 if (captureRequest->mSettingsList.size() > 1) {
5007 halRequest->num_physcam_settings = captureRequest->mSettingsList.size() - 1;
5008 halRequest->physcam_id = new const char* [halRequest->num_physcam_settings];
Emilian Peev00420d22018-02-05 21:33:13 +00005009 if (newRequest) {
5010 halRequest->physcam_settings =
5011 new const camera_metadata* [halRequest->num_physcam_settings];
5012 } else {
5013 halRequest->physcam_settings = nullptr;
5014 }
Emilian Peevaebbe412018-01-15 13:53:24 +00005015 auto it = ++captureRequest->mSettingsList.begin();
5016 size_t i = 0;
5017 for (; it != captureRequest->mSettingsList.end(); it++, i++) {
5018 halRequest->physcam_id[i] = it->cameraId.c_str();
Emilian Peev00420d22018-02-05 21:33:13 +00005019 if (newRequest) {
5020 it->metadata.sort();
5021 halRequest->physcam_settings[i] = it->metadata.getAndLock();
5022 }
Emilian Peevaebbe412018-01-15 13:53:24 +00005023 }
5024 }
5025
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005026 uint32_t totalNumBuffers = 0;
5027
5028 // Fill in buffers
5029 if (captureRequest->mInputStream != NULL) {
5030 halRequest->input_buffer = &captureRequest->mInputBuffer;
Shuzhen Wang83bff122020-11-20 15:51:39 -08005031
5032 halRequest->input_width = captureRequest->mInputBufferSize.width;
5033 halRequest->input_height = captureRequest->mInputBufferSize.height;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005034 totalNumBuffers += 1;
5035 } else {
5036 halRequest->input_buffer = NULL;
5037 }
5038
Emilian Peevf4816702020-04-03 15:44:51 -07005039 outputBuffers->insertAt(camera_stream_buffer_t(), 0,
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005040 captureRequest->mOutputStreams.size());
5041 halRequest->output_buffers = outputBuffers->array();
Shuzhen Wang99080502021-03-07 21:08:20 -08005042 std::set<std::set<String8>> requestedPhysicalCameras;
Yin-Chia Yehb3a80b12018-09-04 12:13:05 -07005043
5044 sp<Camera3Device> parent = mParent.promote();
5045 if (parent == NULL) {
5046 // Should not happen, and nowhere to send errors to, so just log it
5047 CLOGE("RequestThread: Parent is gone");
5048 return INVALID_OPERATION;
5049 }
5050 nsecs_t waitDuration = kBaseGetBufferWait + parent->getExpectedInFlightDuration();
5051
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005052 SurfaceMap uniqueSurfaceIdMap;
Shuzhen Wang4a472662017-02-26 23:29:04 -08005053 for (size_t j = 0; j < captureRequest->mOutputStreams.size(); j++) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005054 sp<Camera3OutputStreamInterface> outputStream =
5055 captureRequest->mOutputStreams.editItemAt(j);
5056 int streamId = outputStream->getId();
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07005057
5058 // Prepare video buffers for high speed recording on the first video request.
5059 if (mPrepareVideoStream && outputStream->isVideoStream()) {
5060 // Only try to prepare video stream on the first video request.
5061 mPrepareVideoStream = false;
5062
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07005063 res = outputStream->startPrepare(Camera3StreamInterface::ALLOCATE_PIPELINE_MAX,
5064 false /*blockRequest*/);
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07005065 while (res == NOT_ENOUGH_DATA) {
5066 res = outputStream->prepareNextBuffer();
5067 }
5068 if (res != OK) {
5069 ALOGW("%s: Preparing video buffers for high speed failed: %s (%d)",
5070 __FUNCTION__, strerror(-res), res);
5071 outputStream->cancelPrepare();
5072 }
5073 }
5074
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005075 std::vector<size_t> uniqueSurfaceIds;
5076 res = outputStream->getUniqueSurfaceIds(
5077 captureRequest->mOutputSurfaces[streamId],
5078 &uniqueSurfaceIds);
5079 // INVALID_OPERATION is normal output for streams not supporting surfaceIds
5080 if (res != OK && res != INVALID_OPERATION) {
5081 ALOGE("%s: failed to query stream %d unique surface IDs",
5082 __FUNCTION__, streamId);
5083 return res;
5084 }
5085 if (res == OK) {
5086 uniqueSurfaceIdMap.insert({streamId, std::move(uniqueSurfaceIds)});
5087 }
5088
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07005089 if (mUseHalBufManager) {
Yin-Chia Yeh110342b2018-11-19 11:47:46 -08005090 if (outputStream->isAbandoned()) {
Yin-Chia Yeha1b56c82019-03-27 15:50:39 -07005091 ALOGV("%s: stream %d is abandoned, skipping request", __FUNCTION__, streamId);
Yin-Chia Yeh110342b2018-11-19 11:47:46 -08005092 return TIMED_OUT;
5093 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07005094 // HAL will request buffer through requestStreamBuffer API
Emilian Peevf4816702020-04-03 15:44:51 -07005095 camera_stream_buffer_t& buffer = outputBuffers->editItemAt(j);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07005096 buffer.stream = outputStream->asHalStream();
5097 buffer.buffer = nullptr;
Emilian Peevf4816702020-04-03 15:44:51 -07005098 buffer.status = CAMERA_BUFFER_STATUS_OK;
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07005099 buffer.acquire_fence = -1;
5100 buffer.release_fence = -1;
Emilian Peevf0348ae2021-01-13 13:39:45 -08005101 // Mark the output stream as unpreparable to block clients from calling
5102 // 'prepare' after this request reaches CameraHal and before the respective
5103 // buffers are requested.
5104 outputStream->markUnpreparable();
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07005105 } else {
5106 res = outputStream->getBuffer(&outputBuffers->editItemAt(j),
5107 waitDuration,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005108 captureRequest->mOutputSurfaces[streamId]);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07005109 if (res != OK) {
5110 // Can't get output buffer from gralloc queue - this could be due to
5111 // abandoned queue or other consumer misbehavior, so not a fatal
5112 // error
Yin-Chia Yeha1b56c82019-03-27 15:50:39 -07005113 ALOGV("RequestThread: Can't get output buffer, skipping request:"
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07005114 " %s (%d)", strerror(-res), res);
5115
5116 return TIMED_OUT;
5117 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005118 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08005119
5120 {
5121 sp<Camera3Device> parent = mParent.promote();
5122 if (parent != nullptr) {
5123 const String8& streamCameraId = outputStream->getPhysicalCameraId();
5124 for (const auto& settings : captureRequest->mSettingsList) {
5125 if ((streamCameraId.isEmpty() &&
5126 parent->getId() == settings.cameraId.c_str()) ||
5127 streamCameraId == settings.cameraId.c_str()) {
5128 outputStream->fireBufferRequestForFrameNumber(
5129 captureRequest->mResultExtras.frameNumber,
5130 settings.metadata);
5131 }
5132 }
5133 }
5134 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07005135
Shuzhen Wang5c22c152017-12-31 17:12:25 -08005136 String8 physicalCameraId = outputStream->getPhysicalCameraId();
Shuzhen Wang99080502021-03-07 21:08:20 -08005137 int32_t streamGroupId = outputStream->getHalStreamGroupId();
5138 if (streamGroupId != -1 && mGroupIdPhysicalCameraMap.count(streamGroupId) == 1) {
5139 requestedPhysicalCameras.insert(mGroupIdPhysicalCameraMap[streamGroupId]);
5140 } else if (!physicalCameraId.isEmpty()) {
5141 requestedPhysicalCameras.insert(std::set<String8>({physicalCameraId}));
Shuzhen Wang5c22c152017-12-31 17:12:25 -08005142 }
5143 halRequest->num_output_buffers++;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005144 }
5145 totalNumBuffers += halRequest->num_output_buffers;
5146
5147 // Log request in the in-flight queue
Shuzhen Wang4a472662017-02-26 23:29:04 -08005148 // If this request list is for constrained high speed recording (not
5149 // preview), and the current request is not the last one in the batch,
5150 // do not send callback to the app.
5151 bool hasCallback = true;
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07005152 if (batchedRequest && i != mNextRequests.size()-1) {
Shuzhen Wang4a472662017-02-26 23:29:04 -08005153 hasCallback = false;
5154 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01005155 bool isStillCapture = false;
Shuzhen Wang26abaf42018-08-28 15:41:20 -07005156 bool isZslCapture = false;
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08005157 const camera_metadata_t* settings = halRequest->settings;
5158 bool shouldUnlockSettings = false;
5159 if (settings == nullptr) {
5160 shouldUnlockSettings = true;
5161 settings = captureRequest->mSettingsList.begin()->metadata.getAndLock();
5162 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01005163 if (!mNextRequests[0].captureRequest->mSettingsList.begin()->metadata.isEmpty()) {
5164 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08005165 find_camera_metadata_ro_entry(settings, ANDROID_CONTROL_CAPTURE_INTENT, &e);
Emilian Peev9dd21f42018-08-03 13:39:29 +01005166 if ((e.count > 0) && (e.data.u8[0] == ANDROID_CONTROL_CAPTURE_INTENT_STILL_CAPTURE)) {
5167 isStillCapture = true;
5168 ATRACE_ASYNC_BEGIN("still capture", mNextRequests[i].halRequest.frame_number);
5169 }
Shuzhen Wang26abaf42018-08-28 15:41:20 -07005170
Emilian Peevaf8416e2021-02-04 17:52:43 -08005171 e = camera_metadata_ro_entry_t();
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08005172 find_camera_metadata_ro_entry(settings, ANDROID_CONTROL_ENABLE_ZSL, &e);
Shuzhen Wang26abaf42018-08-28 15:41:20 -07005173 if ((e.count > 0) && (e.data.u8[0] == ANDROID_CONTROL_ENABLE_ZSL_TRUE)) {
5174 isZslCapture = true;
5175 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01005176 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005177 res = parent->registerInFlight(halRequest->frame_number,
5178 totalNumBuffers, captureRequest->mResultExtras,
5179 /*hasInput*/halRequest->input_buffer != NULL,
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07005180 hasCallback,
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08005181 calculateMaxExpectedDuration(settings),
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005182 requestedPhysicalCameras, isStillCapture, isZslCapture,
5183 captureRequest->mRotateAndCropAuto, mPrevCameraIdsWithZoom,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005184 (mUseHalBufManager) ? uniqueSurfaceIdMap :
Shuzhen Wang316781a2020-08-18 18:11:01 -07005185 SurfaceMap{}, captureRequest->mRequestTimeNs);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005186 ALOGVV("%s: registered in flight requestId = %" PRId32 ", frameNumber = %" PRId64
5187 ", burstId = %" PRId32 ".",
5188 __FUNCTION__,
5189 captureRequest->mResultExtras.requestId, captureRequest->mResultExtras.frameNumber,
5190 captureRequest->mResultExtras.burstId);
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08005191
5192 if (shouldUnlockSettings) {
5193 captureRequest->mSettingsList.begin()->metadata.unlock(settings);
5194 }
5195
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005196 if (res != OK) {
5197 SET_ERR("RequestThread: Unable to register new in-flight request:"
5198 " %s (%d)", strerror(-res), res);
5199 return INVALID_OPERATION;
5200 }
5201 }
5202
5203 return OK;
5204}
5205
Igor Murashkin1e479c02013-09-06 16:55:14 -07005206CameraMetadata Camera3Device::RequestThread::getLatestRequest() const {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005207 ATRACE_CALL();
Igor Murashkin1e479c02013-09-06 16:55:14 -07005208 Mutex::Autolock al(mLatestRequestMutex);
5209
5210 ALOGV("RequestThread::%s", __FUNCTION__);
5211
5212 return mLatestRequest;
5213}
5214
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005215bool Camera3Device::RequestThread::isStreamPending(
5216 sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005217 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005218 Mutex::Autolock l(mRequestLock);
5219
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005220 for (const auto& nextRequest : mNextRequests) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005221 if (!nextRequest.submitted) {
5222 for (const auto& s : nextRequest.captureRequest->mOutputStreams) {
5223 if (stream == s) return true;
5224 }
5225 if (stream == nextRequest.captureRequest->mInputStream) return true;
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07005226 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07005227 }
5228
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005229 for (const auto& request : mRequestQueue) {
5230 for (const auto& s : request->mOutputStreams) {
5231 if (stream == s) return true;
5232 }
5233 if (stream == request->mInputStream) return true;
5234 }
5235
5236 for (const auto& request : mRepeatingRequests) {
5237 for (const auto& s : request->mOutputStreams) {
5238 if (stream == s) return true;
5239 }
5240 if (stream == request->mInputStream) return true;
5241 }
5242
5243 return false;
5244}
Jianing Weicb0652e2014-03-12 18:29:36 -07005245
Emilian Peev40ead602017-09-26 15:46:36 +01005246bool Camera3Device::RequestThread::isOutputSurfacePending(int streamId, size_t surfaceId) {
5247 ATRACE_CALL();
5248 Mutex::Autolock l(mRequestLock);
5249
5250 for (const auto& nextRequest : mNextRequests) {
5251 for (const auto& s : nextRequest.captureRequest->mOutputSurfaces) {
5252 if (s.first == streamId) {
5253 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
5254 if (it != s.second.end()) {
5255 return true;
5256 }
5257 }
5258 }
5259 }
5260
5261 for (const auto& request : mRequestQueue) {
5262 for (const auto& s : request->mOutputSurfaces) {
5263 if (s.first == streamId) {
5264 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
5265 if (it != s.second.end()) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005266 return true;
Emilian Peev40ead602017-09-26 15:46:36 +01005267 }
5268 }
5269 }
5270 }
5271
5272 for (const auto& request : mRepeatingRequests) {
5273 for (const auto& s : request->mOutputSurfaces) {
5274 if (s.first == streamId) {
5275 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
5276 if (it != s.second.end()) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005277 return true;
Emilian Peev40ead602017-09-26 15:46:36 +01005278 }
5279 }
5280 }
5281 }
5282
5283 return false;
5284}
5285
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07005286void Camera3Device::RequestThread::signalPipelineDrain(const std::vector<int>& streamIds) {
5287 if (!mUseHalBufManager) {
5288 ALOGE("%s called for camera device not supporting HAL buffer management", __FUNCTION__);
5289 return;
5290 }
5291
5292 Mutex::Autolock pl(mPauseLock);
5293 if (mPaused) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005294 mInterface->signalPipelineDrain(streamIds);
5295 return;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07005296 }
5297 // If request thread is still busy, wait until paused then notify HAL
5298 mNotifyPipelineDrain = true;
5299 mStreamIdsToBeDrained = streamIds;
5300}
5301
Yin-Chia Yehe52b8fa2020-07-28 00:17:58 -07005302void Camera3Device::RequestThread::resetPipelineDrain() {
5303 Mutex::Autolock pl(mPauseLock);
5304 mNotifyPipelineDrain = false;
5305 mStreamIdsToBeDrained.clear();
5306}
5307
Emilian Peevc0fe54c2020-03-11 14:05:07 -07005308void Camera3Device::RequestThread::clearPreviousRequest() {
5309 Mutex::Autolock l(mRequestLock);
5310 mPrevRequest.clear();
5311}
5312
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005313status_t Camera3Device::RequestThread::switchToOffline(
5314 const std::vector<int32_t>& streamsToKeep,
5315 /*out*/hardware::camera::device::V3_6::CameraOfflineSessionInfo* offlineSessionInfo,
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005316 /*out*/sp<hardware::camera::device::V3_6::ICameraOfflineSession>* offlineSession,
5317 /*out*/camera3::BufferRecords* bufferRecords) {
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005318 Mutex::Autolock l(mRequestLock);
5319 clearRepeatingRequestsLocked(/*lastFrameNumber*/nullptr);
5320
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005321 // Wait until request thread is fully stopped
5322 // TBD: check if request thread is being paused by other APIs (shouldn't be)
5323
5324 // We could also check for mRepeatingRequests.empty(), but the API interface
5325 // is serialized by Camera3Device::mInterfaceLock so no one should be able to submit any
5326 // new requests during the call; hence skip that check.
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005327 bool queueEmpty = mNextRequests.empty() && mRequestQueue.empty();
5328 while (!queueEmpty) {
5329 status_t res = mRequestSubmittedSignal.waitRelative(mRequestLock, kRequestSubmitTimeout);
5330 if (res == TIMED_OUT) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005331 ALOGE("%s: request thread failed to submit one request within timeout!", __FUNCTION__);
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005332 return res;
5333 } else if (res != OK) {
5334 ALOGE("%s: request thread failed to submit a request: %s (%d)!",
5335 __FUNCTION__, strerror(-res), res);
5336 return res;
5337 }
5338 queueEmpty = mNextRequests.empty() && mRequestQueue.empty();
5339 }
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005340
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005341 return mInterface->switchToOffline(
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005342 streamsToKeep, offlineSessionInfo, offlineSession, bufferRecords);
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005343}
5344
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005345status_t Camera3Device::RequestThread::setRotateAndCropAutoBehavior(
5346 camera_metadata_enum_android_scaler_rotate_and_crop_t rotateAndCropValue) {
5347 ATRACE_CALL();
5348 Mutex::Autolock l(mTriggerMutex);
5349 if (rotateAndCropValue == ANDROID_SCALER_ROTATE_AND_CROP_AUTO) {
5350 return BAD_VALUE;
5351 }
5352 mRotateAndCropOverride = rotateAndCropValue;
5353 return OK;
5354}
5355
Emilian Peeve23f1d92021-09-20 14:56:01 -07005356status_t Camera3Device::RequestThread::setComposerSurface(bool composerSurfacePresent) {
5357 ATRACE_CALL();
5358 Mutex::Autolock l(mTriggerMutex);
5359 mComposerOutput = composerSurfacePresent;
5360 return OK;
5361}
5362
Eino-Ville Talvala11afe4f2021-05-27 14:45:31 -07005363status_t Camera3Device::RequestThread::setCameraMute(int32_t muteMode) {
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005364 ATRACE_CALL();
5365 Mutex::Autolock l(mTriggerMutex);
Eino-Ville Talvala11afe4f2021-05-27 14:45:31 -07005366 if (muteMode != mCameraMute) {
5367 mCameraMute = muteMode;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005368 mCameraMuteChanged = true;
5369 }
5370 return OK;
5371}
5372
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07005373nsecs_t Camera3Device::getExpectedInFlightDuration() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005374 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005375 std::lock_guard<std::mutex> l(mInFlightLock);
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07005376 return mExpectedInflightDuration > kMinInflightDuration ?
5377 mExpectedInflightDuration : kMinInflightDuration;
5378}
5379
Emilian Peevaebbe412018-01-15 13:53:24 +00005380void Camera3Device::RequestThread::cleanupPhysicalSettings(sp<CaptureRequest> request,
Emilian Peevf4816702020-04-03 15:44:51 -07005381 camera_capture_request_t *halRequest) {
Emilian Peevaebbe412018-01-15 13:53:24 +00005382 if ((request == nullptr) || (halRequest == nullptr)) {
5383 ALOGE("%s: Invalid request!", __FUNCTION__);
5384 return;
5385 }
5386
5387 if (halRequest->num_physcam_settings > 0) {
5388 if (halRequest->physcam_id != nullptr) {
5389 delete [] halRequest->physcam_id;
5390 halRequest->physcam_id = nullptr;
5391 }
5392 if (halRequest->physcam_settings != nullptr) {
5393 auto it = ++(request->mSettingsList.begin());
5394 size_t i = 0;
5395 for (; it != request->mSettingsList.end(); it++, i++) {
5396 it->metadata.unlock(halRequest->physcam_settings[i]);
5397 }
5398 delete [] halRequest->physcam_settings;
5399 halRequest->physcam_settings = nullptr;
5400 }
5401 }
5402}
5403
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005404void Camera3Device::RequestThread::cleanUpFailedRequests(bool sendRequestError) {
5405 if (mNextRequests.empty()) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005406 return;
5407 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005408
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005409 for (auto& nextRequest : mNextRequests) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005410 // Skip the ones that have been submitted successfully.
5411 if (nextRequest.submitted) {
5412 continue;
5413 }
5414
5415 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
Emilian Peevf4816702020-04-03 15:44:51 -07005416 camera_capture_request_t* halRequest = &nextRequest.halRequest;
5417 Vector<camera_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005418
5419 if (halRequest->settings != NULL) {
Emilian Peevaebbe412018-01-15 13:53:24 +00005420 captureRequest->mSettingsList.begin()->metadata.unlock(halRequest->settings);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005421 }
5422
Emilian Peevaebbe412018-01-15 13:53:24 +00005423 cleanupPhysicalSettings(captureRequest, halRequest);
5424
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005425 if (captureRequest->mInputStream != NULL) {
Emilian Peevf4816702020-04-03 15:44:51 -07005426 captureRequest->mInputBuffer.status = CAMERA_BUFFER_STATUS_ERROR;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005427 captureRequest->mInputStream->returnInputBuffer(captureRequest->mInputBuffer);
5428 }
5429
Yin-Chia Yeh21cb47b2019-01-18 15:08:17 -08005430 // No output buffer can be returned when using HAL buffer manager
5431 if (!mUseHalBufManager) {
5432 for (size_t i = 0; i < halRequest->num_output_buffers; i++) {
5433 //Buffers that failed processing could still have
5434 //valid acquire fence.
5435 int acquireFence = (*outputBuffers)[i].acquire_fence;
5436 if (0 <= acquireFence) {
5437 close(acquireFence);
5438 outputBuffers->editItemAt(i).acquire_fence = -1;
5439 }
Emilian Peevf4816702020-04-03 15:44:51 -07005440 outputBuffers->editItemAt(i).status = CAMERA_BUFFER_STATUS_ERROR;
Yin-Chia Yeh21cb47b2019-01-18 15:08:17 -08005441 captureRequest->mOutputStreams.editItemAt(i)->returnBuffer((*outputBuffers)[i], 0,
5442 /*timestampIncreasing*/true, std::vector<size_t> (),
5443 captureRequest->mResultExtras.frameNumber);
Emilian Peevc58cf4c2017-05-11 17:23:41 +01005444 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005445 }
5446
5447 if (sendRequestError) {
5448 Mutex::Autolock l(mRequestLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005449 sp<NotificationListener> listener = mListener.promote();
5450 if (listener != NULL) {
5451 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08005452 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005453 captureRequest->mResultExtras);
5454 }
5455 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07005456
5457 // Remove yet-to-be submitted inflight request from inflightMap
5458 {
5459 sp<Camera3Device> parent = mParent.promote();
5460 if (parent != NULL) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005461 std::lock_guard<std::mutex> l(parent->mInFlightLock);
Shuzhen Wangcadb3302016-11-04 14:17:56 -07005462 ssize_t idx = parent->mInFlightMap.indexOfKey(captureRequest->mResultExtras.frameNumber);
5463 if (idx >= 0) {
5464 ALOGV("%s: Remove inflight request from queue: frameNumber %" PRId64,
5465 __FUNCTION__, captureRequest->mResultExtras.frameNumber);
5466 parent->removeInFlightMapEntryLocked(idx);
5467 }
5468 }
5469 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005470 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07005471
5472 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005473 mNextRequests.clear();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005474}
5475
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005476void Camera3Device::RequestThread::waitForNextRequestBatch() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005477 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005478 // Optimized a bit for the simple steady-state case (single repeating
5479 // request), to avoid putting that request in the queue temporarily.
5480 Mutex::Autolock l(mRequestLock);
5481
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005482 assert(mNextRequests.empty());
5483
5484 NextRequest nextRequest;
5485 nextRequest.captureRequest = waitForNextRequestLocked();
5486 if (nextRequest.captureRequest == nullptr) {
5487 return;
5488 }
5489
Emilian Peevf4816702020-04-03 15:44:51 -07005490 nextRequest.halRequest = camera_capture_request_t();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005491 nextRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005492 mNextRequests.add(nextRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005493
5494 // Wait for additional requests
5495 const size_t batchSize = nextRequest.captureRequest->mBatchSize;
5496
5497 for (size_t i = 1; i < batchSize; i++) {
5498 NextRequest additionalRequest;
5499 additionalRequest.captureRequest = waitForNextRequestLocked();
5500 if (additionalRequest.captureRequest == nullptr) {
5501 break;
5502 }
5503
Emilian Peevf4816702020-04-03 15:44:51 -07005504 additionalRequest.halRequest = camera_capture_request_t();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005505 additionalRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005506 mNextRequests.add(additionalRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005507 }
5508
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005509 if (mNextRequests.size() < batchSize) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08005510 ALOGE("RequestThread: only get %zu out of %zu requests. Skipping requests.",
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005511 mNextRequests.size(), batchSize);
5512 cleanUpFailedRequests(/*sendRequestError*/true);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005513 }
5514
5515 return;
5516}
5517
5518sp<Camera3Device::CaptureRequest>
5519 Camera3Device::RequestThread::waitForNextRequestLocked() {
5520 status_t res;
5521 sp<CaptureRequest> nextRequest;
5522
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005523 while (mRequestQueue.empty()) {
5524 if (!mRepeatingRequests.empty()) {
5525 // Always atomically enqueue all requests in a repeating request
5526 // list. Guarantees a complete in-sequence set of captures to
5527 // application.
5528 const RequestList &requests = mRepeatingRequests;
Shuzhen Wang316781a2020-08-18 18:11:01 -07005529 if (mFirstRepeating) {
5530 mFirstRepeating = false;
5531 } else {
5532 for (auto& request : requests) {
5533 // For repeating requests, override timestamp request using
5534 // the time a request is inserted into the request queue,
5535 // because the original repeating request will have an old
5536 // fixed timestamp.
5537 request->mRequestTimeNs = systemTime();
5538 }
5539 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005540 RequestList::const_iterator firstRequest =
5541 requests.begin();
5542 nextRequest = *firstRequest;
5543 mRequestQueue.insert(mRequestQueue.end(),
5544 ++firstRequest,
5545 requests.end());
5546 // No need to wait any longer
Jianing Weicb0652e2014-03-12 18:29:36 -07005547
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005548 mRepeatingLastFrameNumber = mFrameNumber + requests.size() - 1;
Jianing Weicb0652e2014-03-12 18:29:36 -07005549
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005550 break;
5551 }
5552
5553 res = mRequestSignal.waitRelative(mRequestLock, kRequestTimeout);
5554
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005555 if ((mRequestQueue.empty() && mRepeatingRequests.empty()) ||
5556 exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005557 Mutex::Autolock pl(mPauseLock);
5558 if (mPaused == false) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005559 ALOGV("%s: RequestThread: Going idle", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005560 mPaused = true;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07005561 if (mNotifyPipelineDrain) {
5562 mInterface->signalPipelineDrain(mStreamIdsToBeDrained);
5563 mNotifyPipelineDrain = false;
5564 mStreamIdsToBeDrained.clear();
5565 }
Yin-Chia Yehc300a072019-02-13 14:56:57 -08005566 // Let the tracker know
5567 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5568 if (statusTracker != 0) {
5569 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
5570 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005571 sp<Camera3Device> parent = mParent.promote();
5572 if (parent != nullptr) {
5573 parent->mRequestBufferSM.onRequestThreadPaused();
5574 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005575 }
5576 // Stop waiting for now and let thread management happen
5577 return NULL;
5578 }
5579 }
5580
5581 if (nextRequest == NULL) {
5582 // Don't have a repeating request already in hand, so queue
5583 // must have an entry now.
5584 RequestList::iterator firstRequest =
5585 mRequestQueue.begin();
5586 nextRequest = *firstRequest;
5587 mRequestQueue.erase(firstRequest);
Shuzhen Wang9d066012016-09-30 11:30:20 -07005588 if (mRequestQueue.empty() && !nextRequest->mRepeating) {
5589 sp<NotificationListener> listener = mListener.promote();
5590 if (listener != NULL) {
5591 listener->notifyRequestQueueEmpty();
5592 }
5593 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005594 }
5595
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005596 // In case we've been unpaused by setPaused clearing mDoPause, need to
5597 // update internal pause state (capture/setRepeatingRequest unpause
5598 // directly).
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005599 Mutex::Autolock pl(mPauseLock);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005600 if (mPaused) {
5601 ALOGV("%s: RequestThread: Unpaused", __FUNCTION__);
5602 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5603 if (statusTracker != 0) {
5604 statusTracker->markComponentActive(mStatusId);
5605 }
5606 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005607 mPaused = false;
5608
5609 // Check if we've reconfigured since last time, and reset the preview
5610 // request if so. Can't use 'NULL request == repeat' across configure calls.
5611 if (mReconfigured) {
5612 mPrevRequest.clear();
5613 mReconfigured = false;
5614 }
5615
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005616 if (nextRequest != NULL) {
5617 nextRequest->mResultExtras.frameNumber = mFrameNumber++;
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07005618 nextRequest->mResultExtras.afTriggerId = mCurrentAfTriggerId;
5619 nextRequest->mResultExtras.precaptureTriggerId = mCurrentPreCaptureTriggerId;
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07005620
5621 // Since RequestThread::clear() removes buffers from the input stream,
5622 // get the right buffer here before unlocking mRequestLock
5623 if (nextRequest->mInputStream != NULL) {
Shuzhen Wang83bff122020-11-20 15:51:39 -08005624 res = nextRequest->mInputStream->getInputBuffer(&nextRequest->mInputBuffer,
5625 &nextRequest->mInputBufferSize);
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07005626 if (res != OK) {
5627 // Can't get input buffer from gralloc queue - this could be due to
5628 // disconnected queue or other producer misbehavior, so not a fatal
5629 // error
5630 ALOGE("%s: Can't get input buffer, skipping request:"
5631 " %s (%d)", __FUNCTION__, strerror(-res), res);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005632
5633 sp<NotificationListener> listener = mListener.promote();
5634 if (listener != NULL) {
5635 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08005636 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07005637 nextRequest->mResultExtras);
5638 }
5639 return NULL;
5640 }
5641 }
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005642 }
Chien-Yu Chend196d612015-06-22 19:49:01 -07005643
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005644 return nextRequest;
5645}
5646
5647bool Camera3Device::RequestThread::waitIfPaused() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005648 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005649 status_t res;
5650 Mutex::Autolock l(mPauseLock);
5651 while (mDoPause) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005652 if (mPaused == false) {
5653 mPaused = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005654 ALOGV("%s: RequestThread: Paused", __FUNCTION__);
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07005655 if (mNotifyPipelineDrain) {
5656 mInterface->signalPipelineDrain(mStreamIdsToBeDrained);
5657 mNotifyPipelineDrain = false;
5658 mStreamIdsToBeDrained.clear();
5659 }
Yin-Chia Yehc300a072019-02-13 14:56:57 -08005660 // Let the tracker know
5661 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5662 if (statusTracker != 0) {
5663 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
5664 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005665 sp<Camera3Device> parent = mParent.promote();
5666 if (parent != nullptr) {
5667 parent->mRequestBufferSM.onRequestThreadPaused();
5668 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005669 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005670
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005671 res = mDoPauseSignal.waitRelative(mPauseLock, kRequestTimeout);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005672 if (res == TIMED_OUT || exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005673 return true;
5674 }
5675 }
5676 // We don't set mPaused to false here, because waitForNextRequest needs
5677 // to further manage the paused state in case of starvation.
5678 return false;
5679}
5680
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005681void Camera3Device::RequestThread::unpauseForNewRequests() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005682 ATRACE_CALL();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005683 // With work to do, mark thread as unpaused.
5684 // If paused by request (setPaused), don't resume, to avoid
5685 // extra signaling/waiting overhead to waitUntilPaused
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005686 mRequestSignal.signal();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005687 Mutex::Autolock p(mPauseLock);
5688 if (!mDoPause) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005689 ALOGV("%s: RequestThread: Going active", __FUNCTION__);
5690 if (mPaused) {
5691 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5692 if (statusTracker != 0) {
5693 statusTracker->markComponentActive(mStatusId);
5694 }
5695 }
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005696 mPaused = false;
5697 }
5698}
5699
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07005700void Camera3Device::RequestThread::setErrorState(const char *fmt, ...) {
5701 sp<Camera3Device> parent = mParent.promote();
5702 if (parent != NULL) {
5703 va_list args;
5704 va_start(args, fmt);
5705
5706 parent->setErrorStateV(fmt, args);
5707
5708 va_end(args);
5709 }
5710}
5711
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005712status_t Camera3Device::RequestThread::insertTriggers(
5713 const sp<CaptureRequest> &request) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005714 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005715 Mutex::Autolock al(mTriggerMutex);
5716
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07005717 sp<Camera3Device> parent = mParent.promote();
5718 if (parent == NULL) {
5719 CLOGE("RequestThread: Parent is gone");
5720 return DEAD_OBJECT;
5721 }
5722
Emilian Peevaebbe412018-01-15 13:53:24 +00005723 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005724 size_t count = mTriggerMap.size();
5725
5726 for (size_t i = 0; i < count; ++i) {
5727 RequestTrigger trigger = mTriggerMap.valueAt(i);
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005728 uint32_t tag = trigger.metadataTag;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07005729
5730 if (tag == ANDROID_CONTROL_AF_TRIGGER_ID || tag == ANDROID_CONTROL_AE_PRECAPTURE_ID) {
5731 bool isAeTrigger = (trigger.metadataTag == ANDROID_CONTROL_AE_PRECAPTURE_ID);
5732 uint32_t triggerId = static_cast<uint32_t>(trigger.entryValue);
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07005733 if (isAeTrigger) {
5734 request->mResultExtras.precaptureTriggerId = triggerId;
5735 mCurrentPreCaptureTriggerId = triggerId;
5736 } else {
5737 request->mResultExtras.afTriggerId = triggerId;
5738 mCurrentAfTriggerId = triggerId;
5739 }
Emilian Peev7e25e5e2017-04-07 15:48:49 +01005740 continue;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07005741 }
5742
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005743 camera_metadata_entry entry = metadata.find(tag);
5744
5745 if (entry.count > 0) {
5746 /**
5747 * Already has an entry for this trigger in the request.
5748 * Rewrite it with our requested trigger value.
5749 */
5750 RequestTrigger oldTrigger = trigger;
5751
5752 oldTrigger.entryValue = entry.data.u8[0];
5753
5754 mTriggerReplacedMap.add(tag, oldTrigger);
5755 } else {
5756 /**
5757 * More typical, no trigger entry, so we just add it
5758 */
5759 mTriggerRemovedMap.add(tag, trigger);
5760 }
5761
5762 status_t res;
5763
5764 switch (trigger.getTagType()) {
5765 case TYPE_BYTE: {
5766 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
5767 res = metadata.update(tag,
5768 &entryValue,
5769 /*count*/1);
5770 break;
5771 }
5772 case TYPE_INT32:
5773 res = metadata.update(tag,
5774 &trigger.entryValue,
5775 /*count*/1);
5776 break;
5777 default:
5778 ALOGE("%s: Type not supported: 0x%x",
5779 __FUNCTION__,
5780 trigger.getTagType());
5781 return INVALID_OPERATION;
5782 }
5783
5784 if (res != OK) {
5785 ALOGE("%s: Failed to update request metadata with trigger tag %s"
5786 ", value %d", __FUNCTION__, trigger.getTagName(),
5787 trigger.entryValue);
5788 return res;
5789 }
5790
5791 ALOGV("%s: Mixed in trigger %s, value %d", __FUNCTION__,
5792 trigger.getTagName(),
5793 trigger.entryValue);
5794 }
5795
5796 mTriggerMap.clear();
5797
5798 return count;
5799}
5800
5801status_t Camera3Device::RequestThread::removeTriggers(
5802 const sp<CaptureRequest> &request) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005803 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005804 Mutex::Autolock al(mTriggerMutex);
5805
Emilian Peevaebbe412018-01-15 13:53:24 +00005806 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005807
5808 /**
5809 * Replace all old entries with their old values.
5810 */
5811 for (size_t i = 0; i < mTriggerReplacedMap.size(); ++i) {
5812 RequestTrigger trigger = mTriggerReplacedMap.valueAt(i);
5813
5814 status_t res;
5815
5816 uint32_t tag = trigger.metadataTag;
5817 switch (trigger.getTagType()) {
5818 case TYPE_BYTE: {
5819 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
5820 res = metadata.update(tag,
5821 &entryValue,
5822 /*count*/1);
5823 break;
5824 }
5825 case TYPE_INT32:
5826 res = metadata.update(tag,
5827 &trigger.entryValue,
5828 /*count*/1);
5829 break;
5830 default:
5831 ALOGE("%s: Type not supported: 0x%x",
5832 __FUNCTION__,
5833 trigger.getTagType());
5834 return INVALID_OPERATION;
5835 }
5836
5837 if (res != OK) {
5838 ALOGE("%s: Failed to restore request metadata with trigger tag %s"
5839 ", trigger value %d", __FUNCTION__,
5840 trigger.getTagName(), trigger.entryValue);
5841 return res;
5842 }
5843 }
5844 mTriggerReplacedMap.clear();
5845
5846 /**
5847 * Remove all new entries.
5848 */
5849 for (size_t i = 0; i < mTriggerRemovedMap.size(); ++i) {
5850 RequestTrigger trigger = mTriggerRemovedMap.valueAt(i);
5851 status_t res = metadata.erase(trigger.metadataTag);
5852
5853 if (res != OK) {
5854 ALOGE("%s: Failed to erase metadata with trigger tag %s"
5855 ", trigger value %d", __FUNCTION__,
5856 trigger.getTagName(), trigger.entryValue);
5857 return res;
5858 }
5859 }
5860 mTriggerRemovedMap.clear();
5861
5862 return OK;
5863}
5864
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04005865status_t Camera3Device::RequestThread::addFakeTriggerIds(
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005866 const sp<CaptureRequest> &request) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08005867 // Trigger ID 0 had special meaning in the HAL2 spec, so avoid it here
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04005868 static const int32_t fakeTriggerId = 1;
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005869 status_t res;
5870
Emilian Peevaebbe412018-01-15 13:53:24 +00005871 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005872
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04005873 // If AF trigger is active, insert a fake AF trigger ID if none already
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005874 // exists
5875 camera_metadata_entry afTrigger = metadata.find(ANDROID_CONTROL_AF_TRIGGER);
5876 camera_metadata_entry afId = metadata.find(ANDROID_CONTROL_AF_TRIGGER_ID);
5877 if (afTrigger.count > 0 &&
5878 afTrigger.data.u8[0] != ANDROID_CONTROL_AF_TRIGGER_IDLE &&
5879 afId.count == 0) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04005880 res = metadata.update(ANDROID_CONTROL_AF_TRIGGER_ID, &fakeTriggerId, 1);
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005881 if (res != OK) return res;
5882 }
5883
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04005884 // If AE precapture trigger is active, insert a fake precapture trigger ID
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005885 // if none already exists
5886 camera_metadata_entry pcTrigger =
5887 metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER);
5888 camera_metadata_entry pcId = metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_ID);
5889 if (pcTrigger.count > 0 &&
5890 pcTrigger.data.u8[0] != ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_IDLE &&
5891 pcId.count == 0) {
5892 res = metadata.update(ANDROID_CONTROL_AE_PRECAPTURE_ID,
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04005893 &fakeTriggerId, 1);
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005894 if (res != OK) return res;
5895 }
5896
5897 return OK;
5898}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005899
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005900bool Camera3Device::RequestThread::overrideAutoRotateAndCrop(
5901 const sp<CaptureRequest> &request) {
5902 ATRACE_CALL();
5903
5904 if (request->mRotateAndCropAuto) {
5905 Mutex::Autolock l(mTriggerMutex);
5906 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
5907
5908 auto rotateAndCropEntry = metadata.find(ANDROID_SCALER_ROTATE_AND_CROP);
5909 if (rotateAndCropEntry.count > 0) {
5910 if (rotateAndCropEntry.data.u8[0] == mRotateAndCropOverride) {
5911 return false;
5912 } else {
5913 rotateAndCropEntry.data.u8[0] = mRotateAndCropOverride;
5914 return true;
5915 }
5916 } else {
5917 uint8_t rotateAndCrop_u8 = mRotateAndCropOverride;
5918 metadata.update(ANDROID_SCALER_ROTATE_AND_CROP,
5919 &rotateAndCrop_u8, 1);
5920 return true;
5921 }
5922 }
5923 return false;
5924}
5925
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005926bool Camera3Device::RequestThread::overrideTestPattern(
5927 const sp<CaptureRequest> &request) {
5928 ATRACE_CALL();
5929
Eino-Ville Talvala1646c3c2021-07-29 13:48:40 -07005930 if (!mSupportCameraMute) return false;
Eino-Ville Talvalac2459842021-07-22 16:36:36 -07005931
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005932 Mutex::Autolock l(mTriggerMutex);
5933
5934 bool changed = false;
5935
Shuzhen Wang911c6a32021-10-27 13:36:03 -07005936 // For a multi-camera, the physical cameras support the same set of
5937 // test pattern modes as the logical camera.
5938 for (auto& settings : request->mSettingsList) {
5939 CameraMetadata &metadata = settings.metadata;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005940
Shuzhen Wang911c6a32021-10-27 13:36:03 -07005941 int32_t testPatternMode = settings.mOriginalTestPatternMode;
5942 int32_t testPatternData[4] = {
5943 settings.mOriginalTestPatternData[0],
5944 settings.mOriginalTestPatternData[1],
5945 settings.mOriginalTestPatternData[2],
5946 settings.mOriginalTestPatternData[3]
5947 };
5948 if (mCameraMute != ANDROID_SENSOR_TEST_PATTERN_MODE_OFF) {
5949 testPatternMode = mCameraMute;
5950 testPatternData[0] = 0;
5951 testPatternData[1] = 0;
5952 testPatternData[2] = 0;
5953 testPatternData[3] = 0;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005954 }
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005955
Shuzhen Wang911c6a32021-10-27 13:36:03 -07005956 auto testPatternEntry = metadata.find(ANDROID_SENSOR_TEST_PATTERN_MODE);
5957 bool supportTestPatternModeKey = settings.mHasTestPatternModeTag;
5958 if (testPatternEntry.count > 0) {
5959 if (testPatternEntry.data.i32[0] != testPatternMode) {
5960 testPatternEntry.data.i32[0] = testPatternMode;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005961 changed = true;
5962 }
Shuzhen Wang911c6a32021-10-27 13:36:03 -07005963 } else if (supportTestPatternModeKey) {
5964 metadata.update(ANDROID_SENSOR_TEST_PATTERN_MODE,
5965 &testPatternMode, 1);
5966 changed = true;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005967 }
Shuzhen Wang911c6a32021-10-27 13:36:03 -07005968
5969 auto testPatternColor = metadata.find(ANDROID_SENSOR_TEST_PATTERN_DATA);
5970 bool supportTestPatternDataKey = settings.mHasTestPatternDataTag;
5971 if (testPatternColor.count >= 4) {
5972 for (size_t i = 0; i < 4; i++) {
5973 if (testPatternColor.data.i32[i] != testPatternData[i]) {
5974 testPatternColor.data.i32[i] = testPatternData[i];
5975 changed = true;
5976 }
5977 }
5978 } else if (supportTestPatternDataKey) {
5979 metadata.update(ANDROID_SENSOR_TEST_PATTERN_DATA,
5980 testPatternData, 4);
5981 changed = true;
5982 }
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005983 }
5984
5985 return changed;
5986}
5987
Cliff Wuc2ad9c82021-04-21 00:58:58 +08005988status_t Camera3Device::RequestThread::setHalInterface(
5989 sp<HalInterface> newHalInterface) {
5990 if (newHalInterface.get() == nullptr) {
5991 ALOGE("%s: The newHalInterface does not exist!", __FUNCTION__);
5992 return DEAD_OBJECT;
5993 }
5994
5995 mInterface = newHalInterface;
5996
5997 return OK;
5998}
5999
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006000/**
6001 * PreparerThread inner class methods
6002 */
6003
6004Camera3Device::PreparerThread::PreparerThread() :
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07006005 Thread(/*canCallJava*/false), mListener(nullptr),
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006006 mActive(false), mCancelNow(false), mCurrentMaxCount(0), mCurrentPrepareComplete(false) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006007}
6008
6009Camera3Device::PreparerThread::~PreparerThread() {
6010 Thread::requestExitAndWait();
6011 if (mCurrentStream != nullptr) {
6012 mCurrentStream->cancelPrepare();
6013 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
6014 mCurrentStream.clear();
6015 }
6016 clear();
6017}
6018
Ruben Brunkc78ac262015-08-13 17:58:46 -07006019status_t Camera3Device::PreparerThread::prepare(int maxCount, sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07006020 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006021 status_t res;
6022
6023 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006024 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006025
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07006026 res = stream->startPrepare(maxCount, true /*blockRequest*/);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006027 if (res == OK) {
6028 // No preparation needed, fire listener right off
6029 ALOGV("%s: Stream %d already prepared", __FUNCTION__, stream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006030 if (listener != NULL) {
6031 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006032 }
6033 return OK;
6034 } else if (res != NOT_ENOUGH_DATA) {
6035 return res;
6036 }
6037
6038 // Need to prepare, start up thread if necessary
6039 if (!mActive) {
6040 // mRunning will change to false before the thread fully shuts down, so wait to be sure it
6041 // isn't running
6042 Thread::requestExitAndWait();
6043 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
6044 if (res != OK) {
6045 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__, res, strerror(-res));
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006046 if (listener != NULL) {
6047 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006048 }
6049 return res;
6050 }
6051 mCancelNow = false;
6052 mActive = true;
6053 ALOGV("%s: Preparer stream started", __FUNCTION__);
6054 }
6055
6056 // queue up the work
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006057 mPendingStreams.emplace(maxCount, stream);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006058 ALOGV("%s: Stream %d queued for preparing", __FUNCTION__, stream->getId());
6059
6060 return OK;
6061}
6062
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006063void Camera3Device::PreparerThread::pause() {
6064 ATRACE_CALL();
6065
6066 Mutex::Autolock l(mLock);
6067
6068 std::unordered_map<int, sp<camera3::Camera3StreamInterface> > pendingStreams;
6069 pendingStreams.insert(mPendingStreams.begin(), mPendingStreams.end());
6070 sp<camera3::Camera3StreamInterface> currentStream = mCurrentStream;
6071 int currentMaxCount = mCurrentMaxCount;
6072 mPendingStreams.clear();
6073 mCancelNow = true;
6074 while (mActive) {
6075 auto res = mThreadActiveSignal.waitRelative(mLock, kActiveTimeout);
6076 if (res == TIMED_OUT) {
6077 ALOGE("%s: Timed out waiting on prepare thread!", __FUNCTION__);
6078 return;
6079 } else if (res != OK) {
6080 ALOGE("%s: Encountered an error: %d waiting on prepare thread!", __FUNCTION__, res);
6081 return;
6082 }
6083 }
6084
6085 //Check whether the prepare thread was able to complete the current
6086 //stream. In case work is still pending emplace it along with the rest
6087 //of the streams in the pending list.
6088 if (currentStream != nullptr) {
6089 if (!mCurrentPrepareComplete) {
6090 pendingStreams.emplace(currentMaxCount, currentStream);
6091 }
6092 }
6093
6094 mPendingStreams.insert(pendingStreams.begin(), pendingStreams.end());
6095 for (const auto& it : mPendingStreams) {
6096 it.second->cancelPrepare();
6097 }
6098}
6099
6100status_t Camera3Device::PreparerThread::resume() {
6101 ATRACE_CALL();
6102 status_t res;
6103
6104 Mutex::Autolock l(mLock);
6105 sp<NotificationListener> listener = mListener.promote();
6106
6107 if (mActive) {
6108 ALOGE("%s: Trying to resume an already active prepare thread!", __FUNCTION__);
6109 return NO_INIT;
6110 }
6111
6112 auto it = mPendingStreams.begin();
6113 for (; it != mPendingStreams.end();) {
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07006114 res = it->second->startPrepare(it->first, true /*blockRequest*/);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006115 if (res == OK) {
6116 if (listener != NULL) {
6117 listener->notifyPrepared(it->second->getId());
6118 }
6119 it = mPendingStreams.erase(it);
6120 } else if (res != NOT_ENOUGH_DATA) {
6121 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__,
6122 res, strerror(-res));
6123 it = mPendingStreams.erase(it);
6124 } else {
6125 it++;
6126 }
6127 }
6128
6129 if (mPendingStreams.empty()) {
6130 return OK;
6131 }
6132
6133 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
6134 if (res != OK) {
6135 ALOGE("%s: Unable to start preparer stream: %d (%s)",
6136 __FUNCTION__, res, strerror(-res));
6137 return res;
6138 }
6139 mCancelNow = false;
6140 mActive = true;
6141 ALOGV("%s: Preparer stream started", __FUNCTION__);
6142
6143 return OK;
6144}
6145
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006146status_t Camera3Device::PreparerThread::clear() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07006147 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006148 Mutex::Autolock l(mLock);
6149
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006150 for (const auto& it : mPendingStreams) {
6151 it.second->cancelPrepare();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006152 }
6153 mPendingStreams.clear();
6154 mCancelNow = true;
6155
6156 return OK;
6157}
6158
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006159void Camera3Device::PreparerThread::setNotificationListener(wp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07006160 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006161 Mutex::Autolock l(mLock);
6162 mListener = listener;
6163}
6164
6165bool Camera3Device::PreparerThread::threadLoop() {
6166 status_t res;
6167 {
6168 Mutex::Autolock l(mLock);
6169 if (mCurrentStream == nullptr) {
6170 // End thread if done with work
6171 if (mPendingStreams.empty()) {
6172 ALOGV("%s: Preparer stream out of work", __FUNCTION__);
6173 // threadLoop _must not_ re-acquire mLock after it sets mActive to false; would
6174 // cause deadlock with prepare()'s requestExitAndWait triggered by !mActive.
6175 mActive = false;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006176 mThreadActiveSignal.signal();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006177 return false;
6178 }
6179
6180 // Get next stream to prepare
6181 auto it = mPendingStreams.begin();
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006182 mCurrentStream = it->second;
6183 mCurrentMaxCount = it->first;
6184 mCurrentPrepareComplete = false;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006185 mPendingStreams.erase(it);
6186 ATRACE_ASYNC_BEGIN("stream prepare", mCurrentStream->getId());
6187 ALOGV("%s: Preparing stream %d", __FUNCTION__, mCurrentStream->getId());
6188 } else if (mCancelNow) {
6189 mCurrentStream->cancelPrepare();
6190 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
6191 ALOGV("%s: Cancelling stream %d prepare", __FUNCTION__, mCurrentStream->getId());
6192 mCurrentStream.clear();
6193 mCancelNow = false;
6194 return true;
6195 }
6196 }
6197
6198 res = mCurrentStream->prepareNextBuffer();
6199 if (res == NOT_ENOUGH_DATA) return true;
6200 if (res != OK) {
6201 // Something bad happened; try to recover by cancelling prepare and
6202 // signalling listener anyway
6203 ALOGE("%s: Stream %d returned error %d (%s) during prepare", __FUNCTION__,
6204 mCurrentStream->getId(), res, strerror(-res));
6205 mCurrentStream->cancelPrepare();
6206 }
6207
6208 // This stream has finished, notify listener
6209 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006210 sp<NotificationListener> listener = mListener.promote();
6211 if (listener != NULL) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006212 ALOGV("%s: Stream %d prepare done, signaling listener", __FUNCTION__,
6213 mCurrentStream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006214 listener->notifyPrepared(mCurrentStream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006215 }
6216
6217 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
6218 mCurrentStream.clear();
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006219 mCurrentPrepareComplete = true;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006220
6221 return true;
6222}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07006223
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006224status_t Camera3Device::RequestBufferStateMachine::initialize(
6225 sp<camera3::StatusTracker> statusTracker) {
6226 if (statusTracker == nullptr) {
6227 ALOGE("%s: statusTracker is null", __FUNCTION__);
6228 return BAD_VALUE;
6229 }
6230
6231 std::lock_guard<std::mutex> lock(mLock);
6232 mStatusTracker = statusTracker;
Yin-Chia Yeh87b3ec02019-06-03 10:44:39 -07006233 mRequestBufferStatusId = statusTracker->addComponent("BufferRequestSM");
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006234 return OK;
6235}
6236
6237bool Camera3Device::RequestBufferStateMachine::startRequestBuffer() {
6238 std::lock_guard<std::mutex> lock(mLock);
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08006239 if (mStatus == RB_STATUS_READY || mStatus == RB_STATUS_PENDING_STOP) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006240 mRequestBufferOngoing = true;
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08006241 notifyTrackerLocked(/*active*/true);
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006242 return true;
6243 }
6244 return false;
6245}
6246
6247void Camera3Device::RequestBufferStateMachine::endRequestBuffer() {
6248 std::lock_guard<std::mutex> lock(mLock);
6249 if (!mRequestBufferOngoing) {
6250 ALOGE("%s called without a successful startRequestBuffer call first!", __FUNCTION__);
6251 return;
6252 }
6253 mRequestBufferOngoing = false;
6254 if (mStatus == RB_STATUS_PENDING_STOP) {
6255 checkSwitchToStopLocked();
6256 }
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08006257 notifyTrackerLocked(/*active*/false);
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006258}
6259
6260void Camera3Device::RequestBufferStateMachine::onStreamsConfigured() {
6261 std::lock_guard<std::mutex> lock(mLock);
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006262 mSwitchedToOffline = false;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006263 mStatus = RB_STATUS_READY;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006264 return;
6265}
6266
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08006267void Camera3Device::RequestBufferStateMachine::onSubmittingRequest() {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006268 std::lock_guard<std::mutex> lock(mLock);
6269 mRequestThreadPaused = false;
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08006270 // inflight map register actually happens in prepareHalRequest now, but it is close enough
6271 // approximation.
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006272 mInflightMapEmpty = false;
6273 if (mStatus == RB_STATUS_STOPPED) {
6274 mStatus = RB_STATUS_READY;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006275 }
6276 return;
6277}
6278
6279void Camera3Device::RequestBufferStateMachine::onRequestThreadPaused() {
6280 std::lock_guard<std::mutex> lock(mLock);
6281 mRequestThreadPaused = true;
6282 if (mStatus == RB_STATUS_PENDING_STOP) {
6283 checkSwitchToStopLocked();
6284 }
6285 return;
6286}
6287
6288void Camera3Device::RequestBufferStateMachine::onInflightMapEmpty() {
6289 std::lock_guard<std::mutex> lock(mLock);
6290 mInflightMapEmpty = true;
6291 if (mStatus == RB_STATUS_PENDING_STOP) {
6292 checkSwitchToStopLocked();
6293 }
6294 return;
6295}
6296
6297void Camera3Device::RequestBufferStateMachine::onWaitUntilIdle() {
6298 std::lock_guard<std::mutex> lock(mLock);
6299 if (!checkSwitchToStopLocked()) {
6300 mStatus = RB_STATUS_PENDING_STOP;
6301 }
6302 return;
6303}
6304
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006305bool Camera3Device::RequestBufferStateMachine::onSwitchToOfflineSuccess() {
6306 std::lock_guard<std::mutex> lock(mLock);
6307 if (mRequestBufferOngoing) {
6308 ALOGE("%s: HAL must not be requesting buffer after HAL returns switchToOffline!",
6309 __FUNCTION__);
6310 return false;
6311 }
6312 mSwitchedToOffline = true;
6313 mInflightMapEmpty = true;
6314 mRequestThreadPaused = true;
6315 mStatus = RB_STATUS_STOPPED;
6316 return true;
6317}
6318
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006319void Camera3Device::RequestBufferStateMachine::notifyTrackerLocked(bool active) {
6320 sp<StatusTracker> statusTracker = mStatusTracker.promote();
6321 if (statusTracker != nullptr) {
6322 if (active) {
6323 statusTracker->markComponentActive(mRequestBufferStatusId);
6324 } else {
6325 statusTracker->markComponentIdle(mRequestBufferStatusId, Fence::NO_FENCE);
6326 }
6327 }
6328}
6329
6330bool Camera3Device::RequestBufferStateMachine::checkSwitchToStopLocked() {
6331 if (mInflightMapEmpty && mRequestThreadPaused && !mRequestBufferOngoing) {
6332 mStatus = RB_STATUS_STOPPED;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006333 return true;
6334 }
6335 return false;
6336}
6337
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006338bool Camera3Device::startRequestBuffer() {
6339 return mRequestBufferSM.startRequestBuffer();
6340}
Shuzhen Wang268a1362018-10-16 16:32:59 -07006341
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006342void Camera3Device::endRequestBuffer() {
6343 mRequestBufferSM.endRequestBuffer();
6344}
Shuzhen Wang268a1362018-10-16 16:32:59 -07006345
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006346nsecs_t Camera3Device::getWaitDuration() {
6347 return kBaseGetBufferWait + getExpectedInFlightDuration();
6348}
Shuzhen Wang268a1362018-10-16 16:32:59 -07006349
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006350void Camera3Device::getInflightBufferKeys(std::vector<std::pair<int32_t, int32_t>>* out) {
6351 mInterface->getInflightBufferKeys(out);
6352}
Shuzhen Wang268a1362018-10-16 16:32:59 -07006353
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006354void Camera3Device::getInflightRequestBufferKeys(std::vector<uint64_t>* out) {
6355 mInterface->getInflightRequestBufferKeys(out);
6356}
Shuzhen Wang268a1362018-10-16 16:32:59 -07006357
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006358std::vector<sp<Camera3StreamInterface>> Camera3Device::getAllStreams() {
6359 std::vector<sp<Camera3StreamInterface>> ret;
6360 bool hasInputStream = mInputStream != nullptr;
6361 ret.reserve(mOutputStreams.size() + mDeletedStreams.size() + ((hasInputStream) ? 1 : 0));
6362 if (hasInputStream) {
6363 ret.push_back(mInputStream);
Shuzhen Wang268a1362018-10-16 16:32:59 -07006364 }
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006365 for (size_t i = 0; i < mOutputStreams.size(); i++) {
6366 ret.push_back(mOutputStreams[i]);
6367 }
6368 for (size_t i = 0; i < mDeletedStreams.size(); i++) {
6369 ret.push_back(mDeletedStreams[i]);
6370 }
6371 return ret;
Shuzhen Wang268a1362018-10-16 16:32:59 -07006372}
6373
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006374status_t Camera3Device::switchToOffline(
6375 const std::vector<int32_t>& streamsToKeep,
6376 /*out*/ sp<CameraOfflineSessionBase>* session) {
6377 ATRACE_CALL();
6378 if (session == nullptr) {
6379 ALOGE("%s: session must not be null", __FUNCTION__);
6380 return BAD_VALUE;
6381 }
6382
6383 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006384
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006385 bool hasInputStream = mInputStream != nullptr;
6386 int32_t inputStreamId = hasInputStream ? mInputStream->getId() : -1;
6387 bool inputStreamSupportsOffline = hasInputStream ?
6388 mInputStream->getOfflineProcessingSupport() : false;
6389 auto outputStreamIds = mOutputStreams.getStreamIds();
6390 auto streamIds = outputStreamIds;
6391 if (hasInputStream) {
6392 streamIds.push_back(mInputStream->getId());
6393 }
6394
6395 // Check all streams in streamsToKeep supports offline mode
6396 for (auto id : streamsToKeep) {
6397 if (std::find(streamIds.begin(), streamIds.end(), id) == streamIds.end()) {
6398 ALOGE("%s: Unknown stream ID %d", __FUNCTION__, id);
6399 return BAD_VALUE;
6400 } else if (id == inputStreamId) {
6401 if (!inputStreamSupportsOffline) {
6402 ALOGE("%s: input stream %d cannot be switched to offline",
6403 __FUNCTION__, id);
6404 return BAD_VALUE;
6405 }
6406 } else {
6407 sp<camera3::Camera3OutputStreamInterface> stream = mOutputStreams.get(id);
6408 if (!stream->getOfflineProcessingSupport()) {
6409 ALOGE("%s: output stream %d cannot be switched to offline",
6410 __FUNCTION__, id);
6411 return BAD_VALUE;
6412 }
6413 }
6414 }
6415
6416 // TODO: block surface sharing and surface group streams until we can support them
6417
6418 // Stop repeating request, wait until all remaining requests are submitted, then call into
6419 // HAL switchToOffline
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006420 hardware::camera::device::V3_6::CameraOfflineSessionInfo offlineSessionInfo;
6421 sp<hardware::camera::device::V3_6::ICameraOfflineSession> offlineSession;
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006422 camera3::BufferRecords bufferRecords;
6423 status_t ret = mRequestThread->switchToOffline(
6424 streamsToKeep, &offlineSessionInfo, &offlineSession, &bufferRecords);
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006425
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006426 if (ret != OK) {
6427 SET_ERR("Switch to offline failed: %s (%d)", strerror(-ret), ret);
6428 return ret;
6429 }
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006430
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006431 bool succ = mRequestBufferSM.onSwitchToOfflineSuccess();
6432 if (!succ) {
6433 SET_ERR("HAL must not be calling requestStreamBuffers call");
6434 // TODO: block ALL callbacks from HAL till app configured new streams?
6435 return UNKNOWN_ERROR;
6436 }
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006437
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006438 // Verify offlineSessionInfo
6439 std::vector<int32_t> offlineStreamIds;
6440 offlineStreamIds.reserve(offlineSessionInfo.offlineStreams.size());
6441 for (auto offlineStream : offlineSessionInfo.offlineStreams) {
6442 // verify stream IDs
6443 int32_t id = offlineStream.id;
6444 if (std::find(streamIds.begin(), streamIds.end(), id) == streamIds.end()) {
6445 SET_ERR("stream ID %d not found!", id);
6446 return UNKNOWN_ERROR;
6447 }
6448
6449 // When not using HAL buf manager, only allow streams requested by app to be preserved
6450 if (!mUseHalBufManager) {
6451 if (std::find(streamsToKeep.begin(), streamsToKeep.end(), id) == streamsToKeep.end()) {
6452 SET_ERR("stream ID %d must not be switched to offline!", id);
6453 return UNKNOWN_ERROR;
6454 }
6455 }
6456
6457 offlineStreamIds.push_back(id);
6458 sp<Camera3StreamInterface> stream = (id == inputStreamId) ?
6459 static_cast<sp<Camera3StreamInterface>>(mInputStream) :
6460 static_cast<sp<Camera3StreamInterface>>(mOutputStreams.get(id));
6461 // Verify number of outstanding buffers
6462 if (stream->getOutstandingBuffersCount() != offlineStream.numOutstandingBuffers) {
6463 SET_ERR("Offline stream %d # of remaining buffer mismatch: (%zu,%d) (service/HAL)",
6464 id, stream->getOutstandingBuffersCount(), offlineStream.numOutstandingBuffers);
6465 return UNKNOWN_ERROR;
6466 }
6467 }
6468
6469 // Verify all streams to be deleted don't have any outstanding buffers
6470 if (hasInputStream && std::find(offlineStreamIds.begin(), offlineStreamIds.end(),
6471 inputStreamId) == offlineStreamIds.end()) {
6472 if (mInputStream->hasOutstandingBuffers()) {
6473 SET_ERR("Input stream %d still has %zu outstanding buffer!",
6474 inputStreamId, mInputStream->getOutstandingBuffersCount());
6475 return UNKNOWN_ERROR;
6476 }
6477 }
6478
6479 for (const auto& outStreamId : outputStreamIds) {
6480 if (std::find(offlineStreamIds.begin(), offlineStreamIds.end(),
6481 outStreamId) == offlineStreamIds.end()) {
6482 auto outStream = mOutputStreams.get(outStreamId);
6483 if (outStream->hasOutstandingBuffers()) {
6484 SET_ERR("Output stream %d still has %zu outstanding buffer!",
6485 outStreamId, outStream->getOutstandingBuffersCount());
6486 return UNKNOWN_ERROR;
6487 }
6488 }
6489 }
6490
6491 InFlightRequestMap offlineReqs;
6492 // Verify inflight requests and their pending buffers
6493 {
6494 std::lock_guard<std::mutex> l(mInFlightLock);
6495 for (auto offlineReq : offlineSessionInfo.offlineRequests) {
6496 int idx = mInFlightMap.indexOfKey(offlineReq.frameNumber);
6497 if (idx == NAME_NOT_FOUND) {
6498 SET_ERR("Offline request frame number %d not found!", offlineReq.frameNumber);
6499 return UNKNOWN_ERROR;
6500 }
6501
6502 const auto& inflightReq = mInFlightMap.valueAt(idx);
6503 // TODO: check specific stream IDs
6504 size_t numBuffersLeft = static_cast<size_t>(inflightReq.numBuffersLeft);
6505 if (numBuffersLeft != offlineReq.pendingStreams.size()) {
6506 SET_ERR("Offline request # of remaining buffer mismatch: (%d,%d) (service/HAL)",
6507 inflightReq.numBuffersLeft, offlineReq.pendingStreams.size());
6508 return UNKNOWN_ERROR;
6509 }
6510 offlineReqs.add(offlineReq.frameNumber, inflightReq);
6511 }
6512 }
6513
6514 // Create Camera3OfflineSession and transfer object ownership
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006515 // (streams, inflight requests, buffer caches)
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006516 camera3::StreamSet offlineStreamSet;
6517 sp<camera3::Camera3Stream> inputStream;
6518 for (auto offlineStream : offlineSessionInfo.offlineStreams) {
6519 int32_t id = offlineStream.id;
6520 if (mInputStream != nullptr && id == mInputStream->getId()) {
6521 inputStream = mInputStream;
6522 } else {
6523 offlineStreamSet.add(id, mOutputStreams.get(id));
6524 }
6525 }
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006526
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006527 // TODO: check if we need to lock before copying states
6528 // though technically no other thread should be talking to Camera3Device at this point
6529 Camera3OfflineStates offlineStates(
6530 mTagMonitor, mVendorTagId, mUseHalBufManager, mNeedFixupMonochromeTags,
Shuzhen Wangb7b42652020-05-07 11:59:02 -07006531 mUsePartialResult, mNumPartialResults, mLastCompletedRegularFrameNumber,
6532 mLastCompletedReprocessFrameNumber, mLastCompletedZslFrameNumber,
6533 mNextResultFrameNumber, mNextReprocessResultFrameNumber,
6534 mNextZslStillResultFrameNumber, mNextShutterFrameNumber,
6535 mNextReprocessShutterFrameNumber, mNextZslStillShutterFrameNumber,
6536 mDeviceInfo, mPhysicalDeviceInfoMap, mDistortionMappers,
6537 mZoomRatioMappers, mRotateAndCropMappers);
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006538
6539 *session = new Camera3OfflineSession(mId, inputStream, offlineStreamSet,
6540 std::move(bufferRecords), offlineReqs, offlineStates, offlineSession);
6541
6542 // Delete all streams that has been transferred to offline session
6543 Mutex::Autolock l(mLock);
6544 for (auto offlineStream : offlineSessionInfo.offlineStreams) {
6545 int32_t id = offlineStream.id;
6546 if (mInputStream != nullptr && id == mInputStream->getId()) {
6547 mInputStream.clear();
6548 } else {
6549 mOutputStreams.remove(id);
6550 }
6551 }
6552
6553 // disconnect all other streams and switch to UNCONFIGURED state
6554 if (mInputStream != nullptr) {
6555 ret = mInputStream->disconnect();
6556 if (ret != OK) {
6557 SET_ERR_L("disconnect input stream failed!");
6558 return UNKNOWN_ERROR;
6559 }
6560 }
6561
6562 for (auto streamId : mOutputStreams.getStreamIds()) {
6563 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
6564 ret = stream->disconnect();
6565 if (ret != OK) {
6566 SET_ERR_L("disconnect output stream %d failed!", streamId);
6567 return UNKNOWN_ERROR;
6568 }
6569 }
6570
6571 mInputStream.clear();
6572 mOutputStreams.clear();
6573 mNeedConfig = true;
6574 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
6575 mOperatingMode = NO_MODE;
6576 mIsConstrainedHighSpeedConfiguration = false;
Emilian Peevc0fe54c2020-03-11 14:05:07 -07006577 mRequestThread->clearPreviousRequest();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006578
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006579 return OK;
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006580 // TO be done by CameraDeviceClient/Camera3OfflineSession
6581 // register the offline client to camera service
6582 // Setup result passthing threads etc
6583 // Initialize offline session so HAL can start sending callback to it (result Fmq)
6584 // TODO: check how many onIdle callback will be sent
6585 // Java side to make sure the CameraCaptureSession is properly closed
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006586}
6587
Emilian Peevcc0b7952020-01-07 13:54:47 -08006588void Camera3Device::getOfflineStreamIds(std::vector<int> *offlineStreamIds) {
6589 ATRACE_CALL();
6590
6591 if (offlineStreamIds == nullptr) {
6592 return;
6593 }
6594
6595 Mutex::Autolock il(mInterfaceLock);
6596
6597 auto streamIds = mOutputStreams.getStreamIds();
6598 bool hasInputStream = mInputStream != nullptr;
6599 if (hasInputStream && mInputStream->getOfflineProcessingSupport()) {
6600 offlineStreamIds->push_back(mInputStream->getId());
6601 }
6602
6603 for (const auto & streamId : streamIds) {
6604 sp<camera3::Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
6605 // Streams that use the camera buffer manager are currently not supported in
6606 // offline mode
6607 if (stream->getOfflineProcessingSupport() &&
6608 (stream->getStreamSetId() == CAMERA3_STREAM_SET_ID_INVALID)) {
6609 offlineStreamIds->push_back(streamId);
6610 }
6611 }
6612}
6613
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08006614status_t Camera3Device::setRotateAndCropAutoBehavior(
6615 camera_metadata_enum_android_scaler_rotate_and_crop_t rotateAndCropValue) {
6616 ATRACE_CALL();
6617 Mutex::Autolock il(mInterfaceLock);
6618 Mutex::Autolock l(mLock);
6619 if (mRequestThread == nullptr) {
6620 return INVALID_OPERATION;
6621 }
6622 return mRequestThread->setRotateAndCropAutoBehavior(rotateAndCropValue);
6623}
6624
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08006625bool Camera3Device::supportsCameraMute() {
6626 Mutex::Autolock il(mInterfaceLock);
6627 Mutex::Autolock l(mLock);
6628
6629 return mSupportCameraMute;
6630}
6631
6632status_t Camera3Device::setCameraMute(bool enabled) {
6633 ATRACE_CALL();
6634 Mutex::Autolock il(mInterfaceLock);
6635 Mutex::Autolock l(mLock);
6636
6637 if (mRequestThread == nullptr || !mSupportCameraMute) {
6638 return INVALID_OPERATION;
6639 }
Eino-Ville Talvala11afe4f2021-05-27 14:45:31 -07006640 int32_t muteMode =
6641 !enabled ? ANDROID_SENSOR_TEST_PATTERN_MODE_OFF :
6642 mSupportTestPatternSolidColor ? ANDROID_SENSOR_TEST_PATTERN_MODE_SOLID_COLOR :
6643 ANDROID_SENSOR_TEST_PATTERN_MODE_BLACK;
6644 return mRequestThread->setCameraMute(muteMode);
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08006645}
6646
Cliff Wuc2ad9c82021-04-21 00:58:58 +08006647status_t Camera3Device::injectCamera(const String8& injectedCamId,
6648 sp<CameraProviderManager> manager) {
6649 ALOGI("%s Injection camera: injectedCamId = %s", __FUNCTION__, injectedCamId.string());
6650 ATRACE_CALL();
6651 Mutex::Autolock il(mInterfaceLock);
6652
6653 status_t res = NO_ERROR;
6654 if (mInjectionMethods->isInjecting()) {
6655 if (injectedCamId == mInjectionMethods->getInjectedCamId()) {
6656 return OK;
6657 } else {
6658 res = mInjectionMethods->stopInjection();
6659 if (res != OK) {
6660 ALOGE("%s: Failed to stop the injection camera! ret != NO_ERROR: %d",
6661 __FUNCTION__, res);
6662 return res;
6663 }
6664 }
6665 }
6666
6667 res = mInjectionMethods->injectionInitialize(injectedCamId, manager, this);
6668 if (res != OK) {
6669 ALOGE("%s: Failed to initialize the injection camera! ret != NO_ERROR: %d",
6670 __FUNCTION__, res);
6671 return res;
6672 }
6673
6674 camera3::camera_stream_configuration injectionConfig;
6675 std::vector<uint32_t> injectionBufferSizes;
6676 mInjectionMethods->getInjectionConfig(&injectionConfig, &injectionBufferSizes);
6677 // When the second display of android is cast to the remote device, and the opened camera is
6678 // also cast to the second display, in this case, because the camera has configured the streams
6679 // at this time, we can directly call injectCamera() to replace the internal camera with
6680 // injection camera.
6681 if (mOperatingMode >= 0 && injectionConfig.num_streams > 0
6682 && injectionBufferSizes.size() > 0) {
6683 ALOGV("%s: The opened camera is directly cast to the remote device.", __FUNCTION__);
6684 res = mInjectionMethods->injectCamera(
6685 injectionConfig, injectionBufferSizes);
6686 if (res != OK) {
6687 ALOGE("Can't finish inject camera process!");
6688 return res;
6689 }
6690 }
6691
6692 return OK;
6693}
6694
6695status_t Camera3Device::stopInjection() {
6696 ALOGI("%s: Injection camera: stopInjection", __FUNCTION__);
6697 Mutex::Autolock il(mInterfaceLock);
6698 return mInjectionMethods->stopInjection();
6699}
6700
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08006701}; // namespace android