blob: aefc75e877bc4c6e7248c483990a854b8a54ed46 [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);
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700174 }
175 }
176
Yifan Hongf79b5542017-04-11 14:44:25 -0700177 std::shared_ptr<RequestMetadataQueue> queue;
Yifan Honga640c5a2017-04-12 16:30:31 -0700178 auto requestQueueRet = session->getCaptureRequestMetadataQueue(
179 [&queue](const auto& descriptor) {
180 queue = std::make_shared<RequestMetadataQueue>(descriptor);
181 if (!queue->isValid() || queue->availableToWrite() <= 0) {
182 ALOGE("HAL returns empty request metadata fmq, not use it");
183 queue = nullptr;
184 // don't use the queue onwards.
185 }
186 });
187 if (!requestQueueRet.isOk()) {
188 ALOGE("Transaction error when getting request metadata fmq: %s, not use it",
189 requestQueueRet.description().c_str());
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -0700190 return DEAD_OBJECT;
Yifan Hongf79b5542017-04-11 14:44:25 -0700191 }
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700192
193 std::unique_ptr<ResultMetadataQueue>& resQueue = mResultMetadataQueue;
Yifan Honga640c5a2017-04-12 16:30:31 -0700194 auto resultQueueRet = session->getCaptureResultMetadataQueue(
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700195 [&resQueue](const auto& descriptor) {
196 resQueue = std::make_unique<ResultMetadataQueue>(descriptor);
197 if (!resQueue->isValid() || resQueue->availableToWrite() <= 0) {
Yifan Honga640c5a2017-04-12 16:30:31 -0700198 ALOGE("HAL returns empty result metadata fmq, not use it");
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700199 resQueue = nullptr;
200 // Don't use the resQueue onwards.
Yifan Honga640c5a2017-04-12 16:30:31 -0700201 }
202 });
203 if (!resultQueueRet.isOk()) {
204 ALOGE("Transaction error when getting result metadata queue from camera session: %s",
205 resultQueueRet.description().c_str());
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -0700206 return DEAD_OBJECT;
Yifan Honga640c5a2017-04-12 16:30:31 -0700207 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -0700208 IF_ALOGV() {
209 session->interfaceChain([](
210 ::android::hardware::hidl_vec<::android::hardware::hidl_string> interfaceChain) {
211 ALOGV("Session interface chain:");
Chih-Hung Hsieh3ef324d2018-12-11 11:48:12 -0800212 for (const auto& iface : interfaceChain) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -0700213 ALOGV(" %s", iface.c_str());
214 }
215 });
216 }
Yifan Hongf79b5542017-04-11 14:44:25 -0700217
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -0800218 camera_metadata_entry bufMgrMode =
219 mDeviceInfo.find(ANDROID_INFO_SUPPORTED_BUFFER_MANAGEMENT_VERSION);
220 if (bufMgrMode.count > 0) {
221 mUseHalBufManager = (bufMgrMode.data.u8[0] ==
222 ANDROID_INFO_SUPPORTED_BUFFER_MANAGEMENT_VERSION_HIDL_DEVICE_3_5);
223 }
224
Yin-Chia Yehb978c382019-10-30 00:22:37 -0700225 camera_metadata_entry_t capabilities = mDeviceInfo.find(ANDROID_REQUEST_AVAILABLE_CAPABILITIES);
226 for (size_t i = 0; i < capabilities.count; i++) {
227 uint8_t capability = capabilities.data.u8[i];
228 if (capability == ANDROID_REQUEST_AVAILABLE_CAPABILITIES_OFFLINE_PROCESSING) {
229 mSupportOfflineProcessing = true;
230 }
231 }
232
233 mInterface = new HalInterface(session, queue, mUseHalBufManager, mSupportOfflineProcessing);
Emilian Peev71c73a22017-03-21 16:35:51 +0000234 std::string providerType;
235 mVendorTagId = manager->getProviderTagIdLocked(mId.string());
Emilian Peevbd8c5032018-02-14 23:05:40 +0000236 mTagMonitor.initialize(mVendorTagId);
237 if (!monitorTags.isEmpty()) {
238 mTagMonitor.parseTagsToMonitor(String8(monitorTags));
239 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800240
Shuzhen Wang268a1362018-10-16 16:32:59 -0700241 // Metadata tags needs fixup for monochrome camera device version less
242 // than 3.5.
243 hardware::hidl_version maxVersion{0,0};
244 res = manager->getHighestSupportedVersion(mId.string(), &maxVersion);
245 if (res != OK) {
246 ALOGE("%s: Error in getting camera device version id: %s (%d)",
247 __FUNCTION__, strerror(-res), res);
248 return res;
249 }
250 int deviceVersion = HARDWARE_DEVICE_API_VERSION(
251 maxVersion.get_major(), maxVersion.get_minor());
252
253 bool isMonochrome = false;
Yin-Chia Yehb978c382019-10-30 00:22:37 -0700254 for (size_t i = 0; i < capabilities.count; i++) {
255 uint8_t capability = capabilities.data.u8[i];
Shuzhen Wang268a1362018-10-16 16:32:59 -0700256 if (capability == ANDROID_REQUEST_AVAILABLE_CAPABILITIES_MONOCHROME) {
257 isMonochrome = true;
258 }
259 }
260 mNeedFixupMonochromeTags = (isMonochrome && deviceVersion < CAMERA_DEVICE_API_VERSION_3_5);
261
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800262 return initializeCommonLocked();
263}
264
265status_t Camera3Device::initializeCommonLocked() {
266
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700267 /** Start up status tracker thread */
268 mStatusTracker = new StatusTracker(this);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800269 status_t res = mStatusTracker->run(String8::format("C3Dev-%s-Status", mId.string()).string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700270 if (res != OK) {
271 SET_ERR_L("Unable to start status tracking thread: %s (%d)",
272 strerror(-res), res);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800273 mInterface->close();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700274 mStatusTracker.clear();
275 return res;
276 }
277
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -0700278 /** Register in-flight map to the status tracker */
Yin-Chia Yeh87b3ec02019-06-03 10:44:39 -0700279 mInFlightStatusId = mStatusTracker->addComponent("InflightRequests");
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -0700280
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -0700281 if (mUseHalBufManager) {
282 res = mRequestBufferSM.initialize(mStatusTracker);
283 if (res != OK) {
284 SET_ERR_L("Unable to start request buffer state machine: %s (%d)",
285 strerror(-res), res);
286 mInterface->close();
287 mStatusTracker.clear();
288 return res;
289 }
290 }
291
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -0800292 /** Create buffer manager */
293 mBufferManager = new Camera3BufferManager();
294
295 Vector<int32_t> sessionParamKeys;
296 camera_metadata_entry_t sessionKeysEntry = mDeviceInfo.find(
297 ANDROID_REQUEST_AVAILABLE_SESSION_KEYS);
298 if (sessionKeysEntry.count > 0) {
299 sessionParamKeys.insertArrayAt(sessionKeysEntry.data.i32, 0, sessionKeysEntry.count);
300 }
301
Chien-Yu Chenab5135b2015-06-30 11:20:58 -0700302 /** Start up request queue thread */
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -0700303 mRequestThread = new RequestThread(
304 this, mStatusTracker, mInterface, sessionParamKeys, mUseHalBufManager);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800305 res = mRequestThread->run(String8::format("C3Dev-%s-ReqQueue", mId.string()).string());
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800306 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700307 SET_ERR_L("Unable to start request queue thread: %s (%d)",
308 strerror(-res), res);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800309 mInterface->close();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800310 mRequestThread.clear();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800311 return res;
312 }
313
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -0700314 mPreparerThread = new PreparerThread();
315
Ruben Brunk183f0562015-08-12 12:55:02 -0700316 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800317 mNextStreamId = 0;
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -0400318 mFakeStreamId = NO_STREAM;
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -0700319 mNeedConfig = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700320 mPauseStateNotify = false;
Shuzhen Wang83bff122020-11-20 15:51:39 -0800321 mIsInputStreamMultiResolution = false;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800322
Shuzhen Wangc28dccc2016-02-11 23:48:46 -0800323 // Measure the clock domain offset between camera and video/hw_composer
324 camera_metadata_entry timestampSource =
325 mDeviceInfo.find(ANDROID_SENSOR_INFO_TIMESTAMP_SOURCE);
326 if (timestampSource.count > 0 && timestampSource.data.u8[0] ==
327 ANDROID_SENSOR_INFO_TIMESTAMP_SOURCE_REALTIME) {
328 mTimestampOffset = getMonoToBoottimeOffset();
329 }
330
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -0700331 // Will the HAL be sending in early partial result metadata?
Emilian Peev08dd2452017-04-06 16:55:14 +0100332 camera_metadata_entry partialResultsCount =
333 mDeviceInfo.find(ANDROID_REQUEST_PARTIAL_RESULT_COUNT);
334 if (partialResultsCount.count > 0) {
335 mNumPartialResults = partialResultsCount.data.i32[0];
336 mUsePartialResult = (mNumPartialResults > 1);
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -0700337 }
338
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800339 bool usePrecorrectArray = DistortionMapper::isDistortionSupported(mDeviceInfo);
340 if (usePrecorrectArray) {
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -0700341 res = mDistortionMappers[mId.c_str()].setupStaticInfo(mDeviceInfo);
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -0700342 if (res != OK) {
343 SET_ERR_L("Unable to read necessary calibration fields for distortion correction");
344 return res;
345 }
346 }
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800347
Shuzhen Wang1c834da2019-12-18 11:17:03 -0800348 mZoomRatioMappers[mId.c_str()] = ZoomRatioMapper(&mDeviceInfo,
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800349 mSupportNativeZoomRatio, usePrecorrectArray);
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800350
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -0800351 if (RotateAndCropMapper::isNeeded(&mDeviceInfo)) {
352 mRotateAndCropMappers.emplace(mId.c_str(), &mDeviceInfo);
353 }
354
Eino-Ville Talvala305cec62020-11-12 14:18:17 -0800355 camera_metadata_entry_t availableTestPatternModes = mDeviceInfo.find(
356 ANDROID_SENSOR_AVAILABLE_TEST_PATTERN_MODES);
357 for (size_t i = 0; i < availableTestPatternModes.count; i++) {
Eino-Ville Talvala11afe4f2021-05-27 14:45:31 -0700358 if (availableTestPatternModes.data.i32[i] ==
359 ANDROID_SENSOR_TEST_PATTERN_MODE_SOLID_COLOR) {
Eino-Ville Talvala305cec62020-11-12 14:18:17 -0800360 mSupportCameraMute = true;
Eino-Ville Talvala11afe4f2021-05-27 14:45:31 -0700361 mSupportTestPatternSolidColor = true;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -0800362 break;
Eino-Ville Talvala11afe4f2021-05-27 14:45:31 -0700363 } else if (availableTestPatternModes.data.i32[i] ==
364 ANDROID_SENSOR_TEST_PATTERN_MODE_BLACK) {
365 mSupportCameraMute = true;
366 mSupportTestPatternSolidColor = false;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -0800367 }
368 }
369
Cliff Wuc2ad9c82021-04-21 00:58:58 +0800370 mInjectionMethods = new Camera3DeviceInjectionMethods(this);
371
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800372 return OK;
373}
374
375status_t Camera3Device::disconnect() {
Yin-Chia Yehc5248132018-08-15 12:19:20 -0700376 return disconnectImpl();
377}
378
379status_t Camera3Device::disconnectImpl() {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800380 ATRACE_CALL();
Yin-Chia Yehe1c80632016-08-08 14:48:05 -0700381 ALOGI("%s: E", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800382
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700383 status_t res = OK;
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700384 std::vector<wp<Camera3StreamInterface>> streams;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700385 {
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800386 Mutex::Autolock il(mInterfaceLock);
387 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
388 {
389 Mutex::Autolock l(mLock);
390 if (mStatus == STATUS_UNINITIALIZED) return res;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700391
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800392 if (mStatus == STATUS_ACTIVE ||
393 (mStatus == STATUS_ERROR && mRequestThread != NULL)) {
394 res = mRequestThread->clearRepeatingRequests();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700395 if (res != OK) {
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800396 SET_ERR_L("Can't stop streaming");
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700397 // Continue to close device even in case of error
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800398 } else {
399 res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
400 if (res != OK) {
401 SET_ERR_L("Timeout waiting for HAL to drain (% " PRIi64 " ns)",
402 maxExpectedDuration);
403 // Continue to close device even in case of error
404 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700405 }
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700406 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800407
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800408 if (mStatus == STATUS_ERROR) {
409 CLOGE("Shutting down in an error state");
410 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700411
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800412 if (mStatusTracker != NULL) {
413 mStatusTracker->requestExit();
414 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700415
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800416 if (mRequestThread != NULL) {
417 mRequestThread->requestExit();
418 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700419
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800420 streams.reserve(mOutputStreams.size() + (mInputStream != nullptr ? 1 : 0));
421 for (size_t i = 0; i < mOutputStreams.size(); i++) {
422 streams.push_back(mOutputStreams[i]);
423 }
424 if (mInputStream != nullptr) {
425 streams.push_back(mInputStream);
426 }
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700427 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700428 }
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800429 // Joining done without holding mLock and mInterfaceLock, otherwise deadlocks may ensue
430 // as the threads try to access parent state (b/143513518)
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700431 if (mRequestThread != NULL && mStatus != STATUS_ERROR) {
432 // HAL may be in a bad state, so waiting for request thread
433 // (which may be stuck in the HAL processCaptureRequest call)
434 // could be dangerous.
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800435 // give up mInterfaceLock here and then lock it again. Could this lead
436 // to other deadlocks
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700437 mRequestThread->join();
438 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700439 {
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800440 Mutex::Autolock il(mInterfaceLock);
441 if (mStatusTracker != NULL) {
442 mStatusTracker->join();
443 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800444
Cliff Wuc2ad9c82021-04-21 00:58:58 +0800445 if (mInjectionMethods->isInjecting()) {
446 mInjectionMethods->stopInjection();
447 }
448
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800449 HalInterface* interface;
450 {
451 Mutex::Autolock l(mLock);
452 mRequestThread.clear();
453 Mutex::Autolock stLock(mTrackerLock);
454 mStatusTracker.clear();
455 interface = mInterface.get();
456 }
Eino-Ville Talvalaefff1c42015-08-28 16:27:27 -0700457
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800458 // Call close without internal mutex held, as the HAL close may need to
459 // wait on assorted callbacks,etc, to complete before it can return.
460 interface->close();
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700461
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800462 flushInflightRequests();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800463
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800464 {
465 Mutex::Autolock l(mLock);
466 mInterface->clear();
467 mOutputStreams.clear();
468 mInputStream.clear();
469 mDeletedStreams.clear();
470 mBufferManager.clear();
471 internalUpdateStatusLocked(STATUS_UNINITIALIZED);
472 }
473
474 for (auto& weakStream : streams) {
475 sp<Camera3StreamInterface> stream = weakStream.promote();
476 if (stream != nullptr) {
477 ALOGE("%s: Stream %d leaked! strong reference (%d)!",
478 __FUNCTION__, stream->getId(), stream->getStrongCount() - 1);
479 }
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700480 }
481 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -0700482 ALOGI("%s: X", __FUNCTION__);
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700483 return res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800484}
485
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700486// For dumping/debugging only -
487// try to acquire a lock a few times, eventually give up to proceed with
488// debug/dump operations
489bool Camera3Device::tryLockSpinRightRound(Mutex& lock) {
490 bool gotLock = false;
491 for (size_t i = 0; i < kDumpLockAttempts; ++i) {
492 if (lock.tryLock() == NO_ERROR) {
493 gotLock = true;
494 break;
495 } else {
496 usleep(kDumpSleepDuration);
497 }
498 }
499 return gotLock;
500}
501
Shuzhen Wang83bff122020-11-20 15:51:39 -0800502camera3::Size Camera3Device::getMaxJpegResolution() const {
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700503 int32_t maxJpegWidth = 0, maxJpegHeight = 0;
Emilian Peev08dd2452017-04-06 16:55:14 +0100504 const int STREAM_CONFIGURATION_SIZE = 4;
505 const int STREAM_FORMAT_OFFSET = 0;
506 const int STREAM_WIDTH_OFFSET = 1;
507 const int STREAM_HEIGHT_OFFSET = 2;
508 const int STREAM_IS_INPUT_OFFSET = 3;
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -0800509 bool isHighResolutionSensor =
510 camera3::SessionConfigurationUtils::isUltraHighResolutionSensor(mDeviceInfo);
511 int32_t scalerSizesTag = isHighResolutionSensor ?
512 ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS_MAXIMUM_RESOLUTION :
513 ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS;
Emilian Peev08dd2452017-04-06 16:55:14 +0100514 camera_metadata_ro_entry_t availableStreamConfigs =
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -0800515 mDeviceInfo.find(scalerSizesTag);
Emilian Peev08dd2452017-04-06 16:55:14 +0100516 if (availableStreamConfigs.count == 0 ||
517 availableStreamConfigs.count % STREAM_CONFIGURATION_SIZE != 0) {
Shuzhen Wang83bff122020-11-20 15:51:39 -0800518 return camera3::Size(0, 0);
Emilian Peev08dd2452017-04-06 16:55:14 +0100519 }
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700520
Emilian Peev08dd2452017-04-06 16:55:14 +0100521 // Get max jpeg size (area-wise).
522 for (size_t i=0; i < availableStreamConfigs.count; i+= STREAM_CONFIGURATION_SIZE) {
523 int32_t format = availableStreamConfigs.data.i32[i + STREAM_FORMAT_OFFSET];
524 int32_t width = availableStreamConfigs.data.i32[i + STREAM_WIDTH_OFFSET];
525 int32_t height = availableStreamConfigs.data.i32[i + STREAM_HEIGHT_OFFSET];
526 int32_t isInput = availableStreamConfigs.data.i32[i + STREAM_IS_INPUT_OFFSET];
527 if (isInput == ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS_OUTPUT
528 && format == HAL_PIXEL_FORMAT_BLOB &&
529 (width * height > maxJpegWidth * maxJpegHeight)) {
530 maxJpegWidth = width;
531 maxJpegHeight = height;
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700532 }
533 }
Emilian Peev08dd2452017-04-06 16:55:14 +0100534
Shuzhen Wang83bff122020-11-20 15:51:39 -0800535 return camera3::Size(maxJpegWidth, maxJpegHeight);
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700536}
537
Shuzhen Wangc28dccc2016-02-11 23:48:46 -0800538nsecs_t Camera3Device::getMonoToBoottimeOffset() {
539 // try three times to get the clock offset, choose the one
540 // with the minimum gap in measurements.
541 const int tries = 3;
542 nsecs_t bestGap, measured;
543 for (int i = 0; i < tries; ++i) {
544 const nsecs_t tmono = systemTime(SYSTEM_TIME_MONOTONIC);
545 const nsecs_t tbase = systemTime(SYSTEM_TIME_BOOTTIME);
546 const nsecs_t tmono2 = systemTime(SYSTEM_TIME_MONOTONIC);
547 const nsecs_t gap = tmono2 - tmono;
548 if (i == 0 || gap < bestGap) {
549 bestGap = gap;
550 measured = tbase - ((tmono + tmono2) >> 1);
551 }
552 }
553 return measured;
554}
555
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800556hardware::graphics::common::V1_0::PixelFormat Camera3Device::mapToPixelFormat(
557 int frameworkFormat) {
558 return (hardware::graphics::common::V1_0::PixelFormat) frameworkFormat;
559}
560
561DataspaceFlags Camera3Device::mapToHidlDataspace(
562 android_dataspace dataSpace) {
563 return dataSpace;
564}
565
Chia-I Wu67a0c0e2017-04-06 13:37:01 -0700566BufferUsageFlags Camera3Device::mapToConsumerUsage(
Emilian Peev050f5dc2017-05-18 14:43:56 +0100567 uint64_t usage) {
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -0700568 return usage;
569}
570
Emilian Peevf4816702020-04-03 15:44:51 -0700571StreamRotation Camera3Device::mapToStreamRotation(camera_stream_rotation_t rotation) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800572 switch (rotation) {
Emilian Peevf4816702020-04-03 15:44:51 -0700573 case CAMERA_STREAM_ROTATION_0:
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800574 return StreamRotation::ROTATION_0;
Emilian Peevf4816702020-04-03 15:44:51 -0700575 case CAMERA_STREAM_ROTATION_90:
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800576 return StreamRotation::ROTATION_90;
Emilian Peevf4816702020-04-03 15:44:51 -0700577 case CAMERA_STREAM_ROTATION_180:
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800578 return StreamRotation::ROTATION_180;
Emilian Peevf4816702020-04-03 15:44:51 -0700579 case CAMERA_STREAM_ROTATION_270:
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800580 return StreamRotation::ROTATION_270;
581 }
582 ALOGE("%s: Unknown stream rotation %d", __FUNCTION__, rotation);
583 return StreamRotation::ROTATION_0;
584}
585
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800586status_t Camera3Device::mapToStreamConfigurationMode(
Emilian Peevf4816702020-04-03 15:44:51 -0700587 camera_stream_configuration_mode_t operationMode, StreamConfigurationMode *mode) {
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800588 if (mode == nullptr) return BAD_VALUE;
Emilian Peevf4816702020-04-03 15:44:51 -0700589 if (operationMode < CAMERA_VENDOR_STREAM_CONFIGURATION_MODE_START) {
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800590 switch(operationMode) {
Emilian Peevf4816702020-04-03 15:44:51 -0700591 case CAMERA_STREAM_CONFIGURATION_NORMAL_MODE:
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800592 *mode = StreamConfigurationMode::NORMAL_MODE;
593 break;
Emilian Peevf4816702020-04-03 15:44:51 -0700594 case CAMERA_STREAM_CONFIGURATION_CONSTRAINED_HIGH_SPEED_MODE:
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800595 *mode = StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE;
596 break;
597 default:
598 ALOGE("%s: Unknown stream configuration mode %d", __FUNCTION__, operationMode);
599 return BAD_VALUE;
600 }
601 } else {
602 *mode = static_cast<StreamConfigurationMode>(operationMode);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800603 }
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800604 return OK;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800605}
606
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800607int Camera3Device::mapToFrameworkFormat(
608 hardware::graphics::common::V1_0::PixelFormat pixelFormat) {
609 return static_cast<uint32_t>(pixelFormat);
610}
611
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -0700612android_dataspace Camera3Device::mapToFrameworkDataspace(
613 DataspaceFlags dataSpace) {
614 return static_cast<android_dataspace>(dataSpace);
615}
616
Emilian Peev050f5dc2017-05-18 14:43:56 +0100617uint64_t Camera3Device::mapConsumerToFrameworkUsage(
Chia-I Wu67a0c0e2017-04-06 13:37:01 -0700618 BufferUsageFlags usage) {
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -0700619 return usage;
620}
621
Emilian Peev050f5dc2017-05-18 14:43:56 +0100622uint64_t Camera3Device::mapProducerToFrameworkUsage(
Chia-I Wu67a0c0e2017-04-06 13:37:01 -0700623 BufferUsageFlags usage) {
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -0700624 return usage;
625}
626
Zhijun Hef7da0962014-04-24 13:27:56 -0700627ssize_t Camera3Device::getJpegBufferSize(uint32_t width, uint32_t height) const {
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700628 // Get max jpeg size (area-wise).
Shuzhen Wang83bff122020-11-20 15:51:39 -0800629 camera3::Size maxJpegResolution = getMaxJpegResolution();
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700630 if (maxJpegResolution.width == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800631 ALOGE("%s: Camera %s: Can't find valid available jpeg sizes in static metadata!",
632 __FUNCTION__, mId.string());
Zhijun Hef7da0962014-04-24 13:27:56 -0700633 return BAD_VALUE;
634 }
635
Zhijun Hef7da0962014-04-24 13:27:56 -0700636 // Get max jpeg buffer size
637 ssize_t maxJpegBufferSize = 0;
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700638 camera_metadata_ro_entry jpegBufMaxSize = mDeviceInfo.find(ANDROID_JPEG_MAX_SIZE);
639 if (jpegBufMaxSize.count == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800640 ALOGE("%s: Camera %s: Can't find maximum JPEG size in static metadata!", __FUNCTION__,
641 mId.string());
Zhijun Hef7da0962014-04-24 13:27:56 -0700642 return BAD_VALUE;
643 }
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700644 maxJpegBufferSize = jpegBufMaxSize.data.i32[0];
Yin-Chia Yeh0c4e56d2015-01-09 15:21:27 -0800645 assert(kMinJpegBufferSize < maxJpegBufferSize);
Zhijun Hef7da0962014-04-24 13:27:56 -0700646
647 // Calculate final jpeg buffer size for the given resolution.
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700648 float scaleFactor = ((float) (width * height)) /
649 (maxJpegResolution.width * maxJpegResolution.height);
Yin-Chia Yeh0c4e56d2015-01-09 15:21:27 -0800650 ssize_t jpegBufferSize = scaleFactor * (maxJpegBufferSize - kMinJpegBufferSize) +
651 kMinJpegBufferSize;
Zhijun Hef7da0962014-04-24 13:27:56 -0700652 if (jpegBufferSize > maxJpegBufferSize) {
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -0800653 ALOGI("%s: jpeg buffer size calculated is > maxJpeg bufferSize(%zd), clamping",
654 __FUNCTION__, maxJpegBufferSize);
Zhijun Hef7da0962014-04-24 13:27:56 -0700655 jpegBufferSize = maxJpegBufferSize;
Zhijun Hef7da0962014-04-24 13:27:56 -0700656 }
657
658 return jpegBufferSize;
659}
660
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700661ssize_t Camera3Device::getPointCloudBufferSize() const {
662 const int FLOATS_PER_POINT=4;
663 camera_metadata_ro_entry maxPointCount = mDeviceInfo.find(ANDROID_DEPTH_MAX_DEPTH_SAMPLES);
664 if (maxPointCount.count == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800665 ALOGE("%s: Camera %s: Can't find maximum depth point cloud size in static metadata!",
666 __FUNCTION__, mId.string());
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700667 return BAD_VALUE;
668 }
669 ssize_t maxBytesForPointCloud = sizeof(android_depth_points) +
670 maxPointCount.data.i32[0] * sizeof(float) * FLOATS_PER_POINT;
671 return maxBytesForPointCloud;
672}
673
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -0800674ssize_t Camera3Device::getRawOpaqueBufferSize(int32_t width, int32_t height,
675 bool maxResolution) const {
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800676 const int PER_CONFIGURATION_SIZE = 3;
677 const int WIDTH_OFFSET = 0;
678 const int HEIGHT_OFFSET = 1;
679 const int SIZE_OFFSET = 2;
680 camera_metadata_ro_entry rawOpaqueSizes =
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -0800681 mDeviceInfo.find(
682 camera3::SessionConfigurationUtils::getAppropriateModeTag(
683 ANDROID_SENSOR_OPAQUE_RAW_SIZE,
684 maxResolution));
Aurimas Liutikasbc57b122016-02-16 09:59:16 -0800685 size_t count = rawOpaqueSizes.count;
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800686 if (count == 0 || (count % PER_CONFIGURATION_SIZE)) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800687 ALOGE("%s: Camera %s: bad opaque RAW size static metadata length(%zu)!",
688 __FUNCTION__, mId.string(), count);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800689 return BAD_VALUE;
690 }
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700691
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800692 for (size_t i = 0; i < count; i += PER_CONFIGURATION_SIZE) {
693 if (width == rawOpaqueSizes.data.i32[i + WIDTH_OFFSET] &&
694 height == rawOpaqueSizes.data.i32[i + HEIGHT_OFFSET]) {
695 return rawOpaqueSizes.data.i32[i + SIZE_OFFSET];
696 }
697 }
698
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800699 ALOGE("%s: Camera %s: cannot find size for %dx%d opaque RAW image!",
700 __FUNCTION__, mId.string(), width, height);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800701 return BAD_VALUE;
702}
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700703
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800704status_t Camera3Device::dump(int fd, const Vector<String16> &args) {
705 ATRACE_CALL();
706 (void)args;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700707
708 // Try to lock, but continue in case of failure (to avoid blocking in
709 // deadlocks)
710 bool gotInterfaceLock = tryLockSpinRightRound(mInterfaceLock);
711 bool gotLock = tryLockSpinRightRound(mLock);
712
713 ALOGW_IF(!gotInterfaceLock,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800714 "Camera %s: %s: Unable to lock interface lock, proceeding anyway",
715 mId.string(), __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700716 ALOGW_IF(!gotLock,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800717 "Camera %s: %s: Unable to lock main lock, proceeding anyway",
718 mId.string(), __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700719
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800720 bool dumpTemplates = false;
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700721
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800722 String16 templatesOption("-t");
723 int n = args.size();
724 for (int i = 0; i < n; i++) {
725 if (args[i] == templatesOption) {
726 dumpTemplates = true;
727 }
Emilian Peevbd8c5032018-02-14 23:05:40 +0000728 if (args[i] == TagMonitor::kMonitorOption) {
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700729 if (i + 1 < n) {
730 String8 monitorTags = String8(args[i + 1]);
731 if (monitorTags == "off") {
732 mTagMonitor.disableMonitoring();
733 } else {
734 mTagMonitor.parseTagsToMonitor(monitorTags);
735 }
736 } else {
737 mTagMonitor.disableMonitoring();
738 }
739 }
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800740 }
741
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800742 String8 lines;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800743
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800744 const char *status =
745 mStatus == STATUS_ERROR ? "ERROR" :
746 mStatus == STATUS_UNINITIALIZED ? "UNINITIALIZED" :
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700747 mStatus == STATUS_UNCONFIGURED ? "UNCONFIGURED" :
748 mStatus == STATUS_CONFIGURED ? "CONFIGURED" :
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800749 mStatus == STATUS_ACTIVE ? "ACTIVE" :
750 "Unknown";
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700751
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800752 lines.appendFormat(" Device status: %s\n", status);
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700753 if (mStatus == STATUS_ERROR) {
754 lines.appendFormat(" Error cause: %s\n", mErrorCause.string());
755 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800756 lines.appendFormat(" Stream configuration:\n");
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800757 const char *mode =
758 mOperatingMode == static_cast<int>(StreamConfigurationMode::NORMAL_MODE) ? "NORMAL" :
759 mOperatingMode == static_cast<int>(
760 StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE) ? "CONSTRAINED_HIGH_SPEED" :
761 "CUSTOM";
762 lines.appendFormat(" Operation mode: %s (%d) \n", mode, mOperatingMode);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800763
764 if (mInputStream != NULL) {
765 write(fd, lines.string(), lines.size());
766 mInputStream->dump(fd, args);
767 } else {
768 lines.appendFormat(" No input stream.\n");
769 write(fd, lines.string(), lines.size());
770 }
771 for (size_t i = 0; i < mOutputStreams.size(); i++) {
772 mOutputStreams[i]->dump(fd,args);
773 }
774
Zhijun He431503c2016-03-07 17:30:16 -0800775 if (mBufferManager != NULL) {
776 lines = String8(" Camera3 Buffer Manager:\n");
777 write(fd, lines.string(), lines.size());
778 mBufferManager->dump(fd, args);
779 }
Zhijun He125684a2015-12-26 15:07:30 -0800780
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700781 lines = String8(" In-flight requests:\n");
Emilian Peeva6138c52021-06-24 12:52:38 -0700782 if (mInFlightLock.try_lock()) {
783 if (mInFlightMap.size() == 0) {
784 lines.append(" None\n");
785 } else {
786 for (size_t i = 0; i < mInFlightMap.size(); i++) {
787 InFlightRequest r = mInFlightMap.valueAt(i);
788 lines.appendFormat(" Frame %d | Timestamp: %" PRId64 ", metadata"
789 " arrived: %s, buffers left: %d\n", mInFlightMap.keyAt(i),
790 r.shutterTimestamp, r.haveResultMetadata ? "true" : "false",
791 r.numBuffersLeft);
792 }
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700793 }
Emilian Peeva6138c52021-06-24 12:52:38 -0700794 mInFlightLock.unlock();
795 } else {
796 lines.append(" Failed to acquire In-flight lock!\n");
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700797 }
798 write(fd, lines.string(), lines.size());
799
Shuzhen Wang686f6442017-06-20 16:16:04 -0700800 if (mRequestThread != NULL) {
801 mRequestThread->dumpCaptureRequestLatency(fd,
802 " ProcessCaptureRequest latency histogram:");
803 }
804
Igor Murashkin1e479c02013-09-06 16:55:14 -0700805 {
806 lines = String8(" Last request sent:\n");
807 write(fd, lines.string(), lines.size());
808
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700809 CameraMetadata lastRequest = getLatestRequestLocked();
Igor Murashkin1e479c02013-09-06 16:55:14 -0700810 lastRequest.dump(fd, /*verbosity*/2, /*indentation*/6);
811 }
812
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800813 if (dumpTemplates) {
Emilian Peevf4816702020-04-03 15:44:51 -0700814 const char *templateNames[CAMERA_TEMPLATE_COUNT] = {
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800815 "TEMPLATE_PREVIEW",
816 "TEMPLATE_STILL_CAPTURE",
817 "TEMPLATE_VIDEO_RECORD",
818 "TEMPLATE_VIDEO_SNAPSHOT",
819 "TEMPLATE_ZERO_SHUTTER_LAG",
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -0800820 "TEMPLATE_MANUAL",
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800821 };
822
Emilian Peevf4816702020-04-03 15:44:51 -0700823 for (int i = 1; i < CAMERA_TEMPLATE_COUNT; i++) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800824 camera_metadata_t *templateRequest = nullptr;
825 mInterface->constructDefaultRequestSettings(
Emilian Peevf4816702020-04-03 15:44:51 -0700826 (camera_request_template_t) i, &templateRequest);
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800827 lines = String8::format(" HAL Request %s:\n", templateNames[i-1]);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800828 if (templateRequest == nullptr) {
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800829 lines.append(" Not supported\n");
830 write(fd, lines.string(), lines.size());
831 } else {
832 write(fd, lines.string(), lines.size());
833 dump_indented_camera_metadata(templateRequest,
834 fd, /*verbosity*/2, /*indentation*/8);
835 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800836 free_camera_metadata(templateRequest);
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800837 }
838 }
839
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700840 mTagMonitor.dumpMonitoredMetadata(fd);
841
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800842 if (mInterface->valid()) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -0800843 lines = String8(" HAL device dump:\n");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800844 write(fd, lines.string(), lines.size());
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800845 mInterface->dump(fd);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800846 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800847
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700848 if (gotLock) mLock.unlock();
849 if (gotInterfaceLock) mInterfaceLock.unlock();
850
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800851 return OK;
852}
853
Emilian Peevfaa4bde2020-01-23 12:19:37 -0800854const CameraMetadata& Camera3Device::infoPhysical(const String8& physicalId) const {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800855 ALOGVV("%s: E", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800856 if (CC_UNLIKELY(mStatus == STATUS_UNINITIALIZED ||
857 mStatus == STATUS_ERROR)) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700858 ALOGW("%s: Access to static info %s!", __FUNCTION__,
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800859 mStatus == STATUS_ERROR ?
860 "when in error state" : "before init");
861 }
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700862 if (physicalId.isEmpty()) {
863 return mDeviceInfo;
864 } else {
865 std::string id(physicalId.c_str());
866 if (mPhysicalDeviceInfoMap.find(id) != mPhysicalDeviceInfoMap.end()) {
867 return mPhysicalDeviceInfoMap.at(id);
868 } else {
869 ALOGE("%s: Invalid physical camera id %s", __FUNCTION__, physicalId.c_str());
870 return mDeviceInfo;
871 }
872 }
873}
874
875const CameraMetadata& Camera3Device::info() const {
876 String8 emptyId;
Emilian Peevfaa4bde2020-01-23 12:19:37 -0800877 return infoPhysical(emptyId);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800878}
879
Jianing Wei90e59c92014-03-12 18:29:36 -0700880status_t Camera3Device::checkStatusOkToCaptureLocked() {
881 switch (mStatus) {
882 case STATUS_ERROR:
883 CLOGE("Device has encountered a serious error");
884 return INVALID_OPERATION;
885 case STATUS_UNINITIALIZED:
886 CLOGE("Device not initialized");
887 return INVALID_OPERATION;
888 case STATUS_UNCONFIGURED:
889 case STATUS_CONFIGURED:
890 case STATUS_ACTIVE:
891 // OK
892 break;
893 default:
894 SET_ERR_L("Unexpected status: %d", mStatus);
895 return INVALID_OPERATION;
896 }
897 return OK;
898}
899
900status_t Camera3Device::convertMetadataListToRequestListLocked(
Emilian Peevaebbe412018-01-15 13:53:24 +0000901 const List<const PhysicalCameraSettingsList> &metadataList,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700902 const std::list<const SurfaceMap> &surfaceMaps,
Shuzhen Wang316781a2020-08-18 18:11:01 -0700903 bool repeating, nsecs_t requestTimeNs,
Shuzhen Wang9d066012016-09-30 11:30:20 -0700904 RequestList *requestList) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700905 if (requestList == NULL) {
906 CLOGE("requestList cannot be NULL.");
907 return BAD_VALUE;
908 }
909
Jianing Weicb0652e2014-03-12 18:29:36 -0700910 int32_t burstId = 0;
Emilian Peevaebbe412018-01-15 13:53:24 +0000911 List<const PhysicalCameraSettingsList>::const_iterator metadataIt = metadataList.begin();
Shuzhen Wang0129d522016-10-30 22:43:41 -0700912 std::list<const SurfaceMap>::const_iterator surfaceMapIt = surfaceMaps.begin();
913 for (; metadataIt != metadataList.end() && surfaceMapIt != surfaceMaps.end();
914 ++metadataIt, ++surfaceMapIt) {
915 sp<CaptureRequest> newRequest = setUpRequestLocked(*metadataIt, *surfaceMapIt);
Jianing Wei90e59c92014-03-12 18:29:36 -0700916 if (newRequest == 0) {
917 CLOGE("Can't create capture request");
918 return BAD_VALUE;
919 }
Jianing Weicb0652e2014-03-12 18:29:36 -0700920
Shuzhen Wang9d066012016-09-30 11:30:20 -0700921 newRequest->mRepeating = repeating;
Shuzhen Wang316781a2020-08-18 18:11:01 -0700922 newRequest->mRequestTimeNs = requestTimeNs;
Shuzhen Wang9d066012016-09-30 11:30:20 -0700923
Jianing Weicb0652e2014-03-12 18:29:36 -0700924 // Setup burst Id and request Id
925 newRequest->mResultExtras.burstId = burstId++;
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -0800926 auto requestIdEntry = metadataIt->begin()->metadata.find(ANDROID_REQUEST_ID);
927 if (requestIdEntry.count == 0) {
Jianing Weicb0652e2014-03-12 18:29:36 -0700928 CLOGE("RequestID does not exist in metadata");
929 return BAD_VALUE;
930 }
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -0800931 newRequest->mResultExtras.requestId = requestIdEntry.data.i32[0];
Jianing Weicb0652e2014-03-12 18:29:36 -0700932
Jianing Wei90e59c92014-03-12 18:29:36 -0700933 requestList->push_back(newRequest);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700934
935 ALOGV("%s: requestId = %" PRId32, __FUNCTION__, newRequest->mResultExtras.requestId);
Jianing Wei90e59c92014-03-12 18:29:36 -0700936 }
Shuzhen Wang0129d522016-10-30 22:43:41 -0700937 if (metadataIt != metadataList.end() || surfaceMapIt != surfaceMaps.end()) {
938 ALOGE("%s: metadataList and surfaceMaps are not the same size!", __FUNCTION__);
939 return BAD_VALUE;
940 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -0700941
942 // Setup batch size if this is a high speed video recording request.
943 if (mIsConstrainedHighSpeedConfiguration && requestList->size() > 0) {
944 auto firstRequest = requestList->begin();
945 for (auto& outputStream : (*firstRequest)->mOutputStreams) {
946 if (outputStream->isVideoStream()) {
947 (*firstRequest)->mBatchSize = requestList->size();
Yin-Chia Yeh14ef48d2020-02-10 15:06:37 -0800948 outputStream->setBatchSize(requestList->size());
Chien-Yu Chen85a64552015-08-28 15:46:12 -0700949 break;
950 }
951 }
952 }
953
Jianing Wei90e59c92014-03-12 18:29:36 -0700954 return OK;
955}
956
Yin-Chia Yeh7e5a2042019-02-06 16:01:06 -0800957status_t Camera3Device::capture(CameraMetadata &request, int64_t* lastFrameNumber) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800958 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800959
Emilian Peevaebbe412018-01-15 13:53:24 +0000960 List<const PhysicalCameraSettingsList> requestsList;
Shuzhen Wang0129d522016-10-30 22:43:41 -0700961 std::list<const SurfaceMap> surfaceMaps;
Emilian Peevaebbe412018-01-15 13:53:24 +0000962 convertToRequestList(requestsList, surfaceMaps, request);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700963
Yin-Chia Yeh7e5a2042019-02-06 16:01:06 -0800964 return captureList(requestsList, surfaceMaps, lastFrameNumber);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700965}
966
Emilian Peevaebbe412018-01-15 13:53:24 +0000967void Camera3Device::convertToRequestList(List<const PhysicalCameraSettingsList>& requestsList,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700968 std::list<const SurfaceMap>& surfaceMaps,
969 const CameraMetadata& request) {
Emilian Peevaebbe412018-01-15 13:53:24 +0000970 PhysicalCameraSettingsList requestList;
971 requestList.push_back({std::string(getId().string()), request});
972 requestsList.push_back(requestList);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700973
974 SurfaceMap surfaceMap;
975 camera_metadata_ro_entry streams = request.find(ANDROID_REQUEST_OUTPUT_STREAMS);
976 // With no surface list passed in, stream and surface will have 1-to-1
977 // mapping. So the surface index is 0 for each stream in the surfaceMap.
978 for (size_t i = 0; i < streams.count; i++) {
979 surfaceMap[streams.data.i32[i]].push_back(0);
980 }
981 surfaceMaps.push_back(surfaceMap);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800982}
983
Jianing Wei90e59c92014-03-12 18:29:36 -0700984status_t Camera3Device::submitRequestsHelper(
Emilian Peevaebbe412018-01-15 13:53:24 +0000985 const List<const PhysicalCameraSettingsList> &requests,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700986 const std::list<const SurfaceMap> &surfaceMaps,
987 bool repeating,
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700988 /*out*/
989 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700990 ATRACE_CALL();
Shuzhen Wang316781a2020-08-18 18:11:01 -0700991 nsecs_t requestTimeNs = systemTime();
992
Jianing Wei90e59c92014-03-12 18:29:36 -0700993 Mutex::Autolock il(mInterfaceLock);
994 Mutex::Autolock l(mLock);
995
996 status_t res = checkStatusOkToCaptureLocked();
997 if (res != OK) {
998 // error logged by previous call
999 return res;
1000 }
1001
1002 RequestList requestList;
1003
Shuzhen Wang0129d522016-10-30 22:43:41 -07001004 res = convertMetadataListToRequestListLocked(requests, surfaceMaps,
Shuzhen Wang316781a2020-08-18 18:11:01 -07001005 repeating, requestTimeNs, /*out*/&requestList);
Jianing Wei90e59c92014-03-12 18:29:36 -07001006 if (res != OK) {
1007 // error logged by previous call
1008 return res;
1009 }
1010
1011 if (repeating) {
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07001012 res = mRequestThread->setRepeatingRequests(requestList, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -07001013 } else {
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07001014 res = mRequestThread->queueRequestList(requestList, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -07001015 }
1016
1017 if (res == OK) {
1018 waitUntilStateThenRelock(/*active*/true, kActiveTimeout);
1019 if (res != OK) {
1020 SET_ERR_L("Can't transition to active in %f seconds!",
1021 kActiveTimeout/1e9);
1022 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001023 ALOGV("Camera %s: Capture request %" PRId32 " enqueued", mId.string(),
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07001024 (*(requestList.begin()))->mResultExtras.requestId);
Jianing Wei90e59c92014-03-12 18:29:36 -07001025 } else {
1026 CLOGE("Cannot queue request. Impossible.");
1027 return BAD_VALUE;
1028 }
1029
1030 return res;
1031}
1032
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001033hardware::Return<void> Camera3Device::requestStreamBuffers(
1034 const hardware::hidl_vec<hardware::camera::device::V3_5::BufferRequest>& bufReqs,
1035 requestStreamBuffers_cb _hidl_cb) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001036 RequestBufferStates states {
Shuzhen Wang316781a2020-08-18 18:11:01 -07001037 mId, mRequestBufferInterfaceLock, mUseHalBufManager, mOutputStreams, mSessionStatsBuilder,
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001038 *this, *mInterface, *this};
1039 camera3::requestStreamBuffers(states, bufReqs, _hidl_cb);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001040 return hardware::Void();
1041}
1042
1043hardware::Return<void> Camera3Device::returnStreamBuffers(
1044 const hardware::hidl_vec<hardware::camera::device::V3_2::StreamBuffer>& buffers) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001045 ReturnBufferStates states {
Shuzhen Wang316781a2020-08-18 18:11:01 -07001046 mId, mUseHalBufManager, mOutputStreams, mSessionStatsBuilder, *mInterface};
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001047 camera3::returnStreamBuffers(states, buffers);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001048 return hardware::Void();
1049}
1050
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001051hardware::Return<void> Camera3Device::processCaptureResult_3_4(
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001052 const hardware::hidl_vec<
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001053 hardware::camera::device::V3_4::CaptureResult>& results) {
Yin-Chia Yeh657c1872017-07-18 18:09:57 -07001054 // Ideally we should grab mLock, but that can lead to deadlock, and
1055 // it's not super important to get up to date value of mStatus for this
1056 // warning print, hence skipping the lock here
1057 if (mStatus == STATUS_ERROR) {
1058 // Per API contract, HAL should act as closed after device error
1059 // But mStatus can be set to error by framework as well, so just log
1060 // a warning here.
1061 ALOGW("%s: received capture result in error state.", __FUNCTION__);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07001062 }
Yifan Honga640c5a2017-04-12 16:30:31 -07001063
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001064 sp<NotificationListener> listener;
1065 {
1066 std::lock_guard<std::mutex> l(mOutputLock);
1067 listener = mListener.promote();
1068 }
1069
Yifan Honga640c5a2017-04-12 16:30:31 -07001070 if (mProcessCaptureResultLock.tryLock() != OK) {
1071 // This should never happen; it indicates a wrong client implementation
1072 // that doesn't follow the contract. But, we can be tolerant here.
1073 ALOGE("%s: callback overlapped! waiting 1s...",
1074 __FUNCTION__);
1075 if (mProcessCaptureResultLock.timedLock(1000000000 /* 1s */) != OK) {
1076 ALOGE("%s: cannot acquire lock in 1s, dropping results",
1077 __FUNCTION__);
1078 // really don't know what to do, so bail out.
1079 return hardware::Void();
1080 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001081 }
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001082 CaptureOutputStates states {
1083 mId,
Shuzhen Wangb7b42652020-05-07 11:59:02 -07001084 mInFlightLock, mLastCompletedRegularFrameNumber,
1085 mLastCompletedReprocessFrameNumber, mLastCompletedZslFrameNumber,
1086 mInFlightMap, mOutputLock, mResultQueue, mResultSignal,
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001087 mNextShutterFrameNumber,
1088 mNextReprocessShutterFrameNumber, mNextZslStillShutterFrameNumber,
1089 mNextResultFrameNumber,
1090 mNextReprocessResultFrameNumber, mNextZslStillResultFrameNumber,
1091 mUseHalBufManager, mUsePartialResult, mNeedFixupMonochromeTags,
1092 mNumPartialResults, mVendorTagId, mDeviceInfo, mPhysicalDeviceInfoMap,
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08001093 mResultMetadataQueue, mDistortionMappers, mZoomRatioMappers, mRotateAndCropMappers,
Shuzhen Wang316781a2020-08-18 18:11:01 -07001094 mTagMonitor, mInputStream, mOutputStreams, mSessionStatsBuilder, listener, *this, *this,
1095 *mInterface
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001096 };
1097
Yifan Honga640c5a2017-04-12 16:30:31 -07001098 for (const auto& result : results) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001099 processOneCaptureResultLocked(states, result.v3_2, result.physicalCameraMetadata);
Yifan Honga640c5a2017-04-12 16:30:31 -07001100 }
1101 mProcessCaptureResultLock.unlock();
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001102 return hardware::Void();
1103}
1104
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001105// Only one processCaptureResult should be called at a time, so
1106// the locks won't block. The locks are present here simply to enforce this.
1107hardware::Return<void> Camera3Device::processCaptureResult(
1108 const hardware::hidl_vec<
1109 hardware::camera::device::V3_2::CaptureResult>& results) {
1110 hardware::hidl_vec<hardware::camera::device::V3_4::PhysicalCameraMetadata> noPhysMetadata;
1111
1112 // Ideally we should grab mLock, but that can lead to deadlock, and
1113 // it's not super important to get up to date value of mStatus for this
1114 // warning print, hence skipping the lock here
1115 if (mStatus == STATUS_ERROR) {
1116 // Per API contract, HAL should act as closed after device error
1117 // But mStatus can be set to error by framework as well, so just log
1118 // a warning here.
1119 ALOGW("%s: received capture result in error state.", __FUNCTION__);
1120 }
1121
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001122 sp<NotificationListener> listener;
1123 {
1124 std::lock_guard<std::mutex> l(mOutputLock);
1125 listener = mListener.promote();
1126 }
1127
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001128 if (mProcessCaptureResultLock.tryLock() != OK) {
1129 // This should never happen; it indicates a wrong client implementation
1130 // that doesn't follow the contract. But, we can be tolerant here.
1131 ALOGE("%s: callback overlapped! waiting 1s...",
1132 __FUNCTION__);
1133 if (mProcessCaptureResultLock.timedLock(1000000000 /* 1s */) != OK) {
1134 ALOGE("%s: cannot acquire lock in 1s, dropping results",
1135 __FUNCTION__);
1136 // really don't know what to do, so bail out.
1137 return hardware::Void();
1138 }
1139 }
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001140
1141 CaptureOutputStates states {
1142 mId,
Shuzhen Wangb7b42652020-05-07 11:59:02 -07001143 mInFlightLock, mLastCompletedRegularFrameNumber,
1144 mLastCompletedReprocessFrameNumber, mLastCompletedZslFrameNumber,
1145 mInFlightMap, mOutputLock, mResultQueue, mResultSignal,
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001146 mNextShutterFrameNumber,
1147 mNextReprocessShutterFrameNumber, mNextZslStillShutterFrameNumber,
1148 mNextResultFrameNumber,
1149 mNextReprocessResultFrameNumber, mNextZslStillResultFrameNumber,
1150 mUseHalBufManager, mUsePartialResult, mNeedFixupMonochromeTags,
1151 mNumPartialResults, mVendorTagId, mDeviceInfo, mPhysicalDeviceInfoMap,
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08001152 mResultMetadataQueue, mDistortionMappers, mZoomRatioMappers, mRotateAndCropMappers,
Shuzhen Wang316781a2020-08-18 18:11:01 -07001153 mTagMonitor, mInputStream, mOutputStreams, mSessionStatsBuilder, listener, *this, *this,
1154 *mInterface
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001155 };
1156
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001157 for (const auto& result : results) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001158 processOneCaptureResultLocked(states, result, noPhysMetadata);
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001159 }
1160 mProcessCaptureResultLock.unlock();
1161 return hardware::Void();
1162}
1163
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001164hardware::Return<void> Camera3Device::notify(
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001165 const hardware::hidl_vec<hardware::camera::device::V3_2::NotifyMsg>& msgs) {
Yin-Chia Yeh657c1872017-07-18 18:09:57 -07001166 // Ideally we should grab mLock, but that can lead to deadlock, and
1167 // it's not super important to get up to date value of mStatus for this
1168 // warning print, hence skipping the lock here
1169 if (mStatus == STATUS_ERROR) {
1170 // Per API contract, HAL should act as closed after device error
1171 // But mStatus can be set to error by framework as well, so just log
1172 // a warning here.
1173 ALOGW("%s: received notify message in error state.", __FUNCTION__);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07001174 }
Yin-Chia Yeh657c1872017-07-18 18:09:57 -07001175
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001176 sp<NotificationListener> listener;
1177 {
1178 std::lock_guard<std::mutex> l(mOutputLock);
1179 listener = mListener.promote();
1180 }
1181
1182 CaptureOutputStates states {
1183 mId,
Shuzhen Wangb7b42652020-05-07 11:59:02 -07001184 mInFlightLock, mLastCompletedRegularFrameNumber,
1185 mLastCompletedReprocessFrameNumber, mLastCompletedZslFrameNumber,
1186 mInFlightMap, mOutputLock, mResultQueue, mResultSignal,
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001187 mNextShutterFrameNumber,
1188 mNextReprocessShutterFrameNumber, mNextZslStillShutterFrameNumber,
1189 mNextResultFrameNumber,
1190 mNextReprocessResultFrameNumber, mNextZslStillResultFrameNumber,
1191 mUseHalBufManager, mUsePartialResult, mNeedFixupMonochromeTags,
1192 mNumPartialResults, mVendorTagId, mDeviceInfo, mPhysicalDeviceInfoMap,
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08001193 mResultMetadataQueue, mDistortionMappers, mZoomRatioMappers, mRotateAndCropMappers,
Shuzhen Wang316781a2020-08-18 18:11:01 -07001194 mTagMonitor, mInputStream, mOutputStreams, mSessionStatsBuilder, listener, *this, *this,
1195 *mInterface
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001196 };
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001197 for (const auto& msg : msgs) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001198 camera3::notify(states, msg);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001199 }
1200 return hardware::Void();
1201}
1202
Emilian Peevaebbe412018-01-15 13:53:24 +00001203status_t Camera3Device::captureList(const List<const PhysicalCameraSettingsList> &requestsList,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001204 const std::list<const SurfaceMap> &surfaceMaps,
Jianing Weicb0652e2014-03-12 18:29:36 -07001205 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -07001206 ATRACE_CALL();
1207
Emilian Peevaebbe412018-01-15 13:53:24 +00001208 return submitRequestsHelper(requestsList, surfaceMaps, /*repeating*/false, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -07001209}
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001210
Jianing Weicb0652e2014-03-12 18:29:36 -07001211status_t Camera3Device::setStreamingRequest(const CameraMetadata &request,
1212 int64_t* /*lastFrameNumber*/) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001213 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001214
Emilian Peevaebbe412018-01-15 13:53:24 +00001215 List<const PhysicalCameraSettingsList> requestsList;
Shuzhen Wang0129d522016-10-30 22:43:41 -07001216 std::list<const SurfaceMap> surfaceMaps;
Emilian Peevaebbe412018-01-15 13:53:24 +00001217 convertToRequestList(requestsList, surfaceMaps, request);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001218
Emilian Peevaebbe412018-01-15 13:53:24 +00001219 return setStreamingRequestList(requestsList, /*surfaceMap*/surfaceMaps,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001220 /*lastFrameNumber*/NULL);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001221}
1222
Emilian Peevaebbe412018-01-15 13:53:24 +00001223status_t Camera3Device::setStreamingRequestList(
1224 const List<const PhysicalCameraSettingsList> &requestsList,
1225 const std::list<const SurfaceMap> &surfaceMaps, int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -07001226 ATRACE_CALL();
1227
Emilian Peevaebbe412018-01-15 13:53:24 +00001228 return submitRequestsHelper(requestsList, surfaceMaps, /*repeating*/true, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -07001229}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001230
1231sp<Camera3Device::CaptureRequest> Camera3Device::setUpRequestLocked(
Emilian Peevaebbe412018-01-15 13:53:24 +00001232 const PhysicalCameraSettingsList &request, const SurfaceMap &surfaceMap) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001233 status_t res;
1234
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001235 if (mStatus == STATUS_UNCONFIGURED || mNeedConfig) {
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08001236 // This point should only be reached via API1 (API2 must explicitly call configureStreams)
1237 // so unilaterally select normal operating mode.
Emilian Peevaebbe412018-01-15 13:53:24 +00001238 res = filterParamsAndConfigureLocked(request.begin()->metadata,
Emilian Peevf4816702020-04-03 15:44:51 -07001239 CAMERA_STREAM_CONFIGURATION_NORMAL_MODE);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001240 // Stream configuration failed. Client might try other configuraitons.
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001241 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001242 CLOGE("Can't set up streams: %s (%d)", strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001243 return NULL;
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001244 } else if (mStatus == STATUS_UNCONFIGURED) {
1245 // Stream configuration successfully configure to empty stream configuration.
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001246 CLOGE("No streams configured");
1247 return NULL;
1248 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001249 }
1250
Shuzhen Wang0129d522016-10-30 22:43:41 -07001251 sp<CaptureRequest> newRequest = createCaptureRequest(request, surfaceMap);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001252 return newRequest;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001253}
1254
Jianing Weicb0652e2014-03-12 18:29:36 -07001255status_t Camera3Device::clearStreamingRequest(int64_t *lastFrameNumber) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001256 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001257 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001258 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001259
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001260 switch (mStatus) {
1261 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001262 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001263 return INVALID_OPERATION;
1264 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001265 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001266 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001267 case STATUS_UNCONFIGURED:
1268 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001269 case STATUS_ACTIVE:
1270 // OK
1271 break;
1272 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001273 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001274 return INVALID_OPERATION;
1275 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001276 ALOGV("Camera %s: Clearing repeating request", mId.string());
Jianing Weicb0652e2014-03-12 18:29:36 -07001277
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07001278 return mRequestThread->clearRepeatingRequests(lastFrameNumber);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001279}
1280
1281status_t Camera3Device::waitUntilRequestReceived(int32_t requestId, nsecs_t timeout) {
1282 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001283 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001284
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001285 return mRequestThread->waitUntilRequestProcessed(requestId, timeout);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001286}
1287
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001288status_t Camera3Device::createInputStream(
Shuzhen Wang83bff122020-11-20 15:51:39 -08001289 uint32_t width, uint32_t height, int format, bool isMultiResolution, int *id) {
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001290 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001291 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001292 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001293 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001294 ALOGV("Camera %s: Creating new input stream %d: %d x %d, format %d",
1295 mId.string(), mNextStreamId, width, height, format);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001296
1297 status_t res;
1298 bool wasActive = false;
1299
1300 switch (mStatus) {
1301 case STATUS_ERROR:
1302 ALOGE("%s: Device has encountered a serious error", __FUNCTION__);
1303 return INVALID_OPERATION;
1304 case STATUS_UNINITIALIZED:
1305 ALOGE("%s: Device not initialized", __FUNCTION__);
1306 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001307 case STATUS_UNCONFIGURED:
1308 case STATUS_CONFIGURED:
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001309 // OK
1310 break;
1311 case STATUS_ACTIVE:
1312 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001313 res = internalPauseAndWaitLocked(maxExpectedDuration);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001314 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001315 SET_ERR_L("Can't pause captures to reconfigure streams!");
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001316 return res;
1317 }
1318 wasActive = true;
1319 break;
1320 default:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001321 SET_ERR_L("%s: Unexpected status: %d", mStatus);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001322 return INVALID_OPERATION;
1323 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001324 assert(mStatus != STATUS_ACTIVE);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001325
1326 if (mInputStream != 0) {
1327 ALOGE("%s: Cannot create more than 1 input stream", __FUNCTION__);
1328 return INVALID_OPERATION;
1329 }
1330
1331 sp<Camera3InputStream> newStream = new Camera3InputStream(mNextStreamId,
1332 width, height, format);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001333 newStream->setStatusTracker(mStatusTracker);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001334
1335 mInputStream = newStream;
Shuzhen Wang83bff122020-11-20 15:51:39 -08001336 mIsInputStreamMultiResolution = isMultiResolution;
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001337
1338 *id = mNextStreamId++;
1339
1340 // Continue captures if active at start
1341 if (wasActive) {
1342 ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001343 // Reuse current operating mode and session parameters for new stream config
1344 res = configureStreamsLocked(mOperatingMode, mSessionParams);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001345 if (res != OK) {
1346 ALOGE("%s: Can't reconfigure device for new stream %d: %s (%d)",
1347 __FUNCTION__, mNextStreamId, strerror(-res), res);
1348 return res;
1349 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001350 internalResumeLocked();
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001351 }
1352
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001353 ALOGV("Camera %s: Created input stream", mId.string());
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001354 return OK;
1355}
1356
Eino-Ville Talvala727d1722015-06-09 13:44:19 -07001357status_t Camera3Device::createStream(sp<Surface> consumer,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001358 uint32_t width, uint32_t height, int format,
Emilian Peevf4816702020-04-03 15:44:51 -07001359 android_dataspace dataSpace, camera_stream_rotation_t rotation, int *id,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001360 const String8& physicalCameraId,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001361 const std::unordered_set<int32_t> &sensorPixelModesUsed,
1362 std::vector<int> *surfaceIds, int streamSetId, bool isShared, bool isMultiResolution,
1363 uint64_t consumerUsage) {
Shuzhen Wang0129d522016-10-30 22:43:41 -07001364 ATRACE_CALL();
1365
1366 if (consumer == nullptr) {
1367 ALOGE("%s: consumer must not be null", __FUNCTION__);
1368 return BAD_VALUE;
1369 }
1370
1371 std::vector<sp<Surface>> consumers;
1372 consumers.push_back(consumer);
1373
1374 return createStream(consumers, /*hasDeferredConsumer*/ false, width, height,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001375 format, dataSpace, rotation, id, physicalCameraId, sensorPixelModesUsed, surfaceIds,
1376 streamSetId, isShared, isMultiResolution, consumerUsage);
1377}
1378
1379static bool isRawFormat(int format) {
1380 switch (format) {
1381 case HAL_PIXEL_FORMAT_RAW16:
1382 case HAL_PIXEL_FORMAT_RAW12:
1383 case HAL_PIXEL_FORMAT_RAW10:
1384 case HAL_PIXEL_FORMAT_RAW_OPAQUE:
1385 return true;
1386 default:
1387 return false;
1388 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001389}
1390
1391status_t Camera3Device::createStream(const std::vector<sp<Surface>>& consumers,
1392 bool hasDeferredConsumer, uint32_t width, uint32_t height, int format,
Emilian Peevf4816702020-04-03 15:44:51 -07001393 android_dataspace dataSpace, camera_stream_rotation_t rotation, int *id,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001394 const String8& physicalCameraId, const std::unordered_set<int32_t> &sensorPixelModesUsed,
Shuzhen Wang83bff122020-11-20 15:51:39 -08001395 std::vector<int> *surfaceIds, int streamSetId, bool isShared, bool isMultiResolution,
1396 uint64_t consumerUsage) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001397 ATRACE_CALL();
Emilian Peev40ead602017-09-26 15:46:36 +01001398
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001399 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001400 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001401 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001402 ALOGV("Camera %s: Creating new stream %d: %d x %d, format %d, dataspace %d rotation %d"
Shuzhen Wang83bff122020-11-20 15:51:39 -08001403 " consumer usage %" PRIu64 ", isShared %d, physicalCameraId %s, isMultiResolution %d",
1404 mId.string(), mNextStreamId, width, height, format, dataSpace, rotation,
1405 consumerUsage, isShared, physicalCameraId.string(), isMultiResolution);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001406
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001407 status_t res;
1408 bool wasActive = false;
1409
1410 switch (mStatus) {
1411 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001412 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001413 return INVALID_OPERATION;
1414 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001415 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001416 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001417 case STATUS_UNCONFIGURED:
1418 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001419 // OK
1420 break;
1421 case STATUS_ACTIVE:
1422 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001423 res = internalPauseAndWaitLocked(maxExpectedDuration);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001424 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001425 SET_ERR_L("Can't pause captures to reconfigure streams!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001426 return res;
1427 }
1428 wasActive = true;
1429 break;
1430 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001431 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001432 return INVALID_OPERATION;
1433 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001434 assert(mStatus != STATUS_ACTIVE);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001435
1436 sp<Camera3OutputStream> newStream;
Zhijun He5d677d12016-05-29 16:52:39 -07001437
Shuzhen Wang0129d522016-10-30 22:43:41 -07001438 if (consumers.size() == 0 && !hasDeferredConsumer) {
1439 ALOGE("%s: Number of consumers cannot be smaller than 1", __FUNCTION__);
1440 return BAD_VALUE;
1441 }
Zhijun He5d677d12016-05-29 16:52:39 -07001442
Shuzhen Wang0129d522016-10-30 22:43:41 -07001443 if (hasDeferredConsumer && format != HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
Zhijun He5d677d12016-05-29 16:52:39 -07001444 ALOGE("Deferred consumer stream creation only support IMPLEMENTATION_DEFINED format");
1445 return BAD_VALUE;
1446 }
1447
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001448 if (isRawFormat(format) && sensorPixelModesUsed.size() > 1) {
1449 // We can't use one stream with a raw format in both sensor pixel modes since its going to
1450 // be found in only one sensor pixel mode.
1451 ALOGE("%s: RAW opaque stream cannot be used with > 1 sensor pixel modes", __FUNCTION__);
1452 return BAD_VALUE;
1453 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001454 if (format == HAL_PIXEL_FORMAT_BLOB) {
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -07001455 ssize_t blobBufferSize;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001456 if (dataSpace == HAL_DATASPACE_DEPTH) {
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -07001457 blobBufferSize = getPointCloudBufferSize();
1458 if (blobBufferSize <= 0) {
1459 SET_ERR_L("Invalid point cloud buffer size %zd", blobBufferSize);
1460 return BAD_VALUE;
1461 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001462 } else if (dataSpace == static_cast<android_dataspace>(HAL_DATASPACE_JPEG_APP_SEGMENTS)) {
1463 blobBufferSize = width * height;
1464 } else {
1465 blobBufferSize = getJpegBufferSize(width, height);
1466 if (blobBufferSize <= 0) {
1467 SET_ERR_L("Invalid jpeg buffer size %zd", blobBufferSize);
1468 return BAD_VALUE;
1469 }
Zhijun Hef7da0962014-04-24 13:27:56 -07001470 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001471 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001472 width, height, blobBufferSize, format, dataSpace, rotation,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001473 mTimestampOffset, physicalCameraId, sensorPixelModesUsed, streamSetId,
1474 isMultiResolution);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -08001475 } else if (format == HAL_PIXEL_FORMAT_RAW_OPAQUE) {
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001476 bool maxResolution =
1477 sensorPixelModesUsed.find(ANDROID_SENSOR_PIXEL_MODE_MAXIMUM_RESOLUTION) !=
1478 sensorPixelModesUsed.end();
1479 ssize_t rawOpaqueBufferSize = getRawOpaqueBufferSize(width, height, maxResolution);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -08001480 if (rawOpaqueBufferSize <= 0) {
1481 SET_ERR_L("Invalid RAW opaque buffer size %zd", rawOpaqueBufferSize);
1482 return BAD_VALUE;
1483 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001484 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001485 width, height, rawOpaqueBufferSize, format, dataSpace, rotation,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001486 mTimestampOffset, physicalCameraId, sensorPixelModesUsed, streamSetId,
1487 isMultiResolution);
Shuzhen Wang758c2152017-01-10 18:26:18 -08001488 } else if (isShared) {
1489 newStream = new Camera3SharedOutputStream(mNextStreamId, consumers,
1490 width, height, format, consumerUsage, dataSpace, rotation,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001491 mTimestampOffset, physicalCameraId, sensorPixelModesUsed, streamSetId,
1492 mUseHalBufManager);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001493 } else if (consumers.size() == 0 && hasDeferredConsumer) {
Zhijun He5d677d12016-05-29 16:52:39 -07001494 newStream = new Camera3OutputStream(mNextStreamId,
1495 width, height, format, consumerUsage, dataSpace, rotation,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001496 mTimestampOffset, physicalCameraId, sensorPixelModesUsed, streamSetId,
1497 isMultiResolution);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001498 } else {
Shuzhen Wang0129d522016-10-30 22:43:41 -07001499 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001500 width, height, format, dataSpace, rotation,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001501 mTimestampOffset, physicalCameraId, sensorPixelModesUsed, streamSetId,
1502 isMultiResolution);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001503 }
Emilian Peev40ead602017-09-26 15:46:36 +01001504
1505 size_t consumerCount = consumers.size();
1506 for (size_t i = 0; i < consumerCount; i++) {
1507 int id = newStream->getSurfaceId(consumers[i]);
1508 if (id < 0) {
1509 SET_ERR_L("Invalid surface id");
1510 return BAD_VALUE;
1511 }
1512 if (surfaceIds != nullptr) {
1513 surfaceIds->push_back(id);
1514 }
1515 }
1516
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001517 newStream->setStatusTracker(mStatusTracker);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001518
Emilian Peev08dd2452017-04-06 16:55:14 +01001519 newStream->setBufferManager(mBufferManager);
Zhijun He125684a2015-12-26 15:07:30 -08001520
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08001521 newStream->setImageDumpMask(mImageDumpMask);
1522
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001523 res = mOutputStreams.add(mNextStreamId, newStream);
1524 if (res < 0) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001525 SET_ERR_L("Can't add new stream to set: %s (%d)", strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001526 return res;
1527 }
1528
Shuzhen Wang316781a2020-08-18 18:11:01 -07001529 mSessionStatsBuilder.addStream(mNextStreamId);
1530
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001531 *id = mNextStreamId++;
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07001532 mNeedConfig = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001533
1534 // Continue captures if active at start
1535 if (wasActive) {
1536 ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001537 // Reuse current operating mode and session parameters for new stream config
1538 res = configureStreamsLocked(mOperatingMode, mSessionParams);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001539 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001540 CLOGE("Can't reconfigure device for new stream %d: %s (%d)",
1541 mNextStreamId, strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001542 return res;
1543 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001544 internalResumeLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001545 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001546 ALOGV("Camera %s: Created new stream", mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001547 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001548}
1549
Emilian Peev710c1422017-08-30 11:19:38 +01001550status_t Camera3Device::getStreamInfo(int id, StreamInfo *streamInfo) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001551 ATRACE_CALL();
Emilian Peev710c1422017-08-30 11:19:38 +01001552 if (nullptr == streamInfo) {
1553 return BAD_VALUE;
1554 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001555 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001556 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001557
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001558 switch (mStatus) {
1559 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001560 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001561 return INVALID_OPERATION;
1562 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001563 CLOGE("Device not initialized!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001564 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001565 case STATUS_UNCONFIGURED:
1566 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001567 case STATUS_ACTIVE:
1568 // OK
1569 break;
1570 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001571 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001572 return INVALID_OPERATION;
1573 }
1574
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001575 sp<Camera3StreamInterface> stream = mOutputStreams.get(id);
1576 if (stream == nullptr) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001577 CLOGE("Stream %d is unknown", id);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001578 return BAD_VALUE;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001579 }
1580
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001581 streamInfo->width = stream->getWidth();
1582 streamInfo->height = stream->getHeight();
1583 streamInfo->format = stream->getFormat();
1584 streamInfo->dataSpace = stream->getDataSpace();
1585 streamInfo->formatOverridden = stream->isFormatOverridden();
1586 streamInfo->originalFormat = stream->getOriginalFormat();
1587 streamInfo->dataSpaceOverridden = stream->isDataSpaceOverridden();
1588 streamInfo->originalDataSpace = stream->getOriginalDataSpace();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001589 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001590}
1591
1592status_t Camera3Device::setStreamTransform(int id,
1593 int transform) {
1594 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001595 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001596 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001597
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001598 switch (mStatus) {
1599 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001600 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001601 return INVALID_OPERATION;
1602 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001603 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001604 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001605 case STATUS_UNCONFIGURED:
1606 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001607 case STATUS_ACTIVE:
1608 // OK
1609 break;
1610 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001611 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001612 return INVALID_OPERATION;
1613 }
1614
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001615 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(id);
1616 if (stream == nullptr) {
1617 CLOGE("Stream %d does not exist", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001618 return BAD_VALUE;
1619 }
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001620 return stream->setTransform(transform);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001621}
1622
1623status_t Camera3Device::deleteStream(int id) {
1624 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001625 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001626 Mutex::Autolock l(mLock);
1627 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001628
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001629 ALOGV("%s: Camera %s: Deleting stream %d", __FUNCTION__, mId.string(), id);
Igor Murashkine2172be2013-05-28 15:31:39 -07001630
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001631 // CameraDevice semantics require device to already be idle before
1632 // deleteStream is called, unlike for createStream.
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001633 if (mStatus == STATUS_ACTIVE) {
Yin-Chia Yeh693047d2018-03-08 12:14:19 -08001634 ALOGW("%s: Camera %s: Device not idle", __FUNCTION__, mId.string());
Igor Murashkin52827132013-05-13 14:53:44 -07001635 return -EBUSY;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001636 }
1637
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07001638 if (mStatus == STATUS_ERROR) {
1639 ALOGW("%s: Camera %s: deleteStream not allowed in ERROR state",
1640 __FUNCTION__, mId.string());
1641 return -EBUSY;
1642 }
1643
Igor Murashkin2fba5842013-04-22 14:03:54 -07001644 sp<Camera3StreamInterface> deletedStream;
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001645 sp<Camera3StreamInterface> stream = mOutputStreams.get(id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001646 if (mInputStream != NULL && id == mInputStream->getId()) {
1647 deletedStream = mInputStream;
1648 mInputStream.clear();
1649 } else {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001650 if (stream == nullptr) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001651 CLOGE("Stream %d does not exist", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001652 return BAD_VALUE;
1653 }
Shuzhen Wang316781a2020-08-18 18:11:01 -07001654 mSessionStatsBuilder.removeStream(id);
Zhijun He5f446352014-01-22 09:49:33 -08001655 }
1656
1657 // Delete output stream or the output part of a bi-directional stream.
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001658 if (stream != nullptr) {
1659 deletedStream = stream;
1660 mOutputStreams.remove(id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001661 }
1662
1663 // Free up the stream endpoint so that it can be used by some other stream
1664 res = deletedStream->disconnect();
1665 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001666 SET_ERR_L("Can't disconnect deleted stream %d", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001667 // fall through since we want to still list the stream as deleted.
1668 }
1669 mDeletedStreams.add(deletedStream);
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07001670 mNeedConfig = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001671
1672 return res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001673}
1674
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001675status_t Camera3Device::configureStreams(const CameraMetadata& sessionParams, int operatingMode) {
Igor Murashkine2d167e2014-08-19 16:19:59 -07001676 ATRACE_CALL();
1677 ALOGV("%s: E", __FUNCTION__);
1678
1679 Mutex::Autolock il(mInterfaceLock);
1680 Mutex::Autolock l(mLock);
Chien-Yu Chen17338fc2015-06-18 16:30:12 -07001681
Emilian Peev811d2952018-05-25 11:08:40 +01001682 // In case the client doesn't include any session parameter, try a
1683 // speculative configuration using the values from the last cached
1684 // default request.
1685 if (sessionParams.isEmpty() &&
Emilian Peevf4816702020-04-03 15:44:51 -07001686 ((mLastTemplateId > 0) && (mLastTemplateId < CAMERA_TEMPLATE_COUNT)) &&
Emilian Peev811d2952018-05-25 11:08:40 +01001687 (!mRequestTemplateCache[mLastTemplateId].isEmpty())) {
1688 ALOGV("%s: Speculative session param configuration with template id: %d", __func__,
1689 mLastTemplateId);
1690 return filterParamsAndConfigureLocked(mRequestTemplateCache[mLastTemplateId],
1691 operatingMode);
1692 }
1693
Emilian Peevac3ce6c2017-12-12 15:27:02 +00001694 return filterParamsAndConfigureLocked(sessionParams, operatingMode);
1695}
1696
1697status_t Camera3Device::filterParamsAndConfigureLocked(const CameraMetadata& sessionParams,
1698 int operatingMode) {
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001699 //Filter out any incoming session parameters
1700 const CameraMetadata params(sessionParams);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001701 camera_metadata_entry_t availableSessionKeys = mDeviceInfo.find(
1702 ANDROID_REQUEST_AVAILABLE_SESSION_KEYS);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00001703 CameraMetadata filteredParams(availableSessionKeys.count);
1704 camera_metadata_t *meta = const_cast<camera_metadata_t *>(
1705 filteredParams.getAndLock());
1706 set_camera_metadata_vendor_id(meta, mVendorTagId);
1707 filteredParams.unlock(meta);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001708 if (availableSessionKeys.count > 0) {
1709 for (size_t i = 0; i < availableSessionKeys.count; i++) {
1710 camera_metadata_ro_entry entry = params.find(
1711 availableSessionKeys.data.i32[i]);
1712 if (entry.count > 0) {
1713 filteredParams.update(entry);
1714 }
1715 }
1716 }
1717
1718 return configureStreamsLocked(operatingMode, filteredParams);
Igor Murashkine2d167e2014-08-19 16:19:59 -07001719}
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001720
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07001721status_t Camera3Device::getInputBufferProducer(
1722 sp<IGraphicBufferProducer> *producer) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07001723 ATRACE_CALL();
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07001724 Mutex::Autolock il(mInterfaceLock);
1725 Mutex::Autolock l(mLock);
1726
1727 if (producer == NULL) {
1728 return BAD_VALUE;
1729 } else if (mInputStream == NULL) {
1730 return INVALID_OPERATION;
1731 }
1732
1733 return mInputStream->getInputBufferProducer(producer);
1734}
1735
Emilian Peevf4816702020-04-03 15:44:51 -07001736status_t Camera3Device::createDefaultRequest(camera_request_template_t templateId,
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001737 CameraMetadata *request) {
1738 ATRACE_CALL();
Alex Rayfe7e0c62013-05-30 00:12:13 -07001739 ALOGV("%s: for template %d", __FUNCTION__, templateId);
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08001740
Emilian Peevf4816702020-04-03 15:44:51 -07001741 if (templateId <= 0 || templateId >= CAMERA_TEMPLATE_COUNT) {
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08001742 android_errorWriteWithInfoLog(CameraService::SN_EVENT_LOG_ID, "26866110",
Jayant Chowdhary12361932018-08-27 14:46:13 -07001743 CameraThreadState::getCallingUid(), nullptr, 0);
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08001744 return BAD_VALUE;
1745 }
1746
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001747 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001748
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001749 {
1750 Mutex::Autolock l(mLock);
1751 switch (mStatus) {
1752 case STATUS_ERROR:
1753 CLOGE("Device has encountered a serious error");
1754 return INVALID_OPERATION;
1755 case STATUS_UNINITIALIZED:
1756 CLOGE("Device is not initialized!");
1757 return INVALID_OPERATION;
1758 case STATUS_UNCONFIGURED:
1759 case STATUS_CONFIGURED:
1760 case STATUS_ACTIVE:
1761 // OK
1762 break;
1763 default:
1764 SET_ERR_L("Unexpected status: %d", mStatus);
1765 return INVALID_OPERATION;
1766 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001767
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001768 if (!mRequestTemplateCache[templateId].isEmpty()) {
1769 *request = mRequestTemplateCache[templateId];
Emilian Peev811d2952018-05-25 11:08:40 +01001770 mLastTemplateId = templateId;
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001771 return OK;
1772 }
Zhijun Hea1530f12014-09-14 12:44:20 -07001773 }
1774
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001775 camera_metadata_t *rawRequest;
1776 status_t res = mInterface->constructDefaultRequestSettings(
Emilian Peevf4816702020-04-03 15:44:51 -07001777 (camera_request_template_t) templateId, &rawRequest);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001778
1779 {
1780 Mutex::Autolock l(mLock);
1781 if (res == BAD_VALUE) {
1782 ALOGI("%s: template %d is not supported on this camera device",
1783 __FUNCTION__, templateId);
1784 return res;
1785 } else if (res != OK) {
1786 CLOGE("Unable to construct request template %d: %s (%d)",
1787 templateId, strerror(-res), res);
1788 return res;
1789 }
1790
1791 set_camera_metadata_vendor_id(rawRequest, mVendorTagId);
1792 mRequestTemplateCache[templateId].acquire(rawRequest);
1793
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08001794 // Override the template request with zoomRatioMapper
1795 res = mZoomRatioMappers[mId.c_str()].initZoomRatioInTemplate(
1796 &mRequestTemplateCache[templateId]);
1797 if (res != OK) {
1798 CLOGE("Failed to update zoom ratio for template %d: %s (%d)",
1799 templateId, strerror(-res), res);
1800 return res;
1801 }
1802
Shuzhen Wangd25dc972020-03-24 17:11:43 -07001803 // Fill in JPEG_QUALITY if not available
1804 if (!mRequestTemplateCache[templateId].exists(ANDROID_JPEG_QUALITY)) {
1805 static const uint8_t kDefaultJpegQuality = 95;
1806 mRequestTemplateCache[templateId].update(ANDROID_JPEG_QUALITY,
1807 &kDefaultJpegQuality, 1);
1808 }
1809
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001810 *request = mRequestTemplateCache[templateId];
Emilian Peev811d2952018-05-25 11:08:40 +01001811 mLastTemplateId = templateId;
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001812 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001813 return OK;
1814}
1815
1816status_t Camera3Device::waitUntilDrained() {
1817 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001818 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001819 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001820 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001821
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001822 return waitUntilDrainedLocked(maxExpectedDuration);
Zhijun He69a37482014-03-23 18:44:49 -07001823}
1824
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001825status_t Camera3Device::waitUntilDrainedLocked(nsecs_t maxExpectedDuration) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001826 switch (mStatus) {
1827 case STATUS_UNINITIALIZED:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001828 case STATUS_UNCONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001829 ALOGV("%s: Already idle", __FUNCTION__);
1830 return OK;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001831 case STATUS_CONFIGURED:
1832 // To avoid race conditions, check with tracker to be sure
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001833 case STATUS_ERROR:
1834 case STATUS_ACTIVE:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001835 // Need to verify shut down
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001836 break;
1837 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001838 SET_ERR_L("Unexpected status: %d",mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001839 return INVALID_OPERATION;
1840 }
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07001841 ALOGV("%s: Camera %s: Waiting until idle (%" PRIi64 "ns)", __FUNCTION__, mId.string(),
1842 maxExpectedDuration);
1843 status_t res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
Eino-Ville Talvala9c8a0912014-09-14 14:52:19 -07001844 if (res != OK) {
Yin-Chia Yeh87b3ec02019-06-03 10:44:39 -07001845 mStatusTracker->dumpActiveComponents();
Eino-Ville Talvala9c8a0912014-09-14 14:52:19 -07001846 SET_ERR_L("Error waiting for HAL to drain: %s (%d)", strerror(-res),
1847 res);
1848 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001849 return res;
1850}
1851
Ruben Brunk183f0562015-08-12 12:55:02 -07001852void Camera3Device::internalUpdateStatusLocked(Status status) {
1853 mStatus = status;
1854 mRecentStatusUpdates.add(mStatus);
1855 mStatusChanged.broadcast();
1856}
1857
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001858// Pause to reconfigure
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001859status_t Camera3Device::internalPauseAndWaitLocked(nsecs_t maxExpectedDuration) {
Emilian Peeve86358b2019-02-15 13:51:39 -08001860 if (mRequestThread.get() != nullptr) {
1861 mRequestThread->setPaused(true);
1862 } else {
1863 return NO_INIT;
1864 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001865
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07001866 ALOGV("%s: Camera %s: Internal wait until idle (% " PRIi64 " ns)", __FUNCTION__, mId.string(),
1867 maxExpectedDuration);
1868 status_t res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001869 if (res != OK) {
1870 SET_ERR_L("Can't idle device in %f seconds!",
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07001871 maxExpectedDuration/1e9);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001872 }
1873
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001874 return res;
1875}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001876
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001877// Resume after internalPauseAndWaitLocked
1878status_t Camera3Device::internalResumeLocked() {
1879 status_t res;
1880
1881 mRequestThread->setPaused(false);
1882
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08001883 ALOGV("%s: Camera %s: Internal wait until active (% " PRIi64 " ns)", __FUNCTION__, mId.string(),
1884 kActiveTimeout);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001885 res = waitUntilStateThenRelock(/*active*/ true, kActiveTimeout);
1886 if (res != OK) {
1887 SET_ERR_L("Can't transition to active in %f seconds!",
1888 kActiveTimeout/1e9);
1889 }
1890 mPauseStateNotify = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001891 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001892}
1893
Ruben Brunk183f0562015-08-12 12:55:02 -07001894status_t Camera3Device::waitUntilStateThenRelock(bool active, nsecs_t timeout) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001895 status_t res = OK;
Ruben Brunk183f0562015-08-12 12:55:02 -07001896
1897 size_t startIndex = 0;
1898 if (mStatusWaiters == 0) {
1899 // Clear the list of recent statuses if there are no existing threads waiting on updates to
1900 // this status list
1901 mRecentStatusUpdates.clear();
1902 } else {
1903 // If other threads are waiting on updates to this status list, set the position of the
1904 // first element that this list will check rather than clearing the list.
1905 startIndex = mRecentStatusUpdates.size();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001906 }
1907
Ruben Brunk183f0562015-08-12 12:55:02 -07001908 mStatusWaiters++;
1909
Yin-Chia Yehe52b8fa2020-07-28 00:17:58 -07001910 bool signalPipelineDrain = false;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07001911 if (!active && mUseHalBufManager) {
1912 auto streamIds = mOutputStreams.getStreamIds();
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08001913 if (mStatus == STATUS_ACTIVE) {
1914 mRequestThread->signalPipelineDrain(streamIds);
Yin-Chia Yehe52b8fa2020-07-28 00:17:58 -07001915 signalPipelineDrain = true;
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08001916 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07001917 mRequestBufferSM.onWaitUntilIdle();
1918 }
1919
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001920 bool stateSeen = false;
1921 do {
Ruben Brunk183f0562015-08-12 12:55:02 -07001922 if (active == (mStatus == STATUS_ACTIVE)) {
1923 // Desired state is current
1924 break;
1925 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001926
1927 res = mStatusChanged.waitRelative(mLock, timeout);
1928 if (res != OK) break;
1929
Ruben Brunk183f0562015-08-12 12:55:02 -07001930 // This is impossible, but if not, could result in subtle deadlocks and invalid state
1931 // transitions.
1932 LOG_ALWAYS_FATAL_IF(startIndex > mRecentStatusUpdates.size(),
1933 "%s: Skipping status updates in Camera3Device, may result in deadlock.",
1934 __FUNCTION__);
1935
1936 // Encountered desired state since we began waiting
1937 for (size_t i = startIndex; i < mRecentStatusUpdates.size(); i++) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001938 if (active == (mRecentStatusUpdates[i] == STATUS_ACTIVE) ) {
1939 stateSeen = true;
1940 break;
1941 }
1942 }
1943 } while (!stateSeen);
1944
Yin-Chia Yehe52b8fa2020-07-28 00:17:58 -07001945 if (signalPipelineDrain) {
1946 mRequestThread->resetPipelineDrain();
1947 }
1948
Ruben Brunk183f0562015-08-12 12:55:02 -07001949 mStatusWaiters--;
1950
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001951 return res;
1952}
1953
1954
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001955status_t Camera3Device::setNotifyCallback(wp<NotificationListener> listener) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001956 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001957 std::lock_guard<std::mutex> l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001958
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001959 if (listener != NULL && mListener != NULL) {
1960 ALOGW("%s: Replacing old callback listener", __FUNCTION__);
1961 }
1962 mListener = listener;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001963 mRequestThread->setNotificationListener(listener);
1964 mPreparerThread->setNotificationListener(listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001965
1966 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001967}
1968
Eino-Ville Talvala46910bd2013-07-18 19:15:17 -07001969bool Camera3Device::willNotify3A() {
1970 return false;
1971}
1972
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001973status_t Camera3Device::waitForNextFrame(nsecs_t timeout) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07001974 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001975 std::unique_lock<std::mutex> l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001976
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001977 while (mResultQueue.empty()) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001978 auto st = mResultSignal.wait_for(l, std::chrono::nanoseconds(timeout));
1979 if (st == std::cv_status::timeout) {
1980 return TIMED_OUT;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001981 }
1982 }
1983 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001984}
1985
Jianing Weicb0652e2014-03-12 18:29:36 -07001986status_t Camera3Device::getNextResult(CaptureResult *frame) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001987 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001988 std::lock_guard<std::mutex> l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001989
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001990 if (mResultQueue.empty()) {
1991 return NOT_ENOUGH_DATA;
1992 }
1993
Jianing Weicb0652e2014-03-12 18:29:36 -07001994 if (frame == NULL) {
1995 ALOGE("%s: argument cannot be NULL", __FUNCTION__);
1996 return BAD_VALUE;
1997 }
1998
1999 CaptureResult &result = *(mResultQueue.begin());
2000 frame->mResultExtras = result.mResultExtras;
2001 frame->mMetadata.acquire(result.mMetadata);
Shuzhen Wang5c22c152017-12-31 17:12:25 -08002002 frame->mPhysicalMetadatas = std::move(result.mPhysicalMetadatas);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002003 mResultQueue.erase(mResultQueue.begin());
2004
2005 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002006}
2007
2008status_t Camera3Device::triggerAutofocus(uint32_t id) {
2009 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002010 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002011
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002012 ALOGV("%s: Triggering autofocus, id %d", __FUNCTION__, id);
2013 // Mix-in this trigger into the next request and only the next request.
2014 RequestTrigger trigger[] = {
2015 {
2016 ANDROID_CONTROL_AF_TRIGGER,
2017 ANDROID_CONTROL_AF_TRIGGER_START
2018 },
2019 {
2020 ANDROID_CONTROL_AF_TRIGGER_ID,
2021 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07002022 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002023 };
2024
2025 return mRequestThread->queueTrigger(trigger,
2026 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002027}
2028
2029status_t Camera3Device::triggerCancelAutofocus(uint32_t id) {
2030 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002031 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002032
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002033 ALOGV("%s: Triggering cancel autofocus, id %d", __FUNCTION__, id);
2034 // Mix-in this trigger into the next request and only the next request.
2035 RequestTrigger trigger[] = {
2036 {
2037 ANDROID_CONTROL_AF_TRIGGER,
2038 ANDROID_CONTROL_AF_TRIGGER_CANCEL
2039 },
2040 {
2041 ANDROID_CONTROL_AF_TRIGGER_ID,
2042 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07002043 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002044 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002045
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002046 return mRequestThread->queueTrigger(trigger,
2047 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002048}
2049
2050status_t Camera3Device::triggerPrecaptureMetering(uint32_t id) {
2051 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002052 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002053
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002054 ALOGV("%s: Triggering precapture metering, id %d", __FUNCTION__, id);
2055 // Mix-in this trigger into the next request and only the next request.
2056 RequestTrigger trigger[] = {
2057 {
2058 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER,
2059 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_START
2060 },
2061 {
2062 ANDROID_CONTROL_AE_PRECAPTURE_ID,
2063 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07002064 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002065 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002066
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002067 return mRequestThread->queueTrigger(trigger,
2068 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002069}
2070
Jianing Weicb0652e2014-03-12 18:29:36 -07002071status_t Camera3Device::flush(int64_t *frameNumber) {
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07002072 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002073 ALOGV("%s: Camera %s: Flushing all requests", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002074 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07002075
Zhijun He7ef20392014-04-21 16:04:17 -07002076 {
2077 Mutex::Autolock l(mLock);
Emilian Peeved2ebe42018-09-25 16:59:09 +01002078
2079 // b/116514106 "disconnect()" can get called twice for the same device. The
2080 // camera device will not be initialized during the second run.
2081 if (mStatus == STATUS_UNINITIALIZED) {
2082 return OK;
2083 }
2084
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002085 mRequestThread->clear(/*out*/frameNumber);
Shuzhen Wang316781a2020-08-18 18:11:01 -07002086
2087 // Stop session and stream counter
2088 mSessionStatsBuilder.stopCounter();
Zhijun He7ef20392014-04-21 16:04:17 -07002089 }
2090
Emilian Peev08dd2452017-04-06 16:55:14 +01002091 return mRequestThread->flush();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07002092}
2093
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002094status_t Camera3Device::prepare(int streamId) {
Ruben Brunkc78ac262015-08-13 17:58:46 -07002095 return prepare(camera3::Camera3StreamInterface::ALLOCATE_PIPELINE_MAX, streamId);
2096}
2097
2098status_t Camera3Device::prepare(int maxCount, int streamId) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002099 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002100 ALOGV("%s: Camera %s: Preparing stream %d", __FUNCTION__, mId.string(), streamId);
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07002101 Mutex::Autolock il(mInterfaceLock);
2102 Mutex::Autolock l(mLock);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002103
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002104 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
2105 if (stream == nullptr) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002106 CLOGE("Stream %d does not exist", streamId);
2107 return BAD_VALUE;
2108 }
2109
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002110 if (stream->isUnpreparable() || stream->hasOutstandingBuffers() ) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07002111 CLOGE("Stream %d has already been a request target", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002112 return BAD_VALUE;
2113 }
2114
2115 if (mRequestThread->isStreamPending(stream)) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07002116 CLOGE("Stream %d is already a target in a pending request", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002117 return BAD_VALUE;
2118 }
2119
Ruben Brunkc78ac262015-08-13 17:58:46 -07002120 return mPreparerThread->prepare(maxCount, stream);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002121}
2122
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002123status_t Camera3Device::tearDown(int streamId) {
2124 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002125 ALOGV("%s: Camera %s: Tearing down stream %d", __FUNCTION__, mId.string(), streamId);
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002126 Mutex::Autolock il(mInterfaceLock);
2127 Mutex::Autolock l(mLock);
2128
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002129 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
2130 if (stream == nullptr) {
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002131 CLOGE("Stream %d does not exist", streamId);
2132 return BAD_VALUE;
2133 }
2134
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002135 if (stream->hasOutstandingBuffers() || mRequestThread->isStreamPending(stream)) {
2136 CLOGE("Stream %d is a target of a in-progress request", streamId);
2137 return BAD_VALUE;
2138 }
2139
2140 return stream->tearDown();
2141}
2142
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002143status_t Camera3Device::addBufferListenerForStream(int streamId,
2144 wp<Camera3StreamBufferListener> listener) {
2145 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002146 ALOGV("%s: Camera %s: Adding buffer listener for stream %d", __FUNCTION__, mId.string(), streamId);
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002147 Mutex::Autolock il(mInterfaceLock);
2148 Mutex::Autolock l(mLock);
2149
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002150 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
2151 if (stream == nullptr) {
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002152 CLOGE("Stream %d does not exist", streamId);
2153 return BAD_VALUE;
2154 }
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002155 stream->addBufferListener(listener);
2156
2157 return OK;
2158}
2159
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002160/**
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002161 * Methods called by subclasses
2162 */
2163
2164void Camera3Device::notifyStatus(bool idle) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002165 ATRACE_CALL();
Shuzhen Wang316781a2020-08-18 18:11:01 -07002166 std::vector<int> streamIds;
2167 std::vector<hardware::CameraStreamStats> streamStats;
2168
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002169 {
2170 // Need mLock to safely update state and synchronize to current
2171 // state of methods in flight.
2172 Mutex::Autolock l(mLock);
2173 // We can get various system-idle notices from the status tracker
2174 // while starting up. Only care about them if we've actually sent
2175 // in some requests recently.
2176 if (mStatus != STATUS_ACTIVE && mStatus != STATUS_CONFIGURED) {
2177 return;
2178 }
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08002179 ALOGV("%s: Camera %s: Now %s, pauseState: %s", __FUNCTION__, mId.string(),
2180 idle ? "idle" : "active", mPauseStateNotify ? "true" : "false");
Ruben Brunk183f0562015-08-12 12:55:02 -07002181 internalUpdateStatusLocked(idle ? STATUS_CONFIGURED : STATUS_ACTIVE);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002182
2183 // Skip notifying listener if we're doing some user-transparent
2184 // state changes
2185 if (mPauseStateNotify) return;
Shuzhen Wang316781a2020-08-18 18:11:01 -07002186
2187 // Populate stream statistics in case of Idle
2188 if (idle) {
2189 for (size_t i = 0; i < mOutputStreams.size(); i++) {
2190 auto stream = mOutputStreams[i];
2191 if (stream.get() == nullptr) continue;
2192 streamIds.push_back(stream->getId());
2193 Camera3Stream* camera3Stream = Camera3Stream::cast(stream->asHalStream());
2194 int64_t usage = 0LL;
2195 if (camera3Stream != nullptr) {
2196 usage = camera3Stream->getUsage();
2197 }
2198 streamStats.emplace_back(stream->getWidth(), stream->getHeight(),
2199 stream->getFormat(), stream->getDataSpace(), usage,
2200 stream->getMaxHalBuffers(),
2201 stream->getMaxTotalBuffers() - stream->getMaxHalBuffers());
2202 }
2203 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002204 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002205
2206 sp<NotificationListener> listener;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002207 {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002208 std::lock_guard<std::mutex> l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002209 listener = mListener.promote();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002210 }
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07002211 status_t res = OK;
2212 if (listener != nullptr) {
2213 if (idle) {
2214 // Get session stats from the builder, and notify the listener.
2215 int64_t requestCount, resultErrorCount;
2216 bool deviceError;
2217 std::map<int, StreamStats> streamStatsMap;
2218 mSessionStatsBuilder.buildAndReset(&requestCount, &resultErrorCount,
2219 &deviceError, &streamStatsMap);
2220 for (size_t i = 0; i < streamIds.size(); i++) {
2221 int streamId = streamIds[i];
2222 auto stats = streamStatsMap.find(streamId);
2223 if (stats != streamStatsMap.end()) {
2224 streamStats[i].mRequestCount = stats->second.mRequestedFrameCount;
2225 streamStats[i].mErrorCount = stats->second.mDroppedFrameCount;
2226 streamStats[i].mStartLatencyMs = stats->second.mStartLatencyMs;
2227 streamStats[i].mHistogramType =
2228 hardware::CameraStreamStats::HISTOGRAM_TYPE_CAPTURE_LATENCY;
2229 streamStats[i].mHistogramBins.assign(
2230 stats->second.mCaptureLatencyBins.begin(),
2231 stats->second.mCaptureLatencyBins.end());
2232 streamStats[i].mHistogramCounts.assign(
2233 stats->second.mCaptureLatencyHistogram.begin(),
2234 stats->second.mCaptureLatencyHistogram.end());
2235 }
Shuzhen Wang316781a2020-08-18 18:11:01 -07002236 }
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07002237 listener->notifyIdle(requestCount, resultErrorCount, deviceError, streamStats);
2238 } else {
2239 res = listener->notifyActive();
Shuzhen Wang316781a2020-08-18 18:11:01 -07002240 }
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07002241 }
2242 if (res != OK) {
2243 SET_ERR("Camera access permission lost mid-operation: %s (%d)",
2244 strerror(-res), res);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002245 }
2246}
2247
Shuzhen Wang758c2152017-01-10 18:26:18 -08002248status_t Camera3Device::setConsumerSurfaces(int streamId,
Emilian Peev40ead602017-09-26 15:46:36 +01002249 const std::vector<sp<Surface>>& consumers, std::vector<int> *surfaceIds) {
Zhijun He5d677d12016-05-29 16:52:39 -07002250 ATRACE_CALL();
Shuzhen Wang758c2152017-01-10 18:26:18 -08002251 ALOGV("%s: Camera %s: set consumer surface for stream %d",
2252 __FUNCTION__, mId.string(), streamId);
Emilian Peev40ead602017-09-26 15:46:36 +01002253
2254 if (surfaceIds == nullptr) {
2255 return BAD_VALUE;
2256 }
2257
Zhijun He5d677d12016-05-29 16:52:39 -07002258 Mutex::Autolock il(mInterfaceLock);
2259 Mutex::Autolock l(mLock);
2260
Shuzhen Wang758c2152017-01-10 18:26:18 -08002261 if (consumers.size() == 0) {
2262 CLOGE("No consumer is passed!");
Zhijun He5d677d12016-05-29 16:52:39 -07002263 return BAD_VALUE;
2264 }
2265
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002266 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
2267 if (stream == nullptr) {
Zhijun He5d677d12016-05-29 16:52:39 -07002268 CLOGE("Stream %d is unknown", streamId);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002269 return BAD_VALUE;
Zhijun He5d677d12016-05-29 16:52:39 -07002270 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002271
2272 // isConsumerConfigurationDeferred will be off after setConsumers
2273 bool isDeferred = stream->isConsumerConfigurationDeferred();
Shuzhen Wang758c2152017-01-10 18:26:18 -08002274 status_t res = stream->setConsumers(consumers);
Zhijun He5d677d12016-05-29 16:52:39 -07002275 if (res != OK) {
2276 CLOGE("Stream %d set consumer failed (error %d %s) ", streamId, res, strerror(-res));
2277 return res;
2278 }
2279
Emilian Peev40ead602017-09-26 15:46:36 +01002280 for (auto &consumer : consumers) {
2281 int id = stream->getSurfaceId(consumer);
2282 if (id < 0) {
2283 CLOGE("Invalid surface id!");
2284 return BAD_VALUE;
2285 }
2286 surfaceIds->push_back(id);
2287 }
2288
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002289 if (isDeferred) {
Shuzhen Wang0129d522016-10-30 22:43:41 -07002290 if (!stream->isConfiguring()) {
2291 CLOGE("Stream %d was already fully configured.", streamId);
2292 return INVALID_OPERATION;
2293 }
Zhijun He5d677d12016-05-29 16:52:39 -07002294
Shuzhen Wang0129d522016-10-30 22:43:41 -07002295 res = stream->finishConfiguration();
2296 if (res != OK) {
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002297 // If finishConfiguration fails due to abandoned surface, do not set
2298 // device to error state.
2299 bool isSurfaceAbandoned =
2300 (res == NO_INIT || res == DEAD_OBJECT) && stream->isAbandoned();
2301 if (!isSurfaceAbandoned) {
2302 SET_ERR_L("Can't finish configuring output stream %d: %s (%d)",
2303 stream->getId(), strerror(-res), res);
2304 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07002305 return res;
2306 }
Zhijun He5d677d12016-05-29 16:52:39 -07002307 }
2308
2309 return OK;
2310}
2311
Emilian Peev40ead602017-09-26 15:46:36 +01002312status_t Camera3Device::updateStream(int streamId, const std::vector<sp<Surface>> &newSurfaces,
2313 const std::vector<OutputStreamInfo> &outputInfo,
2314 const std::vector<size_t> &removedSurfaceIds, KeyedVector<sp<Surface>, size_t> *outputMap) {
2315 Mutex::Autolock il(mInterfaceLock);
2316 Mutex::Autolock l(mLock);
2317
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002318 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
2319 if (stream == nullptr) {
Emilian Peev40ead602017-09-26 15:46:36 +01002320 CLOGE("Stream %d is unknown", streamId);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002321 return BAD_VALUE;
Emilian Peev40ead602017-09-26 15:46:36 +01002322 }
2323
2324 for (const auto &it : removedSurfaceIds) {
2325 if (mRequestThread->isOutputSurfacePending(streamId, it)) {
2326 CLOGE("Shared surface still part of a pending request!");
2327 return -EBUSY;
2328 }
2329 }
2330
Emilian Peev40ead602017-09-26 15:46:36 +01002331 status_t res = stream->updateStream(newSurfaces, outputInfo, removedSurfaceIds, outputMap);
2332 if (res != OK) {
2333 CLOGE("Stream %d failed to update stream (error %d %s) ",
2334 streamId, res, strerror(-res));
2335 if (res == UNKNOWN_ERROR) {
2336 SET_ERR_L("%s: Stream update failed to revert to previous output configuration!",
2337 __FUNCTION__);
2338 }
2339 return res;
2340 }
2341
2342 return res;
2343}
2344
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002345status_t Camera3Device::dropStreamBuffers(bool dropping, int streamId) {
2346 Mutex::Autolock il(mInterfaceLock);
2347 Mutex::Autolock l(mLock);
2348
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002349 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
2350 if (stream == nullptr) {
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002351 ALOGE("%s: Stream %d is not found.", __FUNCTION__, streamId);
2352 return BAD_VALUE;
2353 }
Shuzhen Wang316781a2020-08-18 18:11:01 -07002354
2355 if (dropping) {
2356 mSessionStatsBuilder.stopCounter(streamId);
2357 } else {
2358 mSessionStatsBuilder.startCounter(streamId);
2359 }
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002360 return stream->dropBuffers(dropping);
2361}
2362
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002363/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002364 * Camera3Device private methods
2365 */
2366
2367sp<Camera3Device::CaptureRequest> Camera3Device::createCaptureRequest(
Emilian Peevaebbe412018-01-15 13:53:24 +00002368 const PhysicalCameraSettingsList &request, const SurfaceMap &surfaceMap) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002369 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002370
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08002371 sp<CaptureRequest> newRequest = new CaptureRequest();
Emilian Peevaebbe412018-01-15 13:53:24 +00002372 newRequest->mSettingsList = request;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002373
2374 camera_metadata_entry_t inputStreams =
Emilian Peevaebbe412018-01-15 13:53:24 +00002375 newRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_INPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002376 if (inputStreams.count > 0) {
2377 if (mInputStream == NULL ||
Zhijun Hed1d64672013-09-06 15:00:01 -07002378 mInputStream->getId() != inputStreams.data.i32[0]) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002379 CLOGE("Request references unknown input stream %d",
2380 inputStreams.data.u8[0]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002381 return NULL;
2382 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002383
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002384 if (mInputStream->isConfiguring()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002385 SET_ERR_L("%s: input stream %d is not configured!",
2386 __FUNCTION__, mInputStream->getId());
2387 return NULL;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002388 }
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07002389 // Check if stream prepare is blocking requests.
2390 if (mInputStream->isBlockedByPrepare()) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002391 CLOGE("Request references an input stream that's being prepared!");
2392 return NULL;
2393 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002394
2395 newRequest->mInputStream = mInputStream;
Emilian Peevaebbe412018-01-15 13:53:24 +00002396 newRequest->mSettingsList.begin()->metadata.erase(ANDROID_REQUEST_INPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002397 }
2398
2399 camera_metadata_entry_t streams =
Emilian Peevaebbe412018-01-15 13:53:24 +00002400 newRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_OUTPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002401 if (streams.count == 0) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002402 CLOGE("Zero output streams specified!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002403 return NULL;
2404 }
2405
2406 for (size_t i = 0; i < streams.count; i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002407 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streams.data.i32[i]);
2408 if (stream == nullptr) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002409 CLOGE("Request references unknown stream %d",
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002410 streams.data.i32[i]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002411 return NULL;
2412 }
Zhijun He5d677d12016-05-29 16:52:39 -07002413 // It is illegal to include a deferred consumer output stream into a request
Shuzhen Wang0129d522016-10-30 22:43:41 -07002414 auto iter = surfaceMap.find(streams.data.i32[i]);
2415 if (iter != surfaceMap.end()) {
2416 const std::vector<size_t>& surfaces = iter->second;
2417 for (const auto& surface : surfaces) {
2418 if (stream->isConsumerConfigurationDeferred(surface)) {
2419 CLOGE("Stream %d surface %zu hasn't finished configuration yet "
2420 "due to deferred consumer", stream->getId(), surface);
2421 return NULL;
2422 }
2423 }
Yin-Chia Yeh0b287572018-10-15 12:38:13 -07002424 newRequest->mOutputSurfaces[streams.data.i32[i]] = surfaces;
Zhijun He5d677d12016-05-29 16:52:39 -07002425 }
2426
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002427 if (stream->isConfiguring()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002428 SET_ERR_L("%s: stream %d is not configured!", __FUNCTION__, stream->getId());
2429 return NULL;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002430 }
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07002431 // Check if stream prepare is blocking requests.
2432 if (stream->isBlockedByPrepare()) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002433 CLOGE("Request references an output stream that's being prepared!");
2434 return NULL;
2435 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002436
2437 newRequest->mOutputStreams.push(stream);
2438 }
Emilian Peevaebbe412018-01-15 13:53:24 +00002439 newRequest->mSettingsList.begin()->metadata.erase(ANDROID_REQUEST_OUTPUT_STREAMS);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07002440 newRequest->mBatchSize = 1;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002441
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08002442 auto rotateAndCropEntry =
2443 newRequest->mSettingsList.begin()->metadata.find(ANDROID_SCALER_ROTATE_AND_CROP);
2444 if (rotateAndCropEntry.count > 0 &&
2445 rotateAndCropEntry.data.u8[0] == ANDROID_SCALER_ROTATE_AND_CROP_AUTO) {
2446 newRequest->mRotateAndCropAuto = true;
2447 } else {
2448 newRequest->mRotateAndCropAuto = false;
2449 }
2450
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07002451 auto zoomRatioEntry =
2452 newRequest->mSettingsList.begin()->metadata.find(ANDROID_CONTROL_ZOOM_RATIO);
2453 if (zoomRatioEntry.count > 0 &&
2454 zoomRatioEntry.data.f[0] == 1.0f) {
2455 newRequest->mZoomRatioIs1x = true;
2456 } else {
2457 newRequest->mZoomRatioIs1x = false;
2458 }
2459
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08002460 if (mSupportCameraMute) {
2461 auto testPatternModeEntry =
2462 newRequest->mSettingsList.begin()->metadata.find(ANDROID_SENSOR_TEST_PATTERN_MODE);
2463 newRequest->mOriginalTestPatternMode = testPatternModeEntry.count > 0 ?
2464 testPatternModeEntry.data.i32[0] :
2465 ANDROID_SENSOR_TEST_PATTERN_MODE_OFF;
2466
2467 auto testPatternDataEntry =
2468 newRequest->mSettingsList.begin()->metadata.find(ANDROID_SENSOR_TEST_PATTERN_DATA);
2469 if (testPatternDataEntry.count > 0) {
2470 memcpy(newRequest->mOriginalTestPatternData, testPatternModeEntry.data.i32,
2471 sizeof(newRequest->mOriginalTestPatternData));
2472 } else {
2473 newRequest->mOriginalTestPatternData[0] = 0;
2474 newRequest->mOriginalTestPatternData[1] = 0;
2475 newRequest->mOriginalTestPatternData[2] = 0;
2476 newRequest->mOriginalTestPatternData[3] = 0;
2477 }
2478 }
2479
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002480 return newRequest;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002481}
2482
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002483void Camera3Device::cancelStreamsConfigurationLocked() {
2484 int res = OK;
2485 if (mInputStream != NULL && mInputStream->isConfiguring()) {
2486 res = mInputStream->cancelConfiguration();
2487 if (res != OK) {
2488 CLOGE("Can't cancel configuring input stream %d: %s (%d)",
2489 mInputStream->getId(), strerror(-res), res);
2490 }
2491 }
2492
2493 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002494 sp<Camera3OutputStreamInterface> outputStream = mOutputStreams[i];
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002495 if (outputStream->isConfiguring()) {
2496 res = outputStream->cancelConfiguration();
2497 if (res != OK) {
2498 CLOGE("Can't cancel configuring output stream %d: %s (%d)",
2499 outputStream->getId(), strerror(-res), res);
2500 }
2501 }
2502 }
2503
2504 // Return state to that at start of call, so that future configures
2505 // properly clean things up
2506 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
2507 mNeedConfig = true;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002508
2509 res = mPreparerThread->resume();
2510 if (res != OK) {
2511 ALOGE("%s: Camera %s: Preparer thread failed to resume!", __FUNCTION__, mId.string());
2512 }
2513}
2514
Emilian Peev0d0191e2020-04-21 17:01:18 -07002515bool Camera3Device::checkAbandonedStreamsLocked() {
2516 if ((mInputStream.get() != nullptr) && (mInputStream->isAbandoned())) {
2517 return true;
2518 }
2519
2520 for (size_t i = 0; i < mOutputStreams.size(); i++) {
2521 auto stream = mOutputStreams[i];
2522 if ((stream.get() != nullptr) && (stream->isAbandoned())) {
2523 return true;
2524 }
2525 }
2526
2527 return false;
2528}
2529
Emilian Peev3bead5f2020-05-28 17:29:08 -07002530bool Camera3Device::reconfigureCamera(const CameraMetadata& sessionParams, int clientStatusId) {
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002531 ATRACE_CALL();
2532 bool ret = false;
2533
Shuzhen Wang316781a2020-08-18 18:11:01 -07002534 nsecs_t startTime = systemTime();
2535
Jayant Chowdhary646c31b2020-01-30 13:09:59 -08002536 Mutex::Autolock il(mInterfaceLock);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002537 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
2538
2539 Mutex::Autolock l(mLock);
Emilian Peev0d0191e2020-04-21 17:01:18 -07002540 if (checkAbandonedStreamsLocked()) {
2541 ALOGW("%s: Abandoned stream detected, session parameters can't be applied correctly!",
2542 __FUNCTION__);
2543 return true;
2544 }
2545
Emilian Peev3bead5f2020-05-28 17:29:08 -07002546 status_t rc = NO_ERROR;
2547 bool markClientActive = false;
2548 if (mStatus == STATUS_ACTIVE) {
2549 markClientActive = true;
2550 mPauseStateNotify = true;
2551 mStatusTracker->markComponentIdle(clientStatusId, Fence::NO_FENCE);
2552
2553 rc = internalPauseAndWaitLocked(maxExpectedDuration);
2554 }
2555
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002556 if (rc == NO_ERROR) {
2557 mNeedConfig = true;
2558 rc = configureStreamsLocked(mOperatingMode, sessionParams, /*notifyRequestThread*/ false);
2559 if (rc == NO_ERROR) {
2560 ret = true;
2561 mPauseStateNotify = false;
2562 //Moving to active state while holding 'mLock' is important.
2563 //There could be pending calls to 'create-/deleteStream' which
2564 //will trigger another stream configuration while the already
2565 //present streams end up with outstanding buffers that will
2566 //not get drained.
2567 internalUpdateStatusLocked(STATUS_ACTIVE);
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002568 } else if (rc == DEAD_OBJECT) {
2569 // DEAD_OBJECT can be returned if either the consumer surface is
2570 // abandoned, or the HAL has died.
2571 // - If the HAL has died, configureStreamsLocked call will set
2572 // device to error state,
2573 // - If surface is abandoned, we should not set device to error
2574 // state.
2575 ALOGE("Failed to re-configure camera due to abandoned surface");
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002576 } else {
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002577 SET_ERR_L("Failed to re-configure camera: %d", rc);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002578 }
2579 } else {
2580 ALOGE("%s: Failed to pause streaming: %d", __FUNCTION__, rc);
2581 }
2582
Shuzhen Wang316781a2020-08-18 18:11:01 -07002583 CameraServiceProxyWrapper::logStreamConfigured(mId, mOperatingMode, true /*internalReconfig*/,
2584 ns2ms(systemTime() - startTime));
2585
Emilian Peev3bead5f2020-05-28 17:29:08 -07002586 if (markClientActive) {
2587 mStatusTracker->markComponentActive(clientStatusId);
2588 }
2589
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002590 return ret;
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002591}
2592
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002593status_t Camera3Device::configureStreamsLocked(int operatingMode,
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002594 const CameraMetadata& sessionParams, bool notifyRequestThread) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002595 ATRACE_CALL();
2596 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002597
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002598 if (mStatus != STATUS_UNCONFIGURED && mStatus != STATUS_CONFIGURED) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002599 CLOGE("Not idle");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002600 return INVALID_OPERATION;
2601 }
2602
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08002603 if (operatingMode < 0) {
2604 CLOGE("Invalid operating mode: %d", operatingMode);
2605 return BAD_VALUE;
2606 }
2607
2608 bool isConstrainedHighSpeed =
2609 static_cast<int>(StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE) ==
2610 operatingMode;
2611
2612 if (mOperatingMode != operatingMode) {
2613 mNeedConfig = true;
2614 mIsConstrainedHighSpeedConfiguration = isConstrainedHighSpeed;
2615 mOperatingMode = operatingMode;
2616 }
2617
Shuzhen Wang0cf01cb2019-09-05 13:33:06 -07002618 // In case called from configureStreams, abort queued input buffers not belonging to
2619 // any pending requests.
2620 if (mInputStream != NULL && notifyRequestThread) {
2621 while (true) {
Emilian Peevf4816702020-04-03 15:44:51 -07002622 camera_stream_buffer_t inputBuffer;
Shuzhen Wang83bff122020-11-20 15:51:39 -08002623 camera3::Size inputBufferSize;
Shuzhen Wang0cf01cb2019-09-05 13:33:06 -07002624 status_t res = mInputStream->getInputBuffer(&inputBuffer,
Shuzhen Wang83bff122020-11-20 15:51:39 -08002625 &inputBufferSize, /*respectHalLimit*/ false);
Shuzhen Wang0cf01cb2019-09-05 13:33:06 -07002626 if (res != OK) {
2627 // Exhausted acquiring all input buffers.
2628 break;
2629 }
2630
Emilian Peevf4816702020-04-03 15:44:51 -07002631 inputBuffer.status = CAMERA_BUFFER_STATUS_ERROR;
Shuzhen Wang0cf01cb2019-09-05 13:33:06 -07002632 res = mInputStream->returnInputBuffer(inputBuffer);
2633 if (res != OK) {
2634 ALOGE("%s: %d: couldn't return input buffer while clearing input queue: "
2635 "%s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
2636 }
2637 }
2638 }
2639
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002640 if (!mNeedConfig) {
2641 ALOGV("%s: Skipping config, no stream changes", __FUNCTION__);
2642 return OK;
2643 }
2644
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002645 // Workaround for device HALv3.2 or older spec bug - zero streams requires
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002646 // adding a fake stream instead.
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002647 // TODO: Bug: 17321404 for fixing the HAL spec and removing this workaround.
2648 if (mOutputStreams.size() == 0) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002649 addFakeStreamLocked();
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002650 } else {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002651 tryRemoveFakeStreamLocked();
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002652 }
2653
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002654 // Start configuring the streams
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002655 ALOGV("%s: Camera %s: Starting stream configuration", __FUNCTION__, mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002656
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002657 mPreparerThread->pause();
2658
Emilian Peevf4816702020-04-03 15:44:51 -07002659 camera_stream_configuration config;
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -08002660 config.operation_mode = mOperatingMode;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002661 config.num_streams = (mInputStream != NULL) + mOutputStreams.size();
Shuzhen Wang83bff122020-11-20 15:51:39 -08002662 config.input_is_multi_resolution = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002663
Emilian Peevf4816702020-04-03 15:44:51 -07002664 Vector<camera3::camera_stream_t*> streams;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002665 streams.setCapacity(config.num_streams);
Emilian Peev192ee832018-01-31 14:46:47 +00002666 std::vector<uint32_t> bufferSizes(config.num_streams, 0);
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002667
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002668
2669 if (mInputStream != NULL) {
Emilian Peevf4816702020-04-03 15:44:51 -07002670 camera3::camera_stream_t *inputStream;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002671 inputStream = mInputStream->startConfiguration();
2672 if (inputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002673 CLOGE("Can't start input stream configuration");
2674 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002675 return INVALID_OPERATION;
2676 }
2677 streams.add(inputStream);
Shuzhen Wang83bff122020-11-20 15:51:39 -08002678
2679 config.input_is_multi_resolution = mIsInputStreamMultiResolution;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002680 }
2681
Shuzhen Wang99080502021-03-07 21:08:20 -08002682 mGroupIdPhysicalCameraMap.clear();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002683 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Igor Murashkin2fba5842013-04-22 14:03:54 -07002684
2685 // Don't configure bidi streams twice, nor add them twice to the list
2686 if (mOutputStreams[i].get() ==
2687 static_cast<Camera3StreamInterface*>(mInputStream.get())) {
2688
2689 config.num_streams--;
2690 continue;
2691 }
2692
Emilian Peevf4816702020-04-03 15:44:51 -07002693 camera3::camera_stream_t *outputStream;
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002694 outputStream = mOutputStreams[i]->startConfiguration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002695 if (outputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002696 CLOGE("Can't start output stream configuration");
2697 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002698 return INVALID_OPERATION;
2699 }
2700 streams.add(outputStream);
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002701
Shuzhen Wangb7ab1e42019-02-20 15:42:23 -08002702 if (outputStream->format == HAL_PIXEL_FORMAT_BLOB) {
Emilian Peev192ee832018-01-31 14:46:47 +00002703 size_t k = i + ((mInputStream != nullptr) ? 1 : 0); // Input stream if present should
2704 // always occupy the initial entry.
Shuzhen Wangb7ab1e42019-02-20 15:42:23 -08002705 if (outputStream->data_space == HAL_DATASPACE_V0_JFIF) {
2706 bufferSizes[k] = static_cast<uint32_t>(
2707 getJpegBufferSize(outputStream->width, outputStream->height));
2708 } else if (outputStream->data_space ==
2709 static_cast<android_dataspace>(HAL_DATASPACE_JPEG_APP_SEGMENTS)) {
2710 bufferSizes[k] = outputStream->width * outputStream->height;
2711 } else {
2712 ALOGW("%s: Blob dataSpace %d not supported",
2713 __FUNCTION__, outputStream->data_space);
2714 }
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002715 }
Shuzhen Wang99080502021-03-07 21:08:20 -08002716
2717 if (mOutputStreams[i]->isMultiResolution()) {
2718 int32_t streamGroupId = mOutputStreams[i]->getHalStreamGroupId();
2719 const String8& physicalCameraId = mOutputStreams[i]->getPhysicalCameraId();
2720 mGroupIdPhysicalCameraMap[streamGroupId].insert(physicalCameraId);
2721 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002722 }
2723
2724 config.streams = streams.editArray();
2725
2726 // Do the HAL configuration; will potentially touch stream
Shuzhen Wang92653952019-05-07 15:11:43 -07002727 // max_buffers, usage, and priv fields, as well as data_space and format
2728 // fields for IMPLEMENTATION_DEFINED formats.
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002729
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002730 const camera_metadata_t *sessionBuffer = sessionParams.getAndLock();
Emilian Peev192ee832018-01-31 14:46:47 +00002731 res = mInterface->configureStreams(sessionBuffer, &config, bufferSizes);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002732 sessionParams.unlock(sessionBuffer);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002733
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002734 if (res == BAD_VALUE) {
2735 // HAL rejected this set of streams as unsupported, clean up config
2736 // attempt and return to unconfigured state
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002737 CLOGE("Set of requested inputs/outputs not supported by HAL");
2738 cancelStreamsConfigurationLocked();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002739 return BAD_VALUE;
2740 } else if (res != OK) {
2741 // Some other kind of error from configure_streams - this is not
2742 // expected
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002743 SET_ERR_L("Unable to configure streams with HAL: %s (%d)",
2744 strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002745 return res;
2746 }
2747
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002748 // Finish all stream configuration immediately.
2749 // TODO: Try to relax this later back to lazy completion, which should be
2750 // faster
2751
Igor Murashkin073f8572013-05-02 14:59:28 -07002752 if (mInputStream != NULL && mInputStream->isConfiguring()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002753 bool streamReConfigured = false;
2754 res = mInputStream->finishConfiguration(&streamReConfigured);
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002755 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002756 CLOGE("Can't finish configuring input stream %d: %s (%d)",
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002757 mInputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002758 cancelStreamsConfigurationLocked();
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002759 if ((res == NO_INIT || res == DEAD_OBJECT) && mInputStream->isAbandoned()) {
2760 return DEAD_OBJECT;
2761 }
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002762 return BAD_VALUE;
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002763 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002764 if (streamReConfigured) {
2765 mInterface->onStreamReConfigured(mInputStream->getId());
2766 }
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002767 }
2768
2769 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002770 sp<Camera3OutputStreamInterface> outputStream = mOutputStreams[i];
Zhijun He5d677d12016-05-29 16:52:39 -07002771 if (outputStream->isConfiguring() && !outputStream->isConsumerConfigurationDeferred()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002772 bool streamReConfigured = false;
2773 res = outputStream->finishConfiguration(&streamReConfigured);
Igor Murashkin073f8572013-05-02 14:59:28 -07002774 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002775 CLOGE("Can't finish configuring output stream %d: %s (%d)",
Igor Murashkin073f8572013-05-02 14:59:28 -07002776 outputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002777 cancelStreamsConfigurationLocked();
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002778 if ((res == NO_INIT || res == DEAD_OBJECT) && outputStream->isAbandoned()) {
2779 return DEAD_OBJECT;
2780 }
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002781 return BAD_VALUE;
Igor Murashkin073f8572013-05-02 14:59:28 -07002782 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002783 if (streamReConfigured) {
2784 mInterface->onStreamReConfigured(outputStream->getId());
2785 }
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002786 }
2787 }
2788
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002789 // Request thread needs to know to avoid using repeat-last-settings protocol
2790 // across configure_streams() calls
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002791 if (notifyRequestThread) {
Shuzhen Wang99080502021-03-07 21:08:20 -08002792 mRequestThread->configurationComplete(mIsConstrainedHighSpeedConfiguration,
2793 sessionParams, mGroupIdPhysicalCameraMap);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002794 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002795
Zhijun He90f7c372016-08-16 16:19:43 -07002796 char value[PROPERTY_VALUE_MAX];
2797 property_get("camera.fifo.disable", value, "0");
2798 int32_t disableFifo = atoi(value);
2799 if (disableFifo != 1) {
2800 // Boost priority of request thread to SCHED_FIFO.
2801 pid_t requestThreadTid = mRequestThread->getTid();
2802 res = requestPriority(getpid(), requestThreadTid,
Mikhail Naganov83f04272017-02-07 10:45:09 -08002803 kRequestThreadPriority, /*isForApp*/ false, /*asynchronous*/ false);
Zhijun He90f7c372016-08-16 16:19:43 -07002804 if (res != OK) {
2805 ALOGW("Can't set realtime priority for request processing thread: %s (%d)",
2806 strerror(-res), res);
2807 } else {
2808 ALOGD("Set real time priority for request queue thread (tid %d)", requestThreadTid);
2809 }
Eino-Ville Talvalaf99498e2015-09-25 16:52:55 -07002810 }
2811
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002812 // Update device state
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002813 const camera_metadata_t *newSessionParams = sessionParams.getAndLock();
2814 const camera_metadata_t *currentSessionParams = mSessionParams.getAndLock();
2815 bool updateSessionParams = (newSessionParams != currentSessionParams) ? true : false;
2816 sessionParams.unlock(newSessionParams);
2817 mSessionParams.unlock(currentSessionParams);
2818 if (updateSessionParams) {
2819 mSessionParams = sessionParams;
2820 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002821
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002822 mNeedConfig = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002823
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002824 internalUpdateStatusLocked((mFakeStreamId == NO_STREAM) ?
Ruben Brunk183f0562015-08-12 12:55:02 -07002825 STATUS_CONFIGURED : STATUS_UNCONFIGURED);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002826
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002827 ALOGV("%s: Camera %s: Stream configuration complete", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002828
Zhijun He0a210512014-07-24 13:45:15 -07002829 // tear down the deleted streams after configure streams.
2830 mDeletedStreams.clear();
2831
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002832 auto rc = mPreparerThread->resume();
2833 if (rc != OK) {
2834 SET_ERR_L("%s: Camera %s: Preparer thread failed to resume!", __FUNCTION__, mId.string());
2835 return rc;
2836 }
2837
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002838 if (mFakeStreamId == NO_STREAM) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07002839 mRequestBufferSM.onStreamsConfigured();
2840 }
2841
Cliff Wuc2ad9c82021-04-21 00:58:58 +08002842 // Since the streams configuration of the injection camera is based on the internal camera, we
2843 // must wait until the internal camera configure streams before calling injectCamera() to
2844 // configure the injection streams.
2845 if (mInjectionMethods->isInjecting()) {
2846 ALOGV("%s: Injection camera %s: Start to configure streams.",
2847 __FUNCTION__, mInjectionMethods->getInjectedCamId().string());
2848 res = mInjectionMethods->injectCamera(config, bufferSizes);
2849 if (res != OK) {
2850 ALOGE("Can't finish inject camera process!");
2851 return res;
2852 }
2853 }
2854
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002855 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002856}
2857
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002858status_t Camera3Device::addFakeStreamLocked() {
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002859 ATRACE_CALL();
2860 status_t res;
2861
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002862 if (mFakeStreamId != NO_STREAM) {
2863 // Should never be adding a second fake stream when one is already
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002864 // active
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002865 SET_ERR_L("%s: Camera %s: A fake stream already exists!",
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002866 __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002867 return INVALID_OPERATION;
2868 }
2869
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002870 ALOGV("%s: Camera %s: Adding a fake stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002871
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002872 sp<Camera3OutputStreamInterface> fakeStream =
2873 new Camera3FakeStream(mNextStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002874
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002875 res = mOutputStreams.add(mNextStreamId, fakeStream);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002876 if (res < 0) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002877 SET_ERR_L("Can't add fake stream to set: %s (%d)", strerror(-res), res);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002878 return res;
2879 }
2880
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002881 mFakeStreamId = mNextStreamId;
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002882 mNextStreamId++;
2883
2884 return OK;
2885}
2886
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002887status_t Camera3Device::tryRemoveFakeStreamLocked() {
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002888 ATRACE_CALL();
2889 status_t res;
2890
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002891 if (mFakeStreamId == NO_STREAM) return OK;
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002892 if (mOutputStreams.size() == 1) return OK;
2893
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002894 ALOGV("%s: Camera %s: Removing the fake stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002895
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002896 // Ok, have a fake stream and there's at least one other output stream,
2897 // so remove the fake
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002898
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002899 sp<Camera3StreamInterface> deletedStream = mOutputStreams.get(mFakeStreamId);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002900 if (deletedStream == nullptr) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002901 SET_ERR_L("Fake stream %d does not appear to exist", mFakeStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002902 return INVALID_OPERATION;
2903 }
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002904 mOutputStreams.remove(mFakeStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002905
2906 // Free up the stream endpoint so that it can be used by some other stream
2907 res = deletedStream->disconnect();
2908 if (res != OK) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002909 SET_ERR_L("Can't disconnect deleted fake stream %d", mFakeStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002910 // fall through since we want to still list the stream as deleted.
2911 }
2912 mDeletedStreams.add(deletedStream);
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002913 mFakeStreamId = NO_STREAM;
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002914
2915 return res;
2916}
2917
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002918void Camera3Device::setErrorState(const char *fmt, ...) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002919 ATRACE_CALL();
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002920 Mutex::Autolock l(mLock);
2921 va_list args;
2922 va_start(args, fmt);
2923
2924 setErrorStateLockedV(fmt, args);
2925
2926 va_end(args);
2927}
2928
2929void Camera3Device::setErrorStateV(const char *fmt, va_list args) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002930 ATRACE_CALL();
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002931 Mutex::Autolock l(mLock);
2932 setErrorStateLockedV(fmt, args);
2933}
2934
2935void Camera3Device::setErrorStateLocked(const char *fmt, ...) {
2936 va_list args;
2937 va_start(args, fmt);
2938
2939 setErrorStateLockedV(fmt, args);
2940
2941 va_end(args);
2942}
2943
2944void Camera3Device::setErrorStateLockedV(const char *fmt, va_list args) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002945 // Print out all error messages to log
2946 String8 errorCause = String8::formatV(fmt, args);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002947 ALOGE("Camera %s: %s", mId.string(), errorCause.string());
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002948
2949 // But only do error state transition steps for the first error
Zhijun Heb05eeae2013-06-06 13:51:22 -07002950 if (mStatus == STATUS_ERROR || mStatus == STATUS_UNINITIALIZED) return;
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002951
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002952 mErrorCause = errorCause;
2953
Yin-Chia Yeh3d145ae2017-07-27 12:47:03 -07002954 if (mRequestThread != nullptr) {
2955 mRequestThread->setPaused(true);
2956 }
Ruben Brunk183f0562015-08-12 12:55:02 -07002957 internalUpdateStatusLocked(STATUS_ERROR);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002958
2959 // Notify upstream about a device error
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002960 sp<NotificationListener> listener = mListener.promote();
2961 if (listener != NULL) {
2962 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002963 CaptureResultExtras());
Shuzhen Wang316781a2020-08-18 18:11:01 -07002964 mSessionStatsBuilder.onDeviceError();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002965 }
2966
2967 // Save stack trace. View by dumping it later.
2968 CameraTraces::saveTrace();
2969 // TODO: consider adding errorCause and client pid/procname
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002970}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002971
2972/**
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002973 * In-flight request management
2974 */
2975
Jianing Weicb0652e2014-03-12 18:29:36 -07002976status_t Camera3Device::registerInFlight(uint32_t frameNumber,
Chien-Yu Chend196d612015-06-22 19:49:01 -07002977 int32_t numBuffers, CaptureResultExtras resultExtras, bool hasInput,
Shuzhen Wang5c22c152017-12-31 17:12:25 -08002978 bool hasAppCallback, nsecs_t maxExpectedDuration,
Shuzhen Wang99080502021-03-07 21:08:20 -08002979 const std::set<std::set<String8>>& physicalCameraIds,
2980 bool isStillCapture, bool isZslCapture, bool rotateAndCropAuto,
2981 const std::set<std::string>& cameraIdsWithZoom,
Shuzhen Wang316781a2020-08-18 18:11:01 -07002982 const SurfaceMap& outputSurfaces, nsecs_t requestTimeNs) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002983 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002984 std::lock_guard<std::mutex> l(mInFlightLock);
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002985
2986 ssize_t res;
Chien-Yu Chend196d612015-06-22 19:49:01 -07002987 res = mInFlightMap.add(frameNumber, InFlightRequest(numBuffers, resultExtras, hasInput,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07002988 hasAppCallback, maxExpectedDuration, physicalCameraIds, isStillCapture, isZslCapture,
Shuzhen Wang316781a2020-08-18 18:11:01 -07002989 rotateAndCropAuto, cameraIdsWithZoom, requestTimeNs, outputSurfaces));
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002990 if (res < 0) return res;
2991
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07002992 if (mInFlightMap.size() == 1) {
Emilian Peev26d975d2018-07-05 14:52:57 +01002993 // Hold a separate dedicated tracker lock to prevent race with disconnect and also
2994 // avoid a deadlock during reprocess requests.
2995 Mutex::Autolock l(mTrackerLock);
Yin-Chia Yeh38dfde52017-06-27 17:13:33 -07002996 if (mStatusTracker != nullptr) {
2997 mStatusTracker->markComponentActive(mInFlightStatusId);
2998 }
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07002999 }
3000
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003001 mExpectedInflightDuration += maxExpectedDuration;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003002 return OK;
3003}
3004
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003005void Camera3Device::onInflightEntryRemovedLocked(nsecs_t duration) {
Shuzhen Wangcadb3302016-11-04 14:17:56 -07003006 // Indicate idle inFlightMap to the status tracker
3007 if (mInFlightMap.size() == 0) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07003008 mRequestBufferSM.onInflightMapEmpty();
Emilian Peev26d975d2018-07-05 14:52:57 +01003009 // Hold a separate dedicated tracker lock to prevent race with disconnect and also
3010 // avoid a deadlock during reprocess requests.
3011 Mutex::Autolock l(mTrackerLock);
Yin-Chia Yeh38dfde52017-06-27 17:13:33 -07003012 if (mStatusTracker != nullptr) {
3013 mStatusTracker->markComponentIdle(mInFlightStatusId, Fence::NO_FENCE);
3014 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07003015 }
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003016 mExpectedInflightDuration -= duration;
Shuzhen Wangcadb3302016-11-04 14:17:56 -07003017}
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003018
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003019void Camera3Device::checkInflightMapLengthLocked() {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04003020 // Validation check - if we have too many in-flight frames with long total inflight duration,
Yin-Chia Yeh99fd0972019-06-27 14:22:44 -07003021 // something has likely gone wrong. This might still be legit only if application send in
3022 // a long burst of long exposure requests.
3023 if (mExpectedInflightDuration > kMinWarnInflightDuration) {
3024 if (!mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() > kInFlightWarnLimit) {
3025 CLOGW("In-flight list too large: %zu, total inflight duration %" PRIu64,
3026 mInFlightMap.size(), mExpectedInflightDuration);
3027 } else if (mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() >
3028 kInFlightWarnLimitHighSpeed) {
3029 CLOGW("In-flight list too large for high speed configuration: %zu,"
3030 "total inflight duration %" PRIu64,
3031 mInFlightMap.size(), mExpectedInflightDuration);
3032 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003033 }
3034}
3035
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003036void Camera3Device::onInflightMapFlushedLocked() {
3037 mExpectedInflightDuration = 0;
3038}
3039
3040void Camera3Device::removeInFlightMapEntryLocked(int idx) {
Jayant Chowdharyd4776262020-06-23 23:45:57 -07003041 ATRACE_HFR_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003042 nsecs_t duration = mInFlightMap.valueAt(idx).maxExpectedDuration;
3043 mInFlightMap.removeItemsAt(idx, 1);
3044
3045 onInflightEntryRemovedLocked(duration);
3046}
3047
3048
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003049void Camera3Device::flushInflightRequests() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003050 ATRACE_CALL();
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003051 sp<NotificationListener> listener;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003052 {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003053 std::lock_guard<std::mutex> l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003054 listener = mListener.promote();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003055 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003056
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003057 FlushInflightReqStates states {
3058 mId, mInFlightLock, mInFlightMap, mUseHalBufManager,
Shuzhen Wang316781a2020-08-18 18:11:01 -07003059 listener, *this, *mInterface, *this, mSessionStatsBuilder};
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003060
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003061 camera3::flushInflightRequests(states);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003062}
3063
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003064CameraMetadata Camera3Device::getLatestRequestLocked() {
Igor Murashkin1e479c02013-09-06 16:55:14 -07003065 ALOGV("%s", __FUNCTION__);
3066
Igor Murashkin1e479c02013-09-06 16:55:14 -07003067 CameraMetadata retVal;
3068
3069 if (mRequestThread != NULL) {
3070 retVal = mRequestThread->getLatestRequest();
3071 }
3072
Igor Murashkin1e479c02013-09-06 16:55:14 -07003073 return retVal;
3074}
3075
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07003076void Camera3Device::monitorMetadata(TagMonitor::eventSource source,
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003077 int64_t frameNumber, nsecs_t timestamp, const CameraMetadata& metadata,
3078 const std::unordered_map<std::string, CameraMetadata>& physicalMetadata) {
3079
3080 mTagMonitor.monitorMetadata(source, frameNumber, timestamp, metadata,
3081 physicalMetadata);
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07003082}
3083
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003084/**
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003085 * HalInterface inner class methods
3086 */
3087
Yifan Hongf79b5542017-04-11 14:44:25 -07003088Camera3Device::HalInterface::HalInterface(
3089 sp<ICameraDeviceSession> &session,
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003090 std::shared_ptr<RequestMetadataQueue> queue,
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003091 bool useHalBufManager, bool supportOfflineProcessing) :
Yifan Hongf79b5542017-04-11 14:44:25 -07003092 mHidlSession(session),
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003093 mRequestMetadataQueue(queue),
Emilian Peev4ec17882019-01-24 17:16:58 -08003094 mUseHalBufManager(useHalBufManager),
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003095 mIsReconfigurationQuerySupported(true),
3096 mSupportOfflineProcessing(supportOfflineProcessing) {
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003097 // Check with hardware service manager if we can downcast these interfaces
3098 // Somewhat expensive, so cache the results at startup
Shuzhen Wang83bff122020-11-20 15:51:39 -08003099 auto castResult_3_7 = device::V3_7::ICameraDeviceSession::castFrom(mHidlSession);
3100 if (castResult_3_7.isOk()) {
3101 mHidlSession_3_7 = castResult_3_7;
3102 }
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003103 auto castResult_3_6 = device::V3_6::ICameraDeviceSession::castFrom(mHidlSession);
3104 if (castResult_3_6.isOk()) {
3105 mHidlSession_3_6 = castResult_3_6;
3106 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003107 auto castResult_3_5 = device::V3_5::ICameraDeviceSession::castFrom(mHidlSession);
3108 if (castResult_3_5.isOk()) {
3109 mHidlSession_3_5 = castResult_3_5;
3110 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003111 auto castResult_3_4 = device::V3_4::ICameraDeviceSession::castFrom(mHidlSession);
3112 if (castResult_3_4.isOk()) {
3113 mHidlSession_3_4 = castResult_3_4;
3114 }
3115 auto castResult_3_3 = device::V3_3::ICameraDeviceSession::castFrom(mHidlSession);
3116 if (castResult_3_3.isOk()) {
3117 mHidlSession_3_3 = castResult_3_3;
3118 }
3119}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003120
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003121Camera3Device::HalInterface::HalInterface() :
3122 mUseHalBufManager(false),
3123 mSupportOfflineProcessing(false) {}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003124
3125Camera3Device::HalInterface::HalInterface(const HalInterface& other) :
Yifan Hongf79b5542017-04-11 14:44:25 -07003126 mHidlSession(other.mHidlSession),
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003127 mRequestMetadataQueue(other.mRequestMetadataQueue),
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003128 mUseHalBufManager(other.mUseHalBufManager),
3129 mSupportOfflineProcessing(other.mSupportOfflineProcessing) {}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003130
3131bool Camera3Device::HalInterface::valid() {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003132 return (mHidlSession != nullptr);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003133}
3134
3135void Camera3Device::HalInterface::clear() {
Shuzhen Wang83bff122020-11-20 15:51:39 -08003136 mHidlSession_3_7.clear();
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003137 mHidlSession_3_6.clear();
Emilian Peev644a3e12018-11-23 13:52:39 +00003138 mHidlSession_3_5.clear();
Emilian Peev9e740b02018-01-30 18:28:03 +00003139 mHidlSession_3_4.clear();
3140 mHidlSession_3_3.clear();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003141 mHidlSession.clear();
3142}
3143
3144status_t Camera3Device::HalInterface::constructDefaultRequestSettings(
Emilian Peevf4816702020-04-03 15:44:51 -07003145 camera_request_template_t templateId,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003146 /*out*/ camera_metadata_t **requestTemplate) {
3147 ATRACE_NAME("CameraHal::constructDefaultRequestSettings");
3148 if (!valid()) return INVALID_OPERATION;
3149 status_t res = OK;
3150
Emilian Peev31abd0a2017-05-11 18:37:46 +01003151 common::V1_0::Status status;
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003152
3153 auto requestCallback = [&status, &requestTemplate]
Emilian Peev31abd0a2017-05-11 18:37:46 +01003154 (common::V1_0::Status s, const device::V3_2::CameraMetadata& request) {
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003155 status = s;
3156 if (status == common::V1_0::Status::OK) {
3157 const camera_metadata *r =
3158 reinterpret_cast<const camera_metadata_t*>(request.data());
3159 size_t expectedSize = request.size();
3160 int ret = validate_camera_metadata_structure(r, &expectedSize);
3161 if (ret == OK || ret == CAMERA_METADATA_VALIDATION_SHIFTED) {
3162 *requestTemplate = clone_camera_metadata(r);
3163 if (*requestTemplate == nullptr) {
3164 ALOGE("%s: Unable to clone camera metadata received from HAL",
3165 __FUNCTION__);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003166 status = common::V1_0::Status::INTERNAL_ERROR;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003167 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003168 } else {
3169 ALOGE("%s: Malformed camera metadata received from HAL", __FUNCTION__);
3170 status = common::V1_0::Status::INTERNAL_ERROR;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003171 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003172 }
3173 };
3174 hardware::Return<void> err;
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003175 RequestTemplate id;
3176 switch (templateId) {
Emilian Peevf4816702020-04-03 15:44:51 -07003177 case CAMERA_TEMPLATE_PREVIEW:
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003178 id = RequestTemplate::PREVIEW;
3179 break;
Emilian Peevf4816702020-04-03 15:44:51 -07003180 case CAMERA_TEMPLATE_STILL_CAPTURE:
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003181 id = RequestTemplate::STILL_CAPTURE;
3182 break;
Emilian Peevf4816702020-04-03 15:44:51 -07003183 case CAMERA_TEMPLATE_VIDEO_RECORD:
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003184 id = RequestTemplate::VIDEO_RECORD;
3185 break;
Emilian Peevf4816702020-04-03 15:44:51 -07003186 case CAMERA_TEMPLATE_VIDEO_SNAPSHOT:
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003187 id = RequestTemplate::VIDEO_SNAPSHOT;
3188 break;
Emilian Peevf4816702020-04-03 15:44:51 -07003189 case CAMERA_TEMPLATE_ZERO_SHUTTER_LAG:
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003190 id = RequestTemplate::ZERO_SHUTTER_LAG;
3191 break;
Emilian Peevf4816702020-04-03 15:44:51 -07003192 case CAMERA_TEMPLATE_MANUAL:
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003193 id = RequestTemplate::MANUAL;
3194 break;
3195 default:
3196 // Unknown template ID, or this HAL is too old to support it
3197 return BAD_VALUE;
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003198 }
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003199 err = mHidlSession->constructDefaultRequestSettings(id, requestCallback);
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003200
Emilian Peev31abd0a2017-05-11 18:37:46 +01003201 if (!err.isOk()) {
3202 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3203 res = DEAD_OBJECT;
3204 } else {
3205 res = CameraProviderManager::mapToStatusT(status);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003206 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003207
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003208 return res;
3209}
3210
Emilian Peev4ec17882019-01-24 17:16:58 -08003211bool Camera3Device::HalInterface::isReconfigurationRequired(CameraMetadata& oldSessionParams,
3212 CameraMetadata& newSessionParams) {
3213 // We do reconfiguration by default;
3214 bool ret = true;
3215 if ((mHidlSession_3_5 != nullptr) && mIsReconfigurationQuerySupported) {
3216 android::hardware::hidl_vec<uint8_t> oldParams, newParams;
3217 camera_metadata_t* oldSessioMeta = const_cast<camera_metadata_t*>(
3218 oldSessionParams.getAndLock());
3219 camera_metadata_t* newSessioMeta = const_cast<camera_metadata_t*>(
3220 newSessionParams.getAndLock());
3221 oldParams.setToExternal(reinterpret_cast<uint8_t*>(oldSessioMeta),
3222 get_camera_metadata_size(oldSessioMeta));
3223 newParams.setToExternal(reinterpret_cast<uint8_t*>(newSessioMeta),
3224 get_camera_metadata_size(newSessioMeta));
3225 hardware::camera::common::V1_0::Status callStatus;
3226 bool required;
3227 auto hidlCb = [&callStatus, &required] (hardware::camera::common::V1_0::Status s,
3228 bool requiredFlag) {
3229 callStatus = s;
3230 required = requiredFlag;
3231 };
3232 auto err = mHidlSession_3_5->isReconfigurationRequired(oldParams, newParams, hidlCb);
3233 oldSessionParams.unlock(oldSessioMeta);
3234 newSessionParams.unlock(newSessioMeta);
3235 if (err.isOk()) {
3236 switch (callStatus) {
3237 case hardware::camera::common::V1_0::Status::OK:
3238 ret = required;
3239 break;
3240 case hardware::camera::common::V1_0::Status::METHOD_NOT_SUPPORTED:
3241 mIsReconfigurationQuerySupported = false;
3242 ret = true;
3243 break;
3244 default:
3245 ALOGV("%s: Reconfiguration query failed: %d", __FUNCTION__, callStatus);
3246 ret = true;
3247 }
3248 } else {
3249 ALOGE("%s: Unexpected binder error: %s", __FUNCTION__, err.description().c_str());
3250 ret = true;
3251 }
3252 }
3253
3254 return ret;
3255}
3256
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003257status_t Camera3Device::HalInterface::configureStreams(const camera_metadata_t *sessionParams,
Emilian Peevf4816702020-04-03 15:44:51 -07003258 camera_stream_configuration *config, const std::vector<uint32_t>& bufferSizes) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003259 ATRACE_NAME("CameraHal::configureStreams");
3260 if (!valid()) return INVALID_OPERATION;
3261 status_t res = OK;
3262
Shuzhen Wang83bff122020-11-20 15:51:39 -08003263 if (config->input_is_multi_resolution && mHidlSession_3_7 == nullptr) {
3264 ALOGE("%s: Camera device doesn't support multi-resolution input stream", __FUNCTION__);
3265 return BAD_VALUE;
3266 }
3267
Emilian Peev31abd0a2017-05-11 18:37:46 +01003268 // Convert stream config to HIDL
3269 std::set<int> activeStreams;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003270 device::V3_2::StreamConfiguration requestedConfiguration3_2;
3271 device::V3_4::StreamConfiguration requestedConfiguration3_4;
Shuzhen Wang83bff122020-11-20 15:51:39 -08003272 device::V3_7::StreamConfiguration requestedConfiguration3_7;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003273 requestedConfiguration3_2.streams.resize(config->num_streams);
3274 requestedConfiguration3_4.streams.resize(config->num_streams);
Shuzhen Wang83bff122020-11-20 15:51:39 -08003275 requestedConfiguration3_7.streams.resize(config->num_streams);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003276 for (size_t i = 0; i < config->num_streams; i++) {
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003277 device::V3_2::Stream &dst3_2 = requestedConfiguration3_2.streams[i];
3278 device::V3_4::Stream &dst3_4 = requestedConfiguration3_4.streams[i];
Shuzhen Wang83bff122020-11-20 15:51:39 -08003279 device::V3_7::Stream &dst3_7 = requestedConfiguration3_7.streams[i];
Emilian Peevf4816702020-04-03 15:44:51 -07003280 camera3::camera_stream_t *src = config->streams[i];
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003281
Emilian Peev31abd0a2017-05-11 18:37:46 +01003282 Camera3Stream* cam3stream = Camera3Stream::cast(src);
3283 cam3stream->setBufferFreedListener(this);
3284 int streamId = cam3stream->getId();
3285 StreamType streamType;
3286 switch (src->stream_type) {
Emilian Peevf4816702020-04-03 15:44:51 -07003287 case CAMERA_STREAM_OUTPUT:
Emilian Peev31abd0a2017-05-11 18:37:46 +01003288 streamType = StreamType::OUTPUT;
3289 break;
Emilian Peevf4816702020-04-03 15:44:51 -07003290 case CAMERA_STREAM_INPUT:
Emilian Peev31abd0a2017-05-11 18:37:46 +01003291 streamType = StreamType::INPUT;
3292 break;
3293 default:
3294 ALOGE("%s: Stream %d: Unsupported stream type %d",
3295 __FUNCTION__, streamId, config->streams[i]->stream_type);
3296 return BAD_VALUE;
3297 }
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003298 dst3_2.id = streamId;
3299 dst3_2.streamType = streamType;
3300 dst3_2.width = src->width;
3301 dst3_2.height = src->height;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003302 dst3_2.usage = mapToConsumerUsage(cam3stream->getUsage());
Emilian Peevf4816702020-04-03 15:44:51 -07003303 dst3_2.rotation = mapToStreamRotation((camera_stream_rotation_t) src->rotation);
Shuzhen Wang92653952019-05-07 15:11:43 -07003304 // For HidlSession version 3.5 or newer, the format and dataSpace sent
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08003305 // to HAL are original, not the overridden ones.
Shuzhen Wang92653952019-05-07 15:11:43 -07003306 if (mHidlSession_3_5 != nullptr) {
3307 dst3_2.format = mapToPixelFormat(cam3stream->isFormatOverridden() ?
3308 cam3stream->getOriginalFormat() : src->format);
3309 dst3_2.dataSpace = mapToHidlDataspace(cam3stream->isDataSpaceOverridden() ?
3310 cam3stream->getOriginalDataSpace() : src->data_space);
3311 } else {
3312 dst3_2.format = mapToPixelFormat(src->format);
3313 dst3_2.dataSpace = mapToHidlDataspace(src->data_space);
3314 }
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003315 dst3_4.v3_2 = dst3_2;
Emilian Peev192ee832018-01-31 14:46:47 +00003316 dst3_4.bufferSize = bufferSizes[i];
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003317 if (src->physical_camera_id != nullptr) {
3318 dst3_4.physicalCameraId = src->physical_camera_id;
3319 }
Shuzhen Wang83bff122020-11-20 15:51:39 -08003320 dst3_7.v3_4 = dst3_4;
3321 dst3_7.groupId = cam3stream->getHalStreamGroupId();
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08003322 dst3_7.sensorPixelModesUsed.resize(src->sensor_pixel_modes_used.size());
3323 size_t j = 0;
3324 for (int mode : src->sensor_pixel_modes_used) {
3325 dst3_7.sensorPixelModesUsed[j++] =
3326 static_cast<CameraMetadataEnumAndroidSensorPixelMode>(mode);
3327 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003328 activeStreams.insert(streamId);
3329 // Create Buffer ID map if necessary
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003330 mBufferRecords.tryCreateBufferCache(streamId);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003331 }
3332 // remove BufferIdMap for deleted streams
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003333 mBufferRecords.removeInactiveBufferCaches(activeStreams);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003334
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003335 StreamConfigurationMode operationMode;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003336 res = mapToStreamConfigurationMode(
Emilian Peevf4816702020-04-03 15:44:51 -07003337 (camera_stream_configuration_mode_t) config->operation_mode,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003338 /*out*/ &operationMode);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003339 if (res != OK) {
3340 return res;
3341 }
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003342 requestedConfiguration3_2.operationMode = operationMode;
3343 requestedConfiguration3_4.operationMode = operationMode;
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08003344 requestedConfiguration3_7.operationMode = operationMode;
3345 size_t sessionParamSize = get_camera_metadata_size(sessionParams);
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003346 requestedConfiguration3_4.sessionParams.setToExternal(
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003347 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(sessionParams)),
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08003348 sessionParamSize);
Shuzhen Wang83bff122020-11-20 15:51:39 -08003349 requestedConfiguration3_7.operationMode = operationMode;
3350 requestedConfiguration3_7.sessionParams.setToExternal(
3351 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(sessionParams)),
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08003352 sessionParamSize);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003353
Emilian Peev31abd0a2017-05-11 18:37:46 +01003354 // Invoke configureStreams
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003355 device::V3_3::HalStreamConfiguration finalConfiguration;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003356 device::V3_4::HalStreamConfiguration finalConfiguration3_4;
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003357 device::V3_6::HalStreamConfiguration finalConfiguration3_6;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003358 common::V1_0::Status status;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003359
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003360 auto configStream34Cb = [&status, &finalConfiguration3_4]
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003361 (common::V1_0::Status s, const device::V3_4::HalStreamConfiguration& halConfiguration) {
3362 finalConfiguration3_4 = halConfiguration;
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003363 status = s;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003364 };
3365
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003366 auto configStream36Cb = [&status, &finalConfiguration3_6]
3367 (common::V1_0::Status s, const device::V3_6::HalStreamConfiguration& halConfiguration) {
3368 finalConfiguration3_6 = halConfiguration;
3369 status = s;
3370 };
3371
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003372 auto postprocConfigStream34 = [&finalConfiguration, &finalConfiguration3_4]
3373 (hardware::Return<void>& err) -> status_t {
3374 if (!err.isOk()) {
3375 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3376 return DEAD_OBJECT;
3377 }
3378 finalConfiguration.streams.resize(finalConfiguration3_4.streams.size());
3379 for (size_t i = 0; i < finalConfiguration3_4.streams.size(); i++) {
3380 finalConfiguration.streams[i] = finalConfiguration3_4.streams[i].v3_3;
3381 }
3382 return OK;
3383 };
3384
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003385 auto postprocConfigStream36 = [&finalConfiguration, &finalConfiguration3_6]
3386 (hardware::Return<void>& err) -> status_t {
3387 if (!err.isOk()) {
3388 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3389 return DEAD_OBJECT;
3390 }
3391 finalConfiguration.streams.resize(finalConfiguration3_6.streams.size());
3392 for (size_t i = 0; i < finalConfiguration3_6.streams.size(); i++) {
3393 finalConfiguration.streams[i] = finalConfiguration3_6.streams[i].v3_4.v3_3;
3394 }
3395 return OK;
3396 };
3397
Shuzhen Wang92653952019-05-07 15:11:43 -07003398 // See which version of HAL we have
Shuzhen Wang83bff122020-11-20 15:51:39 -08003399 if (mHidlSession_3_7 != nullptr) {
3400 ALOGV("%s: v3.7 device found", __FUNCTION__);
3401 requestedConfiguration3_7.streamConfigCounter = mNextStreamConfigCounter++;
3402 requestedConfiguration3_7.multiResolutionInputImage = config->input_is_multi_resolution;
3403 auto err = mHidlSession_3_7->configureStreams_3_7(
3404 requestedConfiguration3_7, configStream36Cb);
3405 res = postprocConfigStream36(err);
3406 if (res != OK) {
3407 return res;
3408 }
3409 } else if (mHidlSession_3_6 != nullptr) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003410 ALOGV("%s: v3.6 device found", __FUNCTION__);
3411 device::V3_5::StreamConfiguration requestedConfiguration3_5;
3412 requestedConfiguration3_5.v3_4 = requestedConfiguration3_4;
3413 requestedConfiguration3_5.streamConfigCounter = mNextStreamConfigCounter++;
3414 auto err = mHidlSession_3_6->configureStreams_3_6(
3415 requestedConfiguration3_5, configStream36Cb);
3416 res = postprocConfigStream36(err);
3417 if (res != OK) {
3418 return res;
3419 }
3420 } else if (mHidlSession_3_5 != nullptr) {
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003421 ALOGV("%s: v3.5 device found", __FUNCTION__);
3422 device::V3_5::StreamConfiguration requestedConfiguration3_5;
3423 requestedConfiguration3_5.v3_4 = requestedConfiguration3_4;
3424 requestedConfiguration3_5.streamConfigCounter = mNextStreamConfigCounter++;
3425 auto err = mHidlSession_3_5->configureStreams_3_5(
3426 requestedConfiguration3_5, configStream34Cb);
3427 res = postprocConfigStream34(err);
3428 if (res != OK) {
3429 return res;
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003430 }
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003431 } else if (mHidlSession_3_4 != nullptr) {
3432 // We do; use v3.4 for the call
3433 ALOGV("%s: v3.4 device found", __FUNCTION__);
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003434 auto err = mHidlSession_3_4->configureStreams_3_4(
3435 requestedConfiguration3_4, configStream34Cb);
3436 res = postprocConfigStream34(err);
3437 if (res != OK) {
3438 return res;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003439 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003440 } else if (mHidlSession_3_3 != nullptr) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003441 // We do; use v3.3 for the call
3442 ALOGV("%s: v3.3 device found", __FUNCTION__);
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003443 auto err = mHidlSession_3_3->configureStreams_3_3(requestedConfiguration3_2,
Emilian Peev31abd0a2017-05-11 18:37:46 +01003444 [&status, &finalConfiguration]
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003445 (common::V1_0::Status s, const device::V3_3::HalStreamConfiguration& halConfiguration) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003446 finalConfiguration = halConfiguration;
3447 status = s;
3448 });
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003449 if (!err.isOk()) {
3450 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3451 return DEAD_OBJECT;
3452 }
3453 } else {
3454 // We don't; use v3.2 call and construct a v3.3 HalStreamConfiguration
3455 ALOGV("%s: v3.2 device found", __FUNCTION__);
3456 HalStreamConfiguration finalConfiguration_3_2;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003457 auto err = mHidlSession->configureStreams(requestedConfiguration3_2,
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003458 [&status, &finalConfiguration_3_2]
3459 (common::V1_0::Status s, const HalStreamConfiguration& halConfiguration) {
3460 finalConfiguration_3_2 = halConfiguration;
3461 status = s;
3462 });
3463 if (!err.isOk()) {
3464 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3465 return DEAD_OBJECT;
3466 }
3467 finalConfiguration.streams.resize(finalConfiguration_3_2.streams.size());
3468 for (size_t i = 0; i < finalConfiguration_3_2.streams.size(); i++) {
3469 finalConfiguration.streams[i].v3_2 = finalConfiguration_3_2.streams[i];
3470 finalConfiguration.streams[i].overrideDataSpace =
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003471 requestedConfiguration3_2.streams[i].dataSpace;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003472 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003473 }
3474
3475 if (status != common::V1_0::Status::OK ) {
3476 return CameraProviderManager::mapToStatusT(status);
3477 }
3478
3479 // And convert output stream configuration from HIDL
3480
3481 for (size_t i = 0; i < config->num_streams; i++) {
Emilian Peevf4816702020-04-03 15:44:51 -07003482 camera3::camera_stream_t *dst = config->streams[i];
Emilian Peev31abd0a2017-05-11 18:37:46 +01003483 int streamId = Camera3Stream::cast(dst)->getId();
3484
3485 // Start scan at i, with the assumption that the stream order matches
3486 size_t realIdx = i;
3487 bool found = false;
Eino-Ville Talvala370875f2019-04-12 12:40:27 -07003488 size_t halStreamCount = finalConfiguration.streams.size();
3489 for (size_t idx = 0; idx < halStreamCount; idx++) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003490 if (finalConfiguration.streams[realIdx].v3_2.id == streamId) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003491 found = true;
3492 break;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003493 }
Eino-Ville Talvala370875f2019-04-12 12:40:27 -07003494 realIdx = (realIdx >= halStreamCount - 1) ? 0 : realIdx + 1;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003495 }
3496 if (!found) {
3497 ALOGE("%s: Stream %d not found in stream configuration response from HAL",
3498 __FUNCTION__, streamId);
3499 return INVALID_OPERATION;
3500 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003501 device::V3_3::HalStream &src = finalConfiguration.streams[realIdx];
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003502 device::V3_6::HalStream &src_36 = finalConfiguration3_6.streams[realIdx];
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003503
Emilian Peev710c1422017-08-30 11:19:38 +01003504 Camera3Stream* dstStream = Camera3Stream::cast(dst);
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003505 int overrideFormat = mapToFrameworkFormat(src.v3_2.overrideFormat);
3506 android_dataspace overrideDataSpace = mapToFrameworkDataspace(src.overrideDataSpace);
3507
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003508 if (mHidlSession_3_6 != nullptr) {
3509 dstStream->setOfflineProcessingSupport(src_36.supportOffline);
3510 }
3511
Yin-Chia Yeh90667662019-07-01 15:45:00 -07003512 if (dstStream->getOriginalFormat() != HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
Shuzhen Wang92653952019-05-07 15:11:43 -07003513 dstStream->setFormatOverride(false);
3514 dstStream->setDataSpaceOverride(false);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003515 if (dst->format != overrideFormat) {
3516 ALOGE("%s: Stream %d: Format override not allowed for format 0x%x", __FUNCTION__,
3517 streamId, dst->format);
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003518 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003519 if (dst->data_space != overrideDataSpace) {
3520 ALOGE("%s: Stream %d: DataSpace override not allowed for format 0x%x", __FUNCTION__,
3521 streamId, dst->format);
3522 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003523 } else {
Shuzhen Wang92653952019-05-07 15:11:43 -07003524 bool needFormatOverride =
3525 requestedConfiguration3_2.streams[i].format != src.v3_2.overrideFormat;
3526 bool needDataspaceOverride =
3527 requestedConfiguration3_2.streams[i].dataSpace != src.overrideDataSpace;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003528 // Override allowed with IMPLEMENTATION_DEFINED
Shuzhen Wang92653952019-05-07 15:11:43 -07003529 dstStream->setFormatOverride(needFormatOverride);
3530 dstStream->setDataSpaceOverride(needDataspaceOverride);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003531 dst->format = overrideFormat;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003532 dst->data_space = overrideDataSpace;
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003533 }
3534
Emilian Peevf4816702020-04-03 15:44:51 -07003535 if (dst->stream_type == CAMERA_STREAM_INPUT) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003536 if (src.v3_2.producerUsage != 0) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003537 ALOGE("%s: Stream %d: INPUT streams must have 0 for producer usage",
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003538 __FUNCTION__, streamId);
3539 return INVALID_OPERATION;
3540 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003541 dstStream->setUsage(
3542 mapConsumerToFrameworkUsage(src.v3_2.consumerUsage));
Emilian Peev31abd0a2017-05-11 18:37:46 +01003543 } else {
3544 // OUTPUT
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003545 if (src.v3_2.consumerUsage != 0) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003546 ALOGE("%s: Stream %d: OUTPUT streams must have 0 for consumer usage",
3547 __FUNCTION__, streamId);
3548 return INVALID_OPERATION;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003549 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003550 dstStream->setUsage(
3551 mapProducerToFrameworkUsage(src.v3_2.producerUsage));
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003552 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003553 dst->max_buffers = src.v3_2.maxBuffers;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003554 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003555
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003556 return res;
3557}
3558
Cliff Wuc2ad9c82021-04-21 00:58:58 +08003559status_t Camera3Device::HalInterface::configureInjectedStreams(
3560 const camera_metadata_t* sessionParams, camera_stream_configuration* config,
3561 const std::vector<uint32_t>& bufferSizes,
3562 const CameraMetadata& cameraCharacteristics) {
3563 ATRACE_NAME("InjectionCameraHal::configureStreams");
3564 if (!valid()) return INVALID_OPERATION;
3565 status_t res = OK;
3566
3567 if (config->input_is_multi_resolution) {
3568 ALOGE("%s: Injection camera device doesn't support multi-resolution input "
3569 "stream", __FUNCTION__);
3570 return BAD_VALUE;
3571 }
3572
3573 // Convert stream config to HIDL
3574 std::set<int> activeStreams;
3575 device::V3_2::StreamConfiguration requestedConfiguration3_2;
3576 device::V3_4::StreamConfiguration requestedConfiguration3_4;
3577 device::V3_7::StreamConfiguration requestedConfiguration3_7;
3578 requestedConfiguration3_2.streams.resize(config->num_streams);
3579 requestedConfiguration3_4.streams.resize(config->num_streams);
3580 requestedConfiguration3_7.streams.resize(config->num_streams);
3581 for (size_t i = 0; i < config->num_streams; i++) {
3582 device::V3_2::Stream& dst3_2 = requestedConfiguration3_2.streams[i];
3583 device::V3_4::Stream& dst3_4 = requestedConfiguration3_4.streams[i];
3584 device::V3_7::Stream& dst3_7 = requestedConfiguration3_7.streams[i];
3585 camera3::camera_stream_t* src = config->streams[i];
3586
3587 Camera3Stream* cam3stream = Camera3Stream::cast(src);
3588 cam3stream->setBufferFreedListener(this);
3589 int streamId = cam3stream->getId();
3590 StreamType streamType;
3591 switch (src->stream_type) {
3592 case CAMERA_STREAM_OUTPUT:
3593 streamType = StreamType::OUTPUT;
3594 break;
3595 case CAMERA_STREAM_INPUT:
3596 streamType = StreamType::INPUT;
3597 break;
3598 default:
3599 ALOGE("%s: Stream %d: Unsupported stream type %d", __FUNCTION__,
3600 streamId, config->streams[i]->stream_type);
3601 return BAD_VALUE;
3602 }
3603 dst3_2.id = streamId;
3604 dst3_2.streamType = streamType;
3605 dst3_2.width = src->width;
3606 dst3_2.height = src->height;
3607 dst3_2.usage = mapToConsumerUsage(cam3stream->getUsage());
3608 dst3_2.rotation =
3609 mapToStreamRotation((camera_stream_rotation_t)src->rotation);
3610 // For HidlSession version 3.5 or newer, the format and dataSpace sent
3611 // to HAL are original, not the overridden ones.
3612 if (mHidlSession_3_5 != nullptr) {
3613 dst3_2.format = mapToPixelFormat(cam3stream->isFormatOverridden()
3614 ? cam3stream->getOriginalFormat()
3615 : src->format);
3616 dst3_2.dataSpace =
3617 mapToHidlDataspace(cam3stream->isDataSpaceOverridden()
3618 ? cam3stream->getOriginalDataSpace()
3619 : src->data_space);
3620 } else {
3621 dst3_2.format = mapToPixelFormat(src->format);
3622 dst3_2.dataSpace = mapToHidlDataspace(src->data_space);
3623 }
3624 dst3_4.v3_2 = dst3_2;
3625 dst3_4.bufferSize = bufferSizes[i];
3626 if (src->physical_camera_id != nullptr) {
3627 dst3_4.physicalCameraId = src->physical_camera_id;
3628 }
3629 dst3_7.v3_4 = dst3_4;
3630 dst3_7.groupId = cam3stream->getHalStreamGroupId();
3631 dst3_7.sensorPixelModesUsed.resize(src->sensor_pixel_modes_used.size());
3632 size_t j = 0;
3633 for (int mode : src->sensor_pixel_modes_used) {
3634 dst3_7.sensorPixelModesUsed[j++] =
3635 static_cast<CameraMetadataEnumAndroidSensorPixelMode>(mode);
3636 }
3637 activeStreams.insert(streamId);
3638 // Create Buffer ID map if necessary
3639 mBufferRecords.tryCreateBufferCache(streamId);
3640 }
3641 // remove BufferIdMap for deleted streams
3642 mBufferRecords.removeInactiveBufferCaches(activeStreams);
3643
3644 StreamConfigurationMode operationMode;
3645 res = mapToStreamConfigurationMode(
3646 (camera_stream_configuration_mode_t)config->operation_mode,
3647 /*out*/ &operationMode);
3648 if (res != OK) {
3649 return res;
3650 }
3651 requestedConfiguration3_7.operationMode = operationMode;
3652 size_t sessionParamSize = get_camera_metadata_size(sessionParams);
3653 requestedConfiguration3_7.operationMode = operationMode;
3654 requestedConfiguration3_7.sessionParams.setToExternal(
3655 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(sessionParams)),
3656 sessionParamSize);
3657
3658 // See which version of HAL we have
3659 if (mHidlSession_3_7 != nullptr) {
3660 requestedConfiguration3_7.streamConfigCounter = mNextStreamConfigCounter++;
3661 requestedConfiguration3_7.multiResolutionInputImage =
3662 config->input_is_multi_resolution;
3663
3664 const camera_metadata_t* rawMetadata = cameraCharacteristics.getAndLock();
3665 ::android::hardware::camera::device::V3_2::CameraMetadata hidlChars = {};
3666 hidlChars.setToExternal(
3667 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(rawMetadata)),
3668 get_camera_metadata_size(rawMetadata));
3669 cameraCharacteristics.unlock(rawMetadata);
3670
3671 sp<hardware::camera::device::V3_7::ICameraInjectionSession>
3672 hidlInjectionSession_3_7;
3673 auto castInjectionResult_3_7 =
3674 device::V3_7::ICameraInjectionSession::castFrom(mHidlSession_3_7);
3675 if (castInjectionResult_3_7.isOk()) {
3676 hidlInjectionSession_3_7 = castInjectionResult_3_7;
3677 } else {
3678 ALOGE("%s: Transaction error: %s", __FUNCTION__,
3679 castInjectionResult_3_7.description().c_str());
3680 return DEAD_OBJECT;
3681 }
3682
3683 auto err = hidlInjectionSession_3_7->configureInjectionStreams(
3684 requestedConfiguration3_7, hidlChars);
3685 if (!err.isOk()) {
3686 ALOGE("%s: Transaction error: %s", __FUNCTION__,
3687 err.description().c_str());
3688 return DEAD_OBJECT;
3689 }
3690 } else {
3691 ALOGE("%s: mHidlSession_3_7 does not exist, the lowest version of injection "
3692 "session is 3.7", __FUNCTION__);
3693 return DEAD_OBJECT;
3694 }
3695
3696 return res;
3697}
3698
Emilian Peevf4816702020-04-03 15:44:51 -07003699status_t Camera3Device::HalInterface::wrapAsHidlRequest(camera_capture_request_t* request,
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003700 /*out*/device::V3_2::CaptureRequest* captureRequest,
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003701 /*out*/std::vector<native_handle_t*>* handlesCreated,
3702 /*out*/std::vector<std::pair<int32_t, int32_t>>* inflightBuffers) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003703 ATRACE_CALL();
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003704 if (captureRequest == nullptr || handlesCreated == nullptr || inflightBuffers == nullptr) {
3705 ALOGE("%s: captureRequest (%p), handlesCreated (%p), and inflightBuffers(%p) "
3706 "must not be null", __FUNCTION__, captureRequest, handlesCreated, inflightBuffers);
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003707 return BAD_VALUE;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003708 }
3709
3710 captureRequest->frameNumber = request->frame_number;
Yifan Hongf79b5542017-04-11 14:44:25 -07003711
3712 captureRequest->fmqSettingsSize = 0;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003713
3714 {
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003715 if (request->input_buffer != nullptr) {
3716 int32_t streamId = Camera3Stream::cast(request->input_buffer->stream)->getId();
3717 buffer_handle_t buf = *(request->input_buffer->buffer);
3718 auto pair = getBufferId(buf, streamId);
3719 bool isNewBuffer = pair.first;
3720 uint64_t bufferId = pair.second;
3721 captureRequest->inputBuffer.streamId = streamId;
3722 captureRequest->inputBuffer.bufferId = bufferId;
3723 captureRequest->inputBuffer.buffer = (isNewBuffer) ? buf : nullptr;
3724 captureRequest->inputBuffer.status = BufferStatus::OK;
3725 native_handle_t *acquireFence = nullptr;
3726 if (request->input_buffer->acquire_fence != -1) {
3727 acquireFence = native_handle_create(1,0);
3728 acquireFence->data[0] = request->input_buffer->acquire_fence;
3729 handlesCreated->push_back(acquireFence);
3730 }
3731 captureRequest->inputBuffer.acquireFence = acquireFence;
3732 captureRequest->inputBuffer.releaseFence = nullptr;
3733
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003734 mBufferRecords.pushInflightBuffer(captureRequest->frameNumber, streamId,
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003735 request->input_buffer->buffer);
3736 inflightBuffers->push_back(std::make_pair(captureRequest->frameNumber, streamId));
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003737 } else {
3738 captureRequest->inputBuffer.streamId = -1;
3739 captureRequest->inputBuffer.bufferId = BUFFER_ID_NO_BUFFER;
3740 }
3741
3742 captureRequest->outputBuffers.resize(request->num_output_buffers);
3743 for (size_t i = 0; i < request->num_output_buffers; i++) {
Emilian Peevf4816702020-04-03 15:44:51 -07003744 const camera_stream_buffer_t *src = request->output_buffers + i;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003745 StreamBuffer &dst = captureRequest->outputBuffers[i];
3746 int32_t streamId = Camera3Stream::cast(src->stream)->getId();
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003747 if (src->buffer != nullptr) {
3748 buffer_handle_t buf = *(src->buffer);
3749 auto pair = getBufferId(buf, streamId);
3750 bool isNewBuffer = pair.first;
3751 dst.bufferId = pair.second;
3752 dst.buffer = isNewBuffer ? buf : nullptr;
3753 native_handle_t *acquireFence = nullptr;
3754 if (src->acquire_fence != -1) {
3755 acquireFence = native_handle_create(1,0);
3756 acquireFence->data[0] = src->acquire_fence;
3757 handlesCreated->push_back(acquireFence);
3758 }
3759 dst.acquireFence = acquireFence;
3760 } else if (mUseHalBufManager) {
3761 // HAL buffer management path
3762 dst.bufferId = BUFFER_ID_NO_BUFFER;
3763 dst.buffer = nullptr;
3764 dst.acquireFence = nullptr;
3765 } else {
3766 ALOGE("%s: cannot send a null buffer in capture request!", __FUNCTION__);
3767 return BAD_VALUE;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003768 }
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003769 dst.streamId = streamId;
3770 dst.status = BufferStatus::OK;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003771 dst.releaseFence = nullptr;
3772
Yin-Chia Yeh5f840f82019-03-05 11:59:04 -08003773 // Output buffers are empty when using HAL buffer manager
3774 if (!mUseHalBufManager) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003775 mBufferRecords.pushInflightBuffer(
3776 captureRequest->frameNumber, streamId, src->buffer);
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003777 inflightBuffers->push_back(std::make_pair(captureRequest->frameNumber, streamId));
Yin-Chia Yeh5f840f82019-03-05 11:59:04 -08003778 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003779 }
3780 }
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003781 return OK;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003782}
3783
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003784void Camera3Device::HalInterface::cleanupNativeHandles(
3785 std::vector<native_handle_t*> *handles, bool closeFd) {
3786 if (handles == nullptr) {
3787 return;
3788 }
3789 if (closeFd) {
3790 for (auto& handle : *handles) {
3791 native_handle_close(handle);
3792 }
3793 }
3794 for (auto& handle : *handles) {
3795 native_handle_delete(handle);
3796 }
3797 handles->clear();
3798 return;
3799}
3800
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003801status_t Camera3Device::HalInterface::processBatchCaptureRequests(
Emilian Peevf4816702020-04-03 15:44:51 -07003802 std::vector<camera_capture_request_t*>& requests,/*out*/uint32_t* numRequestProcessed) {
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003803 ATRACE_NAME("CameraHal::processBatchCaptureRequests");
3804 if (!valid()) return INVALID_OPERATION;
3805
Emilian Peevaebbe412018-01-15 13:53:24 +00003806 sp<device::V3_4::ICameraDeviceSession> hidlSession_3_4;
Shuzhen Wang83bff122020-11-20 15:51:39 -08003807 sp<device::V3_7::ICameraDeviceSession> hidlSession_3_7;
3808 auto castResult_3_7 = device::V3_7::ICameraDeviceSession::castFrom(mHidlSession);
3809 if (castResult_3_7.isOk()) {
3810 hidlSession_3_7 = castResult_3_7;
3811 }
Emilian Peevaebbe412018-01-15 13:53:24 +00003812 auto castResult_3_4 = device::V3_4::ICameraDeviceSession::castFrom(mHidlSession);
3813 if (castResult_3_4.isOk()) {
3814 hidlSession_3_4 = castResult_3_4;
3815 }
3816
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003817 hardware::hidl_vec<device::V3_2::CaptureRequest> captureRequests;
Emilian Peevaebbe412018-01-15 13:53:24 +00003818 hardware::hidl_vec<device::V3_4::CaptureRequest> captureRequests_3_4;
Shuzhen Wang83bff122020-11-20 15:51:39 -08003819 hardware::hidl_vec<device::V3_7::CaptureRequest> captureRequests_3_7;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003820 size_t batchSize = requests.size();
Shuzhen Wang83bff122020-11-20 15:51:39 -08003821 if (hidlSession_3_7 != nullptr) {
3822 captureRequests_3_7.resize(batchSize);
3823 } else if (hidlSession_3_4 != nullptr) {
Emilian Peevaebbe412018-01-15 13:53:24 +00003824 captureRequests_3_4.resize(batchSize);
3825 } else {
3826 captureRequests.resize(batchSize);
3827 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003828 std::vector<native_handle_t*> handlesCreated;
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003829 std::vector<std::pair<int32_t, int32_t>> inflightBuffers;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003830
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003831 status_t res = OK;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003832 for (size_t i = 0; i < batchSize; i++) {
Shuzhen Wang83bff122020-11-20 15:51:39 -08003833 if (hidlSession_3_7 != nullptr) {
3834 res = wrapAsHidlRequest(requests[i], /*out*/&captureRequests_3_7[i].v3_4.v3_2,
3835 /*out*/&handlesCreated, /*out*/&inflightBuffers);
3836 } else if (hidlSession_3_4 != nullptr) {
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003837 res = wrapAsHidlRequest(requests[i], /*out*/&captureRequests_3_4[i].v3_2,
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003838 /*out*/&handlesCreated, /*out*/&inflightBuffers);
Emilian Peevaebbe412018-01-15 13:53:24 +00003839 } else {
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003840 res = wrapAsHidlRequest(requests[i], /*out*/&captureRequests[i],
3841 /*out*/&handlesCreated, /*out*/&inflightBuffers);
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003842 }
3843 if (res != OK) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003844 mBufferRecords.popInflightBuffers(inflightBuffers);
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003845 cleanupNativeHandles(&handlesCreated);
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003846 return res;
Emilian Peevaebbe412018-01-15 13:53:24 +00003847 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003848 }
3849
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003850 std::vector<device::V3_2::BufferCache> cachesToRemove;
3851 {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003852 std::lock_guard<std::mutex> lock(mFreedBuffersLock);
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003853 for (auto& pair : mFreedBuffers) {
3854 // The stream might have been removed since onBufferFreed
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003855 if (mBufferRecords.isStreamCached(pair.first)) {
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003856 cachesToRemove.push_back({pair.first, pair.second});
3857 }
3858 }
3859 mFreedBuffers.clear();
3860 }
3861
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003862 common::V1_0::Status status = common::V1_0::Status::INTERNAL_ERROR;
3863 *numRequestProcessed = 0;
Yifan Hongf79b5542017-04-11 14:44:25 -07003864
3865 // Write metadata to FMQ.
3866 for (size_t i = 0; i < batchSize; i++) {
Emilian Peevf4816702020-04-03 15:44:51 -07003867 camera_capture_request_t* request = requests[i];
Emilian Peevaebbe412018-01-15 13:53:24 +00003868 device::V3_2::CaptureRequest* captureRequest;
Shuzhen Wang83bff122020-11-20 15:51:39 -08003869 if (hidlSession_3_7 != nullptr) {
3870 captureRequest = &captureRequests_3_7[i].v3_4.v3_2;
3871 } else if (hidlSession_3_4 != nullptr) {
Emilian Peevaebbe412018-01-15 13:53:24 +00003872 captureRequest = &captureRequests_3_4[i].v3_2;
3873 } else {
3874 captureRequest = &captureRequests[i];
3875 }
Yifan Hongf79b5542017-04-11 14:44:25 -07003876
3877 if (request->settings != nullptr) {
3878 size_t settingsSize = get_camera_metadata_size(request->settings);
3879 if (mRequestMetadataQueue != nullptr && mRequestMetadataQueue->write(
3880 reinterpret_cast<const uint8_t*>(request->settings), settingsSize)) {
3881 captureRequest->settings.resize(0);
3882 captureRequest->fmqSettingsSize = settingsSize;
3883 } else {
3884 if (mRequestMetadataQueue != nullptr) {
3885 ALOGW("%s: couldn't utilize fmq, fallback to hwbinder", __FUNCTION__);
3886 }
3887 captureRequest->settings.setToExternal(
3888 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(request->settings)),
3889 get_camera_metadata_size(request->settings));
3890 captureRequest->fmqSettingsSize = 0u;
3891 }
3892 } else {
3893 // A null request settings maps to a size-0 CameraMetadata
3894 captureRequest->settings.resize(0);
3895 captureRequest->fmqSettingsSize = 0u;
3896 }
Emilian Peevaebbe412018-01-15 13:53:24 +00003897
Shuzhen Wang83bff122020-11-20 15:51:39 -08003898 // hidl session 3.7 specific handling.
3899 if (hidlSession_3_7 != nullptr) {
3900 captureRequests_3_7[i].inputWidth = request->input_width;
3901 captureRequests_3_7[i].inputHeight = request->input_height;
3902 }
3903
3904 // hidl session 3.7 and 3.4 specific handling.
3905 if (hidlSession_3_7 != nullptr || hidlSession_3_4 != nullptr) {
3906 hardware::hidl_vec<device::V3_4::PhysicalCameraSetting>& physicalCameraSettings =
3907 (hidlSession_3_7 != nullptr) ?
3908 captureRequests_3_7[i].v3_4.physicalCameraSettings :
3909 captureRequests_3_4[i].physicalCameraSettings;
3910 physicalCameraSettings.resize(request->num_physcam_settings);
Emilian Peevaebbe412018-01-15 13:53:24 +00003911 for (size_t j = 0; j < request->num_physcam_settings; j++) {
Emilian Peev00420d22018-02-05 21:33:13 +00003912 if (request->physcam_settings != nullptr) {
3913 size_t settingsSize = get_camera_metadata_size(request->physcam_settings[j]);
3914 if (mRequestMetadataQueue != nullptr && mRequestMetadataQueue->write(
3915 reinterpret_cast<const uint8_t*>(request->physcam_settings[j]),
3916 settingsSize)) {
Shuzhen Wang83bff122020-11-20 15:51:39 -08003917 physicalCameraSettings[j].settings.resize(0);
3918 physicalCameraSettings[j].fmqSettingsSize = settingsSize;
Emilian Peev00420d22018-02-05 21:33:13 +00003919 } else {
3920 if (mRequestMetadataQueue != nullptr) {
3921 ALOGW("%s: couldn't utilize fmq, fallback to hwbinder", __FUNCTION__);
3922 }
Shuzhen Wang83bff122020-11-20 15:51:39 -08003923 physicalCameraSettings[j].settings.setToExternal(
Emilian Peev00420d22018-02-05 21:33:13 +00003924 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(
3925 request->physcam_settings[j])),
3926 get_camera_metadata_size(request->physcam_settings[j]));
Shuzhen Wang83bff122020-11-20 15:51:39 -08003927 physicalCameraSettings[j].fmqSettingsSize = 0u;
Emilian Peevaebbe412018-01-15 13:53:24 +00003928 }
Emilian Peev00420d22018-02-05 21:33:13 +00003929 } else {
Yin-Chia Yeha2849702021-03-10 10:11:33 -08003930 physicalCameraSettings[j].fmqSettingsSize = 0u;
3931 physicalCameraSettings[j].settings.resize(0);
Emilian Peevaebbe412018-01-15 13:53:24 +00003932 }
Shuzhen Wang83bff122020-11-20 15:51:39 -08003933 physicalCameraSettings[j].physicalCameraId = request->physcam_id[j];
Emilian Peevaebbe412018-01-15 13:53:24 +00003934 }
3935 }
Yifan Hongf79b5542017-04-11 14:44:25 -07003936 }
Emilian Peevaebbe412018-01-15 13:53:24 +00003937
3938 hardware::details::return_status err;
Jayant Chowdharyc8d581e2018-07-16 14:46:23 -07003939 auto resultCallback =
3940 [&status, &numRequestProcessed] (auto s, uint32_t n) {
3941 status = s;
3942 *numRequestProcessed = n;
3943 };
Shuzhen Wang83bff122020-11-20 15:51:39 -08003944 if (hidlSession_3_7 != nullptr) {
3945 err = hidlSession_3_7->processCaptureRequest_3_7(captureRequests_3_7, cachesToRemove,
3946 resultCallback);
3947 } else if (hidlSession_3_4 != nullptr) {
Emilian Peevaebbe412018-01-15 13:53:24 +00003948 err = hidlSession_3_4->processCaptureRequest_3_4(captureRequests_3_4, cachesToRemove,
Jayant Chowdharyc8d581e2018-07-16 14:46:23 -07003949 resultCallback);
Emilian Peevaebbe412018-01-15 13:53:24 +00003950 } else {
3951 err = mHidlSession->processCaptureRequest(captureRequests, cachesToRemove,
Jayant Chowdharyc8d581e2018-07-16 14:46:23 -07003952 resultCallback);
Emilian Peevaebbe412018-01-15 13:53:24 +00003953 }
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -07003954 if (!err.isOk()) {
3955 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003956 status = common::V1_0::Status::CAMERA_DISCONNECTED;
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -07003957 }
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003958
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003959 if (status == common::V1_0::Status::OK && *numRequestProcessed != batchSize) {
3960 ALOGE("%s: processCaptureRequest returns OK but processed %d/%zu requests",
3961 __FUNCTION__, *numRequestProcessed, batchSize);
3962 status = common::V1_0::Status::INTERNAL_ERROR;
3963 }
3964
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003965 res = CameraProviderManager::mapToStatusT(status);
3966 if (res == OK) {
3967 if (mHidlSession->isRemote()) {
3968 // Only close acquire fence FDs when the HIDL transaction succeeds (so the FDs have been
3969 // sent to camera HAL processes)
3970 cleanupNativeHandles(&handlesCreated, /*closeFd*/true);
3971 } else {
3972 // In passthrough mode the FDs are now owned by HAL
3973 cleanupNativeHandles(&handlesCreated);
3974 }
3975 } else {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003976 mBufferRecords.popInflightBuffers(inflightBuffers);
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003977 cleanupNativeHandles(&handlesCreated);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003978 }
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003979 return res;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003980}
3981
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003982status_t Camera3Device::HalInterface::flush() {
3983 ATRACE_NAME("CameraHal::flush");
3984 if (!valid()) return INVALID_OPERATION;
3985 status_t res = OK;
3986
Emilian Peev31abd0a2017-05-11 18:37:46 +01003987 auto err = mHidlSession->flush();
3988 if (!err.isOk()) {
3989 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3990 res = DEAD_OBJECT;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003991 } else {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003992 res = CameraProviderManager::mapToStatusT(err);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003993 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003994
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003995 return res;
3996}
3997
Emilian Peev31abd0a2017-05-11 18:37:46 +01003998status_t Camera3Device::HalInterface::dump(int /*fd*/) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003999 ATRACE_NAME("CameraHal::dump");
4000 if (!valid()) return INVALID_OPERATION;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004001
Emilian Peev31abd0a2017-05-11 18:37:46 +01004002 // Handled by CameraProviderManager::dump
4003
4004 return OK;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004005}
4006
4007status_t Camera3Device::HalInterface::close() {
4008 ATRACE_NAME("CameraHal::close()");
4009 if (!valid()) return INVALID_OPERATION;
4010 status_t res = OK;
4011
Emilian Peev31abd0a2017-05-11 18:37:46 +01004012 auto err = mHidlSession->close();
4013 // Interface will be dead shortly anyway, so don't log errors
4014 if (!err.isOk()) {
4015 res = DEAD_OBJECT;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004016 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01004017
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004018 return res;
4019}
4020
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004021void Camera3Device::HalInterface::signalPipelineDrain(const std::vector<int>& streamIds) {
4022 ATRACE_NAME("CameraHal::signalPipelineDrain");
4023 if (!valid() || mHidlSession_3_5 == nullptr) {
4024 ALOGE("%s called on invalid camera!", __FUNCTION__);
4025 return;
4026 }
4027
Yin-Chia Yehc300a072019-02-13 14:56:57 -08004028 auto err = mHidlSession_3_5->signalStreamFlush(streamIds, mNextStreamConfigCounter - 1);
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004029 if (!err.isOk()) {
4030 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
4031 return;
4032 }
4033}
4034
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004035status_t Camera3Device::HalInterface::switchToOffline(
4036 const std::vector<int32_t>& streamsToKeep,
4037 /*out*/hardware::camera::device::V3_6::CameraOfflineSessionInfo* offlineSessionInfo,
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004038 /*out*/sp<hardware::camera::device::V3_6::ICameraOfflineSession>* offlineSession,
4039 /*out*/camera3::BufferRecords* bufferRecords) {
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004040 ATRACE_NAME("CameraHal::switchToOffline");
4041 if (!valid() || mHidlSession_3_6 == nullptr) {
4042 ALOGE("%s called on invalid camera!", __FUNCTION__);
4043 return INVALID_OPERATION;
4044 }
4045
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004046 if (offlineSessionInfo == nullptr || offlineSession == nullptr || bufferRecords == nullptr) {
4047 ALOGE("%s: output arguments must not be null!", __FUNCTION__);
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004048 return INVALID_OPERATION;
4049 }
4050
4051 common::V1_0::Status status = common::V1_0::Status::INTERNAL_ERROR;
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004052 auto resultCallback =
4053 [&status, &offlineSessionInfo, &offlineSession] (auto s, auto info, auto session) {
4054 status = s;
4055 *offlineSessionInfo = info;
4056 *offlineSession = session;
4057 };
4058 auto err = mHidlSession_3_6->switchToOffline(streamsToKeep, resultCallback);
4059
4060 if (!err.isOk()) {
4061 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
4062 return DEAD_OBJECT;
4063 }
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004064
4065 status_t ret = CameraProviderManager::mapToStatusT(status);
4066 if (ret != OK) {
4067 return ret;
4068 }
4069
4070 // TODO: assert no ongoing requestBuffer/returnBuffer call here
4071 // TODO: update RequestBufferStateMachine to block requestBuffer/returnBuffer once HAL
4072 // returns from switchToOffline.
4073
4074
4075 // Validate buffer caches
4076 std::vector<int32_t> streams;
4077 streams.reserve(offlineSessionInfo->offlineStreams.size());
4078 for (auto offlineStream : offlineSessionInfo->offlineStreams) {
4079 int32_t id = offlineStream.id;
4080 streams.push_back(id);
4081 // Verify buffer caches
4082 std::vector<uint64_t> bufIds(offlineStream.circulatingBufferIds.begin(),
4083 offlineStream.circulatingBufferIds.end());
4084 if (!verifyBufferIds(id, bufIds)) {
4085 ALOGE("%s: stream ID %d buffer cache records mismatch!", __FUNCTION__, id);
4086 return UNKNOWN_ERROR;
4087 }
4088 }
4089
4090 // Move buffer records
4091 bufferRecords->takeBufferCaches(mBufferRecords, streams);
4092 bufferRecords->takeInflightBufferMap(mBufferRecords);
4093 bufferRecords->takeRequestedBufferMap(mBufferRecords);
4094 return ret;
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004095}
4096
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07004097void Camera3Device::HalInterface::getInflightBufferKeys(
4098 std::vector<std::pair<int32_t, int32_t>>* out) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004099 mBufferRecords.getInflightBufferKeys(out);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07004100 return;
4101}
4102
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08004103void Camera3Device::HalInterface::getInflightRequestBufferKeys(
4104 std::vector<uint64_t>* out) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004105 mBufferRecords.getInflightRequestBufferKeys(out);
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08004106 return;
4107}
4108
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004109bool Camera3Device::HalInterface::verifyBufferIds(
4110 int32_t streamId, std::vector<uint64_t>& bufIds) {
4111 return mBufferRecords.verifyBufferIds(streamId, bufIds);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004112}
4113
4114status_t Camera3Device::HalInterface::popInflightBuffer(
Yin-Chia Yehf4650602017-01-10 13:13:39 -08004115 int32_t frameNumber, int32_t streamId,
4116 /*out*/ buffer_handle_t **buffer) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004117 return mBufferRecords.popInflightBuffer(frameNumber, streamId, buffer);
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07004118}
4119
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004120status_t Camera3Device::HalInterface::pushInflightRequestBuffer(
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08004121 uint64_t bufferId, buffer_handle_t* buf, int32_t streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004122 return mBufferRecords.pushInflightRequestBuffer(bufferId, buf, streamId);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004123}
4124
4125// Find and pop a buffer_handle_t based on bufferId
4126status_t Camera3Device::HalInterface::popInflightRequestBuffer(
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08004127 uint64_t bufferId,
4128 /*out*/ buffer_handle_t** buffer,
4129 /*optional out*/ int32_t* streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004130 return mBufferRecords.popInflightRequestBuffer(bufferId, buffer, streamId);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004131}
4132
Yin-Chia Yeh77327052017-01-09 18:23:07 -08004133std::pair<bool, uint64_t> Camera3Device::HalInterface::getBufferId(
4134 const buffer_handle_t& buf, int streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004135 return mBufferRecords.getBufferId(buf, streamId);
Yin-Chia Yeh77327052017-01-09 18:23:07 -08004136}
4137
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07004138void Camera3Device::HalInterface::onBufferFreed(
4139 int streamId, const native_handle_t* handle) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004140 uint32_t bufferId = mBufferRecords.removeOneBufferCache(streamId, handle);
4141 std::lock_guard<std::mutex> lock(mFreedBuffersLock);
4142 if (bufferId != BUFFER_ID_NO_BUFFER) {
4143 mFreedBuffers.push_back(std::make_pair(streamId, bufferId));
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07004144 }
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07004145}
4146
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07004147void Camera3Device::HalInterface::onStreamReConfigured(int streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004148 std::vector<uint64_t> bufIds = mBufferRecords.clearBufferCaches(streamId);
4149 std::lock_guard<std::mutex> lock(mFreedBuffersLock);
4150 for (auto bufferId : bufIds) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07004151 mFreedBuffers.push_back(std::make_pair(streamId, bufferId));
4152 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07004153}
4154
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004155/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004156 * RequestThread inner class methods
4157 */
4158
4159Camera3Device::RequestThread::RequestThread(wp<Camera3Device> parent,
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004160 sp<StatusTracker> statusTracker,
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004161 sp<HalInterface> interface, const Vector<int32_t>& sessionParamKeys,
4162 bool useHalBufManager) :
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004163 Thread(/*canCallJava*/false),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004164 mParent(parent),
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004165 mStatusTracker(statusTracker),
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004166 mInterface(interface),
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07004167 mListener(nullptr),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004168 mId(getId(parent)),
Shuzhen Wang316781a2020-08-18 18:11:01 -07004169 mFirstRepeating(false),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004170 mReconfigured(false),
4171 mDoPause(false),
4172 mPaused(true),
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004173 mNotifyPipelineDrain(false),
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004174 mFrameNumber(0),
Jianing Weicb0652e2014-03-12 18:29:36 -07004175 mLatestRequestId(NAME_NOT_FOUND),
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07004176 mCurrentAfTriggerId(0),
4177 mCurrentPreCaptureTriggerId(0),
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004178 mRotateAndCropOverride(ANDROID_SCALER_ROTATE_AND_CROP_NONE),
Eino-Ville Talvala11afe4f2021-05-27 14:45:31 -07004179 mCameraMute(ANDROID_SENSOR_TEST_PATTERN_MODE_OFF),
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004180 mCameraMuteChanged(false),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004181 mRepeatingLastFrameNumber(
4182 hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES),
Shuzhen Wang686f6442017-06-20 16:16:04 -07004183 mPrepareVideoStream(false),
Emilian Peeva14b4dd2018-05-15 11:00:31 +01004184 mConstrainedMode(false),
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004185 mRequestLatency(kRequestLatencyBinSize),
4186 mSessionParamKeys(sessionParamKeys),
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004187 mLatestSessionParams(sessionParamKeys.size()),
4188 mUseHalBufManager(useHalBufManager) {
Yin-Chia Yeh87b3ec02019-06-03 10:44:39 -07004189 mStatusId = statusTracker->addComponent("RequestThread");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004190}
4191
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004192Camera3Device::RequestThread::~RequestThread() {}
4193
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004194void Camera3Device::RequestThread::setNotificationListener(
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004195 wp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004196 ATRACE_CALL();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004197 Mutex::Autolock l(mRequestLock);
4198 mListener = listener;
4199}
4200
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004201void Camera3Device::RequestThread::configurationComplete(bool isConstrainedHighSpeed,
Shuzhen Wang99080502021-03-07 21:08:20 -08004202 const CameraMetadata& sessionParams,
4203 const std::map<int32_t, std::set<String8>>& groupIdPhysicalCameraMap) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004204 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004205 Mutex::Autolock l(mRequestLock);
4206 mReconfigured = true;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004207 mLatestSessionParams = sessionParams;
Shuzhen Wang99080502021-03-07 21:08:20 -08004208 mGroupIdPhysicalCameraMap = groupIdPhysicalCameraMap;
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07004209 // Prepare video stream for high speed recording.
4210 mPrepareVideoStream = isConstrainedHighSpeed;
Emilian Peeva14b4dd2018-05-15 11:00:31 +01004211 mConstrainedMode = isConstrainedHighSpeed;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004212}
4213
Jianing Wei90e59c92014-03-12 18:29:36 -07004214status_t Camera3Device::RequestThread::queueRequestList(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004215 List<sp<CaptureRequest> > &requests,
4216 /*out*/
4217 int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004218 ATRACE_CALL();
Jianing Wei90e59c92014-03-12 18:29:36 -07004219 Mutex::Autolock l(mRequestLock);
4220 for (List<sp<CaptureRequest> >::iterator it = requests.begin(); it != requests.end();
4221 ++it) {
4222 mRequestQueue.push_back(*it);
4223 }
4224
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004225 if (lastFrameNumber != NULL) {
4226 *lastFrameNumber = mFrameNumber + mRequestQueue.size() - 1;
4227 ALOGV("%s: requestId %d, mFrameNumber %" PRId32 ", lastFrameNumber %" PRId64 ".",
4228 __FUNCTION__, (*(requests.begin()))->mResultExtras.requestId, mFrameNumber,
4229 *lastFrameNumber);
4230 }
Jianing Weicb0652e2014-03-12 18:29:36 -07004231
Jianing Wei90e59c92014-03-12 18:29:36 -07004232 unpauseForNewRequests();
4233
4234 return OK;
4235}
4236
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004237
4238status_t Camera3Device::RequestThread::queueTrigger(
4239 RequestTrigger trigger[],
4240 size_t count) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004241 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004242 Mutex::Autolock l(mTriggerMutex);
4243 status_t ret;
4244
4245 for (size_t i = 0; i < count; ++i) {
4246 ret = queueTriggerLocked(trigger[i]);
4247
4248 if (ret != OK) {
4249 return ret;
4250 }
4251 }
4252
4253 return OK;
4254}
4255
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004256const String8& Camera3Device::RequestThread::getId(const wp<Camera3Device> &device) {
4257 static String8 deadId("<DeadDevice>");
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004258 sp<Camera3Device> d = device.promote();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004259 if (d != nullptr) return d->mId;
4260 return deadId;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004261}
4262
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004263status_t Camera3Device::RequestThread::queueTriggerLocked(
4264 RequestTrigger trigger) {
4265
4266 uint32_t tag = trigger.metadataTag;
4267 ssize_t index = mTriggerMap.indexOfKey(tag);
4268
4269 switch (trigger.getTagType()) {
4270 case TYPE_BYTE:
4271 // fall-through
4272 case TYPE_INT32:
4273 break;
4274 default:
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004275 ALOGE("%s: Type not supported: 0x%x", __FUNCTION__,
4276 trigger.getTagType());
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004277 return INVALID_OPERATION;
4278 }
4279
4280 /**
4281 * Collect only the latest trigger, since we only have 1 field
4282 * in the request settings per trigger tag, and can't send more than 1
4283 * trigger per request.
4284 */
4285 if (index != NAME_NOT_FOUND) {
4286 mTriggerMap.editValueAt(index) = trigger;
4287 } else {
4288 mTriggerMap.add(tag, trigger);
4289 }
4290
4291 return OK;
4292}
4293
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004294status_t Camera3Device::RequestThread::setRepeatingRequests(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004295 const RequestList &requests,
4296 /*out*/
4297 int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004298 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004299 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004300 if (lastFrameNumber != NULL) {
4301 *lastFrameNumber = mRepeatingLastFrameNumber;
4302 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004303 mRepeatingRequests.clear();
Shuzhen Wang316781a2020-08-18 18:11:01 -07004304 mFirstRepeating = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004305 mRepeatingRequests.insert(mRepeatingRequests.begin(),
4306 requests.begin(), requests.end());
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004307
4308 unpauseForNewRequests();
4309
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004310 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004311 return OK;
4312}
4313
Chih-Hung Hsieh8b0b9712016-08-09 14:25:53 -07004314bool Camera3Device::RequestThread::isRepeatingRequestLocked(const sp<CaptureRequest>& requestIn) {
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07004315 if (mRepeatingRequests.empty()) {
4316 return false;
4317 }
4318 int32_t requestId = requestIn->mResultExtras.requestId;
4319 const RequestList &repeatRequests = mRepeatingRequests;
4320 // All repeating requests are guaranteed to have same id so only check first quest
4321 const sp<CaptureRequest> firstRequest = *repeatRequests.begin();
4322 return (firstRequest->mResultExtras.requestId == requestId);
4323}
4324
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004325status_t Camera3Device::RequestThread::clearRepeatingRequests(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004326 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004327 Mutex::Autolock l(mRequestLock);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004328 return clearRepeatingRequestsLocked(lastFrameNumber);
4329
4330}
4331
4332status_t Camera3Device::RequestThread::clearRepeatingRequestsLocked(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004333 mRepeatingRequests.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004334 if (lastFrameNumber != NULL) {
4335 *lastFrameNumber = mRepeatingLastFrameNumber;
4336 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004337 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004338 return OK;
4339}
4340
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004341status_t Camera3Device::RequestThread::clear(
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004342 /*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004343 ATRACE_CALL();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004344 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004345 ALOGV("RequestThread::%s:", __FUNCTION__);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004346
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004347 mRepeatingRequests.clear();
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07004348
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004349 // Send errors for all requests pending in the request queue, including
4350 // pending repeating requests
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004351 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004352 if (listener != NULL) {
4353 for (RequestList::iterator it = mRequestQueue.begin();
4354 it != mRequestQueue.end(); ++it) {
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004355 // Abort the input buffers for reprocess requests.
4356 if ((*it)->mInputStream != NULL) {
Emilian Peevf4816702020-04-03 15:44:51 -07004357 camera_stream_buffer_t inputBuffer;
Shuzhen Wang83bff122020-11-20 15:51:39 -08004358 camera3::Size inputBufferSize;
Eino-Ville Talvalaba435252017-06-21 16:07:25 -07004359 status_t res = (*it)->mInputStream->getInputBuffer(&inputBuffer,
Shuzhen Wang83bff122020-11-20 15:51:39 -08004360 &inputBufferSize, /*respectHalLimit*/ false);
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004361 if (res != OK) {
4362 ALOGW("%s: %d: couldn't get input buffer while clearing the request "
4363 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
4364 } else {
Emilian Peevf4816702020-04-03 15:44:51 -07004365 inputBuffer.status = CAMERA_BUFFER_STATUS_ERROR;
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004366 res = (*it)->mInputStream->returnInputBuffer(inputBuffer);
4367 if (res != OK) {
4368 ALOGE("%s: %d: couldn't return input buffer while clearing the request "
4369 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
4370 }
4371 }
4372 }
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004373 // Set the frame number this request would have had, if it
4374 // had been submitted; this frame number will not be reused.
4375 // The requestId and burstId fields were set when the request was
4376 // submitted originally (in convertMetadataListToRequestListLocked)
4377 (*it)->mResultExtras.frameNumber = mFrameNumber++;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004378 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004379 (*it)->mResultExtras);
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07004380 }
4381 }
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004382 mRequestQueue.clear();
Jinguang Dongb26e7a02016-11-14 16:04:02 +08004383
4384 Mutex::Autolock al(mTriggerMutex);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004385 mTriggerMap.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004386 if (lastFrameNumber != NULL) {
4387 *lastFrameNumber = mRepeatingLastFrameNumber;
4388 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004389 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Emilian Peev8dae54c2019-12-02 15:17:17 -08004390 mRequestSignal.signal();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004391 return OK;
4392}
4393
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004394status_t Camera3Device::RequestThread::flush() {
4395 ATRACE_CALL();
4396 Mutex::Autolock l(mFlushLock);
4397
Emilian Peev08dd2452017-04-06 16:55:14 +01004398 return mInterface->flush();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004399}
4400
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004401void Camera3Device::RequestThread::setPaused(bool paused) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004402 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004403 Mutex::Autolock l(mPauseLock);
4404 mDoPause = paused;
4405 mDoPauseSignal.signal();
4406}
4407
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004408status_t Camera3Device::RequestThread::waitUntilRequestProcessed(
4409 int32_t requestId, nsecs_t timeout) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004410 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004411 Mutex::Autolock l(mLatestRequestMutex);
4412 status_t res;
4413 while (mLatestRequestId != requestId) {
4414 nsecs_t startTime = systemTime();
4415
4416 res = mLatestRequestSignal.waitRelative(mLatestRequestMutex, timeout);
4417 if (res != OK) return res;
4418
4419 timeout -= (systemTime() - startTime);
4420 }
4421
4422 return OK;
4423}
4424
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004425void Camera3Device::RequestThread::requestExit() {
4426 // Call parent to set up shutdown
4427 Thread::requestExit();
4428 // The exit from any possible waits
4429 mDoPauseSignal.signal();
4430 mRequestSignal.signal();
Shuzhen Wang686f6442017-06-20 16:16:04 -07004431
4432 mRequestLatency.log("ProcessCaptureRequest latency histogram");
4433 mRequestLatency.reset();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004434}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004435
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004436void Camera3Device::RequestThread::checkAndStopRepeatingRequest() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004437 ATRACE_CALL();
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07004438 bool surfaceAbandoned = false;
4439 int64_t lastFrameNumber = 0;
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004440 sp<NotificationListener> listener;
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07004441 {
4442 Mutex::Autolock l(mRequestLock);
4443 // Check all streams needed by repeating requests are still valid. Otherwise, stop
4444 // repeating requests.
4445 for (const auto& request : mRepeatingRequests) {
4446 for (const auto& s : request->mOutputStreams) {
4447 if (s->isAbandoned()) {
4448 surfaceAbandoned = true;
4449 clearRepeatingRequestsLocked(&lastFrameNumber);
4450 break;
4451 }
4452 }
4453 if (surfaceAbandoned) {
4454 break;
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004455 }
4456 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004457 listener = mListener.promote();
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004458 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004459
4460 if (listener != NULL && surfaceAbandoned) {
4461 listener->notifyRepeatingRequestError(lastFrameNumber);
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07004462 }
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004463}
4464
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004465bool Camera3Device::RequestThread::sendRequestsBatch() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004466 ATRACE_CALL();
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004467 status_t res;
4468 size_t batchSize = mNextRequests.size();
Emilian Peevf4816702020-04-03 15:44:51 -07004469 std::vector<camera_capture_request_t*> requests(batchSize);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004470 uint32_t numRequestProcessed = 0;
4471 for (size_t i = 0; i < batchSize; i++) {
4472 requests[i] = &mNextRequests.editItemAt(i).halRequest;
Yin-Chia Yeh885691c2018-05-01 15:54:24 -07004473 ATRACE_ASYNC_BEGIN("frame capture", mNextRequests[i].halRequest.frame_number);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004474 }
4475
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004476 res = mInterface->processBatchCaptureRequests(requests, &numRequestProcessed);
4477
4478 bool triggerRemoveFailed = false;
4479 NextRequest& triggerFailedRequest = mNextRequests.editItemAt(0);
4480 for (size_t i = 0; i < numRequestProcessed; i++) {
4481 NextRequest& nextRequest = mNextRequests.editItemAt(i);
4482 nextRequest.submitted = true;
4483
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004484 updateNextRequest(nextRequest);
Emilian Peevaebbe412018-01-15 13:53:24 +00004485
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004486 if (!triggerRemoveFailed) {
4487 // Remove any previously queued triggers (after unlock)
4488 status_t removeTriggerRes = removeTriggers(mPrevRequest);
4489 if (removeTriggerRes != OK) {
4490 triggerRemoveFailed = true;
4491 triggerFailedRequest = nextRequest;
4492 }
4493 }
4494 }
4495
4496 if (triggerRemoveFailed) {
4497 SET_ERR("RequestThread: Unable to remove triggers "
4498 "(capture request %d, HAL device: %s (%d)",
4499 triggerFailedRequest.halRequest.frame_number, strerror(-res), res);
4500 cleanUpFailedRequests(/*sendRequestError*/ false);
4501 return false;
4502 }
4503
4504 if (res != OK) {
4505 // Should only get a failure here for malformed requests or device-level
4506 // errors, so consider all errors fatal. Bad metadata failures should
4507 // come through notify.
4508 SET_ERR("RequestThread: Unable to submit capture request %d to HAL device: %s (%d)",
4509 mNextRequests[numRequestProcessed].halRequest.frame_number,
4510 strerror(-res), res);
4511 cleanUpFailedRequests(/*sendRequestError*/ false);
4512 return false;
4513 }
4514 return true;
4515}
4516
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07004517nsecs_t Camera3Device::RequestThread::calculateMaxExpectedDuration(const camera_metadata_t *request) {
4518 nsecs_t maxExpectedDuration = kDefaultExpectedDuration;
4519 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
4520 find_camera_metadata_ro_entry(request,
4521 ANDROID_CONTROL_AE_MODE,
4522 &e);
4523 if (e.count == 0) return maxExpectedDuration;
4524
4525 switch (e.data.u8[0]) {
4526 case ANDROID_CONTROL_AE_MODE_OFF:
4527 find_camera_metadata_ro_entry(request,
4528 ANDROID_SENSOR_EXPOSURE_TIME,
4529 &e);
4530 if (e.count > 0) {
4531 maxExpectedDuration = e.data.i64[0];
4532 }
4533 find_camera_metadata_ro_entry(request,
4534 ANDROID_SENSOR_FRAME_DURATION,
4535 &e);
4536 if (e.count > 0) {
4537 maxExpectedDuration = std::max(e.data.i64[0], maxExpectedDuration);
4538 }
4539 break;
4540 default:
4541 find_camera_metadata_ro_entry(request,
4542 ANDROID_CONTROL_AE_TARGET_FPS_RANGE,
4543 &e);
4544 if (e.count > 1) {
4545 maxExpectedDuration = 1e9 / e.data.u8[0];
4546 }
4547 break;
4548 }
4549
4550 return maxExpectedDuration;
4551}
4552
Emilian Peeva14b4dd2018-05-15 11:00:31 +01004553bool Camera3Device::RequestThread::skipHFRTargetFPSUpdate(int32_t tag,
4554 const camera_metadata_ro_entry_t& newEntry, const camera_metadata_entry_t& currentEntry) {
4555 if (mConstrainedMode && (ANDROID_CONTROL_AE_TARGET_FPS_RANGE == tag) &&
4556 (newEntry.count == currentEntry.count) && (currentEntry.count == 2) &&
4557 (currentEntry.data.i32[1] == newEntry.data.i32[1])) {
4558 return true;
4559 }
4560
4561 return false;
4562}
4563
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004564void Camera3Device::RequestThread::updateNextRequest(NextRequest& nextRequest) {
4565 // Update the latest request sent to HAL
Shuzhen Wang83bff122020-11-20 15:51:39 -08004566 camera_capture_request_t& halRequest = nextRequest.halRequest;
4567 if (halRequest.settings != NULL) { // Don't update if they were unchanged
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004568 Mutex::Autolock al(mLatestRequestMutex);
4569
Shuzhen Wang83bff122020-11-20 15:51:39 -08004570 camera_metadata_t* cloned = clone_camera_metadata(halRequest.settings);
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004571 mLatestRequest.acquire(cloned);
4572
4573 mLatestPhysicalRequest.clear();
Shuzhen Wang83bff122020-11-20 15:51:39 -08004574 for (uint32_t i = 0; i < halRequest.num_physcam_settings; i++) {
4575 cloned = clone_camera_metadata(halRequest.physcam_settings[i]);
4576 mLatestPhysicalRequest.emplace(halRequest.physcam_id[i],
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004577 CameraMetadata(cloned));
4578 }
4579
4580 sp<Camera3Device> parent = mParent.promote();
4581 if (parent != NULL) {
4582 parent->monitorMetadata(TagMonitor::REQUEST,
Shuzhen Wang83bff122020-11-20 15:51:39 -08004583 halRequest.frame_number,
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004584 0, mLatestRequest, mLatestPhysicalRequest);
4585 }
4586 }
4587
Shuzhen Wang83bff122020-11-20 15:51:39 -08004588 if (halRequest.settings != NULL) {
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004589 nextRequest.captureRequest->mSettingsList.begin()->metadata.unlock(
Shuzhen Wang83bff122020-11-20 15:51:39 -08004590 halRequest.settings);
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004591 }
4592
Shuzhen Wang83bff122020-11-20 15:51:39 -08004593 cleanupPhysicalSettings(nextRequest.captureRequest, &halRequest);
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004594}
4595
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004596bool Camera3Device::RequestThread::updateSessionParameters(const CameraMetadata& settings) {
4597 ATRACE_CALL();
4598 bool updatesDetected = false;
4599
Emilian Peev4ec17882019-01-24 17:16:58 -08004600 CameraMetadata updatedParams(mLatestSessionParams);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004601 for (auto tag : mSessionParamKeys) {
4602 camera_metadata_ro_entry entry = settings.find(tag);
Emilian Peev4ec17882019-01-24 17:16:58 -08004603 camera_metadata_entry lastEntry = updatedParams.find(tag);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004604
4605 if (entry.count > 0) {
4606 bool isDifferent = false;
4607 if (lastEntry.count > 0) {
4608 // Have a last value, compare to see if changed
4609 if (lastEntry.type == entry.type &&
4610 lastEntry.count == entry.count) {
4611 // Same type and count, compare values
4612 size_t bytesPerValue = camera_metadata_type_size[lastEntry.type];
4613 size_t entryBytes = bytesPerValue * lastEntry.count;
4614 int cmp = memcmp(entry.data.u8, lastEntry.data.u8, entryBytes);
4615 if (cmp != 0) {
4616 isDifferent = true;
4617 }
4618 } else {
4619 // Count or type has changed
4620 isDifferent = true;
4621 }
4622 } else {
4623 // No last entry, so always consider to be different
4624 isDifferent = true;
4625 }
4626
4627 if (isDifferent) {
4628 ALOGV("%s: Session parameter tag id %d changed", __FUNCTION__, tag);
Emilian Peeva14b4dd2018-05-15 11:00:31 +01004629 if (!skipHFRTargetFPSUpdate(tag, entry, lastEntry)) {
4630 updatesDetected = true;
4631 }
Emilian Peev4ec17882019-01-24 17:16:58 -08004632 updatedParams.update(entry);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004633 }
4634 } else if (lastEntry.count > 0) {
4635 // Value has been removed
4636 ALOGV("%s: Session parameter tag id %d removed", __FUNCTION__, tag);
Emilian Peev4ec17882019-01-24 17:16:58 -08004637 updatedParams.erase(tag);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004638 updatesDetected = true;
4639 }
4640 }
4641
Emilian Peev4ec17882019-01-24 17:16:58 -08004642 bool reconfigureRequired;
4643 if (updatesDetected) {
4644 reconfigureRequired = mInterface->isReconfigurationRequired(mLatestSessionParams,
4645 updatedParams);
4646 mLatestSessionParams = updatedParams;
4647 } else {
4648 reconfigureRequired = false;
4649 }
4650
4651 return reconfigureRequired;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004652}
4653
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004654bool Camera3Device::RequestThread::threadLoop() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004655 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004656 status_t res;
Jayant Chowdhary37eca242019-11-18 08:55:56 -08004657 // Any function called from threadLoop() must not hold mInterfaceLock since
4658 // it could lead to deadlocks (disconnect() -> hold mInterfaceMutex -> wait for request thread
4659 // to finish -> request thread waits on mInterfaceMutex) http://b/143513518
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004660
4661 // Handle paused state.
4662 if (waitIfPaused()) {
4663 return true;
4664 }
4665
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004666 // Wait for the next batch of requests.
4667 waitForNextRequestBatch();
4668 if (mNextRequests.size() == 0) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004669 return true;
4670 }
4671
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004672 // Get the latest request ID, if any
4673 int latestRequestId;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004674 camera_metadata_entry_t requestIdEntry = mNextRequests[mNextRequests.size() - 1].
Emilian Peevaebbe412018-01-15 13:53:24 +00004675 captureRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_ID);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004676 if (requestIdEntry.count > 0) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004677 latestRequestId = requestIdEntry.data.i32[0];
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004678 } else {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004679 ALOGW("%s: Did not have android.request.id set in the request.", __FUNCTION__);
4680 latestRequestId = NAME_NOT_FOUND;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004681 }
4682
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004683 // 'mNextRequests' will at this point contain either a set of HFR batched requests
4684 // or a single request from streaming or burst. In either case the first element
4685 // should contain the latest camera settings that we need to check for any session
4686 // parameter updates.
Emilian Peevaebbe412018-01-15 13:53:24 +00004687 if (updateSessionParameters(mNextRequests[0].captureRequest->mSettingsList.begin()->metadata)) {
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004688 res = OK;
4689
4690 //Input stream buffers are already acquired at this point so an input stream
4691 //will not be able to move to idle state unless we force it.
4692 if (mNextRequests[0].captureRequest->mInputStream != nullptr) {
4693 res = mNextRequests[0].captureRequest->mInputStream->forceToIdle();
4694 if (res != OK) {
4695 ALOGE("%s: Failed to force idle input stream: %d", __FUNCTION__, res);
4696 cleanUpFailedRequests(/*sendRequestError*/ false);
4697 return false;
4698 }
4699 }
4700
4701 if (res == OK) {
Emilian Peev3bead5f2020-05-28 17:29:08 -07004702 sp<Camera3Device> parent = mParent.promote();
4703 if (parent != nullptr) {
4704 mReconfigured |= parent->reconfigureCamera(mLatestSessionParams, mStatusId);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004705 }
Emilian Peev3bead5f2020-05-28 17:29:08 -07004706 setPaused(false);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004707
4708 if (mNextRequests[0].captureRequest->mInputStream != nullptr) {
4709 mNextRequests[0].captureRequest->mInputStream->restoreConfiguredState();
4710 if (res != OK) {
4711 ALOGE("%s: Failed to restore configured input stream: %d", __FUNCTION__, res);
4712 cleanUpFailedRequests(/*sendRequestError*/ false);
4713 return false;
4714 }
4715 }
4716 }
4717 }
4718
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004719 // Prepare a batch of HAL requests and output buffers.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004720 res = prepareHalRequests();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004721 if (res == TIMED_OUT) {
4722 // Not a fatal error if getting output buffers time out.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004723 cleanUpFailedRequests(/*sendRequestError*/ true);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004724 // Check if any stream is abandoned.
4725 checkAndStopRepeatingRequest();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004726 return true;
4727 } else if (res != OK) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004728 cleanUpFailedRequests(/*sendRequestError*/ false);
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004729 return false;
4730 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004731
Zhijun Hecc27e112013-10-03 16:12:43 -07004732 // Inform waitUntilRequestProcessed thread of a new request ID
4733 {
4734 Mutex::Autolock al(mLatestRequestMutex);
4735
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004736 mLatestRequestId = latestRequestId;
Zhijun Hecc27e112013-10-03 16:12:43 -07004737 mLatestRequestSignal.signal();
4738 }
4739
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004740 // Submit a batch of requests to HAL.
4741 // Use flush lock only when submitting multilple requests in a batch.
4742 // TODO: The problem with flush lock is flush() will be blocked by process_capture_request()
4743 // which may take a long time to finish so synchronizing flush() and
4744 // process_capture_request() defeats the purpose of cancelling requests ASAP with flush().
4745 // For now, only synchronize for high speed recording and we should figure something out for
4746 // removing the synchronization.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004747 bool useFlushLock = mNextRequests.size() > 1;
Eino-Ville Talvala17a61ad2013-06-03 16:53:32 -07004748
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004749 if (useFlushLock) {
4750 mFlushLock.lock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004751 }
4752
Zhijun Hef0645c12016-08-02 00:58:11 -07004753 ALOGVV("%s: %d: submitting %zu requests in a batch.", __FUNCTION__, __LINE__,
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004754 mNextRequests.size());
Igor Murashkin1e479c02013-09-06 16:55:14 -07004755
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08004756 sp<Camera3Device> parent = mParent.promote();
4757 if (parent != nullptr) {
4758 parent->mRequestBufferSM.onSubmittingRequest();
4759 }
4760
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004761 bool submitRequestSuccess = false;
Shuzhen Wang686f6442017-06-20 16:16:04 -07004762 nsecs_t tRequestStart = systemTime(SYSTEM_TIME_MONOTONIC);
Yin-Chia Yeh11648852019-05-16 10:42:54 -07004763 submitRequestSuccess = sendRequestsBatch();
4764
Shuzhen Wang686f6442017-06-20 16:16:04 -07004765 nsecs_t tRequestEnd = systemTime(SYSTEM_TIME_MONOTONIC);
4766 mRequestLatency.add(tRequestStart, tRequestEnd);
Igor Murashkin1e479c02013-09-06 16:55:14 -07004767
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004768 if (useFlushLock) {
4769 mFlushLock.unlock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004770 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004771
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004772 // Unset as current request
4773 {
4774 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004775 mNextRequests.clear();
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004776 }
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004777 mRequestSubmittedSignal.signal();
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004778
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004779 return submitRequestSuccess;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004780}
4781
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004782status_t Camera3Device::RequestThread::prepareHalRequests() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004783 ATRACE_CALL();
4784
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07004785 bool batchedRequest = mNextRequests[0].captureRequest->mBatchSize > 1;
Shuzhen Wang4a472662017-02-26 23:29:04 -08004786 for (size_t i = 0; i < mNextRequests.size(); i++) {
4787 auto& nextRequest = mNextRequests.editItemAt(i);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004788 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
Emilian Peevf4816702020-04-03 15:44:51 -07004789 camera_capture_request_t* halRequest = &nextRequest.halRequest;
4790 Vector<camera_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004791
4792 // Prepare a request to HAL
4793 halRequest->frame_number = captureRequest->mResultExtras.frameNumber;
4794
4795 // Insert any queued triggers (before metadata is locked)
4796 status_t res = insertTriggers(captureRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004797 if (res < 0) {
4798 SET_ERR("RequestThread: Unable to insert triggers "
4799 "(capture request %d, HAL device: %s (%d)",
4800 halRequest->frame_number, strerror(-res), res);
4801 return INVALID_OPERATION;
4802 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07004803
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004804 int triggerCount = res;
4805 bool triggersMixedIn = (triggerCount > 0 || mPrevTriggers > 0);
4806 mPrevTriggers = triggerCount;
4807
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004808 bool rotateAndCropChanged = overrideAutoRotateAndCrop(captureRequest);
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004809 bool testPatternChanged = overrideTestPattern(captureRequest);
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004810
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004811 // If the request is the same as last, or we had triggers now or last time or
4812 // changing overrides this time
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004813 bool newRequest =
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004814 (mPrevRequest != captureRequest || triggersMixedIn ||
4815 rotateAndCropChanged || testPatternChanged) &&
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07004816 // Request settings are all the same within one batch, so only treat the first
4817 // request in a batch as new
Zhijun He54c36822018-07-18 09:33:39 -07004818 !(batchedRequest && i > 0);
Emilian Peev00420d22018-02-05 21:33:13 +00004819 if (newRequest) {
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08004820 std::set<std::string> cameraIdsWithZoom;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004821 /**
4822 * HAL workaround:
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004823 * Insert a fake trigger ID if a trigger is set but no trigger ID is
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004824 */
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004825 res = addFakeTriggerIds(captureRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004826 if (res != OK) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004827 SET_ERR("RequestThread: Unable to insert fake trigger IDs "
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004828 "(capture request %d, HAL device: %s (%d)",
4829 halRequest->frame_number, strerror(-res), res);
4830 return INVALID_OPERATION;
4831 }
4832
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07004833 {
4834 // Correct metadata regions for distortion correction if enabled
4835 sp<Camera3Device> parent = mParent.promote();
4836 if (parent != nullptr) {
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -07004837 List<PhysicalCameraSettings>::iterator it;
4838 for (it = captureRequest->mSettingsList.begin();
4839 it != captureRequest->mSettingsList.end(); it++) {
4840 if (parent->mDistortionMappers.find(it->cameraId) ==
4841 parent->mDistortionMappers.end()) {
4842 continue;
4843 }
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07004844
4845 if (!captureRequest->mDistortionCorrectionUpdated) {
4846 res = parent->mDistortionMappers[it->cameraId].correctCaptureRequest(
4847 &(it->metadata));
4848 if (res != OK) {
4849 SET_ERR("RequestThread: Unable to correct capture requests "
4850 "for lens distortion for request %d: %s (%d)",
4851 halRequest->frame_number, strerror(-res), res);
4852 return INVALID_OPERATION;
4853 }
4854 captureRequest->mDistortionCorrectionUpdated = true;
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -07004855 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07004856 }
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08004857
4858 for (it = captureRequest->mSettingsList.begin();
4859 it != captureRequest->mSettingsList.end(); it++) {
4860 if (parent->mZoomRatioMappers.find(it->cameraId) ==
4861 parent->mZoomRatioMappers.end()) {
4862 continue;
4863 }
4864
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07004865 if (!captureRequest->mZoomRatioIs1x) {
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08004866 cameraIdsWithZoom.insert(it->cameraId);
4867 }
4868
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07004869 if (!captureRequest->mZoomRatioUpdated) {
4870 res = parent->mZoomRatioMappers[it->cameraId].updateCaptureRequest(
4871 &(it->metadata));
4872 if (res != OK) {
4873 SET_ERR("RequestThread: Unable to correct capture requests "
4874 "for zoom ratio for request %d: %s (%d)",
4875 halRequest->frame_number, strerror(-res), res);
4876 return INVALID_OPERATION;
4877 }
4878 captureRequest->mZoomRatioUpdated = true;
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08004879 }
4880 }
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07004881 if (captureRequest->mRotateAndCropAuto &&
4882 !captureRequest->mRotationAndCropUpdated) {
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004883 for (it = captureRequest->mSettingsList.begin();
4884 it != captureRequest->mSettingsList.end(); it++) {
4885 auto mapper = parent->mRotateAndCropMappers.find(it->cameraId);
4886 if (mapper != parent->mRotateAndCropMappers.end()) {
4887 res = mapper->second.updateCaptureRequest(&(it->metadata));
4888 if (res != OK) {
4889 SET_ERR("RequestThread: Unable to correct capture requests "
4890 "for rotate-and-crop for request %d: %s (%d)",
4891 halRequest->frame_number, strerror(-res), res);
4892 return INVALID_OPERATION;
4893 }
4894 }
4895 }
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07004896 captureRequest->mRotationAndCropUpdated = true;
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004897 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07004898 }
4899 }
4900
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004901 /**
4902 * The request should be presorted so accesses in HAL
4903 * are O(logn). Sidenote, sorting a sorted metadata is nop.
4904 */
Emilian Peevaebbe412018-01-15 13:53:24 +00004905 captureRequest->mSettingsList.begin()->metadata.sort();
4906 halRequest->settings = captureRequest->mSettingsList.begin()->metadata.getAndLock();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004907 mPrevRequest = captureRequest;
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08004908 mPrevCameraIdsWithZoom = cameraIdsWithZoom;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004909 ALOGVV("%s: Request settings are NEW", __FUNCTION__);
4910
4911 IF_ALOGV() {
4912 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
4913 find_camera_metadata_ro_entry(
4914 halRequest->settings,
4915 ANDROID_CONTROL_AF_TRIGGER,
4916 &e
4917 );
4918 if (e.count > 0) {
4919 ALOGV("%s: Request (frame num %d) had AF trigger 0x%x",
4920 __FUNCTION__,
4921 halRequest->frame_number,
4922 e.data.u8[0]);
4923 }
4924 }
4925 } else {
4926 // leave request.settings NULL to indicate 'reuse latest given'
4927 ALOGVV("%s: Request settings are REUSED",
4928 __FUNCTION__);
4929 }
4930
Emilian Peevaebbe412018-01-15 13:53:24 +00004931 if (captureRequest->mSettingsList.size() > 1) {
4932 halRequest->num_physcam_settings = captureRequest->mSettingsList.size() - 1;
4933 halRequest->physcam_id = new const char* [halRequest->num_physcam_settings];
Emilian Peev00420d22018-02-05 21:33:13 +00004934 if (newRequest) {
4935 halRequest->physcam_settings =
4936 new const camera_metadata* [halRequest->num_physcam_settings];
4937 } else {
4938 halRequest->physcam_settings = nullptr;
4939 }
Emilian Peevaebbe412018-01-15 13:53:24 +00004940 auto it = ++captureRequest->mSettingsList.begin();
4941 size_t i = 0;
4942 for (; it != captureRequest->mSettingsList.end(); it++, i++) {
4943 halRequest->physcam_id[i] = it->cameraId.c_str();
Emilian Peev00420d22018-02-05 21:33:13 +00004944 if (newRequest) {
4945 it->metadata.sort();
4946 halRequest->physcam_settings[i] = it->metadata.getAndLock();
4947 }
Emilian Peevaebbe412018-01-15 13:53:24 +00004948 }
4949 }
4950
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004951 uint32_t totalNumBuffers = 0;
4952
4953 // Fill in buffers
4954 if (captureRequest->mInputStream != NULL) {
4955 halRequest->input_buffer = &captureRequest->mInputBuffer;
Shuzhen Wang83bff122020-11-20 15:51:39 -08004956
4957 halRequest->input_width = captureRequest->mInputBufferSize.width;
4958 halRequest->input_height = captureRequest->mInputBufferSize.height;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004959 totalNumBuffers += 1;
4960 } else {
4961 halRequest->input_buffer = NULL;
4962 }
4963
Emilian Peevf4816702020-04-03 15:44:51 -07004964 outputBuffers->insertAt(camera_stream_buffer_t(), 0,
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004965 captureRequest->mOutputStreams.size());
4966 halRequest->output_buffers = outputBuffers->array();
Shuzhen Wang99080502021-03-07 21:08:20 -08004967 std::set<std::set<String8>> requestedPhysicalCameras;
Yin-Chia Yehb3a80b12018-09-04 12:13:05 -07004968
4969 sp<Camera3Device> parent = mParent.promote();
4970 if (parent == NULL) {
4971 // Should not happen, and nowhere to send errors to, so just log it
4972 CLOGE("RequestThread: Parent is gone");
4973 return INVALID_OPERATION;
4974 }
4975 nsecs_t waitDuration = kBaseGetBufferWait + parent->getExpectedInFlightDuration();
4976
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07004977 SurfaceMap uniqueSurfaceIdMap;
Shuzhen Wang4a472662017-02-26 23:29:04 -08004978 for (size_t j = 0; j < captureRequest->mOutputStreams.size(); j++) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07004979 sp<Camera3OutputStreamInterface> outputStream =
4980 captureRequest->mOutputStreams.editItemAt(j);
4981 int streamId = outputStream->getId();
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07004982
4983 // Prepare video buffers for high speed recording on the first video request.
4984 if (mPrepareVideoStream && outputStream->isVideoStream()) {
4985 // Only try to prepare video stream on the first video request.
4986 mPrepareVideoStream = false;
4987
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07004988 res = outputStream->startPrepare(Camera3StreamInterface::ALLOCATE_PIPELINE_MAX,
4989 false /*blockRequest*/);
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07004990 while (res == NOT_ENOUGH_DATA) {
4991 res = outputStream->prepareNextBuffer();
4992 }
4993 if (res != OK) {
4994 ALOGW("%s: Preparing video buffers for high speed failed: %s (%d)",
4995 __FUNCTION__, strerror(-res), res);
4996 outputStream->cancelPrepare();
4997 }
4998 }
4999
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005000 std::vector<size_t> uniqueSurfaceIds;
5001 res = outputStream->getUniqueSurfaceIds(
5002 captureRequest->mOutputSurfaces[streamId],
5003 &uniqueSurfaceIds);
5004 // INVALID_OPERATION is normal output for streams not supporting surfaceIds
5005 if (res != OK && res != INVALID_OPERATION) {
5006 ALOGE("%s: failed to query stream %d unique surface IDs",
5007 __FUNCTION__, streamId);
5008 return res;
5009 }
5010 if (res == OK) {
5011 uniqueSurfaceIdMap.insert({streamId, std::move(uniqueSurfaceIds)});
5012 }
5013
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07005014 if (mUseHalBufManager) {
Yin-Chia Yeh110342b2018-11-19 11:47:46 -08005015 if (outputStream->isAbandoned()) {
Yin-Chia Yeha1b56c82019-03-27 15:50:39 -07005016 ALOGV("%s: stream %d is abandoned, skipping request", __FUNCTION__, streamId);
Yin-Chia Yeh110342b2018-11-19 11:47:46 -08005017 return TIMED_OUT;
5018 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07005019 // HAL will request buffer through requestStreamBuffer API
Emilian Peevf4816702020-04-03 15:44:51 -07005020 camera_stream_buffer_t& buffer = outputBuffers->editItemAt(j);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07005021 buffer.stream = outputStream->asHalStream();
5022 buffer.buffer = nullptr;
Emilian Peevf4816702020-04-03 15:44:51 -07005023 buffer.status = CAMERA_BUFFER_STATUS_OK;
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07005024 buffer.acquire_fence = -1;
5025 buffer.release_fence = -1;
Emilian Peevf0348ae2021-01-13 13:39:45 -08005026 // Mark the output stream as unpreparable to block clients from calling
5027 // 'prepare' after this request reaches CameraHal and before the respective
5028 // buffers are requested.
5029 outputStream->markUnpreparable();
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07005030 } else {
5031 res = outputStream->getBuffer(&outputBuffers->editItemAt(j),
5032 waitDuration,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005033 captureRequest->mOutputSurfaces[streamId]);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07005034 if (res != OK) {
5035 // Can't get output buffer from gralloc queue - this could be due to
5036 // abandoned queue or other consumer misbehavior, so not a fatal
5037 // error
Yin-Chia Yeha1b56c82019-03-27 15:50:39 -07005038 ALOGV("RequestThread: Can't get output buffer, skipping request:"
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07005039 " %s (%d)", strerror(-res), res);
5040
5041 return TIMED_OUT;
5042 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005043 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08005044
5045 {
5046 sp<Camera3Device> parent = mParent.promote();
5047 if (parent != nullptr) {
5048 const String8& streamCameraId = outputStream->getPhysicalCameraId();
5049 for (const auto& settings : captureRequest->mSettingsList) {
5050 if ((streamCameraId.isEmpty() &&
5051 parent->getId() == settings.cameraId.c_str()) ||
5052 streamCameraId == settings.cameraId.c_str()) {
5053 outputStream->fireBufferRequestForFrameNumber(
5054 captureRequest->mResultExtras.frameNumber,
5055 settings.metadata);
5056 }
5057 }
5058 }
5059 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07005060
Shuzhen Wang5c22c152017-12-31 17:12:25 -08005061 String8 physicalCameraId = outputStream->getPhysicalCameraId();
Shuzhen Wang99080502021-03-07 21:08:20 -08005062 int32_t streamGroupId = outputStream->getHalStreamGroupId();
5063 if (streamGroupId != -1 && mGroupIdPhysicalCameraMap.count(streamGroupId) == 1) {
5064 requestedPhysicalCameras.insert(mGroupIdPhysicalCameraMap[streamGroupId]);
5065 } else if (!physicalCameraId.isEmpty()) {
5066 requestedPhysicalCameras.insert(std::set<String8>({physicalCameraId}));
Shuzhen Wang5c22c152017-12-31 17:12:25 -08005067 }
5068 halRequest->num_output_buffers++;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005069 }
5070 totalNumBuffers += halRequest->num_output_buffers;
5071
5072 // Log request in the in-flight queue
Shuzhen Wang4a472662017-02-26 23:29:04 -08005073 // If this request list is for constrained high speed recording (not
5074 // preview), and the current request is not the last one in the batch,
5075 // do not send callback to the app.
5076 bool hasCallback = true;
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07005077 if (batchedRequest && i != mNextRequests.size()-1) {
Shuzhen Wang4a472662017-02-26 23:29:04 -08005078 hasCallback = false;
5079 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01005080 bool isStillCapture = false;
Shuzhen Wang26abaf42018-08-28 15:41:20 -07005081 bool isZslCapture = false;
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08005082 const camera_metadata_t* settings = halRequest->settings;
5083 bool shouldUnlockSettings = false;
5084 if (settings == nullptr) {
5085 shouldUnlockSettings = true;
5086 settings = captureRequest->mSettingsList.begin()->metadata.getAndLock();
5087 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01005088 if (!mNextRequests[0].captureRequest->mSettingsList.begin()->metadata.isEmpty()) {
5089 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08005090 find_camera_metadata_ro_entry(settings, ANDROID_CONTROL_CAPTURE_INTENT, &e);
Emilian Peev9dd21f42018-08-03 13:39:29 +01005091 if ((e.count > 0) && (e.data.u8[0] == ANDROID_CONTROL_CAPTURE_INTENT_STILL_CAPTURE)) {
5092 isStillCapture = true;
5093 ATRACE_ASYNC_BEGIN("still capture", mNextRequests[i].halRequest.frame_number);
5094 }
Shuzhen Wang26abaf42018-08-28 15:41:20 -07005095
Emilian Peevaf8416e2021-02-04 17:52:43 -08005096 e = camera_metadata_ro_entry_t();
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08005097 find_camera_metadata_ro_entry(settings, ANDROID_CONTROL_ENABLE_ZSL, &e);
Shuzhen Wang26abaf42018-08-28 15:41:20 -07005098 if ((e.count > 0) && (e.data.u8[0] == ANDROID_CONTROL_ENABLE_ZSL_TRUE)) {
5099 isZslCapture = true;
5100 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01005101 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005102 res = parent->registerInFlight(halRequest->frame_number,
5103 totalNumBuffers, captureRequest->mResultExtras,
5104 /*hasInput*/halRequest->input_buffer != NULL,
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07005105 hasCallback,
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08005106 calculateMaxExpectedDuration(settings),
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005107 requestedPhysicalCameras, isStillCapture, isZslCapture,
5108 captureRequest->mRotateAndCropAuto, mPrevCameraIdsWithZoom,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005109 (mUseHalBufManager) ? uniqueSurfaceIdMap :
Shuzhen Wang316781a2020-08-18 18:11:01 -07005110 SurfaceMap{}, captureRequest->mRequestTimeNs);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005111 ALOGVV("%s: registered in flight requestId = %" PRId32 ", frameNumber = %" PRId64
5112 ", burstId = %" PRId32 ".",
5113 __FUNCTION__,
5114 captureRequest->mResultExtras.requestId, captureRequest->mResultExtras.frameNumber,
5115 captureRequest->mResultExtras.burstId);
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08005116
5117 if (shouldUnlockSettings) {
5118 captureRequest->mSettingsList.begin()->metadata.unlock(settings);
5119 }
5120
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005121 if (res != OK) {
5122 SET_ERR("RequestThread: Unable to register new in-flight request:"
5123 " %s (%d)", strerror(-res), res);
5124 return INVALID_OPERATION;
5125 }
5126 }
5127
5128 return OK;
5129}
5130
Igor Murashkin1e479c02013-09-06 16:55:14 -07005131CameraMetadata Camera3Device::RequestThread::getLatestRequest() const {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005132 ATRACE_CALL();
Igor Murashkin1e479c02013-09-06 16:55:14 -07005133 Mutex::Autolock al(mLatestRequestMutex);
5134
5135 ALOGV("RequestThread::%s", __FUNCTION__);
5136
5137 return mLatestRequest;
5138}
5139
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005140bool Camera3Device::RequestThread::isStreamPending(
5141 sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005142 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005143 Mutex::Autolock l(mRequestLock);
5144
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005145 for (const auto& nextRequest : mNextRequests) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005146 if (!nextRequest.submitted) {
5147 for (const auto& s : nextRequest.captureRequest->mOutputStreams) {
5148 if (stream == s) return true;
5149 }
5150 if (stream == nextRequest.captureRequest->mInputStream) return true;
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07005151 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07005152 }
5153
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005154 for (const auto& request : mRequestQueue) {
5155 for (const auto& s : request->mOutputStreams) {
5156 if (stream == s) return true;
5157 }
5158 if (stream == request->mInputStream) return true;
5159 }
5160
5161 for (const auto& request : mRepeatingRequests) {
5162 for (const auto& s : request->mOutputStreams) {
5163 if (stream == s) return true;
5164 }
5165 if (stream == request->mInputStream) return true;
5166 }
5167
5168 return false;
5169}
Jianing Weicb0652e2014-03-12 18:29:36 -07005170
Emilian Peev40ead602017-09-26 15:46:36 +01005171bool Camera3Device::RequestThread::isOutputSurfacePending(int streamId, size_t surfaceId) {
5172 ATRACE_CALL();
5173 Mutex::Autolock l(mRequestLock);
5174
5175 for (const auto& nextRequest : mNextRequests) {
5176 for (const auto& s : nextRequest.captureRequest->mOutputSurfaces) {
5177 if (s.first == streamId) {
5178 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
5179 if (it != s.second.end()) {
5180 return true;
5181 }
5182 }
5183 }
5184 }
5185
5186 for (const auto& request : mRequestQueue) {
5187 for (const auto& s : request->mOutputSurfaces) {
5188 if (s.first == streamId) {
5189 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
5190 if (it != s.second.end()) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005191 return true;
Emilian Peev40ead602017-09-26 15:46:36 +01005192 }
5193 }
5194 }
5195 }
5196
5197 for (const auto& request : mRepeatingRequests) {
5198 for (const auto& s : request->mOutputSurfaces) {
5199 if (s.first == streamId) {
5200 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
5201 if (it != s.second.end()) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005202 return true;
Emilian Peev40ead602017-09-26 15:46:36 +01005203 }
5204 }
5205 }
5206 }
5207
5208 return false;
5209}
5210
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07005211void Camera3Device::RequestThread::signalPipelineDrain(const std::vector<int>& streamIds) {
5212 if (!mUseHalBufManager) {
5213 ALOGE("%s called for camera device not supporting HAL buffer management", __FUNCTION__);
5214 return;
5215 }
5216
5217 Mutex::Autolock pl(mPauseLock);
5218 if (mPaused) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005219 mInterface->signalPipelineDrain(streamIds);
5220 return;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07005221 }
5222 // If request thread is still busy, wait until paused then notify HAL
5223 mNotifyPipelineDrain = true;
5224 mStreamIdsToBeDrained = streamIds;
5225}
5226
Yin-Chia Yehe52b8fa2020-07-28 00:17:58 -07005227void Camera3Device::RequestThread::resetPipelineDrain() {
5228 Mutex::Autolock pl(mPauseLock);
5229 mNotifyPipelineDrain = false;
5230 mStreamIdsToBeDrained.clear();
5231}
5232
Emilian Peevc0fe54c2020-03-11 14:05:07 -07005233void Camera3Device::RequestThread::clearPreviousRequest() {
5234 Mutex::Autolock l(mRequestLock);
5235 mPrevRequest.clear();
5236}
5237
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005238status_t Camera3Device::RequestThread::switchToOffline(
5239 const std::vector<int32_t>& streamsToKeep,
5240 /*out*/hardware::camera::device::V3_6::CameraOfflineSessionInfo* offlineSessionInfo,
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005241 /*out*/sp<hardware::camera::device::V3_6::ICameraOfflineSession>* offlineSession,
5242 /*out*/camera3::BufferRecords* bufferRecords) {
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005243 Mutex::Autolock l(mRequestLock);
5244 clearRepeatingRequestsLocked(/*lastFrameNumber*/nullptr);
5245
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005246 // Wait until request thread is fully stopped
5247 // TBD: check if request thread is being paused by other APIs (shouldn't be)
5248
5249 // We could also check for mRepeatingRequests.empty(), but the API interface
5250 // is serialized by Camera3Device::mInterfaceLock so no one should be able to submit any
5251 // new requests during the call; hence skip that check.
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005252 bool queueEmpty = mNextRequests.empty() && mRequestQueue.empty();
5253 while (!queueEmpty) {
5254 status_t res = mRequestSubmittedSignal.waitRelative(mRequestLock, kRequestSubmitTimeout);
5255 if (res == TIMED_OUT) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005256 ALOGE("%s: request thread failed to submit one request within timeout!", __FUNCTION__);
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005257 return res;
5258 } else if (res != OK) {
5259 ALOGE("%s: request thread failed to submit a request: %s (%d)!",
5260 __FUNCTION__, strerror(-res), res);
5261 return res;
5262 }
5263 queueEmpty = mNextRequests.empty() && mRequestQueue.empty();
5264 }
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005265
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005266 return mInterface->switchToOffline(
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005267 streamsToKeep, offlineSessionInfo, offlineSession, bufferRecords);
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005268}
5269
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005270status_t Camera3Device::RequestThread::setRotateAndCropAutoBehavior(
5271 camera_metadata_enum_android_scaler_rotate_and_crop_t rotateAndCropValue) {
5272 ATRACE_CALL();
5273 Mutex::Autolock l(mTriggerMutex);
5274 if (rotateAndCropValue == ANDROID_SCALER_ROTATE_AND_CROP_AUTO) {
5275 return BAD_VALUE;
5276 }
5277 mRotateAndCropOverride = rotateAndCropValue;
5278 return OK;
5279}
5280
Eino-Ville Talvala11afe4f2021-05-27 14:45:31 -07005281status_t Camera3Device::RequestThread::setCameraMute(int32_t muteMode) {
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005282 ATRACE_CALL();
5283 Mutex::Autolock l(mTriggerMutex);
Eino-Ville Talvala11afe4f2021-05-27 14:45:31 -07005284 if (muteMode != mCameraMute) {
5285 mCameraMute = muteMode;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005286 mCameraMuteChanged = true;
5287 }
5288 return OK;
5289}
5290
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07005291nsecs_t Camera3Device::getExpectedInFlightDuration() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005292 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005293 std::lock_guard<std::mutex> l(mInFlightLock);
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07005294 return mExpectedInflightDuration > kMinInflightDuration ?
5295 mExpectedInflightDuration : kMinInflightDuration;
5296}
5297
Emilian Peevaebbe412018-01-15 13:53:24 +00005298void Camera3Device::RequestThread::cleanupPhysicalSettings(sp<CaptureRequest> request,
Emilian Peevf4816702020-04-03 15:44:51 -07005299 camera_capture_request_t *halRequest) {
Emilian Peevaebbe412018-01-15 13:53:24 +00005300 if ((request == nullptr) || (halRequest == nullptr)) {
5301 ALOGE("%s: Invalid request!", __FUNCTION__);
5302 return;
5303 }
5304
5305 if (halRequest->num_physcam_settings > 0) {
5306 if (halRequest->physcam_id != nullptr) {
5307 delete [] halRequest->physcam_id;
5308 halRequest->physcam_id = nullptr;
5309 }
5310 if (halRequest->physcam_settings != nullptr) {
5311 auto it = ++(request->mSettingsList.begin());
5312 size_t i = 0;
5313 for (; it != request->mSettingsList.end(); it++, i++) {
5314 it->metadata.unlock(halRequest->physcam_settings[i]);
5315 }
5316 delete [] halRequest->physcam_settings;
5317 halRequest->physcam_settings = nullptr;
5318 }
5319 }
5320}
5321
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005322void Camera3Device::RequestThread::cleanUpFailedRequests(bool sendRequestError) {
5323 if (mNextRequests.empty()) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005324 return;
5325 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005326
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005327 for (auto& nextRequest : mNextRequests) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005328 // Skip the ones that have been submitted successfully.
5329 if (nextRequest.submitted) {
5330 continue;
5331 }
5332
5333 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
Emilian Peevf4816702020-04-03 15:44:51 -07005334 camera_capture_request_t* halRequest = &nextRequest.halRequest;
5335 Vector<camera_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005336
5337 if (halRequest->settings != NULL) {
Emilian Peevaebbe412018-01-15 13:53:24 +00005338 captureRequest->mSettingsList.begin()->metadata.unlock(halRequest->settings);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005339 }
5340
Emilian Peevaebbe412018-01-15 13:53:24 +00005341 cleanupPhysicalSettings(captureRequest, halRequest);
5342
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005343 if (captureRequest->mInputStream != NULL) {
Emilian Peevf4816702020-04-03 15:44:51 -07005344 captureRequest->mInputBuffer.status = CAMERA_BUFFER_STATUS_ERROR;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005345 captureRequest->mInputStream->returnInputBuffer(captureRequest->mInputBuffer);
5346 }
5347
Yin-Chia Yeh21cb47b2019-01-18 15:08:17 -08005348 // No output buffer can be returned when using HAL buffer manager
5349 if (!mUseHalBufManager) {
5350 for (size_t i = 0; i < halRequest->num_output_buffers; i++) {
5351 //Buffers that failed processing could still have
5352 //valid acquire fence.
5353 int acquireFence = (*outputBuffers)[i].acquire_fence;
5354 if (0 <= acquireFence) {
5355 close(acquireFence);
5356 outputBuffers->editItemAt(i).acquire_fence = -1;
5357 }
Emilian Peevf4816702020-04-03 15:44:51 -07005358 outputBuffers->editItemAt(i).status = CAMERA_BUFFER_STATUS_ERROR;
Yin-Chia Yeh21cb47b2019-01-18 15:08:17 -08005359 captureRequest->mOutputStreams.editItemAt(i)->returnBuffer((*outputBuffers)[i], 0,
5360 /*timestampIncreasing*/true, std::vector<size_t> (),
5361 captureRequest->mResultExtras.frameNumber);
Emilian Peevc58cf4c2017-05-11 17:23:41 +01005362 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005363 }
5364
5365 if (sendRequestError) {
5366 Mutex::Autolock l(mRequestLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005367 sp<NotificationListener> listener = mListener.promote();
5368 if (listener != NULL) {
5369 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08005370 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005371 captureRequest->mResultExtras);
5372 }
5373 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07005374
5375 // Remove yet-to-be submitted inflight request from inflightMap
5376 {
5377 sp<Camera3Device> parent = mParent.promote();
5378 if (parent != NULL) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005379 std::lock_guard<std::mutex> l(parent->mInFlightLock);
Shuzhen Wangcadb3302016-11-04 14:17:56 -07005380 ssize_t idx = parent->mInFlightMap.indexOfKey(captureRequest->mResultExtras.frameNumber);
5381 if (idx >= 0) {
5382 ALOGV("%s: Remove inflight request from queue: frameNumber %" PRId64,
5383 __FUNCTION__, captureRequest->mResultExtras.frameNumber);
5384 parent->removeInFlightMapEntryLocked(idx);
5385 }
5386 }
5387 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005388 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07005389
5390 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005391 mNextRequests.clear();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005392}
5393
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005394void Camera3Device::RequestThread::waitForNextRequestBatch() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005395 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005396 // Optimized a bit for the simple steady-state case (single repeating
5397 // request), to avoid putting that request in the queue temporarily.
5398 Mutex::Autolock l(mRequestLock);
5399
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005400 assert(mNextRequests.empty());
5401
5402 NextRequest nextRequest;
5403 nextRequest.captureRequest = waitForNextRequestLocked();
5404 if (nextRequest.captureRequest == nullptr) {
5405 return;
5406 }
5407
Emilian Peevf4816702020-04-03 15:44:51 -07005408 nextRequest.halRequest = camera_capture_request_t();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005409 nextRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005410 mNextRequests.add(nextRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005411
5412 // Wait for additional requests
5413 const size_t batchSize = nextRequest.captureRequest->mBatchSize;
5414
5415 for (size_t i = 1; i < batchSize; i++) {
5416 NextRequest additionalRequest;
5417 additionalRequest.captureRequest = waitForNextRequestLocked();
5418 if (additionalRequest.captureRequest == nullptr) {
5419 break;
5420 }
5421
Emilian Peevf4816702020-04-03 15:44:51 -07005422 additionalRequest.halRequest = camera_capture_request_t();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005423 additionalRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005424 mNextRequests.add(additionalRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005425 }
5426
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005427 if (mNextRequests.size() < batchSize) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08005428 ALOGE("RequestThread: only get %zu out of %zu requests. Skipping requests.",
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005429 mNextRequests.size(), batchSize);
5430 cleanUpFailedRequests(/*sendRequestError*/true);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005431 }
5432
5433 return;
5434}
5435
5436sp<Camera3Device::CaptureRequest>
5437 Camera3Device::RequestThread::waitForNextRequestLocked() {
5438 status_t res;
5439 sp<CaptureRequest> nextRequest;
5440
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005441 while (mRequestQueue.empty()) {
5442 if (!mRepeatingRequests.empty()) {
5443 // Always atomically enqueue all requests in a repeating request
5444 // list. Guarantees a complete in-sequence set of captures to
5445 // application.
5446 const RequestList &requests = mRepeatingRequests;
Shuzhen Wang316781a2020-08-18 18:11:01 -07005447 if (mFirstRepeating) {
5448 mFirstRepeating = false;
5449 } else {
5450 for (auto& request : requests) {
5451 // For repeating requests, override timestamp request using
5452 // the time a request is inserted into the request queue,
5453 // because the original repeating request will have an old
5454 // fixed timestamp.
5455 request->mRequestTimeNs = systemTime();
5456 }
5457 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005458 RequestList::const_iterator firstRequest =
5459 requests.begin();
5460 nextRequest = *firstRequest;
5461 mRequestQueue.insert(mRequestQueue.end(),
5462 ++firstRequest,
5463 requests.end());
5464 // No need to wait any longer
Jianing Weicb0652e2014-03-12 18:29:36 -07005465
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005466 mRepeatingLastFrameNumber = mFrameNumber + requests.size() - 1;
Jianing Weicb0652e2014-03-12 18:29:36 -07005467
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005468 break;
5469 }
5470
5471 res = mRequestSignal.waitRelative(mRequestLock, kRequestTimeout);
5472
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005473 if ((mRequestQueue.empty() && mRepeatingRequests.empty()) ||
5474 exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005475 Mutex::Autolock pl(mPauseLock);
5476 if (mPaused == false) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005477 ALOGV("%s: RequestThread: Going idle", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005478 mPaused = true;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07005479 if (mNotifyPipelineDrain) {
5480 mInterface->signalPipelineDrain(mStreamIdsToBeDrained);
5481 mNotifyPipelineDrain = false;
5482 mStreamIdsToBeDrained.clear();
5483 }
Yin-Chia Yehc300a072019-02-13 14:56:57 -08005484 // Let the tracker know
5485 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5486 if (statusTracker != 0) {
5487 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
5488 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005489 sp<Camera3Device> parent = mParent.promote();
5490 if (parent != nullptr) {
5491 parent->mRequestBufferSM.onRequestThreadPaused();
5492 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005493 }
5494 // Stop waiting for now and let thread management happen
5495 return NULL;
5496 }
5497 }
5498
5499 if (nextRequest == NULL) {
5500 // Don't have a repeating request already in hand, so queue
5501 // must have an entry now.
5502 RequestList::iterator firstRequest =
5503 mRequestQueue.begin();
5504 nextRequest = *firstRequest;
5505 mRequestQueue.erase(firstRequest);
Shuzhen Wang9d066012016-09-30 11:30:20 -07005506 if (mRequestQueue.empty() && !nextRequest->mRepeating) {
5507 sp<NotificationListener> listener = mListener.promote();
5508 if (listener != NULL) {
5509 listener->notifyRequestQueueEmpty();
5510 }
5511 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005512 }
5513
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005514 // In case we've been unpaused by setPaused clearing mDoPause, need to
5515 // update internal pause state (capture/setRepeatingRequest unpause
5516 // directly).
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005517 Mutex::Autolock pl(mPauseLock);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005518 if (mPaused) {
5519 ALOGV("%s: RequestThread: Unpaused", __FUNCTION__);
5520 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5521 if (statusTracker != 0) {
5522 statusTracker->markComponentActive(mStatusId);
5523 }
5524 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005525 mPaused = false;
5526
5527 // Check if we've reconfigured since last time, and reset the preview
5528 // request if so. Can't use 'NULL request == repeat' across configure calls.
5529 if (mReconfigured) {
5530 mPrevRequest.clear();
5531 mReconfigured = false;
5532 }
5533
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005534 if (nextRequest != NULL) {
5535 nextRequest->mResultExtras.frameNumber = mFrameNumber++;
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07005536 nextRequest->mResultExtras.afTriggerId = mCurrentAfTriggerId;
5537 nextRequest->mResultExtras.precaptureTriggerId = mCurrentPreCaptureTriggerId;
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07005538
5539 // Since RequestThread::clear() removes buffers from the input stream,
5540 // get the right buffer here before unlocking mRequestLock
5541 if (nextRequest->mInputStream != NULL) {
Shuzhen Wang83bff122020-11-20 15:51:39 -08005542 res = nextRequest->mInputStream->getInputBuffer(&nextRequest->mInputBuffer,
5543 &nextRequest->mInputBufferSize);
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07005544 if (res != OK) {
5545 // Can't get input buffer from gralloc queue - this could be due to
5546 // disconnected queue or other producer misbehavior, so not a fatal
5547 // error
5548 ALOGE("%s: Can't get input buffer, skipping request:"
5549 " %s (%d)", __FUNCTION__, strerror(-res), res);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005550
5551 sp<NotificationListener> listener = mListener.promote();
5552 if (listener != NULL) {
5553 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08005554 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07005555 nextRequest->mResultExtras);
5556 }
5557 return NULL;
5558 }
5559 }
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005560 }
Chien-Yu Chend196d612015-06-22 19:49:01 -07005561
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005562 return nextRequest;
5563}
5564
5565bool Camera3Device::RequestThread::waitIfPaused() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005566 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005567 status_t res;
5568 Mutex::Autolock l(mPauseLock);
5569 while (mDoPause) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005570 if (mPaused == false) {
5571 mPaused = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005572 ALOGV("%s: RequestThread: Paused", __FUNCTION__);
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07005573 if (mNotifyPipelineDrain) {
5574 mInterface->signalPipelineDrain(mStreamIdsToBeDrained);
5575 mNotifyPipelineDrain = false;
5576 mStreamIdsToBeDrained.clear();
5577 }
Yin-Chia Yehc300a072019-02-13 14:56:57 -08005578 // Let the tracker know
5579 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5580 if (statusTracker != 0) {
5581 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
5582 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005583 sp<Camera3Device> parent = mParent.promote();
5584 if (parent != nullptr) {
5585 parent->mRequestBufferSM.onRequestThreadPaused();
5586 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005587 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005588
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005589 res = mDoPauseSignal.waitRelative(mPauseLock, kRequestTimeout);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005590 if (res == TIMED_OUT || exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005591 return true;
5592 }
5593 }
5594 // We don't set mPaused to false here, because waitForNextRequest needs
5595 // to further manage the paused state in case of starvation.
5596 return false;
5597}
5598
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005599void Camera3Device::RequestThread::unpauseForNewRequests() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005600 ATRACE_CALL();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005601 // With work to do, mark thread as unpaused.
5602 // If paused by request (setPaused), don't resume, to avoid
5603 // extra signaling/waiting overhead to waitUntilPaused
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005604 mRequestSignal.signal();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005605 Mutex::Autolock p(mPauseLock);
5606 if (!mDoPause) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005607 ALOGV("%s: RequestThread: Going active", __FUNCTION__);
5608 if (mPaused) {
5609 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5610 if (statusTracker != 0) {
5611 statusTracker->markComponentActive(mStatusId);
5612 }
5613 }
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005614 mPaused = false;
5615 }
5616}
5617
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07005618void Camera3Device::RequestThread::setErrorState(const char *fmt, ...) {
5619 sp<Camera3Device> parent = mParent.promote();
5620 if (parent != NULL) {
5621 va_list args;
5622 va_start(args, fmt);
5623
5624 parent->setErrorStateV(fmt, args);
5625
5626 va_end(args);
5627 }
5628}
5629
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005630status_t Camera3Device::RequestThread::insertTriggers(
5631 const sp<CaptureRequest> &request) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005632 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005633 Mutex::Autolock al(mTriggerMutex);
5634
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07005635 sp<Camera3Device> parent = mParent.promote();
5636 if (parent == NULL) {
5637 CLOGE("RequestThread: Parent is gone");
5638 return DEAD_OBJECT;
5639 }
5640
Emilian Peevaebbe412018-01-15 13:53:24 +00005641 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005642 size_t count = mTriggerMap.size();
5643
5644 for (size_t i = 0; i < count; ++i) {
5645 RequestTrigger trigger = mTriggerMap.valueAt(i);
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005646 uint32_t tag = trigger.metadataTag;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07005647
5648 if (tag == ANDROID_CONTROL_AF_TRIGGER_ID || tag == ANDROID_CONTROL_AE_PRECAPTURE_ID) {
5649 bool isAeTrigger = (trigger.metadataTag == ANDROID_CONTROL_AE_PRECAPTURE_ID);
5650 uint32_t triggerId = static_cast<uint32_t>(trigger.entryValue);
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07005651 if (isAeTrigger) {
5652 request->mResultExtras.precaptureTriggerId = triggerId;
5653 mCurrentPreCaptureTriggerId = triggerId;
5654 } else {
5655 request->mResultExtras.afTriggerId = triggerId;
5656 mCurrentAfTriggerId = triggerId;
5657 }
Emilian Peev7e25e5e2017-04-07 15:48:49 +01005658 continue;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07005659 }
5660
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005661 camera_metadata_entry entry = metadata.find(tag);
5662
5663 if (entry.count > 0) {
5664 /**
5665 * Already has an entry for this trigger in the request.
5666 * Rewrite it with our requested trigger value.
5667 */
5668 RequestTrigger oldTrigger = trigger;
5669
5670 oldTrigger.entryValue = entry.data.u8[0];
5671
5672 mTriggerReplacedMap.add(tag, oldTrigger);
5673 } else {
5674 /**
5675 * More typical, no trigger entry, so we just add it
5676 */
5677 mTriggerRemovedMap.add(tag, trigger);
5678 }
5679
5680 status_t res;
5681
5682 switch (trigger.getTagType()) {
5683 case TYPE_BYTE: {
5684 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
5685 res = metadata.update(tag,
5686 &entryValue,
5687 /*count*/1);
5688 break;
5689 }
5690 case TYPE_INT32:
5691 res = metadata.update(tag,
5692 &trigger.entryValue,
5693 /*count*/1);
5694 break;
5695 default:
5696 ALOGE("%s: Type not supported: 0x%x",
5697 __FUNCTION__,
5698 trigger.getTagType());
5699 return INVALID_OPERATION;
5700 }
5701
5702 if (res != OK) {
5703 ALOGE("%s: Failed to update request metadata with trigger tag %s"
5704 ", value %d", __FUNCTION__, trigger.getTagName(),
5705 trigger.entryValue);
5706 return res;
5707 }
5708
5709 ALOGV("%s: Mixed in trigger %s, value %d", __FUNCTION__,
5710 trigger.getTagName(),
5711 trigger.entryValue);
5712 }
5713
5714 mTriggerMap.clear();
5715
5716 return count;
5717}
5718
5719status_t Camera3Device::RequestThread::removeTriggers(
5720 const sp<CaptureRequest> &request) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005721 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005722 Mutex::Autolock al(mTriggerMutex);
5723
Emilian Peevaebbe412018-01-15 13:53:24 +00005724 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005725
5726 /**
5727 * Replace all old entries with their old values.
5728 */
5729 for (size_t i = 0; i < mTriggerReplacedMap.size(); ++i) {
5730 RequestTrigger trigger = mTriggerReplacedMap.valueAt(i);
5731
5732 status_t res;
5733
5734 uint32_t tag = trigger.metadataTag;
5735 switch (trigger.getTagType()) {
5736 case TYPE_BYTE: {
5737 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
5738 res = metadata.update(tag,
5739 &entryValue,
5740 /*count*/1);
5741 break;
5742 }
5743 case TYPE_INT32:
5744 res = metadata.update(tag,
5745 &trigger.entryValue,
5746 /*count*/1);
5747 break;
5748 default:
5749 ALOGE("%s: Type not supported: 0x%x",
5750 __FUNCTION__,
5751 trigger.getTagType());
5752 return INVALID_OPERATION;
5753 }
5754
5755 if (res != OK) {
5756 ALOGE("%s: Failed to restore request metadata with trigger tag %s"
5757 ", trigger value %d", __FUNCTION__,
5758 trigger.getTagName(), trigger.entryValue);
5759 return res;
5760 }
5761 }
5762 mTriggerReplacedMap.clear();
5763
5764 /**
5765 * Remove all new entries.
5766 */
5767 for (size_t i = 0; i < mTriggerRemovedMap.size(); ++i) {
5768 RequestTrigger trigger = mTriggerRemovedMap.valueAt(i);
5769 status_t res = metadata.erase(trigger.metadataTag);
5770
5771 if (res != OK) {
5772 ALOGE("%s: Failed to erase metadata with trigger tag %s"
5773 ", trigger value %d", __FUNCTION__,
5774 trigger.getTagName(), trigger.entryValue);
5775 return res;
5776 }
5777 }
5778 mTriggerRemovedMap.clear();
5779
5780 return OK;
5781}
5782
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04005783status_t Camera3Device::RequestThread::addFakeTriggerIds(
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005784 const sp<CaptureRequest> &request) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08005785 // Trigger ID 0 had special meaning in the HAL2 spec, so avoid it here
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04005786 static const int32_t fakeTriggerId = 1;
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005787 status_t res;
5788
Emilian Peevaebbe412018-01-15 13:53:24 +00005789 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005790
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04005791 // If AF trigger is active, insert a fake AF trigger ID if none already
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005792 // exists
5793 camera_metadata_entry afTrigger = metadata.find(ANDROID_CONTROL_AF_TRIGGER);
5794 camera_metadata_entry afId = metadata.find(ANDROID_CONTROL_AF_TRIGGER_ID);
5795 if (afTrigger.count > 0 &&
5796 afTrigger.data.u8[0] != ANDROID_CONTROL_AF_TRIGGER_IDLE &&
5797 afId.count == 0) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04005798 res = metadata.update(ANDROID_CONTROL_AF_TRIGGER_ID, &fakeTriggerId, 1);
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005799 if (res != OK) return res;
5800 }
5801
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04005802 // If AE precapture trigger is active, insert a fake precapture trigger ID
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005803 // if none already exists
5804 camera_metadata_entry pcTrigger =
5805 metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER);
5806 camera_metadata_entry pcId = metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_ID);
5807 if (pcTrigger.count > 0 &&
5808 pcTrigger.data.u8[0] != ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_IDLE &&
5809 pcId.count == 0) {
5810 res = metadata.update(ANDROID_CONTROL_AE_PRECAPTURE_ID,
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04005811 &fakeTriggerId, 1);
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005812 if (res != OK) return res;
5813 }
5814
5815 return OK;
5816}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005817
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005818bool Camera3Device::RequestThread::overrideAutoRotateAndCrop(
5819 const sp<CaptureRequest> &request) {
5820 ATRACE_CALL();
5821
5822 if (request->mRotateAndCropAuto) {
5823 Mutex::Autolock l(mTriggerMutex);
5824 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
5825
5826 auto rotateAndCropEntry = metadata.find(ANDROID_SCALER_ROTATE_AND_CROP);
5827 if (rotateAndCropEntry.count > 0) {
5828 if (rotateAndCropEntry.data.u8[0] == mRotateAndCropOverride) {
5829 return false;
5830 } else {
5831 rotateAndCropEntry.data.u8[0] = mRotateAndCropOverride;
5832 return true;
5833 }
5834 } else {
5835 uint8_t rotateAndCrop_u8 = mRotateAndCropOverride;
5836 metadata.update(ANDROID_SCALER_ROTATE_AND_CROP,
5837 &rotateAndCrop_u8, 1);
5838 return true;
5839 }
5840 }
5841 return false;
5842}
5843
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005844bool Camera3Device::RequestThread::overrideTestPattern(
5845 const sp<CaptureRequest> &request) {
5846 ATRACE_CALL();
5847
5848 Mutex::Autolock l(mTriggerMutex);
5849
5850 bool changed = false;
5851
5852 int32_t testPatternMode = request->mOriginalTestPatternMode;
5853 int32_t testPatternData[4] = {
5854 request->mOriginalTestPatternData[0],
5855 request->mOriginalTestPatternData[1],
5856 request->mOriginalTestPatternData[2],
5857 request->mOriginalTestPatternData[3]
5858 };
5859
Eino-Ville Talvala11afe4f2021-05-27 14:45:31 -07005860 if (mCameraMute != ANDROID_SENSOR_TEST_PATTERN_MODE_OFF) {
5861 testPatternMode = mCameraMute;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005862 testPatternData[0] = 0;
5863 testPatternData[1] = 0;
5864 testPatternData[2] = 0;
5865 testPatternData[3] = 0;
5866 }
5867
5868 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
5869
5870 auto testPatternEntry = metadata.find(ANDROID_SENSOR_TEST_PATTERN_MODE);
5871 if (testPatternEntry.count > 0) {
5872 if (testPatternEntry.data.i32[0] != testPatternMode) {
5873 testPatternEntry.data.i32[0] = testPatternMode;
5874 changed = true;
5875 }
5876 } else {
5877 metadata.update(ANDROID_SENSOR_TEST_PATTERN_MODE,
5878 &testPatternMode, 1);
5879 changed = true;
5880 }
5881
5882 auto testPatternColor = metadata.find(ANDROID_SENSOR_TEST_PATTERN_DATA);
5883 if (testPatternColor.count > 0) {
5884 for (size_t i = 0; i < 4; i++) {
5885 if (testPatternColor.data.i32[i] != (int32_t)testPatternData[i]) {
5886 testPatternColor.data.i32[i] = testPatternData[i];
5887 changed = true;
5888 }
5889 }
5890 } else {
5891 metadata.update(ANDROID_SENSOR_TEST_PATTERN_DATA,
5892 (int32_t*)testPatternData, 4);
5893 changed = true;
5894 }
5895
5896 return changed;
5897}
5898
Cliff Wuc2ad9c82021-04-21 00:58:58 +08005899status_t Camera3Device::RequestThread::setHalInterface(
5900 sp<HalInterface> newHalInterface) {
5901 if (newHalInterface.get() == nullptr) {
5902 ALOGE("%s: The newHalInterface does not exist!", __FUNCTION__);
5903 return DEAD_OBJECT;
5904 }
5905
5906 mInterface = newHalInterface;
5907
5908 return OK;
5909}
5910
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005911/**
5912 * PreparerThread inner class methods
5913 */
5914
5915Camera3Device::PreparerThread::PreparerThread() :
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07005916 Thread(/*canCallJava*/false), mListener(nullptr),
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005917 mActive(false), mCancelNow(false), mCurrentMaxCount(0), mCurrentPrepareComplete(false) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005918}
5919
5920Camera3Device::PreparerThread::~PreparerThread() {
5921 Thread::requestExitAndWait();
5922 if (mCurrentStream != nullptr) {
5923 mCurrentStream->cancelPrepare();
5924 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
5925 mCurrentStream.clear();
5926 }
5927 clear();
5928}
5929
Ruben Brunkc78ac262015-08-13 17:58:46 -07005930status_t Camera3Device::PreparerThread::prepare(int maxCount, sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005931 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005932 status_t res;
5933
5934 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005935 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005936
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07005937 res = stream->startPrepare(maxCount, true /*blockRequest*/);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005938 if (res == OK) {
5939 // No preparation needed, fire listener right off
5940 ALOGV("%s: Stream %d already prepared", __FUNCTION__, stream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005941 if (listener != NULL) {
5942 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005943 }
5944 return OK;
5945 } else if (res != NOT_ENOUGH_DATA) {
5946 return res;
5947 }
5948
5949 // Need to prepare, start up thread if necessary
5950 if (!mActive) {
5951 // mRunning will change to false before the thread fully shuts down, so wait to be sure it
5952 // isn't running
5953 Thread::requestExitAndWait();
5954 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
5955 if (res != OK) {
5956 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__, res, strerror(-res));
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005957 if (listener != NULL) {
5958 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005959 }
5960 return res;
5961 }
5962 mCancelNow = false;
5963 mActive = true;
5964 ALOGV("%s: Preparer stream started", __FUNCTION__);
5965 }
5966
5967 // queue up the work
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005968 mPendingStreams.emplace(maxCount, stream);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005969 ALOGV("%s: Stream %d queued for preparing", __FUNCTION__, stream->getId());
5970
5971 return OK;
5972}
5973
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005974void Camera3Device::PreparerThread::pause() {
5975 ATRACE_CALL();
5976
5977 Mutex::Autolock l(mLock);
5978
5979 std::unordered_map<int, sp<camera3::Camera3StreamInterface> > pendingStreams;
5980 pendingStreams.insert(mPendingStreams.begin(), mPendingStreams.end());
5981 sp<camera3::Camera3StreamInterface> currentStream = mCurrentStream;
5982 int currentMaxCount = mCurrentMaxCount;
5983 mPendingStreams.clear();
5984 mCancelNow = true;
5985 while (mActive) {
5986 auto res = mThreadActiveSignal.waitRelative(mLock, kActiveTimeout);
5987 if (res == TIMED_OUT) {
5988 ALOGE("%s: Timed out waiting on prepare thread!", __FUNCTION__);
5989 return;
5990 } else if (res != OK) {
5991 ALOGE("%s: Encountered an error: %d waiting on prepare thread!", __FUNCTION__, res);
5992 return;
5993 }
5994 }
5995
5996 //Check whether the prepare thread was able to complete the current
5997 //stream. In case work is still pending emplace it along with the rest
5998 //of the streams in the pending list.
5999 if (currentStream != nullptr) {
6000 if (!mCurrentPrepareComplete) {
6001 pendingStreams.emplace(currentMaxCount, currentStream);
6002 }
6003 }
6004
6005 mPendingStreams.insert(pendingStreams.begin(), pendingStreams.end());
6006 for (const auto& it : mPendingStreams) {
6007 it.second->cancelPrepare();
6008 }
6009}
6010
6011status_t Camera3Device::PreparerThread::resume() {
6012 ATRACE_CALL();
6013 status_t res;
6014
6015 Mutex::Autolock l(mLock);
6016 sp<NotificationListener> listener = mListener.promote();
6017
6018 if (mActive) {
6019 ALOGE("%s: Trying to resume an already active prepare thread!", __FUNCTION__);
6020 return NO_INIT;
6021 }
6022
6023 auto it = mPendingStreams.begin();
6024 for (; it != mPendingStreams.end();) {
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07006025 res = it->second->startPrepare(it->first, true /*blockRequest*/);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006026 if (res == OK) {
6027 if (listener != NULL) {
6028 listener->notifyPrepared(it->second->getId());
6029 }
6030 it = mPendingStreams.erase(it);
6031 } else if (res != NOT_ENOUGH_DATA) {
6032 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__,
6033 res, strerror(-res));
6034 it = mPendingStreams.erase(it);
6035 } else {
6036 it++;
6037 }
6038 }
6039
6040 if (mPendingStreams.empty()) {
6041 return OK;
6042 }
6043
6044 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
6045 if (res != OK) {
6046 ALOGE("%s: Unable to start preparer stream: %d (%s)",
6047 __FUNCTION__, res, strerror(-res));
6048 return res;
6049 }
6050 mCancelNow = false;
6051 mActive = true;
6052 ALOGV("%s: Preparer stream started", __FUNCTION__);
6053
6054 return OK;
6055}
6056
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006057status_t Camera3Device::PreparerThread::clear() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07006058 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006059 Mutex::Autolock l(mLock);
6060
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006061 for (const auto& it : mPendingStreams) {
6062 it.second->cancelPrepare();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006063 }
6064 mPendingStreams.clear();
6065 mCancelNow = true;
6066
6067 return OK;
6068}
6069
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006070void Camera3Device::PreparerThread::setNotificationListener(wp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07006071 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006072 Mutex::Autolock l(mLock);
6073 mListener = listener;
6074}
6075
6076bool Camera3Device::PreparerThread::threadLoop() {
6077 status_t res;
6078 {
6079 Mutex::Autolock l(mLock);
6080 if (mCurrentStream == nullptr) {
6081 // End thread if done with work
6082 if (mPendingStreams.empty()) {
6083 ALOGV("%s: Preparer stream out of work", __FUNCTION__);
6084 // threadLoop _must not_ re-acquire mLock after it sets mActive to false; would
6085 // cause deadlock with prepare()'s requestExitAndWait triggered by !mActive.
6086 mActive = false;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006087 mThreadActiveSignal.signal();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006088 return false;
6089 }
6090
6091 // Get next stream to prepare
6092 auto it = mPendingStreams.begin();
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006093 mCurrentStream = it->second;
6094 mCurrentMaxCount = it->first;
6095 mCurrentPrepareComplete = false;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006096 mPendingStreams.erase(it);
6097 ATRACE_ASYNC_BEGIN("stream prepare", mCurrentStream->getId());
6098 ALOGV("%s: Preparing stream %d", __FUNCTION__, mCurrentStream->getId());
6099 } else if (mCancelNow) {
6100 mCurrentStream->cancelPrepare();
6101 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
6102 ALOGV("%s: Cancelling stream %d prepare", __FUNCTION__, mCurrentStream->getId());
6103 mCurrentStream.clear();
6104 mCancelNow = false;
6105 return true;
6106 }
6107 }
6108
6109 res = mCurrentStream->prepareNextBuffer();
6110 if (res == NOT_ENOUGH_DATA) return true;
6111 if (res != OK) {
6112 // Something bad happened; try to recover by cancelling prepare and
6113 // signalling listener anyway
6114 ALOGE("%s: Stream %d returned error %d (%s) during prepare", __FUNCTION__,
6115 mCurrentStream->getId(), res, strerror(-res));
6116 mCurrentStream->cancelPrepare();
6117 }
6118
6119 // This stream has finished, notify listener
6120 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006121 sp<NotificationListener> listener = mListener.promote();
6122 if (listener != NULL) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006123 ALOGV("%s: Stream %d prepare done, signaling listener", __FUNCTION__,
6124 mCurrentStream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006125 listener->notifyPrepared(mCurrentStream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006126 }
6127
6128 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
6129 mCurrentStream.clear();
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006130 mCurrentPrepareComplete = true;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006131
6132 return true;
6133}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07006134
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006135status_t Camera3Device::RequestBufferStateMachine::initialize(
6136 sp<camera3::StatusTracker> statusTracker) {
6137 if (statusTracker == nullptr) {
6138 ALOGE("%s: statusTracker is null", __FUNCTION__);
6139 return BAD_VALUE;
6140 }
6141
6142 std::lock_guard<std::mutex> lock(mLock);
6143 mStatusTracker = statusTracker;
Yin-Chia Yeh87b3ec02019-06-03 10:44:39 -07006144 mRequestBufferStatusId = statusTracker->addComponent("BufferRequestSM");
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006145 return OK;
6146}
6147
6148bool Camera3Device::RequestBufferStateMachine::startRequestBuffer() {
6149 std::lock_guard<std::mutex> lock(mLock);
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08006150 if (mStatus == RB_STATUS_READY || mStatus == RB_STATUS_PENDING_STOP) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006151 mRequestBufferOngoing = true;
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08006152 notifyTrackerLocked(/*active*/true);
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006153 return true;
6154 }
6155 return false;
6156}
6157
6158void Camera3Device::RequestBufferStateMachine::endRequestBuffer() {
6159 std::lock_guard<std::mutex> lock(mLock);
6160 if (!mRequestBufferOngoing) {
6161 ALOGE("%s called without a successful startRequestBuffer call first!", __FUNCTION__);
6162 return;
6163 }
6164 mRequestBufferOngoing = false;
6165 if (mStatus == RB_STATUS_PENDING_STOP) {
6166 checkSwitchToStopLocked();
6167 }
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08006168 notifyTrackerLocked(/*active*/false);
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006169}
6170
6171void Camera3Device::RequestBufferStateMachine::onStreamsConfigured() {
6172 std::lock_guard<std::mutex> lock(mLock);
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006173 mSwitchedToOffline = false;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006174 mStatus = RB_STATUS_READY;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006175 return;
6176}
6177
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08006178void Camera3Device::RequestBufferStateMachine::onSubmittingRequest() {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006179 std::lock_guard<std::mutex> lock(mLock);
6180 mRequestThreadPaused = false;
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08006181 // inflight map register actually happens in prepareHalRequest now, but it is close enough
6182 // approximation.
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006183 mInflightMapEmpty = false;
6184 if (mStatus == RB_STATUS_STOPPED) {
6185 mStatus = RB_STATUS_READY;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006186 }
6187 return;
6188}
6189
6190void Camera3Device::RequestBufferStateMachine::onRequestThreadPaused() {
6191 std::lock_guard<std::mutex> lock(mLock);
6192 mRequestThreadPaused = true;
6193 if (mStatus == RB_STATUS_PENDING_STOP) {
6194 checkSwitchToStopLocked();
6195 }
6196 return;
6197}
6198
6199void Camera3Device::RequestBufferStateMachine::onInflightMapEmpty() {
6200 std::lock_guard<std::mutex> lock(mLock);
6201 mInflightMapEmpty = true;
6202 if (mStatus == RB_STATUS_PENDING_STOP) {
6203 checkSwitchToStopLocked();
6204 }
6205 return;
6206}
6207
6208void Camera3Device::RequestBufferStateMachine::onWaitUntilIdle() {
6209 std::lock_guard<std::mutex> lock(mLock);
6210 if (!checkSwitchToStopLocked()) {
6211 mStatus = RB_STATUS_PENDING_STOP;
6212 }
6213 return;
6214}
6215
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006216bool Camera3Device::RequestBufferStateMachine::onSwitchToOfflineSuccess() {
6217 std::lock_guard<std::mutex> lock(mLock);
6218 if (mRequestBufferOngoing) {
6219 ALOGE("%s: HAL must not be requesting buffer after HAL returns switchToOffline!",
6220 __FUNCTION__);
6221 return false;
6222 }
6223 mSwitchedToOffline = true;
6224 mInflightMapEmpty = true;
6225 mRequestThreadPaused = true;
6226 mStatus = RB_STATUS_STOPPED;
6227 return true;
6228}
6229
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006230void Camera3Device::RequestBufferStateMachine::notifyTrackerLocked(bool active) {
6231 sp<StatusTracker> statusTracker = mStatusTracker.promote();
6232 if (statusTracker != nullptr) {
6233 if (active) {
6234 statusTracker->markComponentActive(mRequestBufferStatusId);
6235 } else {
6236 statusTracker->markComponentIdle(mRequestBufferStatusId, Fence::NO_FENCE);
6237 }
6238 }
6239}
6240
6241bool Camera3Device::RequestBufferStateMachine::checkSwitchToStopLocked() {
6242 if (mInflightMapEmpty && mRequestThreadPaused && !mRequestBufferOngoing) {
6243 mStatus = RB_STATUS_STOPPED;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006244 return true;
6245 }
6246 return false;
6247}
6248
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006249bool Camera3Device::startRequestBuffer() {
6250 return mRequestBufferSM.startRequestBuffer();
6251}
Shuzhen Wang268a1362018-10-16 16:32:59 -07006252
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006253void Camera3Device::endRequestBuffer() {
6254 mRequestBufferSM.endRequestBuffer();
6255}
Shuzhen Wang268a1362018-10-16 16:32:59 -07006256
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006257nsecs_t Camera3Device::getWaitDuration() {
6258 return kBaseGetBufferWait + getExpectedInFlightDuration();
6259}
Shuzhen Wang268a1362018-10-16 16:32:59 -07006260
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006261void Camera3Device::getInflightBufferKeys(std::vector<std::pair<int32_t, int32_t>>* out) {
6262 mInterface->getInflightBufferKeys(out);
6263}
Shuzhen Wang268a1362018-10-16 16:32:59 -07006264
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006265void Camera3Device::getInflightRequestBufferKeys(std::vector<uint64_t>* out) {
6266 mInterface->getInflightRequestBufferKeys(out);
6267}
Shuzhen Wang268a1362018-10-16 16:32:59 -07006268
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006269std::vector<sp<Camera3StreamInterface>> Camera3Device::getAllStreams() {
6270 std::vector<sp<Camera3StreamInterface>> ret;
6271 bool hasInputStream = mInputStream != nullptr;
6272 ret.reserve(mOutputStreams.size() + mDeletedStreams.size() + ((hasInputStream) ? 1 : 0));
6273 if (hasInputStream) {
6274 ret.push_back(mInputStream);
Shuzhen Wang268a1362018-10-16 16:32:59 -07006275 }
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006276 for (size_t i = 0; i < mOutputStreams.size(); i++) {
6277 ret.push_back(mOutputStreams[i]);
6278 }
6279 for (size_t i = 0; i < mDeletedStreams.size(); i++) {
6280 ret.push_back(mDeletedStreams[i]);
6281 }
6282 return ret;
Shuzhen Wang268a1362018-10-16 16:32:59 -07006283}
6284
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006285status_t Camera3Device::switchToOffline(
6286 const std::vector<int32_t>& streamsToKeep,
6287 /*out*/ sp<CameraOfflineSessionBase>* session) {
6288 ATRACE_CALL();
6289 if (session == nullptr) {
6290 ALOGE("%s: session must not be null", __FUNCTION__);
6291 return BAD_VALUE;
6292 }
6293
6294 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006295
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006296 bool hasInputStream = mInputStream != nullptr;
6297 int32_t inputStreamId = hasInputStream ? mInputStream->getId() : -1;
6298 bool inputStreamSupportsOffline = hasInputStream ?
6299 mInputStream->getOfflineProcessingSupport() : false;
6300 auto outputStreamIds = mOutputStreams.getStreamIds();
6301 auto streamIds = outputStreamIds;
6302 if (hasInputStream) {
6303 streamIds.push_back(mInputStream->getId());
6304 }
6305
6306 // Check all streams in streamsToKeep supports offline mode
6307 for (auto id : streamsToKeep) {
6308 if (std::find(streamIds.begin(), streamIds.end(), id) == streamIds.end()) {
6309 ALOGE("%s: Unknown stream ID %d", __FUNCTION__, id);
6310 return BAD_VALUE;
6311 } else if (id == inputStreamId) {
6312 if (!inputStreamSupportsOffline) {
6313 ALOGE("%s: input stream %d cannot be switched to offline",
6314 __FUNCTION__, id);
6315 return BAD_VALUE;
6316 }
6317 } else {
6318 sp<camera3::Camera3OutputStreamInterface> stream = mOutputStreams.get(id);
6319 if (!stream->getOfflineProcessingSupport()) {
6320 ALOGE("%s: output stream %d cannot be switched to offline",
6321 __FUNCTION__, id);
6322 return BAD_VALUE;
6323 }
6324 }
6325 }
6326
6327 // TODO: block surface sharing and surface group streams until we can support them
6328
6329 // Stop repeating request, wait until all remaining requests are submitted, then call into
6330 // HAL switchToOffline
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006331 hardware::camera::device::V3_6::CameraOfflineSessionInfo offlineSessionInfo;
6332 sp<hardware::camera::device::V3_6::ICameraOfflineSession> offlineSession;
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006333 camera3::BufferRecords bufferRecords;
6334 status_t ret = mRequestThread->switchToOffline(
6335 streamsToKeep, &offlineSessionInfo, &offlineSession, &bufferRecords);
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006336
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006337 if (ret != OK) {
6338 SET_ERR("Switch to offline failed: %s (%d)", strerror(-ret), ret);
6339 return ret;
6340 }
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006341
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006342 bool succ = mRequestBufferSM.onSwitchToOfflineSuccess();
6343 if (!succ) {
6344 SET_ERR("HAL must not be calling requestStreamBuffers call");
6345 // TODO: block ALL callbacks from HAL till app configured new streams?
6346 return UNKNOWN_ERROR;
6347 }
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006348
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006349 // Verify offlineSessionInfo
6350 std::vector<int32_t> offlineStreamIds;
6351 offlineStreamIds.reserve(offlineSessionInfo.offlineStreams.size());
6352 for (auto offlineStream : offlineSessionInfo.offlineStreams) {
6353 // verify stream IDs
6354 int32_t id = offlineStream.id;
6355 if (std::find(streamIds.begin(), streamIds.end(), id) == streamIds.end()) {
6356 SET_ERR("stream ID %d not found!", id);
6357 return UNKNOWN_ERROR;
6358 }
6359
6360 // When not using HAL buf manager, only allow streams requested by app to be preserved
6361 if (!mUseHalBufManager) {
6362 if (std::find(streamsToKeep.begin(), streamsToKeep.end(), id) == streamsToKeep.end()) {
6363 SET_ERR("stream ID %d must not be switched to offline!", id);
6364 return UNKNOWN_ERROR;
6365 }
6366 }
6367
6368 offlineStreamIds.push_back(id);
6369 sp<Camera3StreamInterface> stream = (id == inputStreamId) ?
6370 static_cast<sp<Camera3StreamInterface>>(mInputStream) :
6371 static_cast<sp<Camera3StreamInterface>>(mOutputStreams.get(id));
6372 // Verify number of outstanding buffers
6373 if (stream->getOutstandingBuffersCount() != offlineStream.numOutstandingBuffers) {
6374 SET_ERR("Offline stream %d # of remaining buffer mismatch: (%zu,%d) (service/HAL)",
6375 id, stream->getOutstandingBuffersCount(), offlineStream.numOutstandingBuffers);
6376 return UNKNOWN_ERROR;
6377 }
6378 }
6379
6380 // Verify all streams to be deleted don't have any outstanding buffers
6381 if (hasInputStream && std::find(offlineStreamIds.begin(), offlineStreamIds.end(),
6382 inputStreamId) == offlineStreamIds.end()) {
6383 if (mInputStream->hasOutstandingBuffers()) {
6384 SET_ERR("Input stream %d still has %zu outstanding buffer!",
6385 inputStreamId, mInputStream->getOutstandingBuffersCount());
6386 return UNKNOWN_ERROR;
6387 }
6388 }
6389
6390 for (const auto& outStreamId : outputStreamIds) {
6391 if (std::find(offlineStreamIds.begin(), offlineStreamIds.end(),
6392 outStreamId) == offlineStreamIds.end()) {
6393 auto outStream = mOutputStreams.get(outStreamId);
6394 if (outStream->hasOutstandingBuffers()) {
6395 SET_ERR("Output stream %d still has %zu outstanding buffer!",
6396 outStreamId, outStream->getOutstandingBuffersCount());
6397 return UNKNOWN_ERROR;
6398 }
6399 }
6400 }
6401
6402 InFlightRequestMap offlineReqs;
6403 // Verify inflight requests and their pending buffers
6404 {
6405 std::lock_guard<std::mutex> l(mInFlightLock);
6406 for (auto offlineReq : offlineSessionInfo.offlineRequests) {
6407 int idx = mInFlightMap.indexOfKey(offlineReq.frameNumber);
6408 if (idx == NAME_NOT_FOUND) {
6409 SET_ERR("Offline request frame number %d not found!", offlineReq.frameNumber);
6410 return UNKNOWN_ERROR;
6411 }
6412
6413 const auto& inflightReq = mInFlightMap.valueAt(idx);
6414 // TODO: check specific stream IDs
6415 size_t numBuffersLeft = static_cast<size_t>(inflightReq.numBuffersLeft);
6416 if (numBuffersLeft != offlineReq.pendingStreams.size()) {
6417 SET_ERR("Offline request # of remaining buffer mismatch: (%d,%d) (service/HAL)",
6418 inflightReq.numBuffersLeft, offlineReq.pendingStreams.size());
6419 return UNKNOWN_ERROR;
6420 }
6421 offlineReqs.add(offlineReq.frameNumber, inflightReq);
6422 }
6423 }
6424
6425 // Create Camera3OfflineSession and transfer object ownership
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006426 // (streams, inflight requests, buffer caches)
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006427 camera3::StreamSet offlineStreamSet;
6428 sp<camera3::Camera3Stream> inputStream;
6429 for (auto offlineStream : offlineSessionInfo.offlineStreams) {
6430 int32_t id = offlineStream.id;
6431 if (mInputStream != nullptr && id == mInputStream->getId()) {
6432 inputStream = mInputStream;
6433 } else {
6434 offlineStreamSet.add(id, mOutputStreams.get(id));
6435 }
6436 }
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006437
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006438 // TODO: check if we need to lock before copying states
6439 // though technically no other thread should be talking to Camera3Device at this point
6440 Camera3OfflineStates offlineStates(
6441 mTagMonitor, mVendorTagId, mUseHalBufManager, mNeedFixupMonochromeTags,
Shuzhen Wangb7b42652020-05-07 11:59:02 -07006442 mUsePartialResult, mNumPartialResults, mLastCompletedRegularFrameNumber,
6443 mLastCompletedReprocessFrameNumber, mLastCompletedZslFrameNumber,
6444 mNextResultFrameNumber, mNextReprocessResultFrameNumber,
6445 mNextZslStillResultFrameNumber, mNextShutterFrameNumber,
6446 mNextReprocessShutterFrameNumber, mNextZslStillShutterFrameNumber,
6447 mDeviceInfo, mPhysicalDeviceInfoMap, mDistortionMappers,
6448 mZoomRatioMappers, mRotateAndCropMappers);
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006449
6450 *session = new Camera3OfflineSession(mId, inputStream, offlineStreamSet,
6451 std::move(bufferRecords), offlineReqs, offlineStates, offlineSession);
6452
6453 // Delete all streams that has been transferred to offline session
6454 Mutex::Autolock l(mLock);
6455 for (auto offlineStream : offlineSessionInfo.offlineStreams) {
6456 int32_t id = offlineStream.id;
6457 if (mInputStream != nullptr && id == mInputStream->getId()) {
6458 mInputStream.clear();
6459 } else {
6460 mOutputStreams.remove(id);
6461 }
6462 }
6463
6464 // disconnect all other streams and switch to UNCONFIGURED state
6465 if (mInputStream != nullptr) {
6466 ret = mInputStream->disconnect();
6467 if (ret != OK) {
6468 SET_ERR_L("disconnect input stream failed!");
6469 return UNKNOWN_ERROR;
6470 }
6471 }
6472
6473 for (auto streamId : mOutputStreams.getStreamIds()) {
6474 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
6475 ret = stream->disconnect();
6476 if (ret != OK) {
6477 SET_ERR_L("disconnect output stream %d failed!", streamId);
6478 return UNKNOWN_ERROR;
6479 }
6480 }
6481
6482 mInputStream.clear();
6483 mOutputStreams.clear();
6484 mNeedConfig = true;
6485 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
6486 mOperatingMode = NO_MODE;
6487 mIsConstrainedHighSpeedConfiguration = false;
Emilian Peevc0fe54c2020-03-11 14:05:07 -07006488 mRequestThread->clearPreviousRequest();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006489
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006490 return OK;
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006491 // TO be done by CameraDeviceClient/Camera3OfflineSession
6492 // register the offline client to camera service
6493 // Setup result passthing threads etc
6494 // Initialize offline session so HAL can start sending callback to it (result Fmq)
6495 // TODO: check how many onIdle callback will be sent
6496 // Java side to make sure the CameraCaptureSession is properly closed
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006497}
6498
Emilian Peevcc0b7952020-01-07 13:54:47 -08006499void Camera3Device::getOfflineStreamIds(std::vector<int> *offlineStreamIds) {
6500 ATRACE_CALL();
6501
6502 if (offlineStreamIds == nullptr) {
6503 return;
6504 }
6505
6506 Mutex::Autolock il(mInterfaceLock);
6507
6508 auto streamIds = mOutputStreams.getStreamIds();
6509 bool hasInputStream = mInputStream != nullptr;
6510 if (hasInputStream && mInputStream->getOfflineProcessingSupport()) {
6511 offlineStreamIds->push_back(mInputStream->getId());
6512 }
6513
6514 for (const auto & streamId : streamIds) {
6515 sp<camera3::Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
6516 // Streams that use the camera buffer manager are currently not supported in
6517 // offline mode
6518 if (stream->getOfflineProcessingSupport() &&
6519 (stream->getStreamSetId() == CAMERA3_STREAM_SET_ID_INVALID)) {
6520 offlineStreamIds->push_back(streamId);
6521 }
6522 }
6523}
6524
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08006525status_t Camera3Device::setRotateAndCropAutoBehavior(
6526 camera_metadata_enum_android_scaler_rotate_and_crop_t rotateAndCropValue) {
6527 ATRACE_CALL();
6528 Mutex::Autolock il(mInterfaceLock);
6529 Mutex::Autolock l(mLock);
6530 if (mRequestThread == nullptr) {
6531 return INVALID_OPERATION;
6532 }
6533 return mRequestThread->setRotateAndCropAutoBehavior(rotateAndCropValue);
6534}
6535
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08006536bool Camera3Device::supportsCameraMute() {
6537 Mutex::Autolock il(mInterfaceLock);
6538 Mutex::Autolock l(mLock);
6539
6540 return mSupportCameraMute;
6541}
6542
6543status_t Camera3Device::setCameraMute(bool enabled) {
6544 ATRACE_CALL();
6545 Mutex::Autolock il(mInterfaceLock);
6546 Mutex::Autolock l(mLock);
6547
6548 if (mRequestThread == nullptr || !mSupportCameraMute) {
6549 return INVALID_OPERATION;
6550 }
Eino-Ville Talvala11afe4f2021-05-27 14:45:31 -07006551 int32_t muteMode =
6552 !enabled ? ANDROID_SENSOR_TEST_PATTERN_MODE_OFF :
6553 mSupportTestPatternSolidColor ? ANDROID_SENSOR_TEST_PATTERN_MODE_SOLID_COLOR :
6554 ANDROID_SENSOR_TEST_PATTERN_MODE_BLACK;
6555 return mRequestThread->setCameraMute(muteMode);
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08006556}
6557
Cliff Wuc2ad9c82021-04-21 00:58:58 +08006558status_t Camera3Device::injectCamera(const String8& injectedCamId,
6559 sp<CameraProviderManager> manager) {
6560 ALOGI("%s Injection camera: injectedCamId = %s", __FUNCTION__, injectedCamId.string());
6561 ATRACE_CALL();
6562 Mutex::Autolock il(mInterfaceLock);
6563
6564 status_t res = NO_ERROR;
6565 if (mInjectionMethods->isInjecting()) {
6566 if (injectedCamId == mInjectionMethods->getInjectedCamId()) {
6567 return OK;
6568 } else {
6569 res = mInjectionMethods->stopInjection();
6570 if (res != OK) {
6571 ALOGE("%s: Failed to stop the injection camera! ret != NO_ERROR: %d",
6572 __FUNCTION__, res);
6573 return res;
6574 }
6575 }
6576 }
6577
6578 res = mInjectionMethods->injectionInitialize(injectedCamId, manager, this);
6579 if (res != OK) {
6580 ALOGE("%s: Failed to initialize the injection camera! ret != NO_ERROR: %d",
6581 __FUNCTION__, res);
6582 return res;
6583 }
6584
6585 camera3::camera_stream_configuration injectionConfig;
6586 std::vector<uint32_t> injectionBufferSizes;
6587 mInjectionMethods->getInjectionConfig(&injectionConfig, &injectionBufferSizes);
6588 // When the second display of android is cast to the remote device, and the opened camera is
6589 // also cast to the second display, in this case, because the camera has configured the streams
6590 // at this time, we can directly call injectCamera() to replace the internal camera with
6591 // injection camera.
6592 if (mOperatingMode >= 0 && injectionConfig.num_streams > 0
6593 && injectionBufferSizes.size() > 0) {
6594 ALOGV("%s: The opened camera is directly cast to the remote device.", __FUNCTION__);
6595 res = mInjectionMethods->injectCamera(
6596 injectionConfig, injectionBufferSizes);
6597 if (res != OK) {
6598 ALOGE("Can't finish inject camera process!");
6599 return res;
6600 }
6601 }
6602
6603 return OK;
6604}
6605
6606status_t Camera3Device::stopInjection() {
6607 ALOGI("%s: Injection camera: stopInjection", __FUNCTION__);
6608 Mutex::Autolock il(mInterfaceLock);
6609 return mInjectionMethods->stopInjection();
6610}
6611
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08006612}; // namespace android