blob: d572d57943c2dbadfe9985e10a7f089856b9b5bc [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
Shuzhen Wangd4abdf72021-05-28 11:22:50 -070078Camera3Device::Camera3Device(const String8 &id, bool overrideForPerfClass):
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080079 mId(id),
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -080080 mOperatingMode(NO_MODE),
Eino-Ville Talvala9a179412015-06-09 13:15:16 -070081 mIsConstrainedHighSpeedConfiguration(false),
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -070082 mStatus(STATUS_UNINITIALIZED),
Ruben Brunk183f0562015-08-12 12:55:02 -070083 mStatusWaiters(0),
Zhijun He204e3292014-07-14 17:09:23 -070084 mUsePartialResult(false),
85 mNumPartialResults(1),
Shuzhen Wangc28dccc2016-02-11 23:48:46 -080086 mTimestampOffset(0),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -070087 mNextResultFrameNumber(0),
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -070088 mNextReprocessResultFrameNumber(0),
Shuzhen Wang5ee99842019-04-12 11:55:48 -070089 mNextZslStillResultFrameNumber(0),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -070090 mNextShutterFrameNumber(0),
Chien-Yu Chen3df11ce2015-09-30 14:13:30 -070091 mNextReprocessShutterFrameNumber(0),
Shuzhen Wang5ee99842019-04-12 11:55:48 -070092 mNextZslStillShutterFrameNumber(0),
Emilian Peev71c73a22017-03-21 16:35:51 +000093 mListener(NULL),
Emilian Peev811d2952018-05-25 11:08:40 +010094 mVendorTagId(CAMERA_METADATA_INVALID_VENDOR_ID),
Shuzhen Wang268a1362018-10-16 16:32:59 -070095 mLastTemplateId(-1),
Shuzhen Wangd4abdf72021-05-28 11:22:50 -070096 mNeedFixupMonochromeTags(false),
97 mOverrideForPerfClass(overrideForPerfClass)
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080098{
99 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800100 ALOGV("%s: Created device for camera %s", __FUNCTION__, mId.string());
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800101}
102
103Camera3Device::~Camera3Device()
104{
105 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800106 ALOGV("%s: Tearing down for camera id %s", __FUNCTION__, mId.string());
Yin-Chia Yehc5248132018-08-15 12:19:20 -0700107 disconnectImpl();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800108}
109
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800110const String8& Camera3Device::getId() const {
Igor Murashkin71381052013-03-04 14:53:08 -0800111 return mId;
112}
113
Emilian Peevbd8c5032018-02-14 23:05:40 +0000114status_t Camera3Device::initialize(sp<CameraProviderManager> manager, const String8& monitorTags) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800115 ATRACE_CALL();
116 Mutex::Autolock il(mInterfaceLock);
117 Mutex::Autolock l(mLock);
118
119 ALOGV("%s: Initializing HIDL device for camera %s", __FUNCTION__, mId.string());
120 if (mStatus != STATUS_UNINITIALIZED) {
121 CLOGE("Already initialized!");
122 return INVALID_OPERATION;
123 }
124 if (manager == nullptr) return INVALID_OPERATION;
125
126 sp<ICameraDeviceSession> session;
127 ATRACE_BEGIN("CameraHal::openSession");
Steven Moreland5ff9c912017-03-09 23:13:00 -0800128 status_t res = manager->openSession(mId.string(), this,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800129 /*out*/ &session);
130 ATRACE_END();
131 if (res != OK) {
132 SET_ERR_L("Could not open camera session: %s (%d)", strerror(-res), res);
133 return res;
134 }
135
Shuzhen Wangd4abdf72021-05-28 11:22:50 -0700136 res = manager->getCameraCharacteristics(mId.string(), mOverrideForPerfClass, &mDeviceInfo);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800137 if (res != OK) {
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700138 SET_ERR_L("Could not retrieve camera characteristics: %s (%d)", strerror(-res), res);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800139 session->close();
140 return res;
141 }
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800142 mSupportNativeZoomRatio = manager->supportNativeZoomRatio(mId.string());
Yin-Chia Yeh52778d42016-12-22 18:20:43 -0800143
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700144 std::vector<std::string> physicalCameraIds;
Shuzhen Wang03d8cc12018-09-12 14:17:09 -0700145 bool isLogical = manager->isLogicalCamera(mId.string(), &physicalCameraIds);
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700146 if (isLogical) {
147 for (auto& physicalId : physicalCameraIds) {
Shuzhen Wangd4abdf72021-05-28 11:22:50 -0700148 // Do not override characteristics for physical cameras
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -0700149 res = manager->getCameraCharacteristics(
Shuzhen Wangd4abdf72021-05-28 11:22:50 -0700150 physicalId, /*overrideForPerfClass*/false, &mPhysicalDeviceInfoMap[physicalId]);
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700151 if (res != OK) {
152 SET_ERR_L("Could not retrieve camera %s characteristics: %s (%d)",
153 physicalId.c_str(), strerror(-res), res);
154 session->close();
155 return res;
156 }
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -0700157
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800158 bool usePrecorrectArray =
159 DistortionMapper::isDistortionSupported(mPhysicalDeviceInfoMap[physicalId]);
160 if (usePrecorrectArray) {
161 res = mDistortionMappers[physicalId].setupStaticInfo(
162 mPhysicalDeviceInfoMap[physicalId]);
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -0700163 if (res != OK) {
164 SET_ERR_L("Unable to read camera %s's calibration fields for distortion "
165 "correction", physicalId.c_str());
166 session->close();
167 return res;
168 }
169 }
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800170
Shuzhen Wang1c834da2019-12-18 11:17:03 -0800171 mZoomRatioMappers[physicalId] = ZoomRatioMapper(
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800172 &mPhysicalDeviceInfoMap[physicalId],
173 mSupportNativeZoomRatio, usePrecorrectArray);
Jayant Chowdhary9255ce02021-07-15 11:18:17 -0700174
175 if (SessionConfigurationUtils::isUltraHighResolutionSensor(
176 mPhysicalDeviceInfoMap[physicalId])) {
177 mUHRCropAndMeteringRegionMappers[physicalId] =
178 UHRCropAndMeteringRegionMapper(mPhysicalDeviceInfoMap[physicalId],
179 usePrecorrectArray);
180 }
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700181 }
182 }
183
Yifan Hongf79b5542017-04-11 14:44:25 -0700184 std::shared_ptr<RequestMetadataQueue> queue;
Yifan Honga640c5a2017-04-12 16:30:31 -0700185 auto requestQueueRet = session->getCaptureRequestMetadataQueue(
186 [&queue](const auto& descriptor) {
187 queue = std::make_shared<RequestMetadataQueue>(descriptor);
188 if (!queue->isValid() || queue->availableToWrite() <= 0) {
189 ALOGE("HAL returns empty request metadata fmq, not use it");
190 queue = nullptr;
191 // don't use the queue onwards.
192 }
193 });
194 if (!requestQueueRet.isOk()) {
195 ALOGE("Transaction error when getting request metadata fmq: %s, not use it",
196 requestQueueRet.description().c_str());
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -0700197 return DEAD_OBJECT;
Yifan Hongf79b5542017-04-11 14:44:25 -0700198 }
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700199
200 std::unique_ptr<ResultMetadataQueue>& resQueue = mResultMetadataQueue;
Yifan Honga640c5a2017-04-12 16:30:31 -0700201 auto resultQueueRet = session->getCaptureResultMetadataQueue(
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700202 [&resQueue](const auto& descriptor) {
203 resQueue = std::make_unique<ResultMetadataQueue>(descriptor);
204 if (!resQueue->isValid() || resQueue->availableToWrite() <= 0) {
Yifan Honga640c5a2017-04-12 16:30:31 -0700205 ALOGE("HAL returns empty result metadata fmq, not use it");
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700206 resQueue = nullptr;
207 // Don't use the resQueue onwards.
Yifan Honga640c5a2017-04-12 16:30:31 -0700208 }
209 });
210 if (!resultQueueRet.isOk()) {
211 ALOGE("Transaction error when getting result metadata queue from camera session: %s",
212 resultQueueRet.description().c_str());
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -0700213 return DEAD_OBJECT;
Yifan Honga640c5a2017-04-12 16:30:31 -0700214 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -0700215 IF_ALOGV() {
216 session->interfaceChain([](
217 ::android::hardware::hidl_vec<::android::hardware::hidl_string> interfaceChain) {
218 ALOGV("Session interface chain:");
Chih-Hung Hsieh3ef324d2018-12-11 11:48:12 -0800219 for (const auto& iface : interfaceChain) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -0700220 ALOGV(" %s", iface.c_str());
221 }
222 });
223 }
Yifan Hongf79b5542017-04-11 14:44:25 -0700224
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -0800225 camera_metadata_entry bufMgrMode =
226 mDeviceInfo.find(ANDROID_INFO_SUPPORTED_BUFFER_MANAGEMENT_VERSION);
227 if (bufMgrMode.count > 0) {
228 mUseHalBufManager = (bufMgrMode.data.u8[0] ==
229 ANDROID_INFO_SUPPORTED_BUFFER_MANAGEMENT_VERSION_HIDL_DEVICE_3_5);
230 }
231
Yin-Chia Yehb978c382019-10-30 00:22:37 -0700232 camera_metadata_entry_t capabilities = mDeviceInfo.find(ANDROID_REQUEST_AVAILABLE_CAPABILITIES);
233 for (size_t i = 0; i < capabilities.count; i++) {
234 uint8_t capability = capabilities.data.u8[i];
235 if (capability == ANDROID_REQUEST_AVAILABLE_CAPABILITIES_OFFLINE_PROCESSING) {
236 mSupportOfflineProcessing = true;
237 }
238 }
239
240 mInterface = new HalInterface(session, queue, mUseHalBufManager, mSupportOfflineProcessing);
Emilian Peev71c73a22017-03-21 16:35:51 +0000241 std::string providerType;
242 mVendorTagId = manager->getProviderTagIdLocked(mId.string());
Emilian Peevbd8c5032018-02-14 23:05:40 +0000243 mTagMonitor.initialize(mVendorTagId);
244 if (!monitorTags.isEmpty()) {
245 mTagMonitor.parseTagsToMonitor(String8(monitorTags));
246 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800247
Shuzhen Wang268a1362018-10-16 16:32:59 -0700248 // Metadata tags needs fixup for monochrome camera device version less
249 // than 3.5.
250 hardware::hidl_version maxVersion{0,0};
251 res = manager->getHighestSupportedVersion(mId.string(), &maxVersion);
252 if (res != OK) {
253 ALOGE("%s: Error in getting camera device version id: %s (%d)",
254 __FUNCTION__, strerror(-res), res);
255 return res;
256 }
257 int deviceVersion = HARDWARE_DEVICE_API_VERSION(
258 maxVersion.get_major(), maxVersion.get_minor());
259
260 bool isMonochrome = false;
Yin-Chia Yehb978c382019-10-30 00:22:37 -0700261 for (size_t i = 0; i < capabilities.count; i++) {
262 uint8_t capability = capabilities.data.u8[i];
Shuzhen Wang268a1362018-10-16 16:32:59 -0700263 if (capability == ANDROID_REQUEST_AVAILABLE_CAPABILITIES_MONOCHROME) {
264 isMonochrome = true;
265 }
266 }
267 mNeedFixupMonochromeTags = (isMonochrome && deviceVersion < CAMERA_DEVICE_API_VERSION_3_5);
268
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800269 return initializeCommonLocked();
270}
271
272status_t Camera3Device::initializeCommonLocked() {
273
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700274 /** Start up status tracker thread */
275 mStatusTracker = new StatusTracker(this);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800276 status_t res = mStatusTracker->run(String8::format("C3Dev-%s-Status", mId.string()).string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700277 if (res != OK) {
278 SET_ERR_L("Unable to start status tracking thread: %s (%d)",
279 strerror(-res), res);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800280 mInterface->close();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700281 mStatusTracker.clear();
282 return res;
283 }
284
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -0700285 /** Register in-flight map to the status tracker */
Yin-Chia Yeh87b3ec02019-06-03 10:44:39 -0700286 mInFlightStatusId = mStatusTracker->addComponent("InflightRequests");
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -0700287
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -0700288 if (mUseHalBufManager) {
289 res = mRequestBufferSM.initialize(mStatusTracker);
290 if (res != OK) {
291 SET_ERR_L("Unable to start request buffer state machine: %s (%d)",
292 strerror(-res), res);
293 mInterface->close();
294 mStatusTracker.clear();
295 return res;
296 }
297 }
298
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -0800299 /** Create buffer manager */
300 mBufferManager = new Camera3BufferManager();
301
302 Vector<int32_t> sessionParamKeys;
303 camera_metadata_entry_t sessionKeysEntry = mDeviceInfo.find(
304 ANDROID_REQUEST_AVAILABLE_SESSION_KEYS);
305 if (sessionKeysEntry.count > 0) {
306 sessionParamKeys.insertArrayAt(sessionKeysEntry.data.i32, 0, sessionKeysEntry.count);
307 }
308
Chien-Yu Chenab5135b2015-06-30 11:20:58 -0700309 /** Start up request queue thread */
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -0700310 mRequestThread = new RequestThread(
311 this, mStatusTracker, mInterface, sessionParamKeys, mUseHalBufManager);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800312 res = mRequestThread->run(String8::format("C3Dev-%s-ReqQueue", mId.string()).string());
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800313 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700314 SET_ERR_L("Unable to start request queue thread: %s (%d)",
315 strerror(-res), res);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800316 mInterface->close();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800317 mRequestThread.clear();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800318 return res;
319 }
320
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -0700321 mPreparerThread = new PreparerThread();
322
Ruben Brunk183f0562015-08-12 12:55:02 -0700323 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800324 mNextStreamId = 0;
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -0400325 mFakeStreamId = NO_STREAM;
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -0700326 mNeedConfig = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700327 mPauseStateNotify = false;
Shuzhen Wang83bff122020-11-20 15:51:39 -0800328 mIsInputStreamMultiResolution = false;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800329
Shuzhen Wangc28dccc2016-02-11 23:48:46 -0800330 // Measure the clock domain offset between camera and video/hw_composer
331 camera_metadata_entry timestampSource =
332 mDeviceInfo.find(ANDROID_SENSOR_INFO_TIMESTAMP_SOURCE);
333 if (timestampSource.count > 0 && timestampSource.data.u8[0] ==
334 ANDROID_SENSOR_INFO_TIMESTAMP_SOURCE_REALTIME) {
335 mTimestampOffset = getMonoToBoottimeOffset();
336 }
337
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -0700338 // Will the HAL be sending in early partial result metadata?
Emilian Peev08dd2452017-04-06 16:55:14 +0100339 camera_metadata_entry partialResultsCount =
340 mDeviceInfo.find(ANDROID_REQUEST_PARTIAL_RESULT_COUNT);
341 if (partialResultsCount.count > 0) {
342 mNumPartialResults = partialResultsCount.data.i32[0];
343 mUsePartialResult = (mNumPartialResults > 1);
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -0700344 }
345
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800346 bool usePrecorrectArray = DistortionMapper::isDistortionSupported(mDeviceInfo);
347 if (usePrecorrectArray) {
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -0700348 res = mDistortionMappers[mId.c_str()].setupStaticInfo(mDeviceInfo);
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -0700349 if (res != OK) {
350 SET_ERR_L("Unable to read necessary calibration fields for distortion correction");
351 return res;
352 }
353 }
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800354
Shuzhen Wang1c834da2019-12-18 11:17:03 -0800355 mZoomRatioMappers[mId.c_str()] = ZoomRatioMapper(&mDeviceInfo,
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800356 mSupportNativeZoomRatio, usePrecorrectArray);
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800357
Jayant Chowdhary9255ce02021-07-15 11:18:17 -0700358 if (SessionConfigurationUtils::isUltraHighResolutionSensor(mDeviceInfo)) {
359 mUHRCropAndMeteringRegionMappers[mId.c_str()] =
360 UHRCropAndMeteringRegionMapper(mDeviceInfo, usePrecorrectArray);
361 }
362
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -0800363 if (RotateAndCropMapper::isNeeded(&mDeviceInfo)) {
364 mRotateAndCropMappers.emplace(mId.c_str(), &mDeviceInfo);
365 }
366
Eino-Ville Talvala305cec62020-11-12 14:18:17 -0800367 camera_metadata_entry_t availableTestPatternModes = mDeviceInfo.find(
368 ANDROID_SENSOR_AVAILABLE_TEST_PATTERN_MODES);
369 for (size_t i = 0; i < availableTestPatternModes.count; i++) {
Eino-Ville Talvala11afe4f2021-05-27 14:45:31 -0700370 if (availableTestPatternModes.data.i32[i] ==
371 ANDROID_SENSOR_TEST_PATTERN_MODE_SOLID_COLOR) {
Eino-Ville Talvala305cec62020-11-12 14:18:17 -0800372 mSupportCameraMute = true;
Eino-Ville Talvala11afe4f2021-05-27 14:45:31 -0700373 mSupportTestPatternSolidColor = true;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -0800374 break;
Eino-Ville Talvala11afe4f2021-05-27 14:45:31 -0700375 } else if (availableTestPatternModes.data.i32[i] ==
376 ANDROID_SENSOR_TEST_PATTERN_MODE_BLACK) {
377 mSupportCameraMute = true;
378 mSupportTestPatternSolidColor = false;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -0800379 }
380 }
381
Cliff Wuc2ad9c82021-04-21 00:58:58 +0800382 mInjectionMethods = new Camera3DeviceInjectionMethods(this);
383
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800384 return OK;
385}
386
387status_t Camera3Device::disconnect() {
Yin-Chia Yehc5248132018-08-15 12:19:20 -0700388 return disconnectImpl();
389}
390
391status_t Camera3Device::disconnectImpl() {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800392 ATRACE_CALL();
Yin-Chia Yehe1c80632016-08-08 14:48:05 -0700393 ALOGI("%s: E", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800394
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700395 status_t res = OK;
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700396 std::vector<wp<Camera3StreamInterface>> streams;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700397 {
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800398 Mutex::Autolock il(mInterfaceLock);
399 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
400 {
401 Mutex::Autolock l(mLock);
402 if (mStatus == STATUS_UNINITIALIZED) return res;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700403
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800404 if (mStatus == STATUS_ACTIVE ||
405 (mStatus == STATUS_ERROR && mRequestThread != NULL)) {
406 res = mRequestThread->clearRepeatingRequests();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700407 if (res != OK) {
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800408 SET_ERR_L("Can't stop streaming");
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700409 // Continue to close device even in case of error
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800410 } else {
411 res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
412 if (res != OK) {
413 SET_ERR_L("Timeout waiting for HAL to drain (% " PRIi64 " ns)",
414 maxExpectedDuration);
415 // Continue to close device even in case of error
416 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700417 }
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700418 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800419
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800420 if (mStatus == STATUS_ERROR) {
421 CLOGE("Shutting down in an error state");
422 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700423
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800424 if (mStatusTracker != NULL) {
425 mStatusTracker->requestExit();
426 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700427
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800428 if (mRequestThread != NULL) {
429 mRequestThread->requestExit();
430 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700431
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800432 streams.reserve(mOutputStreams.size() + (mInputStream != nullptr ? 1 : 0));
433 for (size_t i = 0; i < mOutputStreams.size(); i++) {
434 streams.push_back(mOutputStreams[i]);
435 }
436 if (mInputStream != nullptr) {
437 streams.push_back(mInputStream);
438 }
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700439 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700440 }
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800441 // Joining done without holding mLock and mInterfaceLock, otherwise deadlocks may ensue
442 // as the threads try to access parent state (b/143513518)
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700443 if (mRequestThread != NULL && mStatus != STATUS_ERROR) {
444 // HAL may be in a bad state, so waiting for request thread
445 // (which may be stuck in the HAL processCaptureRequest call)
446 // could be dangerous.
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800447 // give up mInterfaceLock here and then lock it again. Could this lead
448 // to other deadlocks
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700449 mRequestThread->join();
450 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700451 {
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800452 Mutex::Autolock il(mInterfaceLock);
453 if (mStatusTracker != NULL) {
454 mStatusTracker->join();
455 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800456
Cliff Wuc2ad9c82021-04-21 00:58:58 +0800457 if (mInjectionMethods->isInjecting()) {
458 mInjectionMethods->stopInjection();
459 }
460
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800461 HalInterface* interface;
462 {
463 Mutex::Autolock l(mLock);
464 mRequestThread.clear();
465 Mutex::Autolock stLock(mTrackerLock);
466 mStatusTracker.clear();
467 interface = mInterface.get();
468 }
Eino-Ville Talvalaefff1c42015-08-28 16:27:27 -0700469
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800470 // Call close without internal mutex held, as the HAL close may need to
471 // wait on assorted callbacks,etc, to complete before it can return.
472 interface->close();
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700473
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800474 flushInflightRequests();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800475
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800476 {
477 Mutex::Autolock l(mLock);
478 mInterface->clear();
479 mOutputStreams.clear();
480 mInputStream.clear();
481 mDeletedStreams.clear();
482 mBufferManager.clear();
483 internalUpdateStatusLocked(STATUS_UNINITIALIZED);
484 }
485
486 for (auto& weakStream : streams) {
487 sp<Camera3StreamInterface> stream = weakStream.promote();
488 if (stream != nullptr) {
489 ALOGE("%s: Stream %d leaked! strong reference (%d)!",
490 __FUNCTION__, stream->getId(), stream->getStrongCount() - 1);
491 }
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700492 }
493 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -0700494 ALOGI("%s: X", __FUNCTION__);
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700495 return res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800496}
497
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700498// For dumping/debugging only -
499// try to acquire a lock a few times, eventually give up to proceed with
500// debug/dump operations
501bool Camera3Device::tryLockSpinRightRound(Mutex& lock) {
502 bool gotLock = false;
503 for (size_t i = 0; i < kDumpLockAttempts; ++i) {
504 if (lock.tryLock() == NO_ERROR) {
505 gotLock = true;
506 break;
507 } else {
508 usleep(kDumpSleepDuration);
509 }
510 }
511 return gotLock;
512}
513
Shuzhen Wangc28dccc2016-02-11 23:48:46 -0800514nsecs_t Camera3Device::getMonoToBoottimeOffset() {
515 // try three times to get the clock offset, choose the one
516 // with the minimum gap in measurements.
517 const int tries = 3;
518 nsecs_t bestGap, measured;
519 for (int i = 0; i < tries; ++i) {
520 const nsecs_t tmono = systemTime(SYSTEM_TIME_MONOTONIC);
521 const nsecs_t tbase = systemTime(SYSTEM_TIME_BOOTTIME);
522 const nsecs_t tmono2 = systemTime(SYSTEM_TIME_MONOTONIC);
523 const nsecs_t gap = tmono2 - tmono;
524 if (i == 0 || gap < bestGap) {
525 bestGap = gap;
526 measured = tbase - ((tmono + tmono2) >> 1);
527 }
528 }
529 return measured;
530}
531
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800532hardware::graphics::common::V1_0::PixelFormat Camera3Device::mapToPixelFormat(
533 int frameworkFormat) {
534 return (hardware::graphics::common::V1_0::PixelFormat) frameworkFormat;
535}
536
537DataspaceFlags Camera3Device::mapToHidlDataspace(
538 android_dataspace dataSpace) {
539 return dataSpace;
540}
541
Chia-I Wu67a0c0e2017-04-06 13:37:01 -0700542BufferUsageFlags Camera3Device::mapToConsumerUsage(
Emilian Peev050f5dc2017-05-18 14:43:56 +0100543 uint64_t usage) {
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -0700544 return usage;
545}
546
Emilian Peevf4816702020-04-03 15:44:51 -0700547StreamRotation Camera3Device::mapToStreamRotation(camera_stream_rotation_t rotation) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800548 switch (rotation) {
Emilian Peevf4816702020-04-03 15:44:51 -0700549 case CAMERA_STREAM_ROTATION_0:
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800550 return StreamRotation::ROTATION_0;
Emilian Peevf4816702020-04-03 15:44:51 -0700551 case CAMERA_STREAM_ROTATION_90:
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800552 return StreamRotation::ROTATION_90;
Emilian Peevf4816702020-04-03 15:44:51 -0700553 case CAMERA_STREAM_ROTATION_180:
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800554 return StreamRotation::ROTATION_180;
Emilian Peevf4816702020-04-03 15:44:51 -0700555 case CAMERA_STREAM_ROTATION_270:
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800556 return StreamRotation::ROTATION_270;
557 }
558 ALOGE("%s: Unknown stream rotation %d", __FUNCTION__, rotation);
559 return StreamRotation::ROTATION_0;
560}
561
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800562status_t Camera3Device::mapToStreamConfigurationMode(
Emilian Peevf4816702020-04-03 15:44:51 -0700563 camera_stream_configuration_mode_t operationMode, StreamConfigurationMode *mode) {
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800564 if (mode == nullptr) return BAD_VALUE;
Emilian Peevf4816702020-04-03 15:44:51 -0700565 if (operationMode < CAMERA_VENDOR_STREAM_CONFIGURATION_MODE_START) {
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800566 switch(operationMode) {
Emilian Peevf4816702020-04-03 15:44:51 -0700567 case CAMERA_STREAM_CONFIGURATION_NORMAL_MODE:
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800568 *mode = StreamConfigurationMode::NORMAL_MODE;
569 break;
Emilian Peevf4816702020-04-03 15:44:51 -0700570 case CAMERA_STREAM_CONFIGURATION_CONSTRAINED_HIGH_SPEED_MODE:
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800571 *mode = StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE;
572 break;
573 default:
574 ALOGE("%s: Unknown stream configuration mode %d", __FUNCTION__, operationMode);
575 return BAD_VALUE;
576 }
577 } else {
578 *mode = static_cast<StreamConfigurationMode>(operationMode);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800579 }
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800580 return OK;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800581}
582
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800583int Camera3Device::mapToFrameworkFormat(
584 hardware::graphics::common::V1_0::PixelFormat pixelFormat) {
585 return static_cast<uint32_t>(pixelFormat);
586}
587
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -0700588android_dataspace Camera3Device::mapToFrameworkDataspace(
589 DataspaceFlags dataSpace) {
590 return static_cast<android_dataspace>(dataSpace);
591}
592
Emilian Peev050f5dc2017-05-18 14:43:56 +0100593uint64_t Camera3Device::mapConsumerToFrameworkUsage(
Chia-I Wu67a0c0e2017-04-06 13:37:01 -0700594 BufferUsageFlags usage) {
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -0700595 return usage;
596}
597
Emilian Peev050f5dc2017-05-18 14:43:56 +0100598uint64_t Camera3Device::mapProducerToFrameworkUsage(
Chia-I Wu67a0c0e2017-04-06 13:37:01 -0700599 BufferUsageFlags usage) {
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -0700600 return usage;
601}
602
Zhijun Hef7da0962014-04-24 13:27:56 -0700603ssize_t Camera3Device::getJpegBufferSize(uint32_t width, uint32_t height) const {
Jayant Chowdharycd3d36b2021-07-10 10:53:53 -0700604 // Get max jpeg size (area-wise) for default sensor pixel mode
605 camera3::Size maxDefaultJpegResolution =
606 SessionConfigurationUtils::getMaxJpegResolution(mDeviceInfo,
607 /*isUltraHighResolutionSensor*/false);
608 // Get max jpeg size (area-wise) for max resolution sensor pixel mode / 0 if
609 // not ultra high res sensor
610 camera3::Size uhrMaxJpegResolution =
611 SessionConfigurationUtils::getMaxJpegResolution(mDeviceInfo,
612 /*isUltraHighResolution*/true);
613 if (maxDefaultJpegResolution.width == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800614 ALOGE("%s: Camera %s: Can't find valid available jpeg sizes in static metadata!",
615 __FUNCTION__, mId.string());
Zhijun Hef7da0962014-04-24 13:27:56 -0700616 return BAD_VALUE;
617 }
Jayant Chowdharycd3d36b2021-07-10 10:53:53 -0700618 bool useMaxSensorPixelModeThreshold = false;
619 if (uhrMaxJpegResolution.width != 0 &&
620 width * height > maxDefaultJpegResolution.width * maxDefaultJpegResolution.height) {
621 // Use the ultra high res max jpeg size and max jpeg buffer size
622 useMaxSensorPixelModeThreshold = true;
623 }
Zhijun Hef7da0962014-04-24 13:27:56 -0700624
Zhijun Hef7da0962014-04-24 13:27:56 -0700625 // Get max jpeg buffer size
626 ssize_t maxJpegBufferSize = 0;
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700627 camera_metadata_ro_entry jpegBufMaxSize = mDeviceInfo.find(ANDROID_JPEG_MAX_SIZE);
628 if (jpegBufMaxSize.count == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800629 ALOGE("%s: Camera %s: Can't find maximum JPEG size in static metadata!", __FUNCTION__,
630 mId.string());
Zhijun Hef7da0962014-04-24 13:27:56 -0700631 return BAD_VALUE;
632 }
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700633 maxJpegBufferSize = jpegBufMaxSize.data.i32[0];
Jayant Chowdharycd3d36b2021-07-10 10:53:53 -0700634
635 camera3::Size chosenMaxJpegResolution = maxDefaultJpegResolution;
636 if (useMaxSensorPixelModeThreshold) {
637 maxJpegBufferSize =
638 SessionConfigurationUtils::getUHRMaxJpegBufferSize(uhrMaxJpegResolution,
639 maxDefaultJpegResolution, maxJpegBufferSize);
640 chosenMaxJpegResolution = uhrMaxJpegResolution;
641 }
Yin-Chia Yeh0c4e56d2015-01-09 15:21:27 -0800642 assert(kMinJpegBufferSize < maxJpegBufferSize);
Zhijun Hef7da0962014-04-24 13:27:56 -0700643
644 // Calculate final jpeg buffer size for the given resolution.
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700645 float scaleFactor = ((float) (width * height)) /
Jayant Chowdharycd3d36b2021-07-10 10:53:53 -0700646 (chosenMaxJpegResolution.width * chosenMaxJpegResolution.height);
Yin-Chia Yeh0c4e56d2015-01-09 15:21:27 -0800647 ssize_t jpegBufferSize = scaleFactor * (maxJpegBufferSize - kMinJpegBufferSize) +
648 kMinJpegBufferSize;
Zhijun Hef7da0962014-04-24 13:27:56 -0700649 if (jpegBufferSize > maxJpegBufferSize) {
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -0800650 ALOGI("%s: jpeg buffer size calculated is > maxJpeg bufferSize(%zd), clamping",
651 __FUNCTION__, maxJpegBufferSize);
Zhijun Hef7da0962014-04-24 13:27:56 -0700652 jpegBufferSize = maxJpegBufferSize;
Zhijun Hef7da0962014-04-24 13:27:56 -0700653 }
Zhijun Hef7da0962014-04-24 13:27:56 -0700654 return jpegBufferSize;
655}
656
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700657ssize_t Camera3Device::getPointCloudBufferSize() const {
658 const int FLOATS_PER_POINT=4;
659 camera_metadata_ro_entry maxPointCount = mDeviceInfo.find(ANDROID_DEPTH_MAX_DEPTH_SAMPLES);
660 if (maxPointCount.count == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800661 ALOGE("%s: Camera %s: Can't find maximum depth point cloud size in static metadata!",
662 __FUNCTION__, mId.string());
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700663 return BAD_VALUE;
664 }
665 ssize_t maxBytesForPointCloud = sizeof(android_depth_points) +
666 maxPointCount.data.i32[0] * sizeof(float) * FLOATS_PER_POINT;
667 return maxBytesForPointCloud;
668}
669
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -0800670ssize_t Camera3Device::getRawOpaqueBufferSize(int32_t width, int32_t height,
671 bool maxResolution) const {
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800672 const int PER_CONFIGURATION_SIZE = 3;
673 const int WIDTH_OFFSET = 0;
674 const int HEIGHT_OFFSET = 1;
675 const int SIZE_OFFSET = 2;
676 camera_metadata_ro_entry rawOpaqueSizes =
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -0800677 mDeviceInfo.find(
678 camera3::SessionConfigurationUtils::getAppropriateModeTag(
679 ANDROID_SENSOR_OPAQUE_RAW_SIZE,
680 maxResolution));
Aurimas Liutikasbc57b122016-02-16 09:59:16 -0800681 size_t count = rawOpaqueSizes.count;
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800682 if (count == 0 || (count % PER_CONFIGURATION_SIZE)) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800683 ALOGE("%s: Camera %s: bad opaque RAW size static metadata length(%zu)!",
684 __FUNCTION__, mId.string(), count);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800685 return BAD_VALUE;
686 }
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700687
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800688 for (size_t i = 0; i < count; i += PER_CONFIGURATION_SIZE) {
689 if (width == rawOpaqueSizes.data.i32[i + WIDTH_OFFSET] &&
690 height == rawOpaqueSizes.data.i32[i + HEIGHT_OFFSET]) {
691 return rawOpaqueSizes.data.i32[i + SIZE_OFFSET];
692 }
693 }
694
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800695 ALOGE("%s: Camera %s: cannot find size for %dx%d opaque RAW image!",
696 __FUNCTION__, mId.string(), width, height);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800697 return BAD_VALUE;
698}
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700699
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800700status_t Camera3Device::dump(int fd, const Vector<String16> &args) {
701 ATRACE_CALL();
702 (void)args;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700703
704 // Try to lock, but continue in case of failure (to avoid blocking in
705 // deadlocks)
706 bool gotInterfaceLock = tryLockSpinRightRound(mInterfaceLock);
707 bool gotLock = tryLockSpinRightRound(mLock);
708
709 ALOGW_IF(!gotInterfaceLock,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800710 "Camera %s: %s: Unable to lock interface lock, proceeding anyway",
711 mId.string(), __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700712 ALOGW_IF(!gotLock,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800713 "Camera %s: %s: Unable to lock main lock, proceeding anyway",
714 mId.string(), __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700715
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800716 bool dumpTemplates = false;
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700717
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800718 String16 templatesOption("-t");
719 int n = args.size();
720 for (int i = 0; i < n; i++) {
721 if (args[i] == templatesOption) {
722 dumpTemplates = true;
723 }
Emilian Peevbd8c5032018-02-14 23:05:40 +0000724 if (args[i] == TagMonitor::kMonitorOption) {
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700725 if (i + 1 < n) {
726 String8 monitorTags = String8(args[i + 1]);
727 if (monitorTags == "off") {
728 mTagMonitor.disableMonitoring();
729 } else {
730 mTagMonitor.parseTagsToMonitor(monitorTags);
731 }
732 } else {
733 mTagMonitor.disableMonitoring();
734 }
735 }
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800736 }
737
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800738 String8 lines;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800739
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800740 const char *status =
741 mStatus == STATUS_ERROR ? "ERROR" :
742 mStatus == STATUS_UNINITIALIZED ? "UNINITIALIZED" :
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700743 mStatus == STATUS_UNCONFIGURED ? "UNCONFIGURED" :
744 mStatus == STATUS_CONFIGURED ? "CONFIGURED" :
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800745 mStatus == STATUS_ACTIVE ? "ACTIVE" :
746 "Unknown";
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700747
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800748 lines.appendFormat(" Device status: %s\n", status);
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700749 if (mStatus == STATUS_ERROR) {
750 lines.appendFormat(" Error cause: %s\n", mErrorCause.string());
751 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800752 lines.appendFormat(" Stream configuration:\n");
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800753 const char *mode =
754 mOperatingMode == static_cast<int>(StreamConfigurationMode::NORMAL_MODE) ? "NORMAL" :
755 mOperatingMode == static_cast<int>(
756 StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE) ? "CONSTRAINED_HIGH_SPEED" :
757 "CUSTOM";
758 lines.appendFormat(" Operation mode: %s (%d) \n", mode, mOperatingMode);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800759
760 if (mInputStream != NULL) {
761 write(fd, lines.string(), lines.size());
762 mInputStream->dump(fd, args);
763 } else {
764 lines.appendFormat(" No input stream.\n");
765 write(fd, lines.string(), lines.size());
766 }
767 for (size_t i = 0; i < mOutputStreams.size(); i++) {
768 mOutputStreams[i]->dump(fd,args);
769 }
770
Zhijun He431503c2016-03-07 17:30:16 -0800771 if (mBufferManager != NULL) {
772 lines = String8(" Camera3 Buffer Manager:\n");
773 write(fd, lines.string(), lines.size());
774 mBufferManager->dump(fd, args);
775 }
Zhijun He125684a2015-12-26 15:07:30 -0800776
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700777 lines = String8(" In-flight requests:\n");
Emilian Peeva6138c52021-06-24 12:52:38 -0700778 if (mInFlightLock.try_lock()) {
779 if (mInFlightMap.size() == 0) {
780 lines.append(" None\n");
781 } else {
782 for (size_t i = 0; i < mInFlightMap.size(); i++) {
783 InFlightRequest r = mInFlightMap.valueAt(i);
784 lines.appendFormat(" Frame %d | Timestamp: %" PRId64 ", metadata"
785 " arrived: %s, buffers left: %d\n", mInFlightMap.keyAt(i),
786 r.shutterTimestamp, r.haveResultMetadata ? "true" : "false",
787 r.numBuffersLeft);
788 }
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700789 }
Emilian Peeva6138c52021-06-24 12:52:38 -0700790 mInFlightLock.unlock();
791 } else {
792 lines.append(" Failed to acquire In-flight lock!\n");
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700793 }
794 write(fd, lines.string(), lines.size());
795
Shuzhen Wang686f6442017-06-20 16:16:04 -0700796 if (mRequestThread != NULL) {
797 mRequestThread->dumpCaptureRequestLatency(fd,
798 " ProcessCaptureRequest latency histogram:");
799 }
800
Igor Murashkin1e479c02013-09-06 16:55:14 -0700801 {
802 lines = String8(" Last request sent:\n");
803 write(fd, lines.string(), lines.size());
804
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700805 CameraMetadata lastRequest = getLatestRequestLocked();
Igor Murashkin1e479c02013-09-06 16:55:14 -0700806 lastRequest.dump(fd, /*verbosity*/2, /*indentation*/6);
807 }
808
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800809 if (dumpTemplates) {
Emilian Peevf4816702020-04-03 15:44:51 -0700810 const char *templateNames[CAMERA_TEMPLATE_COUNT] = {
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800811 "TEMPLATE_PREVIEW",
812 "TEMPLATE_STILL_CAPTURE",
813 "TEMPLATE_VIDEO_RECORD",
814 "TEMPLATE_VIDEO_SNAPSHOT",
815 "TEMPLATE_ZERO_SHUTTER_LAG",
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -0800816 "TEMPLATE_MANUAL",
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800817 };
818
Emilian Peevf4816702020-04-03 15:44:51 -0700819 for (int i = 1; i < CAMERA_TEMPLATE_COUNT; i++) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800820 camera_metadata_t *templateRequest = nullptr;
821 mInterface->constructDefaultRequestSettings(
Emilian Peevf4816702020-04-03 15:44:51 -0700822 (camera_request_template_t) i, &templateRequest);
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800823 lines = String8::format(" HAL Request %s:\n", templateNames[i-1]);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800824 if (templateRequest == nullptr) {
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800825 lines.append(" Not supported\n");
826 write(fd, lines.string(), lines.size());
827 } else {
828 write(fd, lines.string(), lines.size());
829 dump_indented_camera_metadata(templateRequest,
830 fd, /*verbosity*/2, /*indentation*/8);
831 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800832 free_camera_metadata(templateRequest);
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800833 }
834 }
835
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700836 mTagMonitor.dumpMonitoredMetadata(fd);
837
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800838 if (mInterface->valid()) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -0800839 lines = String8(" HAL device dump:\n");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800840 write(fd, lines.string(), lines.size());
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800841 mInterface->dump(fd);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800842 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800843
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700844 if (gotLock) mLock.unlock();
845 if (gotInterfaceLock) mInterfaceLock.unlock();
846
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800847 return OK;
848}
849
Emilian Peevfaa4bde2020-01-23 12:19:37 -0800850const CameraMetadata& Camera3Device::infoPhysical(const String8& physicalId) const {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800851 ALOGVV("%s: E", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800852 if (CC_UNLIKELY(mStatus == STATUS_UNINITIALIZED ||
853 mStatus == STATUS_ERROR)) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700854 ALOGW("%s: Access to static info %s!", __FUNCTION__,
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800855 mStatus == STATUS_ERROR ?
856 "when in error state" : "before init");
857 }
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700858 if (physicalId.isEmpty()) {
859 return mDeviceInfo;
860 } else {
861 std::string id(physicalId.c_str());
862 if (mPhysicalDeviceInfoMap.find(id) != mPhysicalDeviceInfoMap.end()) {
863 return mPhysicalDeviceInfoMap.at(id);
864 } else {
865 ALOGE("%s: Invalid physical camera id %s", __FUNCTION__, physicalId.c_str());
866 return mDeviceInfo;
867 }
868 }
869}
870
871const CameraMetadata& Camera3Device::info() const {
872 String8 emptyId;
Emilian Peevfaa4bde2020-01-23 12:19:37 -0800873 return infoPhysical(emptyId);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800874}
875
Jianing Wei90e59c92014-03-12 18:29:36 -0700876status_t Camera3Device::checkStatusOkToCaptureLocked() {
877 switch (mStatus) {
878 case STATUS_ERROR:
879 CLOGE("Device has encountered a serious error");
880 return INVALID_OPERATION;
881 case STATUS_UNINITIALIZED:
882 CLOGE("Device not initialized");
883 return INVALID_OPERATION;
884 case STATUS_UNCONFIGURED:
885 case STATUS_CONFIGURED:
886 case STATUS_ACTIVE:
887 // OK
888 break;
889 default:
890 SET_ERR_L("Unexpected status: %d", mStatus);
891 return INVALID_OPERATION;
892 }
893 return OK;
894}
895
896status_t Camera3Device::convertMetadataListToRequestListLocked(
Emilian Peevaebbe412018-01-15 13:53:24 +0000897 const List<const PhysicalCameraSettingsList> &metadataList,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700898 const std::list<const SurfaceMap> &surfaceMaps,
Shuzhen Wang316781a2020-08-18 18:11:01 -0700899 bool repeating, nsecs_t requestTimeNs,
Shuzhen Wang9d066012016-09-30 11:30:20 -0700900 RequestList *requestList) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700901 if (requestList == NULL) {
902 CLOGE("requestList cannot be NULL.");
903 return BAD_VALUE;
904 }
905
Jianing Weicb0652e2014-03-12 18:29:36 -0700906 int32_t burstId = 0;
Emilian Peevaebbe412018-01-15 13:53:24 +0000907 List<const PhysicalCameraSettingsList>::const_iterator metadataIt = metadataList.begin();
Shuzhen Wang0129d522016-10-30 22:43:41 -0700908 std::list<const SurfaceMap>::const_iterator surfaceMapIt = surfaceMaps.begin();
909 for (; metadataIt != metadataList.end() && surfaceMapIt != surfaceMaps.end();
910 ++metadataIt, ++surfaceMapIt) {
911 sp<CaptureRequest> newRequest = setUpRequestLocked(*metadataIt, *surfaceMapIt);
Jianing Wei90e59c92014-03-12 18:29:36 -0700912 if (newRequest == 0) {
913 CLOGE("Can't create capture request");
914 return BAD_VALUE;
915 }
Jianing Weicb0652e2014-03-12 18:29:36 -0700916
Shuzhen Wang9d066012016-09-30 11:30:20 -0700917 newRequest->mRepeating = repeating;
Shuzhen Wang316781a2020-08-18 18:11:01 -0700918 newRequest->mRequestTimeNs = requestTimeNs;
Shuzhen Wang9d066012016-09-30 11:30:20 -0700919
Jianing Weicb0652e2014-03-12 18:29:36 -0700920 // Setup burst Id and request Id
921 newRequest->mResultExtras.burstId = burstId++;
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -0800922 auto requestIdEntry = metadataIt->begin()->metadata.find(ANDROID_REQUEST_ID);
923 if (requestIdEntry.count == 0) {
Jianing Weicb0652e2014-03-12 18:29:36 -0700924 CLOGE("RequestID does not exist in metadata");
925 return BAD_VALUE;
926 }
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -0800927 newRequest->mResultExtras.requestId = requestIdEntry.data.i32[0];
Jianing Weicb0652e2014-03-12 18:29:36 -0700928
Jianing Wei90e59c92014-03-12 18:29:36 -0700929 requestList->push_back(newRequest);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700930
931 ALOGV("%s: requestId = %" PRId32, __FUNCTION__, newRequest->mResultExtras.requestId);
Jianing Wei90e59c92014-03-12 18:29:36 -0700932 }
Shuzhen Wang0129d522016-10-30 22:43:41 -0700933 if (metadataIt != metadataList.end() || surfaceMapIt != surfaceMaps.end()) {
934 ALOGE("%s: metadataList and surfaceMaps are not the same size!", __FUNCTION__);
935 return BAD_VALUE;
936 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -0700937
938 // Setup batch size if this is a high speed video recording request.
939 if (mIsConstrainedHighSpeedConfiguration && requestList->size() > 0) {
940 auto firstRequest = requestList->begin();
941 for (auto& outputStream : (*firstRequest)->mOutputStreams) {
942 if (outputStream->isVideoStream()) {
943 (*firstRequest)->mBatchSize = requestList->size();
Yin-Chia Yeh14ef48d2020-02-10 15:06:37 -0800944 outputStream->setBatchSize(requestList->size());
Chien-Yu Chen85a64552015-08-28 15:46:12 -0700945 break;
946 }
947 }
948 }
949
Jianing Wei90e59c92014-03-12 18:29:36 -0700950 return OK;
951}
952
Yin-Chia Yeh7e5a2042019-02-06 16:01:06 -0800953status_t Camera3Device::capture(CameraMetadata &request, int64_t* lastFrameNumber) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800954 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800955
Emilian Peevaebbe412018-01-15 13:53:24 +0000956 List<const PhysicalCameraSettingsList> requestsList;
Shuzhen Wang0129d522016-10-30 22:43:41 -0700957 std::list<const SurfaceMap> surfaceMaps;
Emilian Peevaebbe412018-01-15 13:53:24 +0000958 convertToRequestList(requestsList, surfaceMaps, request);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700959
Yin-Chia Yeh7e5a2042019-02-06 16:01:06 -0800960 return captureList(requestsList, surfaceMaps, lastFrameNumber);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700961}
962
Emilian Peevaebbe412018-01-15 13:53:24 +0000963void Camera3Device::convertToRequestList(List<const PhysicalCameraSettingsList>& requestsList,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700964 std::list<const SurfaceMap>& surfaceMaps,
965 const CameraMetadata& request) {
Emilian Peevaebbe412018-01-15 13:53:24 +0000966 PhysicalCameraSettingsList requestList;
967 requestList.push_back({std::string(getId().string()), request});
968 requestsList.push_back(requestList);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700969
970 SurfaceMap surfaceMap;
971 camera_metadata_ro_entry streams = request.find(ANDROID_REQUEST_OUTPUT_STREAMS);
972 // With no surface list passed in, stream and surface will have 1-to-1
973 // mapping. So the surface index is 0 for each stream in the surfaceMap.
974 for (size_t i = 0; i < streams.count; i++) {
975 surfaceMap[streams.data.i32[i]].push_back(0);
976 }
977 surfaceMaps.push_back(surfaceMap);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800978}
979
Jianing Wei90e59c92014-03-12 18:29:36 -0700980status_t Camera3Device::submitRequestsHelper(
Emilian Peevaebbe412018-01-15 13:53:24 +0000981 const List<const PhysicalCameraSettingsList> &requests,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700982 const std::list<const SurfaceMap> &surfaceMaps,
983 bool repeating,
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700984 /*out*/
985 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700986 ATRACE_CALL();
Shuzhen Wang316781a2020-08-18 18:11:01 -0700987 nsecs_t requestTimeNs = systemTime();
988
Jianing Wei90e59c92014-03-12 18:29:36 -0700989 Mutex::Autolock il(mInterfaceLock);
990 Mutex::Autolock l(mLock);
991
992 status_t res = checkStatusOkToCaptureLocked();
993 if (res != OK) {
994 // error logged by previous call
995 return res;
996 }
997
998 RequestList requestList;
999
Shuzhen Wang0129d522016-10-30 22:43:41 -07001000 res = convertMetadataListToRequestListLocked(requests, surfaceMaps,
Shuzhen Wang316781a2020-08-18 18:11:01 -07001001 repeating, requestTimeNs, /*out*/&requestList);
Jianing Wei90e59c92014-03-12 18:29:36 -07001002 if (res != OK) {
1003 // error logged by previous call
1004 return res;
1005 }
1006
1007 if (repeating) {
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07001008 res = mRequestThread->setRepeatingRequests(requestList, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -07001009 } else {
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07001010 res = mRequestThread->queueRequestList(requestList, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -07001011 }
1012
1013 if (res == OK) {
1014 waitUntilStateThenRelock(/*active*/true, kActiveTimeout);
1015 if (res != OK) {
1016 SET_ERR_L("Can't transition to active in %f seconds!",
1017 kActiveTimeout/1e9);
1018 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001019 ALOGV("Camera %s: Capture request %" PRId32 " enqueued", mId.string(),
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07001020 (*(requestList.begin()))->mResultExtras.requestId);
Jianing Wei90e59c92014-03-12 18:29:36 -07001021 } else {
1022 CLOGE("Cannot queue request. Impossible.");
1023 return BAD_VALUE;
1024 }
1025
1026 return res;
1027}
1028
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001029hardware::Return<void> Camera3Device::requestStreamBuffers(
1030 const hardware::hidl_vec<hardware::camera::device::V3_5::BufferRequest>& bufReqs,
1031 requestStreamBuffers_cb _hidl_cb) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001032 RequestBufferStates states {
Shuzhen Wang316781a2020-08-18 18:11:01 -07001033 mId, mRequestBufferInterfaceLock, mUseHalBufManager, mOutputStreams, mSessionStatsBuilder,
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001034 *this, *mInterface, *this};
1035 camera3::requestStreamBuffers(states, bufReqs, _hidl_cb);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001036 return hardware::Void();
1037}
1038
1039hardware::Return<void> Camera3Device::returnStreamBuffers(
1040 const hardware::hidl_vec<hardware::camera::device::V3_2::StreamBuffer>& buffers) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001041 ReturnBufferStates states {
Shuzhen Wang316781a2020-08-18 18:11:01 -07001042 mId, mUseHalBufManager, mOutputStreams, mSessionStatsBuilder, *mInterface};
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001043 camera3::returnStreamBuffers(states, buffers);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001044 return hardware::Void();
1045}
1046
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001047hardware::Return<void> Camera3Device::processCaptureResult_3_4(
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001048 const hardware::hidl_vec<
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001049 hardware::camera::device::V3_4::CaptureResult>& results) {
Yin-Chia Yeh657c1872017-07-18 18:09:57 -07001050 // Ideally we should grab mLock, but that can lead to deadlock, and
1051 // it's not super important to get up to date value of mStatus for this
1052 // warning print, hence skipping the lock here
1053 if (mStatus == STATUS_ERROR) {
1054 // Per API contract, HAL should act as closed after device error
1055 // But mStatus can be set to error by framework as well, so just log
1056 // a warning here.
1057 ALOGW("%s: received capture result in error state.", __FUNCTION__);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07001058 }
Yifan Honga640c5a2017-04-12 16:30:31 -07001059
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001060 sp<NotificationListener> listener;
1061 {
1062 std::lock_guard<std::mutex> l(mOutputLock);
1063 listener = mListener.promote();
1064 }
1065
Yifan Honga640c5a2017-04-12 16:30:31 -07001066 if (mProcessCaptureResultLock.tryLock() != OK) {
1067 // This should never happen; it indicates a wrong client implementation
1068 // that doesn't follow the contract. But, we can be tolerant here.
1069 ALOGE("%s: callback overlapped! waiting 1s...",
1070 __FUNCTION__);
1071 if (mProcessCaptureResultLock.timedLock(1000000000 /* 1s */) != OK) {
1072 ALOGE("%s: cannot acquire lock in 1s, dropping results",
1073 __FUNCTION__);
1074 // really don't know what to do, so bail out.
1075 return hardware::Void();
1076 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001077 }
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001078 CaptureOutputStates states {
1079 mId,
Shuzhen Wangb7b42652020-05-07 11:59:02 -07001080 mInFlightLock, mLastCompletedRegularFrameNumber,
1081 mLastCompletedReprocessFrameNumber, mLastCompletedZslFrameNumber,
1082 mInFlightMap, mOutputLock, mResultQueue, mResultSignal,
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001083 mNextShutterFrameNumber,
1084 mNextReprocessShutterFrameNumber, mNextZslStillShutterFrameNumber,
1085 mNextResultFrameNumber,
1086 mNextReprocessResultFrameNumber, mNextZslStillResultFrameNumber,
1087 mUseHalBufManager, mUsePartialResult, mNeedFixupMonochromeTags,
1088 mNumPartialResults, mVendorTagId, mDeviceInfo, mPhysicalDeviceInfoMap,
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08001089 mResultMetadataQueue, mDistortionMappers, mZoomRatioMappers, mRotateAndCropMappers,
Shuzhen Wang316781a2020-08-18 18:11:01 -07001090 mTagMonitor, mInputStream, mOutputStreams, mSessionStatsBuilder, listener, *this, *this,
1091 *mInterface
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001092 };
1093
Yifan Honga640c5a2017-04-12 16:30:31 -07001094 for (const auto& result : results) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001095 processOneCaptureResultLocked(states, result.v3_2, result.physicalCameraMetadata);
Yifan Honga640c5a2017-04-12 16:30:31 -07001096 }
1097 mProcessCaptureResultLock.unlock();
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001098 return hardware::Void();
1099}
1100
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001101// Only one processCaptureResult should be called at a time, so
1102// the locks won't block. The locks are present here simply to enforce this.
1103hardware::Return<void> Camera3Device::processCaptureResult(
1104 const hardware::hidl_vec<
1105 hardware::camera::device::V3_2::CaptureResult>& results) {
1106 hardware::hidl_vec<hardware::camera::device::V3_4::PhysicalCameraMetadata> noPhysMetadata;
1107
1108 // Ideally we should grab mLock, but that can lead to deadlock, and
1109 // it's not super important to get up to date value of mStatus for this
1110 // warning print, hence skipping the lock here
1111 if (mStatus == STATUS_ERROR) {
1112 // Per API contract, HAL should act as closed after device error
1113 // But mStatus can be set to error by framework as well, so just log
1114 // a warning here.
1115 ALOGW("%s: received capture result in error state.", __FUNCTION__);
1116 }
1117
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001118 sp<NotificationListener> listener;
1119 {
1120 std::lock_guard<std::mutex> l(mOutputLock);
1121 listener = mListener.promote();
1122 }
1123
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001124 if (mProcessCaptureResultLock.tryLock() != OK) {
1125 // This should never happen; it indicates a wrong client implementation
1126 // that doesn't follow the contract. But, we can be tolerant here.
1127 ALOGE("%s: callback overlapped! waiting 1s...",
1128 __FUNCTION__);
1129 if (mProcessCaptureResultLock.timedLock(1000000000 /* 1s */) != OK) {
1130 ALOGE("%s: cannot acquire lock in 1s, dropping results",
1131 __FUNCTION__);
1132 // really don't know what to do, so bail out.
1133 return hardware::Void();
1134 }
1135 }
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001136
1137 CaptureOutputStates states {
1138 mId,
Shuzhen Wangb7b42652020-05-07 11:59:02 -07001139 mInFlightLock, mLastCompletedRegularFrameNumber,
1140 mLastCompletedReprocessFrameNumber, mLastCompletedZslFrameNumber,
1141 mInFlightMap, mOutputLock, mResultQueue, mResultSignal,
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001142 mNextShutterFrameNumber,
1143 mNextReprocessShutterFrameNumber, mNextZslStillShutterFrameNumber,
1144 mNextResultFrameNumber,
1145 mNextReprocessResultFrameNumber, mNextZslStillResultFrameNumber,
1146 mUseHalBufManager, mUsePartialResult, mNeedFixupMonochromeTags,
1147 mNumPartialResults, mVendorTagId, mDeviceInfo, mPhysicalDeviceInfoMap,
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08001148 mResultMetadataQueue, mDistortionMappers, mZoomRatioMappers, mRotateAndCropMappers,
Shuzhen Wang316781a2020-08-18 18:11:01 -07001149 mTagMonitor, mInputStream, mOutputStreams, mSessionStatsBuilder, listener, *this, *this,
1150 *mInterface
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001151 };
1152
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001153 for (const auto& result : results) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001154 processOneCaptureResultLocked(states, result, noPhysMetadata);
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001155 }
1156 mProcessCaptureResultLock.unlock();
1157 return hardware::Void();
1158}
1159
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001160hardware::Return<void> Camera3Device::notify(
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001161 const hardware::hidl_vec<hardware::camera::device::V3_2::NotifyMsg>& msgs) {
Yin-Chia Yeh657c1872017-07-18 18:09:57 -07001162 // Ideally we should grab mLock, but that can lead to deadlock, and
1163 // it's not super important to get up to date value of mStatus for this
1164 // warning print, hence skipping the lock here
1165 if (mStatus == STATUS_ERROR) {
1166 // Per API contract, HAL should act as closed after device error
1167 // But mStatus can be set to error by framework as well, so just log
1168 // a warning here.
1169 ALOGW("%s: received notify message in error state.", __FUNCTION__);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07001170 }
Yin-Chia Yeh657c1872017-07-18 18:09:57 -07001171
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001172 sp<NotificationListener> listener;
1173 {
1174 std::lock_guard<std::mutex> l(mOutputLock);
1175 listener = mListener.promote();
1176 }
1177
1178 CaptureOutputStates states {
1179 mId,
Shuzhen Wangb7b42652020-05-07 11:59:02 -07001180 mInFlightLock, mLastCompletedRegularFrameNumber,
1181 mLastCompletedReprocessFrameNumber, mLastCompletedZslFrameNumber,
1182 mInFlightMap, mOutputLock, mResultQueue, mResultSignal,
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001183 mNextShutterFrameNumber,
1184 mNextReprocessShutterFrameNumber, mNextZslStillShutterFrameNumber,
1185 mNextResultFrameNumber,
1186 mNextReprocessResultFrameNumber, mNextZslStillResultFrameNumber,
1187 mUseHalBufManager, mUsePartialResult, mNeedFixupMonochromeTags,
1188 mNumPartialResults, mVendorTagId, mDeviceInfo, mPhysicalDeviceInfoMap,
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08001189 mResultMetadataQueue, mDistortionMappers, mZoomRatioMappers, mRotateAndCropMappers,
Shuzhen Wang316781a2020-08-18 18:11:01 -07001190 mTagMonitor, mInputStream, mOutputStreams, mSessionStatsBuilder, listener, *this, *this,
1191 *mInterface
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001192 };
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001193 for (const auto& msg : msgs) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001194 camera3::notify(states, msg);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001195 }
1196 return hardware::Void();
1197}
1198
Emilian Peevaebbe412018-01-15 13:53:24 +00001199status_t Camera3Device::captureList(const List<const PhysicalCameraSettingsList> &requestsList,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001200 const std::list<const SurfaceMap> &surfaceMaps,
Jianing Weicb0652e2014-03-12 18:29:36 -07001201 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -07001202 ATRACE_CALL();
1203
Emilian Peevaebbe412018-01-15 13:53:24 +00001204 return submitRequestsHelper(requestsList, surfaceMaps, /*repeating*/false, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -07001205}
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001206
Jianing Weicb0652e2014-03-12 18:29:36 -07001207status_t Camera3Device::setStreamingRequest(const CameraMetadata &request,
1208 int64_t* /*lastFrameNumber*/) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001209 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001210
Emilian Peevaebbe412018-01-15 13:53:24 +00001211 List<const PhysicalCameraSettingsList> requestsList;
Shuzhen Wang0129d522016-10-30 22:43:41 -07001212 std::list<const SurfaceMap> surfaceMaps;
Emilian Peevaebbe412018-01-15 13:53:24 +00001213 convertToRequestList(requestsList, surfaceMaps, request);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001214
Emilian Peevaebbe412018-01-15 13:53:24 +00001215 return setStreamingRequestList(requestsList, /*surfaceMap*/surfaceMaps,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001216 /*lastFrameNumber*/NULL);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001217}
1218
Emilian Peevaebbe412018-01-15 13:53:24 +00001219status_t Camera3Device::setStreamingRequestList(
1220 const List<const PhysicalCameraSettingsList> &requestsList,
1221 const std::list<const SurfaceMap> &surfaceMaps, int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -07001222 ATRACE_CALL();
1223
Emilian Peevaebbe412018-01-15 13:53:24 +00001224 return submitRequestsHelper(requestsList, surfaceMaps, /*repeating*/true, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -07001225}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001226
1227sp<Camera3Device::CaptureRequest> Camera3Device::setUpRequestLocked(
Emilian Peevaebbe412018-01-15 13:53:24 +00001228 const PhysicalCameraSettingsList &request, const SurfaceMap &surfaceMap) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001229 status_t res;
1230
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001231 if (mStatus == STATUS_UNCONFIGURED || mNeedConfig) {
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08001232 // This point should only be reached via API1 (API2 must explicitly call configureStreams)
1233 // so unilaterally select normal operating mode.
Emilian Peevaebbe412018-01-15 13:53:24 +00001234 res = filterParamsAndConfigureLocked(request.begin()->metadata,
Emilian Peevf4816702020-04-03 15:44:51 -07001235 CAMERA_STREAM_CONFIGURATION_NORMAL_MODE);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001236 // Stream configuration failed. Client might try other configuraitons.
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001237 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001238 CLOGE("Can't set up streams: %s (%d)", strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001239 return NULL;
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001240 } else if (mStatus == STATUS_UNCONFIGURED) {
1241 // Stream configuration successfully configure to empty stream configuration.
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001242 CLOGE("No streams configured");
1243 return NULL;
1244 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001245 }
1246
Shuzhen Wang0129d522016-10-30 22:43:41 -07001247 sp<CaptureRequest> newRequest = createCaptureRequest(request, surfaceMap);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001248 return newRequest;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001249}
1250
Jianing Weicb0652e2014-03-12 18:29:36 -07001251status_t Camera3Device::clearStreamingRequest(int64_t *lastFrameNumber) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001252 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001253 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001254 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001255
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001256 switch (mStatus) {
1257 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001258 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001259 return INVALID_OPERATION;
1260 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001261 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001262 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001263 case STATUS_UNCONFIGURED:
1264 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001265 case STATUS_ACTIVE:
1266 // OK
1267 break;
1268 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001269 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001270 return INVALID_OPERATION;
1271 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001272 ALOGV("Camera %s: Clearing repeating request", mId.string());
Jianing Weicb0652e2014-03-12 18:29:36 -07001273
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07001274 return mRequestThread->clearRepeatingRequests(lastFrameNumber);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001275}
1276
1277status_t Camera3Device::waitUntilRequestReceived(int32_t requestId, nsecs_t timeout) {
1278 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001279 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001280
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001281 return mRequestThread->waitUntilRequestProcessed(requestId, timeout);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001282}
1283
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001284status_t Camera3Device::createInputStream(
Shuzhen Wang83bff122020-11-20 15:51:39 -08001285 uint32_t width, uint32_t height, int format, bool isMultiResolution, int *id) {
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001286 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001287 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001288 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001289 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001290 ALOGV("Camera %s: Creating new input stream %d: %d x %d, format %d",
1291 mId.string(), mNextStreamId, width, height, format);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001292
1293 status_t res;
1294 bool wasActive = false;
1295
1296 switch (mStatus) {
1297 case STATUS_ERROR:
1298 ALOGE("%s: Device has encountered a serious error", __FUNCTION__);
1299 return INVALID_OPERATION;
1300 case STATUS_UNINITIALIZED:
1301 ALOGE("%s: Device not initialized", __FUNCTION__);
1302 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001303 case STATUS_UNCONFIGURED:
1304 case STATUS_CONFIGURED:
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001305 // OK
1306 break;
1307 case STATUS_ACTIVE:
1308 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001309 res = internalPauseAndWaitLocked(maxExpectedDuration);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001310 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001311 SET_ERR_L("Can't pause captures to reconfigure streams!");
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001312 return res;
1313 }
1314 wasActive = true;
1315 break;
1316 default:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001317 SET_ERR_L("%s: Unexpected status: %d", mStatus);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001318 return INVALID_OPERATION;
1319 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001320 assert(mStatus != STATUS_ACTIVE);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001321
1322 if (mInputStream != 0) {
1323 ALOGE("%s: Cannot create more than 1 input stream", __FUNCTION__);
1324 return INVALID_OPERATION;
1325 }
1326
1327 sp<Camera3InputStream> newStream = new Camera3InputStream(mNextStreamId,
1328 width, height, format);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001329 newStream->setStatusTracker(mStatusTracker);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001330
1331 mInputStream = newStream;
Shuzhen Wang83bff122020-11-20 15:51:39 -08001332 mIsInputStreamMultiResolution = isMultiResolution;
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001333
1334 *id = mNextStreamId++;
1335
1336 // Continue captures if active at start
1337 if (wasActive) {
1338 ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001339 // Reuse current operating mode and session parameters for new stream config
1340 res = configureStreamsLocked(mOperatingMode, mSessionParams);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001341 if (res != OK) {
1342 ALOGE("%s: Can't reconfigure device for new stream %d: %s (%d)",
1343 __FUNCTION__, mNextStreamId, strerror(-res), res);
1344 return res;
1345 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001346 internalResumeLocked();
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001347 }
1348
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001349 ALOGV("Camera %s: Created input stream", mId.string());
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001350 return OK;
1351}
1352
Eino-Ville Talvala727d1722015-06-09 13:44:19 -07001353status_t Camera3Device::createStream(sp<Surface> consumer,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001354 uint32_t width, uint32_t height, int format,
Emilian Peevf4816702020-04-03 15:44:51 -07001355 android_dataspace dataSpace, camera_stream_rotation_t rotation, int *id,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001356 const String8& physicalCameraId,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001357 const std::unordered_set<int32_t> &sensorPixelModesUsed,
1358 std::vector<int> *surfaceIds, int streamSetId, bool isShared, bool isMultiResolution,
1359 uint64_t consumerUsage) {
Shuzhen Wang0129d522016-10-30 22:43:41 -07001360 ATRACE_CALL();
1361
1362 if (consumer == nullptr) {
1363 ALOGE("%s: consumer must not be null", __FUNCTION__);
1364 return BAD_VALUE;
1365 }
1366
1367 std::vector<sp<Surface>> consumers;
1368 consumers.push_back(consumer);
1369
1370 return createStream(consumers, /*hasDeferredConsumer*/ false, width, height,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001371 format, dataSpace, rotation, id, physicalCameraId, sensorPixelModesUsed, surfaceIds,
1372 streamSetId, isShared, isMultiResolution, consumerUsage);
1373}
1374
1375static bool isRawFormat(int format) {
1376 switch (format) {
1377 case HAL_PIXEL_FORMAT_RAW16:
1378 case HAL_PIXEL_FORMAT_RAW12:
1379 case HAL_PIXEL_FORMAT_RAW10:
1380 case HAL_PIXEL_FORMAT_RAW_OPAQUE:
1381 return true;
1382 default:
1383 return false;
1384 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001385}
1386
1387status_t Camera3Device::createStream(const std::vector<sp<Surface>>& consumers,
1388 bool hasDeferredConsumer, uint32_t width, uint32_t height, int format,
Emilian Peevf4816702020-04-03 15:44:51 -07001389 android_dataspace dataSpace, camera_stream_rotation_t rotation, int *id,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001390 const String8& physicalCameraId, const std::unordered_set<int32_t> &sensorPixelModesUsed,
Shuzhen Wang83bff122020-11-20 15:51:39 -08001391 std::vector<int> *surfaceIds, int streamSetId, bool isShared, bool isMultiResolution,
1392 uint64_t consumerUsage) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001393 ATRACE_CALL();
Emilian Peev40ead602017-09-26 15:46:36 +01001394
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001395 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001396 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001397 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001398 ALOGV("Camera %s: Creating new stream %d: %d x %d, format %d, dataspace %d rotation %d"
Shuzhen Wang83bff122020-11-20 15:51:39 -08001399 " consumer usage %" PRIu64 ", isShared %d, physicalCameraId %s, isMultiResolution %d",
1400 mId.string(), mNextStreamId, width, height, format, dataSpace, rotation,
1401 consumerUsage, isShared, physicalCameraId.string(), isMultiResolution);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001402
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001403 status_t res;
1404 bool wasActive = false;
1405
1406 switch (mStatus) {
1407 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001408 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001409 return INVALID_OPERATION;
1410 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001411 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001412 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001413 case STATUS_UNCONFIGURED:
1414 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001415 // OK
1416 break;
1417 case STATUS_ACTIVE:
1418 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001419 res = internalPauseAndWaitLocked(maxExpectedDuration);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001420 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001421 SET_ERR_L("Can't pause captures to reconfigure streams!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001422 return res;
1423 }
1424 wasActive = true;
1425 break;
1426 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001427 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001428 return INVALID_OPERATION;
1429 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001430 assert(mStatus != STATUS_ACTIVE);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001431
1432 sp<Camera3OutputStream> newStream;
Zhijun He5d677d12016-05-29 16:52:39 -07001433
Shuzhen Wang0129d522016-10-30 22:43:41 -07001434 if (consumers.size() == 0 && !hasDeferredConsumer) {
1435 ALOGE("%s: Number of consumers cannot be smaller than 1", __FUNCTION__);
1436 return BAD_VALUE;
1437 }
Zhijun He5d677d12016-05-29 16:52:39 -07001438
Shuzhen Wang0129d522016-10-30 22:43:41 -07001439 if (hasDeferredConsumer && format != HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
Zhijun He5d677d12016-05-29 16:52:39 -07001440 ALOGE("Deferred consumer stream creation only support IMPLEMENTATION_DEFINED format");
1441 return BAD_VALUE;
1442 }
1443
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001444 if (isRawFormat(format) && sensorPixelModesUsed.size() > 1) {
1445 // We can't use one stream with a raw format in both sensor pixel modes since its going to
1446 // be found in only one sensor pixel mode.
1447 ALOGE("%s: RAW opaque stream cannot be used with > 1 sensor pixel modes", __FUNCTION__);
1448 return BAD_VALUE;
1449 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001450 if (format == HAL_PIXEL_FORMAT_BLOB) {
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -07001451 ssize_t blobBufferSize;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001452 if (dataSpace == HAL_DATASPACE_DEPTH) {
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -07001453 blobBufferSize = getPointCloudBufferSize();
1454 if (blobBufferSize <= 0) {
1455 SET_ERR_L("Invalid point cloud buffer size %zd", blobBufferSize);
1456 return BAD_VALUE;
1457 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001458 } else if (dataSpace == static_cast<android_dataspace>(HAL_DATASPACE_JPEG_APP_SEGMENTS)) {
1459 blobBufferSize = width * height;
1460 } else {
1461 blobBufferSize = getJpegBufferSize(width, height);
1462 if (blobBufferSize <= 0) {
1463 SET_ERR_L("Invalid jpeg buffer size %zd", blobBufferSize);
1464 return BAD_VALUE;
1465 }
Zhijun Hef7da0962014-04-24 13:27:56 -07001466 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001467 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001468 width, height, blobBufferSize, format, dataSpace, rotation,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001469 mTimestampOffset, physicalCameraId, sensorPixelModesUsed, streamSetId,
1470 isMultiResolution);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -08001471 } else if (format == HAL_PIXEL_FORMAT_RAW_OPAQUE) {
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001472 bool maxResolution =
1473 sensorPixelModesUsed.find(ANDROID_SENSOR_PIXEL_MODE_MAXIMUM_RESOLUTION) !=
1474 sensorPixelModesUsed.end();
1475 ssize_t rawOpaqueBufferSize = getRawOpaqueBufferSize(width, height, maxResolution);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -08001476 if (rawOpaqueBufferSize <= 0) {
1477 SET_ERR_L("Invalid RAW opaque buffer size %zd", rawOpaqueBufferSize);
1478 return BAD_VALUE;
1479 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001480 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001481 width, height, rawOpaqueBufferSize, format, dataSpace, rotation,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001482 mTimestampOffset, physicalCameraId, sensorPixelModesUsed, streamSetId,
1483 isMultiResolution);
Shuzhen Wang758c2152017-01-10 18:26:18 -08001484 } else if (isShared) {
1485 newStream = new Camera3SharedOutputStream(mNextStreamId, consumers,
1486 width, height, format, consumerUsage, dataSpace, rotation,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001487 mTimestampOffset, physicalCameraId, sensorPixelModesUsed, streamSetId,
1488 mUseHalBufManager);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001489 } else if (consumers.size() == 0 && hasDeferredConsumer) {
Zhijun He5d677d12016-05-29 16:52:39 -07001490 newStream = new Camera3OutputStream(mNextStreamId,
1491 width, height, format, consumerUsage, dataSpace, rotation,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001492 mTimestampOffset, physicalCameraId, sensorPixelModesUsed, streamSetId,
1493 isMultiResolution);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001494 } else {
Shuzhen Wang0129d522016-10-30 22:43:41 -07001495 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001496 width, height, format, dataSpace, rotation,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001497 mTimestampOffset, physicalCameraId, sensorPixelModesUsed, streamSetId,
1498 isMultiResolution);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001499 }
Emilian Peev40ead602017-09-26 15:46:36 +01001500
1501 size_t consumerCount = consumers.size();
1502 for (size_t i = 0; i < consumerCount; i++) {
1503 int id = newStream->getSurfaceId(consumers[i]);
1504 if (id < 0) {
1505 SET_ERR_L("Invalid surface id");
1506 return BAD_VALUE;
1507 }
1508 if (surfaceIds != nullptr) {
1509 surfaceIds->push_back(id);
1510 }
1511 }
1512
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001513 newStream->setStatusTracker(mStatusTracker);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001514
Emilian Peev08dd2452017-04-06 16:55:14 +01001515 newStream->setBufferManager(mBufferManager);
Zhijun He125684a2015-12-26 15:07:30 -08001516
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08001517 newStream->setImageDumpMask(mImageDumpMask);
1518
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001519 res = mOutputStreams.add(mNextStreamId, newStream);
1520 if (res < 0) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001521 SET_ERR_L("Can't add new stream to set: %s (%d)", strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001522 return res;
1523 }
1524
Shuzhen Wang316781a2020-08-18 18:11:01 -07001525 mSessionStatsBuilder.addStream(mNextStreamId);
1526
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001527 *id = mNextStreamId++;
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07001528 mNeedConfig = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001529
1530 // Continue captures if active at start
1531 if (wasActive) {
1532 ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001533 // Reuse current operating mode and session parameters for new stream config
1534 res = configureStreamsLocked(mOperatingMode, mSessionParams);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001535 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001536 CLOGE("Can't reconfigure device for new stream %d: %s (%d)",
1537 mNextStreamId, strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001538 return res;
1539 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001540 internalResumeLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001541 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001542 ALOGV("Camera %s: Created new stream", mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001543 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001544}
1545
Emilian Peev710c1422017-08-30 11:19:38 +01001546status_t Camera3Device::getStreamInfo(int id, StreamInfo *streamInfo) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001547 ATRACE_CALL();
Emilian Peev710c1422017-08-30 11:19:38 +01001548 if (nullptr == streamInfo) {
1549 return BAD_VALUE;
1550 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001551 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001552 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001553
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001554 switch (mStatus) {
1555 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001556 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001557 return INVALID_OPERATION;
1558 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001559 CLOGE("Device not initialized!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001560 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001561 case STATUS_UNCONFIGURED:
1562 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001563 case STATUS_ACTIVE:
1564 // OK
1565 break;
1566 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001567 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001568 return INVALID_OPERATION;
1569 }
1570
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001571 sp<Camera3StreamInterface> stream = mOutputStreams.get(id);
1572 if (stream == nullptr) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001573 CLOGE("Stream %d is unknown", id);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001574 return BAD_VALUE;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001575 }
1576
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001577 streamInfo->width = stream->getWidth();
1578 streamInfo->height = stream->getHeight();
1579 streamInfo->format = stream->getFormat();
1580 streamInfo->dataSpace = stream->getDataSpace();
1581 streamInfo->formatOverridden = stream->isFormatOverridden();
1582 streamInfo->originalFormat = stream->getOriginalFormat();
1583 streamInfo->dataSpaceOverridden = stream->isDataSpaceOverridden();
1584 streamInfo->originalDataSpace = stream->getOriginalDataSpace();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001585 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001586}
1587
1588status_t Camera3Device::setStreamTransform(int id,
1589 int transform) {
1590 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001591 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001592 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001593
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001594 switch (mStatus) {
1595 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001596 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001597 return INVALID_OPERATION;
1598 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001599 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001600 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001601 case STATUS_UNCONFIGURED:
1602 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001603 case STATUS_ACTIVE:
1604 // OK
1605 break;
1606 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001607 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001608 return INVALID_OPERATION;
1609 }
1610
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001611 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(id);
1612 if (stream == nullptr) {
1613 CLOGE("Stream %d does not exist", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001614 return BAD_VALUE;
1615 }
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001616 return stream->setTransform(transform);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001617}
1618
1619status_t Camera3Device::deleteStream(int id) {
1620 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001621 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001622 Mutex::Autolock l(mLock);
1623 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001624
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001625 ALOGV("%s: Camera %s: Deleting stream %d", __FUNCTION__, mId.string(), id);
Igor Murashkine2172be2013-05-28 15:31:39 -07001626
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001627 // CameraDevice semantics require device to already be idle before
1628 // deleteStream is called, unlike for createStream.
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001629 if (mStatus == STATUS_ACTIVE) {
Yin-Chia Yeh693047d2018-03-08 12:14:19 -08001630 ALOGW("%s: Camera %s: Device not idle", __FUNCTION__, mId.string());
Igor Murashkin52827132013-05-13 14:53:44 -07001631 return -EBUSY;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001632 }
1633
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07001634 if (mStatus == STATUS_ERROR) {
1635 ALOGW("%s: Camera %s: deleteStream not allowed in ERROR state",
1636 __FUNCTION__, mId.string());
1637 return -EBUSY;
1638 }
1639
Igor Murashkin2fba5842013-04-22 14:03:54 -07001640 sp<Camera3StreamInterface> deletedStream;
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001641 sp<Camera3StreamInterface> stream = mOutputStreams.get(id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001642 if (mInputStream != NULL && id == mInputStream->getId()) {
1643 deletedStream = mInputStream;
1644 mInputStream.clear();
1645 } else {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001646 if (stream == nullptr) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001647 CLOGE("Stream %d does not exist", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001648 return BAD_VALUE;
1649 }
Shuzhen Wang316781a2020-08-18 18:11:01 -07001650 mSessionStatsBuilder.removeStream(id);
Zhijun He5f446352014-01-22 09:49:33 -08001651 }
1652
1653 // Delete output stream or the output part of a bi-directional stream.
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001654 if (stream != nullptr) {
1655 deletedStream = stream;
1656 mOutputStreams.remove(id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001657 }
1658
1659 // Free up the stream endpoint so that it can be used by some other stream
1660 res = deletedStream->disconnect();
1661 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001662 SET_ERR_L("Can't disconnect deleted stream %d", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001663 // fall through since we want to still list the stream as deleted.
1664 }
1665 mDeletedStreams.add(deletedStream);
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07001666 mNeedConfig = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001667
1668 return res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001669}
1670
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001671status_t Camera3Device::configureStreams(const CameraMetadata& sessionParams, int operatingMode) {
Igor Murashkine2d167e2014-08-19 16:19:59 -07001672 ATRACE_CALL();
1673 ALOGV("%s: E", __FUNCTION__);
1674
1675 Mutex::Autolock il(mInterfaceLock);
1676 Mutex::Autolock l(mLock);
Chien-Yu Chen17338fc2015-06-18 16:30:12 -07001677
Emilian Peev811d2952018-05-25 11:08:40 +01001678 // In case the client doesn't include any session parameter, try a
1679 // speculative configuration using the values from the last cached
1680 // default request.
1681 if (sessionParams.isEmpty() &&
Emilian Peevf4816702020-04-03 15:44:51 -07001682 ((mLastTemplateId > 0) && (mLastTemplateId < CAMERA_TEMPLATE_COUNT)) &&
Emilian Peev811d2952018-05-25 11:08:40 +01001683 (!mRequestTemplateCache[mLastTemplateId].isEmpty())) {
1684 ALOGV("%s: Speculative session param configuration with template id: %d", __func__,
1685 mLastTemplateId);
1686 return filterParamsAndConfigureLocked(mRequestTemplateCache[mLastTemplateId],
1687 operatingMode);
1688 }
1689
Emilian Peevac3ce6c2017-12-12 15:27:02 +00001690 return filterParamsAndConfigureLocked(sessionParams, operatingMode);
1691}
1692
1693status_t Camera3Device::filterParamsAndConfigureLocked(const CameraMetadata& sessionParams,
1694 int operatingMode) {
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001695 //Filter out any incoming session parameters
1696 const CameraMetadata params(sessionParams);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001697 camera_metadata_entry_t availableSessionKeys = mDeviceInfo.find(
1698 ANDROID_REQUEST_AVAILABLE_SESSION_KEYS);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00001699 CameraMetadata filteredParams(availableSessionKeys.count);
1700 camera_metadata_t *meta = const_cast<camera_metadata_t *>(
1701 filteredParams.getAndLock());
1702 set_camera_metadata_vendor_id(meta, mVendorTagId);
1703 filteredParams.unlock(meta);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001704 if (availableSessionKeys.count > 0) {
1705 for (size_t i = 0; i < availableSessionKeys.count; i++) {
1706 camera_metadata_ro_entry entry = params.find(
1707 availableSessionKeys.data.i32[i]);
1708 if (entry.count > 0) {
1709 filteredParams.update(entry);
1710 }
1711 }
1712 }
1713
1714 return configureStreamsLocked(operatingMode, filteredParams);
Igor Murashkine2d167e2014-08-19 16:19:59 -07001715}
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001716
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07001717status_t Camera3Device::getInputBufferProducer(
1718 sp<IGraphicBufferProducer> *producer) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07001719 ATRACE_CALL();
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07001720 Mutex::Autolock il(mInterfaceLock);
1721 Mutex::Autolock l(mLock);
1722
1723 if (producer == NULL) {
1724 return BAD_VALUE;
1725 } else if (mInputStream == NULL) {
1726 return INVALID_OPERATION;
1727 }
1728
1729 return mInputStream->getInputBufferProducer(producer);
1730}
1731
Emilian Peevf4816702020-04-03 15:44:51 -07001732status_t Camera3Device::createDefaultRequest(camera_request_template_t templateId,
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001733 CameraMetadata *request) {
1734 ATRACE_CALL();
Alex Rayfe7e0c62013-05-30 00:12:13 -07001735 ALOGV("%s: for template %d", __FUNCTION__, templateId);
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08001736
Emilian Peevf4816702020-04-03 15:44:51 -07001737 if (templateId <= 0 || templateId >= CAMERA_TEMPLATE_COUNT) {
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08001738 android_errorWriteWithInfoLog(CameraService::SN_EVENT_LOG_ID, "26866110",
Jayant Chowdhary12361932018-08-27 14:46:13 -07001739 CameraThreadState::getCallingUid(), nullptr, 0);
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08001740 return BAD_VALUE;
1741 }
1742
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001743 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001744
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001745 {
1746 Mutex::Autolock l(mLock);
1747 switch (mStatus) {
1748 case STATUS_ERROR:
1749 CLOGE("Device has encountered a serious error");
1750 return INVALID_OPERATION;
1751 case STATUS_UNINITIALIZED:
1752 CLOGE("Device is not initialized!");
1753 return INVALID_OPERATION;
1754 case STATUS_UNCONFIGURED:
1755 case STATUS_CONFIGURED:
1756 case STATUS_ACTIVE:
1757 // OK
1758 break;
1759 default:
1760 SET_ERR_L("Unexpected status: %d", mStatus);
1761 return INVALID_OPERATION;
1762 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001763
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001764 if (!mRequestTemplateCache[templateId].isEmpty()) {
1765 *request = mRequestTemplateCache[templateId];
Emilian Peev811d2952018-05-25 11:08:40 +01001766 mLastTemplateId = templateId;
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001767 return OK;
1768 }
Zhijun Hea1530f12014-09-14 12:44:20 -07001769 }
1770
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001771 camera_metadata_t *rawRequest;
1772 status_t res = mInterface->constructDefaultRequestSettings(
Emilian Peevf4816702020-04-03 15:44:51 -07001773 (camera_request_template_t) templateId, &rawRequest);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001774
1775 {
1776 Mutex::Autolock l(mLock);
1777 if (res == BAD_VALUE) {
1778 ALOGI("%s: template %d is not supported on this camera device",
1779 __FUNCTION__, templateId);
1780 return res;
1781 } else if (res != OK) {
1782 CLOGE("Unable to construct request template %d: %s (%d)",
1783 templateId, strerror(-res), res);
1784 return res;
1785 }
1786
1787 set_camera_metadata_vendor_id(rawRequest, mVendorTagId);
1788 mRequestTemplateCache[templateId].acquire(rawRequest);
1789
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08001790 // Override the template request with zoomRatioMapper
1791 res = mZoomRatioMappers[mId.c_str()].initZoomRatioInTemplate(
1792 &mRequestTemplateCache[templateId]);
1793 if (res != OK) {
1794 CLOGE("Failed to update zoom ratio for template %d: %s (%d)",
1795 templateId, strerror(-res), res);
1796 return res;
1797 }
1798
Shuzhen Wangd25dc972020-03-24 17:11:43 -07001799 // Fill in JPEG_QUALITY if not available
1800 if (!mRequestTemplateCache[templateId].exists(ANDROID_JPEG_QUALITY)) {
1801 static const uint8_t kDefaultJpegQuality = 95;
1802 mRequestTemplateCache[templateId].update(ANDROID_JPEG_QUALITY,
1803 &kDefaultJpegQuality, 1);
1804 }
1805
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001806 *request = mRequestTemplateCache[templateId];
Emilian Peev811d2952018-05-25 11:08:40 +01001807 mLastTemplateId = templateId;
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001808 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001809 return OK;
1810}
1811
1812status_t Camera3Device::waitUntilDrained() {
1813 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001814 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001815 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001816 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001817
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001818 return waitUntilDrainedLocked(maxExpectedDuration);
Zhijun He69a37482014-03-23 18:44:49 -07001819}
1820
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001821status_t Camera3Device::waitUntilDrainedLocked(nsecs_t maxExpectedDuration) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001822 switch (mStatus) {
1823 case STATUS_UNINITIALIZED:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001824 case STATUS_UNCONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001825 ALOGV("%s: Already idle", __FUNCTION__);
1826 return OK;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001827 case STATUS_CONFIGURED:
1828 // To avoid race conditions, check with tracker to be sure
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001829 case STATUS_ERROR:
1830 case STATUS_ACTIVE:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001831 // Need to verify shut down
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001832 break;
1833 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001834 SET_ERR_L("Unexpected status: %d",mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001835 return INVALID_OPERATION;
1836 }
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07001837 ALOGV("%s: Camera %s: Waiting until idle (%" PRIi64 "ns)", __FUNCTION__, mId.string(),
1838 maxExpectedDuration);
1839 status_t res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
Eino-Ville Talvala9c8a0912014-09-14 14:52:19 -07001840 if (res != OK) {
Yin-Chia Yeh87b3ec02019-06-03 10:44:39 -07001841 mStatusTracker->dumpActiveComponents();
Eino-Ville Talvala9c8a0912014-09-14 14:52:19 -07001842 SET_ERR_L("Error waiting for HAL to drain: %s (%d)", strerror(-res),
1843 res);
1844 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001845 return res;
1846}
1847
Ruben Brunk183f0562015-08-12 12:55:02 -07001848void Camera3Device::internalUpdateStatusLocked(Status status) {
1849 mStatus = status;
1850 mRecentStatusUpdates.add(mStatus);
1851 mStatusChanged.broadcast();
1852}
1853
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001854// Pause to reconfigure
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001855status_t Camera3Device::internalPauseAndWaitLocked(nsecs_t maxExpectedDuration) {
Emilian Peeve86358b2019-02-15 13:51:39 -08001856 if (mRequestThread.get() != nullptr) {
1857 mRequestThread->setPaused(true);
1858 } else {
1859 return NO_INIT;
1860 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001861
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07001862 ALOGV("%s: Camera %s: Internal wait until idle (% " PRIi64 " ns)", __FUNCTION__, mId.string(),
1863 maxExpectedDuration);
1864 status_t res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001865 if (res != OK) {
1866 SET_ERR_L("Can't idle device in %f seconds!",
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07001867 maxExpectedDuration/1e9);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001868 }
1869
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001870 return res;
1871}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001872
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001873// Resume after internalPauseAndWaitLocked
1874status_t Camera3Device::internalResumeLocked() {
1875 status_t res;
1876
1877 mRequestThread->setPaused(false);
1878
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08001879 ALOGV("%s: Camera %s: Internal wait until active (% " PRIi64 " ns)", __FUNCTION__, mId.string(),
1880 kActiveTimeout);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001881 res = waitUntilStateThenRelock(/*active*/ true, kActiveTimeout);
1882 if (res != OK) {
1883 SET_ERR_L("Can't transition to active in %f seconds!",
1884 kActiveTimeout/1e9);
1885 }
1886 mPauseStateNotify = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001887 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001888}
1889
Ruben Brunk183f0562015-08-12 12:55:02 -07001890status_t Camera3Device::waitUntilStateThenRelock(bool active, nsecs_t timeout) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001891 status_t res = OK;
Ruben Brunk183f0562015-08-12 12:55:02 -07001892
1893 size_t startIndex = 0;
1894 if (mStatusWaiters == 0) {
1895 // Clear the list of recent statuses if there are no existing threads waiting on updates to
1896 // this status list
1897 mRecentStatusUpdates.clear();
1898 } else {
1899 // If other threads are waiting on updates to this status list, set the position of the
1900 // first element that this list will check rather than clearing the list.
1901 startIndex = mRecentStatusUpdates.size();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001902 }
1903
Ruben Brunk183f0562015-08-12 12:55:02 -07001904 mStatusWaiters++;
1905
Yin-Chia Yehe52b8fa2020-07-28 00:17:58 -07001906 bool signalPipelineDrain = false;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07001907 if (!active && mUseHalBufManager) {
1908 auto streamIds = mOutputStreams.getStreamIds();
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08001909 if (mStatus == STATUS_ACTIVE) {
1910 mRequestThread->signalPipelineDrain(streamIds);
Yin-Chia Yehe52b8fa2020-07-28 00:17:58 -07001911 signalPipelineDrain = true;
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08001912 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07001913 mRequestBufferSM.onWaitUntilIdle();
1914 }
1915
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001916 bool stateSeen = false;
1917 do {
Ruben Brunk183f0562015-08-12 12:55:02 -07001918 if (active == (mStatus == STATUS_ACTIVE)) {
1919 // Desired state is current
1920 break;
1921 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001922
1923 res = mStatusChanged.waitRelative(mLock, timeout);
1924 if (res != OK) break;
1925
Ruben Brunk183f0562015-08-12 12:55:02 -07001926 // This is impossible, but if not, could result in subtle deadlocks and invalid state
1927 // transitions.
1928 LOG_ALWAYS_FATAL_IF(startIndex > mRecentStatusUpdates.size(),
1929 "%s: Skipping status updates in Camera3Device, may result in deadlock.",
1930 __FUNCTION__);
1931
1932 // Encountered desired state since we began waiting
1933 for (size_t i = startIndex; i < mRecentStatusUpdates.size(); i++) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001934 if (active == (mRecentStatusUpdates[i] == STATUS_ACTIVE) ) {
1935 stateSeen = true;
1936 break;
1937 }
1938 }
1939 } while (!stateSeen);
1940
Yin-Chia Yehe52b8fa2020-07-28 00:17:58 -07001941 if (signalPipelineDrain) {
1942 mRequestThread->resetPipelineDrain();
1943 }
1944
Ruben Brunk183f0562015-08-12 12:55:02 -07001945 mStatusWaiters--;
1946
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001947 return res;
1948}
1949
1950
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001951status_t Camera3Device::setNotifyCallback(wp<NotificationListener> listener) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001952 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001953 std::lock_guard<std::mutex> l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001954
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001955 if (listener != NULL && mListener != NULL) {
1956 ALOGW("%s: Replacing old callback listener", __FUNCTION__);
1957 }
1958 mListener = listener;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001959 mRequestThread->setNotificationListener(listener);
1960 mPreparerThread->setNotificationListener(listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001961
1962 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001963}
1964
Eino-Ville Talvala46910bd2013-07-18 19:15:17 -07001965bool Camera3Device::willNotify3A() {
1966 return false;
1967}
1968
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001969status_t Camera3Device::waitForNextFrame(nsecs_t timeout) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07001970 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001971 std::unique_lock<std::mutex> l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001972
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001973 while (mResultQueue.empty()) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001974 auto st = mResultSignal.wait_for(l, std::chrono::nanoseconds(timeout));
1975 if (st == std::cv_status::timeout) {
1976 return TIMED_OUT;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001977 }
1978 }
1979 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001980}
1981
Jianing Weicb0652e2014-03-12 18:29:36 -07001982status_t Camera3Device::getNextResult(CaptureResult *frame) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001983 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001984 std::lock_guard<std::mutex> l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001985
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001986 if (mResultQueue.empty()) {
1987 return NOT_ENOUGH_DATA;
1988 }
1989
Jianing Weicb0652e2014-03-12 18:29:36 -07001990 if (frame == NULL) {
1991 ALOGE("%s: argument cannot be NULL", __FUNCTION__);
1992 return BAD_VALUE;
1993 }
1994
1995 CaptureResult &result = *(mResultQueue.begin());
1996 frame->mResultExtras = result.mResultExtras;
1997 frame->mMetadata.acquire(result.mMetadata);
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001998 frame->mPhysicalMetadatas = std::move(result.mPhysicalMetadatas);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001999 mResultQueue.erase(mResultQueue.begin());
2000
2001 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002002}
2003
2004status_t Camera3Device::triggerAutofocus(uint32_t id) {
2005 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002006 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002007
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002008 ALOGV("%s: Triggering autofocus, id %d", __FUNCTION__, id);
2009 // Mix-in this trigger into the next request and only the next request.
2010 RequestTrigger trigger[] = {
2011 {
2012 ANDROID_CONTROL_AF_TRIGGER,
2013 ANDROID_CONTROL_AF_TRIGGER_START
2014 },
2015 {
2016 ANDROID_CONTROL_AF_TRIGGER_ID,
2017 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07002018 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002019 };
2020
2021 return mRequestThread->queueTrigger(trigger,
2022 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002023}
2024
2025status_t Camera3Device::triggerCancelAutofocus(uint32_t id) {
2026 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002027 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002028
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002029 ALOGV("%s: Triggering cancel autofocus, id %d", __FUNCTION__, id);
2030 // Mix-in this trigger into the next request and only the next request.
2031 RequestTrigger trigger[] = {
2032 {
2033 ANDROID_CONTROL_AF_TRIGGER,
2034 ANDROID_CONTROL_AF_TRIGGER_CANCEL
2035 },
2036 {
2037 ANDROID_CONTROL_AF_TRIGGER_ID,
2038 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07002039 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002040 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002041
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002042 return mRequestThread->queueTrigger(trigger,
2043 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002044}
2045
2046status_t Camera3Device::triggerPrecaptureMetering(uint32_t id) {
2047 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002048 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002049
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002050 ALOGV("%s: Triggering precapture metering, id %d", __FUNCTION__, id);
2051 // Mix-in this trigger into the next request and only the next request.
2052 RequestTrigger trigger[] = {
2053 {
2054 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER,
2055 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_START
2056 },
2057 {
2058 ANDROID_CONTROL_AE_PRECAPTURE_ID,
2059 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07002060 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002061 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002062
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002063 return mRequestThread->queueTrigger(trigger,
2064 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002065}
2066
Jianing Weicb0652e2014-03-12 18:29:36 -07002067status_t Camera3Device::flush(int64_t *frameNumber) {
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07002068 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002069 ALOGV("%s: Camera %s: Flushing all requests", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002070 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07002071
Zhijun He7ef20392014-04-21 16:04:17 -07002072 {
2073 Mutex::Autolock l(mLock);
Emilian Peeved2ebe42018-09-25 16:59:09 +01002074
2075 // b/116514106 "disconnect()" can get called twice for the same device. The
2076 // camera device will not be initialized during the second run.
2077 if (mStatus == STATUS_UNINITIALIZED) {
2078 return OK;
2079 }
2080
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002081 mRequestThread->clear(/*out*/frameNumber);
Shuzhen Wang316781a2020-08-18 18:11:01 -07002082
2083 // Stop session and stream counter
2084 mSessionStatsBuilder.stopCounter();
Zhijun He7ef20392014-04-21 16:04:17 -07002085 }
2086
Emilian Peev08dd2452017-04-06 16:55:14 +01002087 return mRequestThread->flush();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07002088}
2089
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002090status_t Camera3Device::prepare(int streamId) {
Ruben Brunkc78ac262015-08-13 17:58:46 -07002091 return prepare(camera3::Camera3StreamInterface::ALLOCATE_PIPELINE_MAX, streamId);
2092}
2093
2094status_t Camera3Device::prepare(int maxCount, int streamId) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002095 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002096 ALOGV("%s: Camera %s: Preparing stream %d", __FUNCTION__, mId.string(), streamId);
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07002097 Mutex::Autolock il(mInterfaceLock);
2098 Mutex::Autolock l(mLock);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002099
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002100 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
2101 if (stream == nullptr) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002102 CLOGE("Stream %d does not exist", streamId);
2103 return BAD_VALUE;
2104 }
2105
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002106 if (stream->isUnpreparable() || stream->hasOutstandingBuffers() ) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07002107 CLOGE("Stream %d has already been a request target", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002108 return BAD_VALUE;
2109 }
2110
2111 if (mRequestThread->isStreamPending(stream)) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07002112 CLOGE("Stream %d is already a target in a pending request", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002113 return BAD_VALUE;
2114 }
2115
Ruben Brunkc78ac262015-08-13 17:58:46 -07002116 return mPreparerThread->prepare(maxCount, stream);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002117}
2118
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002119status_t Camera3Device::tearDown(int streamId) {
2120 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002121 ALOGV("%s: Camera %s: Tearing down stream %d", __FUNCTION__, mId.string(), streamId);
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002122 Mutex::Autolock il(mInterfaceLock);
2123 Mutex::Autolock l(mLock);
2124
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002125 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
2126 if (stream == nullptr) {
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002127 CLOGE("Stream %d does not exist", streamId);
2128 return BAD_VALUE;
2129 }
2130
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002131 if (stream->hasOutstandingBuffers() || mRequestThread->isStreamPending(stream)) {
2132 CLOGE("Stream %d is a target of a in-progress request", streamId);
2133 return BAD_VALUE;
2134 }
2135
2136 return stream->tearDown();
2137}
2138
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002139status_t Camera3Device::addBufferListenerForStream(int streamId,
2140 wp<Camera3StreamBufferListener> listener) {
2141 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002142 ALOGV("%s: Camera %s: Adding buffer listener for stream %d", __FUNCTION__, mId.string(), streamId);
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002143 Mutex::Autolock il(mInterfaceLock);
2144 Mutex::Autolock l(mLock);
2145
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002146 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
2147 if (stream == nullptr) {
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002148 CLOGE("Stream %d does not exist", streamId);
2149 return BAD_VALUE;
2150 }
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002151 stream->addBufferListener(listener);
2152
2153 return OK;
2154}
2155
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002156/**
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002157 * Methods called by subclasses
2158 */
2159
2160void Camera3Device::notifyStatus(bool idle) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002161 ATRACE_CALL();
Shuzhen Wang316781a2020-08-18 18:11:01 -07002162 std::vector<int> streamIds;
2163 std::vector<hardware::CameraStreamStats> streamStats;
2164
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002165 {
2166 // Need mLock to safely update state and synchronize to current
2167 // state of methods in flight.
2168 Mutex::Autolock l(mLock);
2169 // We can get various system-idle notices from the status tracker
2170 // while starting up. Only care about them if we've actually sent
2171 // in some requests recently.
2172 if (mStatus != STATUS_ACTIVE && mStatus != STATUS_CONFIGURED) {
2173 return;
2174 }
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08002175 ALOGV("%s: Camera %s: Now %s, pauseState: %s", __FUNCTION__, mId.string(),
2176 idle ? "idle" : "active", mPauseStateNotify ? "true" : "false");
Ruben Brunk183f0562015-08-12 12:55:02 -07002177 internalUpdateStatusLocked(idle ? STATUS_CONFIGURED : STATUS_ACTIVE);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002178
2179 // Skip notifying listener if we're doing some user-transparent
2180 // state changes
2181 if (mPauseStateNotify) return;
Shuzhen Wang316781a2020-08-18 18:11:01 -07002182
2183 // Populate stream statistics in case of Idle
2184 if (idle) {
2185 for (size_t i = 0; i < mOutputStreams.size(); i++) {
2186 auto stream = mOutputStreams[i];
2187 if (stream.get() == nullptr) continue;
2188 streamIds.push_back(stream->getId());
2189 Camera3Stream* camera3Stream = Camera3Stream::cast(stream->asHalStream());
2190 int64_t usage = 0LL;
2191 if (camera3Stream != nullptr) {
2192 usage = camera3Stream->getUsage();
2193 }
2194 streamStats.emplace_back(stream->getWidth(), stream->getHeight(),
2195 stream->getFormat(), stream->getDataSpace(), usage,
2196 stream->getMaxHalBuffers(),
2197 stream->getMaxTotalBuffers() - stream->getMaxHalBuffers());
2198 }
2199 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002200 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002201
2202 sp<NotificationListener> listener;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002203 {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002204 std::lock_guard<std::mutex> l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002205 listener = mListener.promote();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002206 }
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07002207 status_t res = OK;
2208 if (listener != nullptr) {
2209 if (idle) {
2210 // Get session stats from the builder, and notify the listener.
2211 int64_t requestCount, resultErrorCount;
2212 bool deviceError;
2213 std::map<int, StreamStats> streamStatsMap;
2214 mSessionStatsBuilder.buildAndReset(&requestCount, &resultErrorCount,
2215 &deviceError, &streamStatsMap);
2216 for (size_t i = 0; i < streamIds.size(); i++) {
2217 int streamId = streamIds[i];
2218 auto stats = streamStatsMap.find(streamId);
2219 if (stats != streamStatsMap.end()) {
2220 streamStats[i].mRequestCount = stats->second.mRequestedFrameCount;
2221 streamStats[i].mErrorCount = stats->second.mDroppedFrameCount;
2222 streamStats[i].mStartLatencyMs = stats->second.mStartLatencyMs;
2223 streamStats[i].mHistogramType =
2224 hardware::CameraStreamStats::HISTOGRAM_TYPE_CAPTURE_LATENCY;
2225 streamStats[i].mHistogramBins.assign(
2226 stats->second.mCaptureLatencyBins.begin(),
2227 stats->second.mCaptureLatencyBins.end());
2228 streamStats[i].mHistogramCounts.assign(
2229 stats->second.mCaptureLatencyHistogram.begin(),
2230 stats->second.mCaptureLatencyHistogram.end());
2231 }
Shuzhen Wang316781a2020-08-18 18:11:01 -07002232 }
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07002233 listener->notifyIdle(requestCount, resultErrorCount, deviceError, streamStats);
2234 } else {
2235 res = listener->notifyActive();
Shuzhen Wang316781a2020-08-18 18:11:01 -07002236 }
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07002237 }
2238 if (res != OK) {
2239 SET_ERR("Camera access permission lost mid-operation: %s (%d)",
2240 strerror(-res), res);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002241 }
2242}
2243
Shuzhen Wang758c2152017-01-10 18:26:18 -08002244status_t Camera3Device::setConsumerSurfaces(int streamId,
Emilian Peev40ead602017-09-26 15:46:36 +01002245 const std::vector<sp<Surface>>& consumers, std::vector<int> *surfaceIds) {
Zhijun He5d677d12016-05-29 16:52:39 -07002246 ATRACE_CALL();
Shuzhen Wang758c2152017-01-10 18:26:18 -08002247 ALOGV("%s: Camera %s: set consumer surface for stream %d",
2248 __FUNCTION__, mId.string(), streamId);
Emilian Peev40ead602017-09-26 15:46:36 +01002249
2250 if (surfaceIds == nullptr) {
2251 return BAD_VALUE;
2252 }
2253
Zhijun He5d677d12016-05-29 16:52:39 -07002254 Mutex::Autolock il(mInterfaceLock);
2255 Mutex::Autolock l(mLock);
2256
Shuzhen Wang758c2152017-01-10 18:26:18 -08002257 if (consumers.size() == 0) {
2258 CLOGE("No consumer is passed!");
Zhijun He5d677d12016-05-29 16:52:39 -07002259 return BAD_VALUE;
2260 }
2261
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002262 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
2263 if (stream == nullptr) {
Zhijun He5d677d12016-05-29 16:52:39 -07002264 CLOGE("Stream %d is unknown", streamId);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002265 return BAD_VALUE;
Zhijun He5d677d12016-05-29 16:52:39 -07002266 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002267
2268 // isConsumerConfigurationDeferred will be off after setConsumers
2269 bool isDeferred = stream->isConsumerConfigurationDeferred();
Shuzhen Wang758c2152017-01-10 18:26:18 -08002270 status_t res = stream->setConsumers(consumers);
Zhijun He5d677d12016-05-29 16:52:39 -07002271 if (res != OK) {
2272 CLOGE("Stream %d set consumer failed (error %d %s) ", streamId, res, strerror(-res));
2273 return res;
2274 }
2275
Emilian Peev40ead602017-09-26 15:46:36 +01002276 for (auto &consumer : consumers) {
2277 int id = stream->getSurfaceId(consumer);
2278 if (id < 0) {
2279 CLOGE("Invalid surface id!");
2280 return BAD_VALUE;
2281 }
2282 surfaceIds->push_back(id);
2283 }
2284
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002285 if (isDeferred) {
Shuzhen Wang0129d522016-10-30 22:43:41 -07002286 if (!stream->isConfiguring()) {
2287 CLOGE("Stream %d was already fully configured.", streamId);
2288 return INVALID_OPERATION;
2289 }
Zhijun He5d677d12016-05-29 16:52:39 -07002290
Shuzhen Wang0129d522016-10-30 22:43:41 -07002291 res = stream->finishConfiguration();
2292 if (res != OK) {
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002293 // If finishConfiguration fails due to abandoned surface, do not set
2294 // device to error state.
2295 bool isSurfaceAbandoned =
2296 (res == NO_INIT || res == DEAD_OBJECT) && stream->isAbandoned();
2297 if (!isSurfaceAbandoned) {
2298 SET_ERR_L("Can't finish configuring output stream %d: %s (%d)",
2299 stream->getId(), strerror(-res), res);
2300 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07002301 return res;
2302 }
Zhijun He5d677d12016-05-29 16:52:39 -07002303 }
2304
2305 return OK;
2306}
2307
Emilian Peev40ead602017-09-26 15:46:36 +01002308status_t Camera3Device::updateStream(int streamId, const std::vector<sp<Surface>> &newSurfaces,
2309 const std::vector<OutputStreamInfo> &outputInfo,
2310 const std::vector<size_t> &removedSurfaceIds, KeyedVector<sp<Surface>, size_t> *outputMap) {
2311 Mutex::Autolock il(mInterfaceLock);
2312 Mutex::Autolock l(mLock);
2313
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002314 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
2315 if (stream == nullptr) {
Emilian Peev40ead602017-09-26 15:46:36 +01002316 CLOGE("Stream %d is unknown", streamId);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002317 return BAD_VALUE;
Emilian Peev40ead602017-09-26 15:46:36 +01002318 }
2319
2320 for (const auto &it : removedSurfaceIds) {
2321 if (mRequestThread->isOutputSurfacePending(streamId, it)) {
2322 CLOGE("Shared surface still part of a pending request!");
2323 return -EBUSY;
2324 }
2325 }
2326
Emilian Peev40ead602017-09-26 15:46:36 +01002327 status_t res = stream->updateStream(newSurfaces, outputInfo, removedSurfaceIds, outputMap);
2328 if (res != OK) {
2329 CLOGE("Stream %d failed to update stream (error %d %s) ",
2330 streamId, res, strerror(-res));
2331 if (res == UNKNOWN_ERROR) {
2332 SET_ERR_L("%s: Stream update failed to revert to previous output configuration!",
2333 __FUNCTION__);
2334 }
2335 return res;
2336 }
2337
2338 return res;
2339}
2340
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002341status_t Camera3Device::dropStreamBuffers(bool dropping, int streamId) {
2342 Mutex::Autolock il(mInterfaceLock);
2343 Mutex::Autolock l(mLock);
2344
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002345 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
2346 if (stream == nullptr) {
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002347 ALOGE("%s: Stream %d is not found.", __FUNCTION__, streamId);
2348 return BAD_VALUE;
2349 }
Shuzhen Wang316781a2020-08-18 18:11:01 -07002350
2351 if (dropping) {
2352 mSessionStatsBuilder.stopCounter(streamId);
2353 } else {
2354 mSessionStatsBuilder.startCounter(streamId);
2355 }
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002356 return stream->dropBuffers(dropping);
2357}
2358
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002359/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002360 * Camera3Device private methods
2361 */
2362
2363sp<Camera3Device::CaptureRequest> Camera3Device::createCaptureRequest(
Emilian Peevaebbe412018-01-15 13:53:24 +00002364 const PhysicalCameraSettingsList &request, const SurfaceMap &surfaceMap) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002365 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002366
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08002367 sp<CaptureRequest> newRequest = new CaptureRequest();
Emilian Peevaebbe412018-01-15 13:53:24 +00002368 newRequest->mSettingsList = request;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002369
2370 camera_metadata_entry_t inputStreams =
Emilian Peevaebbe412018-01-15 13:53:24 +00002371 newRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_INPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002372 if (inputStreams.count > 0) {
2373 if (mInputStream == NULL ||
Zhijun Hed1d64672013-09-06 15:00:01 -07002374 mInputStream->getId() != inputStreams.data.i32[0]) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002375 CLOGE("Request references unknown input stream %d",
2376 inputStreams.data.u8[0]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002377 return NULL;
2378 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002379
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002380 if (mInputStream->isConfiguring()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002381 SET_ERR_L("%s: input stream %d is not configured!",
2382 __FUNCTION__, mInputStream->getId());
2383 return NULL;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002384 }
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07002385 // Check if stream prepare is blocking requests.
2386 if (mInputStream->isBlockedByPrepare()) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002387 CLOGE("Request references an input stream that's being prepared!");
2388 return NULL;
2389 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002390
2391 newRequest->mInputStream = mInputStream;
Emilian Peevaebbe412018-01-15 13:53:24 +00002392 newRequest->mSettingsList.begin()->metadata.erase(ANDROID_REQUEST_INPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002393 }
2394
2395 camera_metadata_entry_t streams =
Emilian Peevaebbe412018-01-15 13:53:24 +00002396 newRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_OUTPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002397 if (streams.count == 0) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002398 CLOGE("Zero output streams specified!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002399 return NULL;
2400 }
2401
2402 for (size_t i = 0; i < streams.count; i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002403 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streams.data.i32[i]);
2404 if (stream == nullptr) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002405 CLOGE("Request references unknown stream %d",
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002406 streams.data.i32[i]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002407 return NULL;
2408 }
Zhijun He5d677d12016-05-29 16:52:39 -07002409 // It is illegal to include a deferred consumer output stream into a request
Shuzhen Wang0129d522016-10-30 22:43:41 -07002410 auto iter = surfaceMap.find(streams.data.i32[i]);
2411 if (iter != surfaceMap.end()) {
2412 const std::vector<size_t>& surfaces = iter->second;
2413 for (const auto& surface : surfaces) {
2414 if (stream->isConsumerConfigurationDeferred(surface)) {
2415 CLOGE("Stream %d surface %zu hasn't finished configuration yet "
2416 "due to deferred consumer", stream->getId(), surface);
2417 return NULL;
2418 }
2419 }
Yin-Chia Yeh0b287572018-10-15 12:38:13 -07002420 newRequest->mOutputSurfaces[streams.data.i32[i]] = surfaces;
Zhijun He5d677d12016-05-29 16:52:39 -07002421 }
2422
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002423 if (stream->isConfiguring()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002424 SET_ERR_L("%s: stream %d is not configured!", __FUNCTION__, stream->getId());
2425 return NULL;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002426 }
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07002427 // Check if stream prepare is blocking requests.
2428 if (stream->isBlockedByPrepare()) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002429 CLOGE("Request references an output stream that's being prepared!");
2430 return NULL;
2431 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002432
2433 newRequest->mOutputStreams.push(stream);
2434 }
Emilian Peevaebbe412018-01-15 13:53:24 +00002435 newRequest->mSettingsList.begin()->metadata.erase(ANDROID_REQUEST_OUTPUT_STREAMS);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07002436 newRequest->mBatchSize = 1;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002437
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08002438 auto rotateAndCropEntry =
2439 newRequest->mSettingsList.begin()->metadata.find(ANDROID_SCALER_ROTATE_AND_CROP);
2440 if (rotateAndCropEntry.count > 0 &&
2441 rotateAndCropEntry.data.u8[0] == ANDROID_SCALER_ROTATE_AND_CROP_AUTO) {
2442 newRequest->mRotateAndCropAuto = true;
2443 } else {
2444 newRequest->mRotateAndCropAuto = false;
2445 }
2446
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07002447 auto zoomRatioEntry =
2448 newRequest->mSettingsList.begin()->metadata.find(ANDROID_CONTROL_ZOOM_RATIO);
2449 if (zoomRatioEntry.count > 0 &&
2450 zoomRatioEntry.data.f[0] == 1.0f) {
2451 newRequest->mZoomRatioIs1x = true;
2452 } else {
2453 newRequest->mZoomRatioIs1x = false;
2454 }
2455
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08002456 if (mSupportCameraMute) {
2457 auto testPatternModeEntry =
2458 newRequest->mSettingsList.begin()->metadata.find(ANDROID_SENSOR_TEST_PATTERN_MODE);
2459 newRequest->mOriginalTestPatternMode = testPatternModeEntry.count > 0 ?
2460 testPatternModeEntry.data.i32[0] :
2461 ANDROID_SENSOR_TEST_PATTERN_MODE_OFF;
2462
2463 auto testPatternDataEntry =
2464 newRequest->mSettingsList.begin()->metadata.find(ANDROID_SENSOR_TEST_PATTERN_DATA);
Eino-Ville Talvalac2459842021-07-22 16:36:36 -07002465 if (testPatternDataEntry.count >= 4) {
2466 memcpy(newRequest->mOriginalTestPatternData, testPatternDataEntry.data.i32,
2467 sizeof(CaptureRequest::mOriginalTestPatternData));
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08002468 } else {
2469 newRequest->mOriginalTestPatternData[0] = 0;
2470 newRequest->mOriginalTestPatternData[1] = 0;
2471 newRequest->mOriginalTestPatternData[2] = 0;
2472 newRequest->mOriginalTestPatternData[3] = 0;
2473 }
2474 }
2475
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002476 return newRequest;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002477}
2478
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002479void Camera3Device::cancelStreamsConfigurationLocked() {
2480 int res = OK;
2481 if (mInputStream != NULL && mInputStream->isConfiguring()) {
2482 res = mInputStream->cancelConfiguration();
2483 if (res != OK) {
2484 CLOGE("Can't cancel configuring input stream %d: %s (%d)",
2485 mInputStream->getId(), strerror(-res), res);
2486 }
2487 }
2488
2489 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002490 sp<Camera3OutputStreamInterface> outputStream = mOutputStreams[i];
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002491 if (outputStream->isConfiguring()) {
2492 res = outputStream->cancelConfiguration();
2493 if (res != OK) {
2494 CLOGE("Can't cancel configuring output stream %d: %s (%d)",
2495 outputStream->getId(), strerror(-res), res);
2496 }
2497 }
2498 }
2499
2500 // Return state to that at start of call, so that future configures
2501 // properly clean things up
2502 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
2503 mNeedConfig = true;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002504
2505 res = mPreparerThread->resume();
2506 if (res != OK) {
2507 ALOGE("%s: Camera %s: Preparer thread failed to resume!", __FUNCTION__, mId.string());
2508 }
2509}
2510
Emilian Peev0d0191e2020-04-21 17:01:18 -07002511bool Camera3Device::checkAbandonedStreamsLocked() {
2512 if ((mInputStream.get() != nullptr) && (mInputStream->isAbandoned())) {
2513 return true;
2514 }
2515
2516 for (size_t i = 0; i < mOutputStreams.size(); i++) {
2517 auto stream = mOutputStreams[i];
2518 if ((stream.get() != nullptr) && (stream->isAbandoned())) {
2519 return true;
2520 }
2521 }
2522
2523 return false;
2524}
2525
Emilian Peev3bead5f2020-05-28 17:29:08 -07002526bool Camera3Device::reconfigureCamera(const CameraMetadata& sessionParams, int clientStatusId) {
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002527 ATRACE_CALL();
2528 bool ret = false;
2529
Shuzhen Wang316781a2020-08-18 18:11:01 -07002530 nsecs_t startTime = systemTime();
2531
Jayant Chowdhary646c31b2020-01-30 13:09:59 -08002532 Mutex::Autolock il(mInterfaceLock);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002533 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
2534
2535 Mutex::Autolock l(mLock);
Emilian Peev0d0191e2020-04-21 17:01:18 -07002536 if (checkAbandonedStreamsLocked()) {
2537 ALOGW("%s: Abandoned stream detected, session parameters can't be applied correctly!",
2538 __FUNCTION__);
2539 return true;
2540 }
2541
Emilian Peev3bead5f2020-05-28 17:29:08 -07002542 status_t rc = NO_ERROR;
2543 bool markClientActive = false;
2544 if (mStatus == STATUS_ACTIVE) {
2545 markClientActive = true;
2546 mPauseStateNotify = true;
2547 mStatusTracker->markComponentIdle(clientStatusId, Fence::NO_FENCE);
2548
2549 rc = internalPauseAndWaitLocked(maxExpectedDuration);
2550 }
2551
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002552 if (rc == NO_ERROR) {
2553 mNeedConfig = true;
2554 rc = configureStreamsLocked(mOperatingMode, sessionParams, /*notifyRequestThread*/ false);
2555 if (rc == NO_ERROR) {
2556 ret = true;
2557 mPauseStateNotify = false;
2558 //Moving to active state while holding 'mLock' is important.
2559 //There could be pending calls to 'create-/deleteStream' which
2560 //will trigger another stream configuration while the already
2561 //present streams end up with outstanding buffers that will
2562 //not get drained.
2563 internalUpdateStatusLocked(STATUS_ACTIVE);
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002564 } else if (rc == DEAD_OBJECT) {
2565 // DEAD_OBJECT can be returned if either the consumer surface is
2566 // abandoned, or the HAL has died.
2567 // - If the HAL has died, configureStreamsLocked call will set
2568 // device to error state,
2569 // - If surface is abandoned, we should not set device to error
2570 // state.
2571 ALOGE("Failed to re-configure camera due to abandoned surface");
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002572 } else {
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002573 SET_ERR_L("Failed to re-configure camera: %d", rc);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002574 }
2575 } else {
2576 ALOGE("%s: Failed to pause streaming: %d", __FUNCTION__, rc);
2577 }
2578
Shuzhen Wang316781a2020-08-18 18:11:01 -07002579 CameraServiceProxyWrapper::logStreamConfigured(mId, mOperatingMode, true /*internalReconfig*/,
2580 ns2ms(systemTime() - startTime));
2581
Emilian Peev3bead5f2020-05-28 17:29:08 -07002582 if (markClientActive) {
2583 mStatusTracker->markComponentActive(clientStatusId);
2584 }
2585
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002586 return ret;
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002587}
2588
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002589status_t Camera3Device::configureStreamsLocked(int operatingMode,
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002590 const CameraMetadata& sessionParams, bool notifyRequestThread) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002591 ATRACE_CALL();
2592 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002593
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002594 if (mStatus != STATUS_UNCONFIGURED && mStatus != STATUS_CONFIGURED) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002595 CLOGE("Not idle");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002596 return INVALID_OPERATION;
2597 }
2598
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08002599 if (operatingMode < 0) {
2600 CLOGE("Invalid operating mode: %d", operatingMode);
2601 return BAD_VALUE;
2602 }
2603
2604 bool isConstrainedHighSpeed =
2605 static_cast<int>(StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE) ==
2606 operatingMode;
2607
2608 if (mOperatingMode != operatingMode) {
2609 mNeedConfig = true;
2610 mIsConstrainedHighSpeedConfiguration = isConstrainedHighSpeed;
2611 mOperatingMode = operatingMode;
2612 }
2613
Shuzhen Wang0cf01cb2019-09-05 13:33:06 -07002614 // In case called from configureStreams, abort queued input buffers not belonging to
2615 // any pending requests.
2616 if (mInputStream != NULL && notifyRequestThread) {
2617 while (true) {
Emilian Peevf4816702020-04-03 15:44:51 -07002618 camera_stream_buffer_t inputBuffer;
Shuzhen Wang83bff122020-11-20 15:51:39 -08002619 camera3::Size inputBufferSize;
Shuzhen Wang0cf01cb2019-09-05 13:33:06 -07002620 status_t res = mInputStream->getInputBuffer(&inputBuffer,
Shuzhen Wang83bff122020-11-20 15:51:39 -08002621 &inputBufferSize, /*respectHalLimit*/ false);
Shuzhen Wang0cf01cb2019-09-05 13:33:06 -07002622 if (res != OK) {
2623 // Exhausted acquiring all input buffers.
2624 break;
2625 }
2626
Emilian Peevf4816702020-04-03 15:44:51 -07002627 inputBuffer.status = CAMERA_BUFFER_STATUS_ERROR;
Shuzhen Wang0cf01cb2019-09-05 13:33:06 -07002628 res = mInputStream->returnInputBuffer(inputBuffer);
2629 if (res != OK) {
2630 ALOGE("%s: %d: couldn't return input buffer while clearing input queue: "
2631 "%s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
2632 }
2633 }
2634 }
2635
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002636 if (!mNeedConfig) {
2637 ALOGV("%s: Skipping config, no stream changes", __FUNCTION__);
2638 return OK;
2639 }
2640
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002641 // Workaround for device HALv3.2 or older spec bug - zero streams requires
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002642 // adding a fake stream instead.
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002643 // TODO: Bug: 17321404 for fixing the HAL spec and removing this workaround.
2644 if (mOutputStreams.size() == 0) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002645 addFakeStreamLocked();
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002646 } else {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002647 tryRemoveFakeStreamLocked();
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002648 }
2649
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002650 // Start configuring the streams
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002651 ALOGV("%s: Camera %s: Starting stream configuration", __FUNCTION__, mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002652
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002653 mPreparerThread->pause();
2654
Emilian Peevf4816702020-04-03 15:44:51 -07002655 camera_stream_configuration config;
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -08002656 config.operation_mode = mOperatingMode;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002657 config.num_streams = (mInputStream != NULL) + mOutputStreams.size();
Shuzhen Wang83bff122020-11-20 15:51:39 -08002658 config.input_is_multi_resolution = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002659
Emilian Peevf4816702020-04-03 15:44:51 -07002660 Vector<camera3::camera_stream_t*> streams;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002661 streams.setCapacity(config.num_streams);
Emilian Peev192ee832018-01-31 14:46:47 +00002662 std::vector<uint32_t> bufferSizes(config.num_streams, 0);
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002663
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002664
2665 if (mInputStream != NULL) {
Emilian Peevf4816702020-04-03 15:44:51 -07002666 camera3::camera_stream_t *inputStream;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002667 inputStream = mInputStream->startConfiguration();
2668 if (inputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002669 CLOGE("Can't start input stream configuration");
2670 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002671 return INVALID_OPERATION;
2672 }
2673 streams.add(inputStream);
Shuzhen Wang83bff122020-11-20 15:51:39 -08002674
2675 config.input_is_multi_resolution = mIsInputStreamMultiResolution;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002676 }
2677
Shuzhen Wang99080502021-03-07 21:08:20 -08002678 mGroupIdPhysicalCameraMap.clear();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002679 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Igor Murashkin2fba5842013-04-22 14:03:54 -07002680
2681 // Don't configure bidi streams twice, nor add them twice to the list
2682 if (mOutputStreams[i].get() ==
2683 static_cast<Camera3StreamInterface*>(mInputStream.get())) {
2684
2685 config.num_streams--;
2686 continue;
2687 }
2688
Emilian Peevf4816702020-04-03 15:44:51 -07002689 camera3::camera_stream_t *outputStream;
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002690 outputStream = mOutputStreams[i]->startConfiguration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002691 if (outputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002692 CLOGE("Can't start output stream configuration");
2693 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002694 return INVALID_OPERATION;
2695 }
2696 streams.add(outputStream);
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002697
Shuzhen Wangb7ab1e42019-02-20 15:42:23 -08002698 if (outputStream->format == HAL_PIXEL_FORMAT_BLOB) {
Emilian Peev192ee832018-01-31 14:46:47 +00002699 size_t k = i + ((mInputStream != nullptr) ? 1 : 0); // Input stream if present should
2700 // always occupy the initial entry.
Shuzhen Wangb7ab1e42019-02-20 15:42:23 -08002701 if (outputStream->data_space == HAL_DATASPACE_V0_JFIF) {
2702 bufferSizes[k] = static_cast<uint32_t>(
2703 getJpegBufferSize(outputStream->width, outputStream->height));
2704 } else if (outputStream->data_space ==
2705 static_cast<android_dataspace>(HAL_DATASPACE_JPEG_APP_SEGMENTS)) {
2706 bufferSizes[k] = outputStream->width * outputStream->height;
2707 } else {
2708 ALOGW("%s: Blob dataSpace %d not supported",
2709 __FUNCTION__, outputStream->data_space);
2710 }
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002711 }
Shuzhen Wang99080502021-03-07 21:08:20 -08002712
2713 if (mOutputStreams[i]->isMultiResolution()) {
2714 int32_t streamGroupId = mOutputStreams[i]->getHalStreamGroupId();
2715 const String8& physicalCameraId = mOutputStreams[i]->getPhysicalCameraId();
2716 mGroupIdPhysicalCameraMap[streamGroupId].insert(physicalCameraId);
2717 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002718 }
2719
2720 config.streams = streams.editArray();
2721
2722 // Do the HAL configuration; will potentially touch stream
Shuzhen Wang92653952019-05-07 15:11:43 -07002723 // max_buffers, usage, and priv fields, as well as data_space and format
2724 // fields for IMPLEMENTATION_DEFINED formats.
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002725
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002726 const camera_metadata_t *sessionBuffer = sessionParams.getAndLock();
Emilian Peev192ee832018-01-31 14:46:47 +00002727 res = mInterface->configureStreams(sessionBuffer, &config, bufferSizes);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002728 sessionParams.unlock(sessionBuffer);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002729
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002730 if (res == BAD_VALUE) {
2731 // HAL rejected this set of streams as unsupported, clean up config
2732 // attempt and return to unconfigured state
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002733 CLOGE("Set of requested inputs/outputs not supported by HAL");
2734 cancelStreamsConfigurationLocked();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002735 return BAD_VALUE;
2736 } else if (res != OK) {
2737 // Some other kind of error from configure_streams - this is not
2738 // expected
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002739 SET_ERR_L("Unable to configure streams with HAL: %s (%d)",
2740 strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002741 return res;
2742 }
2743
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002744 // Finish all stream configuration immediately.
2745 // TODO: Try to relax this later back to lazy completion, which should be
2746 // faster
2747
Igor Murashkin073f8572013-05-02 14:59:28 -07002748 if (mInputStream != NULL && mInputStream->isConfiguring()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002749 bool streamReConfigured = false;
2750 res = mInputStream->finishConfiguration(&streamReConfigured);
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002751 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002752 CLOGE("Can't finish configuring input stream %d: %s (%d)",
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002753 mInputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002754 cancelStreamsConfigurationLocked();
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002755 if ((res == NO_INIT || res == DEAD_OBJECT) && mInputStream->isAbandoned()) {
2756 return DEAD_OBJECT;
2757 }
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002758 return BAD_VALUE;
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002759 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002760 if (streamReConfigured) {
2761 mInterface->onStreamReConfigured(mInputStream->getId());
2762 }
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002763 }
2764
2765 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002766 sp<Camera3OutputStreamInterface> outputStream = mOutputStreams[i];
Zhijun He5d677d12016-05-29 16:52:39 -07002767 if (outputStream->isConfiguring() && !outputStream->isConsumerConfigurationDeferred()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002768 bool streamReConfigured = false;
2769 res = outputStream->finishConfiguration(&streamReConfigured);
Igor Murashkin073f8572013-05-02 14:59:28 -07002770 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002771 CLOGE("Can't finish configuring output stream %d: %s (%d)",
Igor Murashkin073f8572013-05-02 14:59:28 -07002772 outputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002773 cancelStreamsConfigurationLocked();
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002774 if ((res == NO_INIT || res == DEAD_OBJECT) && outputStream->isAbandoned()) {
2775 return DEAD_OBJECT;
2776 }
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002777 return BAD_VALUE;
Igor Murashkin073f8572013-05-02 14:59:28 -07002778 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002779 if (streamReConfigured) {
2780 mInterface->onStreamReConfigured(outputStream->getId());
2781 }
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002782 }
2783 }
2784
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002785 // Request thread needs to know to avoid using repeat-last-settings protocol
2786 // across configure_streams() calls
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002787 if (notifyRequestThread) {
Shuzhen Wang99080502021-03-07 21:08:20 -08002788 mRequestThread->configurationComplete(mIsConstrainedHighSpeedConfiguration,
2789 sessionParams, mGroupIdPhysicalCameraMap);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002790 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002791
Zhijun He90f7c372016-08-16 16:19:43 -07002792 char value[PROPERTY_VALUE_MAX];
2793 property_get("camera.fifo.disable", value, "0");
2794 int32_t disableFifo = atoi(value);
2795 if (disableFifo != 1) {
2796 // Boost priority of request thread to SCHED_FIFO.
2797 pid_t requestThreadTid = mRequestThread->getTid();
2798 res = requestPriority(getpid(), requestThreadTid,
Mikhail Naganov83f04272017-02-07 10:45:09 -08002799 kRequestThreadPriority, /*isForApp*/ false, /*asynchronous*/ false);
Zhijun He90f7c372016-08-16 16:19:43 -07002800 if (res != OK) {
2801 ALOGW("Can't set realtime priority for request processing thread: %s (%d)",
2802 strerror(-res), res);
2803 } else {
2804 ALOGD("Set real time priority for request queue thread (tid %d)", requestThreadTid);
2805 }
Eino-Ville Talvalaf99498e2015-09-25 16:52:55 -07002806 }
2807
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002808 // Update device state
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002809 const camera_metadata_t *newSessionParams = sessionParams.getAndLock();
2810 const camera_metadata_t *currentSessionParams = mSessionParams.getAndLock();
2811 bool updateSessionParams = (newSessionParams != currentSessionParams) ? true : false;
2812 sessionParams.unlock(newSessionParams);
2813 mSessionParams.unlock(currentSessionParams);
2814 if (updateSessionParams) {
2815 mSessionParams = sessionParams;
2816 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002817
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002818 mNeedConfig = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002819
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002820 internalUpdateStatusLocked((mFakeStreamId == NO_STREAM) ?
Ruben Brunk183f0562015-08-12 12:55:02 -07002821 STATUS_CONFIGURED : STATUS_UNCONFIGURED);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002822
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002823 ALOGV("%s: Camera %s: Stream configuration complete", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002824
Zhijun He0a210512014-07-24 13:45:15 -07002825 // tear down the deleted streams after configure streams.
2826 mDeletedStreams.clear();
2827
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002828 auto rc = mPreparerThread->resume();
2829 if (rc != OK) {
2830 SET_ERR_L("%s: Camera %s: Preparer thread failed to resume!", __FUNCTION__, mId.string());
2831 return rc;
2832 }
2833
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002834 if (mFakeStreamId == NO_STREAM) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07002835 mRequestBufferSM.onStreamsConfigured();
2836 }
2837
Cliff Wuc2ad9c82021-04-21 00:58:58 +08002838 // Since the streams configuration of the injection camera is based on the internal camera, we
2839 // must wait until the internal camera configure streams before calling injectCamera() to
2840 // configure the injection streams.
2841 if (mInjectionMethods->isInjecting()) {
2842 ALOGV("%s: Injection camera %s: Start to configure streams.",
2843 __FUNCTION__, mInjectionMethods->getInjectedCamId().string());
2844 res = mInjectionMethods->injectCamera(config, bufferSizes);
2845 if (res != OK) {
2846 ALOGE("Can't finish inject camera process!");
2847 return res;
2848 }
2849 }
2850
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002851 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002852}
2853
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002854status_t Camera3Device::addFakeStreamLocked() {
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002855 ATRACE_CALL();
2856 status_t res;
2857
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002858 if (mFakeStreamId != NO_STREAM) {
2859 // Should never be adding a second fake stream when one is already
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002860 // active
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002861 SET_ERR_L("%s: Camera %s: A fake stream already exists!",
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002862 __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002863 return INVALID_OPERATION;
2864 }
2865
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002866 ALOGV("%s: Camera %s: Adding a fake stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002867
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002868 sp<Camera3OutputStreamInterface> fakeStream =
2869 new Camera3FakeStream(mNextStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002870
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002871 res = mOutputStreams.add(mNextStreamId, fakeStream);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002872 if (res < 0) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002873 SET_ERR_L("Can't add fake stream to set: %s (%d)", strerror(-res), res);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002874 return res;
2875 }
2876
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002877 mFakeStreamId = mNextStreamId;
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002878 mNextStreamId++;
2879
2880 return OK;
2881}
2882
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002883status_t Camera3Device::tryRemoveFakeStreamLocked() {
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002884 ATRACE_CALL();
2885 status_t res;
2886
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002887 if (mFakeStreamId == NO_STREAM) return OK;
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002888 if (mOutputStreams.size() == 1) return OK;
2889
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002890 ALOGV("%s: Camera %s: Removing the fake stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002891
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002892 // Ok, have a fake stream and there's at least one other output stream,
2893 // so remove the fake
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002894
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002895 sp<Camera3StreamInterface> deletedStream = mOutputStreams.get(mFakeStreamId);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002896 if (deletedStream == nullptr) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002897 SET_ERR_L("Fake stream %d does not appear to exist", mFakeStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002898 return INVALID_OPERATION;
2899 }
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002900 mOutputStreams.remove(mFakeStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002901
2902 // Free up the stream endpoint so that it can be used by some other stream
2903 res = deletedStream->disconnect();
2904 if (res != OK) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002905 SET_ERR_L("Can't disconnect deleted fake stream %d", mFakeStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002906 // fall through since we want to still list the stream as deleted.
2907 }
2908 mDeletedStreams.add(deletedStream);
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002909 mFakeStreamId = NO_STREAM;
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002910
2911 return res;
2912}
2913
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002914void Camera3Device::setErrorState(const char *fmt, ...) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002915 ATRACE_CALL();
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002916 Mutex::Autolock l(mLock);
2917 va_list args;
2918 va_start(args, fmt);
2919
2920 setErrorStateLockedV(fmt, args);
2921
2922 va_end(args);
2923}
2924
2925void Camera3Device::setErrorStateV(const char *fmt, va_list args) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002926 ATRACE_CALL();
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002927 Mutex::Autolock l(mLock);
2928 setErrorStateLockedV(fmt, args);
2929}
2930
2931void Camera3Device::setErrorStateLocked(const char *fmt, ...) {
2932 va_list args;
2933 va_start(args, fmt);
2934
2935 setErrorStateLockedV(fmt, args);
2936
2937 va_end(args);
2938}
2939
2940void Camera3Device::setErrorStateLockedV(const char *fmt, va_list args) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002941 // Print out all error messages to log
2942 String8 errorCause = String8::formatV(fmt, args);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002943 ALOGE("Camera %s: %s", mId.string(), errorCause.string());
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002944
2945 // But only do error state transition steps for the first error
Zhijun Heb05eeae2013-06-06 13:51:22 -07002946 if (mStatus == STATUS_ERROR || mStatus == STATUS_UNINITIALIZED) return;
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002947
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002948 mErrorCause = errorCause;
2949
Yin-Chia Yeh3d145ae2017-07-27 12:47:03 -07002950 if (mRequestThread != nullptr) {
2951 mRequestThread->setPaused(true);
2952 }
Ruben Brunk183f0562015-08-12 12:55:02 -07002953 internalUpdateStatusLocked(STATUS_ERROR);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002954
2955 // Notify upstream about a device error
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002956 sp<NotificationListener> listener = mListener.promote();
2957 if (listener != NULL) {
2958 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002959 CaptureResultExtras());
Shuzhen Wang316781a2020-08-18 18:11:01 -07002960 mSessionStatsBuilder.onDeviceError();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002961 }
2962
2963 // Save stack trace. View by dumping it later.
2964 CameraTraces::saveTrace();
2965 // TODO: consider adding errorCause and client pid/procname
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002966}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002967
2968/**
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002969 * In-flight request management
2970 */
2971
Jianing Weicb0652e2014-03-12 18:29:36 -07002972status_t Camera3Device::registerInFlight(uint32_t frameNumber,
Chien-Yu Chend196d612015-06-22 19:49:01 -07002973 int32_t numBuffers, CaptureResultExtras resultExtras, bool hasInput,
Shuzhen Wang5c22c152017-12-31 17:12:25 -08002974 bool hasAppCallback, nsecs_t maxExpectedDuration,
Shuzhen Wang99080502021-03-07 21:08:20 -08002975 const std::set<std::set<String8>>& physicalCameraIds,
2976 bool isStillCapture, bool isZslCapture, bool rotateAndCropAuto,
2977 const std::set<std::string>& cameraIdsWithZoom,
Shuzhen Wang316781a2020-08-18 18:11:01 -07002978 const SurfaceMap& outputSurfaces, nsecs_t requestTimeNs) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002979 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002980 std::lock_guard<std::mutex> l(mInFlightLock);
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002981
2982 ssize_t res;
Chien-Yu Chend196d612015-06-22 19:49:01 -07002983 res = mInFlightMap.add(frameNumber, InFlightRequest(numBuffers, resultExtras, hasInput,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07002984 hasAppCallback, maxExpectedDuration, physicalCameraIds, isStillCapture, isZslCapture,
Shuzhen Wang316781a2020-08-18 18:11:01 -07002985 rotateAndCropAuto, cameraIdsWithZoom, requestTimeNs, outputSurfaces));
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002986 if (res < 0) return res;
2987
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07002988 if (mInFlightMap.size() == 1) {
Emilian Peev26d975d2018-07-05 14:52:57 +01002989 // Hold a separate dedicated tracker lock to prevent race with disconnect and also
2990 // avoid a deadlock during reprocess requests.
2991 Mutex::Autolock l(mTrackerLock);
Yin-Chia Yeh38dfde52017-06-27 17:13:33 -07002992 if (mStatusTracker != nullptr) {
2993 mStatusTracker->markComponentActive(mInFlightStatusId);
2994 }
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07002995 }
2996
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07002997 mExpectedInflightDuration += maxExpectedDuration;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002998 return OK;
2999}
3000
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003001void Camera3Device::onInflightEntryRemovedLocked(nsecs_t duration) {
Shuzhen Wangcadb3302016-11-04 14:17:56 -07003002 // Indicate idle inFlightMap to the status tracker
3003 if (mInFlightMap.size() == 0) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07003004 mRequestBufferSM.onInflightMapEmpty();
Emilian Peev26d975d2018-07-05 14:52:57 +01003005 // Hold a separate dedicated tracker lock to prevent race with disconnect and also
3006 // avoid a deadlock during reprocess requests.
3007 Mutex::Autolock l(mTrackerLock);
Yin-Chia Yeh38dfde52017-06-27 17:13:33 -07003008 if (mStatusTracker != nullptr) {
3009 mStatusTracker->markComponentIdle(mInFlightStatusId, Fence::NO_FENCE);
3010 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07003011 }
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003012 mExpectedInflightDuration -= duration;
Shuzhen Wangcadb3302016-11-04 14:17:56 -07003013}
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003014
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003015void Camera3Device::checkInflightMapLengthLocked() {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04003016 // Validation check - if we have too many in-flight frames with long total inflight duration,
Yin-Chia Yeh99fd0972019-06-27 14:22:44 -07003017 // something has likely gone wrong. This might still be legit only if application send in
3018 // a long burst of long exposure requests.
3019 if (mExpectedInflightDuration > kMinWarnInflightDuration) {
3020 if (!mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() > kInFlightWarnLimit) {
3021 CLOGW("In-flight list too large: %zu, total inflight duration %" PRIu64,
3022 mInFlightMap.size(), mExpectedInflightDuration);
3023 } else if (mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() >
3024 kInFlightWarnLimitHighSpeed) {
3025 CLOGW("In-flight list too large for high speed configuration: %zu,"
3026 "total inflight duration %" PRIu64,
3027 mInFlightMap.size(), mExpectedInflightDuration);
3028 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003029 }
3030}
3031
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003032void Camera3Device::onInflightMapFlushedLocked() {
3033 mExpectedInflightDuration = 0;
3034}
3035
3036void Camera3Device::removeInFlightMapEntryLocked(int idx) {
Jayant Chowdharyd4776262020-06-23 23:45:57 -07003037 ATRACE_HFR_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003038 nsecs_t duration = mInFlightMap.valueAt(idx).maxExpectedDuration;
3039 mInFlightMap.removeItemsAt(idx, 1);
3040
3041 onInflightEntryRemovedLocked(duration);
3042}
3043
3044
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003045void Camera3Device::flushInflightRequests() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003046 ATRACE_CALL();
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003047 sp<NotificationListener> listener;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003048 {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003049 std::lock_guard<std::mutex> l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003050 listener = mListener.promote();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003051 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003052
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003053 FlushInflightReqStates states {
3054 mId, mInFlightLock, mInFlightMap, mUseHalBufManager,
Shuzhen Wang316781a2020-08-18 18:11:01 -07003055 listener, *this, *mInterface, *this, mSessionStatsBuilder};
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003056
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003057 camera3::flushInflightRequests(states);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003058}
3059
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003060CameraMetadata Camera3Device::getLatestRequestLocked() {
Igor Murashkin1e479c02013-09-06 16:55:14 -07003061 ALOGV("%s", __FUNCTION__);
3062
Igor Murashkin1e479c02013-09-06 16:55:14 -07003063 CameraMetadata retVal;
3064
3065 if (mRequestThread != NULL) {
3066 retVal = mRequestThread->getLatestRequest();
3067 }
3068
Igor Murashkin1e479c02013-09-06 16:55:14 -07003069 return retVal;
3070}
3071
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07003072void Camera3Device::monitorMetadata(TagMonitor::eventSource source,
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003073 int64_t frameNumber, nsecs_t timestamp, const CameraMetadata& metadata,
3074 const std::unordered_map<std::string, CameraMetadata>& physicalMetadata) {
3075
3076 mTagMonitor.monitorMetadata(source, frameNumber, timestamp, metadata,
3077 physicalMetadata);
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07003078}
3079
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003080/**
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003081 * HalInterface inner class methods
3082 */
3083
Yifan Hongf79b5542017-04-11 14:44:25 -07003084Camera3Device::HalInterface::HalInterface(
3085 sp<ICameraDeviceSession> &session,
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003086 std::shared_ptr<RequestMetadataQueue> queue,
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003087 bool useHalBufManager, bool supportOfflineProcessing) :
Yifan Hongf79b5542017-04-11 14:44:25 -07003088 mHidlSession(session),
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003089 mRequestMetadataQueue(queue),
Emilian Peev4ec17882019-01-24 17:16:58 -08003090 mUseHalBufManager(useHalBufManager),
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003091 mIsReconfigurationQuerySupported(true),
3092 mSupportOfflineProcessing(supportOfflineProcessing) {
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003093 // Check with hardware service manager if we can downcast these interfaces
3094 // Somewhat expensive, so cache the results at startup
Shuzhen Wang83bff122020-11-20 15:51:39 -08003095 auto castResult_3_7 = device::V3_7::ICameraDeviceSession::castFrom(mHidlSession);
3096 if (castResult_3_7.isOk()) {
3097 mHidlSession_3_7 = castResult_3_7;
3098 }
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003099 auto castResult_3_6 = device::V3_6::ICameraDeviceSession::castFrom(mHidlSession);
3100 if (castResult_3_6.isOk()) {
3101 mHidlSession_3_6 = castResult_3_6;
3102 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003103 auto castResult_3_5 = device::V3_5::ICameraDeviceSession::castFrom(mHidlSession);
3104 if (castResult_3_5.isOk()) {
3105 mHidlSession_3_5 = castResult_3_5;
3106 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003107 auto castResult_3_4 = device::V3_4::ICameraDeviceSession::castFrom(mHidlSession);
3108 if (castResult_3_4.isOk()) {
3109 mHidlSession_3_4 = castResult_3_4;
3110 }
3111 auto castResult_3_3 = device::V3_3::ICameraDeviceSession::castFrom(mHidlSession);
3112 if (castResult_3_3.isOk()) {
3113 mHidlSession_3_3 = castResult_3_3;
3114 }
3115}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003116
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003117Camera3Device::HalInterface::HalInterface() :
3118 mUseHalBufManager(false),
3119 mSupportOfflineProcessing(false) {}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003120
3121Camera3Device::HalInterface::HalInterface(const HalInterface& other) :
Yifan Hongf79b5542017-04-11 14:44:25 -07003122 mHidlSession(other.mHidlSession),
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003123 mRequestMetadataQueue(other.mRequestMetadataQueue),
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003124 mUseHalBufManager(other.mUseHalBufManager),
3125 mSupportOfflineProcessing(other.mSupportOfflineProcessing) {}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003126
3127bool Camera3Device::HalInterface::valid() {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003128 return (mHidlSession != nullptr);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003129}
3130
3131void Camera3Device::HalInterface::clear() {
Shuzhen Wang83bff122020-11-20 15:51:39 -08003132 mHidlSession_3_7.clear();
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003133 mHidlSession_3_6.clear();
Emilian Peev644a3e12018-11-23 13:52:39 +00003134 mHidlSession_3_5.clear();
Emilian Peev9e740b02018-01-30 18:28:03 +00003135 mHidlSession_3_4.clear();
3136 mHidlSession_3_3.clear();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003137 mHidlSession.clear();
3138}
3139
3140status_t Camera3Device::HalInterface::constructDefaultRequestSettings(
Emilian Peevf4816702020-04-03 15:44:51 -07003141 camera_request_template_t templateId,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003142 /*out*/ camera_metadata_t **requestTemplate) {
3143 ATRACE_NAME("CameraHal::constructDefaultRequestSettings");
3144 if (!valid()) return INVALID_OPERATION;
3145 status_t res = OK;
3146
Emilian Peev31abd0a2017-05-11 18:37:46 +01003147 common::V1_0::Status status;
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003148
3149 auto requestCallback = [&status, &requestTemplate]
Emilian Peev31abd0a2017-05-11 18:37:46 +01003150 (common::V1_0::Status s, const device::V3_2::CameraMetadata& request) {
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003151 status = s;
3152 if (status == common::V1_0::Status::OK) {
3153 const camera_metadata *r =
3154 reinterpret_cast<const camera_metadata_t*>(request.data());
3155 size_t expectedSize = request.size();
3156 int ret = validate_camera_metadata_structure(r, &expectedSize);
3157 if (ret == OK || ret == CAMERA_METADATA_VALIDATION_SHIFTED) {
3158 *requestTemplate = clone_camera_metadata(r);
3159 if (*requestTemplate == nullptr) {
3160 ALOGE("%s: Unable to clone camera metadata received from HAL",
3161 __FUNCTION__);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003162 status = common::V1_0::Status::INTERNAL_ERROR;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003163 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003164 } else {
3165 ALOGE("%s: Malformed camera metadata received from HAL", __FUNCTION__);
3166 status = common::V1_0::Status::INTERNAL_ERROR;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003167 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003168 }
3169 };
3170 hardware::Return<void> err;
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003171 RequestTemplate id;
3172 switch (templateId) {
Emilian Peevf4816702020-04-03 15:44:51 -07003173 case CAMERA_TEMPLATE_PREVIEW:
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003174 id = RequestTemplate::PREVIEW;
3175 break;
Emilian Peevf4816702020-04-03 15:44:51 -07003176 case CAMERA_TEMPLATE_STILL_CAPTURE:
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003177 id = RequestTemplate::STILL_CAPTURE;
3178 break;
Emilian Peevf4816702020-04-03 15:44:51 -07003179 case CAMERA_TEMPLATE_VIDEO_RECORD:
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003180 id = RequestTemplate::VIDEO_RECORD;
3181 break;
Emilian Peevf4816702020-04-03 15:44:51 -07003182 case CAMERA_TEMPLATE_VIDEO_SNAPSHOT:
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003183 id = RequestTemplate::VIDEO_SNAPSHOT;
3184 break;
Emilian Peevf4816702020-04-03 15:44:51 -07003185 case CAMERA_TEMPLATE_ZERO_SHUTTER_LAG:
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003186 id = RequestTemplate::ZERO_SHUTTER_LAG;
3187 break;
Emilian Peevf4816702020-04-03 15:44:51 -07003188 case CAMERA_TEMPLATE_MANUAL:
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003189 id = RequestTemplate::MANUAL;
3190 break;
3191 default:
3192 // Unknown template ID, or this HAL is too old to support it
3193 return BAD_VALUE;
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003194 }
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003195 err = mHidlSession->constructDefaultRequestSettings(id, requestCallback);
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003196
Emilian Peev31abd0a2017-05-11 18:37:46 +01003197 if (!err.isOk()) {
3198 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3199 res = DEAD_OBJECT;
3200 } else {
3201 res = CameraProviderManager::mapToStatusT(status);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003202 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003203
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003204 return res;
3205}
3206
Emilian Peev4ec17882019-01-24 17:16:58 -08003207bool Camera3Device::HalInterface::isReconfigurationRequired(CameraMetadata& oldSessionParams,
3208 CameraMetadata& newSessionParams) {
3209 // We do reconfiguration by default;
3210 bool ret = true;
3211 if ((mHidlSession_3_5 != nullptr) && mIsReconfigurationQuerySupported) {
3212 android::hardware::hidl_vec<uint8_t> oldParams, newParams;
3213 camera_metadata_t* oldSessioMeta = const_cast<camera_metadata_t*>(
3214 oldSessionParams.getAndLock());
3215 camera_metadata_t* newSessioMeta = const_cast<camera_metadata_t*>(
3216 newSessionParams.getAndLock());
3217 oldParams.setToExternal(reinterpret_cast<uint8_t*>(oldSessioMeta),
3218 get_camera_metadata_size(oldSessioMeta));
3219 newParams.setToExternal(reinterpret_cast<uint8_t*>(newSessioMeta),
3220 get_camera_metadata_size(newSessioMeta));
3221 hardware::camera::common::V1_0::Status callStatus;
3222 bool required;
3223 auto hidlCb = [&callStatus, &required] (hardware::camera::common::V1_0::Status s,
3224 bool requiredFlag) {
3225 callStatus = s;
3226 required = requiredFlag;
3227 };
3228 auto err = mHidlSession_3_5->isReconfigurationRequired(oldParams, newParams, hidlCb);
3229 oldSessionParams.unlock(oldSessioMeta);
3230 newSessionParams.unlock(newSessioMeta);
3231 if (err.isOk()) {
3232 switch (callStatus) {
3233 case hardware::camera::common::V1_0::Status::OK:
3234 ret = required;
3235 break;
3236 case hardware::camera::common::V1_0::Status::METHOD_NOT_SUPPORTED:
3237 mIsReconfigurationQuerySupported = false;
3238 ret = true;
3239 break;
3240 default:
3241 ALOGV("%s: Reconfiguration query failed: %d", __FUNCTION__, callStatus);
3242 ret = true;
3243 }
3244 } else {
3245 ALOGE("%s: Unexpected binder error: %s", __FUNCTION__, err.description().c_str());
3246 ret = true;
3247 }
3248 }
3249
3250 return ret;
3251}
3252
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003253status_t Camera3Device::HalInterface::configureStreams(const camera_metadata_t *sessionParams,
Emilian Peevf4816702020-04-03 15:44:51 -07003254 camera_stream_configuration *config, const std::vector<uint32_t>& bufferSizes) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003255 ATRACE_NAME("CameraHal::configureStreams");
3256 if (!valid()) return INVALID_OPERATION;
3257 status_t res = OK;
3258
Shuzhen Wang83bff122020-11-20 15:51:39 -08003259 if (config->input_is_multi_resolution && mHidlSession_3_7 == nullptr) {
3260 ALOGE("%s: Camera device doesn't support multi-resolution input stream", __FUNCTION__);
3261 return BAD_VALUE;
3262 }
3263
Emilian Peev31abd0a2017-05-11 18:37:46 +01003264 // Convert stream config to HIDL
3265 std::set<int> activeStreams;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003266 device::V3_2::StreamConfiguration requestedConfiguration3_2;
3267 device::V3_4::StreamConfiguration requestedConfiguration3_4;
Shuzhen Wang83bff122020-11-20 15:51:39 -08003268 device::V3_7::StreamConfiguration requestedConfiguration3_7;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003269 requestedConfiguration3_2.streams.resize(config->num_streams);
3270 requestedConfiguration3_4.streams.resize(config->num_streams);
Shuzhen Wang83bff122020-11-20 15:51:39 -08003271 requestedConfiguration3_7.streams.resize(config->num_streams);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003272 for (size_t i = 0; i < config->num_streams; i++) {
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003273 device::V3_2::Stream &dst3_2 = requestedConfiguration3_2.streams[i];
3274 device::V3_4::Stream &dst3_4 = requestedConfiguration3_4.streams[i];
Shuzhen Wang83bff122020-11-20 15:51:39 -08003275 device::V3_7::Stream &dst3_7 = requestedConfiguration3_7.streams[i];
Emilian Peevf4816702020-04-03 15:44:51 -07003276 camera3::camera_stream_t *src = config->streams[i];
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003277
Emilian Peev31abd0a2017-05-11 18:37:46 +01003278 Camera3Stream* cam3stream = Camera3Stream::cast(src);
3279 cam3stream->setBufferFreedListener(this);
3280 int streamId = cam3stream->getId();
3281 StreamType streamType;
3282 switch (src->stream_type) {
Emilian Peevf4816702020-04-03 15:44:51 -07003283 case CAMERA_STREAM_OUTPUT:
Emilian Peev31abd0a2017-05-11 18:37:46 +01003284 streamType = StreamType::OUTPUT;
3285 break;
Emilian Peevf4816702020-04-03 15:44:51 -07003286 case CAMERA_STREAM_INPUT:
Emilian Peev31abd0a2017-05-11 18:37:46 +01003287 streamType = StreamType::INPUT;
3288 break;
3289 default:
3290 ALOGE("%s: Stream %d: Unsupported stream type %d",
3291 __FUNCTION__, streamId, config->streams[i]->stream_type);
3292 return BAD_VALUE;
3293 }
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003294 dst3_2.id = streamId;
3295 dst3_2.streamType = streamType;
3296 dst3_2.width = src->width;
3297 dst3_2.height = src->height;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003298 dst3_2.usage = mapToConsumerUsage(cam3stream->getUsage());
Emilian Peevf4816702020-04-03 15:44:51 -07003299 dst3_2.rotation = mapToStreamRotation((camera_stream_rotation_t) src->rotation);
Shuzhen Wang92653952019-05-07 15:11:43 -07003300 // For HidlSession version 3.5 or newer, the format and dataSpace sent
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08003301 // to HAL are original, not the overridden ones.
Shuzhen Wang92653952019-05-07 15:11:43 -07003302 if (mHidlSession_3_5 != nullptr) {
3303 dst3_2.format = mapToPixelFormat(cam3stream->isFormatOverridden() ?
3304 cam3stream->getOriginalFormat() : src->format);
3305 dst3_2.dataSpace = mapToHidlDataspace(cam3stream->isDataSpaceOverridden() ?
3306 cam3stream->getOriginalDataSpace() : src->data_space);
3307 } else {
3308 dst3_2.format = mapToPixelFormat(src->format);
3309 dst3_2.dataSpace = mapToHidlDataspace(src->data_space);
3310 }
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003311 dst3_4.v3_2 = dst3_2;
Emilian Peev192ee832018-01-31 14:46:47 +00003312 dst3_4.bufferSize = bufferSizes[i];
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003313 if (src->physical_camera_id != nullptr) {
3314 dst3_4.physicalCameraId = src->physical_camera_id;
3315 }
Shuzhen Wang83bff122020-11-20 15:51:39 -08003316 dst3_7.v3_4 = dst3_4;
3317 dst3_7.groupId = cam3stream->getHalStreamGroupId();
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08003318 dst3_7.sensorPixelModesUsed.resize(src->sensor_pixel_modes_used.size());
3319 size_t j = 0;
3320 for (int mode : src->sensor_pixel_modes_used) {
3321 dst3_7.sensorPixelModesUsed[j++] =
3322 static_cast<CameraMetadataEnumAndroidSensorPixelMode>(mode);
3323 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003324 activeStreams.insert(streamId);
3325 // Create Buffer ID map if necessary
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003326 mBufferRecords.tryCreateBufferCache(streamId);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003327 }
3328 // remove BufferIdMap for deleted streams
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003329 mBufferRecords.removeInactiveBufferCaches(activeStreams);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003330
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003331 StreamConfigurationMode operationMode;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003332 res = mapToStreamConfigurationMode(
Emilian Peevf4816702020-04-03 15:44:51 -07003333 (camera_stream_configuration_mode_t) config->operation_mode,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003334 /*out*/ &operationMode);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003335 if (res != OK) {
3336 return res;
3337 }
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003338 requestedConfiguration3_2.operationMode = operationMode;
3339 requestedConfiguration3_4.operationMode = operationMode;
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08003340 requestedConfiguration3_7.operationMode = operationMode;
3341 size_t sessionParamSize = get_camera_metadata_size(sessionParams);
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003342 requestedConfiguration3_4.sessionParams.setToExternal(
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003343 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(sessionParams)),
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08003344 sessionParamSize);
Shuzhen Wang83bff122020-11-20 15:51:39 -08003345 requestedConfiguration3_7.operationMode = operationMode;
3346 requestedConfiguration3_7.sessionParams.setToExternal(
3347 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(sessionParams)),
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08003348 sessionParamSize);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003349
Emilian Peev31abd0a2017-05-11 18:37:46 +01003350 // Invoke configureStreams
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003351 device::V3_3::HalStreamConfiguration finalConfiguration;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003352 device::V3_4::HalStreamConfiguration finalConfiguration3_4;
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003353 device::V3_6::HalStreamConfiguration finalConfiguration3_6;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003354 common::V1_0::Status status;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003355
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003356 auto configStream34Cb = [&status, &finalConfiguration3_4]
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003357 (common::V1_0::Status s, const device::V3_4::HalStreamConfiguration& halConfiguration) {
3358 finalConfiguration3_4 = halConfiguration;
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003359 status = s;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003360 };
3361
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003362 auto configStream36Cb = [&status, &finalConfiguration3_6]
3363 (common::V1_0::Status s, const device::V3_6::HalStreamConfiguration& halConfiguration) {
3364 finalConfiguration3_6 = halConfiguration;
3365 status = s;
3366 };
3367
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003368 auto postprocConfigStream34 = [&finalConfiguration, &finalConfiguration3_4]
3369 (hardware::Return<void>& err) -> status_t {
3370 if (!err.isOk()) {
3371 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3372 return DEAD_OBJECT;
3373 }
3374 finalConfiguration.streams.resize(finalConfiguration3_4.streams.size());
3375 for (size_t i = 0; i < finalConfiguration3_4.streams.size(); i++) {
3376 finalConfiguration.streams[i] = finalConfiguration3_4.streams[i].v3_3;
3377 }
3378 return OK;
3379 };
3380
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003381 auto postprocConfigStream36 = [&finalConfiguration, &finalConfiguration3_6]
3382 (hardware::Return<void>& err) -> status_t {
3383 if (!err.isOk()) {
3384 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3385 return DEAD_OBJECT;
3386 }
3387 finalConfiguration.streams.resize(finalConfiguration3_6.streams.size());
3388 for (size_t i = 0; i < finalConfiguration3_6.streams.size(); i++) {
3389 finalConfiguration.streams[i] = finalConfiguration3_6.streams[i].v3_4.v3_3;
3390 }
3391 return OK;
3392 };
3393
Shuzhen Wang92653952019-05-07 15:11:43 -07003394 // See which version of HAL we have
Shuzhen Wang83bff122020-11-20 15:51:39 -08003395 if (mHidlSession_3_7 != nullptr) {
3396 ALOGV("%s: v3.7 device found", __FUNCTION__);
3397 requestedConfiguration3_7.streamConfigCounter = mNextStreamConfigCounter++;
3398 requestedConfiguration3_7.multiResolutionInputImage = config->input_is_multi_resolution;
3399 auto err = mHidlSession_3_7->configureStreams_3_7(
3400 requestedConfiguration3_7, configStream36Cb);
3401 res = postprocConfigStream36(err);
3402 if (res != OK) {
3403 return res;
3404 }
3405 } else if (mHidlSession_3_6 != nullptr) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003406 ALOGV("%s: v3.6 device found", __FUNCTION__);
3407 device::V3_5::StreamConfiguration requestedConfiguration3_5;
3408 requestedConfiguration3_5.v3_4 = requestedConfiguration3_4;
3409 requestedConfiguration3_5.streamConfigCounter = mNextStreamConfigCounter++;
3410 auto err = mHidlSession_3_6->configureStreams_3_6(
3411 requestedConfiguration3_5, configStream36Cb);
3412 res = postprocConfigStream36(err);
3413 if (res != OK) {
3414 return res;
3415 }
3416 } else if (mHidlSession_3_5 != nullptr) {
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003417 ALOGV("%s: v3.5 device found", __FUNCTION__);
3418 device::V3_5::StreamConfiguration requestedConfiguration3_5;
3419 requestedConfiguration3_5.v3_4 = requestedConfiguration3_4;
3420 requestedConfiguration3_5.streamConfigCounter = mNextStreamConfigCounter++;
3421 auto err = mHidlSession_3_5->configureStreams_3_5(
3422 requestedConfiguration3_5, configStream34Cb);
3423 res = postprocConfigStream34(err);
3424 if (res != OK) {
3425 return res;
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003426 }
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003427 } else if (mHidlSession_3_4 != nullptr) {
3428 // We do; use v3.4 for the call
3429 ALOGV("%s: v3.4 device found", __FUNCTION__);
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003430 auto err = mHidlSession_3_4->configureStreams_3_4(
3431 requestedConfiguration3_4, configStream34Cb);
3432 res = postprocConfigStream34(err);
3433 if (res != OK) {
3434 return res;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003435 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003436 } else if (mHidlSession_3_3 != nullptr) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003437 // We do; use v3.3 for the call
3438 ALOGV("%s: v3.3 device found", __FUNCTION__);
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003439 auto err = mHidlSession_3_3->configureStreams_3_3(requestedConfiguration3_2,
Emilian Peev31abd0a2017-05-11 18:37:46 +01003440 [&status, &finalConfiguration]
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003441 (common::V1_0::Status s, const device::V3_3::HalStreamConfiguration& halConfiguration) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003442 finalConfiguration = halConfiguration;
3443 status = s;
3444 });
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003445 if (!err.isOk()) {
3446 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3447 return DEAD_OBJECT;
3448 }
3449 } else {
3450 // We don't; use v3.2 call and construct a v3.3 HalStreamConfiguration
3451 ALOGV("%s: v3.2 device found", __FUNCTION__);
3452 HalStreamConfiguration finalConfiguration_3_2;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003453 auto err = mHidlSession->configureStreams(requestedConfiguration3_2,
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003454 [&status, &finalConfiguration_3_2]
3455 (common::V1_0::Status s, const HalStreamConfiguration& halConfiguration) {
3456 finalConfiguration_3_2 = halConfiguration;
3457 status = s;
3458 });
3459 if (!err.isOk()) {
3460 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3461 return DEAD_OBJECT;
3462 }
3463 finalConfiguration.streams.resize(finalConfiguration_3_2.streams.size());
3464 for (size_t i = 0; i < finalConfiguration_3_2.streams.size(); i++) {
3465 finalConfiguration.streams[i].v3_2 = finalConfiguration_3_2.streams[i];
3466 finalConfiguration.streams[i].overrideDataSpace =
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003467 requestedConfiguration3_2.streams[i].dataSpace;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003468 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003469 }
3470
3471 if (status != common::V1_0::Status::OK ) {
3472 return CameraProviderManager::mapToStatusT(status);
3473 }
3474
3475 // And convert output stream configuration from HIDL
3476
3477 for (size_t i = 0; i < config->num_streams; i++) {
Emilian Peevf4816702020-04-03 15:44:51 -07003478 camera3::camera_stream_t *dst = config->streams[i];
Emilian Peev31abd0a2017-05-11 18:37:46 +01003479 int streamId = Camera3Stream::cast(dst)->getId();
3480
3481 // Start scan at i, with the assumption that the stream order matches
3482 size_t realIdx = i;
3483 bool found = false;
Eino-Ville Talvala370875f2019-04-12 12:40:27 -07003484 size_t halStreamCount = finalConfiguration.streams.size();
3485 for (size_t idx = 0; idx < halStreamCount; idx++) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003486 if (finalConfiguration.streams[realIdx].v3_2.id == streamId) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003487 found = true;
3488 break;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003489 }
Eino-Ville Talvala370875f2019-04-12 12:40:27 -07003490 realIdx = (realIdx >= halStreamCount - 1) ? 0 : realIdx + 1;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003491 }
3492 if (!found) {
3493 ALOGE("%s: Stream %d not found in stream configuration response from HAL",
3494 __FUNCTION__, streamId);
3495 return INVALID_OPERATION;
3496 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003497 device::V3_3::HalStream &src = finalConfiguration.streams[realIdx];
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003498 device::V3_6::HalStream &src_36 = finalConfiguration3_6.streams[realIdx];
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003499
Emilian Peev710c1422017-08-30 11:19:38 +01003500 Camera3Stream* dstStream = Camera3Stream::cast(dst);
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003501 int overrideFormat = mapToFrameworkFormat(src.v3_2.overrideFormat);
3502 android_dataspace overrideDataSpace = mapToFrameworkDataspace(src.overrideDataSpace);
3503
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003504 if (mHidlSession_3_6 != nullptr) {
3505 dstStream->setOfflineProcessingSupport(src_36.supportOffline);
3506 }
3507
Yin-Chia Yeh90667662019-07-01 15:45:00 -07003508 if (dstStream->getOriginalFormat() != HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
Shuzhen Wang92653952019-05-07 15:11:43 -07003509 dstStream->setFormatOverride(false);
3510 dstStream->setDataSpaceOverride(false);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003511 if (dst->format != overrideFormat) {
3512 ALOGE("%s: Stream %d: Format override not allowed for format 0x%x", __FUNCTION__,
3513 streamId, dst->format);
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003514 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003515 if (dst->data_space != overrideDataSpace) {
3516 ALOGE("%s: Stream %d: DataSpace override not allowed for format 0x%x", __FUNCTION__,
3517 streamId, dst->format);
3518 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003519 } else {
Shuzhen Wang92653952019-05-07 15:11:43 -07003520 bool needFormatOverride =
3521 requestedConfiguration3_2.streams[i].format != src.v3_2.overrideFormat;
3522 bool needDataspaceOverride =
3523 requestedConfiguration3_2.streams[i].dataSpace != src.overrideDataSpace;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003524 // Override allowed with IMPLEMENTATION_DEFINED
Shuzhen Wang92653952019-05-07 15:11:43 -07003525 dstStream->setFormatOverride(needFormatOverride);
3526 dstStream->setDataSpaceOverride(needDataspaceOverride);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003527 dst->format = overrideFormat;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003528 dst->data_space = overrideDataSpace;
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003529 }
3530
Emilian Peevf4816702020-04-03 15:44:51 -07003531 if (dst->stream_type == CAMERA_STREAM_INPUT) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003532 if (src.v3_2.producerUsage != 0) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003533 ALOGE("%s: Stream %d: INPUT streams must have 0 for producer usage",
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003534 __FUNCTION__, streamId);
3535 return INVALID_OPERATION;
3536 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003537 dstStream->setUsage(
3538 mapConsumerToFrameworkUsage(src.v3_2.consumerUsage));
Emilian Peev31abd0a2017-05-11 18:37:46 +01003539 } else {
3540 // OUTPUT
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003541 if (src.v3_2.consumerUsage != 0) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003542 ALOGE("%s: Stream %d: OUTPUT streams must have 0 for consumer usage",
3543 __FUNCTION__, streamId);
3544 return INVALID_OPERATION;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003545 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003546 dstStream->setUsage(
3547 mapProducerToFrameworkUsage(src.v3_2.producerUsage));
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003548 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003549 dst->max_buffers = src.v3_2.maxBuffers;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003550 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003551
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003552 return res;
3553}
3554
Cliff Wuc2ad9c82021-04-21 00:58:58 +08003555status_t Camera3Device::HalInterface::configureInjectedStreams(
3556 const camera_metadata_t* sessionParams, camera_stream_configuration* config,
3557 const std::vector<uint32_t>& bufferSizes,
3558 const CameraMetadata& cameraCharacteristics) {
3559 ATRACE_NAME("InjectionCameraHal::configureStreams");
3560 if (!valid()) return INVALID_OPERATION;
3561 status_t res = OK;
3562
3563 if (config->input_is_multi_resolution) {
3564 ALOGE("%s: Injection camera device doesn't support multi-resolution input "
3565 "stream", __FUNCTION__);
3566 return BAD_VALUE;
3567 }
3568
3569 // Convert stream config to HIDL
3570 std::set<int> activeStreams;
3571 device::V3_2::StreamConfiguration requestedConfiguration3_2;
3572 device::V3_4::StreamConfiguration requestedConfiguration3_4;
3573 device::V3_7::StreamConfiguration requestedConfiguration3_7;
3574 requestedConfiguration3_2.streams.resize(config->num_streams);
3575 requestedConfiguration3_4.streams.resize(config->num_streams);
3576 requestedConfiguration3_7.streams.resize(config->num_streams);
3577 for (size_t i = 0; i < config->num_streams; i++) {
3578 device::V3_2::Stream& dst3_2 = requestedConfiguration3_2.streams[i];
3579 device::V3_4::Stream& dst3_4 = requestedConfiguration3_4.streams[i];
3580 device::V3_7::Stream& dst3_7 = requestedConfiguration3_7.streams[i];
3581 camera3::camera_stream_t* src = config->streams[i];
3582
3583 Camera3Stream* cam3stream = Camera3Stream::cast(src);
3584 cam3stream->setBufferFreedListener(this);
3585 int streamId = cam3stream->getId();
3586 StreamType streamType;
3587 switch (src->stream_type) {
3588 case CAMERA_STREAM_OUTPUT:
3589 streamType = StreamType::OUTPUT;
3590 break;
3591 case CAMERA_STREAM_INPUT:
3592 streamType = StreamType::INPUT;
3593 break;
3594 default:
3595 ALOGE("%s: Stream %d: Unsupported stream type %d", __FUNCTION__,
3596 streamId, config->streams[i]->stream_type);
3597 return BAD_VALUE;
3598 }
3599 dst3_2.id = streamId;
3600 dst3_2.streamType = streamType;
3601 dst3_2.width = src->width;
3602 dst3_2.height = src->height;
3603 dst3_2.usage = mapToConsumerUsage(cam3stream->getUsage());
3604 dst3_2.rotation =
3605 mapToStreamRotation((camera_stream_rotation_t)src->rotation);
3606 // For HidlSession version 3.5 or newer, the format and dataSpace sent
3607 // to HAL are original, not the overridden ones.
3608 if (mHidlSession_3_5 != nullptr) {
3609 dst3_2.format = mapToPixelFormat(cam3stream->isFormatOverridden()
3610 ? cam3stream->getOriginalFormat()
3611 : src->format);
3612 dst3_2.dataSpace =
3613 mapToHidlDataspace(cam3stream->isDataSpaceOverridden()
3614 ? cam3stream->getOriginalDataSpace()
3615 : src->data_space);
3616 } else {
3617 dst3_2.format = mapToPixelFormat(src->format);
3618 dst3_2.dataSpace = mapToHidlDataspace(src->data_space);
3619 }
3620 dst3_4.v3_2 = dst3_2;
3621 dst3_4.bufferSize = bufferSizes[i];
3622 if (src->physical_camera_id != nullptr) {
3623 dst3_4.physicalCameraId = src->physical_camera_id;
3624 }
3625 dst3_7.v3_4 = dst3_4;
3626 dst3_7.groupId = cam3stream->getHalStreamGroupId();
3627 dst3_7.sensorPixelModesUsed.resize(src->sensor_pixel_modes_used.size());
3628 size_t j = 0;
3629 for (int mode : src->sensor_pixel_modes_used) {
3630 dst3_7.sensorPixelModesUsed[j++] =
3631 static_cast<CameraMetadataEnumAndroidSensorPixelMode>(mode);
3632 }
3633 activeStreams.insert(streamId);
3634 // Create Buffer ID map if necessary
3635 mBufferRecords.tryCreateBufferCache(streamId);
3636 }
3637 // remove BufferIdMap for deleted streams
3638 mBufferRecords.removeInactiveBufferCaches(activeStreams);
3639
3640 StreamConfigurationMode operationMode;
3641 res = mapToStreamConfigurationMode(
3642 (camera_stream_configuration_mode_t)config->operation_mode,
3643 /*out*/ &operationMode);
3644 if (res != OK) {
3645 return res;
3646 }
3647 requestedConfiguration3_7.operationMode = operationMode;
3648 size_t sessionParamSize = get_camera_metadata_size(sessionParams);
3649 requestedConfiguration3_7.operationMode = operationMode;
3650 requestedConfiguration3_7.sessionParams.setToExternal(
3651 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(sessionParams)),
3652 sessionParamSize);
3653
3654 // See which version of HAL we have
3655 if (mHidlSession_3_7 != nullptr) {
3656 requestedConfiguration3_7.streamConfigCounter = mNextStreamConfigCounter++;
3657 requestedConfiguration3_7.multiResolutionInputImage =
3658 config->input_is_multi_resolution;
3659
3660 const camera_metadata_t* rawMetadata = cameraCharacteristics.getAndLock();
3661 ::android::hardware::camera::device::V3_2::CameraMetadata hidlChars = {};
3662 hidlChars.setToExternal(
3663 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(rawMetadata)),
3664 get_camera_metadata_size(rawMetadata));
3665 cameraCharacteristics.unlock(rawMetadata);
3666
3667 sp<hardware::camera::device::V3_7::ICameraInjectionSession>
3668 hidlInjectionSession_3_7;
3669 auto castInjectionResult_3_7 =
3670 device::V3_7::ICameraInjectionSession::castFrom(mHidlSession_3_7);
3671 if (castInjectionResult_3_7.isOk()) {
3672 hidlInjectionSession_3_7 = castInjectionResult_3_7;
3673 } else {
3674 ALOGE("%s: Transaction error: %s", __FUNCTION__,
3675 castInjectionResult_3_7.description().c_str());
3676 return DEAD_OBJECT;
3677 }
3678
3679 auto err = hidlInjectionSession_3_7->configureInjectionStreams(
3680 requestedConfiguration3_7, hidlChars);
3681 if (!err.isOk()) {
3682 ALOGE("%s: Transaction error: %s", __FUNCTION__,
3683 err.description().c_str());
3684 return DEAD_OBJECT;
3685 }
3686 } else {
3687 ALOGE("%s: mHidlSession_3_7 does not exist, the lowest version of injection "
3688 "session is 3.7", __FUNCTION__);
3689 return DEAD_OBJECT;
3690 }
3691
3692 return res;
3693}
3694
Emilian Peevf4816702020-04-03 15:44:51 -07003695status_t Camera3Device::HalInterface::wrapAsHidlRequest(camera_capture_request_t* request,
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003696 /*out*/device::V3_2::CaptureRequest* captureRequest,
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003697 /*out*/std::vector<native_handle_t*>* handlesCreated,
3698 /*out*/std::vector<std::pair<int32_t, int32_t>>* inflightBuffers) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003699 ATRACE_CALL();
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003700 if (captureRequest == nullptr || handlesCreated == nullptr || inflightBuffers == nullptr) {
3701 ALOGE("%s: captureRequest (%p), handlesCreated (%p), and inflightBuffers(%p) "
3702 "must not be null", __FUNCTION__, captureRequest, handlesCreated, inflightBuffers);
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003703 return BAD_VALUE;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003704 }
3705
3706 captureRequest->frameNumber = request->frame_number;
Yifan Hongf79b5542017-04-11 14:44:25 -07003707
3708 captureRequest->fmqSettingsSize = 0;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003709
3710 {
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003711 if (request->input_buffer != nullptr) {
3712 int32_t streamId = Camera3Stream::cast(request->input_buffer->stream)->getId();
3713 buffer_handle_t buf = *(request->input_buffer->buffer);
3714 auto pair = getBufferId(buf, streamId);
3715 bool isNewBuffer = pair.first;
3716 uint64_t bufferId = pair.second;
3717 captureRequest->inputBuffer.streamId = streamId;
3718 captureRequest->inputBuffer.bufferId = bufferId;
3719 captureRequest->inputBuffer.buffer = (isNewBuffer) ? buf : nullptr;
3720 captureRequest->inputBuffer.status = BufferStatus::OK;
3721 native_handle_t *acquireFence = nullptr;
3722 if (request->input_buffer->acquire_fence != -1) {
3723 acquireFence = native_handle_create(1,0);
3724 acquireFence->data[0] = request->input_buffer->acquire_fence;
3725 handlesCreated->push_back(acquireFence);
3726 }
3727 captureRequest->inputBuffer.acquireFence = acquireFence;
3728 captureRequest->inputBuffer.releaseFence = nullptr;
3729
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003730 mBufferRecords.pushInflightBuffer(captureRequest->frameNumber, streamId,
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003731 request->input_buffer->buffer);
3732 inflightBuffers->push_back(std::make_pair(captureRequest->frameNumber, streamId));
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003733 } else {
3734 captureRequest->inputBuffer.streamId = -1;
3735 captureRequest->inputBuffer.bufferId = BUFFER_ID_NO_BUFFER;
3736 }
3737
3738 captureRequest->outputBuffers.resize(request->num_output_buffers);
3739 for (size_t i = 0; i < request->num_output_buffers; i++) {
Emilian Peevf4816702020-04-03 15:44:51 -07003740 const camera_stream_buffer_t *src = request->output_buffers + i;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003741 StreamBuffer &dst = captureRequest->outputBuffers[i];
3742 int32_t streamId = Camera3Stream::cast(src->stream)->getId();
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003743 if (src->buffer != nullptr) {
3744 buffer_handle_t buf = *(src->buffer);
3745 auto pair = getBufferId(buf, streamId);
3746 bool isNewBuffer = pair.first;
3747 dst.bufferId = pair.second;
3748 dst.buffer = isNewBuffer ? buf : nullptr;
3749 native_handle_t *acquireFence = nullptr;
3750 if (src->acquire_fence != -1) {
3751 acquireFence = native_handle_create(1,0);
3752 acquireFence->data[0] = src->acquire_fence;
3753 handlesCreated->push_back(acquireFence);
3754 }
3755 dst.acquireFence = acquireFence;
3756 } else if (mUseHalBufManager) {
3757 // HAL buffer management path
3758 dst.bufferId = BUFFER_ID_NO_BUFFER;
3759 dst.buffer = nullptr;
3760 dst.acquireFence = nullptr;
3761 } else {
3762 ALOGE("%s: cannot send a null buffer in capture request!", __FUNCTION__);
3763 return BAD_VALUE;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003764 }
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003765 dst.streamId = streamId;
3766 dst.status = BufferStatus::OK;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003767 dst.releaseFence = nullptr;
3768
Yin-Chia Yeh5f840f82019-03-05 11:59:04 -08003769 // Output buffers are empty when using HAL buffer manager
3770 if (!mUseHalBufManager) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003771 mBufferRecords.pushInflightBuffer(
3772 captureRequest->frameNumber, streamId, src->buffer);
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003773 inflightBuffers->push_back(std::make_pair(captureRequest->frameNumber, streamId));
Yin-Chia Yeh5f840f82019-03-05 11:59:04 -08003774 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003775 }
3776 }
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003777 return OK;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003778}
3779
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003780void Camera3Device::HalInterface::cleanupNativeHandles(
3781 std::vector<native_handle_t*> *handles, bool closeFd) {
3782 if (handles == nullptr) {
3783 return;
3784 }
3785 if (closeFd) {
3786 for (auto& handle : *handles) {
3787 native_handle_close(handle);
3788 }
3789 }
3790 for (auto& handle : *handles) {
3791 native_handle_delete(handle);
3792 }
3793 handles->clear();
3794 return;
3795}
3796
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003797status_t Camera3Device::HalInterface::processBatchCaptureRequests(
Emilian Peevf4816702020-04-03 15:44:51 -07003798 std::vector<camera_capture_request_t*>& requests,/*out*/uint32_t* numRequestProcessed) {
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003799 ATRACE_NAME("CameraHal::processBatchCaptureRequests");
3800 if (!valid()) return INVALID_OPERATION;
3801
Emilian Peevaebbe412018-01-15 13:53:24 +00003802 sp<device::V3_4::ICameraDeviceSession> hidlSession_3_4;
Shuzhen Wang83bff122020-11-20 15:51:39 -08003803 sp<device::V3_7::ICameraDeviceSession> hidlSession_3_7;
3804 auto castResult_3_7 = device::V3_7::ICameraDeviceSession::castFrom(mHidlSession);
3805 if (castResult_3_7.isOk()) {
3806 hidlSession_3_7 = castResult_3_7;
3807 }
Emilian Peevaebbe412018-01-15 13:53:24 +00003808 auto castResult_3_4 = device::V3_4::ICameraDeviceSession::castFrom(mHidlSession);
3809 if (castResult_3_4.isOk()) {
3810 hidlSession_3_4 = castResult_3_4;
3811 }
3812
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003813 hardware::hidl_vec<device::V3_2::CaptureRequest> captureRequests;
Emilian Peevaebbe412018-01-15 13:53:24 +00003814 hardware::hidl_vec<device::V3_4::CaptureRequest> captureRequests_3_4;
Shuzhen Wang83bff122020-11-20 15:51:39 -08003815 hardware::hidl_vec<device::V3_7::CaptureRequest> captureRequests_3_7;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003816 size_t batchSize = requests.size();
Shuzhen Wang83bff122020-11-20 15:51:39 -08003817 if (hidlSession_3_7 != nullptr) {
3818 captureRequests_3_7.resize(batchSize);
3819 } else if (hidlSession_3_4 != nullptr) {
Emilian Peevaebbe412018-01-15 13:53:24 +00003820 captureRequests_3_4.resize(batchSize);
3821 } else {
3822 captureRequests.resize(batchSize);
3823 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003824 std::vector<native_handle_t*> handlesCreated;
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003825 std::vector<std::pair<int32_t, int32_t>> inflightBuffers;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003826
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003827 status_t res = OK;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003828 for (size_t i = 0; i < batchSize; i++) {
Shuzhen Wang83bff122020-11-20 15:51:39 -08003829 if (hidlSession_3_7 != nullptr) {
3830 res = wrapAsHidlRequest(requests[i], /*out*/&captureRequests_3_7[i].v3_4.v3_2,
3831 /*out*/&handlesCreated, /*out*/&inflightBuffers);
3832 } else if (hidlSession_3_4 != nullptr) {
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003833 res = wrapAsHidlRequest(requests[i], /*out*/&captureRequests_3_4[i].v3_2,
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003834 /*out*/&handlesCreated, /*out*/&inflightBuffers);
Emilian Peevaebbe412018-01-15 13:53:24 +00003835 } else {
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003836 res = wrapAsHidlRequest(requests[i], /*out*/&captureRequests[i],
3837 /*out*/&handlesCreated, /*out*/&inflightBuffers);
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003838 }
3839 if (res != OK) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003840 mBufferRecords.popInflightBuffers(inflightBuffers);
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003841 cleanupNativeHandles(&handlesCreated);
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003842 return res;
Emilian Peevaebbe412018-01-15 13:53:24 +00003843 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003844 }
3845
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003846 std::vector<device::V3_2::BufferCache> cachesToRemove;
3847 {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003848 std::lock_guard<std::mutex> lock(mFreedBuffersLock);
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003849 for (auto& pair : mFreedBuffers) {
3850 // The stream might have been removed since onBufferFreed
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003851 if (mBufferRecords.isStreamCached(pair.first)) {
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003852 cachesToRemove.push_back({pair.first, pair.second});
3853 }
3854 }
3855 mFreedBuffers.clear();
3856 }
3857
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003858 common::V1_0::Status status = common::V1_0::Status::INTERNAL_ERROR;
3859 *numRequestProcessed = 0;
Yifan Hongf79b5542017-04-11 14:44:25 -07003860
3861 // Write metadata to FMQ.
3862 for (size_t i = 0; i < batchSize; i++) {
Emilian Peevf4816702020-04-03 15:44:51 -07003863 camera_capture_request_t* request = requests[i];
Emilian Peevaebbe412018-01-15 13:53:24 +00003864 device::V3_2::CaptureRequest* captureRequest;
Shuzhen Wang83bff122020-11-20 15:51:39 -08003865 if (hidlSession_3_7 != nullptr) {
3866 captureRequest = &captureRequests_3_7[i].v3_4.v3_2;
3867 } else if (hidlSession_3_4 != nullptr) {
Emilian Peevaebbe412018-01-15 13:53:24 +00003868 captureRequest = &captureRequests_3_4[i].v3_2;
3869 } else {
3870 captureRequest = &captureRequests[i];
3871 }
Yifan Hongf79b5542017-04-11 14:44:25 -07003872
3873 if (request->settings != nullptr) {
3874 size_t settingsSize = get_camera_metadata_size(request->settings);
3875 if (mRequestMetadataQueue != nullptr && mRequestMetadataQueue->write(
3876 reinterpret_cast<const uint8_t*>(request->settings), settingsSize)) {
3877 captureRequest->settings.resize(0);
3878 captureRequest->fmqSettingsSize = settingsSize;
3879 } else {
3880 if (mRequestMetadataQueue != nullptr) {
3881 ALOGW("%s: couldn't utilize fmq, fallback to hwbinder", __FUNCTION__);
3882 }
3883 captureRequest->settings.setToExternal(
3884 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(request->settings)),
3885 get_camera_metadata_size(request->settings));
3886 captureRequest->fmqSettingsSize = 0u;
3887 }
3888 } else {
3889 // A null request settings maps to a size-0 CameraMetadata
3890 captureRequest->settings.resize(0);
3891 captureRequest->fmqSettingsSize = 0u;
3892 }
Emilian Peevaebbe412018-01-15 13:53:24 +00003893
Shuzhen Wang83bff122020-11-20 15:51:39 -08003894 // hidl session 3.7 specific handling.
3895 if (hidlSession_3_7 != nullptr) {
3896 captureRequests_3_7[i].inputWidth = request->input_width;
3897 captureRequests_3_7[i].inputHeight = request->input_height;
3898 }
3899
3900 // hidl session 3.7 and 3.4 specific handling.
3901 if (hidlSession_3_7 != nullptr || hidlSession_3_4 != nullptr) {
3902 hardware::hidl_vec<device::V3_4::PhysicalCameraSetting>& physicalCameraSettings =
3903 (hidlSession_3_7 != nullptr) ?
3904 captureRequests_3_7[i].v3_4.physicalCameraSettings :
3905 captureRequests_3_4[i].physicalCameraSettings;
3906 physicalCameraSettings.resize(request->num_physcam_settings);
Emilian Peevaebbe412018-01-15 13:53:24 +00003907 for (size_t j = 0; j < request->num_physcam_settings; j++) {
Emilian Peev00420d22018-02-05 21:33:13 +00003908 if (request->physcam_settings != nullptr) {
3909 size_t settingsSize = get_camera_metadata_size(request->physcam_settings[j]);
3910 if (mRequestMetadataQueue != nullptr && mRequestMetadataQueue->write(
3911 reinterpret_cast<const uint8_t*>(request->physcam_settings[j]),
3912 settingsSize)) {
Shuzhen Wang83bff122020-11-20 15:51:39 -08003913 physicalCameraSettings[j].settings.resize(0);
3914 physicalCameraSettings[j].fmqSettingsSize = settingsSize;
Emilian Peev00420d22018-02-05 21:33:13 +00003915 } else {
3916 if (mRequestMetadataQueue != nullptr) {
3917 ALOGW("%s: couldn't utilize fmq, fallback to hwbinder", __FUNCTION__);
3918 }
Shuzhen Wang83bff122020-11-20 15:51:39 -08003919 physicalCameraSettings[j].settings.setToExternal(
Emilian Peev00420d22018-02-05 21:33:13 +00003920 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(
3921 request->physcam_settings[j])),
3922 get_camera_metadata_size(request->physcam_settings[j]));
Shuzhen Wang83bff122020-11-20 15:51:39 -08003923 physicalCameraSettings[j].fmqSettingsSize = 0u;
Emilian Peevaebbe412018-01-15 13:53:24 +00003924 }
Emilian Peev00420d22018-02-05 21:33:13 +00003925 } else {
Yin-Chia Yeha2849702021-03-10 10:11:33 -08003926 physicalCameraSettings[j].fmqSettingsSize = 0u;
3927 physicalCameraSettings[j].settings.resize(0);
Emilian Peevaebbe412018-01-15 13:53:24 +00003928 }
Shuzhen Wang83bff122020-11-20 15:51:39 -08003929 physicalCameraSettings[j].physicalCameraId = request->physcam_id[j];
Emilian Peevaebbe412018-01-15 13:53:24 +00003930 }
3931 }
Yifan Hongf79b5542017-04-11 14:44:25 -07003932 }
Emilian Peevaebbe412018-01-15 13:53:24 +00003933
3934 hardware::details::return_status err;
Jayant Chowdharyc8d581e2018-07-16 14:46:23 -07003935 auto resultCallback =
3936 [&status, &numRequestProcessed] (auto s, uint32_t n) {
3937 status = s;
3938 *numRequestProcessed = n;
3939 };
Shuzhen Wang83bff122020-11-20 15:51:39 -08003940 if (hidlSession_3_7 != nullptr) {
3941 err = hidlSession_3_7->processCaptureRequest_3_7(captureRequests_3_7, cachesToRemove,
3942 resultCallback);
3943 } else if (hidlSession_3_4 != nullptr) {
Emilian Peevaebbe412018-01-15 13:53:24 +00003944 err = hidlSession_3_4->processCaptureRequest_3_4(captureRequests_3_4, cachesToRemove,
Jayant Chowdharyc8d581e2018-07-16 14:46:23 -07003945 resultCallback);
Emilian Peevaebbe412018-01-15 13:53:24 +00003946 } else {
3947 err = mHidlSession->processCaptureRequest(captureRequests, cachesToRemove,
Jayant Chowdharyc8d581e2018-07-16 14:46:23 -07003948 resultCallback);
Emilian Peevaebbe412018-01-15 13:53:24 +00003949 }
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -07003950 if (!err.isOk()) {
3951 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003952 status = common::V1_0::Status::CAMERA_DISCONNECTED;
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -07003953 }
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003954
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003955 if (status == common::V1_0::Status::OK && *numRequestProcessed != batchSize) {
3956 ALOGE("%s: processCaptureRequest returns OK but processed %d/%zu requests",
3957 __FUNCTION__, *numRequestProcessed, batchSize);
3958 status = common::V1_0::Status::INTERNAL_ERROR;
3959 }
3960
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003961 res = CameraProviderManager::mapToStatusT(status);
3962 if (res == OK) {
3963 if (mHidlSession->isRemote()) {
3964 // Only close acquire fence FDs when the HIDL transaction succeeds (so the FDs have been
3965 // sent to camera HAL processes)
3966 cleanupNativeHandles(&handlesCreated, /*closeFd*/true);
3967 } else {
3968 // In passthrough mode the FDs are now owned by HAL
3969 cleanupNativeHandles(&handlesCreated);
3970 }
3971 } else {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003972 mBufferRecords.popInflightBuffers(inflightBuffers);
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003973 cleanupNativeHandles(&handlesCreated);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003974 }
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003975 return res;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003976}
3977
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003978status_t Camera3Device::HalInterface::flush() {
3979 ATRACE_NAME("CameraHal::flush");
3980 if (!valid()) return INVALID_OPERATION;
3981 status_t res = OK;
3982
Emilian Peev31abd0a2017-05-11 18:37:46 +01003983 auto err = mHidlSession->flush();
3984 if (!err.isOk()) {
3985 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3986 res = DEAD_OBJECT;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003987 } else {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003988 res = CameraProviderManager::mapToStatusT(err);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003989 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003990
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003991 return res;
3992}
3993
Emilian Peev31abd0a2017-05-11 18:37:46 +01003994status_t Camera3Device::HalInterface::dump(int /*fd*/) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003995 ATRACE_NAME("CameraHal::dump");
3996 if (!valid()) return INVALID_OPERATION;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003997
Emilian Peev31abd0a2017-05-11 18:37:46 +01003998 // Handled by CameraProviderManager::dump
3999
4000 return OK;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004001}
4002
4003status_t Camera3Device::HalInterface::close() {
4004 ATRACE_NAME("CameraHal::close()");
4005 if (!valid()) return INVALID_OPERATION;
4006 status_t res = OK;
4007
Emilian Peev31abd0a2017-05-11 18:37:46 +01004008 auto err = mHidlSession->close();
4009 // Interface will be dead shortly anyway, so don't log errors
4010 if (!err.isOk()) {
4011 res = DEAD_OBJECT;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004012 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01004013
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004014 return res;
4015}
4016
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004017void Camera3Device::HalInterface::signalPipelineDrain(const std::vector<int>& streamIds) {
4018 ATRACE_NAME("CameraHal::signalPipelineDrain");
4019 if (!valid() || mHidlSession_3_5 == nullptr) {
4020 ALOGE("%s called on invalid camera!", __FUNCTION__);
4021 return;
4022 }
4023
Yin-Chia Yehc300a072019-02-13 14:56:57 -08004024 auto err = mHidlSession_3_5->signalStreamFlush(streamIds, mNextStreamConfigCounter - 1);
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004025 if (!err.isOk()) {
4026 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
4027 return;
4028 }
4029}
4030
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004031status_t Camera3Device::HalInterface::switchToOffline(
4032 const std::vector<int32_t>& streamsToKeep,
4033 /*out*/hardware::camera::device::V3_6::CameraOfflineSessionInfo* offlineSessionInfo,
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004034 /*out*/sp<hardware::camera::device::V3_6::ICameraOfflineSession>* offlineSession,
4035 /*out*/camera3::BufferRecords* bufferRecords) {
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004036 ATRACE_NAME("CameraHal::switchToOffline");
4037 if (!valid() || mHidlSession_3_6 == nullptr) {
4038 ALOGE("%s called on invalid camera!", __FUNCTION__);
4039 return INVALID_OPERATION;
4040 }
4041
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004042 if (offlineSessionInfo == nullptr || offlineSession == nullptr || bufferRecords == nullptr) {
4043 ALOGE("%s: output arguments must not be null!", __FUNCTION__);
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004044 return INVALID_OPERATION;
4045 }
4046
4047 common::V1_0::Status status = common::V1_0::Status::INTERNAL_ERROR;
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004048 auto resultCallback =
4049 [&status, &offlineSessionInfo, &offlineSession] (auto s, auto info, auto session) {
4050 status = s;
4051 *offlineSessionInfo = info;
4052 *offlineSession = session;
4053 };
4054 auto err = mHidlSession_3_6->switchToOffline(streamsToKeep, resultCallback);
4055
4056 if (!err.isOk()) {
4057 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
4058 return DEAD_OBJECT;
4059 }
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004060
4061 status_t ret = CameraProviderManager::mapToStatusT(status);
4062 if (ret != OK) {
4063 return ret;
4064 }
4065
4066 // TODO: assert no ongoing requestBuffer/returnBuffer call here
4067 // TODO: update RequestBufferStateMachine to block requestBuffer/returnBuffer once HAL
4068 // returns from switchToOffline.
4069
4070
4071 // Validate buffer caches
4072 std::vector<int32_t> streams;
4073 streams.reserve(offlineSessionInfo->offlineStreams.size());
4074 for (auto offlineStream : offlineSessionInfo->offlineStreams) {
4075 int32_t id = offlineStream.id;
4076 streams.push_back(id);
4077 // Verify buffer caches
4078 std::vector<uint64_t> bufIds(offlineStream.circulatingBufferIds.begin(),
4079 offlineStream.circulatingBufferIds.end());
4080 if (!verifyBufferIds(id, bufIds)) {
4081 ALOGE("%s: stream ID %d buffer cache records mismatch!", __FUNCTION__, id);
4082 return UNKNOWN_ERROR;
4083 }
4084 }
4085
4086 // Move buffer records
4087 bufferRecords->takeBufferCaches(mBufferRecords, streams);
4088 bufferRecords->takeInflightBufferMap(mBufferRecords);
4089 bufferRecords->takeRequestedBufferMap(mBufferRecords);
4090 return ret;
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004091}
4092
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07004093void Camera3Device::HalInterface::getInflightBufferKeys(
4094 std::vector<std::pair<int32_t, int32_t>>* out) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004095 mBufferRecords.getInflightBufferKeys(out);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07004096 return;
4097}
4098
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08004099void Camera3Device::HalInterface::getInflightRequestBufferKeys(
4100 std::vector<uint64_t>* out) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004101 mBufferRecords.getInflightRequestBufferKeys(out);
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08004102 return;
4103}
4104
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004105bool Camera3Device::HalInterface::verifyBufferIds(
4106 int32_t streamId, std::vector<uint64_t>& bufIds) {
4107 return mBufferRecords.verifyBufferIds(streamId, bufIds);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004108}
4109
4110status_t Camera3Device::HalInterface::popInflightBuffer(
Yin-Chia Yehf4650602017-01-10 13:13:39 -08004111 int32_t frameNumber, int32_t streamId,
4112 /*out*/ buffer_handle_t **buffer) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004113 return mBufferRecords.popInflightBuffer(frameNumber, streamId, buffer);
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07004114}
4115
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004116status_t Camera3Device::HalInterface::pushInflightRequestBuffer(
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08004117 uint64_t bufferId, buffer_handle_t* buf, int32_t streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004118 return mBufferRecords.pushInflightRequestBuffer(bufferId, buf, streamId);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004119}
4120
4121// Find and pop a buffer_handle_t based on bufferId
4122status_t Camera3Device::HalInterface::popInflightRequestBuffer(
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08004123 uint64_t bufferId,
4124 /*out*/ buffer_handle_t** buffer,
4125 /*optional out*/ int32_t* streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004126 return mBufferRecords.popInflightRequestBuffer(bufferId, buffer, streamId);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004127}
4128
Yin-Chia Yeh77327052017-01-09 18:23:07 -08004129std::pair<bool, uint64_t> Camera3Device::HalInterface::getBufferId(
4130 const buffer_handle_t& buf, int streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004131 return mBufferRecords.getBufferId(buf, streamId);
Yin-Chia Yeh77327052017-01-09 18:23:07 -08004132}
4133
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07004134void Camera3Device::HalInterface::onBufferFreed(
4135 int streamId, const native_handle_t* handle) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004136 uint32_t bufferId = mBufferRecords.removeOneBufferCache(streamId, handle);
4137 std::lock_guard<std::mutex> lock(mFreedBuffersLock);
4138 if (bufferId != BUFFER_ID_NO_BUFFER) {
4139 mFreedBuffers.push_back(std::make_pair(streamId, bufferId));
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07004140 }
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07004141}
4142
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07004143void Camera3Device::HalInterface::onStreamReConfigured(int streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004144 std::vector<uint64_t> bufIds = mBufferRecords.clearBufferCaches(streamId);
4145 std::lock_guard<std::mutex> lock(mFreedBuffersLock);
4146 for (auto bufferId : bufIds) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07004147 mFreedBuffers.push_back(std::make_pair(streamId, bufferId));
4148 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07004149}
4150
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004151/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004152 * RequestThread inner class methods
4153 */
4154
4155Camera3Device::RequestThread::RequestThread(wp<Camera3Device> parent,
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004156 sp<StatusTracker> statusTracker,
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004157 sp<HalInterface> interface, const Vector<int32_t>& sessionParamKeys,
4158 bool useHalBufManager) :
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004159 Thread(/*canCallJava*/false),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004160 mParent(parent),
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004161 mStatusTracker(statusTracker),
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004162 mInterface(interface),
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07004163 mListener(nullptr),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004164 mId(getId(parent)),
Shuzhen Wang316781a2020-08-18 18:11:01 -07004165 mFirstRepeating(false),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004166 mReconfigured(false),
4167 mDoPause(false),
4168 mPaused(true),
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004169 mNotifyPipelineDrain(false),
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004170 mFrameNumber(0),
Jianing Weicb0652e2014-03-12 18:29:36 -07004171 mLatestRequestId(NAME_NOT_FOUND),
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07004172 mCurrentAfTriggerId(0),
4173 mCurrentPreCaptureTriggerId(0),
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004174 mRotateAndCropOverride(ANDROID_SCALER_ROTATE_AND_CROP_NONE),
Eino-Ville Talvala11afe4f2021-05-27 14:45:31 -07004175 mCameraMute(ANDROID_SENSOR_TEST_PATTERN_MODE_OFF),
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004176 mCameraMuteChanged(false),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004177 mRepeatingLastFrameNumber(
4178 hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES),
Shuzhen Wang686f6442017-06-20 16:16:04 -07004179 mPrepareVideoStream(false),
Emilian Peeva14b4dd2018-05-15 11:00:31 +01004180 mConstrainedMode(false),
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004181 mRequestLatency(kRequestLatencyBinSize),
4182 mSessionParamKeys(sessionParamKeys),
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004183 mLatestSessionParams(sessionParamKeys.size()),
4184 mUseHalBufManager(useHalBufManager) {
Yin-Chia Yeh87b3ec02019-06-03 10:44:39 -07004185 mStatusId = statusTracker->addComponent("RequestThread");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004186}
4187
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004188Camera3Device::RequestThread::~RequestThread() {}
4189
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004190void Camera3Device::RequestThread::setNotificationListener(
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004191 wp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004192 ATRACE_CALL();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004193 Mutex::Autolock l(mRequestLock);
4194 mListener = listener;
4195}
4196
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004197void Camera3Device::RequestThread::configurationComplete(bool isConstrainedHighSpeed,
Shuzhen Wang99080502021-03-07 21:08:20 -08004198 const CameraMetadata& sessionParams,
4199 const std::map<int32_t, std::set<String8>>& groupIdPhysicalCameraMap) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004200 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004201 Mutex::Autolock l(mRequestLock);
4202 mReconfigured = true;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004203 mLatestSessionParams = sessionParams;
Shuzhen Wang99080502021-03-07 21:08:20 -08004204 mGroupIdPhysicalCameraMap = groupIdPhysicalCameraMap;
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07004205 // Prepare video stream for high speed recording.
4206 mPrepareVideoStream = isConstrainedHighSpeed;
Emilian Peeva14b4dd2018-05-15 11:00:31 +01004207 mConstrainedMode = isConstrainedHighSpeed;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004208}
4209
Jianing Wei90e59c92014-03-12 18:29:36 -07004210status_t Camera3Device::RequestThread::queueRequestList(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004211 List<sp<CaptureRequest> > &requests,
4212 /*out*/
4213 int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004214 ATRACE_CALL();
Jianing Wei90e59c92014-03-12 18:29:36 -07004215 Mutex::Autolock l(mRequestLock);
4216 for (List<sp<CaptureRequest> >::iterator it = requests.begin(); it != requests.end();
4217 ++it) {
4218 mRequestQueue.push_back(*it);
4219 }
4220
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004221 if (lastFrameNumber != NULL) {
4222 *lastFrameNumber = mFrameNumber + mRequestQueue.size() - 1;
4223 ALOGV("%s: requestId %d, mFrameNumber %" PRId32 ", lastFrameNumber %" PRId64 ".",
4224 __FUNCTION__, (*(requests.begin()))->mResultExtras.requestId, mFrameNumber,
4225 *lastFrameNumber);
4226 }
Jianing Weicb0652e2014-03-12 18:29:36 -07004227
Jianing Wei90e59c92014-03-12 18:29:36 -07004228 unpauseForNewRequests();
4229
4230 return OK;
4231}
4232
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004233
4234status_t Camera3Device::RequestThread::queueTrigger(
4235 RequestTrigger trigger[],
4236 size_t count) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004237 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004238 Mutex::Autolock l(mTriggerMutex);
4239 status_t ret;
4240
4241 for (size_t i = 0; i < count; ++i) {
4242 ret = queueTriggerLocked(trigger[i]);
4243
4244 if (ret != OK) {
4245 return ret;
4246 }
4247 }
4248
4249 return OK;
4250}
4251
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004252const String8& Camera3Device::RequestThread::getId(const wp<Camera3Device> &device) {
4253 static String8 deadId("<DeadDevice>");
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004254 sp<Camera3Device> d = device.promote();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004255 if (d != nullptr) return d->mId;
4256 return deadId;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004257}
4258
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004259status_t Camera3Device::RequestThread::queueTriggerLocked(
4260 RequestTrigger trigger) {
4261
4262 uint32_t tag = trigger.metadataTag;
4263 ssize_t index = mTriggerMap.indexOfKey(tag);
4264
4265 switch (trigger.getTagType()) {
4266 case TYPE_BYTE:
4267 // fall-through
4268 case TYPE_INT32:
4269 break;
4270 default:
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004271 ALOGE("%s: Type not supported: 0x%x", __FUNCTION__,
4272 trigger.getTagType());
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004273 return INVALID_OPERATION;
4274 }
4275
4276 /**
4277 * Collect only the latest trigger, since we only have 1 field
4278 * in the request settings per trigger tag, and can't send more than 1
4279 * trigger per request.
4280 */
4281 if (index != NAME_NOT_FOUND) {
4282 mTriggerMap.editValueAt(index) = trigger;
4283 } else {
4284 mTriggerMap.add(tag, trigger);
4285 }
4286
4287 return OK;
4288}
4289
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004290status_t Camera3Device::RequestThread::setRepeatingRequests(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004291 const RequestList &requests,
4292 /*out*/
4293 int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004294 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004295 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004296 if (lastFrameNumber != NULL) {
4297 *lastFrameNumber = mRepeatingLastFrameNumber;
4298 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004299 mRepeatingRequests.clear();
Shuzhen Wang316781a2020-08-18 18:11:01 -07004300 mFirstRepeating = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004301 mRepeatingRequests.insert(mRepeatingRequests.begin(),
4302 requests.begin(), requests.end());
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004303
4304 unpauseForNewRequests();
4305
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004306 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004307 return OK;
4308}
4309
Chih-Hung Hsieh8b0b9712016-08-09 14:25:53 -07004310bool Camera3Device::RequestThread::isRepeatingRequestLocked(const sp<CaptureRequest>& requestIn) {
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07004311 if (mRepeatingRequests.empty()) {
4312 return false;
4313 }
4314 int32_t requestId = requestIn->mResultExtras.requestId;
4315 const RequestList &repeatRequests = mRepeatingRequests;
4316 // All repeating requests are guaranteed to have same id so only check first quest
4317 const sp<CaptureRequest> firstRequest = *repeatRequests.begin();
4318 return (firstRequest->mResultExtras.requestId == requestId);
4319}
4320
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004321status_t Camera3Device::RequestThread::clearRepeatingRequests(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004322 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004323 Mutex::Autolock l(mRequestLock);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004324 return clearRepeatingRequestsLocked(lastFrameNumber);
4325
4326}
4327
4328status_t Camera3Device::RequestThread::clearRepeatingRequestsLocked(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004329 mRepeatingRequests.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004330 if (lastFrameNumber != NULL) {
4331 *lastFrameNumber = mRepeatingLastFrameNumber;
4332 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004333 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004334 return OK;
4335}
4336
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004337status_t Camera3Device::RequestThread::clear(
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004338 /*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004339 ATRACE_CALL();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004340 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004341 ALOGV("RequestThread::%s:", __FUNCTION__);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004342
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004343 mRepeatingRequests.clear();
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07004344
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004345 // Send errors for all requests pending in the request queue, including
4346 // pending repeating requests
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004347 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004348 if (listener != NULL) {
4349 for (RequestList::iterator it = mRequestQueue.begin();
4350 it != mRequestQueue.end(); ++it) {
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004351 // Abort the input buffers for reprocess requests.
4352 if ((*it)->mInputStream != NULL) {
Emilian Peevf4816702020-04-03 15:44:51 -07004353 camera_stream_buffer_t inputBuffer;
Shuzhen Wang83bff122020-11-20 15:51:39 -08004354 camera3::Size inputBufferSize;
Eino-Ville Talvalaba435252017-06-21 16:07:25 -07004355 status_t res = (*it)->mInputStream->getInputBuffer(&inputBuffer,
Shuzhen Wang83bff122020-11-20 15:51:39 -08004356 &inputBufferSize, /*respectHalLimit*/ false);
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004357 if (res != OK) {
4358 ALOGW("%s: %d: couldn't get input buffer while clearing the request "
4359 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
4360 } else {
Emilian Peevf4816702020-04-03 15:44:51 -07004361 inputBuffer.status = CAMERA_BUFFER_STATUS_ERROR;
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004362 res = (*it)->mInputStream->returnInputBuffer(inputBuffer);
4363 if (res != OK) {
4364 ALOGE("%s: %d: couldn't return input buffer while clearing the request "
4365 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
4366 }
4367 }
4368 }
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004369 // Set the frame number this request would have had, if it
4370 // had been submitted; this frame number will not be reused.
4371 // The requestId and burstId fields were set when the request was
4372 // submitted originally (in convertMetadataListToRequestListLocked)
4373 (*it)->mResultExtras.frameNumber = mFrameNumber++;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004374 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004375 (*it)->mResultExtras);
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07004376 }
4377 }
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004378 mRequestQueue.clear();
Jinguang Dongb26e7a02016-11-14 16:04:02 +08004379
4380 Mutex::Autolock al(mTriggerMutex);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004381 mTriggerMap.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004382 if (lastFrameNumber != NULL) {
4383 *lastFrameNumber = mRepeatingLastFrameNumber;
4384 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004385 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Emilian Peev8dae54c2019-12-02 15:17:17 -08004386 mRequestSignal.signal();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004387 return OK;
4388}
4389
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004390status_t Camera3Device::RequestThread::flush() {
4391 ATRACE_CALL();
4392 Mutex::Autolock l(mFlushLock);
4393
Emilian Peev08dd2452017-04-06 16:55:14 +01004394 return mInterface->flush();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004395}
4396
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004397void Camera3Device::RequestThread::setPaused(bool paused) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004398 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004399 Mutex::Autolock l(mPauseLock);
4400 mDoPause = paused;
4401 mDoPauseSignal.signal();
4402}
4403
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004404status_t Camera3Device::RequestThread::waitUntilRequestProcessed(
4405 int32_t requestId, nsecs_t timeout) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004406 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004407 Mutex::Autolock l(mLatestRequestMutex);
4408 status_t res;
4409 while (mLatestRequestId != requestId) {
4410 nsecs_t startTime = systemTime();
4411
4412 res = mLatestRequestSignal.waitRelative(mLatestRequestMutex, timeout);
4413 if (res != OK) return res;
4414
4415 timeout -= (systemTime() - startTime);
4416 }
4417
4418 return OK;
4419}
4420
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004421void Camera3Device::RequestThread::requestExit() {
4422 // Call parent to set up shutdown
4423 Thread::requestExit();
4424 // The exit from any possible waits
4425 mDoPauseSignal.signal();
4426 mRequestSignal.signal();
Shuzhen Wang686f6442017-06-20 16:16:04 -07004427
4428 mRequestLatency.log("ProcessCaptureRequest latency histogram");
4429 mRequestLatency.reset();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004430}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004431
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004432void Camera3Device::RequestThread::checkAndStopRepeatingRequest() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004433 ATRACE_CALL();
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07004434 bool surfaceAbandoned = false;
4435 int64_t lastFrameNumber = 0;
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004436 sp<NotificationListener> listener;
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07004437 {
4438 Mutex::Autolock l(mRequestLock);
4439 // Check all streams needed by repeating requests are still valid. Otherwise, stop
4440 // repeating requests.
4441 for (const auto& request : mRepeatingRequests) {
4442 for (const auto& s : request->mOutputStreams) {
4443 if (s->isAbandoned()) {
4444 surfaceAbandoned = true;
4445 clearRepeatingRequestsLocked(&lastFrameNumber);
4446 break;
4447 }
4448 }
4449 if (surfaceAbandoned) {
4450 break;
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004451 }
4452 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004453 listener = mListener.promote();
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004454 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004455
4456 if (listener != NULL && surfaceAbandoned) {
4457 listener->notifyRepeatingRequestError(lastFrameNumber);
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07004458 }
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004459}
4460
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004461bool Camera3Device::RequestThread::sendRequestsBatch() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004462 ATRACE_CALL();
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004463 status_t res;
4464 size_t batchSize = mNextRequests.size();
Emilian Peevf4816702020-04-03 15:44:51 -07004465 std::vector<camera_capture_request_t*> requests(batchSize);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004466 uint32_t numRequestProcessed = 0;
4467 for (size_t i = 0; i < batchSize; i++) {
4468 requests[i] = &mNextRequests.editItemAt(i).halRequest;
Yin-Chia Yeh885691c2018-05-01 15:54:24 -07004469 ATRACE_ASYNC_BEGIN("frame capture", mNextRequests[i].halRequest.frame_number);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004470 }
4471
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004472 res = mInterface->processBatchCaptureRequests(requests, &numRequestProcessed);
4473
4474 bool triggerRemoveFailed = false;
4475 NextRequest& triggerFailedRequest = mNextRequests.editItemAt(0);
4476 for (size_t i = 0; i < numRequestProcessed; i++) {
4477 NextRequest& nextRequest = mNextRequests.editItemAt(i);
4478 nextRequest.submitted = true;
4479
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004480 updateNextRequest(nextRequest);
Emilian Peevaebbe412018-01-15 13:53:24 +00004481
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004482 if (!triggerRemoveFailed) {
4483 // Remove any previously queued triggers (after unlock)
4484 status_t removeTriggerRes = removeTriggers(mPrevRequest);
4485 if (removeTriggerRes != OK) {
4486 triggerRemoveFailed = true;
4487 triggerFailedRequest = nextRequest;
4488 }
4489 }
4490 }
4491
4492 if (triggerRemoveFailed) {
4493 SET_ERR("RequestThread: Unable to remove triggers "
4494 "(capture request %d, HAL device: %s (%d)",
4495 triggerFailedRequest.halRequest.frame_number, strerror(-res), res);
4496 cleanUpFailedRequests(/*sendRequestError*/ false);
4497 return false;
4498 }
4499
4500 if (res != OK) {
4501 // Should only get a failure here for malformed requests or device-level
4502 // errors, so consider all errors fatal. Bad metadata failures should
4503 // come through notify.
4504 SET_ERR("RequestThread: Unable to submit capture request %d to HAL device: %s (%d)",
4505 mNextRequests[numRequestProcessed].halRequest.frame_number,
4506 strerror(-res), res);
4507 cleanUpFailedRequests(/*sendRequestError*/ false);
4508 return false;
4509 }
4510 return true;
4511}
4512
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07004513nsecs_t Camera3Device::RequestThread::calculateMaxExpectedDuration(const camera_metadata_t *request) {
4514 nsecs_t maxExpectedDuration = kDefaultExpectedDuration;
4515 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
4516 find_camera_metadata_ro_entry(request,
4517 ANDROID_CONTROL_AE_MODE,
4518 &e);
4519 if (e.count == 0) return maxExpectedDuration;
4520
4521 switch (e.data.u8[0]) {
4522 case ANDROID_CONTROL_AE_MODE_OFF:
4523 find_camera_metadata_ro_entry(request,
4524 ANDROID_SENSOR_EXPOSURE_TIME,
4525 &e);
4526 if (e.count > 0) {
4527 maxExpectedDuration = e.data.i64[0];
4528 }
4529 find_camera_metadata_ro_entry(request,
4530 ANDROID_SENSOR_FRAME_DURATION,
4531 &e);
4532 if (e.count > 0) {
4533 maxExpectedDuration = std::max(e.data.i64[0], maxExpectedDuration);
4534 }
4535 break;
4536 default:
4537 find_camera_metadata_ro_entry(request,
4538 ANDROID_CONTROL_AE_TARGET_FPS_RANGE,
4539 &e);
4540 if (e.count > 1) {
4541 maxExpectedDuration = 1e9 / e.data.u8[0];
4542 }
4543 break;
4544 }
4545
4546 return maxExpectedDuration;
4547}
4548
Emilian Peeva14b4dd2018-05-15 11:00:31 +01004549bool Camera3Device::RequestThread::skipHFRTargetFPSUpdate(int32_t tag,
4550 const camera_metadata_ro_entry_t& newEntry, const camera_metadata_entry_t& currentEntry) {
4551 if (mConstrainedMode && (ANDROID_CONTROL_AE_TARGET_FPS_RANGE == tag) &&
4552 (newEntry.count == currentEntry.count) && (currentEntry.count == 2) &&
4553 (currentEntry.data.i32[1] == newEntry.data.i32[1])) {
4554 return true;
4555 }
4556
4557 return false;
4558}
4559
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004560void Camera3Device::RequestThread::updateNextRequest(NextRequest& nextRequest) {
4561 // Update the latest request sent to HAL
Shuzhen Wang83bff122020-11-20 15:51:39 -08004562 camera_capture_request_t& halRequest = nextRequest.halRequest;
4563 if (halRequest.settings != NULL) { // Don't update if they were unchanged
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004564 Mutex::Autolock al(mLatestRequestMutex);
4565
Shuzhen Wang83bff122020-11-20 15:51:39 -08004566 camera_metadata_t* cloned = clone_camera_metadata(halRequest.settings);
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004567 mLatestRequest.acquire(cloned);
4568
4569 mLatestPhysicalRequest.clear();
Shuzhen Wang83bff122020-11-20 15:51:39 -08004570 for (uint32_t i = 0; i < halRequest.num_physcam_settings; i++) {
4571 cloned = clone_camera_metadata(halRequest.physcam_settings[i]);
4572 mLatestPhysicalRequest.emplace(halRequest.physcam_id[i],
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004573 CameraMetadata(cloned));
4574 }
4575
4576 sp<Camera3Device> parent = mParent.promote();
4577 if (parent != NULL) {
4578 parent->monitorMetadata(TagMonitor::REQUEST,
Shuzhen Wang83bff122020-11-20 15:51:39 -08004579 halRequest.frame_number,
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004580 0, mLatestRequest, mLatestPhysicalRequest);
4581 }
4582 }
4583
Shuzhen Wang83bff122020-11-20 15:51:39 -08004584 if (halRequest.settings != NULL) {
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004585 nextRequest.captureRequest->mSettingsList.begin()->metadata.unlock(
Shuzhen Wang83bff122020-11-20 15:51:39 -08004586 halRequest.settings);
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004587 }
4588
Shuzhen Wang83bff122020-11-20 15:51:39 -08004589 cleanupPhysicalSettings(nextRequest.captureRequest, &halRequest);
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004590}
4591
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004592bool Camera3Device::RequestThread::updateSessionParameters(const CameraMetadata& settings) {
4593 ATRACE_CALL();
4594 bool updatesDetected = false;
4595
Emilian Peev4ec17882019-01-24 17:16:58 -08004596 CameraMetadata updatedParams(mLatestSessionParams);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004597 for (auto tag : mSessionParamKeys) {
4598 camera_metadata_ro_entry entry = settings.find(tag);
Emilian Peev4ec17882019-01-24 17:16:58 -08004599 camera_metadata_entry lastEntry = updatedParams.find(tag);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004600
4601 if (entry.count > 0) {
4602 bool isDifferent = false;
4603 if (lastEntry.count > 0) {
4604 // Have a last value, compare to see if changed
4605 if (lastEntry.type == entry.type &&
4606 lastEntry.count == entry.count) {
4607 // Same type and count, compare values
4608 size_t bytesPerValue = camera_metadata_type_size[lastEntry.type];
4609 size_t entryBytes = bytesPerValue * lastEntry.count;
4610 int cmp = memcmp(entry.data.u8, lastEntry.data.u8, entryBytes);
4611 if (cmp != 0) {
4612 isDifferent = true;
4613 }
4614 } else {
4615 // Count or type has changed
4616 isDifferent = true;
4617 }
4618 } else {
4619 // No last entry, so always consider to be different
4620 isDifferent = true;
4621 }
4622
4623 if (isDifferent) {
4624 ALOGV("%s: Session parameter tag id %d changed", __FUNCTION__, tag);
Emilian Peeva14b4dd2018-05-15 11:00:31 +01004625 if (!skipHFRTargetFPSUpdate(tag, entry, lastEntry)) {
4626 updatesDetected = true;
4627 }
Emilian Peev4ec17882019-01-24 17:16:58 -08004628 updatedParams.update(entry);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004629 }
4630 } else if (lastEntry.count > 0) {
4631 // Value has been removed
4632 ALOGV("%s: Session parameter tag id %d removed", __FUNCTION__, tag);
Emilian Peev4ec17882019-01-24 17:16:58 -08004633 updatedParams.erase(tag);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004634 updatesDetected = true;
4635 }
4636 }
4637
Emilian Peev4ec17882019-01-24 17:16:58 -08004638 bool reconfigureRequired;
4639 if (updatesDetected) {
4640 reconfigureRequired = mInterface->isReconfigurationRequired(mLatestSessionParams,
4641 updatedParams);
4642 mLatestSessionParams = updatedParams;
4643 } else {
4644 reconfigureRequired = false;
4645 }
4646
4647 return reconfigureRequired;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004648}
4649
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004650bool Camera3Device::RequestThread::threadLoop() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004651 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004652 status_t res;
Jayant Chowdhary37eca242019-11-18 08:55:56 -08004653 // Any function called from threadLoop() must not hold mInterfaceLock since
4654 // it could lead to deadlocks (disconnect() -> hold mInterfaceMutex -> wait for request thread
4655 // to finish -> request thread waits on mInterfaceMutex) http://b/143513518
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004656
4657 // Handle paused state.
4658 if (waitIfPaused()) {
4659 return true;
4660 }
4661
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004662 // Wait for the next batch of requests.
4663 waitForNextRequestBatch();
4664 if (mNextRequests.size() == 0) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004665 return true;
4666 }
4667
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004668 // Get the latest request ID, if any
4669 int latestRequestId;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004670 camera_metadata_entry_t requestIdEntry = mNextRequests[mNextRequests.size() - 1].
Emilian Peevaebbe412018-01-15 13:53:24 +00004671 captureRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_ID);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004672 if (requestIdEntry.count > 0) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004673 latestRequestId = requestIdEntry.data.i32[0];
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004674 } else {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004675 ALOGW("%s: Did not have android.request.id set in the request.", __FUNCTION__);
4676 latestRequestId = NAME_NOT_FOUND;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004677 }
4678
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004679 // 'mNextRequests' will at this point contain either a set of HFR batched requests
4680 // or a single request from streaming or burst. In either case the first element
4681 // should contain the latest camera settings that we need to check for any session
4682 // parameter updates.
Emilian Peevaebbe412018-01-15 13:53:24 +00004683 if (updateSessionParameters(mNextRequests[0].captureRequest->mSettingsList.begin()->metadata)) {
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004684 res = OK;
4685
4686 //Input stream buffers are already acquired at this point so an input stream
4687 //will not be able to move to idle state unless we force it.
4688 if (mNextRequests[0].captureRequest->mInputStream != nullptr) {
4689 res = mNextRequests[0].captureRequest->mInputStream->forceToIdle();
4690 if (res != OK) {
4691 ALOGE("%s: Failed to force idle input stream: %d", __FUNCTION__, res);
4692 cleanUpFailedRequests(/*sendRequestError*/ false);
4693 return false;
4694 }
4695 }
4696
4697 if (res == OK) {
Emilian Peev3bead5f2020-05-28 17:29:08 -07004698 sp<Camera3Device> parent = mParent.promote();
4699 if (parent != nullptr) {
4700 mReconfigured |= parent->reconfigureCamera(mLatestSessionParams, mStatusId);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004701 }
Emilian Peev3bead5f2020-05-28 17:29:08 -07004702 setPaused(false);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004703
4704 if (mNextRequests[0].captureRequest->mInputStream != nullptr) {
4705 mNextRequests[0].captureRequest->mInputStream->restoreConfiguredState();
4706 if (res != OK) {
4707 ALOGE("%s: Failed to restore configured input stream: %d", __FUNCTION__, res);
4708 cleanUpFailedRequests(/*sendRequestError*/ false);
4709 return false;
4710 }
4711 }
4712 }
4713 }
4714
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004715 // Prepare a batch of HAL requests and output buffers.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004716 res = prepareHalRequests();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004717 if (res == TIMED_OUT) {
4718 // Not a fatal error if getting output buffers time out.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004719 cleanUpFailedRequests(/*sendRequestError*/ true);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004720 // Check if any stream is abandoned.
4721 checkAndStopRepeatingRequest();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004722 return true;
4723 } else if (res != OK) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004724 cleanUpFailedRequests(/*sendRequestError*/ false);
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004725 return false;
4726 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004727
Zhijun Hecc27e112013-10-03 16:12:43 -07004728 // Inform waitUntilRequestProcessed thread of a new request ID
4729 {
4730 Mutex::Autolock al(mLatestRequestMutex);
4731
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004732 mLatestRequestId = latestRequestId;
Zhijun Hecc27e112013-10-03 16:12:43 -07004733 mLatestRequestSignal.signal();
4734 }
4735
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004736 // Submit a batch of requests to HAL.
4737 // Use flush lock only when submitting multilple requests in a batch.
4738 // TODO: The problem with flush lock is flush() will be blocked by process_capture_request()
4739 // which may take a long time to finish so synchronizing flush() and
4740 // process_capture_request() defeats the purpose of cancelling requests ASAP with flush().
4741 // For now, only synchronize for high speed recording and we should figure something out for
4742 // removing the synchronization.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004743 bool useFlushLock = mNextRequests.size() > 1;
Eino-Ville Talvala17a61ad2013-06-03 16:53:32 -07004744
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004745 if (useFlushLock) {
4746 mFlushLock.lock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004747 }
4748
Zhijun Hef0645c12016-08-02 00:58:11 -07004749 ALOGVV("%s: %d: submitting %zu requests in a batch.", __FUNCTION__, __LINE__,
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004750 mNextRequests.size());
Igor Murashkin1e479c02013-09-06 16:55:14 -07004751
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08004752 sp<Camera3Device> parent = mParent.promote();
4753 if (parent != nullptr) {
4754 parent->mRequestBufferSM.onSubmittingRequest();
4755 }
4756
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004757 bool submitRequestSuccess = false;
Shuzhen Wang686f6442017-06-20 16:16:04 -07004758 nsecs_t tRequestStart = systemTime(SYSTEM_TIME_MONOTONIC);
Yin-Chia Yeh11648852019-05-16 10:42:54 -07004759 submitRequestSuccess = sendRequestsBatch();
4760
Shuzhen Wang686f6442017-06-20 16:16:04 -07004761 nsecs_t tRequestEnd = systemTime(SYSTEM_TIME_MONOTONIC);
4762 mRequestLatency.add(tRequestStart, tRequestEnd);
Igor Murashkin1e479c02013-09-06 16:55:14 -07004763
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004764 if (useFlushLock) {
4765 mFlushLock.unlock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004766 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004767
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004768 // Unset as current request
4769 {
4770 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004771 mNextRequests.clear();
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004772 }
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004773 mRequestSubmittedSignal.signal();
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004774
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004775 return submitRequestSuccess;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004776}
4777
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004778status_t Camera3Device::RequestThread::prepareHalRequests() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004779 ATRACE_CALL();
4780
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07004781 bool batchedRequest = mNextRequests[0].captureRequest->mBatchSize > 1;
Shuzhen Wang4a472662017-02-26 23:29:04 -08004782 for (size_t i = 0; i < mNextRequests.size(); i++) {
4783 auto& nextRequest = mNextRequests.editItemAt(i);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004784 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
Emilian Peevf4816702020-04-03 15:44:51 -07004785 camera_capture_request_t* halRequest = &nextRequest.halRequest;
4786 Vector<camera_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004787
4788 // Prepare a request to HAL
4789 halRequest->frame_number = captureRequest->mResultExtras.frameNumber;
4790
4791 // Insert any queued triggers (before metadata is locked)
4792 status_t res = insertTriggers(captureRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004793 if (res < 0) {
4794 SET_ERR("RequestThread: Unable to insert triggers "
4795 "(capture request %d, HAL device: %s (%d)",
4796 halRequest->frame_number, strerror(-res), res);
4797 return INVALID_OPERATION;
4798 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07004799
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004800 int triggerCount = res;
4801 bool triggersMixedIn = (triggerCount > 0 || mPrevTriggers > 0);
4802 mPrevTriggers = triggerCount;
4803
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004804 bool rotateAndCropChanged = overrideAutoRotateAndCrop(captureRequest);
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004805 bool testPatternChanged = overrideTestPattern(captureRequest);
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004806
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004807 // If the request is the same as last, or we had triggers now or last time or
4808 // changing overrides this time
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004809 bool newRequest =
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004810 (mPrevRequest != captureRequest || triggersMixedIn ||
4811 rotateAndCropChanged || testPatternChanged) &&
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07004812 // Request settings are all the same within one batch, so only treat the first
4813 // request in a batch as new
Zhijun He54c36822018-07-18 09:33:39 -07004814 !(batchedRequest && i > 0);
Emilian Peev00420d22018-02-05 21:33:13 +00004815 if (newRequest) {
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08004816 std::set<std::string> cameraIdsWithZoom;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004817 /**
4818 * HAL workaround:
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004819 * Insert a fake trigger ID if a trigger is set but no trigger ID is
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004820 */
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004821 res = addFakeTriggerIds(captureRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004822 if (res != OK) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004823 SET_ERR("RequestThread: Unable to insert fake trigger IDs "
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004824 "(capture request %d, HAL device: %s (%d)",
4825 halRequest->frame_number, strerror(-res), res);
4826 return INVALID_OPERATION;
4827 }
4828
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07004829 {
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07004830 sp<Camera3Device> parent = mParent.promote();
4831 if (parent != nullptr) {
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -07004832 List<PhysicalCameraSettings>::iterator it;
4833 for (it = captureRequest->mSettingsList.begin();
4834 it != captureRequest->mSettingsList.end(); it++) {
Jayant Chowdhary9255ce02021-07-15 11:18:17 -07004835 if (parent->mUHRCropAndMeteringRegionMappers.find(it->cameraId) ==
4836 parent->mUHRCropAndMeteringRegionMappers.end()) {
4837 continue;
4838 }
4839
4840 if (!captureRequest->mUHRCropAndMeteringRegionsUpdated) {
4841 res = parent->mUHRCropAndMeteringRegionMappers[it->cameraId].
4842 updateCaptureRequest(&(it->metadata));
4843 if (res != OK) {
4844 SET_ERR("RequestThread: Unable to correct capture requests "
4845 "for scaler crop region and metering regions for request "
4846 "%d: %s (%d)", halRequest->frame_number, strerror(-res),
4847 res);
4848 return INVALID_OPERATION;
4849 }
4850 captureRequest->mUHRCropAndMeteringRegionsUpdated = true;
4851 }
4852 }
4853
4854 // Correct metadata regions for distortion correction if enabled
4855 for (it = captureRequest->mSettingsList.begin();
4856 it != captureRequest->mSettingsList.end(); it++) {
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -07004857 if (parent->mDistortionMappers.find(it->cameraId) ==
4858 parent->mDistortionMappers.end()) {
4859 continue;
4860 }
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07004861
4862 if (!captureRequest->mDistortionCorrectionUpdated) {
4863 res = parent->mDistortionMappers[it->cameraId].correctCaptureRequest(
4864 &(it->metadata));
4865 if (res != OK) {
4866 SET_ERR("RequestThread: Unable to correct capture requests "
4867 "for lens distortion for request %d: %s (%d)",
4868 halRequest->frame_number, strerror(-res), res);
4869 return INVALID_OPERATION;
4870 }
4871 captureRequest->mDistortionCorrectionUpdated = true;
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -07004872 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07004873 }
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08004874
4875 for (it = captureRequest->mSettingsList.begin();
4876 it != captureRequest->mSettingsList.end(); it++) {
4877 if (parent->mZoomRatioMappers.find(it->cameraId) ==
4878 parent->mZoomRatioMappers.end()) {
4879 continue;
4880 }
4881
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07004882 if (!captureRequest->mZoomRatioIs1x) {
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08004883 cameraIdsWithZoom.insert(it->cameraId);
4884 }
4885
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07004886 if (!captureRequest->mZoomRatioUpdated) {
4887 res = parent->mZoomRatioMappers[it->cameraId].updateCaptureRequest(
4888 &(it->metadata));
4889 if (res != OK) {
4890 SET_ERR("RequestThread: Unable to correct capture requests "
4891 "for zoom ratio for request %d: %s (%d)",
4892 halRequest->frame_number, strerror(-res), res);
4893 return INVALID_OPERATION;
4894 }
4895 captureRequest->mZoomRatioUpdated = true;
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08004896 }
4897 }
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07004898 if (captureRequest->mRotateAndCropAuto &&
4899 !captureRequest->mRotationAndCropUpdated) {
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004900 for (it = captureRequest->mSettingsList.begin();
4901 it != captureRequest->mSettingsList.end(); it++) {
4902 auto mapper = parent->mRotateAndCropMappers.find(it->cameraId);
4903 if (mapper != parent->mRotateAndCropMappers.end()) {
4904 res = mapper->second.updateCaptureRequest(&(it->metadata));
4905 if (res != OK) {
4906 SET_ERR("RequestThread: Unable to correct capture requests "
4907 "for rotate-and-crop for request %d: %s (%d)",
4908 halRequest->frame_number, strerror(-res), res);
4909 return INVALID_OPERATION;
4910 }
4911 }
4912 }
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07004913 captureRequest->mRotationAndCropUpdated = true;
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004914 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07004915 }
4916 }
4917
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004918 /**
4919 * The request should be presorted so accesses in HAL
4920 * are O(logn). Sidenote, sorting a sorted metadata is nop.
4921 */
Emilian Peevaebbe412018-01-15 13:53:24 +00004922 captureRequest->mSettingsList.begin()->metadata.sort();
4923 halRequest->settings = captureRequest->mSettingsList.begin()->metadata.getAndLock();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004924 mPrevRequest = captureRequest;
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08004925 mPrevCameraIdsWithZoom = cameraIdsWithZoom;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004926 ALOGVV("%s: Request settings are NEW", __FUNCTION__);
4927
4928 IF_ALOGV() {
4929 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
4930 find_camera_metadata_ro_entry(
4931 halRequest->settings,
4932 ANDROID_CONTROL_AF_TRIGGER,
4933 &e
4934 );
4935 if (e.count > 0) {
4936 ALOGV("%s: Request (frame num %d) had AF trigger 0x%x",
4937 __FUNCTION__,
4938 halRequest->frame_number,
4939 e.data.u8[0]);
4940 }
4941 }
4942 } else {
4943 // leave request.settings NULL to indicate 'reuse latest given'
4944 ALOGVV("%s: Request settings are REUSED",
4945 __FUNCTION__);
4946 }
4947
Emilian Peevaebbe412018-01-15 13:53:24 +00004948 if (captureRequest->mSettingsList.size() > 1) {
4949 halRequest->num_physcam_settings = captureRequest->mSettingsList.size() - 1;
4950 halRequest->physcam_id = new const char* [halRequest->num_physcam_settings];
Emilian Peev00420d22018-02-05 21:33:13 +00004951 if (newRequest) {
4952 halRequest->physcam_settings =
4953 new const camera_metadata* [halRequest->num_physcam_settings];
4954 } else {
4955 halRequest->physcam_settings = nullptr;
4956 }
Emilian Peevaebbe412018-01-15 13:53:24 +00004957 auto it = ++captureRequest->mSettingsList.begin();
4958 size_t i = 0;
4959 for (; it != captureRequest->mSettingsList.end(); it++, i++) {
4960 halRequest->physcam_id[i] = it->cameraId.c_str();
Emilian Peev00420d22018-02-05 21:33:13 +00004961 if (newRequest) {
4962 it->metadata.sort();
4963 halRequest->physcam_settings[i] = it->metadata.getAndLock();
4964 }
Emilian Peevaebbe412018-01-15 13:53:24 +00004965 }
4966 }
4967
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004968 uint32_t totalNumBuffers = 0;
4969
4970 // Fill in buffers
4971 if (captureRequest->mInputStream != NULL) {
4972 halRequest->input_buffer = &captureRequest->mInputBuffer;
Shuzhen Wang83bff122020-11-20 15:51:39 -08004973
4974 halRequest->input_width = captureRequest->mInputBufferSize.width;
4975 halRequest->input_height = captureRequest->mInputBufferSize.height;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004976 totalNumBuffers += 1;
4977 } else {
4978 halRequest->input_buffer = NULL;
4979 }
4980
Emilian Peevf4816702020-04-03 15:44:51 -07004981 outputBuffers->insertAt(camera_stream_buffer_t(), 0,
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004982 captureRequest->mOutputStreams.size());
4983 halRequest->output_buffers = outputBuffers->array();
Shuzhen Wang99080502021-03-07 21:08:20 -08004984 std::set<std::set<String8>> requestedPhysicalCameras;
Yin-Chia Yehb3a80b12018-09-04 12:13:05 -07004985
4986 sp<Camera3Device> parent = mParent.promote();
4987 if (parent == NULL) {
4988 // Should not happen, and nowhere to send errors to, so just log it
4989 CLOGE("RequestThread: Parent is gone");
4990 return INVALID_OPERATION;
4991 }
4992 nsecs_t waitDuration = kBaseGetBufferWait + parent->getExpectedInFlightDuration();
4993
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07004994 SurfaceMap uniqueSurfaceIdMap;
Shuzhen Wang4a472662017-02-26 23:29:04 -08004995 for (size_t j = 0; j < captureRequest->mOutputStreams.size(); j++) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07004996 sp<Camera3OutputStreamInterface> outputStream =
4997 captureRequest->mOutputStreams.editItemAt(j);
4998 int streamId = outputStream->getId();
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07004999
5000 // Prepare video buffers for high speed recording on the first video request.
5001 if (mPrepareVideoStream && outputStream->isVideoStream()) {
5002 // Only try to prepare video stream on the first video request.
5003 mPrepareVideoStream = false;
5004
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07005005 res = outputStream->startPrepare(Camera3StreamInterface::ALLOCATE_PIPELINE_MAX,
5006 false /*blockRequest*/);
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07005007 while (res == NOT_ENOUGH_DATA) {
5008 res = outputStream->prepareNextBuffer();
5009 }
5010 if (res != OK) {
5011 ALOGW("%s: Preparing video buffers for high speed failed: %s (%d)",
5012 __FUNCTION__, strerror(-res), res);
5013 outputStream->cancelPrepare();
5014 }
5015 }
5016
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005017 std::vector<size_t> uniqueSurfaceIds;
5018 res = outputStream->getUniqueSurfaceIds(
5019 captureRequest->mOutputSurfaces[streamId],
5020 &uniqueSurfaceIds);
5021 // INVALID_OPERATION is normal output for streams not supporting surfaceIds
5022 if (res != OK && res != INVALID_OPERATION) {
5023 ALOGE("%s: failed to query stream %d unique surface IDs",
5024 __FUNCTION__, streamId);
5025 return res;
5026 }
5027 if (res == OK) {
5028 uniqueSurfaceIdMap.insert({streamId, std::move(uniqueSurfaceIds)});
5029 }
5030
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07005031 if (mUseHalBufManager) {
Yin-Chia Yeh110342b2018-11-19 11:47:46 -08005032 if (outputStream->isAbandoned()) {
Yin-Chia Yeha1b56c82019-03-27 15:50:39 -07005033 ALOGV("%s: stream %d is abandoned, skipping request", __FUNCTION__, streamId);
Yin-Chia Yeh110342b2018-11-19 11:47:46 -08005034 return TIMED_OUT;
5035 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07005036 // HAL will request buffer through requestStreamBuffer API
Emilian Peevf4816702020-04-03 15:44:51 -07005037 camera_stream_buffer_t& buffer = outputBuffers->editItemAt(j);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07005038 buffer.stream = outputStream->asHalStream();
5039 buffer.buffer = nullptr;
Emilian Peevf4816702020-04-03 15:44:51 -07005040 buffer.status = CAMERA_BUFFER_STATUS_OK;
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07005041 buffer.acquire_fence = -1;
5042 buffer.release_fence = -1;
Emilian Peevf0348ae2021-01-13 13:39:45 -08005043 // Mark the output stream as unpreparable to block clients from calling
5044 // 'prepare' after this request reaches CameraHal and before the respective
5045 // buffers are requested.
5046 outputStream->markUnpreparable();
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07005047 } else {
5048 res = outputStream->getBuffer(&outputBuffers->editItemAt(j),
5049 waitDuration,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005050 captureRequest->mOutputSurfaces[streamId]);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07005051 if (res != OK) {
5052 // Can't get output buffer from gralloc queue - this could be due to
5053 // abandoned queue or other consumer misbehavior, so not a fatal
5054 // error
Yin-Chia Yeha1b56c82019-03-27 15:50:39 -07005055 ALOGV("RequestThread: Can't get output buffer, skipping request:"
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07005056 " %s (%d)", strerror(-res), res);
5057
5058 return TIMED_OUT;
5059 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005060 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08005061
5062 {
5063 sp<Camera3Device> parent = mParent.promote();
5064 if (parent != nullptr) {
5065 const String8& streamCameraId = outputStream->getPhysicalCameraId();
5066 for (const auto& settings : captureRequest->mSettingsList) {
5067 if ((streamCameraId.isEmpty() &&
5068 parent->getId() == settings.cameraId.c_str()) ||
5069 streamCameraId == settings.cameraId.c_str()) {
5070 outputStream->fireBufferRequestForFrameNumber(
5071 captureRequest->mResultExtras.frameNumber,
5072 settings.metadata);
5073 }
5074 }
5075 }
5076 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07005077
Shuzhen Wang5c22c152017-12-31 17:12:25 -08005078 String8 physicalCameraId = outputStream->getPhysicalCameraId();
Shuzhen Wang99080502021-03-07 21:08:20 -08005079 int32_t streamGroupId = outputStream->getHalStreamGroupId();
5080 if (streamGroupId != -1 && mGroupIdPhysicalCameraMap.count(streamGroupId) == 1) {
5081 requestedPhysicalCameras.insert(mGroupIdPhysicalCameraMap[streamGroupId]);
5082 } else if (!physicalCameraId.isEmpty()) {
5083 requestedPhysicalCameras.insert(std::set<String8>({physicalCameraId}));
Shuzhen Wang5c22c152017-12-31 17:12:25 -08005084 }
5085 halRequest->num_output_buffers++;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005086 }
5087 totalNumBuffers += halRequest->num_output_buffers;
5088
5089 // Log request in the in-flight queue
Shuzhen Wang4a472662017-02-26 23:29:04 -08005090 // If this request list is for constrained high speed recording (not
5091 // preview), and the current request is not the last one in the batch,
5092 // do not send callback to the app.
5093 bool hasCallback = true;
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07005094 if (batchedRequest && i != mNextRequests.size()-1) {
Shuzhen Wang4a472662017-02-26 23:29:04 -08005095 hasCallback = false;
5096 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01005097 bool isStillCapture = false;
Shuzhen Wang26abaf42018-08-28 15:41:20 -07005098 bool isZslCapture = false;
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08005099 const camera_metadata_t* settings = halRequest->settings;
5100 bool shouldUnlockSettings = false;
5101 if (settings == nullptr) {
5102 shouldUnlockSettings = true;
5103 settings = captureRequest->mSettingsList.begin()->metadata.getAndLock();
5104 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01005105 if (!mNextRequests[0].captureRequest->mSettingsList.begin()->metadata.isEmpty()) {
5106 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08005107 find_camera_metadata_ro_entry(settings, ANDROID_CONTROL_CAPTURE_INTENT, &e);
Emilian Peev9dd21f42018-08-03 13:39:29 +01005108 if ((e.count > 0) && (e.data.u8[0] == ANDROID_CONTROL_CAPTURE_INTENT_STILL_CAPTURE)) {
5109 isStillCapture = true;
5110 ATRACE_ASYNC_BEGIN("still capture", mNextRequests[i].halRequest.frame_number);
5111 }
Shuzhen Wang26abaf42018-08-28 15:41:20 -07005112
Emilian Peevaf8416e2021-02-04 17:52:43 -08005113 e = camera_metadata_ro_entry_t();
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08005114 find_camera_metadata_ro_entry(settings, ANDROID_CONTROL_ENABLE_ZSL, &e);
Shuzhen Wang26abaf42018-08-28 15:41:20 -07005115 if ((e.count > 0) && (e.data.u8[0] == ANDROID_CONTROL_ENABLE_ZSL_TRUE)) {
5116 isZslCapture = true;
5117 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01005118 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005119 res = parent->registerInFlight(halRequest->frame_number,
5120 totalNumBuffers, captureRequest->mResultExtras,
5121 /*hasInput*/halRequest->input_buffer != NULL,
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07005122 hasCallback,
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08005123 calculateMaxExpectedDuration(settings),
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005124 requestedPhysicalCameras, isStillCapture, isZslCapture,
5125 captureRequest->mRotateAndCropAuto, mPrevCameraIdsWithZoom,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005126 (mUseHalBufManager) ? uniqueSurfaceIdMap :
Shuzhen Wang316781a2020-08-18 18:11:01 -07005127 SurfaceMap{}, captureRequest->mRequestTimeNs);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005128 ALOGVV("%s: registered in flight requestId = %" PRId32 ", frameNumber = %" PRId64
5129 ", burstId = %" PRId32 ".",
5130 __FUNCTION__,
5131 captureRequest->mResultExtras.requestId, captureRequest->mResultExtras.frameNumber,
5132 captureRequest->mResultExtras.burstId);
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08005133
5134 if (shouldUnlockSettings) {
5135 captureRequest->mSettingsList.begin()->metadata.unlock(settings);
5136 }
5137
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005138 if (res != OK) {
5139 SET_ERR("RequestThread: Unable to register new in-flight request:"
5140 " %s (%d)", strerror(-res), res);
5141 return INVALID_OPERATION;
5142 }
5143 }
5144
5145 return OK;
5146}
5147
Igor Murashkin1e479c02013-09-06 16:55:14 -07005148CameraMetadata Camera3Device::RequestThread::getLatestRequest() const {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005149 ATRACE_CALL();
Igor Murashkin1e479c02013-09-06 16:55:14 -07005150 Mutex::Autolock al(mLatestRequestMutex);
5151
5152 ALOGV("RequestThread::%s", __FUNCTION__);
5153
5154 return mLatestRequest;
5155}
5156
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005157bool Camera3Device::RequestThread::isStreamPending(
5158 sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005159 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005160 Mutex::Autolock l(mRequestLock);
5161
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005162 for (const auto& nextRequest : mNextRequests) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005163 if (!nextRequest.submitted) {
5164 for (const auto& s : nextRequest.captureRequest->mOutputStreams) {
5165 if (stream == s) return true;
5166 }
5167 if (stream == nextRequest.captureRequest->mInputStream) return true;
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07005168 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07005169 }
5170
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005171 for (const auto& request : mRequestQueue) {
5172 for (const auto& s : request->mOutputStreams) {
5173 if (stream == s) return true;
5174 }
5175 if (stream == request->mInputStream) return true;
5176 }
5177
5178 for (const auto& request : mRepeatingRequests) {
5179 for (const auto& s : request->mOutputStreams) {
5180 if (stream == s) return true;
5181 }
5182 if (stream == request->mInputStream) return true;
5183 }
5184
5185 return false;
5186}
Jianing Weicb0652e2014-03-12 18:29:36 -07005187
Emilian Peev40ead602017-09-26 15:46:36 +01005188bool Camera3Device::RequestThread::isOutputSurfacePending(int streamId, size_t surfaceId) {
5189 ATRACE_CALL();
5190 Mutex::Autolock l(mRequestLock);
5191
5192 for (const auto& nextRequest : mNextRequests) {
5193 for (const auto& s : nextRequest.captureRequest->mOutputSurfaces) {
5194 if (s.first == streamId) {
5195 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
5196 if (it != s.second.end()) {
5197 return true;
5198 }
5199 }
5200 }
5201 }
5202
5203 for (const auto& request : mRequestQueue) {
5204 for (const auto& s : request->mOutputSurfaces) {
5205 if (s.first == streamId) {
5206 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
5207 if (it != s.second.end()) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005208 return true;
Emilian Peev40ead602017-09-26 15:46:36 +01005209 }
5210 }
5211 }
5212 }
5213
5214 for (const auto& request : mRepeatingRequests) {
5215 for (const auto& s : request->mOutputSurfaces) {
5216 if (s.first == streamId) {
5217 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
5218 if (it != s.second.end()) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005219 return true;
Emilian Peev40ead602017-09-26 15:46:36 +01005220 }
5221 }
5222 }
5223 }
5224
5225 return false;
5226}
5227
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07005228void Camera3Device::RequestThread::signalPipelineDrain(const std::vector<int>& streamIds) {
5229 if (!mUseHalBufManager) {
5230 ALOGE("%s called for camera device not supporting HAL buffer management", __FUNCTION__);
5231 return;
5232 }
5233
5234 Mutex::Autolock pl(mPauseLock);
5235 if (mPaused) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005236 mInterface->signalPipelineDrain(streamIds);
5237 return;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07005238 }
5239 // If request thread is still busy, wait until paused then notify HAL
5240 mNotifyPipelineDrain = true;
5241 mStreamIdsToBeDrained = streamIds;
5242}
5243
Yin-Chia Yehe52b8fa2020-07-28 00:17:58 -07005244void Camera3Device::RequestThread::resetPipelineDrain() {
5245 Mutex::Autolock pl(mPauseLock);
5246 mNotifyPipelineDrain = false;
5247 mStreamIdsToBeDrained.clear();
5248}
5249
Emilian Peevc0fe54c2020-03-11 14:05:07 -07005250void Camera3Device::RequestThread::clearPreviousRequest() {
5251 Mutex::Autolock l(mRequestLock);
5252 mPrevRequest.clear();
5253}
5254
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005255status_t Camera3Device::RequestThread::switchToOffline(
5256 const std::vector<int32_t>& streamsToKeep,
5257 /*out*/hardware::camera::device::V3_6::CameraOfflineSessionInfo* offlineSessionInfo,
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005258 /*out*/sp<hardware::camera::device::V3_6::ICameraOfflineSession>* offlineSession,
5259 /*out*/camera3::BufferRecords* bufferRecords) {
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005260 Mutex::Autolock l(mRequestLock);
5261 clearRepeatingRequestsLocked(/*lastFrameNumber*/nullptr);
5262
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005263 // Wait until request thread is fully stopped
5264 // TBD: check if request thread is being paused by other APIs (shouldn't be)
5265
5266 // We could also check for mRepeatingRequests.empty(), but the API interface
5267 // is serialized by Camera3Device::mInterfaceLock so no one should be able to submit any
5268 // new requests during the call; hence skip that check.
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005269 bool queueEmpty = mNextRequests.empty() && mRequestQueue.empty();
5270 while (!queueEmpty) {
5271 status_t res = mRequestSubmittedSignal.waitRelative(mRequestLock, kRequestSubmitTimeout);
5272 if (res == TIMED_OUT) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005273 ALOGE("%s: request thread failed to submit one request within timeout!", __FUNCTION__);
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005274 return res;
5275 } else if (res != OK) {
5276 ALOGE("%s: request thread failed to submit a request: %s (%d)!",
5277 __FUNCTION__, strerror(-res), res);
5278 return res;
5279 }
5280 queueEmpty = mNextRequests.empty() && mRequestQueue.empty();
5281 }
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005282
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005283 return mInterface->switchToOffline(
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005284 streamsToKeep, offlineSessionInfo, offlineSession, bufferRecords);
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005285}
5286
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005287status_t Camera3Device::RequestThread::setRotateAndCropAutoBehavior(
5288 camera_metadata_enum_android_scaler_rotate_and_crop_t rotateAndCropValue) {
5289 ATRACE_CALL();
5290 Mutex::Autolock l(mTriggerMutex);
5291 if (rotateAndCropValue == ANDROID_SCALER_ROTATE_AND_CROP_AUTO) {
5292 return BAD_VALUE;
5293 }
5294 mRotateAndCropOverride = rotateAndCropValue;
5295 return OK;
5296}
5297
Eino-Ville Talvala11afe4f2021-05-27 14:45:31 -07005298status_t Camera3Device::RequestThread::setCameraMute(int32_t muteMode) {
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005299 ATRACE_CALL();
5300 Mutex::Autolock l(mTriggerMutex);
Eino-Ville Talvala11afe4f2021-05-27 14:45:31 -07005301 if (muteMode != mCameraMute) {
5302 mCameraMute = muteMode;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005303 mCameraMuteChanged = true;
5304 }
5305 return OK;
5306}
5307
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07005308nsecs_t Camera3Device::getExpectedInFlightDuration() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005309 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005310 std::lock_guard<std::mutex> l(mInFlightLock);
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07005311 return mExpectedInflightDuration > kMinInflightDuration ?
5312 mExpectedInflightDuration : kMinInflightDuration;
5313}
5314
Emilian Peevaebbe412018-01-15 13:53:24 +00005315void Camera3Device::RequestThread::cleanupPhysicalSettings(sp<CaptureRequest> request,
Emilian Peevf4816702020-04-03 15:44:51 -07005316 camera_capture_request_t *halRequest) {
Emilian Peevaebbe412018-01-15 13:53:24 +00005317 if ((request == nullptr) || (halRequest == nullptr)) {
5318 ALOGE("%s: Invalid request!", __FUNCTION__);
5319 return;
5320 }
5321
5322 if (halRequest->num_physcam_settings > 0) {
5323 if (halRequest->physcam_id != nullptr) {
5324 delete [] halRequest->physcam_id;
5325 halRequest->physcam_id = nullptr;
5326 }
5327 if (halRequest->physcam_settings != nullptr) {
5328 auto it = ++(request->mSettingsList.begin());
5329 size_t i = 0;
5330 for (; it != request->mSettingsList.end(); it++, i++) {
5331 it->metadata.unlock(halRequest->physcam_settings[i]);
5332 }
5333 delete [] halRequest->physcam_settings;
5334 halRequest->physcam_settings = nullptr;
5335 }
5336 }
5337}
5338
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005339void Camera3Device::RequestThread::cleanUpFailedRequests(bool sendRequestError) {
5340 if (mNextRequests.empty()) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005341 return;
5342 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005343
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005344 for (auto& nextRequest : mNextRequests) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005345 // Skip the ones that have been submitted successfully.
5346 if (nextRequest.submitted) {
5347 continue;
5348 }
5349
5350 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
Emilian Peevf4816702020-04-03 15:44:51 -07005351 camera_capture_request_t* halRequest = &nextRequest.halRequest;
5352 Vector<camera_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005353
5354 if (halRequest->settings != NULL) {
Emilian Peevaebbe412018-01-15 13:53:24 +00005355 captureRequest->mSettingsList.begin()->metadata.unlock(halRequest->settings);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005356 }
5357
Emilian Peevaebbe412018-01-15 13:53:24 +00005358 cleanupPhysicalSettings(captureRequest, halRequest);
5359
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005360 if (captureRequest->mInputStream != NULL) {
Emilian Peevf4816702020-04-03 15:44:51 -07005361 captureRequest->mInputBuffer.status = CAMERA_BUFFER_STATUS_ERROR;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005362 captureRequest->mInputStream->returnInputBuffer(captureRequest->mInputBuffer);
5363 }
5364
Yin-Chia Yeh21cb47b2019-01-18 15:08:17 -08005365 // No output buffer can be returned when using HAL buffer manager
5366 if (!mUseHalBufManager) {
5367 for (size_t i = 0; i < halRequest->num_output_buffers; i++) {
5368 //Buffers that failed processing could still have
5369 //valid acquire fence.
5370 int acquireFence = (*outputBuffers)[i].acquire_fence;
5371 if (0 <= acquireFence) {
5372 close(acquireFence);
5373 outputBuffers->editItemAt(i).acquire_fence = -1;
5374 }
Emilian Peevf4816702020-04-03 15:44:51 -07005375 outputBuffers->editItemAt(i).status = CAMERA_BUFFER_STATUS_ERROR;
Yin-Chia Yeh21cb47b2019-01-18 15:08:17 -08005376 captureRequest->mOutputStreams.editItemAt(i)->returnBuffer((*outputBuffers)[i], 0,
5377 /*timestampIncreasing*/true, std::vector<size_t> (),
5378 captureRequest->mResultExtras.frameNumber);
Emilian Peevc58cf4c2017-05-11 17:23:41 +01005379 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005380 }
5381
5382 if (sendRequestError) {
5383 Mutex::Autolock l(mRequestLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005384 sp<NotificationListener> listener = mListener.promote();
5385 if (listener != NULL) {
5386 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08005387 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005388 captureRequest->mResultExtras);
5389 }
5390 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07005391
5392 // Remove yet-to-be submitted inflight request from inflightMap
5393 {
5394 sp<Camera3Device> parent = mParent.promote();
5395 if (parent != NULL) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005396 std::lock_guard<std::mutex> l(parent->mInFlightLock);
Shuzhen Wangcadb3302016-11-04 14:17:56 -07005397 ssize_t idx = parent->mInFlightMap.indexOfKey(captureRequest->mResultExtras.frameNumber);
5398 if (idx >= 0) {
5399 ALOGV("%s: Remove inflight request from queue: frameNumber %" PRId64,
5400 __FUNCTION__, captureRequest->mResultExtras.frameNumber);
5401 parent->removeInFlightMapEntryLocked(idx);
5402 }
5403 }
5404 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005405 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07005406
5407 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005408 mNextRequests.clear();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005409}
5410
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005411void Camera3Device::RequestThread::waitForNextRequestBatch() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005412 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005413 // Optimized a bit for the simple steady-state case (single repeating
5414 // request), to avoid putting that request in the queue temporarily.
5415 Mutex::Autolock l(mRequestLock);
5416
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005417 assert(mNextRequests.empty());
5418
5419 NextRequest nextRequest;
5420 nextRequest.captureRequest = waitForNextRequestLocked();
5421 if (nextRequest.captureRequest == nullptr) {
5422 return;
5423 }
5424
Emilian Peevf4816702020-04-03 15:44:51 -07005425 nextRequest.halRequest = camera_capture_request_t();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005426 nextRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005427 mNextRequests.add(nextRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005428
5429 // Wait for additional requests
5430 const size_t batchSize = nextRequest.captureRequest->mBatchSize;
5431
5432 for (size_t i = 1; i < batchSize; i++) {
5433 NextRequest additionalRequest;
5434 additionalRequest.captureRequest = waitForNextRequestLocked();
5435 if (additionalRequest.captureRequest == nullptr) {
5436 break;
5437 }
5438
Emilian Peevf4816702020-04-03 15:44:51 -07005439 additionalRequest.halRequest = camera_capture_request_t();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005440 additionalRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005441 mNextRequests.add(additionalRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005442 }
5443
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005444 if (mNextRequests.size() < batchSize) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08005445 ALOGE("RequestThread: only get %zu out of %zu requests. Skipping requests.",
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005446 mNextRequests.size(), batchSize);
5447 cleanUpFailedRequests(/*sendRequestError*/true);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005448 }
5449
5450 return;
5451}
5452
5453sp<Camera3Device::CaptureRequest>
5454 Camera3Device::RequestThread::waitForNextRequestLocked() {
5455 status_t res;
5456 sp<CaptureRequest> nextRequest;
5457
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005458 while (mRequestQueue.empty()) {
5459 if (!mRepeatingRequests.empty()) {
5460 // Always atomically enqueue all requests in a repeating request
5461 // list. Guarantees a complete in-sequence set of captures to
5462 // application.
5463 const RequestList &requests = mRepeatingRequests;
Shuzhen Wang316781a2020-08-18 18:11:01 -07005464 if (mFirstRepeating) {
5465 mFirstRepeating = false;
5466 } else {
5467 for (auto& request : requests) {
5468 // For repeating requests, override timestamp request using
5469 // the time a request is inserted into the request queue,
5470 // because the original repeating request will have an old
5471 // fixed timestamp.
5472 request->mRequestTimeNs = systemTime();
5473 }
5474 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005475 RequestList::const_iterator firstRequest =
5476 requests.begin();
5477 nextRequest = *firstRequest;
5478 mRequestQueue.insert(mRequestQueue.end(),
5479 ++firstRequest,
5480 requests.end());
5481 // No need to wait any longer
Jianing Weicb0652e2014-03-12 18:29:36 -07005482
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005483 mRepeatingLastFrameNumber = mFrameNumber + requests.size() - 1;
Jianing Weicb0652e2014-03-12 18:29:36 -07005484
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005485 break;
5486 }
5487
5488 res = mRequestSignal.waitRelative(mRequestLock, kRequestTimeout);
5489
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005490 if ((mRequestQueue.empty() && mRepeatingRequests.empty()) ||
5491 exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005492 Mutex::Autolock pl(mPauseLock);
5493 if (mPaused == false) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005494 ALOGV("%s: RequestThread: Going idle", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005495 mPaused = true;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07005496 if (mNotifyPipelineDrain) {
5497 mInterface->signalPipelineDrain(mStreamIdsToBeDrained);
5498 mNotifyPipelineDrain = false;
5499 mStreamIdsToBeDrained.clear();
5500 }
Yin-Chia Yehc300a072019-02-13 14:56:57 -08005501 // Let the tracker know
5502 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5503 if (statusTracker != 0) {
5504 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
5505 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005506 sp<Camera3Device> parent = mParent.promote();
5507 if (parent != nullptr) {
5508 parent->mRequestBufferSM.onRequestThreadPaused();
5509 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005510 }
5511 // Stop waiting for now and let thread management happen
5512 return NULL;
5513 }
5514 }
5515
5516 if (nextRequest == NULL) {
5517 // Don't have a repeating request already in hand, so queue
5518 // must have an entry now.
5519 RequestList::iterator firstRequest =
5520 mRequestQueue.begin();
5521 nextRequest = *firstRequest;
5522 mRequestQueue.erase(firstRequest);
Shuzhen Wang9d066012016-09-30 11:30:20 -07005523 if (mRequestQueue.empty() && !nextRequest->mRepeating) {
5524 sp<NotificationListener> listener = mListener.promote();
5525 if (listener != NULL) {
5526 listener->notifyRequestQueueEmpty();
5527 }
5528 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005529 }
5530
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005531 // In case we've been unpaused by setPaused clearing mDoPause, need to
5532 // update internal pause state (capture/setRepeatingRequest unpause
5533 // directly).
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005534 Mutex::Autolock pl(mPauseLock);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005535 if (mPaused) {
5536 ALOGV("%s: RequestThread: Unpaused", __FUNCTION__);
5537 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5538 if (statusTracker != 0) {
5539 statusTracker->markComponentActive(mStatusId);
5540 }
5541 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005542 mPaused = false;
5543
5544 // Check if we've reconfigured since last time, and reset the preview
5545 // request if so. Can't use 'NULL request == repeat' across configure calls.
5546 if (mReconfigured) {
5547 mPrevRequest.clear();
5548 mReconfigured = false;
5549 }
5550
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005551 if (nextRequest != NULL) {
5552 nextRequest->mResultExtras.frameNumber = mFrameNumber++;
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07005553 nextRequest->mResultExtras.afTriggerId = mCurrentAfTriggerId;
5554 nextRequest->mResultExtras.precaptureTriggerId = mCurrentPreCaptureTriggerId;
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07005555
5556 // Since RequestThread::clear() removes buffers from the input stream,
5557 // get the right buffer here before unlocking mRequestLock
5558 if (nextRequest->mInputStream != NULL) {
Shuzhen Wang83bff122020-11-20 15:51:39 -08005559 res = nextRequest->mInputStream->getInputBuffer(&nextRequest->mInputBuffer,
5560 &nextRequest->mInputBufferSize);
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07005561 if (res != OK) {
5562 // Can't get input buffer from gralloc queue - this could be due to
5563 // disconnected queue or other producer misbehavior, so not a fatal
5564 // error
5565 ALOGE("%s: Can't get input buffer, skipping request:"
5566 " %s (%d)", __FUNCTION__, strerror(-res), res);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005567
5568 sp<NotificationListener> listener = mListener.promote();
5569 if (listener != NULL) {
5570 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08005571 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07005572 nextRequest->mResultExtras);
5573 }
5574 return NULL;
5575 }
5576 }
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005577 }
Chien-Yu Chend196d612015-06-22 19:49:01 -07005578
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005579 return nextRequest;
5580}
5581
5582bool Camera3Device::RequestThread::waitIfPaused() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005583 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005584 status_t res;
5585 Mutex::Autolock l(mPauseLock);
5586 while (mDoPause) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005587 if (mPaused == false) {
5588 mPaused = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005589 ALOGV("%s: RequestThread: Paused", __FUNCTION__);
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07005590 if (mNotifyPipelineDrain) {
5591 mInterface->signalPipelineDrain(mStreamIdsToBeDrained);
5592 mNotifyPipelineDrain = false;
5593 mStreamIdsToBeDrained.clear();
5594 }
Yin-Chia Yehc300a072019-02-13 14:56:57 -08005595 // Let the tracker know
5596 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5597 if (statusTracker != 0) {
5598 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
5599 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005600 sp<Camera3Device> parent = mParent.promote();
5601 if (parent != nullptr) {
5602 parent->mRequestBufferSM.onRequestThreadPaused();
5603 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005604 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005605
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005606 res = mDoPauseSignal.waitRelative(mPauseLock, kRequestTimeout);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005607 if (res == TIMED_OUT || exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005608 return true;
5609 }
5610 }
5611 // We don't set mPaused to false here, because waitForNextRequest needs
5612 // to further manage the paused state in case of starvation.
5613 return false;
5614}
5615
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005616void Camera3Device::RequestThread::unpauseForNewRequests() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005617 ATRACE_CALL();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005618 // With work to do, mark thread as unpaused.
5619 // If paused by request (setPaused), don't resume, to avoid
5620 // extra signaling/waiting overhead to waitUntilPaused
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005621 mRequestSignal.signal();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005622 Mutex::Autolock p(mPauseLock);
5623 if (!mDoPause) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005624 ALOGV("%s: RequestThread: Going active", __FUNCTION__);
5625 if (mPaused) {
5626 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5627 if (statusTracker != 0) {
5628 statusTracker->markComponentActive(mStatusId);
5629 }
5630 }
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005631 mPaused = false;
5632 }
5633}
5634
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07005635void Camera3Device::RequestThread::setErrorState(const char *fmt, ...) {
5636 sp<Camera3Device> parent = mParent.promote();
5637 if (parent != NULL) {
5638 va_list args;
5639 va_start(args, fmt);
5640
5641 parent->setErrorStateV(fmt, args);
5642
5643 va_end(args);
5644 }
5645}
5646
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005647status_t Camera3Device::RequestThread::insertTriggers(
5648 const sp<CaptureRequest> &request) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005649 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005650 Mutex::Autolock al(mTriggerMutex);
5651
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07005652 sp<Camera3Device> parent = mParent.promote();
5653 if (parent == NULL) {
5654 CLOGE("RequestThread: Parent is gone");
5655 return DEAD_OBJECT;
5656 }
5657
Emilian Peevaebbe412018-01-15 13:53:24 +00005658 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005659 size_t count = mTriggerMap.size();
5660
5661 for (size_t i = 0; i < count; ++i) {
5662 RequestTrigger trigger = mTriggerMap.valueAt(i);
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005663 uint32_t tag = trigger.metadataTag;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07005664
5665 if (tag == ANDROID_CONTROL_AF_TRIGGER_ID || tag == ANDROID_CONTROL_AE_PRECAPTURE_ID) {
5666 bool isAeTrigger = (trigger.metadataTag == ANDROID_CONTROL_AE_PRECAPTURE_ID);
5667 uint32_t triggerId = static_cast<uint32_t>(trigger.entryValue);
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07005668 if (isAeTrigger) {
5669 request->mResultExtras.precaptureTriggerId = triggerId;
5670 mCurrentPreCaptureTriggerId = triggerId;
5671 } else {
5672 request->mResultExtras.afTriggerId = triggerId;
5673 mCurrentAfTriggerId = triggerId;
5674 }
Emilian Peev7e25e5e2017-04-07 15:48:49 +01005675 continue;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07005676 }
5677
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005678 camera_metadata_entry entry = metadata.find(tag);
5679
5680 if (entry.count > 0) {
5681 /**
5682 * Already has an entry for this trigger in the request.
5683 * Rewrite it with our requested trigger value.
5684 */
5685 RequestTrigger oldTrigger = trigger;
5686
5687 oldTrigger.entryValue = entry.data.u8[0];
5688
5689 mTriggerReplacedMap.add(tag, oldTrigger);
5690 } else {
5691 /**
5692 * More typical, no trigger entry, so we just add it
5693 */
5694 mTriggerRemovedMap.add(tag, trigger);
5695 }
5696
5697 status_t res;
5698
5699 switch (trigger.getTagType()) {
5700 case TYPE_BYTE: {
5701 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
5702 res = metadata.update(tag,
5703 &entryValue,
5704 /*count*/1);
5705 break;
5706 }
5707 case TYPE_INT32:
5708 res = metadata.update(tag,
5709 &trigger.entryValue,
5710 /*count*/1);
5711 break;
5712 default:
5713 ALOGE("%s: Type not supported: 0x%x",
5714 __FUNCTION__,
5715 trigger.getTagType());
5716 return INVALID_OPERATION;
5717 }
5718
5719 if (res != OK) {
5720 ALOGE("%s: Failed to update request metadata with trigger tag %s"
5721 ", value %d", __FUNCTION__, trigger.getTagName(),
5722 trigger.entryValue);
5723 return res;
5724 }
5725
5726 ALOGV("%s: Mixed in trigger %s, value %d", __FUNCTION__,
5727 trigger.getTagName(),
5728 trigger.entryValue);
5729 }
5730
5731 mTriggerMap.clear();
5732
5733 return count;
5734}
5735
5736status_t Camera3Device::RequestThread::removeTriggers(
5737 const sp<CaptureRequest> &request) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005738 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005739 Mutex::Autolock al(mTriggerMutex);
5740
Emilian Peevaebbe412018-01-15 13:53:24 +00005741 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005742
5743 /**
5744 * Replace all old entries with their old values.
5745 */
5746 for (size_t i = 0; i < mTriggerReplacedMap.size(); ++i) {
5747 RequestTrigger trigger = mTriggerReplacedMap.valueAt(i);
5748
5749 status_t res;
5750
5751 uint32_t tag = trigger.metadataTag;
5752 switch (trigger.getTagType()) {
5753 case TYPE_BYTE: {
5754 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
5755 res = metadata.update(tag,
5756 &entryValue,
5757 /*count*/1);
5758 break;
5759 }
5760 case TYPE_INT32:
5761 res = metadata.update(tag,
5762 &trigger.entryValue,
5763 /*count*/1);
5764 break;
5765 default:
5766 ALOGE("%s: Type not supported: 0x%x",
5767 __FUNCTION__,
5768 trigger.getTagType());
5769 return INVALID_OPERATION;
5770 }
5771
5772 if (res != OK) {
5773 ALOGE("%s: Failed to restore request metadata with trigger tag %s"
5774 ", trigger value %d", __FUNCTION__,
5775 trigger.getTagName(), trigger.entryValue);
5776 return res;
5777 }
5778 }
5779 mTriggerReplacedMap.clear();
5780
5781 /**
5782 * Remove all new entries.
5783 */
5784 for (size_t i = 0; i < mTriggerRemovedMap.size(); ++i) {
5785 RequestTrigger trigger = mTriggerRemovedMap.valueAt(i);
5786 status_t res = metadata.erase(trigger.metadataTag);
5787
5788 if (res != OK) {
5789 ALOGE("%s: Failed to erase metadata with trigger tag %s"
5790 ", trigger value %d", __FUNCTION__,
5791 trigger.getTagName(), trigger.entryValue);
5792 return res;
5793 }
5794 }
5795 mTriggerRemovedMap.clear();
5796
5797 return OK;
5798}
5799
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04005800status_t Camera3Device::RequestThread::addFakeTriggerIds(
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005801 const sp<CaptureRequest> &request) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08005802 // Trigger ID 0 had special meaning in the HAL2 spec, so avoid it here
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04005803 static const int32_t fakeTriggerId = 1;
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005804 status_t res;
5805
Emilian Peevaebbe412018-01-15 13:53:24 +00005806 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005807
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04005808 // If AF trigger is active, insert a fake AF trigger ID if none already
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005809 // exists
5810 camera_metadata_entry afTrigger = metadata.find(ANDROID_CONTROL_AF_TRIGGER);
5811 camera_metadata_entry afId = metadata.find(ANDROID_CONTROL_AF_TRIGGER_ID);
5812 if (afTrigger.count > 0 &&
5813 afTrigger.data.u8[0] != ANDROID_CONTROL_AF_TRIGGER_IDLE &&
5814 afId.count == 0) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04005815 res = metadata.update(ANDROID_CONTROL_AF_TRIGGER_ID, &fakeTriggerId, 1);
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005816 if (res != OK) return res;
5817 }
5818
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04005819 // If AE precapture trigger is active, insert a fake precapture trigger ID
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005820 // if none already exists
5821 camera_metadata_entry pcTrigger =
5822 metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER);
5823 camera_metadata_entry pcId = metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_ID);
5824 if (pcTrigger.count > 0 &&
5825 pcTrigger.data.u8[0] != ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_IDLE &&
5826 pcId.count == 0) {
5827 res = metadata.update(ANDROID_CONTROL_AE_PRECAPTURE_ID,
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04005828 &fakeTriggerId, 1);
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005829 if (res != OK) return res;
5830 }
5831
5832 return OK;
5833}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005834
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005835bool Camera3Device::RequestThread::overrideAutoRotateAndCrop(
5836 const sp<CaptureRequest> &request) {
5837 ATRACE_CALL();
5838
5839 if (request->mRotateAndCropAuto) {
5840 Mutex::Autolock l(mTriggerMutex);
5841 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
5842
5843 auto rotateAndCropEntry = metadata.find(ANDROID_SCALER_ROTATE_AND_CROP);
5844 if (rotateAndCropEntry.count > 0) {
5845 if (rotateAndCropEntry.data.u8[0] == mRotateAndCropOverride) {
5846 return false;
5847 } else {
5848 rotateAndCropEntry.data.u8[0] = mRotateAndCropOverride;
5849 return true;
5850 }
5851 } else {
5852 uint8_t rotateAndCrop_u8 = mRotateAndCropOverride;
5853 metadata.update(ANDROID_SCALER_ROTATE_AND_CROP,
5854 &rotateAndCrop_u8, 1);
5855 return true;
5856 }
5857 }
5858 return false;
5859}
5860
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005861bool Camera3Device::RequestThread::overrideTestPattern(
5862 const sp<CaptureRequest> &request) {
5863 ATRACE_CALL();
5864
Eino-Ville Talvalac2459842021-07-22 16:36:36 -07005865 {
5866 sp<Camera3Device> parent = mParent.promote();
5867 if (parent != nullptr) {
5868 if (!parent->supportsCameraMute()) return false;
5869 }
5870 }
5871
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005872 Mutex::Autolock l(mTriggerMutex);
5873
5874 bool changed = false;
5875
5876 int32_t testPatternMode = request->mOriginalTestPatternMode;
5877 int32_t testPatternData[4] = {
5878 request->mOriginalTestPatternData[0],
5879 request->mOriginalTestPatternData[1],
5880 request->mOriginalTestPatternData[2],
5881 request->mOriginalTestPatternData[3]
5882 };
5883
Eino-Ville Talvala11afe4f2021-05-27 14:45:31 -07005884 if (mCameraMute != ANDROID_SENSOR_TEST_PATTERN_MODE_OFF) {
5885 testPatternMode = mCameraMute;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005886 testPatternData[0] = 0;
5887 testPatternData[1] = 0;
5888 testPatternData[2] = 0;
5889 testPatternData[3] = 0;
5890 }
5891
5892 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
5893
5894 auto testPatternEntry = metadata.find(ANDROID_SENSOR_TEST_PATTERN_MODE);
5895 if (testPatternEntry.count > 0) {
5896 if (testPatternEntry.data.i32[0] != testPatternMode) {
5897 testPatternEntry.data.i32[0] = testPatternMode;
5898 changed = true;
5899 }
5900 } else {
5901 metadata.update(ANDROID_SENSOR_TEST_PATTERN_MODE,
5902 &testPatternMode, 1);
5903 changed = true;
5904 }
5905
5906 auto testPatternColor = metadata.find(ANDROID_SENSOR_TEST_PATTERN_DATA);
Eino-Ville Talvalac2459842021-07-22 16:36:36 -07005907 if (testPatternColor.count >= 4) {
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005908 for (size_t i = 0; i < 4; i++) {
Eino-Ville Talvalac2459842021-07-22 16:36:36 -07005909 if (testPatternColor.data.i32[i] != testPatternData[i]) {
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005910 testPatternColor.data.i32[i] = testPatternData[i];
5911 changed = true;
5912 }
5913 }
5914 } else {
5915 metadata.update(ANDROID_SENSOR_TEST_PATTERN_DATA,
Eino-Ville Talvalac2459842021-07-22 16:36:36 -07005916 testPatternData, 4);
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005917 changed = true;
5918 }
5919
5920 return changed;
5921}
5922
Cliff Wuc2ad9c82021-04-21 00:58:58 +08005923status_t Camera3Device::RequestThread::setHalInterface(
5924 sp<HalInterface> newHalInterface) {
5925 if (newHalInterface.get() == nullptr) {
5926 ALOGE("%s: The newHalInterface does not exist!", __FUNCTION__);
5927 return DEAD_OBJECT;
5928 }
5929
5930 mInterface = newHalInterface;
5931
5932 return OK;
5933}
5934
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005935/**
5936 * PreparerThread inner class methods
5937 */
5938
5939Camera3Device::PreparerThread::PreparerThread() :
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07005940 Thread(/*canCallJava*/false), mListener(nullptr),
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005941 mActive(false), mCancelNow(false), mCurrentMaxCount(0), mCurrentPrepareComplete(false) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005942}
5943
5944Camera3Device::PreparerThread::~PreparerThread() {
5945 Thread::requestExitAndWait();
5946 if (mCurrentStream != nullptr) {
5947 mCurrentStream->cancelPrepare();
5948 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
5949 mCurrentStream.clear();
5950 }
5951 clear();
5952}
5953
Ruben Brunkc78ac262015-08-13 17:58:46 -07005954status_t Camera3Device::PreparerThread::prepare(int maxCount, sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005955 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005956 status_t res;
5957
5958 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005959 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005960
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07005961 res = stream->startPrepare(maxCount, true /*blockRequest*/);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005962 if (res == OK) {
5963 // No preparation needed, fire listener right off
5964 ALOGV("%s: Stream %d already prepared", __FUNCTION__, stream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005965 if (listener != NULL) {
5966 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005967 }
5968 return OK;
5969 } else if (res != NOT_ENOUGH_DATA) {
5970 return res;
5971 }
5972
5973 // Need to prepare, start up thread if necessary
5974 if (!mActive) {
5975 // mRunning will change to false before the thread fully shuts down, so wait to be sure it
5976 // isn't running
5977 Thread::requestExitAndWait();
5978 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
5979 if (res != OK) {
5980 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__, res, strerror(-res));
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005981 if (listener != NULL) {
5982 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005983 }
5984 return res;
5985 }
5986 mCancelNow = false;
5987 mActive = true;
5988 ALOGV("%s: Preparer stream started", __FUNCTION__);
5989 }
5990
5991 // queue up the work
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005992 mPendingStreams.emplace(maxCount, stream);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005993 ALOGV("%s: Stream %d queued for preparing", __FUNCTION__, stream->getId());
5994
5995 return OK;
5996}
5997
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005998void Camera3Device::PreparerThread::pause() {
5999 ATRACE_CALL();
6000
6001 Mutex::Autolock l(mLock);
6002
6003 std::unordered_map<int, sp<camera3::Camera3StreamInterface> > pendingStreams;
6004 pendingStreams.insert(mPendingStreams.begin(), mPendingStreams.end());
6005 sp<camera3::Camera3StreamInterface> currentStream = mCurrentStream;
6006 int currentMaxCount = mCurrentMaxCount;
6007 mPendingStreams.clear();
6008 mCancelNow = true;
6009 while (mActive) {
6010 auto res = mThreadActiveSignal.waitRelative(mLock, kActiveTimeout);
6011 if (res == TIMED_OUT) {
6012 ALOGE("%s: Timed out waiting on prepare thread!", __FUNCTION__);
6013 return;
6014 } else if (res != OK) {
6015 ALOGE("%s: Encountered an error: %d waiting on prepare thread!", __FUNCTION__, res);
6016 return;
6017 }
6018 }
6019
6020 //Check whether the prepare thread was able to complete the current
6021 //stream. In case work is still pending emplace it along with the rest
6022 //of the streams in the pending list.
6023 if (currentStream != nullptr) {
6024 if (!mCurrentPrepareComplete) {
6025 pendingStreams.emplace(currentMaxCount, currentStream);
6026 }
6027 }
6028
6029 mPendingStreams.insert(pendingStreams.begin(), pendingStreams.end());
6030 for (const auto& it : mPendingStreams) {
6031 it.second->cancelPrepare();
6032 }
6033}
6034
6035status_t Camera3Device::PreparerThread::resume() {
6036 ATRACE_CALL();
6037 status_t res;
6038
6039 Mutex::Autolock l(mLock);
6040 sp<NotificationListener> listener = mListener.promote();
6041
6042 if (mActive) {
6043 ALOGE("%s: Trying to resume an already active prepare thread!", __FUNCTION__);
6044 return NO_INIT;
6045 }
6046
6047 auto it = mPendingStreams.begin();
6048 for (; it != mPendingStreams.end();) {
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07006049 res = it->second->startPrepare(it->first, true /*blockRequest*/);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006050 if (res == OK) {
6051 if (listener != NULL) {
6052 listener->notifyPrepared(it->second->getId());
6053 }
6054 it = mPendingStreams.erase(it);
6055 } else if (res != NOT_ENOUGH_DATA) {
6056 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__,
6057 res, strerror(-res));
6058 it = mPendingStreams.erase(it);
6059 } else {
6060 it++;
6061 }
6062 }
6063
6064 if (mPendingStreams.empty()) {
6065 return OK;
6066 }
6067
6068 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
6069 if (res != OK) {
6070 ALOGE("%s: Unable to start preparer stream: %d (%s)",
6071 __FUNCTION__, res, strerror(-res));
6072 return res;
6073 }
6074 mCancelNow = false;
6075 mActive = true;
6076 ALOGV("%s: Preparer stream started", __FUNCTION__);
6077
6078 return OK;
6079}
6080
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006081status_t Camera3Device::PreparerThread::clear() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07006082 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006083 Mutex::Autolock l(mLock);
6084
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006085 for (const auto& it : mPendingStreams) {
6086 it.second->cancelPrepare();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006087 }
6088 mPendingStreams.clear();
6089 mCancelNow = true;
6090
6091 return OK;
6092}
6093
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006094void Camera3Device::PreparerThread::setNotificationListener(wp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07006095 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006096 Mutex::Autolock l(mLock);
6097 mListener = listener;
6098}
6099
6100bool Camera3Device::PreparerThread::threadLoop() {
6101 status_t res;
6102 {
6103 Mutex::Autolock l(mLock);
6104 if (mCurrentStream == nullptr) {
6105 // End thread if done with work
6106 if (mPendingStreams.empty()) {
6107 ALOGV("%s: Preparer stream out of work", __FUNCTION__);
6108 // threadLoop _must not_ re-acquire mLock after it sets mActive to false; would
6109 // cause deadlock with prepare()'s requestExitAndWait triggered by !mActive.
6110 mActive = false;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006111 mThreadActiveSignal.signal();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006112 return false;
6113 }
6114
6115 // Get next stream to prepare
6116 auto it = mPendingStreams.begin();
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006117 mCurrentStream = it->second;
6118 mCurrentMaxCount = it->first;
6119 mCurrentPrepareComplete = false;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006120 mPendingStreams.erase(it);
6121 ATRACE_ASYNC_BEGIN("stream prepare", mCurrentStream->getId());
6122 ALOGV("%s: Preparing stream %d", __FUNCTION__, mCurrentStream->getId());
6123 } else if (mCancelNow) {
6124 mCurrentStream->cancelPrepare();
6125 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
6126 ALOGV("%s: Cancelling stream %d prepare", __FUNCTION__, mCurrentStream->getId());
6127 mCurrentStream.clear();
6128 mCancelNow = false;
6129 return true;
6130 }
6131 }
6132
6133 res = mCurrentStream->prepareNextBuffer();
6134 if (res == NOT_ENOUGH_DATA) return true;
6135 if (res != OK) {
6136 // Something bad happened; try to recover by cancelling prepare and
6137 // signalling listener anyway
6138 ALOGE("%s: Stream %d returned error %d (%s) during prepare", __FUNCTION__,
6139 mCurrentStream->getId(), res, strerror(-res));
6140 mCurrentStream->cancelPrepare();
6141 }
6142
6143 // This stream has finished, notify listener
6144 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006145 sp<NotificationListener> listener = mListener.promote();
6146 if (listener != NULL) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006147 ALOGV("%s: Stream %d prepare done, signaling listener", __FUNCTION__,
6148 mCurrentStream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006149 listener->notifyPrepared(mCurrentStream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006150 }
6151
6152 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
6153 mCurrentStream.clear();
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006154 mCurrentPrepareComplete = true;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006155
6156 return true;
6157}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07006158
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006159status_t Camera3Device::RequestBufferStateMachine::initialize(
6160 sp<camera3::StatusTracker> statusTracker) {
6161 if (statusTracker == nullptr) {
6162 ALOGE("%s: statusTracker is null", __FUNCTION__);
6163 return BAD_VALUE;
6164 }
6165
6166 std::lock_guard<std::mutex> lock(mLock);
6167 mStatusTracker = statusTracker;
Yin-Chia Yeh87b3ec02019-06-03 10:44:39 -07006168 mRequestBufferStatusId = statusTracker->addComponent("BufferRequestSM");
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006169 return OK;
6170}
6171
6172bool Camera3Device::RequestBufferStateMachine::startRequestBuffer() {
6173 std::lock_guard<std::mutex> lock(mLock);
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08006174 if (mStatus == RB_STATUS_READY || mStatus == RB_STATUS_PENDING_STOP) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006175 mRequestBufferOngoing = true;
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08006176 notifyTrackerLocked(/*active*/true);
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006177 return true;
6178 }
6179 return false;
6180}
6181
6182void Camera3Device::RequestBufferStateMachine::endRequestBuffer() {
6183 std::lock_guard<std::mutex> lock(mLock);
6184 if (!mRequestBufferOngoing) {
6185 ALOGE("%s called without a successful startRequestBuffer call first!", __FUNCTION__);
6186 return;
6187 }
6188 mRequestBufferOngoing = false;
6189 if (mStatus == RB_STATUS_PENDING_STOP) {
6190 checkSwitchToStopLocked();
6191 }
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08006192 notifyTrackerLocked(/*active*/false);
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006193}
6194
6195void Camera3Device::RequestBufferStateMachine::onStreamsConfigured() {
6196 std::lock_guard<std::mutex> lock(mLock);
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006197 mSwitchedToOffline = false;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006198 mStatus = RB_STATUS_READY;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006199 return;
6200}
6201
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08006202void Camera3Device::RequestBufferStateMachine::onSubmittingRequest() {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006203 std::lock_guard<std::mutex> lock(mLock);
6204 mRequestThreadPaused = false;
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08006205 // inflight map register actually happens in prepareHalRequest now, but it is close enough
6206 // approximation.
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006207 mInflightMapEmpty = false;
6208 if (mStatus == RB_STATUS_STOPPED) {
6209 mStatus = RB_STATUS_READY;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006210 }
6211 return;
6212}
6213
6214void Camera3Device::RequestBufferStateMachine::onRequestThreadPaused() {
6215 std::lock_guard<std::mutex> lock(mLock);
6216 mRequestThreadPaused = true;
6217 if (mStatus == RB_STATUS_PENDING_STOP) {
6218 checkSwitchToStopLocked();
6219 }
6220 return;
6221}
6222
6223void Camera3Device::RequestBufferStateMachine::onInflightMapEmpty() {
6224 std::lock_guard<std::mutex> lock(mLock);
6225 mInflightMapEmpty = true;
6226 if (mStatus == RB_STATUS_PENDING_STOP) {
6227 checkSwitchToStopLocked();
6228 }
6229 return;
6230}
6231
6232void Camera3Device::RequestBufferStateMachine::onWaitUntilIdle() {
6233 std::lock_guard<std::mutex> lock(mLock);
6234 if (!checkSwitchToStopLocked()) {
6235 mStatus = RB_STATUS_PENDING_STOP;
6236 }
6237 return;
6238}
6239
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006240bool Camera3Device::RequestBufferStateMachine::onSwitchToOfflineSuccess() {
6241 std::lock_guard<std::mutex> lock(mLock);
6242 if (mRequestBufferOngoing) {
6243 ALOGE("%s: HAL must not be requesting buffer after HAL returns switchToOffline!",
6244 __FUNCTION__);
6245 return false;
6246 }
6247 mSwitchedToOffline = true;
6248 mInflightMapEmpty = true;
6249 mRequestThreadPaused = true;
6250 mStatus = RB_STATUS_STOPPED;
6251 return true;
6252}
6253
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006254void Camera3Device::RequestBufferStateMachine::notifyTrackerLocked(bool active) {
6255 sp<StatusTracker> statusTracker = mStatusTracker.promote();
6256 if (statusTracker != nullptr) {
6257 if (active) {
6258 statusTracker->markComponentActive(mRequestBufferStatusId);
6259 } else {
6260 statusTracker->markComponentIdle(mRequestBufferStatusId, Fence::NO_FENCE);
6261 }
6262 }
6263}
6264
6265bool Camera3Device::RequestBufferStateMachine::checkSwitchToStopLocked() {
6266 if (mInflightMapEmpty && mRequestThreadPaused && !mRequestBufferOngoing) {
6267 mStatus = RB_STATUS_STOPPED;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006268 return true;
6269 }
6270 return false;
6271}
6272
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006273bool Camera3Device::startRequestBuffer() {
6274 return mRequestBufferSM.startRequestBuffer();
6275}
Shuzhen Wang268a1362018-10-16 16:32:59 -07006276
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006277void Camera3Device::endRequestBuffer() {
6278 mRequestBufferSM.endRequestBuffer();
6279}
Shuzhen Wang268a1362018-10-16 16:32:59 -07006280
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006281nsecs_t Camera3Device::getWaitDuration() {
6282 return kBaseGetBufferWait + getExpectedInFlightDuration();
6283}
Shuzhen Wang268a1362018-10-16 16:32:59 -07006284
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006285void Camera3Device::getInflightBufferKeys(std::vector<std::pair<int32_t, int32_t>>* out) {
6286 mInterface->getInflightBufferKeys(out);
6287}
Shuzhen Wang268a1362018-10-16 16:32:59 -07006288
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006289void Camera3Device::getInflightRequestBufferKeys(std::vector<uint64_t>* out) {
6290 mInterface->getInflightRequestBufferKeys(out);
6291}
Shuzhen Wang268a1362018-10-16 16:32:59 -07006292
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006293std::vector<sp<Camera3StreamInterface>> Camera3Device::getAllStreams() {
6294 std::vector<sp<Camera3StreamInterface>> ret;
6295 bool hasInputStream = mInputStream != nullptr;
6296 ret.reserve(mOutputStreams.size() + mDeletedStreams.size() + ((hasInputStream) ? 1 : 0));
6297 if (hasInputStream) {
6298 ret.push_back(mInputStream);
Shuzhen Wang268a1362018-10-16 16:32:59 -07006299 }
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006300 for (size_t i = 0; i < mOutputStreams.size(); i++) {
6301 ret.push_back(mOutputStreams[i]);
6302 }
6303 for (size_t i = 0; i < mDeletedStreams.size(); i++) {
6304 ret.push_back(mDeletedStreams[i]);
6305 }
6306 return ret;
Shuzhen Wang268a1362018-10-16 16:32:59 -07006307}
6308
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006309status_t Camera3Device::switchToOffline(
6310 const std::vector<int32_t>& streamsToKeep,
6311 /*out*/ sp<CameraOfflineSessionBase>* session) {
6312 ATRACE_CALL();
6313 if (session == nullptr) {
6314 ALOGE("%s: session must not be null", __FUNCTION__);
6315 return BAD_VALUE;
6316 }
6317
6318 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006319
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006320 bool hasInputStream = mInputStream != nullptr;
6321 int32_t inputStreamId = hasInputStream ? mInputStream->getId() : -1;
6322 bool inputStreamSupportsOffline = hasInputStream ?
6323 mInputStream->getOfflineProcessingSupport() : false;
6324 auto outputStreamIds = mOutputStreams.getStreamIds();
6325 auto streamIds = outputStreamIds;
6326 if (hasInputStream) {
6327 streamIds.push_back(mInputStream->getId());
6328 }
6329
6330 // Check all streams in streamsToKeep supports offline mode
6331 for (auto id : streamsToKeep) {
6332 if (std::find(streamIds.begin(), streamIds.end(), id) == streamIds.end()) {
6333 ALOGE("%s: Unknown stream ID %d", __FUNCTION__, id);
6334 return BAD_VALUE;
6335 } else if (id == inputStreamId) {
6336 if (!inputStreamSupportsOffline) {
6337 ALOGE("%s: input stream %d cannot be switched to offline",
6338 __FUNCTION__, id);
6339 return BAD_VALUE;
6340 }
6341 } else {
6342 sp<camera3::Camera3OutputStreamInterface> stream = mOutputStreams.get(id);
6343 if (!stream->getOfflineProcessingSupport()) {
6344 ALOGE("%s: output stream %d cannot be switched to offline",
6345 __FUNCTION__, id);
6346 return BAD_VALUE;
6347 }
6348 }
6349 }
6350
6351 // TODO: block surface sharing and surface group streams until we can support them
6352
6353 // Stop repeating request, wait until all remaining requests are submitted, then call into
6354 // HAL switchToOffline
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006355 hardware::camera::device::V3_6::CameraOfflineSessionInfo offlineSessionInfo;
6356 sp<hardware::camera::device::V3_6::ICameraOfflineSession> offlineSession;
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006357 camera3::BufferRecords bufferRecords;
6358 status_t ret = mRequestThread->switchToOffline(
6359 streamsToKeep, &offlineSessionInfo, &offlineSession, &bufferRecords);
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006360
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006361 if (ret != OK) {
6362 SET_ERR("Switch to offline failed: %s (%d)", strerror(-ret), ret);
6363 return ret;
6364 }
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006365
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006366 bool succ = mRequestBufferSM.onSwitchToOfflineSuccess();
6367 if (!succ) {
6368 SET_ERR("HAL must not be calling requestStreamBuffers call");
6369 // TODO: block ALL callbacks from HAL till app configured new streams?
6370 return UNKNOWN_ERROR;
6371 }
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006372
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006373 // Verify offlineSessionInfo
6374 std::vector<int32_t> offlineStreamIds;
6375 offlineStreamIds.reserve(offlineSessionInfo.offlineStreams.size());
6376 for (auto offlineStream : offlineSessionInfo.offlineStreams) {
6377 // verify stream IDs
6378 int32_t id = offlineStream.id;
6379 if (std::find(streamIds.begin(), streamIds.end(), id) == streamIds.end()) {
6380 SET_ERR("stream ID %d not found!", id);
6381 return UNKNOWN_ERROR;
6382 }
6383
6384 // When not using HAL buf manager, only allow streams requested by app to be preserved
6385 if (!mUseHalBufManager) {
6386 if (std::find(streamsToKeep.begin(), streamsToKeep.end(), id) == streamsToKeep.end()) {
6387 SET_ERR("stream ID %d must not be switched to offline!", id);
6388 return UNKNOWN_ERROR;
6389 }
6390 }
6391
6392 offlineStreamIds.push_back(id);
6393 sp<Camera3StreamInterface> stream = (id == inputStreamId) ?
6394 static_cast<sp<Camera3StreamInterface>>(mInputStream) :
6395 static_cast<sp<Camera3StreamInterface>>(mOutputStreams.get(id));
6396 // Verify number of outstanding buffers
6397 if (stream->getOutstandingBuffersCount() != offlineStream.numOutstandingBuffers) {
6398 SET_ERR("Offline stream %d # of remaining buffer mismatch: (%zu,%d) (service/HAL)",
6399 id, stream->getOutstandingBuffersCount(), offlineStream.numOutstandingBuffers);
6400 return UNKNOWN_ERROR;
6401 }
6402 }
6403
6404 // Verify all streams to be deleted don't have any outstanding buffers
6405 if (hasInputStream && std::find(offlineStreamIds.begin(), offlineStreamIds.end(),
6406 inputStreamId) == offlineStreamIds.end()) {
6407 if (mInputStream->hasOutstandingBuffers()) {
6408 SET_ERR("Input stream %d still has %zu outstanding buffer!",
6409 inputStreamId, mInputStream->getOutstandingBuffersCount());
6410 return UNKNOWN_ERROR;
6411 }
6412 }
6413
6414 for (const auto& outStreamId : outputStreamIds) {
6415 if (std::find(offlineStreamIds.begin(), offlineStreamIds.end(),
6416 outStreamId) == offlineStreamIds.end()) {
6417 auto outStream = mOutputStreams.get(outStreamId);
6418 if (outStream->hasOutstandingBuffers()) {
6419 SET_ERR("Output stream %d still has %zu outstanding buffer!",
6420 outStreamId, outStream->getOutstandingBuffersCount());
6421 return UNKNOWN_ERROR;
6422 }
6423 }
6424 }
6425
6426 InFlightRequestMap offlineReqs;
6427 // Verify inflight requests and their pending buffers
6428 {
6429 std::lock_guard<std::mutex> l(mInFlightLock);
6430 for (auto offlineReq : offlineSessionInfo.offlineRequests) {
6431 int idx = mInFlightMap.indexOfKey(offlineReq.frameNumber);
6432 if (idx == NAME_NOT_FOUND) {
6433 SET_ERR("Offline request frame number %d not found!", offlineReq.frameNumber);
6434 return UNKNOWN_ERROR;
6435 }
6436
6437 const auto& inflightReq = mInFlightMap.valueAt(idx);
6438 // TODO: check specific stream IDs
6439 size_t numBuffersLeft = static_cast<size_t>(inflightReq.numBuffersLeft);
6440 if (numBuffersLeft != offlineReq.pendingStreams.size()) {
6441 SET_ERR("Offline request # of remaining buffer mismatch: (%d,%d) (service/HAL)",
6442 inflightReq.numBuffersLeft, offlineReq.pendingStreams.size());
6443 return UNKNOWN_ERROR;
6444 }
6445 offlineReqs.add(offlineReq.frameNumber, inflightReq);
6446 }
6447 }
6448
6449 // Create Camera3OfflineSession and transfer object ownership
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006450 // (streams, inflight requests, buffer caches)
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006451 camera3::StreamSet offlineStreamSet;
6452 sp<camera3::Camera3Stream> inputStream;
6453 for (auto offlineStream : offlineSessionInfo.offlineStreams) {
6454 int32_t id = offlineStream.id;
6455 if (mInputStream != nullptr && id == mInputStream->getId()) {
6456 inputStream = mInputStream;
6457 } else {
6458 offlineStreamSet.add(id, mOutputStreams.get(id));
6459 }
6460 }
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006461
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006462 // TODO: check if we need to lock before copying states
6463 // though technically no other thread should be talking to Camera3Device at this point
6464 Camera3OfflineStates offlineStates(
6465 mTagMonitor, mVendorTagId, mUseHalBufManager, mNeedFixupMonochromeTags,
Shuzhen Wangb7b42652020-05-07 11:59:02 -07006466 mUsePartialResult, mNumPartialResults, mLastCompletedRegularFrameNumber,
6467 mLastCompletedReprocessFrameNumber, mLastCompletedZslFrameNumber,
6468 mNextResultFrameNumber, mNextReprocessResultFrameNumber,
6469 mNextZslStillResultFrameNumber, mNextShutterFrameNumber,
6470 mNextReprocessShutterFrameNumber, mNextZslStillShutterFrameNumber,
6471 mDeviceInfo, mPhysicalDeviceInfoMap, mDistortionMappers,
6472 mZoomRatioMappers, mRotateAndCropMappers);
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006473
6474 *session = new Camera3OfflineSession(mId, inputStream, offlineStreamSet,
6475 std::move(bufferRecords), offlineReqs, offlineStates, offlineSession);
6476
6477 // Delete all streams that has been transferred to offline session
6478 Mutex::Autolock l(mLock);
6479 for (auto offlineStream : offlineSessionInfo.offlineStreams) {
6480 int32_t id = offlineStream.id;
6481 if (mInputStream != nullptr && id == mInputStream->getId()) {
6482 mInputStream.clear();
6483 } else {
6484 mOutputStreams.remove(id);
6485 }
6486 }
6487
6488 // disconnect all other streams and switch to UNCONFIGURED state
6489 if (mInputStream != nullptr) {
6490 ret = mInputStream->disconnect();
6491 if (ret != OK) {
6492 SET_ERR_L("disconnect input stream failed!");
6493 return UNKNOWN_ERROR;
6494 }
6495 }
6496
6497 for (auto streamId : mOutputStreams.getStreamIds()) {
6498 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
6499 ret = stream->disconnect();
6500 if (ret != OK) {
6501 SET_ERR_L("disconnect output stream %d failed!", streamId);
6502 return UNKNOWN_ERROR;
6503 }
6504 }
6505
6506 mInputStream.clear();
6507 mOutputStreams.clear();
6508 mNeedConfig = true;
6509 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
6510 mOperatingMode = NO_MODE;
6511 mIsConstrainedHighSpeedConfiguration = false;
Emilian Peevc0fe54c2020-03-11 14:05:07 -07006512 mRequestThread->clearPreviousRequest();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006513
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006514 return OK;
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006515 // TO be done by CameraDeviceClient/Camera3OfflineSession
6516 // register the offline client to camera service
6517 // Setup result passthing threads etc
6518 // Initialize offline session so HAL can start sending callback to it (result Fmq)
6519 // TODO: check how many onIdle callback will be sent
6520 // Java side to make sure the CameraCaptureSession is properly closed
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006521}
6522
Emilian Peevcc0b7952020-01-07 13:54:47 -08006523void Camera3Device::getOfflineStreamIds(std::vector<int> *offlineStreamIds) {
6524 ATRACE_CALL();
6525
6526 if (offlineStreamIds == nullptr) {
6527 return;
6528 }
6529
6530 Mutex::Autolock il(mInterfaceLock);
6531
6532 auto streamIds = mOutputStreams.getStreamIds();
6533 bool hasInputStream = mInputStream != nullptr;
6534 if (hasInputStream && mInputStream->getOfflineProcessingSupport()) {
6535 offlineStreamIds->push_back(mInputStream->getId());
6536 }
6537
6538 for (const auto & streamId : streamIds) {
6539 sp<camera3::Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
6540 // Streams that use the camera buffer manager are currently not supported in
6541 // offline mode
6542 if (stream->getOfflineProcessingSupport() &&
6543 (stream->getStreamSetId() == CAMERA3_STREAM_SET_ID_INVALID)) {
6544 offlineStreamIds->push_back(streamId);
6545 }
6546 }
6547}
6548
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08006549status_t Camera3Device::setRotateAndCropAutoBehavior(
6550 camera_metadata_enum_android_scaler_rotate_and_crop_t rotateAndCropValue) {
6551 ATRACE_CALL();
6552 Mutex::Autolock il(mInterfaceLock);
6553 Mutex::Autolock l(mLock);
6554 if (mRequestThread == nullptr) {
6555 return INVALID_OPERATION;
6556 }
6557 return mRequestThread->setRotateAndCropAutoBehavior(rotateAndCropValue);
6558}
6559
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08006560bool Camera3Device::supportsCameraMute() {
6561 Mutex::Autolock il(mInterfaceLock);
6562 Mutex::Autolock l(mLock);
6563
6564 return mSupportCameraMute;
6565}
6566
6567status_t Camera3Device::setCameraMute(bool enabled) {
6568 ATRACE_CALL();
6569 Mutex::Autolock il(mInterfaceLock);
6570 Mutex::Autolock l(mLock);
6571
6572 if (mRequestThread == nullptr || !mSupportCameraMute) {
6573 return INVALID_OPERATION;
6574 }
Eino-Ville Talvala11afe4f2021-05-27 14:45:31 -07006575 int32_t muteMode =
6576 !enabled ? ANDROID_SENSOR_TEST_PATTERN_MODE_OFF :
6577 mSupportTestPatternSolidColor ? ANDROID_SENSOR_TEST_PATTERN_MODE_SOLID_COLOR :
6578 ANDROID_SENSOR_TEST_PATTERN_MODE_BLACK;
6579 return mRequestThread->setCameraMute(muteMode);
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08006580}
6581
Cliff Wuc2ad9c82021-04-21 00:58:58 +08006582status_t Camera3Device::injectCamera(const String8& injectedCamId,
6583 sp<CameraProviderManager> manager) {
6584 ALOGI("%s Injection camera: injectedCamId = %s", __FUNCTION__, injectedCamId.string());
6585 ATRACE_CALL();
6586 Mutex::Autolock il(mInterfaceLock);
6587
6588 status_t res = NO_ERROR;
6589 if (mInjectionMethods->isInjecting()) {
6590 if (injectedCamId == mInjectionMethods->getInjectedCamId()) {
6591 return OK;
6592 } else {
6593 res = mInjectionMethods->stopInjection();
6594 if (res != OK) {
6595 ALOGE("%s: Failed to stop the injection camera! ret != NO_ERROR: %d",
6596 __FUNCTION__, res);
6597 return res;
6598 }
6599 }
6600 }
6601
6602 res = mInjectionMethods->injectionInitialize(injectedCamId, manager, this);
6603 if (res != OK) {
6604 ALOGE("%s: Failed to initialize the injection camera! ret != NO_ERROR: %d",
6605 __FUNCTION__, res);
6606 return res;
6607 }
6608
6609 camera3::camera_stream_configuration injectionConfig;
6610 std::vector<uint32_t> injectionBufferSizes;
6611 mInjectionMethods->getInjectionConfig(&injectionConfig, &injectionBufferSizes);
6612 // When the second display of android is cast to the remote device, and the opened camera is
6613 // also cast to the second display, in this case, because the camera has configured the streams
6614 // at this time, we can directly call injectCamera() to replace the internal camera with
6615 // injection camera.
6616 if (mOperatingMode >= 0 && injectionConfig.num_streams > 0
6617 && injectionBufferSizes.size() > 0) {
6618 ALOGV("%s: The opened camera is directly cast to the remote device.", __FUNCTION__);
6619 res = mInjectionMethods->injectCamera(
6620 injectionConfig, injectionBufferSizes);
6621 if (res != OK) {
6622 ALOGE("Can't finish inject camera process!");
6623 return res;
6624 }
6625 }
6626
6627 return OK;
6628}
6629
6630status_t Camera3Device::stopInjection() {
6631 ALOGI("%s: Injection camera: stopInjection", __FUNCTION__);
6632 Mutex::Autolock il(mInterfaceLock);
6633 return mInjectionMethods->stopInjection();
6634}
6635
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08006636}; // namespace android