blob: 7542c291607e8862ee776298cadea8661dd24a61 [file] [log] [blame]
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001/*
Shuzhen Wangc28189a2017-11-27 23:05:10 -08002 * Copyright (C) 2013-2018 The Android Open Source Project
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#define LOG_TAG "Camera3-Device"
18#define ATRACE_TAG ATRACE_TAG_CAMERA
19//#define LOG_NDEBUG 0
20//#define LOG_NNDEBUG 0 // Per-frame verbose logging
21
22#ifdef LOG_NNDEBUG
23#define ALOGVV(...) ALOGV(__VA_ARGS__)
24#else
25#define ALOGVV(...) ((void)0)
26#endif
27
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -070028// Convenience macro for transient errors
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080029#define CLOGE(fmt, ...) ALOGE("Camera %s: %s: " fmt, mId.string(), __FUNCTION__, \
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -070030 ##__VA_ARGS__)
31
Yin-Chia Yeh99fd0972019-06-27 14:22:44 -070032#define CLOGW(fmt, ...) ALOGW("Camera %s: %s: " fmt, mId.string(), __FUNCTION__, \
33 ##__VA_ARGS__)
34
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -070035// Convenience macros for transitioning to the error state
36#define SET_ERR(fmt, ...) setErrorState( \
37 "%s: " fmt, __FUNCTION__, \
38 ##__VA_ARGS__)
39#define SET_ERR_L(fmt, ...) setErrorStateLocked( \
40 "%s: " fmt, __FUNCTION__, \
41 ##__VA_ARGS__)
42
Colin Crosse5729fa2014-03-21 15:04:25 -070043#include <inttypes.h>
44
Shuzhen Wang5c22c152017-12-31 17:12:25 -080045#include <utility>
46
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080047#include <utils/Log.h>
48#include <utils/Trace.h>
49#include <utils/Timers.h>
Zhijun He90f7c372016-08-16 16:19:43 -070050#include <cutils/properties.h>
Eino-Ville Talvala7b82efe2013-07-25 17:12:35 -070051
Cliff Wuc2ad9c82021-04-21 00:58:58 +080052#include <android/hardware/camera/device/3.7/ICameraInjectionSession.h>
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -080053#include <android/hardware/camera2/ICameraDeviceUser.h>
54
Igor Murashkinff3e31d2013-10-23 16:40:06 -070055#include "utils/CameraTraces.h"
Eino-Ville Talvalaf99498e2015-09-25 16:52:55 -070056#include "mediautils/SchedulingPolicyService.h"
Eino-Ville Talvala7b82efe2013-07-25 17:12:35 -070057#include "device3/Camera3Device.h"
58#include "device3/Camera3OutputStream.h"
59#include "device3/Camera3InputStream.h"
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -040060#include "device3/Camera3FakeStream.h"
Shuzhen Wang0129d522016-10-30 22:43:41 -070061#include "device3/Camera3SharedOutputStream.h"
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -070062#include "CameraService.h"
Jayant Chowdhary12361932018-08-27 14:46:13 -070063#include "utils/CameraThreadState.h"
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -080064#include "utils/SessionConfigurationUtils.h"
Jayant Chowdharyd4776262020-06-23 23:45:57 -070065#include "utils/TraceHFR.h"
Shuzhen Wang316781a2020-08-18 18:11:01 -070066#include "utils/CameraServiceProxyWrapper.h"
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -080067
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -080068#include <algorithm>
Yin-Chia Yeh84be5782019-03-01 11:47:02 -080069#include <tuple>
70
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -080071using namespace android::camera3;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080072using namespace android::hardware::camera;
73using namespace android::hardware::camera::device::V3_2;
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -080074using android::hardware::camera::metadata::V3_6::CameraMetadataEnumAndroidSensorPixelMode;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080075
76namespace android {
77
Shuzhen Wangd4abdf72021-05-28 11:22:50 -070078Camera3Device::Camera3Device(const String8 &id, bool overrideForPerfClass):
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080079 mId(id),
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -080080 mOperatingMode(NO_MODE),
Eino-Ville Talvala9a179412015-06-09 13:15:16 -070081 mIsConstrainedHighSpeedConfiguration(false),
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -070082 mStatus(STATUS_UNINITIALIZED),
Ruben Brunk183f0562015-08-12 12:55:02 -070083 mStatusWaiters(0),
Zhijun He204e3292014-07-14 17:09:23 -070084 mUsePartialResult(false),
85 mNumPartialResults(1),
Shuzhen Wangc28dccc2016-02-11 23:48:46 -080086 mTimestampOffset(0),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -070087 mNextResultFrameNumber(0),
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -070088 mNextReprocessResultFrameNumber(0),
Shuzhen Wang5ee99842019-04-12 11:55:48 -070089 mNextZslStillResultFrameNumber(0),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -070090 mNextShutterFrameNumber(0),
Chien-Yu Chen3df11ce2015-09-30 14:13:30 -070091 mNextReprocessShutterFrameNumber(0),
Shuzhen Wang5ee99842019-04-12 11:55:48 -070092 mNextZslStillShutterFrameNumber(0),
Emilian Peev71c73a22017-03-21 16:35:51 +000093 mListener(NULL),
Emilian Peev811d2952018-05-25 11:08:40 +010094 mVendorTagId(CAMERA_METADATA_INVALID_VENDOR_ID),
Shuzhen Wang268a1362018-10-16 16:32:59 -070095 mLastTemplateId(-1),
Shuzhen Wangd4abdf72021-05-28 11:22:50 -070096 mNeedFixupMonochromeTags(false),
97 mOverrideForPerfClass(overrideForPerfClass)
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080098{
99 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800100 ALOGV("%s: Created device for camera %s", __FUNCTION__, mId.string());
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800101}
102
103Camera3Device::~Camera3Device()
104{
105 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800106 ALOGV("%s: Tearing down for camera id %s", __FUNCTION__, mId.string());
Yin-Chia Yehc5248132018-08-15 12:19:20 -0700107 disconnectImpl();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800108}
109
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800110const String8& Camera3Device::getId() const {
Igor Murashkin71381052013-03-04 14:53:08 -0800111 return mId;
112}
113
Emilian Peevbd8c5032018-02-14 23:05:40 +0000114status_t Camera3Device::initialize(sp<CameraProviderManager> manager, const String8& monitorTags) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800115 ATRACE_CALL();
116 Mutex::Autolock il(mInterfaceLock);
117 Mutex::Autolock l(mLock);
118
119 ALOGV("%s: Initializing HIDL device for camera %s", __FUNCTION__, mId.string());
120 if (mStatus != STATUS_UNINITIALIZED) {
121 CLOGE("Already initialized!");
122 return INVALID_OPERATION;
123 }
124 if (manager == nullptr) return INVALID_OPERATION;
125
126 sp<ICameraDeviceSession> session;
127 ATRACE_BEGIN("CameraHal::openSession");
Steven Moreland5ff9c912017-03-09 23:13:00 -0800128 status_t res = manager->openSession(mId.string(), this,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800129 /*out*/ &session);
130 ATRACE_END();
131 if (res != OK) {
132 SET_ERR_L("Could not open camera session: %s (%d)", strerror(-res), res);
133 return res;
134 }
135
Shuzhen Wangd4abdf72021-05-28 11:22:50 -0700136 res = manager->getCameraCharacteristics(mId.string(), mOverrideForPerfClass, &mDeviceInfo);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800137 if (res != OK) {
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700138 SET_ERR_L("Could not retrieve camera characteristics: %s (%d)", strerror(-res), res);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800139 session->close();
140 return res;
141 }
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800142 mSupportNativeZoomRatio = manager->supportNativeZoomRatio(mId.string());
Yin-Chia Yeh52778d42016-12-22 18:20:43 -0800143
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700144 std::vector<std::string> physicalCameraIds;
Shuzhen Wang03d8cc12018-09-12 14:17:09 -0700145 bool isLogical = manager->isLogicalCamera(mId.string(), &physicalCameraIds);
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700146 if (isLogical) {
147 for (auto& physicalId : physicalCameraIds) {
Shuzhen Wangd4abdf72021-05-28 11:22:50 -0700148 // Do not override characteristics for physical cameras
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -0700149 res = manager->getCameraCharacteristics(
Shuzhen Wangd4abdf72021-05-28 11:22:50 -0700150 physicalId, /*overrideForPerfClass*/false, &mPhysicalDeviceInfoMap[physicalId]);
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700151 if (res != OK) {
152 SET_ERR_L("Could not retrieve camera %s characteristics: %s (%d)",
153 physicalId.c_str(), strerror(-res), res);
154 session->close();
155 return res;
156 }
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -0700157
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800158 bool usePrecorrectArray =
159 DistortionMapper::isDistortionSupported(mPhysicalDeviceInfoMap[physicalId]);
160 if (usePrecorrectArray) {
161 res = mDistortionMappers[physicalId].setupStaticInfo(
162 mPhysicalDeviceInfoMap[physicalId]);
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -0700163 if (res != OK) {
164 SET_ERR_L("Unable to read camera %s's calibration fields for distortion "
165 "correction", physicalId.c_str());
166 session->close();
167 return res;
168 }
169 }
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800170
Shuzhen Wang1c834da2019-12-18 11:17:03 -0800171 mZoomRatioMappers[physicalId] = ZoomRatioMapper(
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800172 &mPhysicalDeviceInfoMap[physicalId],
173 mSupportNativeZoomRatio, usePrecorrectArray);
Jayant Chowdhary9255ce02021-07-15 11:18:17 -0700174
175 if (SessionConfigurationUtils::isUltraHighResolutionSensor(
176 mPhysicalDeviceInfoMap[physicalId])) {
177 mUHRCropAndMeteringRegionMappers[physicalId] =
178 UHRCropAndMeteringRegionMapper(mPhysicalDeviceInfoMap[physicalId],
179 usePrecorrectArray);
180 }
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700181 }
182 }
183
Yifan Hongf79b5542017-04-11 14:44:25 -0700184 std::shared_ptr<RequestMetadataQueue> queue;
Yifan Honga640c5a2017-04-12 16:30:31 -0700185 auto requestQueueRet = session->getCaptureRequestMetadataQueue(
186 [&queue](const auto& descriptor) {
187 queue = std::make_shared<RequestMetadataQueue>(descriptor);
188 if (!queue->isValid() || queue->availableToWrite() <= 0) {
189 ALOGE("HAL returns empty request metadata fmq, not use it");
190 queue = nullptr;
191 // don't use the queue onwards.
192 }
193 });
194 if (!requestQueueRet.isOk()) {
195 ALOGE("Transaction error when getting request metadata fmq: %s, not use it",
196 requestQueueRet.description().c_str());
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -0700197 return DEAD_OBJECT;
Yifan Hongf79b5542017-04-11 14:44:25 -0700198 }
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700199
200 std::unique_ptr<ResultMetadataQueue>& resQueue = mResultMetadataQueue;
Yifan Honga640c5a2017-04-12 16:30:31 -0700201 auto resultQueueRet = session->getCaptureResultMetadataQueue(
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700202 [&resQueue](const auto& descriptor) {
203 resQueue = std::make_unique<ResultMetadataQueue>(descriptor);
204 if (!resQueue->isValid() || resQueue->availableToWrite() <= 0) {
Yifan Honga640c5a2017-04-12 16:30:31 -0700205 ALOGE("HAL returns empty result metadata fmq, not use it");
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700206 resQueue = nullptr;
207 // Don't use the resQueue onwards.
Yifan Honga640c5a2017-04-12 16:30:31 -0700208 }
209 });
210 if (!resultQueueRet.isOk()) {
211 ALOGE("Transaction error when getting result metadata queue from camera session: %s",
212 resultQueueRet.description().c_str());
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -0700213 return DEAD_OBJECT;
Yifan Honga640c5a2017-04-12 16:30:31 -0700214 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -0700215 IF_ALOGV() {
216 session->interfaceChain([](
217 ::android::hardware::hidl_vec<::android::hardware::hidl_string> interfaceChain) {
218 ALOGV("Session interface chain:");
Chih-Hung Hsieh3ef324d2018-12-11 11:48:12 -0800219 for (const auto& iface : interfaceChain) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -0700220 ALOGV(" %s", iface.c_str());
221 }
222 });
223 }
Yifan Hongf79b5542017-04-11 14:44:25 -0700224
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -0800225 camera_metadata_entry bufMgrMode =
226 mDeviceInfo.find(ANDROID_INFO_SUPPORTED_BUFFER_MANAGEMENT_VERSION);
227 if (bufMgrMode.count > 0) {
228 mUseHalBufManager = (bufMgrMode.data.u8[0] ==
229 ANDROID_INFO_SUPPORTED_BUFFER_MANAGEMENT_VERSION_HIDL_DEVICE_3_5);
230 }
231
Yin-Chia Yehb978c382019-10-30 00:22:37 -0700232 camera_metadata_entry_t capabilities = mDeviceInfo.find(ANDROID_REQUEST_AVAILABLE_CAPABILITIES);
233 for (size_t i = 0; i < capabilities.count; i++) {
234 uint8_t capability = capabilities.data.u8[i];
235 if (capability == ANDROID_REQUEST_AVAILABLE_CAPABILITIES_OFFLINE_PROCESSING) {
236 mSupportOfflineProcessing = true;
237 }
238 }
239
240 mInterface = new HalInterface(session, queue, mUseHalBufManager, mSupportOfflineProcessing);
Emilian Peev71c73a22017-03-21 16:35:51 +0000241 std::string providerType;
242 mVendorTagId = manager->getProviderTagIdLocked(mId.string());
Emilian Peevbd8c5032018-02-14 23:05:40 +0000243 mTagMonitor.initialize(mVendorTagId);
244 if (!monitorTags.isEmpty()) {
245 mTagMonitor.parseTagsToMonitor(String8(monitorTags));
246 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800247
Shuzhen Wang268a1362018-10-16 16:32:59 -0700248 // Metadata tags needs fixup for monochrome camera device version less
249 // than 3.5.
250 hardware::hidl_version maxVersion{0,0};
251 res = manager->getHighestSupportedVersion(mId.string(), &maxVersion);
252 if (res != OK) {
253 ALOGE("%s: Error in getting camera device version id: %s (%d)",
254 __FUNCTION__, strerror(-res), res);
255 return res;
256 }
257 int deviceVersion = HARDWARE_DEVICE_API_VERSION(
258 maxVersion.get_major(), maxVersion.get_minor());
259
260 bool isMonochrome = false;
Yin-Chia Yehb978c382019-10-30 00:22:37 -0700261 for (size_t i = 0; i < capabilities.count; i++) {
262 uint8_t capability = capabilities.data.u8[i];
Shuzhen Wang268a1362018-10-16 16:32:59 -0700263 if (capability == ANDROID_REQUEST_AVAILABLE_CAPABILITIES_MONOCHROME) {
264 isMonochrome = true;
265 }
266 }
267 mNeedFixupMonochromeTags = (isMonochrome && deviceVersion < CAMERA_DEVICE_API_VERSION_3_5);
268
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800269 return initializeCommonLocked();
270}
271
272status_t Camera3Device::initializeCommonLocked() {
273
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700274 /** Start up status tracker thread */
275 mStatusTracker = new StatusTracker(this);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800276 status_t res = mStatusTracker->run(String8::format("C3Dev-%s-Status", mId.string()).string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700277 if (res != OK) {
278 SET_ERR_L("Unable to start status tracking thread: %s (%d)",
279 strerror(-res), res);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800280 mInterface->close();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700281 mStatusTracker.clear();
282 return res;
283 }
284
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -0700285 /** Register in-flight map to the status tracker */
Yin-Chia Yeh87b3ec02019-06-03 10:44:39 -0700286 mInFlightStatusId = mStatusTracker->addComponent("InflightRequests");
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -0700287
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -0700288 if (mUseHalBufManager) {
289 res = mRequestBufferSM.initialize(mStatusTracker);
290 if (res != OK) {
291 SET_ERR_L("Unable to start request buffer state machine: %s (%d)",
292 strerror(-res), res);
293 mInterface->close();
294 mStatusTracker.clear();
295 return res;
296 }
297 }
298
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -0800299 /** Create buffer manager */
300 mBufferManager = new Camera3BufferManager();
301
302 Vector<int32_t> sessionParamKeys;
303 camera_metadata_entry_t sessionKeysEntry = mDeviceInfo.find(
304 ANDROID_REQUEST_AVAILABLE_SESSION_KEYS);
305 if (sessionKeysEntry.count > 0) {
306 sessionParamKeys.insertArrayAt(sessionKeysEntry.data.i32, 0, sessionKeysEntry.count);
307 }
308
Chien-Yu Chenab5135b2015-06-30 11:20:58 -0700309 /** Start up request queue thread */
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -0700310 mRequestThread = new RequestThread(
311 this, mStatusTracker, mInterface, sessionParamKeys, mUseHalBufManager);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800312 res = mRequestThread->run(String8::format("C3Dev-%s-ReqQueue", mId.string()).string());
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800313 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700314 SET_ERR_L("Unable to start request queue thread: %s (%d)",
315 strerror(-res), res);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800316 mInterface->close();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800317 mRequestThread.clear();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800318 return res;
319 }
320
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -0700321 mPreparerThread = new PreparerThread();
322
Ruben Brunk183f0562015-08-12 12:55:02 -0700323 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800324 mNextStreamId = 0;
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -0400325 mFakeStreamId = NO_STREAM;
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -0700326 mNeedConfig = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700327 mPauseStateNotify = false;
Shuzhen Wang83bff122020-11-20 15:51:39 -0800328 mIsInputStreamMultiResolution = false;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800329
Shuzhen Wangc28dccc2016-02-11 23:48:46 -0800330 // Measure the clock domain offset between camera and video/hw_composer
331 camera_metadata_entry timestampSource =
332 mDeviceInfo.find(ANDROID_SENSOR_INFO_TIMESTAMP_SOURCE);
333 if (timestampSource.count > 0 && timestampSource.data.u8[0] ==
334 ANDROID_SENSOR_INFO_TIMESTAMP_SOURCE_REALTIME) {
335 mTimestampOffset = getMonoToBoottimeOffset();
336 }
337
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -0700338 // Will the HAL be sending in early partial result metadata?
Emilian Peev08dd2452017-04-06 16:55:14 +0100339 camera_metadata_entry partialResultsCount =
340 mDeviceInfo.find(ANDROID_REQUEST_PARTIAL_RESULT_COUNT);
341 if (partialResultsCount.count > 0) {
342 mNumPartialResults = partialResultsCount.data.i32[0];
343 mUsePartialResult = (mNumPartialResults > 1);
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -0700344 }
345
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800346 bool usePrecorrectArray = DistortionMapper::isDistortionSupported(mDeviceInfo);
347 if (usePrecorrectArray) {
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -0700348 res = mDistortionMappers[mId.c_str()].setupStaticInfo(mDeviceInfo);
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -0700349 if (res != OK) {
350 SET_ERR_L("Unable to read necessary calibration fields for distortion correction");
351 return res;
352 }
353 }
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800354
Shuzhen Wang1c834da2019-12-18 11:17:03 -0800355 mZoomRatioMappers[mId.c_str()] = ZoomRatioMapper(&mDeviceInfo,
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800356 mSupportNativeZoomRatio, usePrecorrectArray);
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800357
Jayant Chowdhary9255ce02021-07-15 11:18:17 -0700358 if (SessionConfigurationUtils::isUltraHighResolutionSensor(mDeviceInfo)) {
359 mUHRCropAndMeteringRegionMappers[mId.c_str()] =
360 UHRCropAndMeteringRegionMapper(mDeviceInfo, usePrecorrectArray);
361 }
362
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -0800363 if (RotateAndCropMapper::isNeeded(&mDeviceInfo)) {
364 mRotateAndCropMappers.emplace(mId.c_str(), &mDeviceInfo);
365 }
366
Eino-Ville Talvala305cec62020-11-12 14:18:17 -0800367 camera_metadata_entry_t availableTestPatternModes = mDeviceInfo.find(
368 ANDROID_SENSOR_AVAILABLE_TEST_PATTERN_MODES);
369 for (size_t i = 0; i < availableTestPatternModes.count; i++) {
Eino-Ville Talvala11afe4f2021-05-27 14:45:31 -0700370 if (availableTestPatternModes.data.i32[i] ==
371 ANDROID_SENSOR_TEST_PATTERN_MODE_SOLID_COLOR) {
Eino-Ville Talvala305cec62020-11-12 14:18:17 -0800372 mSupportCameraMute = true;
Eino-Ville Talvala11afe4f2021-05-27 14:45:31 -0700373 mSupportTestPatternSolidColor = true;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -0800374 break;
Eino-Ville Talvala11afe4f2021-05-27 14:45:31 -0700375 } else if (availableTestPatternModes.data.i32[i] ==
376 ANDROID_SENSOR_TEST_PATTERN_MODE_BLACK) {
377 mSupportCameraMute = true;
378 mSupportTestPatternSolidColor = false;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -0800379 }
380 }
381
Cliff Wuc2ad9c82021-04-21 00:58:58 +0800382 mInjectionMethods = new Camera3DeviceInjectionMethods(this);
383
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800384 return OK;
385}
386
387status_t Camera3Device::disconnect() {
Yin-Chia Yehc5248132018-08-15 12:19:20 -0700388 return disconnectImpl();
389}
390
391status_t Camera3Device::disconnectImpl() {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800392 ATRACE_CALL();
Yin-Chia Yehe1c80632016-08-08 14:48:05 -0700393 ALOGI("%s: E", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800394
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700395 status_t res = OK;
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700396 std::vector<wp<Camera3StreamInterface>> streams;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700397 {
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800398 Mutex::Autolock il(mInterfaceLock);
399 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
400 {
401 Mutex::Autolock l(mLock);
402 if (mStatus == STATUS_UNINITIALIZED) return res;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700403
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800404 if (mStatus == STATUS_ACTIVE ||
405 (mStatus == STATUS_ERROR && mRequestThread != NULL)) {
406 res = mRequestThread->clearRepeatingRequests();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700407 if (res != OK) {
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800408 SET_ERR_L("Can't stop streaming");
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700409 // Continue to close device even in case of error
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800410 } else {
411 res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
412 if (res != OK) {
413 SET_ERR_L("Timeout waiting for HAL to drain (% " PRIi64 " ns)",
414 maxExpectedDuration);
415 // Continue to close device even in case of error
416 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700417 }
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700418 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800419
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800420 if (mStatus == STATUS_ERROR) {
421 CLOGE("Shutting down in an error state");
422 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700423
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800424 if (mStatusTracker != NULL) {
425 mStatusTracker->requestExit();
426 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700427
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800428 if (mRequestThread != NULL) {
429 mRequestThread->requestExit();
430 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700431
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800432 streams.reserve(mOutputStreams.size() + (mInputStream != nullptr ? 1 : 0));
433 for (size_t i = 0; i < mOutputStreams.size(); i++) {
434 streams.push_back(mOutputStreams[i]);
435 }
436 if (mInputStream != nullptr) {
437 streams.push_back(mInputStream);
438 }
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700439 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700440 }
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800441 // Joining done without holding mLock and mInterfaceLock, otherwise deadlocks may ensue
442 // as the threads try to access parent state (b/143513518)
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700443 if (mRequestThread != NULL && mStatus != STATUS_ERROR) {
444 // HAL may be in a bad state, so waiting for request thread
445 // (which may be stuck in the HAL processCaptureRequest call)
446 // could be dangerous.
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800447 // give up mInterfaceLock here and then lock it again. Could this lead
448 // to other deadlocks
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700449 mRequestThread->join();
450 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700451 {
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800452 Mutex::Autolock il(mInterfaceLock);
453 if (mStatusTracker != NULL) {
454 mStatusTracker->join();
455 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800456
Cliff Wuc2ad9c82021-04-21 00:58:58 +0800457 if (mInjectionMethods->isInjecting()) {
458 mInjectionMethods->stopInjection();
459 }
460
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800461 HalInterface* interface;
462 {
463 Mutex::Autolock l(mLock);
464 mRequestThread.clear();
465 Mutex::Autolock stLock(mTrackerLock);
466 mStatusTracker.clear();
467 interface = mInterface.get();
468 }
Eino-Ville Talvalaefff1c42015-08-28 16:27:27 -0700469
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800470 // Call close without internal mutex held, as the HAL close may need to
471 // wait on assorted callbacks,etc, to complete before it can return.
472 interface->close();
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700473
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800474 flushInflightRequests();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800475
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800476 {
477 Mutex::Autolock l(mLock);
478 mInterface->clear();
479 mOutputStreams.clear();
480 mInputStream.clear();
481 mDeletedStreams.clear();
482 mBufferManager.clear();
483 internalUpdateStatusLocked(STATUS_UNINITIALIZED);
484 }
485
486 for (auto& weakStream : streams) {
487 sp<Camera3StreamInterface> stream = weakStream.promote();
488 if (stream != nullptr) {
489 ALOGE("%s: Stream %d leaked! strong reference (%d)!",
490 __FUNCTION__, stream->getId(), stream->getStrongCount() - 1);
491 }
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700492 }
493 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -0700494 ALOGI("%s: X", __FUNCTION__);
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700495 return res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800496}
497
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700498// For dumping/debugging only -
499// try to acquire a lock a few times, eventually give up to proceed with
500// debug/dump operations
501bool Camera3Device::tryLockSpinRightRound(Mutex& lock) {
502 bool gotLock = false;
503 for (size_t i = 0; i < kDumpLockAttempts; ++i) {
504 if (lock.tryLock() == NO_ERROR) {
505 gotLock = true;
506 break;
507 } else {
508 usleep(kDumpSleepDuration);
509 }
510 }
511 return gotLock;
512}
513
Shuzhen Wang83bff122020-11-20 15:51:39 -0800514camera3::Size Camera3Device::getMaxJpegResolution() const {
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700515 int32_t maxJpegWidth = 0, maxJpegHeight = 0;
Emilian Peev08dd2452017-04-06 16:55:14 +0100516 const int STREAM_CONFIGURATION_SIZE = 4;
517 const int STREAM_FORMAT_OFFSET = 0;
518 const int STREAM_WIDTH_OFFSET = 1;
519 const int STREAM_HEIGHT_OFFSET = 2;
520 const int STREAM_IS_INPUT_OFFSET = 3;
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -0800521 bool isHighResolutionSensor =
522 camera3::SessionConfigurationUtils::isUltraHighResolutionSensor(mDeviceInfo);
523 int32_t scalerSizesTag = isHighResolutionSensor ?
524 ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS_MAXIMUM_RESOLUTION :
525 ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS;
Emilian Peev08dd2452017-04-06 16:55:14 +0100526 camera_metadata_ro_entry_t availableStreamConfigs =
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -0800527 mDeviceInfo.find(scalerSizesTag);
Emilian Peev08dd2452017-04-06 16:55:14 +0100528 if (availableStreamConfigs.count == 0 ||
529 availableStreamConfigs.count % STREAM_CONFIGURATION_SIZE != 0) {
Shuzhen Wang83bff122020-11-20 15:51:39 -0800530 return camera3::Size(0, 0);
Emilian Peev08dd2452017-04-06 16:55:14 +0100531 }
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700532
Emilian Peev08dd2452017-04-06 16:55:14 +0100533 // Get max jpeg size (area-wise).
534 for (size_t i=0; i < availableStreamConfigs.count; i+= STREAM_CONFIGURATION_SIZE) {
535 int32_t format = availableStreamConfigs.data.i32[i + STREAM_FORMAT_OFFSET];
536 int32_t width = availableStreamConfigs.data.i32[i + STREAM_WIDTH_OFFSET];
537 int32_t height = availableStreamConfigs.data.i32[i + STREAM_HEIGHT_OFFSET];
538 int32_t isInput = availableStreamConfigs.data.i32[i + STREAM_IS_INPUT_OFFSET];
539 if (isInput == ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS_OUTPUT
540 && format == HAL_PIXEL_FORMAT_BLOB &&
541 (width * height > maxJpegWidth * maxJpegHeight)) {
542 maxJpegWidth = width;
543 maxJpegHeight = height;
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700544 }
545 }
Emilian Peev08dd2452017-04-06 16:55:14 +0100546
Shuzhen Wang83bff122020-11-20 15:51:39 -0800547 return camera3::Size(maxJpegWidth, maxJpegHeight);
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700548}
549
Shuzhen Wangc28dccc2016-02-11 23:48:46 -0800550nsecs_t Camera3Device::getMonoToBoottimeOffset() {
551 // try three times to get the clock offset, choose the one
552 // with the minimum gap in measurements.
553 const int tries = 3;
554 nsecs_t bestGap, measured;
555 for (int i = 0; i < tries; ++i) {
556 const nsecs_t tmono = systemTime(SYSTEM_TIME_MONOTONIC);
557 const nsecs_t tbase = systemTime(SYSTEM_TIME_BOOTTIME);
558 const nsecs_t tmono2 = systemTime(SYSTEM_TIME_MONOTONIC);
559 const nsecs_t gap = tmono2 - tmono;
560 if (i == 0 || gap < bestGap) {
561 bestGap = gap;
562 measured = tbase - ((tmono + tmono2) >> 1);
563 }
564 }
565 return measured;
566}
567
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800568hardware::graphics::common::V1_0::PixelFormat Camera3Device::mapToPixelFormat(
569 int frameworkFormat) {
570 return (hardware::graphics::common::V1_0::PixelFormat) frameworkFormat;
571}
572
573DataspaceFlags Camera3Device::mapToHidlDataspace(
574 android_dataspace dataSpace) {
575 return dataSpace;
576}
577
Chia-I Wu67a0c0e2017-04-06 13:37:01 -0700578BufferUsageFlags Camera3Device::mapToConsumerUsage(
Emilian Peev050f5dc2017-05-18 14:43:56 +0100579 uint64_t usage) {
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -0700580 return usage;
581}
582
Emilian Peevf4816702020-04-03 15:44:51 -0700583StreamRotation Camera3Device::mapToStreamRotation(camera_stream_rotation_t rotation) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800584 switch (rotation) {
Emilian Peevf4816702020-04-03 15:44:51 -0700585 case CAMERA_STREAM_ROTATION_0:
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800586 return StreamRotation::ROTATION_0;
Emilian Peevf4816702020-04-03 15:44:51 -0700587 case CAMERA_STREAM_ROTATION_90:
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800588 return StreamRotation::ROTATION_90;
Emilian Peevf4816702020-04-03 15:44:51 -0700589 case CAMERA_STREAM_ROTATION_180:
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800590 return StreamRotation::ROTATION_180;
Emilian Peevf4816702020-04-03 15:44:51 -0700591 case CAMERA_STREAM_ROTATION_270:
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800592 return StreamRotation::ROTATION_270;
593 }
594 ALOGE("%s: Unknown stream rotation %d", __FUNCTION__, rotation);
595 return StreamRotation::ROTATION_0;
596}
597
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800598status_t Camera3Device::mapToStreamConfigurationMode(
Emilian Peevf4816702020-04-03 15:44:51 -0700599 camera_stream_configuration_mode_t operationMode, StreamConfigurationMode *mode) {
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800600 if (mode == nullptr) return BAD_VALUE;
Emilian Peevf4816702020-04-03 15:44:51 -0700601 if (operationMode < CAMERA_VENDOR_STREAM_CONFIGURATION_MODE_START) {
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800602 switch(operationMode) {
Emilian Peevf4816702020-04-03 15:44:51 -0700603 case CAMERA_STREAM_CONFIGURATION_NORMAL_MODE:
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800604 *mode = StreamConfigurationMode::NORMAL_MODE;
605 break;
Emilian Peevf4816702020-04-03 15:44:51 -0700606 case CAMERA_STREAM_CONFIGURATION_CONSTRAINED_HIGH_SPEED_MODE:
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800607 *mode = StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE;
608 break;
609 default:
610 ALOGE("%s: Unknown stream configuration mode %d", __FUNCTION__, operationMode);
611 return BAD_VALUE;
612 }
613 } else {
614 *mode = static_cast<StreamConfigurationMode>(operationMode);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800615 }
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800616 return OK;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800617}
618
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800619int Camera3Device::mapToFrameworkFormat(
620 hardware::graphics::common::V1_0::PixelFormat pixelFormat) {
621 return static_cast<uint32_t>(pixelFormat);
622}
623
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -0700624android_dataspace Camera3Device::mapToFrameworkDataspace(
625 DataspaceFlags dataSpace) {
626 return static_cast<android_dataspace>(dataSpace);
627}
628
Emilian Peev050f5dc2017-05-18 14:43:56 +0100629uint64_t Camera3Device::mapConsumerToFrameworkUsage(
Chia-I Wu67a0c0e2017-04-06 13:37:01 -0700630 BufferUsageFlags usage) {
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -0700631 return usage;
632}
633
Emilian Peev050f5dc2017-05-18 14:43:56 +0100634uint64_t Camera3Device::mapProducerToFrameworkUsage(
Chia-I Wu67a0c0e2017-04-06 13:37:01 -0700635 BufferUsageFlags usage) {
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -0700636 return usage;
637}
638
Zhijun Hef7da0962014-04-24 13:27:56 -0700639ssize_t Camera3Device::getJpegBufferSize(uint32_t width, uint32_t height) const {
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700640 // Get max jpeg size (area-wise).
Shuzhen Wang83bff122020-11-20 15:51:39 -0800641 camera3::Size maxJpegResolution = getMaxJpegResolution();
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700642 if (maxJpegResolution.width == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800643 ALOGE("%s: Camera %s: Can't find valid available jpeg sizes in static metadata!",
644 __FUNCTION__, mId.string());
Zhijun Hef7da0962014-04-24 13:27:56 -0700645 return BAD_VALUE;
646 }
647
Zhijun Hef7da0962014-04-24 13:27:56 -0700648 // Get max jpeg buffer size
649 ssize_t maxJpegBufferSize = 0;
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700650 camera_metadata_ro_entry jpegBufMaxSize = mDeviceInfo.find(ANDROID_JPEG_MAX_SIZE);
651 if (jpegBufMaxSize.count == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800652 ALOGE("%s: Camera %s: Can't find maximum JPEG size in static metadata!", __FUNCTION__,
653 mId.string());
Zhijun Hef7da0962014-04-24 13:27:56 -0700654 return BAD_VALUE;
655 }
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700656 maxJpegBufferSize = jpegBufMaxSize.data.i32[0];
Yin-Chia Yeh0c4e56d2015-01-09 15:21:27 -0800657 assert(kMinJpegBufferSize < maxJpegBufferSize);
Zhijun Hef7da0962014-04-24 13:27:56 -0700658
659 // Calculate final jpeg buffer size for the given resolution.
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700660 float scaleFactor = ((float) (width * height)) /
661 (maxJpegResolution.width * maxJpegResolution.height);
Yin-Chia Yeh0c4e56d2015-01-09 15:21:27 -0800662 ssize_t jpegBufferSize = scaleFactor * (maxJpegBufferSize - kMinJpegBufferSize) +
663 kMinJpegBufferSize;
Zhijun Hef7da0962014-04-24 13:27:56 -0700664 if (jpegBufferSize > maxJpegBufferSize) {
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -0800665 ALOGI("%s: jpeg buffer size calculated is > maxJpeg bufferSize(%zd), clamping",
666 __FUNCTION__, maxJpegBufferSize);
Zhijun Hef7da0962014-04-24 13:27:56 -0700667 jpegBufferSize = maxJpegBufferSize;
Zhijun Hef7da0962014-04-24 13:27:56 -0700668 }
669
670 return jpegBufferSize;
671}
672
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700673ssize_t Camera3Device::getPointCloudBufferSize() const {
674 const int FLOATS_PER_POINT=4;
675 camera_metadata_ro_entry maxPointCount = mDeviceInfo.find(ANDROID_DEPTH_MAX_DEPTH_SAMPLES);
676 if (maxPointCount.count == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800677 ALOGE("%s: Camera %s: Can't find maximum depth point cloud size in static metadata!",
678 __FUNCTION__, mId.string());
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700679 return BAD_VALUE;
680 }
681 ssize_t maxBytesForPointCloud = sizeof(android_depth_points) +
682 maxPointCount.data.i32[0] * sizeof(float) * FLOATS_PER_POINT;
683 return maxBytesForPointCloud;
684}
685
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -0800686ssize_t Camera3Device::getRawOpaqueBufferSize(int32_t width, int32_t height,
687 bool maxResolution) const {
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800688 const int PER_CONFIGURATION_SIZE = 3;
689 const int WIDTH_OFFSET = 0;
690 const int HEIGHT_OFFSET = 1;
691 const int SIZE_OFFSET = 2;
692 camera_metadata_ro_entry rawOpaqueSizes =
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -0800693 mDeviceInfo.find(
694 camera3::SessionConfigurationUtils::getAppropriateModeTag(
695 ANDROID_SENSOR_OPAQUE_RAW_SIZE,
696 maxResolution));
Aurimas Liutikasbc57b122016-02-16 09:59:16 -0800697 size_t count = rawOpaqueSizes.count;
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800698 if (count == 0 || (count % PER_CONFIGURATION_SIZE)) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800699 ALOGE("%s: Camera %s: bad opaque RAW size static metadata length(%zu)!",
700 __FUNCTION__, mId.string(), count);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800701 return BAD_VALUE;
702 }
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700703
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800704 for (size_t i = 0; i < count; i += PER_CONFIGURATION_SIZE) {
705 if (width == rawOpaqueSizes.data.i32[i + WIDTH_OFFSET] &&
706 height == rawOpaqueSizes.data.i32[i + HEIGHT_OFFSET]) {
707 return rawOpaqueSizes.data.i32[i + SIZE_OFFSET];
708 }
709 }
710
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800711 ALOGE("%s: Camera %s: cannot find size for %dx%d opaque RAW image!",
712 __FUNCTION__, mId.string(), width, height);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800713 return BAD_VALUE;
714}
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700715
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800716status_t Camera3Device::dump(int fd, const Vector<String16> &args) {
717 ATRACE_CALL();
718 (void)args;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700719
720 // Try to lock, but continue in case of failure (to avoid blocking in
721 // deadlocks)
722 bool gotInterfaceLock = tryLockSpinRightRound(mInterfaceLock);
723 bool gotLock = tryLockSpinRightRound(mLock);
724
725 ALOGW_IF(!gotInterfaceLock,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800726 "Camera %s: %s: Unable to lock interface lock, proceeding anyway",
727 mId.string(), __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700728 ALOGW_IF(!gotLock,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800729 "Camera %s: %s: Unable to lock main lock, proceeding anyway",
730 mId.string(), __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700731
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800732 bool dumpTemplates = false;
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700733
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800734 String16 templatesOption("-t");
735 int n = args.size();
736 for (int i = 0; i < n; i++) {
737 if (args[i] == templatesOption) {
738 dumpTemplates = true;
739 }
Emilian Peevbd8c5032018-02-14 23:05:40 +0000740 if (args[i] == TagMonitor::kMonitorOption) {
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700741 if (i + 1 < n) {
742 String8 monitorTags = String8(args[i + 1]);
743 if (monitorTags == "off") {
744 mTagMonitor.disableMonitoring();
745 } else {
746 mTagMonitor.parseTagsToMonitor(monitorTags);
747 }
748 } else {
749 mTagMonitor.disableMonitoring();
750 }
751 }
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800752 }
753
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800754 String8 lines;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800755
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800756 const char *status =
757 mStatus == STATUS_ERROR ? "ERROR" :
758 mStatus == STATUS_UNINITIALIZED ? "UNINITIALIZED" :
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700759 mStatus == STATUS_UNCONFIGURED ? "UNCONFIGURED" :
760 mStatus == STATUS_CONFIGURED ? "CONFIGURED" :
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800761 mStatus == STATUS_ACTIVE ? "ACTIVE" :
762 "Unknown";
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700763
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800764 lines.appendFormat(" Device status: %s\n", status);
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700765 if (mStatus == STATUS_ERROR) {
766 lines.appendFormat(" Error cause: %s\n", mErrorCause.string());
767 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800768 lines.appendFormat(" Stream configuration:\n");
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800769 const char *mode =
770 mOperatingMode == static_cast<int>(StreamConfigurationMode::NORMAL_MODE) ? "NORMAL" :
771 mOperatingMode == static_cast<int>(
772 StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE) ? "CONSTRAINED_HIGH_SPEED" :
773 "CUSTOM";
774 lines.appendFormat(" Operation mode: %s (%d) \n", mode, mOperatingMode);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800775
776 if (mInputStream != NULL) {
777 write(fd, lines.string(), lines.size());
778 mInputStream->dump(fd, args);
779 } else {
780 lines.appendFormat(" No input stream.\n");
781 write(fd, lines.string(), lines.size());
782 }
783 for (size_t i = 0; i < mOutputStreams.size(); i++) {
784 mOutputStreams[i]->dump(fd,args);
785 }
786
Zhijun He431503c2016-03-07 17:30:16 -0800787 if (mBufferManager != NULL) {
788 lines = String8(" Camera3 Buffer Manager:\n");
789 write(fd, lines.string(), lines.size());
790 mBufferManager->dump(fd, args);
791 }
Zhijun He125684a2015-12-26 15:07:30 -0800792
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700793 lines = String8(" In-flight requests:\n");
794 if (mInFlightMap.size() == 0) {
795 lines.append(" None\n");
796 } else {
797 for (size_t i = 0; i < mInFlightMap.size(); i++) {
798 InFlightRequest r = mInFlightMap.valueAt(i);
Colin Crosse5729fa2014-03-21 15:04:25 -0700799 lines.appendFormat(" Frame %d | Timestamp: %" PRId64 ", metadata"
Greg Kaiser51b882c2020-06-10 05:41:44 +0000800 " arrived: %s, buffers left: %d\n", mInFlightMap.keyAt(i),
Chien-Yu Chen43e69a62014-11-25 16:38:33 -0800801 r.shutterTimestamp, r.haveResultMetadata ? "true" : "false",
Greg Kaiser51b882c2020-06-10 05:41:44 +0000802 r.numBuffersLeft);
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700803 }
804 }
805 write(fd, lines.string(), lines.size());
806
Shuzhen Wang686f6442017-06-20 16:16:04 -0700807 if (mRequestThread != NULL) {
808 mRequestThread->dumpCaptureRequestLatency(fd,
809 " ProcessCaptureRequest latency histogram:");
810 }
811
Igor Murashkin1e479c02013-09-06 16:55:14 -0700812 {
813 lines = String8(" Last request sent:\n");
814 write(fd, lines.string(), lines.size());
815
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700816 CameraMetadata lastRequest = getLatestRequestLocked();
Igor Murashkin1e479c02013-09-06 16:55:14 -0700817 lastRequest.dump(fd, /*verbosity*/2, /*indentation*/6);
818 }
819
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800820 if (dumpTemplates) {
Emilian Peevf4816702020-04-03 15:44:51 -0700821 const char *templateNames[CAMERA_TEMPLATE_COUNT] = {
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800822 "TEMPLATE_PREVIEW",
823 "TEMPLATE_STILL_CAPTURE",
824 "TEMPLATE_VIDEO_RECORD",
825 "TEMPLATE_VIDEO_SNAPSHOT",
826 "TEMPLATE_ZERO_SHUTTER_LAG",
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -0800827 "TEMPLATE_MANUAL",
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800828 };
829
Emilian Peevf4816702020-04-03 15:44:51 -0700830 for (int i = 1; i < CAMERA_TEMPLATE_COUNT; i++) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800831 camera_metadata_t *templateRequest = nullptr;
832 mInterface->constructDefaultRequestSettings(
Emilian Peevf4816702020-04-03 15:44:51 -0700833 (camera_request_template_t) i, &templateRequest);
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800834 lines = String8::format(" HAL Request %s:\n", templateNames[i-1]);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800835 if (templateRequest == nullptr) {
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800836 lines.append(" Not supported\n");
837 write(fd, lines.string(), lines.size());
838 } else {
839 write(fd, lines.string(), lines.size());
840 dump_indented_camera_metadata(templateRequest,
841 fd, /*verbosity*/2, /*indentation*/8);
842 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800843 free_camera_metadata(templateRequest);
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800844 }
845 }
846
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700847 mTagMonitor.dumpMonitoredMetadata(fd);
848
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800849 if (mInterface->valid()) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -0800850 lines = String8(" HAL device dump:\n");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800851 write(fd, lines.string(), lines.size());
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800852 mInterface->dump(fd);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800853 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800854
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700855 if (gotLock) mLock.unlock();
856 if (gotInterfaceLock) mInterfaceLock.unlock();
857
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800858 return OK;
859}
860
Emilian Peevfaa4bde2020-01-23 12:19:37 -0800861const CameraMetadata& Camera3Device::infoPhysical(const String8& physicalId) const {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800862 ALOGVV("%s: E", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800863 if (CC_UNLIKELY(mStatus == STATUS_UNINITIALIZED ||
864 mStatus == STATUS_ERROR)) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700865 ALOGW("%s: Access to static info %s!", __FUNCTION__,
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800866 mStatus == STATUS_ERROR ?
867 "when in error state" : "before init");
868 }
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700869 if (physicalId.isEmpty()) {
870 return mDeviceInfo;
871 } else {
872 std::string id(physicalId.c_str());
873 if (mPhysicalDeviceInfoMap.find(id) != mPhysicalDeviceInfoMap.end()) {
874 return mPhysicalDeviceInfoMap.at(id);
875 } else {
876 ALOGE("%s: Invalid physical camera id %s", __FUNCTION__, physicalId.c_str());
877 return mDeviceInfo;
878 }
879 }
880}
881
882const CameraMetadata& Camera3Device::info() const {
883 String8 emptyId;
Emilian Peevfaa4bde2020-01-23 12:19:37 -0800884 return infoPhysical(emptyId);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800885}
886
Jianing Wei90e59c92014-03-12 18:29:36 -0700887status_t Camera3Device::checkStatusOkToCaptureLocked() {
888 switch (mStatus) {
889 case STATUS_ERROR:
890 CLOGE("Device has encountered a serious error");
891 return INVALID_OPERATION;
892 case STATUS_UNINITIALIZED:
893 CLOGE("Device not initialized");
894 return INVALID_OPERATION;
895 case STATUS_UNCONFIGURED:
896 case STATUS_CONFIGURED:
897 case STATUS_ACTIVE:
898 // OK
899 break;
900 default:
901 SET_ERR_L("Unexpected status: %d", mStatus);
902 return INVALID_OPERATION;
903 }
904 return OK;
905}
906
907status_t Camera3Device::convertMetadataListToRequestListLocked(
Emilian Peevaebbe412018-01-15 13:53:24 +0000908 const List<const PhysicalCameraSettingsList> &metadataList,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700909 const std::list<const SurfaceMap> &surfaceMaps,
Shuzhen Wang316781a2020-08-18 18:11:01 -0700910 bool repeating, nsecs_t requestTimeNs,
Shuzhen Wang9d066012016-09-30 11:30:20 -0700911 RequestList *requestList) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700912 if (requestList == NULL) {
913 CLOGE("requestList cannot be NULL.");
914 return BAD_VALUE;
915 }
916
Jianing Weicb0652e2014-03-12 18:29:36 -0700917 int32_t burstId = 0;
Emilian Peevaebbe412018-01-15 13:53:24 +0000918 List<const PhysicalCameraSettingsList>::const_iterator metadataIt = metadataList.begin();
Shuzhen Wang0129d522016-10-30 22:43:41 -0700919 std::list<const SurfaceMap>::const_iterator surfaceMapIt = surfaceMaps.begin();
920 for (; metadataIt != metadataList.end() && surfaceMapIt != surfaceMaps.end();
921 ++metadataIt, ++surfaceMapIt) {
922 sp<CaptureRequest> newRequest = setUpRequestLocked(*metadataIt, *surfaceMapIt);
Jianing Wei90e59c92014-03-12 18:29:36 -0700923 if (newRequest == 0) {
924 CLOGE("Can't create capture request");
925 return BAD_VALUE;
926 }
Jianing Weicb0652e2014-03-12 18:29:36 -0700927
Shuzhen Wang9d066012016-09-30 11:30:20 -0700928 newRequest->mRepeating = repeating;
Shuzhen Wang316781a2020-08-18 18:11:01 -0700929 newRequest->mRequestTimeNs = requestTimeNs;
Shuzhen Wang9d066012016-09-30 11:30:20 -0700930
Jianing Weicb0652e2014-03-12 18:29:36 -0700931 // Setup burst Id and request Id
932 newRequest->mResultExtras.burstId = burstId++;
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -0800933 auto requestIdEntry = metadataIt->begin()->metadata.find(ANDROID_REQUEST_ID);
934 if (requestIdEntry.count == 0) {
Jianing Weicb0652e2014-03-12 18:29:36 -0700935 CLOGE("RequestID does not exist in metadata");
936 return BAD_VALUE;
937 }
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -0800938 newRequest->mResultExtras.requestId = requestIdEntry.data.i32[0];
Jianing Weicb0652e2014-03-12 18:29:36 -0700939
Jianing Wei90e59c92014-03-12 18:29:36 -0700940 requestList->push_back(newRequest);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700941
942 ALOGV("%s: requestId = %" PRId32, __FUNCTION__, newRequest->mResultExtras.requestId);
Jianing Wei90e59c92014-03-12 18:29:36 -0700943 }
Shuzhen Wang0129d522016-10-30 22:43:41 -0700944 if (metadataIt != metadataList.end() || surfaceMapIt != surfaceMaps.end()) {
945 ALOGE("%s: metadataList and surfaceMaps are not the same size!", __FUNCTION__);
946 return BAD_VALUE;
947 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -0700948
949 // Setup batch size if this is a high speed video recording request.
950 if (mIsConstrainedHighSpeedConfiguration && requestList->size() > 0) {
951 auto firstRequest = requestList->begin();
952 for (auto& outputStream : (*firstRequest)->mOutputStreams) {
953 if (outputStream->isVideoStream()) {
954 (*firstRequest)->mBatchSize = requestList->size();
Yin-Chia Yeh14ef48d2020-02-10 15:06:37 -0800955 outputStream->setBatchSize(requestList->size());
Chien-Yu Chen85a64552015-08-28 15:46:12 -0700956 break;
957 }
958 }
959 }
960
Jianing Wei90e59c92014-03-12 18:29:36 -0700961 return OK;
962}
963
Yin-Chia Yeh7e5a2042019-02-06 16:01:06 -0800964status_t Camera3Device::capture(CameraMetadata &request, int64_t* lastFrameNumber) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800965 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800966
Emilian Peevaebbe412018-01-15 13:53:24 +0000967 List<const PhysicalCameraSettingsList> requestsList;
Shuzhen Wang0129d522016-10-30 22:43:41 -0700968 std::list<const SurfaceMap> surfaceMaps;
Emilian Peevaebbe412018-01-15 13:53:24 +0000969 convertToRequestList(requestsList, surfaceMaps, request);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700970
Yin-Chia Yeh7e5a2042019-02-06 16:01:06 -0800971 return captureList(requestsList, surfaceMaps, lastFrameNumber);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700972}
973
Emilian Peevaebbe412018-01-15 13:53:24 +0000974void Camera3Device::convertToRequestList(List<const PhysicalCameraSettingsList>& requestsList,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700975 std::list<const SurfaceMap>& surfaceMaps,
976 const CameraMetadata& request) {
Emilian Peevaebbe412018-01-15 13:53:24 +0000977 PhysicalCameraSettingsList requestList;
978 requestList.push_back({std::string(getId().string()), request});
979 requestsList.push_back(requestList);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700980
981 SurfaceMap surfaceMap;
982 camera_metadata_ro_entry streams = request.find(ANDROID_REQUEST_OUTPUT_STREAMS);
983 // With no surface list passed in, stream and surface will have 1-to-1
984 // mapping. So the surface index is 0 for each stream in the surfaceMap.
985 for (size_t i = 0; i < streams.count; i++) {
986 surfaceMap[streams.data.i32[i]].push_back(0);
987 }
988 surfaceMaps.push_back(surfaceMap);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800989}
990
Jianing Wei90e59c92014-03-12 18:29:36 -0700991status_t Camera3Device::submitRequestsHelper(
Emilian Peevaebbe412018-01-15 13:53:24 +0000992 const List<const PhysicalCameraSettingsList> &requests,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700993 const std::list<const SurfaceMap> &surfaceMaps,
994 bool repeating,
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700995 /*out*/
996 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700997 ATRACE_CALL();
Shuzhen Wang316781a2020-08-18 18:11:01 -0700998 nsecs_t requestTimeNs = systemTime();
999
Jianing Wei90e59c92014-03-12 18:29:36 -07001000 Mutex::Autolock il(mInterfaceLock);
1001 Mutex::Autolock l(mLock);
1002
1003 status_t res = checkStatusOkToCaptureLocked();
1004 if (res != OK) {
1005 // error logged by previous call
1006 return res;
1007 }
1008
1009 RequestList requestList;
1010
Shuzhen Wang0129d522016-10-30 22:43:41 -07001011 res = convertMetadataListToRequestListLocked(requests, surfaceMaps,
Shuzhen Wang316781a2020-08-18 18:11:01 -07001012 repeating, requestTimeNs, /*out*/&requestList);
Jianing Wei90e59c92014-03-12 18:29:36 -07001013 if (res != OK) {
1014 // error logged by previous call
1015 return res;
1016 }
1017
1018 if (repeating) {
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07001019 res = mRequestThread->setRepeatingRequests(requestList, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -07001020 } else {
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07001021 res = mRequestThread->queueRequestList(requestList, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -07001022 }
1023
1024 if (res == OK) {
1025 waitUntilStateThenRelock(/*active*/true, kActiveTimeout);
1026 if (res != OK) {
1027 SET_ERR_L("Can't transition to active in %f seconds!",
1028 kActiveTimeout/1e9);
1029 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001030 ALOGV("Camera %s: Capture request %" PRId32 " enqueued", mId.string(),
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07001031 (*(requestList.begin()))->mResultExtras.requestId);
Jianing Wei90e59c92014-03-12 18:29:36 -07001032 } else {
1033 CLOGE("Cannot queue request. Impossible.");
1034 return BAD_VALUE;
1035 }
1036
1037 return res;
1038}
1039
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001040hardware::Return<void> Camera3Device::requestStreamBuffers(
1041 const hardware::hidl_vec<hardware::camera::device::V3_5::BufferRequest>& bufReqs,
1042 requestStreamBuffers_cb _hidl_cb) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001043 RequestBufferStates states {
Shuzhen Wang316781a2020-08-18 18:11:01 -07001044 mId, mRequestBufferInterfaceLock, mUseHalBufManager, mOutputStreams, mSessionStatsBuilder,
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001045 *this, *mInterface, *this};
1046 camera3::requestStreamBuffers(states, bufReqs, _hidl_cb);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001047 return hardware::Void();
1048}
1049
1050hardware::Return<void> Camera3Device::returnStreamBuffers(
1051 const hardware::hidl_vec<hardware::camera::device::V3_2::StreamBuffer>& buffers) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001052 ReturnBufferStates states {
Shuzhen Wang316781a2020-08-18 18:11:01 -07001053 mId, mUseHalBufManager, mOutputStreams, mSessionStatsBuilder, *mInterface};
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001054 camera3::returnStreamBuffers(states, buffers);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001055 return hardware::Void();
1056}
1057
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001058hardware::Return<void> Camera3Device::processCaptureResult_3_4(
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001059 const hardware::hidl_vec<
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001060 hardware::camera::device::V3_4::CaptureResult>& results) {
Yin-Chia Yeh657c1872017-07-18 18:09:57 -07001061 // Ideally we should grab mLock, but that can lead to deadlock, and
1062 // it's not super important to get up to date value of mStatus for this
1063 // warning print, hence skipping the lock here
1064 if (mStatus == STATUS_ERROR) {
1065 // Per API contract, HAL should act as closed after device error
1066 // But mStatus can be set to error by framework as well, so just log
1067 // a warning here.
1068 ALOGW("%s: received capture result in error state.", __FUNCTION__);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07001069 }
Yifan Honga640c5a2017-04-12 16:30:31 -07001070
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001071 sp<NotificationListener> listener;
1072 {
1073 std::lock_guard<std::mutex> l(mOutputLock);
1074 listener = mListener.promote();
1075 }
1076
Yifan Honga640c5a2017-04-12 16:30:31 -07001077 if (mProcessCaptureResultLock.tryLock() != OK) {
1078 // This should never happen; it indicates a wrong client implementation
1079 // that doesn't follow the contract. But, we can be tolerant here.
1080 ALOGE("%s: callback overlapped! waiting 1s...",
1081 __FUNCTION__);
1082 if (mProcessCaptureResultLock.timedLock(1000000000 /* 1s */) != OK) {
1083 ALOGE("%s: cannot acquire lock in 1s, dropping results",
1084 __FUNCTION__);
1085 // really don't know what to do, so bail out.
1086 return hardware::Void();
1087 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001088 }
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001089 CaptureOutputStates states {
1090 mId,
Shuzhen Wangb7b42652020-05-07 11:59:02 -07001091 mInFlightLock, mLastCompletedRegularFrameNumber,
1092 mLastCompletedReprocessFrameNumber, mLastCompletedZslFrameNumber,
1093 mInFlightMap, mOutputLock, mResultQueue, mResultSignal,
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001094 mNextShutterFrameNumber,
1095 mNextReprocessShutterFrameNumber, mNextZslStillShutterFrameNumber,
1096 mNextResultFrameNumber,
1097 mNextReprocessResultFrameNumber, mNextZslStillResultFrameNumber,
1098 mUseHalBufManager, mUsePartialResult, mNeedFixupMonochromeTags,
1099 mNumPartialResults, mVendorTagId, mDeviceInfo, mPhysicalDeviceInfoMap,
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08001100 mResultMetadataQueue, mDistortionMappers, mZoomRatioMappers, mRotateAndCropMappers,
Shuzhen Wang316781a2020-08-18 18:11:01 -07001101 mTagMonitor, mInputStream, mOutputStreams, mSessionStatsBuilder, listener, *this, *this,
1102 *mInterface
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001103 };
1104
Yifan Honga640c5a2017-04-12 16:30:31 -07001105 for (const auto& result : results) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001106 processOneCaptureResultLocked(states, result.v3_2, result.physicalCameraMetadata);
Yifan Honga640c5a2017-04-12 16:30:31 -07001107 }
1108 mProcessCaptureResultLock.unlock();
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001109 return hardware::Void();
1110}
1111
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001112// Only one processCaptureResult should be called at a time, so
1113// the locks won't block. The locks are present here simply to enforce this.
1114hardware::Return<void> Camera3Device::processCaptureResult(
1115 const hardware::hidl_vec<
1116 hardware::camera::device::V3_2::CaptureResult>& results) {
1117 hardware::hidl_vec<hardware::camera::device::V3_4::PhysicalCameraMetadata> noPhysMetadata;
1118
1119 // Ideally we should grab mLock, but that can lead to deadlock, and
1120 // it's not super important to get up to date value of mStatus for this
1121 // warning print, hence skipping the lock here
1122 if (mStatus == STATUS_ERROR) {
1123 // Per API contract, HAL should act as closed after device error
1124 // But mStatus can be set to error by framework as well, so just log
1125 // a warning here.
1126 ALOGW("%s: received capture result in error state.", __FUNCTION__);
1127 }
1128
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001129 sp<NotificationListener> listener;
1130 {
1131 std::lock_guard<std::mutex> l(mOutputLock);
1132 listener = mListener.promote();
1133 }
1134
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001135 if (mProcessCaptureResultLock.tryLock() != OK) {
1136 // This should never happen; it indicates a wrong client implementation
1137 // that doesn't follow the contract. But, we can be tolerant here.
1138 ALOGE("%s: callback overlapped! waiting 1s...",
1139 __FUNCTION__);
1140 if (mProcessCaptureResultLock.timedLock(1000000000 /* 1s */) != OK) {
1141 ALOGE("%s: cannot acquire lock in 1s, dropping results",
1142 __FUNCTION__);
1143 // really don't know what to do, so bail out.
1144 return hardware::Void();
1145 }
1146 }
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001147
1148 CaptureOutputStates states {
1149 mId,
Shuzhen Wangb7b42652020-05-07 11:59:02 -07001150 mInFlightLock, mLastCompletedRegularFrameNumber,
1151 mLastCompletedReprocessFrameNumber, mLastCompletedZslFrameNumber,
1152 mInFlightMap, mOutputLock, mResultQueue, mResultSignal,
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001153 mNextShutterFrameNumber,
1154 mNextReprocessShutterFrameNumber, mNextZslStillShutterFrameNumber,
1155 mNextResultFrameNumber,
1156 mNextReprocessResultFrameNumber, mNextZslStillResultFrameNumber,
1157 mUseHalBufManager, mUsePartialResult, mNeedFixupMonochromeTags,
1158 mNumPartialResults, mVendorTagId, mDeviceInfo, mPhysicalDeviceInfoMap,
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08001159 mResultMetadataQueue, mDistortionMappers, mZoomRatioMappers, mRotateAndCropMappers,
Shuzhen Wang316781a2020-08-18 18:11:01 -07001160 mTagMonitor, mInputStream, mOutputStreams, mSessionStatsBuilder, listener, *this, *this,
1161 *mInterface
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001162 };
1163
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001164 for (const auto& result : results) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001165 processOneCaptureResultLocked(states, result, noPhysMetadata);
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001166 }
1167 mProcessCaptureResultLock.unlock();
1168 return hardware::Void();
1169}
1170
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001171hardware::Return<void> Camera3Device::notify(
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001172 const hardware::hidl_vec<hardware::camera::device::V3_2::NotifyMsg>& msgs) {
Yin-Chia Yeh657c1872017-07-18 18:09:57 -07001173 // Ideally we should grab mLock, but that can lead to deadlock, and
1174 // it's not super important to get up to date value of mStatus for this
1175 // warning print, hence skipping the lock here
1176 if (mStatus == STATUS_ERROR) {
1177 // Per API contract, HAL should act as closed after device error
1178 // But mStatus can be set to error by framework as well, so just log
1179 // a warning here.
1180 ALOGW("%s: received notify message in error state.", __FUNCTION__);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07001181 }
Yin-Chia Yeh657c1872017-07-18 18:09:57 -07001182
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001183 sp<NotificationListener> listener;
1184 {
1185 std::lock_guard<std::mutex> l(mOutputLock);
1186 listener = mListener.promote();
1187 }
1188
1189 CaptureOutputStates states {
1190 mId,
Shuzhen Wangb7b42652020-05-07 11:59:02 -07001191 mInFlightLock, mLastCompletedRegularFrameNumber,
1192 mLastCompletedReprocessFrameNumber, mLastCompletedZslFrameNumber,
1193 mInFlightMap, mOutputLock, mResultQueue, mResultSignal,
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001194 mNextShutterFrameNumber,
1195 mNextReprocessShutterFrameNumber, mNextZslStillShutterFrameNumber,
1196 mNextResultFrameNumber,
1197 mNextReprocessResultFrameNumber, mNextZslStillResultFrameNumber,
1198 mUseHalBufManager, mUsePartialResult, mNeedFixupMonochromeTags,
1199 mNumPartialResults, mVendorTagId, mDeviceInfo, mPhysicalDeviceInfoMap,
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08001200 mResultMetadataQueue, mDistortionMappers, mZoomRatioMappers, mRotateAndCropMappers,
Shuzhen Wang316781a2020-08-18 18:11:01 -07001201 mTagMonitor, mInputStream, mOutputStreams, mSessionStatsBuilder, listener, *this, *this,
1202 *mInterface
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001203 };
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001204 for (const auto& msg : msgs) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001205 camera3::notify(states, msg);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001206 }
1207 return hardware::Void();
1208}
1209
Emilian Peevaebbe412018-01-15 13:53:24 +00001210status_t Camera3Device::captureList(const List<const PhysicalCameraSettingsList> &requestsList,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001211 const std::list<const SurfaceMap> &surfaceMaps,
Jianing Weicb0652e2014-03-12 18:29:36 -07001212 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -07001213 ATRACE_CALL();
1214
Emilian Peevaebbe412018-01-15 13:53:24 +00001215 return submitRequestsHelper(requestsList, surfaceMaps, /*repeating*/false, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -07001216}
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001217
Jianing Weicb0652e2014-03-12 18:29:36 -07001218status_t Camera3Device::setStreamingRequest(const CameraMetadata &request,
1219 int64_t* /*lastFrameNumber*/) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001220 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001221
Emilian Peevaebbe412018-01-15 13:53:24 +00001222 List<const PhysicalCameraSettingsList> requestsList;
Shuzhen Wang0129d522016-10-30 22:43:41 -07001223 std::list<const SurfaceMap> surfaceMaps;
Emilian Peevaebbe412018-01-15 13:53:24 +00001224 convertToRequestList(requestsList, surfaceMaps, request);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001225
Emilian Peevaebbe412018-01-15 13:53:24 +00001226 return setStreamingRequestList(requestsList, /*surfaceMap*/surfaceMaps,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001227 /*lastFrameNumber*/NULL);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001228}
1229
Emilian Peevaebbe412018-01-15 13:53:24 +00001230status_t Camera3Device::setStreamingRequestList(
1231 const List<const PhysicalCameraSettingsList> &requestsList,
1232 const std::list<const SurfaceMap> &surfaceMaps, int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -07001233 ATRACE_CALL();
1234
Emilian Peevaebbe412018-01-15 13:53:24 +00001235 return submitRequestsHelper(requestsList, surfaceMaps, /*repeating*/true, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -07001236}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001237
1238sp<Camera3Device::CaptureRequest> Camera3Device::setUpRequestLocked(
Emilian Peevaebbe412018-01-15 13:53:24 +00001239 const PhysicalCameraSettingsList &request, const SurfaceMap &surfaceMap) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001240 status_t res;
1241
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001242 if (mStatus == STATUS_UNCONFIGURED || mNeedConfig) {
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08001243 // This point should only be reached via API1 (API2 must explicitly call configureStreams)
1244 // so unilaterally select normal operating mode.
Emilian Peevaebbe412018-01-15 13:53:24 +00001245 res = filterParamsAndConfigureLocked(request.begin()->metadata,
Emilian Peevf4816702020-04-03 15:44:51 -07001246 CAMERA_STREAM_CONFIGURATION_NORMAL_MODE);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001247 // Stream configuration failed. Client might try other configuraitons.
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001248 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001249 CLOGE("Can't set up streams: %s (%d)", strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001250 return NULL;
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001251 } else if (mStatus == STATUS_UNCONFIGURED) {
1252 // Stream configuration successfully configure to empty stream configuration.
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001253 CLOGE("No streams configured");
1254 return NULL;
1255 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001256 }
1257
Shuzhen Wang0129d522016-10-30 22:43:41 -07001258 sp<CaptureRequest> newRequest = createCaptureRequest(request, surfaceMap);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001259 return newRequest;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001260}
1261
Jianing Weicb0652e2014-03-12 18:29:36 -07001262status_t Camera3Device::clearStreamingRequest(int64_t *lastFrameNumber) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001263 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001264 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001265 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001266
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001267 switch (mStatus) {
1268 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001269 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001270 return INVALID_OPERATION;
1271 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001272 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001273 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001274 case STATUS_UNCONFIGURED:
1275 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001276 case STATUS_ACTIVE:
1277 // OK
1278 break;
1279 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001280 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001281 return INVALID_OPERATION;
1282 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001283 ALOGV("Camera %s: Clearing repeating request", mId.string());
Jianing Weicb0652e2014-03-12 18:29:36 -07001284
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07001285 return mRequestThread->clearRepeatingRequests(lastFrameNumber);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001286}
1287
1288status_t Camera3Device::waitUntilRequestReceived(int32_t requestId, nsecs_t timeout) {
1289 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001290 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001291
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001292 return mRequestThread->waitUntilRequestProcessed(requestId, timeout);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001293}
1294
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001295status_t Camera3Device::createInputStream(
Shuzhen Wang83bff122020-11-20 15:51:39 -08001296 uint32_t width, uint32_t height, int format, bool isMultiResolution, int *id) {
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001297 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001298 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001299 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001300 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001301 ALOGV("Camera %s: Creating new input stream %d: %d x %d, format %d",
1302 mId.string(), mNextStreamId, width, height, format);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001303
1304 status_t res;
1305 bool wasActive = false;
1306
1307 switch (mStatus) {
1308 case STATUS_ERROR:
1309 ALOGE("%s: Device has encountered a serious error", __FUNCTION__);
1310 return INVALID_OPERATION;
1311 case STATUS_UNINITIALIZED:
1312 ALOGE("%s: Device not initialized", __FUNCTION__);
1313 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001314 case STATUS_UNCONFIGURED:
1315 case STATUS_CONFIGURED:
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001316 // OK
1317 break;
1318 case STATUS_ACTIVE:
1319 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001320 res = internalPauseAndWaitLocked(maxExpectedDuration);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001321 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001322 SET_ERR_L("Can't pause captures to reconfigure streams!");
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001323 return res;
1324 }
1325 wasActive = true;
1326 break;
1327 default:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001328 SET_ERR_L("%s: Unexpected status: %d", mStatus);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001329 return INVALID_OPERATION;
1330 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001331 assert(mStatus != STATUS_ACTIVE);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001332
1333 if (mInputStream != 0) {
1334 ALOGE("%s: Cannot create more than 1 input stream", __FUNCTION__);
1335 return INVALID_OPERATION;
1336 }
1337
1338 sp<Camera3InputStream> newStream = new Camera3InputStream(mNextStreamId,
1339 width, height, format);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001340 newStream->setStatusTracker(mStatusTracker);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001341
1342 mInputStream = newStream;
Shuzhen Wang83bff122020-11-20 15:51:39 -08001343 mIsInputStreamMultiResolution = isMultiResolution;
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001344
1345 *id = mNextStreamId++;
1346
1347 // Continue captures if active at start
1348 if (wasActive) {
1349 ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001350 // Reuse current operating mode and session parameters for new stream config
1351 res = configureStreamsLocked(mOperatingMode, mSessionParams);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001352 if (res != OK) {
1353 ALOGE("%s: Can't reconfigure device for new stream %d: %s (%d)",
1354 __FUNCTION__, mNextStreamId, strerror(-res), res);
1355 return res;
1356 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001357 internalResumeLocked();
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001358 }
1359
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001360 ALOGV("Camera %s: Created input stream", mId.string());
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001361 return OK;
1362}
1363
Eino-Ville Talvala727d1722015-06-09 13:44:19 -07001364status_t Camera3Device::createStream(sp<Surface> consumer,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001365 uint32_t width, uint32_t height, int format,
Emilian Peevf4816702020-04-03 15:44:51 -07001366 android_dataspace dataSpace, camera_stream_rotation_t rotation, int *id,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001367 const String8& physicalCameraId,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001368 const std::unordered_set<int32_t> &sensorPixelModesUsed,
1369 std::vector<int> *surfaceIds, int streamSetId, bool isShared, bool isMultiResolution,
1370 uint64_t consumerUsage) {
Shuzhen Wang0129d522016-10-30 22:43:41 -07001371 ATRACE_CALL();
1372
1373 if (consumer == nullptr) {
1374 ALOGE("%s: consumer must not be null", __FUNCTION__);
1375 return BAD_VALUE;
1376 }
1377
1378 std::vector<sp<Surface>> consumers;
1379 consumers.push_back(consumer);
1380
1381 return createStream(consumers, /*hasDeferredConsumer*/ false, width, height,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001382 format, dataSpace, rotation, id, physicalCameraId, sensorPixelModesUsed, surfaceIds,
1383 streamSetId, isShared, isMultiResolution, consumerUsage);
1384}
1385
1386static bool isRawFormat(int format) {
1387 switch (format) {
1388 case HAL_PIXEL_FORMAT_RAW16:
1389 case HAL_PIXEL_FORMAT_RAW12:
1390 case HAL_PIXEL_FORMAT_RAW10:
1391 case HAL_PIXEL_FORMAT_RAW_OPAQUE:
1392 return true;
1393 default:
1394 return false;
1395 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001396}
1397
1398status_t Camera3Device::createStream(const std::vector<sp<Surface>>& consumers,
1399 bool hasDeferredConsumer, uint32_t width, uint32_t height, int format,
Emilian Peevf4816702020-04-03 15:44:51 -07001400 android_dataspace dataSpace, camera_stream_rotation_t rotation, int *id,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001401 const String8& physicalCameraId, const std::unordered_set<int32_t> &sensorPixelModesUsed,
Shuzhen Wang83bff122020-11-20 15:51:39 -08001402 std::vector<int> *surfaceIds, int streamSetId, bool isShared, bool isMultiResolution,
1403 uint64_t consumerUsage) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001404 ATRACE_CALL();
Emilian Peev40ead602017-09-26 15:46:36 +01001405
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001406 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001407 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001408 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001409 ALOGV("Camera %s: Creating new stream %d: %d x %d, format %d, dataspace %d rotation %d"
Shuzhen Wang83bff122020-11-20 15:51:39 -08001410 " consumer usage %" PRIu64 ", isShared %d, physicalCameraId %s, isMultiResolution %d",
1411 mId.string(), mNextStreamId, width, height, format, dataSpace, rotation,
1412 consumerUsage, isShared, physicalCameraId.string(), isMultiResolution);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001413
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001414 status_t res;
1415 bool wasActive = false;
1416
1417 switch (mStatus) {
1418 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001419 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001420 return INVALID_OPERATION;
1421 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001422 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001423 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001424 case STATUS_UNCONFIGURED:
1425 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001426 // OK
1427 break;
1428 case STATUS_ACTIVE:
1429 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001430 res = internalPauseAndWaitLocked(maxExpectedDuration);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001431 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001432 SET_ERR_L("Can't pause captures to reconfigure streams!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001433 return res;
1434 }
1435 wasActive = true;
1436 break;
1437 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001438 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001439 return INVALID_OPERATION;
1440 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001441 assert(mStatus != STATUS_ACTIVE);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001442
1443 sp<Camera3OutputStream> newStream;
Zhijun He5d677d12016-05-29 16:52:39 -07001444
Shuzhen Wang0129d522016-10-30 22:43:41 -07001445 if (consumers.size() == 0 && !hasDeferredConsumer) {
1446 ALOGE("%s: Number of consumers cannot be smaller than 1", __FUNCTION__);
1447 return BAD_VALUE;
1448 }
Zhijun He5d677d12016-05-29 16:52:39 -07001449
Shuzhen Wang0129d522016-10-30 22:43:41 -07001450 if (hasDeferredConsumer && format != HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
Zhijun He5d677d12016-05-29 16:52:39 -07001451 ALOGE("Deferred consumer stream creation only support IMPLEMENTATION_DEFINED format");
1452 return BAD_VALUE;
1453 }
1454
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001455 if (isRawFormat(format) && sensorPixelModesUsed.size() > 1) {
1456 // We can't use one stream with a raw format in both sensor pixel modes since its going to
1457 // be found in only one sensor pixel mode.
1458 ALOGE("%s: RAW opaque stream cannot be used with > 1 sensor pixel modes", __FUNCTION__);
1459 return BAD_VALUE;
1460 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001461 if (format == HAL_PIXEL_FORMAT_BLOB) {
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -07001462 ssize_t blobBufferSize;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001463 if (dataSpace == HAL_DATASPACE_DEPTH) {
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -07001464 blobBufferSize = getPointCloudBufferSize();
1465 if (blobBufferSize <= 0) {
1466 SET_ERR_L("Invalid point cloud buffer size %zd", blobBufferSize);
1467 return BAD_VALUE;
1468 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001469 } else if (dataSpace == static_cast<android_dataspace>(HAL_DATASPACE_JPEG_APP_SEGMENTS)) {
1470 blobBufferSize = width * height;
1471 } else {
1472 blobBufferSize = getJpegBufferSize(width, height);
1473 if (blobBufferSize <= 0) {
1474 SET_ERR_L("Invalid jpeg buffer size %zd", blobBufferSize);
1475 return BAD_VALUE;
1476 }
Zhijun Hef7da0962014-04-24 13:27:56 -07001477 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001478 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001479 width, height, blobBufferSize, format, dataSpace, rotation,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001480 mTimestampOffset, physicalCameraId, sensorPixelModesUsed, streamSetId,
1481 isMultiResolution);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -08001482 } else if (format == HAL_PIXEL_FORMAT_RAW_OPAQUE) {
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001483 bool maxResolution =
1484 sensorPixelModesUsed.find(ANDROID_SENSOR_PIXEL_MODE_MAXIMUM_RESOLUTION) !=
1485 sensorPixelModesUsed.end();
1486 ssize_t rawOpaqueBufferSize = getRawOpaqueBufferSize(width, height, maxResolution);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -08001487 if (rawOpaqueBufferSize <= 0) {
1488 SET_ERR_L("Invalid RAW opaque buffer size %zd", rawOpaqueBufferSize);
1489 return BAD_VALUE;
1490 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001491 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001492 width, height, rawOpaqueBufferSize, format, dataSpace, rotation,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001493 mTimestampOffset, physicalCameraId, sensorPixelModesUsed, streamSetId,
1494 isMultiResolution);
Shuzhen Wang758c2152017-01-10 18:26:18 -08001495 } else if (isShared) {
1496 newStream = new Camera3SharedOutputStream(mNextStreamId, consumers,
1497 width, height, format, consumerUsage, dataSpace, rotation,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001498 mTimestampOffset, physicalCameraId, sensorPixelModesUsed, streamSetId,
1499 mUseHalBufManager);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001500 } else if (consumers.size() == 0 && hasDeferredConsumer) {
Zhijun He5d677d12016-05-29 16:52:39 -07001501 newStream = new Camera3OutputStream(mNextStreamId,
1502 width, height, format, consumerUsage, dataSpace, rotation,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001503 mTimestampOffset, physicalCameraId, sensorPixelModesUsed, streamSetId,
1504 isMultiResolution);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001505 } else {
Shuzhen Wang0129d522016-10-30 22:43:41 -07001506 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001507 width, height, format, dataSpace, rotation,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001508 mTimestampOffset, physicalCameraId, sensorPixelModesUsed, streamSetId,
1509 isMultiResolution);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001510 }
Emilian Peev40ead602017-09-26 15:46:36 +01001511
1512 size_t consumerCount = consumers.size();
1513 for (size_t i = 0; i < consumerCount; i++) {
1514 int id = newStream->getSurfaceId(consumers[i]);
1515 if (id < 0) {
1516 SET_ERR_L("Invalid surface id");
1517 return BAD_VALUE;
1518 }
1519 if (surfaceIds != nullptr) {
1520 surfaceIds->push_back(id);
1521 }
1522 }
1523
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001524 newStream->setStatusTracker(mStatusTracker);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001525
Emilian Peev08dd2452017-04-06 16:55:14 +01001526 newStream->setBufferManager(mBufferManager);
Zhijun He125684a2015-12-26 15:07:30 -08001527
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08001528 newStream->setImageDumpMask(mImageDumpMask);
1529
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001530 res = mOutputStreams.add(mNextStreamId, newStream);
1531 if (res < 0) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001532 SET_ERR_L("Can't add new stream to set: %s (%d)", strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001533 return res;
1534 }
1535
Shuzhen Wang316781a2020-08-18 18:11:01 -07001536 mSessionStatsBuilder.addStream(mNextStreamId);
1537
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001538 *id = mNextStreamId++;
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07001539 mNeedConfig = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001540
1541 // Continue captures if active at start
1542 if (wasActive) {
1543 ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001544 // Reuse current operating mode and session parameters for new stream config
1545 res = configureStreamsLocked(mOperatingMode, mSessionParams);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001546 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001547 CLOGE("Can't reconfigure device for new stream %d: %s (%d)",
1548 mNextStreamId, strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001549 return res;
1550 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001551 internalResumeLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001552 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001553 ALOGV("Camera %s: Created new stream", mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001554 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001555}
1556
Emilian Peev710c1422017-08-30 11:19:38 +01001557status_t Camera3Device::getStreamInfo(int id, StreamInfo *streamInfo) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001558 ATRACE_CALL();
Emilian Peev710c1422017-08-30 11:19:38 +01001559 if (nullptr == streamInfo) {
1560 return BAD_VALUE;
1561 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001562 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001563 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001564
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001565 switch (mStatus) {
1566 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001567 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001568 return INVALID_OPERATION;
1569 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001570 CLOGE("Device not initialized!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001571 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001572 case STATUS_UNCONFIGURED:
1573 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001574 case STATUS_ACTIVE:
1575 // OK
1576 break;
1577 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001578 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001579 return INVALID_OPERATION;
1580 }
1581
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001582 sp<Camera3StreamInterface> stream = mOutputStreams.get(id);
1583 if (stream == nullptr) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001584 CLOGE("Stream %d is unknown", id);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001585 return BAD_VALUE;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001586 }
1587
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001588 streamInfo->width = stream->getWidth();
1589 streamInfo->height = stream->getHeight();
1590 streamInfo->format = stream->getFormat();
1591 streamInfo->dataSpace = stream->getDataSpace();
1592 streamInfo->formatOverridden = stream->isFormatOverridden();
1593 streamInfo->originalFormat = stream->getOriginalFormat();
1594 streamInfo->dataSpaceOverridden = stream->isDataSpaceOverridden();
1595 streamInfo->originalDataSpace = stream->getOriginalDataSpace();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001596 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001597}
1598
1599status_t Camera3Device::setStreamTransform(int id,
1600 int transform) {
1601 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001602 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001603 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001604
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001605 switch (mStatus) {
1606 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001607 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001608 return INVALID_OPERATION;
1609 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001610 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001611 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001612 case STATUS_UNCONFIGURED:
1613 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001614 case STATUS_ACTIVE:
1615 // OK
1616 break;
1617 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001618 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001619 return INVALID_OPERATION;
1620 }
1621
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001622 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(id);
1623 if (stream == nullptr) {
1624 CLOGE("Stream %d does not exist", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001625 return BAD_VALUE;
1626 }
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001627 return stream->setTransform(transform);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001628}
1629
1630status_t Camera3Device::deleteStream(int id) {
1631 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001632 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001633 Mutex::Autolock l(mLock);
1634 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001635
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001636 ALOGV("%s: Camera %s: Deleting stream %d", __FUNCTION__, mId.string(), id);
Igor Murashkine2172be2013-05-28 15:31:39 -07001637
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001638 // CameraDevice semantics require device to already be idle before
1639 // deleteStream is called, unlike for createStream.
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001640 if (mStatus == STATUS_ACTIVE) {
Yin-Chia Yeh693047d2018-03-08 12:14:19 -08001641 ALOGW("%s: Camera %s: Device not idle", __FUNCTION__, mId.string());
Igor Murashkin52827132013-05-13 14:53:44 -07001642 return -EBUSY;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001643 }
1644
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07001645 if (mStatus == STATUS_ERROR) {
1646 ALOGW("%s: Camera %s: deleteStream not allowed in ERROR state",
1647 __FUNCTION__, mId.string());
1648 return -EBUSY;
1649 }
1650
Igor Murashkin2fba5842013-04-22 14:03:54 -07001651 sp<Camera3StreamInterface> deletedStream;
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001652 sp<Camera3StreamInterface> stream = mOutputStreams.get(id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001653 if (mInputStream != NULL && id == mInputStream->getId()) {
1654 deletedStream = mInputStream;
1655 mInputStream.clear();
1656 } else {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001657 if (stream == nullptr) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001658 CLOGE("Stream %d does not exist", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001659 return BAD_VALUE;
1660 }
Shuzhen Wang316781a2020-08-18 18:11:01 -07001661 mSessionStatsBuilder.removeStream(id);
Zhijun He5f446352014-01-22 09:49:33 -08001662 }
1663
1664 // Delete output stream or the output part of a bi-directional stream.
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001665 if (stream != nullptr) {
1666 deletedStream = stream;
1667 mOutputStreams.remove(id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001668 }
1669
1670 // Free up the stream endpoint so that it can be used by some other stream
1671 res = deletedStream->disconnect();
1672 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001673 SET_ERR_L("Can't disconnect deleted stream %d", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001674 // fall through since we want to still list the stream as deleted.
1675 }
1676 mDeletedStreams.add(deletedStream);
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07001677 mNeedConfig = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001678
1679 return res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001680}
1681
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001682status_t Camera3Device::configureStreams(const CameraMetadata& sessionParams, int operatingMode) {
Igor Murashkine2d167e2014-08-19 16:19:59 -07001683 ATRACE_CALL();
1684 ALOGV("%s: E", __FUNCTION__);
1685
1686 Mutex::Autolock il(mInterfaceLock);
1687 Mutex::Autolock l(mLock);
Chien-Yu Chen17338fc2015-06-18 16:30:12 -07001688
Emilian Peev811d2952018-05-25 11:08:40 +01001689 // In case the client doesn't include any session parameter, try a
1690 // speculative configuration using the values from the last cached
1691 // default request.
1692 if (sessionParams.isEmpty() &&
Emilian Peevf4816702020-04-03 15:44:51 -07001693 ((mLastTemplateId > 0) && (mLastTemplateId < CAMERA_TEMPLATE_COUNT)) &&
Emilian Peev811d2952018-05-25 11:08:40 +01001694 (!mRequestTemplateCache[mLastTemplateId].isEmpty())) {
1695 ALOGV("%s: Speculative session param configuration with template id: %d", __func__,
1696 mLastTemplateId);
1697 return filterParamsAndConfigureLocked(mRequestTemplateCache[mLastTemplateId],
1698 operatingMode);
1699 }
1700
Emilian Peevac3ce6c2017-12-12 15:27:02 +00001701 return filterParamsAndConfigureLocked(sessionParams, operatingMode);
1702}
1703
1704status_t Camera3Device::filterParamsAndConfigureLocked(const CameraMetadata& sessionParams,
1705 int operatingMode) {
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001706 //Filter out any incoming session parameters
1707 const CameraMetadata params(sessionParams);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001708 camera_metadata_entry_t availableSessionKeys = mDeviceInfo.find(
1709 ANDROID_REQUEST_AVAILABLE_SESSION_KEYS);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00001710 CameraMetadata filteredParams(availableSessionKeys.count);
1711 camera_metadata_t *meta = const_cast<camera_metadata_t *>(
1712 filteredParams.getAndLock());
1713 set_camera_metadata_vendor_id(meta, mVendorTagId);
1714 filteredParams.unlock(meta);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001715 if (availableSessionKeys.count > 0) {
1716 for (size_t i = 0; i < availableSessionKeys.count; i++) {
1717 camera_metadata_ro_entry entry = params.find(
1718 availableSessionKeys.data.i32[i]);
1719 if (entry.count > 0) {
1720 filteredParams.update(entry);
1721 }
1722 }
1723 }
1724
1725 return configureStreamsLocked(operatingMode, filteredParams);
Igor Murashkine2d167e2014-08-19 16:19:59 -07001726}
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001727
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07001728status_t Camera3Device::getInputBufferProducer(
1729 sp<IGraphicBufferProducer> *producer) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07001730 ATRACE_CALL();
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07001731 Mutex::Autolock il(mInterfaceLock);
1732 Mutex::Autolock l(mLock);
1733
1734 if (producer == NULL) {
1735 return BAD_VALUE;
1736 } else if (mInputStream == NULL) {
1737 return INVALID_OPERATION;
1738 }
1739
1740 return mInputStream->getInputBufferProducer(producer);
1741}
1742
Emilian Peevf4816702020-04-03 15:44:51 -07001743status_t Camera3Device::createDefaultRequest(camera_request_template_t templateId,
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001744 CameraMetadata *request) {
1745 ATRACE_CALL();
Alex Rayfe7e0c62013-05-30 00:12:13 -07001746 ALOGV("%s: for template %d", __FUNCTION__, templateId);
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08001747
Emilian Peevf4816702020-04-03 15:44:51 -07001748 if (templateId <= 0 || templateId >= CAMERA_TEMPLATE_COUNT) {
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08001749 android_errorWriteWithInfoLog(CameraService::SN_EVENT_LOG_ID, "26866110",
Jayant Chowdhary12361932018-08-27 14:46:13 -07001750 CameraThreadState::getCallingUid(), nullptr, 0);
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08001751 return BAD_VALUE;
1752 }
1753
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001754 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001755
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001756 {
1757 Mutex::Autolock l(mLock);
1758 switch (mStatus) {
1759 case STATUS_ERROR:
1760 CLOGE("Device has encountered a serious error");
1761 return INVALID_OPERATION;
1762 case STATUS_UNINITIALIZED:
1763 CLOGE("Device is not initialized!");
1764 return INVALID_OPERATION;
1765 case STATUS_UNCONFIGURED:
1766 case STATUS_CONFIGURED:
1767 case STATUS_ACTIVE:
1768 // OK
1769 break;
1770 default:
1771 SET_ERR_L("Unexpected status: %d", mStatus);
1772 return INVALID_OPERATION;
1773 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001774
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001775 if (!mRequestTemplateCache[templateId].isEmpty()) {
1776 *request = mRequestTemplateCache[templateId];
Emilian Peev811d2952018-05-25 11:08:40 +01001777 mLastTemplateId = templateId;
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001778 return OK;
1779 }
Zhijun Hea1530f12014-09-14 12:44:20 -07001780 }
1781
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001782 camera_metadata_t *rawRequest;
1783 status_t res = mInterface->constructDefaultRequestSettings(
Emilian Peevf4816702020-04-03 15:44:51 -07001784 (camera_request_template_t) templateId, &rawRequest);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001785
1786 {
1787 Mutex::Autolock l(mLock);
1788 if (res == BAD_VALUE) {
1789 ALOGI("%s: template %d is not supported on this camera device",
1790 __FUNCTION__, templateId);
1791 return res;
1792 } else if (res != OK) {
1793 CLOGE("Unable to construct request template %d: %s (%d)",
1794 templateId, strerror(-res), res);
1795 return res;
1796 }
1797
1798 set_camera_metadata_vendor_id(rawRequest, mVendorTagId);
1799 mRequestTemplateCache[templateId].acquire(rawRequest);
1800
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08001801 // Override the template request with zoomRatioMapper
1802 res = mZoomRatioMappers[mId.c_str()].initZoomRatioInTemplate(
1803 &mRequestTemplateCache[templateId]);
1804 if (res != OK) {
1805 CLOGE("Failed to update zoom ratio for template %d: %s (%d)",
1806 templateId, strerror(-res), res);
1807 return res;
1808 }
1809
Shuzhen Wangd25dc972020-03-24 17:11:43 -07001810 // Fill in JPEG_QUALITY if not available
1811 if (!mRequestTemplateCache[templateId].exists(ANDROID_JPEG_QUALITY)) {
1812 static const uint8_t kDefaultJpegQuality = 95;
1813 mRequestTemplateCache[templateId].update(ANDROID_JPEG_QUALITY,
1814 &kDefaultJpegQuality, 1);
1815 }
1816
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001817 *request = mRequestTemplateCache[templateId];
Emilian Peev811d2952018-05-25 11:08:40 +01001818 mLastTemplateId = templateId;
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001819 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001820 return OK;
1821}
1822
1823status_t Camera3Device::waitUntilDrained() {
1824 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001825 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001826 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001827 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001828
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001829 return waitUntilDrainedLocked(maxExpectedDuration);
Zhijun He69a37482014-03-23 18:44:49 -07001830}
1831
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001832status_t Camera3Device::waitUntilDrainedLocked(nsecs_t maxExpectedDuration) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001833 switch (mStatus) {
1834 case STATUS_UNINITIALIZED:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001835 case STATUS_UNCONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001836 ALOGV("%s: Already idle", __FUNCTION__);
1837 return OK;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001838 case STATUS_CONFIGURED:
1839 // To avoid race conditions, check with tracker to be sure
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001840 case STATUS_ERROR:
1841 case STATUS_ACTIVE:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001842 // Need to verify shut down
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001843 break;
1844 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001845 SET_ERR_L("Unexpected status: %d",mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001846 return INVALID_OPERATION;
1847 }
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07001848 ALOGV("%s: Camera %s: Waiting until idle (%" PRIi64 "ns)", __FUNCTION__, mId.string(),
1849 maxExpectedDuration);
1850 status_t res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
Eino-Ville Talvala9c8a0912014-09-14 14:52:19 -07001851 if (res != OK) {
Yin-Chia Yeh87b3ec02019-06-03 10:44:39 -07001852 mStatusTracker->dumpActiveComponents();
Eino-Ville Talvala9c8a0912014-09-14 14:52:19 -07001853 SET_ERR_L("Error waiting for HAL to drain: %s (%d)", strerror(-res),
1854 res);
1855 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001856 return res;
1857}
1858
Ruben Brunk183f0562015-08-12 12:55:02 -07001859void Camera3Device::internalUpdateStatusLocked(Status status) {
1860 mStatus = status;
1861 mRecentStatusUpdates.add(mStatus);
1862 mStatusChanged.broadcast();
1863}
1864
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001865// Pause to reconfigure
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001866status_t Camera3Device::internalPauseAndWaitLocked(nsecs_t maxExpectedDuration) {
Emilian Peeve86358b2019-02-15 13:51:39 -08001867 if (mRequestThread.get() != nullptr) {
1868 mRequestThread->setPaused(true);
1869 } else {
1870 return NO_INIT;
1871 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001872
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07001873 ALOGV("%s: Camera %s: Internal wait until idle (% " PRIi64 " ns)", __FUNCTION__, mId.string(),
1874 maxExpectedDuration);
1875 status_t res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001876 if (res != OK) {
1877 SET_ERR_L("Can't idle device in %f seconds!",
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07001878 maxExpectedDuration/1e9);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001879 }
1880
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001881 return res;
1882}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001883
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001884// Resume after internalPauseAndWaitLocked
1885status_t Camera3Device::internalResumeLocked() {
1886 status_t res;
1887
1888 mRequestThread->setPaused(false);
1889
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08001890 ALOGV("%s: Camera %s: Internal wait until active (% " PRIi64 " ns)", __FUNCTION__, mId.string(),
1891 kActiveTimeout);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001892 res = waitUntilStateThenRelock(/*active*/ true, kActiveTimeout);
1893 if (res != OK) {
1894 SET_ERR_L("Can't transition to active in %f seconds!",
1895 kActiveTimeout/1e9);
1896 }
1897 mPauseStateNotify = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001898 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001899}
1900
Ruben Brunk183f0562015-08-12 12:55:02 -07001901status_t Camera3Device::waitUntilStateThenRelock(bool active, nsecs_t timeout) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001902 status_t res = OK;
Ruben Brunk183f0562015-08-12 12:55:02 -07001903
1904 size_t startIndex = 0;
1905 if (mStatusWaiters == 0) {
1906 // Clear the list of recent statuses if there are no existing threads waiting on updates to
1907 // this status list
1908 mRecentStatusUpdates.clear();
1909 } else {
1910 // If other threads are waiting on updates to this status list, set the position of the
1911 // first element that this list will check rather than clearing the list.
1912 startIndex = mRecentStatusUpdates.size();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001913 }
1914
Ruben Brunk183f0562015-08-12 12:55:02 -07001915 mStatusWaiters++;
1916
Yin-Chia Yehe52b8fa2020-07-28 00:17:58 -07001917 bool signalPipelineDrain = false;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07001918 if (!active && mUseHalBufManager) {
1919 auto streamIds = mOutputStreams.getStreamIds();
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08001920 if (mStatus == STATUS_ACTIVE) {
1921 mRequestThread->signalPipelineDrain(streamIds);
Yin-Chia Yehe52b8fa2020-07-28 00:17:58 -07001922 signalPipelineDrain = true;
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08001923 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07001924 mRequestBufferSM.onWaitUntilIdle();
1925 }
1926
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001927 bool stateSeen = false;
1928 do {
Ruben Brunk183f0562015-08-12 12:55:02 -07001929 if (active == (mStatus == STATUS_ACTIVE)) {
1930 // Desired state is current
1931 break;
1932 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001933
1934 res = mStatusChanged.waitRelative(mLock, timeout);
1935 if (res != OK) break;
1936
Ruben Brunk183f0562015-08-12 12:55:02 -07001937 // This is impossible, but if not, could result in subtle deadlocks and invalid state
1938 // transitions.
1939 LOG_ALWAYS_FATAL_IF(startIndex > mRecentStatusUpdates.size(),
1940 "%s: Skipping status updates in Camera3Device, may result in deadlock.",
1941 __FUNCTION__);
1942
1943 // Encountered desired state since we began waiting
1944 for (size_t i = startIndex; i < mRecentStatusUpdates.size(); i++) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001945 if (active == (mRecentStatusUpdates[i] == STATUS_ACTIVE) ) {
1946 stateSeen = true;
1947 break;
1948 }
1949 }
1950 } while (!stateSeen);
1951
Yin-Chia Yehe52b8fa2020-07-28 00:17:58 -07001952 if (signalPipelineDrain) {
1953 mRequestThread->resetPipelineDrain();
1954 }
1955
Ruben Brunk183f0562015-08-12 12:55:02 -07001956 mStatusWaiters--;
1957
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001958 return res;
1959}
1960
1961
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001962status_t Camera3Device::setNotifyCallback(wp<NotificationListener> listener) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001963 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001964 std::lock_guard<std::mutex> l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001965
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001966 if (listener != NULL && mListener != NULL) {
1967 ALOGW("%s: Replacing old callback listener", __FUNCTION__);
1968 }
1969 mListener = listener;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001970 mRequestThread->setNotificationListener(listener);
1971 mPreparerThread->setNotificationListener(listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001972
1973 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001974}
1975
Eino-Ville Talvala46910bd2013-07-18 19:15:17 -07001976bool Camera3Device::willNotify3A() {
1977 return false;
1978}
1979
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001980status_t Camera3Device::waitForNextFrame(nsecs_t timeout) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07001981 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001982 std::unique_lock<std::mutex> l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001983
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001984 while (mResultQueue.empty()) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001985 auto st = mResultSignal.wait_for(l, std::chrono::nanoseconds(timeout));
1986 if (st == std::cv_status::timeout) {
1987 return TIMED_OUT;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001988 }
1989 }
1990 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001991}
1992
Jianing Weicb0652e2014-03-12 18:29:36 -07001993status_t Camera3Device::getNextResult(CaptureResult *frame) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001994 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001995 std::lock_guard<std::mutex> l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001996
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001997 if (mResultQueue.empty()) {
1998 return NOT_ENOUGH_DATA;
1999 }
2000
Jianing Weicb0652e2014-03-12 18:29:36 -07002001 if (frame == NULL) {
2002 ALOGE("%s: argument cannot be NULL", __FUNCTION__);
2003 return BAD_VALUE;
2004 }
2005
2006 CaptureResult &result = *(mResultQueue.begin());
2007 frame->mResultExtras = result.mResultExtras;
2008 frame->mMetadata.acquire(result.mMetadata);
Shuzhen Wang5c22c152017-12-31 17:12:25 -08002009 frame->mPhysicalMetadatas = std::move(result.mPhysicalMetadatas);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002010 mResultQueue.erase(mResultQueue.begin());
2011
2012 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002013}
2014
2015status_t Camera3Device::triggerAutofocus(uint32_t id) {
2016 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002017 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002018
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002019 ALOGV("%s: Triggering autofocus, id %d", __FUNCTION__, id);
2020 // Mix-in this trigger into the next request and only the next request.
2021 RequestTrigger trigger[] = {
2022 {
2023 ANDROID_CONTROL_AF_TRIGGER,
2024 ANDROID_CONTROL_AF_TRIGGER_START
2025 },
2026 {
2027 ANDROID_CONTROL_AF_TRIGGER_ID,
2028 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07002029 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002030 };
2031
2032 return mRequestThread->queueTrigger(trigger,
2033 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002034}
2035
2036status_t Camera3Device::triggerCancelAutofocus(uint32_t id) {
2037 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002038 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002039
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002040 ALOGV("%s: Triggering cancel autofocus, id %d", __FUNCTION__, id);
2041 // Mix-in this trigger into the next request and only the next request.
2042 RequestTrigger trigger[] = {
2043 {
2044 ANDROID_CONTROL_AF_TRIGGER,
2045 ANDROID_CONTROL_AF_TRIGGER_CANCEL
2046 },
2047 {
2048 ANDROID_CONTROL_AF_TRIGGER_ID,
2049 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07002050 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002051 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002052
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002053 return mRequestThread->queueTrigger(trigger,
2054 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002055}
2056
2057status_t Camera3Device::triggerPrecaptureMetering(uint32_t id) {
2058 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002059 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002060
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002061 ALOGV("%s: Triggering precapture metering, id %d", __FUNCTION__, id);
2062 // Mix-in this trigger into the next request and only the next request.
2063 RequestTrigger trigger[] = {
2064 {
2065 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER,
2066 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_START
2067 },
2068 {
2069 ANDROID_CONTROL_AE_PRECAPTURE_ID,
2070 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07002071 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002072 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002073
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002074 return mRequestThread->queueTrigger(trigger,
2075 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002076}
2077
Jianing Weicb0652e2014-03-12 18:29:36 -07002078status_t Camera3Device::flush(int64_t *frameNumber) {
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07002079 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002080 ALOGV("%s: Camera %s: Flushing all requests", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002081 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07002082
Zhijun He7ef20392014-04-21 16:04:17 -07002083 {
2084 Mutex::Autolock l(mLock);
Emilian Peeved2ebe42018-09-25 16:59:09 +01002085
2086 // b/116514106 "disconnect()" can get called twice for the same device. The
2087 // camera device will not be initialized during the second run.
2088 if (mStatus == STATUS_UNINITIALIZED) {
2089 return OK;
2090 }
2091
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002092 mRequestThread->clear(/*out*/frameNumber);
Shuzhen Wang316781a2020-08-18 18:11:01 -07002093
2094 // Stop session and stream counter
2095 mSessionStatsBuilder.stopCounter();
Zhijun He7ef20392014-04-21 16:04:17 -07002096 }
2097
Emilian Peev08dd2452017-04-06 16:55:14 +01002098 return mRequestThread->flush();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07002099}
2100
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002101status_t Camera3Device::prepare(int streamId) {
Ruben Brunkc78ac262015-08-13 17:58:46 -07002102 return prepare(camera3::Camera3StreamInterface::ALLOCATE_PIPELINE_MAX, streamId);
2103}
2104
2105status_t Camera3Device::prepare(int maxCount, int streamId) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002106 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002107 ALOGV("%s: Camera %s: Preparing stream %d", __FUNCTION__, mId.string(), streamId);
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07002108 Mutex::Autolock il(mInterfaceLock);
2109 Mutex::Autolock l(mLock);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002110
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002111 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
2112 if (stream == nullptr) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002113 CLOGE("Stream %d does not exist", streamId);
2114 return BAD_VALUE;
2115 }
2116
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002117 if (stream->isUnpreparable() || stream->hasOutstandingBuffers() ) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07002118 CLOGE("Stream %d has already been a request target", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002119 return BAD_VALUE;
2120 }
2121
2122 if (mRequestThread->isStreamPending(stream)) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07002123 CLOGE("Stream %d is already a target in a pending request", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002124 return BAD_VALUE;
2125 }
2126
Ruben Brunkc78ac262015-08-13 17:58:46 -07002127 return mPreparerThread->prepare(maxCount, stream);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002128}
2129
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002130status_t Camera3Device::tearDown(int streamId) {
2131 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002132 ALOGV("%s: Camera %s: Tearing down stream %d", __FUNCTION__, mId.string(), streamId);
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002133 Mutex::Autolock il(mInterfaceLock);
2134 Mutex::Autolock l(mLock);
2135
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002136 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
2137 if (stream == nullptr) {
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002138 CLOGE("Stream %d does not exist", streamId);
2139 return BAD_VALUE;
2140 }
2141
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002142 if (stream->hasOutstandingBuffers() || mRequestThread->isStreamPending(stream)) {
2143 CLOGE("Stream %d is a target of a in-progress request", streamId);
2144 return BAD_VALUE;
2145 }
2146
2147 return stream->tearDown();
2148}
2149
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002150status_t Camera3Device::addBufferListenerForStream(int streamId,
2151 wp<Camera3StreamBufferListener> listener) {
2152 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002153 ALOGV("%s: Camera %s: Adding buffer listener for stream %d", __FUNCTION__, mId.string(), streamId);
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002154 Mutex::Autolock il(mInterfaceLock);
2155 Mutex::Autolock l(mLock);
2156
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002157 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
2158 if (stream == nullptr) {
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002159 CLOGE("Stream %d does not exist", streamId);
2160 return BAD_VALUE;
2161 }
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002162 stream->addBufferListener(listener);
2163
2164 return OK;
2165}
2166
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002167/**
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002168 * Methods called by subclasses
2169 */
2170
2171void Camera3Device::notifyStatus(bool idle) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002172 ATRACE_CALL();
Shuzhen Wang316781a2020-08-18 18:11:01 -07002173 std::vector<int> streamIds;
2174 std::vector<hardware::CameraStreamStats> streamStats;
2175
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002176 {
2177 // Need mLock to safely update state and synchronize to current
2178 // state of methods in flight.
2179 Mutex::Autolock l(mLock);
2180 // We can get various system-idle notices from the status tracker
2181 // while starting up. Only care about them if we've actually sent
2182 // in some requests recently.
2183 if (mStatus != STATUS_ACTIVE && mStatus != STATUS_CONFIGURED) {
2184 return;
2185 }
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08002186 ALOGV("%s: Camera %s: Now %s, pauseState: %s", __FUNCTION__, mId.string(),
2187 idle ? "idle" : "active", mPauseStateNotify ? "true" : "false");
Ruben Brunk183f0562015-08-12 12:55:02 -07002188 internalUpdateStatusLocked(idle ? STATUS_CONFIGURED : STATUS_ACTIVE);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002189
2190 // Skip notifying listener if we're doing some user-transparent
2191 // state changes
2192 if (mPauseStateNotify) return;
Shuzhen Wang316781a2020-08-18 18:11:01 -07002193
2194 // Populate stream statistics in case of Idle
2195 if (idle) {
2196 for (size_t i = 0; i < mOutputStreams.size(); i++) {
2197 auto stream = mOutputStreams[i];
2198 if (stream.get() == nullptr) continue;
2199 streamIds.push_back(stream->getId());
2200 Camera3Stream* camera3Stream = Camera3Stream::cast(stream->asHalStream());
2201 int64_t usage = 0LL;
2202 if (camera3Stream != nullptr) {
2203 usage = camera3Stream->getUsage();
2204 }
2205 streamStats.emplace_back(stream->getWidth(), stream->getHeight(),
2206 stream->getFormat(), stream->getDataSpace(), usage,
2207 stream->getMaxHalBuffers(),
2208 stream->getMaxTotalBuffers() - stream->getMaxHalBuffers());
2209 }
2210 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002211 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002212
2213 sp<NotificationListener> listener;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002214 {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002215 std::lock_guard<std::mutex> l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002216 listener = mListener.promote();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002217 }
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07002218 status_t res = OK;
2219 if (listener != nullptr) {
2220 if (idle) {
2221 // Get session stats from the builder, and notify the listener.
2222 int64_t requestCount, resultErrorCount;
2223 bool deviceError;
2224 std::map<int, StreamStats> streamStatsMap;
2225 mSessionStatsBuilder.buildAndReset(&requestCount, &resultErrorCount,
2226 &deviceError, &streamStatsMap);
2227 for (size_t i = 0; i < streamIds.size(); i++) {
2228 int streamId = streamIds[i];
2229 auto stats = streamStatsMap.find(streamId);
2230 if (stats != streamStatsMap.end()) {
2231 streamStats[i].mRequestCount = stats->second.mRequestedFrameCount;
2232 streamStats[i].mErrorCount = stats->second.mDroppedFrameCount;
2233 streamStats[i].mStartLatencyMs = stats->second.mStartLatencyMs;
2234 streamStats[i].mHistogramType =
2235 hardware::CameraStreamStats::HISTOGRAM_TYPE_CAPTURE_LATENCY;
2236 streamStats[i].mHistogramBins.assign(
2237 stats->second.mCaptureLatencyBins.begin(),
2238 stats->second.mCaptureLatencyBins.end());
2239 streamStats[i].mHistogramCounts.assign(
2240 stats->second.mCaptureLatencyHistogram.begin(),
2241 stats->second.mCaptureLatencyHistogram.end());
2242 }
Shuzhen Wang316781a2020-08-18 18:11:01 -07002243 }
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07002244 listener->notifyIdle(requestCount, resultErrorCount, deviceError, streamStats);
2245 } else {
2246 res = listener->notifyActive();
Shuzhen Wang316781a2020-08-18 18:11:01 -07002247 }
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07002248 }
2249 if (res != OK) {
2250 SET_ERR("Camera access permission lost mid-operation: %s (%d)",
2251 strerror(-res), res);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002252 }
2253}
2254
Shuzhen Wang758c2152017-01-10 18:26:18 -08002255status_t Camera3Device::setConsumerSurfaces(int streamId,
Emilian Peev40ead602017-09-26 15:46:36 +01002256 const std::vector<sp<Surface>>& consumers, std::vector<int> *surfaceIds) {
Zhijun He5d677d12016-05-29 16:52:39 -07002257 ATRACE_CALL();
Shuzhen Wang758c2152017-01-10 18:26:18 -08002258 ALOGV("%s: Camera %s: set consumer surface for stream %d",
2259 __FUNCTION__, mId.string(), streamId);
Emilian Peev40ead602017-09-26 15:46:36 +01002260
2261 if (surfaceIds == nullptr) {
2262 return BAD_VALUE;
2263 }
2264
Zhijun He5d677d12016-05-29 16:52:39 -07002265 Mutex::Autolock il(mInterfaceLock);
2266 Mutex::Autolock l(mLock);
2267
Shuzhen Wang758c2152017-01-10 18:26:18 -08002268 if (consumers.size() == 0) {
2269 CLOGE("No consumer is passed!");
Zhijun He5d677d12016-05-29 16:52:39 -07002270 return BAD_VALUE;
2271 }
2272
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002273 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
2274 if (stream == nullptr) {
Zhijun He5d677d12016-05-29 16:52:39 -07002275 CLOGE("Stream %d is unknown", streamId);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002276 return BAD_VALUE;
Zhijun He5d677d12016-05-29 16:52:39 -07002277 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002278
2279 // isConsumerConfigurationDeferred will be off after setConsumers
2280 bool isDeferred = stream->isConsumerConfigurationDeferred();
Shuzhen Wang758c2152017-01-10 18:26:18 -08002281 status_t res = stream->setConsumers(consumers);
Zhijun He5d677d12016-05-29 16:52:39 -07002282 if (res != OK) {
2283 CLOGE("Stream %d set consumer failed (error %d %s) ", streamId, res, strerror(-res));
2284 return res;
2285 }
2286
Emilian Peev40ead602017-09-26 15:46:36 +01002287 for (auto &consumer : consumers) {
2288 int id = stream->getSurfaceId(consumer);
2289 if (id < 0) {
2290 CLOGE("Invalid surface id!");
2291 return BAD_VALUE;
2292 }
2293 surfaceIds->push_back(id);
2294 }
2295
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002296 if (isDeferred) {
Shuzhen Wang0129d522016-10-30 22:43:41 -07002297 if (!stream->isConfiguring()) {
2298 CLOGE("Stream %d was already fully configured.", streamId);
2299 return INVALID_OPERATION;
2300 }
Zhijun He5d677d12016-05-29 16:52:39 -07002301
Shuzhen Wang0129d522016-10-30 22:43:41 -07002302 res = stream->finishConfiguration();
2303 if (res != OK) {
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002304 // If finishConfiguration fails due to abandoned surface, do not set
2305 // device to error state.
2306 bool isSurfaceAbandoned =
2307 (res == NO_INIT || res == DEAD_OBJECT) && stream->isAbandoned();
2308 if (!isSurfaceAbandoned) {
2309 SET_ERR_L("Can't finish configuring output stream %d: %s (%d)",
2310 stream->getId(), strerror(-res), res);
2311 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07002312 return res;
2313 }
Zhijun He5d677d12016-05-29 16:52:39 -07002314 }
2315
2316 return OK;
2317}
2318
Emilian Peev40ead602017-09-26 15:46:36 +01002319status_t Camera3Device::updateStream(int streamId, const std::vector<sp<Surface>> &newSurfaces,
2320 const std::vector<OutputStreamInfo> &outputInfo,
2321 const std::vector<size_t> &removedSurfaceIds, KeyedVector<sp<Surface>, size_t> *outputMap) {
2322 Mutex::Autolock il(mInterfaceLock);
2323 Mutex::Autolock l(mLock);
2324
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002325 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
2326 if (stream == nullptr) {
Emilian Peev40ead602017-09-26 15:46:36 +01002327 CLOGE("Stream %d is unknown", streamId);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002328 return BAD_VALUE;
Emilian Peev40ead602017-09-26 15:46:36 +01002329 }
2330
2331 for (const auto &it : removedSurfaceIds) {
2332 if (mRequestThread->isOutputSurfacePending(streamId, it)) {
2333 CLOGE("Shared surface still part of a pending request!");
2334 return -EBUSY;
2335 }
2336 }
2337
Emilian Peev40ead602017-09-26 15:46:36 +01002338 status_t res = stream->updateStream(newSurfaces, outputInfo, removedSurfaceIds, outputMap);
2339 if (res != OK) {
2340 CLOGE("Stream %d failed to update stream (error %d %s) ",
2341 streamId, res, strerror(-res));
2342 if (res == UNKNOWN_ERROR) {
2343 SET_ERR_L("%s: Stream update failed to revert to previous output configuration!",
2344 __FUNCTION__);
2345 }
2346 return res;
2347 }
2348
2349 return res;
2350}
2351
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002352status_t Camera3Device::dropStreamBuffers(bool dropping, int streamId) {
2353 Mutex::Autolock il(mInterfaceLock);
2354 Mutex::Autolock l(mLock);
2355
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002356 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
2357 if (stream == nullptr) {
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002358 ALOGE("%s: Stream %d is not found.", __FUNCTION__, streamId);
2359 return BAD_VALUE;
2360 }
Shuzhen Wang316781a2020-08-18 18:11:01 -07002361
2362 if (dropping) {
2363 mSessionStatsBuilder.stopCounter(streamId);
2364 } else {
2365 mSessionStatsBuilder.startCounter(streamId);
2366 }
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002367 return stream->dropBuffers(dropping);
2368}
2369
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002370/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002371 * Camera3Device private methods
2372 */
2373
2374sp<Camera3Device::CaptureRequest> Camera3Device::createCaptureRequest(
Emilian Peevaebbe412018-01-15 13:53:24 +00002375 const PhysicalCameraSettingsList &request, const SurfaceMap &surfaceMap) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002376 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002377
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08002378 sp<CaptureRequest> newRequest = new CaptureRequest();
Emilian Peevaebbe412018-01-15 13:53:24 +00002379 newRequest->mSettingsList = request;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002380
2381 camera_metadata_entry_t inputStreams =
Emilian Peevaebbe412018-01-15 13:53:24 +00002382 newRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_INPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002383 if (inputStreams.count > 0) {
2384 if (mInputStream == NULL ||
Zhijun Hed1d64672013-09-06 15:00:01 -07002385 mInputStream->getId() != inputStreams.data.i32[0]) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002386 CLOGE("Request references unknown input stream %d",
2387 inputStreams.data.u8[0]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002388 return NULL;
2389 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002390
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002391 if (mInputStream->isConfiguring()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002392 SET_ERR_L("%s: input stream %d is not configured!",
2393 __FUNCTION__, mInputStream->getId());
2394 return NULL;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002395 }
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07002396 // Check if stream prepare is blocking requests.
2397 if (mInputStream->isBlockedByPrepare()) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002398 CLOGE("Request references an input stream that's being prepared!");
2399 return NULL;
2400 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002401
2402 newRequest->mInputStream = mInputStream;
Emilian Peevaebbe412018-01-15 13:53:24 +00002403 newRequest->mSettingsList.begin()->metadata.erase(ANDROID_REQUEST_INPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002404 }
2405
2406 camera_metadata_entry_t streams =
Emilian Peevaebbe412018-01-15 13:53:24 +00002407 newRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_OUTPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002408 if (streams.count == 0) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002409 CLOGE("Zero output streams specified!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002410 return NULL;
2411 }
2412
2413 for (size_t i = 0; i < streams.count; i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002414 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streams.data.i32[i]);
2415 if (stream == nullptr) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002416 CLOGE("Request references unknown stream %d",
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002417 streams.data.i32[i]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002418 return NULL;
2419 }
Zhijun He5d677d12016-05-29 16:52:39 -07002420 // It is illegal to include a deferred consumer output stream into a request
Shuzhen Wang0129d522016-10-30 22:43:41 -07002421 auto iter = surfaceMap.find(streams.data.i32[i]);
2422 if (iter != surfaceMap.end()) {
2423 const std::vector<size_t>& surfaces = iter->second;
2424 for (const auto& surface : surfaces) {
2425 if (stream->isConsumerConfigurationDeferred(surface)) {
2426 CLOGE("Stream %d surface %zu hasn't finished configuration yet "
2427 "due to deferred consumer", stream->getId(), surface);
2428 return NULL;
2429 }
2430 }
Yin-Chia Yeh0b287572018-10-15 12:38:13 -07002431 newRequest->mOutputSurfaces[streams.data.i32[i]] = surfaces;
Zhijun He5d677d12016-05-29 16:52:39 -07002432 }
2433
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002434 if (stream->isConfiguring()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002435 SET_ERR_L("%s: stream %d is not configured!", __FUNCTION__, stream->getId());
2436 return NULL;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002437 }
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07002438 // Check if stream prepare is blocking requests.
2439 if (stream->isBlockedByPrepare()) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002440 CLOGE("Request references an output stream that's being prepared!");
2441 return NULL;
2442 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002443
2444 newRequest->mOutputStreams.push(stream);
2445 }
Emilian Peevaebbe412018-01-15 13:53:24 +00002446 newRequest->mSettingsList.begin()->metadata.erase(ANDROID_REQUEST_OUTPUT_STREAMS);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07002447 newRequest->mBatchSize = 1;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002448
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08002449 auto rotateAndCropEntry =
2450 newRequest->mSettingsList.begin()->metadata.find(ANDROID_SCALER_ROTATE_AND_CROP);
2451 if (rotateAndCropEntry.count > 0 &&
2452 rotateAndCropEntry.data.u8[0] == ANDROID_SCALER_ROTATE_AND_CROP_AUTO) {
2453 newRequest->mRotateAndCropAuto = true;
2454 } else {
2455 newRequest->mRotateAndCropAuto = false;
2456 }
2457
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07002458 auto zoomRatioEntry =
2459 newRequest->mSettingsList.begin()->metadata.find(ANDROID_CONTROL_ZOOM_RATIO);
2460 if (zoomRatioEntry.count > 0 &&
2461 zoomRatioEntry.data.f[0] == 1.0f) {
2462 newRequest->mZoomRatioIs1x = true;
2463 } else {
2464 newRequest->mZoomRatioIs1x = false;
2465 }
2466
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08002467 if (mSupportCameraMute) {
2468 auto testPatternModeEntry =
2469 newRequest->mSettingsList.begin()->metadata.find(ANDROID_SENSOR_TEST_PATTERN_MODE);
2470 newRequest->mOriginalTestPatternMode = testPatternModeEntry.count > 0 ?
2471 testPatternModeEntry.data.i32[0] :
2472 ANDROID_SENSOR_TEST_PATTERN_MODE_OFF;
2473
2474 auto testPatternDataEntry =
2475 newRequest->mSettingsList.begin()->metadata.find(ANDROID_SENSOR_TEST_PATTERN_DATA);
2476 if (testPatternDataEntry.count > 0) {
2477 memcpy(newRequest->mOriginalTestPatternData, testPatternModeEntry.data.i32,
2478 sizeof(newRequest->mOriginalTestPatternData));
2479 } else {
2480 newRequest->mOriginalTestPatternData[0] = 0;
2481 newRequest->mOriginalTestPatternData[1] = 0;
2482 newRequest->mOriginalTestPatternData[2] = 0;
2483 newRequest->mOriginalTestPatternData[3] = 0;
2484 }
2485 }
2486
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002487 return newRequest;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002488}
2489
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002490void Camera3Device::cancelStreamsConfigurationLocked() {
2491 int res = OK;
2492 if (mInputStream != NULL && mInputStream->isConfiguring()) {
2493 res = mInputStream->cancelConfiguration();
2494 if (res != OK) {
2495 CLOGE("Can't cancel configuring input stream %d: %s (%d)",
2496 mInputStream->getId(), strerror(-res), res);
2497 }
2498 }
2499
2500 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002501 sp<Camera3OutputStreamInterface> outputStream = mOutputStreams[i];
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002502 if (outputStream->isConfiguring()) {
2503 res = outputStream->cancelConfiguration();
2504 if (res != OK) {
2505 CLOGE("Can't cancel configuring output stream %d: %s (%d)",
2506 outputStream->getId(), strerror(-res), res);
2507 }
2508 }
2509 }
2510
2511 // Return state to that at start of call, so that future configures
2512 // properly clean things up
2513 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
2514 mNeedConfig = true;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002515
2516 res = mPreparerThread->resume();
2517 if (res != OK) {
2518 ALOGE("%s: Camera %s: Preparer thread failed to resume!", __FUNCTION__, mId.string());
2519 }
2520}
2521
Emilian Peev0d0191e2020-04-21 17:01:18 -07002522bool Camera3Device::checkAbandonedStreamsLocked() {
2523 if ((mInputStream.get() != nullptr) && (mInputStream->isAbandoned())) {
2524 return true;
2525 }
2526
2527 for (size_t i = 0; i < mOutputStreams.size(); i++) {
2528 auto stream = mOutputStreams[i];
2529 if ((stream.get() != nullptr) && (stream->isAbandoned())) {
2530 return true;
2531 }
2532 }
2533
2534 return false;
2535}
2536
Emilian Peev3bead5f2020-05-28 17:29:08 -07002537bool Camera3Device::reconfigureCamera(const CameraMetadata& sessionParams, int clientStatusId) {
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002538 ATRACE_CALL();
2539 bool ret = false;
2540
Shuzhen Wang316781a2020-08-18 18:11:01 -07002541 nsecs_t startTime = systemTime();
2542
Jayant Chowdhary646c31b2020-01-30 13:09:59 -08002543 Mutex::Autolock il(mInterfaceLock);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002544 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
2545
2546 Mutex::Autolock l(mLock);
Emilian Peev0d0191e2020-04-21 17:01:18 -07002547 if (checkAbandonedStreamsLocked()) {
2548 ALOGW("%s: Abandoned stream detected, session parameters can't be applied correctly!",
2549 __FUNCTION__);
2550 return true;
2551 }
2552
Emilian Peev3bead5f2020-05-28 17:29:08 -07002553 status_t rc = NO_ERROR;
2554 bool markClientActive = false;
2555 if (mStatus == STATUS_ACTIVE) {
2556 markClientActive = true;
2557 mPauseStateNotify = true;
2558 mStatusTracker->markComponentIdle(clientStatusId, Fence::NO_FENCE);
2559
2560 rc = internalPauseAndWaitLocked(maxExpectedDuration);
2561 }
2562
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002563 if (rc == NO_ERROR) {
2564 mNeedConfig = true;
2565 rc = configureStreamsLocked(mOperatingMode, sessionParams, /*notifyRequestThread*/ false);
2566 if (rc == NO_ERROR) {
2567 ret = true;
2568 mPauseStateNotify = false;
2569 //Moving to active state while holding 'mLock' is important.
2570 //There could be pending calls to 'create-/deleteStream' which
2571 //will trigger another stream configuration while the already
2572 //present streams end up with outstanding buffers that will
2573 //not get drained.
2574 internalUpdateStatusLocked(STATUS_ACTIVE);
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002575 } else if (rc == DEAD_OBJECT) {
2576 // DEAD_OBJECT can be returned if either the consumer surface is
2577 // abandoned, or the HAL has died.
2578 // - If the HAL has died, configureStreamsLocked call will set
2579 // device to error state,
2580 // - If surface is abandoned, we should not set device to error
2581 // state.
2582 ALOGE("Failed to re-configure camera due to abandoned surface");
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002583 } else {
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002584 SET_ERR_L("Failed to re-configure camera: %d", rc);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002585 }
2586 } else {
2587 ALOGE("%s: Failed to pause streaming: %d", __FUNCTION__, rc);
2588 }
2589
Shuzhen Wang316781a2020-08-18 18:11:01 -07002590 CameraServiceProxyWrapper::logStreamConfigured(mId, mOperatingMode, true /*internalReconfig*/,
2591 ns2ms(systemTime() - startTime));
2592
Emilian Peev3bead5f2020-05-28 17:29:08 -07002593 if (markClientActive) {
2594 mStatusTracker->markComponentActive(clientStatusId);
2595 }
2596
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002597 return ret;
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002598}
2599
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002600status_t Camera3Device::configureStreamsLocked(int operatingMode,
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002601 const CameraMetadata& sessionParams, bool notifyRequestThread) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002602 ATRACE_CALL();
2603 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002604
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002605 if (mStatus != STATUS_UNCONFIGURED && mStatus != STATUS_CONFIGURED) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002606 CLOGE("Not idle");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002607 return INVALID_OPERATION;
2608 }
2609
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08002610 if (operatingMode < 0) {
2611 CLOGE("Invalid operating mode: %d", operatingMode);
2612 return BAD_VALUE;
2613 }
2614
2615 bool isConstrainedHighSpeed =
2616 static_cast<int>(StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE) ==
2617 operatingMode;
2618
2619 if (mOperatingMode != operatingMode) {
2620 mNeedConfig = true;
2621 mIsConstrainedHighSpeedConfiguration = isConstrainedHighSpeed;
2622 mOperatingMode = operatingMode;
2623 }
2624
Shuzhen Wang0cf01cb2019-09-05 13:33:06 -07002625 // In case called from configureStreams, abort queued input buffers not belonging to
2626 // any pending requests.
2627 if (mInputStream != NULL && notifyRequestThread) {
2628 while (true) {
Emilian Peevf4816702020-04-03 15:44:51 -07002629 camera_stream_buffer_t inputBuffer;
Shuzhen Wang83bff122020-11-20 15:51:39 -08002630 camera3::Size inputBufferSize;
Shuzhen Wang0cf01cb2019-09-05 13:33:06 -07002631 status_t res = mInputStream->getInputBuffer(&inputBuffer,
Shuzhen Wang83bff122020-11-20 15:51:39 -08002632 &inputBufferSize, /*respectHalLimit*/ false);
Shuzhen Wang0cf01cb2019-09-05 13:33:06 -07002633 if (res != OK) {
2634 // Exhausted acquiring all input buffers.
2635 break;
2636 }
2637
Emilian Peevf4816702020-04-03 15:44:51 -07002638 inputBuffer.status = CAMERA_BUFFER_STATUS_ERROR;
Shuzhen Wang0cf01cb2019-09-05 13:33:06 -07002639 res = mInputStream->returnInputBuffer(inputBuffer);
2640 if (res != OK) {
2641 ALOGE("%s: %d: couldn't return input buffer while clearing input queue: "
2642 "%s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
2643 }
2644 }
2645 }
2646
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002647 if (!mNeedConfig) {
2648 ALOGV("%s: Skipping config, no stream changes", __FUNCTION__);
2649 return OK;
2650 }
2651
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002652 // Workaround for device HALv3.2 or older spec bug - zero streams requires
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002653 // adding a fake stream instead.
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002654 // TODO: Bug: 17321404 for fixing the HAL spec and removing this workaround.
2655 if (mOutputStreams.size() == 0) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002656 addFakeStreamLocked();
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002657 } else {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002658 tryRemoveFakeStreamLocked();
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002659 }
2660
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002661 // Start configuring the streams
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002662 ALOGV("%s: Camera %s: Starting stream configuration", __FUNCTION__, mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002663
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002664 mPreparerThread->pause();
2665
Emilian Peevf4816702020-04-03 15:44:51 -07002666 camera_stream_configuration config;
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -08002667 config.operation_mode = mOperatingMode;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002668 config.num_streams = (mInputStream != NULL) + mOutputStreams.size();
Shuzhen Wang83bff122020-11-20 15:51:39 -08002669 config.input_is_multi_resolution = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002670
Emilian Peevf4816702020-04-03 15:44:51 -07002671 Vector<camera3::camera_stream_t*> streams;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002672 streams.setCapacity(config.num_streams);
Emilian Peev192ee832018-01-31 14:46:47 +00002673 std::vector<uint32_t> bufferSizes(config.num_streams, 0);
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002674
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002675
2676 if (mInputStream != NULL) {
Emilian Peevf4816702020-04-03 15:44:51 -07002677 camera3::camera_stream_t *inputStream;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002678 inputStream = mInputStream->startConfiguration();
2679 if (inputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002680 CLOGE("Can't start input stream configuration");
2681 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002682 return INVALID_OPERATION;
2683 }
2684 streams.add(inputStream);
Shuzhen Wang83bff122020-11-20 15:51:39 -08002685
2686 config.input_is_multi_resolution = mIsInputStreamMultiResolution;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002687 }
2688
Shuzhen Wang99080502021-03-07 21:08:20 -08002689 mGroupIdPhysicalCameraMap.clear();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002690 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Igor Murashkin2fba5842013-04-22 14:03:54 -07002691
2692 // Don't configure bidi streams twice, nor add them twice to the list
2693 if (mOutputStreams[i].get() ==
2694 static_cast<Camera3StreamInterface*>(mInputStream.get())) {
2695
2696 config.num_streams--;
2697 continue;
2698 }
2699
Emilian Peevf4816702020-04-03 15:44:51 -07002700 camera3::camera_stream_t *outputStream;
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002701 outputStream = mOutputStreams[i]->startConfiguration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002702 if (outputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002703 CLOGE("Can't start output stream configuration");
2704 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002705 return INVALID_OPERATION;
2706 }
2707 streams.add(outputStream);
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002708
Shuzhen Wangb7ab1e42019-02-20 15:42:23 -08002709 if (outputStream->format == HAL_PIXEL_FORMAT_BLOB) {
Emilian Peev192ee832018-01-31 14:46:47 +00002710 size_t k = i + ((mInputStream != nullptr) ? 1 : 0); // Input stream if present should
2711 // always occupy the initial entry.
Shuzhen Wangb7ab1e42019-02-20 15:42:23 -08002712 if (outputStream->data_space == HAL_DATASPACE_V0_JFIF) {
2713 bufferSizes[k] = static_cast<uint32_t>(
2714 getJpegBufferSize(outputStream->width, outputStream->height));
2715 } else if (outputStream->data_space ==
2716 static_cast<android_dataspace>(HAL_DATASPACE_JPEG_APP_SEGMENTS)) {
2717 bufferSizes[k] = outputStream->width * outputStream->height;
2718 } else {
2719 ALOGW("%s: Blob dataSpace %d not supported",
2720 __FUNCTION__, outputStream->data_space);
2721 }
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002722 }
Shuzhen Wang99080502021-03-07 21:08:20 -08002723
2724 if (mOutputStreams[i]->isMultiResolution()) {
2725 int32_t streamGroupId = mOutputStreams[i]->getHalStreamGroupId();
2726 const String8& physicalCameraId = mOutputStreams[i]->getPhysicalCameraId();
2727 mGroupIdPhysicalCameraMap[streamGroupId].insert(physicalCameraId);
2728 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002729 }
2730
2731 config.streams = streams.editArray();
2732
2733 // Do the HAL configuration; will potentially touch stream
Shuzhen Wang92653952019-05-07 15:11:43 -07002734 // max_buffers, usage, and priv fields, as well as data_space and format
2735 // fields for IMPLEMENTATION_DEFINED formats.
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002736
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002737 const camera_metadata_t *sessionBuffer = sessionParams.getAndLock();
Emilian Peev192ee832018-01-31 14:46:47 +00002738 res = mInterface->configureStreams(sessionBuffer, &config, bufferSizes);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002739 sessionParams.unlock(sessionBuffer);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002740
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002741 if (res == BAD_VALUE) {
2742 // HAL rejected this set of streams as unsupported, clean up config
2743 // attempt and return to unconfigured state
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002744 CLOGE("Set of requested inputs/outputs not supported by HAL");
2745 cancelStreamsConfigurationLocked();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002746 return BAD_VALUE;
2747 } else if (res != OK) {
2748 // Some other kind of error from configure_streams - this is not
2749 // expected
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002750 SET_ERR_L("Unable to configure streams with HAL: %s (%d)",
2751 strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002752 return res;
2753 }
2754
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002755 // Finish all stream configuration immediately.
2756 // TODO: Try to relax this later back to lazy completion, which should be
2757 // faster
2758
Igor Murashkin073f8572013-05-02 14:59:28 -07002759 if (mInputStream != NULL && mInputStream->isConfiguring()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002760 bool streamReConfigured = false;
2761 res = mInputStream->finishConfiguration(&streamReConfigured);
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002762 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002763 CLOGE("Can't finish configuring input stream %d: %s (%d)",
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002764 mInputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002765 cancelStreamsConfigurationLocked();
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002766 if ((res == NO_INIT || res == DEAD_OBJECT) && mInputStream->isAbandoned()) {
2767 return DEAD_OBJECT;
2768 }
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002769 return BAD_VALUE;
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002770 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002771 if (streamReConfigured) {
2772 mInterface->onStreamReConfigured(mInputStream->getId());
2773 }
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002774 }
2775
2776 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002777 sp<Camera3OutputStreamInterface> outputStream = mOutputStreams[i];
Zhijun He5d677d12016-05-29 16:52:39 -07002778 if (outputStream->isConfiguring() && !outputStream->isConsumerConfigurationDeferred()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002779 bool streamReConfigured = false;
2780 res = outputStream->finishConfiguration(&streamReConfigured);
Igor Murashkin073f8572013-05-02 14:59:28 -07002781 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002782 CLOGE("Can't finish configuring output stream %d: %s (%d)",
Igor Murashkin073f8572013-05-02 14:59:28 -07002783 outputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002784 cancelStreamsConfigurationLocked();
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002785 if ((res == NO_INIT || res == DEAD_OBJECT) && outputStream->isAbandoned()) {
2786 return DEAD_OBJECT;
2787 }
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002788 return BAD_VALUE;
Igor Murashkin073f8572013-05-02 14:59:28 -07002789 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002790 if (streamReConfigured) {
2791 mInterface->onStreamReConfigured(outputStream->getId());
2792 }
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002793 }
2794 }
2795
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002796 // Request thread needs to know to avoid using repeat-last-settings protocol
2797 // across configure_streams() calls
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002798 if (notifyRequestThread) {
Shuzhen Wang99080502021-03-07 21:08:20 -08002799 mRequestThread->configurationComplete(mIsConstrainedHighSpeedConfiguration,
2800 sessionParams, mGroupIdPhysicalCameraMap);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002801 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002802
Zhijun He90f7c372016-08-16 16:19:43 -07002803 char value[PROPERTY_VALUE_MAX];
2804 property_get("camera.fifo.disable", value, "0");
2805 int32_t disableFifo = atoi(value);
2806 if (disableFifo != 1) {
2807 // Boost priority of request thread to SCHED_FIFO.
2808 pid_t requestThreadTid = mRequestThread->getTid();
2809 res = requestPriority(getpid(), requestThreadTid,
Mikhail Naganov83f04272017-02-07 10:45:09 -08002810 kRequestThreadPriority, /*isForApp*/ false, /*asynchronous*/ false);
Zhijun He90f7c372016-08-16 16:19:43 -07002811 if (res != OK) {
2812 ALOGW("Can't set realtime priority for request processing thread: %s (%d)",
2813 strerror(-res), res);
2814 } else {
2815 ALOGD("Set real time priority for request queue thread (tid %d)", requestThreadTid);
2816 }
Eino-Ville Talvalaf99498e2015-09-25 16:52:55 -07002817 }
2818
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002819 // Update device state
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002820 const camera_metadata_t *newSessionParams = sessionParams.getAndLock();
2821 const camera_metadata_t *currentSessionParams = mSessionParams.getAndLock();
2822 bool updateSessionParams = (newSessionParams != currentSessionParams) ? true : false;
2823 sessionParams.unlock(newSessionParams);
2824 mSessionParams.unlock(currentSessionParams);
2825 if (updateSessionParams) {
2826 mSessionParams = sessionParams;
2827 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002828
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002829 mNeedConfig = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002830
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002831 internalUpdateStatusLocked((mFakeStreamId == NO_STREAM) ?
Ruben Brunk183f0562015-08-12 12:55:02 -07002832 STATUS_CONFIGURED : STATUS_UNCONFIGURED);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002833
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002834 ALOGV("%s: Camera %s: Stream configuration complete", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002835
Zhijun He0a210512014-07-24 13:45:15 -07002836 // tear down the deleted streams after configure streams.
2837 mDeletedStreams.clear();
2838
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002839 auto rc = mPreparerThread->resume();
2840 if (rc != OK) {
2841 SET_ERR_L("%s: Camera %s: Preparer thread failed to resume!", __FUNCTION__, mId.string());
2842 return rc;
2843 }
2844
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002845 if (mFakeStreamId == NO_STREAM) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07002846 mRequestBufferSM.onStreamsConfigured();
2847 }
2848
Cliff Wuc2ad9c82021-04-21 00:58:58 +08002849 // Since the streams configuration of the injection camera is based on the internal camera, we
2850 // must wait until the internal camera configure streams before calling injectCamera() to
2851 // configure the injection streams.
2852 if (mInjectionMethods->isInjecting()) {
2853 ALOGV("%s: Injection camera %s: Start to configure streams.",
2854 __FUNCTION__, mInjectionMethods->getInjectedCamId().string());
2855 res = mInjectionMethods->injectCamera(config, bufferSizes);
2856 if (res != OK) {
2857 ALOGE("Can't finish inject camera process!");
2858 return res;
2859 }
2860 }
2861
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002862 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002863}
2864
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002865status_t Camera3Device::addFakeStreamLocked() {
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002866 ATRACE_CALL();
2867 status_t res;
2868
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002869 if (mFakeStreamId != NO_STREAM) {
2870 // Should never be adding a second fake stream when one is already
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002871 // active
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002872 SET_ERR_L("%s: Camera %s: A fake stream already exists!",
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002873 __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002874 return INVALID_OPERATION;
2875 }
2876
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002877 ALOGV("%s: Camera %s: Adding a fake stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002878
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002879 sp<Camera3OutputStreamInterface> fakeStream =
2880 new Camera3FakeStream(mNextStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002881
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002882 res = mOutputStreams.add(mNextStreamId, fakeStream);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002883 if (res < 0) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002884 SET_ERR_L("Can't add fake stream to set: %s (%d)", strerror(-res), res);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002885 return res;
2886 }
2887
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002888 mFakeStreamId = mNextStreamId;
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002889 mNextStreamId++;
2890
2891 return OK;
2892}
2893
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002894status_t Camera3Device::tryRemoveFakeStreamLocked() {
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002895 ATRACE_CALL();
2896 status_t res;
2897
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002898 if (mFakeStreamId == NO_STREAM) return OK;
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002899 if (mOutputStreams.size() == 1) return OK;
2900
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002901 ALOGV("%s: Camera %s: Removing the fake stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002902
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002903 // Ok, have a fake stream and there's at least one other output stream,
2904 // so remove the fake
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002905
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002906 sp<Camera3StreamInterface> deletedStream = mOutputStreams.get(mFakeStreamId);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002907 if (deletedStream == nullptr) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002908 SET_ERR_L("Fake stream %d does not appear to exist", mFakeStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002909 return INVALID_OPERATION;
2910 }
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002911 mOutputStreams.remove(mFakeStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002912
2913 // Free up the stream endpoint so that it can be used by some other stream
2914 res = deletedStream->disconnect();
2915 if (res != OK) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002916 SET_ERR_L("Can't disconnect deleted fake stream %d", mFakeStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002917 // fall through since we want to still list the stream as deleted.
2918 }
2919 mDeletedStreams.add(deletedStream);
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002920 mFakeStreamId = NO_STREAM;
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002921
2922 return res;
2923}
2924
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002925void Camera3Device::setErrorState(const char *fmt, ...) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002926 ATRACE_CALL();
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002927 Mutex::Autolock l(mLock);
2928 va_list args;
2929 va_start(args, fmt);
2930
2931 setErrorStateLockedV(fmt, args);
2932
2933 va_end(args);
2934}
2935
2936void Camera3Device::setErrorStateV(const char *fmt, va_list args) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002937 ATRACE_CALL();
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002938 Mutex::Autolock l(mLock);
2939 setErrorStateLockedV(fmt, args);
2940}
2941
2942void Camera3Device::setErrorStateLocked(const char *fmt, ...) {
2943 va_list args;
2944 va_start(args, fmt);
2945
2946 setErrorStateLockedV(fmt, args);
2947
2948 va_end(args);
2949}
2950
2951void Camera3Device::setErrorStateLockedV(const char *fmt, va_list args) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002952 // Print out all error messages to log
2953 String8 errorCause = String8::formatV(fmt, args);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002954 ALOGE("Camera %s: %s", mId.string(), errorCause.string());
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002955
2956 // But only do error state transition steps for the first error
Zhijun Heb05eeae2013-06-06 13:51:22 -07002957 if (mStatus == STATUS_ERROR || mStatus == STATUS_UNINITIALIZED) return;
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002958
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002959 mErrorCause = errorCause;
2960
Yin-Chia Yeh3d145ae2017-07-27 12:47:03 -07002961 if (mRequestThread != nullptr) {
2962 mRequestThread->setPaused(true);
2963 }
Ruben Brunk183f0562015-08-12 12:55:02 -07002964 internalUpdateStatusLocked(STATUS_ERROR);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002965
2966 // Notify upstream about a device error
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002967 sp<NotificationListener> listener = mListener.promote();
2968 if (listener != NULL) {
2969 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002970 CaptureResultExtras());
Shuzhen Wang316781a2020-08-18 18:11:01 -07002971 mSessionStatsBuilder.onDeviceError();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002972 }
2973
2974 // Save stack trace. View by dumping it later.
2975 CameraTraces::saveTrace();
2976 // TODO: consider adding errorCause and client pid/procname
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002977}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002978
2979/**
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002980 * In-flight request management
2981 */
2982
Jianing Weicb0652e2014-03-12 18:29:36 -07002983status_t Camera3Device::registerInFlight(uint32_t frameNumber,
Chien-Yu Chend196d612015-06-22 19:49:01 -07002984 int32_t numBuffers, CaptureResultExtras resultExtras, bool hasInput,
Shuzhen Wang5c22c152017-12-31 17:12:25 -08002985 bool hasAppCallback, nsecs_t maxExpectedDuration,
Shuzhen Wang99080502021-03-07 21:08:20 -08002986 const std::set<std::set<String8>>& physicalCameraIds,
2987 bool isStillCapture, bool isZslCapture, bool rotateAndCropAuto,
2988 const std::set<std::string>& cameraIdsWithZoom,
Shuzhen Wang316781a2020-08-18 18:11:01 -07002989 const SurfaceMap& outputSurfaces, nsecs_t requestTimeNs) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002990 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002991 std::lock_guard<std::mutex> l(mInFlightLock);
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002992
2993 ssize_t res;
Chien-Yu Chend196d612015-06-22 19:49:01 -07002994 res = mInFlightMap.add(frameNumber, InFlightRequest(numBuffers, resultExtras, hasInput,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07002995 hasAppCallback, maxExpectedDuration, physicalCameraIds, isStillCapture, isZslCapture,
Shuzhen Wang316781a2020-08-18 18:11:01 -07002996 rotateAndCropAuto, cameraIdsWithZoom, requestTimeNs, outputSurfaces));
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002997 if (res < 0) return res;
2998
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07002999 if (mInFlightMap.size() == 1) {
Emilian Peev26d975d2018-07-05 14:52:57 +01003000 // Hold a separate dedicated tracker lock to prevent race with disconnect and also
3001 // avoid a deadlock during reprocess requests.
3002 Mutex::Autolock l(mTrackerLock);
Yin-Chia Yeh38dfde52017-06-27 17:13:33 -07003003 if (mStatusTracker != nullptr) {
3004 mStatusTracker->markComponentActive(mInFlightStatusId);
3005 }
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07003006 }
3007
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003008 mExpectedInflightDuration += maxExpectedDuration;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003009 return OK;
3010}
3011
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003012void Camera3Device::onInflightEntryRemovedLocked(nsecs_t duration) {
Shuzhen Wangcadb3302016-11-04 14:17:56 -07003013 // Indicate idle inFlightMap to the status tracker
3014 if (mInFlightMap.size() == 0) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07003015 mRequestBufferSM.onInflightMapEmpty();
Emilian Peev26d975d2018-07-05 14:52:57 +01003016 // Hold a separate dedicated tracker lock to prevent race with disconnect and also
3017 // avoid a deadlock during reprocess requests.
3018 Mutex::Autolock l(mTrackerLock);
Yin-Chia Yeh38dfde52017-06-27 17:13:33 -07003019 if (mStatusTracker != nullptr) {
3020 mStatusTracker->markComponentIdle(mInFlightStatusId, Fence::NO_FENCE);
3021 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07003022 }
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003023 mExpectedInflightDuration -= duration;
Shuzhen Wangcadb3302016-11-04 14:17:56 -07003024}
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003025
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003026void Camera3Device::checkInflightMapLengthLocked() {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04003027 // Validation check - if we have too many in-flight frames with long total inflight duration,
Yin-Chia Yeh99fd0972019-06-27 14:22:44 -07003028 // something has likely gone wrong. This might still be legit only if application send in
3029 // a long burst of long exposure requests.
3030 if (mExpectedInflightDuration > kMinWarnInflightDuration) {
3031 if (!mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() > kInFlightWarnLimit) {
3032 CLOGW("In-flight list too large: %zu, total inflight duration %" PRIu64,
3033 mInFlightMap.size(), mExpectedInflightDuration);
3034 } else if (mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() >
3035 kInFlightWarnLimitHighSpeed) {
3036 CLOGW("In-flight list too large for high speed configuration: %zu,"
3037 "total inflight duration %" PRIu64,
3038 mInFlightMap.size(), mExpectedInflightDuration);
3039 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003040 }
3041}
3042
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003043void Camera3Device::onInflightMapFlushedLocked() {
3044 mExpectedInflightDuration = 0;
3045}
3046
3047void Camera3Device::removeInFlightMapEntryLocked(int idx) {
Jayant Chowdharyd4776262020-06-23 23:45:57 -07003048 ATRACE_HFR_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003049 nsecs_t duration = mInFlightMap.valueAt(idx).maxExpectedDuration;
3050 mInFlightMap.removeItemsAt(idx, 1);
3051
3052 onInflightEntryRemovedLocked(duration);
3053}
3054
3055
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003056void Camera3Device::flushInflightRequests() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003057 ATRACE_CALL();
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003058 sp<NotificationListener> listener;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003059 {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003060 std::lock_guard<std::mutex> l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003061 listener = mListener.promote();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003062 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003063
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003064 FlushInflightReqStates states {
3065 mId, mInFlightLock, mInFlightMap, mUseHalBufManager,
Shuzhen Wang316781a2020-08-18 18:11:01 -07003066 listener, *this, *mInterface, *this, mSessionStatsBuilder};
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003067
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003068 camera3::flushInflightRequests(states);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003069}
3070
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003071CameraMetadata Camera3Device::getLatestRequestLocked() {
Igor Murashkin1e479c02013-09-06 16:55:14 -07003072 ALOGV("%s", __FUNCTION__);
3073
Igor Murashkin1e479c02013-09-06 16:55:14 -07003074 CameraMetadata retVal;
3075
3076 if (mRequestThread != NULL) {
3077 retVal = mRequestThread->getLatestRequest();
3078 }
3079
Igor Murashkin1e479c02013-09-06 16:55:14 -07003080 return retVal;
3081}
3082
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07003083void Camera3Device::monitorMetadata(TagMonitor::eventSource source,
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003084 int64_t frameNumber, nsecs_t timestamp, const CameraMetadata& metadata,
3085 const std::unordered_map<std::string, CameraMetadata>& physicalMetadata) {
3086
3087 mTagMonitor.monitorMetadata(source, frameNumber, timestamp, metadata,
3088 physicalMetadata);
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07003089}
3090
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003091/**
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003092 * HalInterface inner class methods
3093 */
3094
Yifan Hongf79b5542017-04-11 14:44:25 -07003095Camera3Device::HalInterface::HalInterface(
3096 sp<ICameraDeviceSession> &session,
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003097 std::shared_ptr<RequestMetadataQueue> queue,
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003098 bool useHalBufManager, bool supportOfflineProcessing) :
Yifan Hongf79b5542017-04-11 14:44:25 -07003099 mHidlSession(session),
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003100 mRequestMetadataQueue(queue),
Emilian Peev4ec17882019-01-24 17:16:58 -08003101 mUseHalBufManager(useHalBufManager),
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003102 mIsReconfigurationQuerySupported(true),
3103 mSupportOfflineProcessing(supportOfflineProcessing) {
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003104 // Check with hardware service manager if we can downcast these interfaces
3105 // Somewhat expensive, so cache the results at startup
Shuzhen Wang83bff122020-11-20 15:51:39 -08003106 auto castResult_3_7 = device::V3_7::ICameraDeviceSession::castFrom(mHidlSession);
3107 if (castResult_3_7.isOk()) {
3108 mHidlSession_3_7 = castResult_3_7;
3109 }
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003110 auto castResult_3_6 = device::V3_6::ICameraDeviceSession::castFrom(mHidlSession);
3111 if (castResult_3_6.isOk()) {
3112 mHidlSession_3_6 = castResult_3_6;
3113 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003114 auto castResult_3_5 = device::V3_5::ICameraDeviceSession::castFrom(mHidlSession);
3115 if (castResult_3_5.isOk()) {
3116 mHidlSession_3_5 = castResult_3_5;
3117 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003118 auto castResult_3_4 = device::V3_4::ICameraDeviceSession::castFrom(mHidlSession);
3119 if (castResult_3_4.isOk()) {
3120 mHidlSession_3_4 = castResult_3_4;
3121 }
3122 auto castResult_3_3 = device::V3_3::ICameraDeviceSession::castFrom(mHidlSession);
3123 if (castResult_3_3.isOk()) {
3124 mHidlSession_3_3 = castResult_3_3;
3125 }
3126}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003127
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003128Camera3Device::HalInterface::HalInterface() :
3129 mUseHalBufManager(false),
3130 mSupportOfflineProcessing(false) {}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003131
3132Camera3Device::HalInterface::HalInterface(const HalInterface& other) :
Yifan Hongf79b5542017-04-11 14:44:25 -07003133 mHidlSession(other.mHidlSession),
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003134 mRequestMetadataQueue(other.mRequestMetadataQueue),
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003135 mUseHalBufManager(other.mUseHalBufManager),
3136 mSupportOfflineProcessing(other.mSupportOfflineProcessing) {}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003137
3138bool Camera3Device::HalInterface::valid() {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003139 return (mHidlSession != nullptr);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003140}
3141
3142void Camera3Device::HalInterface::clear() {
Shuzhen Wang83bff122020-11-20 15:51:39 -08003143 mHidlSession_3_7.clear();
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003144 mHidlSession_3_6.clear();
Emilian Peev644a3e12018-11-23 13:52:39 +00003145 mHidlSession_3_5.clear();
Emilian Peev9e740b02018-01-30 18:28:03 +00003146 mHidlSession_3_4.clear();
3147 mHidlSession_3_3.clear();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003148 mHidlSession.clear();
3149}
3150
3151status_t Camera3Device::HalInterface::constructDefaultRequestSettings(
Emilian Peevf4816702020-04-03 15:44:51 -07003152 camera_request_template_t templateId,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003153 /*out*/ camera_metadata_t **requestTemplate) {
3154 ATRACE_NAME("CameraHal::constructDefaultRequestSettings");
3155 if (!valid()) return INVALID_OPERATION;
3156 status_t res = OK;
3157
Emilian Peev31abd0a2017-05-11 18:37:46 +01003158 common::V1_0::Status status;
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003159
3160 auto requestCallback = [&status, &requestTemplate]
Emilian Peev31abd0a2017-05-11 18:37:46 +01003161 (common::V1_0::Status s, const device::V3_2::CameraMetadata& request) {
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003162 status = s;
3163 if (status == common::V1_0::Status::OK) {
3164 const camera_metadata *r =
3165 reinterpret_cast<const camera_metadata_t*>(request.data());
3166 size_t expectedSize = request.size();
3167 int ret = validate_camera_metadata_structure(r, &expectedSize);
3168 if (ret == OK || ret == CAMERA_METADATA_VALIDATION_SHIFTED) {
3169 *requestTemplate = clone_camera_metadata(r);
3170 if (*requestTemplate == nullptr) {
3171 ALOGE("%s: Unable to clone camera metadata received from HAL",
3172 __FUNCTION__);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003173 status = common::V1_0::Status::INTERNAL_ERROR;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003174 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003175 } else {
3176 ALOGE("%s: Malformed camera metadata received from HAL", __FUNCTION__);
3177 status = common::V1_0::Status::INTERNAL_ERROR;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003178 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003179 }
3180 };
3181 hardware::Return<void> err;
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003182 RequestTemplate id;
3183 switch (templateId) {
Emilian Peevf4816702020-04-03 15:44:51 -07003184 case CAMERA_TEMPLATE_PREVIEW:
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003185 id = RequestTemplate::PREVIEW;
3186 break;
Emilian Peevf4816702020-04-03 15:44:51 -07003187 case CAMERA_TEMPLATE_STILL_CAPTURE:
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003188 id = RequestTemplate::STILL_CAPTURE;
3189 break;
Emilian Peevf4816702020-04-03 15:44:51 -07003190 case CAMERA_TEMPLATE_VIDEO_RECORD:
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003191 id = RequestTemplate::VIDEO_RECORD;
3192 break;
Emilian Peevf4816702020-04-03 15:44:51 -07003193 case CAMERA_TEMPLATE_VIDEO_SNAPSHOT:
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003194 id = RequestTemplate::VIDEO_SNAPSHOT;
3195 break;
Emilian Peevf4816702020-04-03 15:44:51 -07003196 case CAMERA_TEMPLATE_ZERO_SHUTTER_LAG:
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003197 id = RequestTemplate::ZERO_SHUTTER_LAG;
3198 break;
Emilian Peevf4816702020-04-03 15:44:51 -07003199 case CAMERA_TEMPLATE_MANUAL:
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003200 id = RequestTemplate::MANUAL;
3201 break;
3202 default:
3203 // Unknown template ID, or this HAL is too old to support it
3204 return BAD_VALUE;
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003205 }
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003206 err = mHidlSession->constructDefaultRequestSettings(id, requestCallback);
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003207
Emilian Peev31abd0a2017-05-11 18:37:46 +01003208 if (!err.isOk()) {
3209 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3210 res = DEAD_OBJECT;
3211 } else {
3212 res = CameraProviderManager::mapToStatusT(status);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003213 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003214
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003215 return res;
3216}
3217
Emilian Peev4ec17882019-01-24 17:16:58 -08003218bool Camera3Device::HalInterface::isReconfigurationRequired(CameraMetadata& oldSessionParams,
3219 CameraMetadata& newSessionParams) {
3220 // We do reconfiguration by default;
3221 bool ret = true;
3222 if ((mHidlSession_3_5 != nullptr) && mIsReconfigurationQuerySupported) {
3223 android::hardware::hidl_vec<uint8_t> oldParams, newParams;
3224 camera_metadata_t* oldSessioMeta = const_cast<camera_metadata_t*>(
3225 oldSessionParams.getAndLock());
3226 camera_metadata_t* newSessioMeta = const_cast<camera_metadata_t*>(
3227 newSessionParams.getAndLock());
3228 oldParams.setToExternal(reinterpret_cast<uint8_t*>(oldSessioMeta),
3229 get_camera_metadata_size(oldSessioMeta));
3230 newParams.setToExternal(reinterpret_cast<uint8_t*>(newSessioMeta),
3231 get_camera_metadata_size(newSessioMeta));
3232 hardware::camera::common::V1_0::Status callStatus;
3233 bool required;
3234 auto hidlCb = [&callStatus, &required] (hardware::camera::common::V1_0::Status s,
3235 bool requiredFlag) {
3236 callStatus = s;
3237 required = requiredFlag;
3238 };
3239 auto err = mHidlSession_3_5->isReconfigurationRequired(oldParams, newParams, hidlCb);
3240 oldSessionParams.unlock(oldSessioMeta);
3241 newSessionParams.unlock(newSessioMeta);
3242 if (err.isOk()) {
3243 switch (callStatus) {
3244 case hardware::camera::common::V1_0::Status::OK:
3245 ret = required;
3246 break;
3247 case hardware::camera::common::V1_0::Status::METHOD_NOT_SUPPORTED:
3248 mIsReconfigurationQuerySupported = false;
3249 ret = true;
3250 break;
3251 default:
3252 ALOGV("%s: Reconfiguration query failed: %d", __FUNCTION__, callStatus);
3253 ret = true;
3254 }
3255 } else {
3256 ALOGE("%s: Unexpected binder error: %s", __FUNCTION__, err.description().c_str());
3257 ret = true;
3258 }
3259 }
3260
3261 return ret;
3262}
3263
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003264status_t Camera3Device::HalInterface::configureStreams(const camera_metadata_t *sessionParams,
Emilian Peevf4816702020-04-03 15:44:51 -07003265 camera_stream_configuration *config, const std::vector<uint32_t>& bufferSizes) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003266 ATRACE_NAME("CameraHal::configureStreams");
3267 if (!valid()) return INVALID_OPERATION;
3268 status_t res = OK;
3269
Shuzhen Wang83bff122020-11-20 15:51:39 -08003270 if (config->input_is_multi_resolution && mHidlSession_3_7 == nullptr) {
3271 ALOGE("%s: Camera device doesn't support multi-resolution input stream", __FUNCTION__);
3272 return BAD_VALUE;
3273 }
3274
Emilian Peev31abd0a2017-05-11 18:37:46 +01003275 // Convert stream config to HIDL
3276 std::set<int> activeStreams;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003277 device::V3_2::StreamConfiguration requestedConfiguration3_2;
3278 device::V3_4::StreamConfiguration requestedConfiguration3_4;
Shuzhen Wang83bff122020-11-20 15:51:39 -08003279 device::V3_7::StreamConfiguration requestedConfiguration3_7;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003280 requestedConfiguration3_2.streams.resize(config->num_streams);
3281 requestedConfiguration3_4.streams.resize(config->num_streams);
Shuzhen Wang83bff122020-11-20 15:51:39 -08003282 requestedConfiguration3_7.streams.resize(config->num_streams);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003283 for (size_t i = 0; i < config->num_streams; i++) {
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003284 device::V3_2::Stream &dst3_2 = requestedConfiguration3_2.streams[i];
3285 device::V3_4::Stream &dst3_4 = requestedConfiguration3_4.streams[i];
Shuzhen Wang83bff122020-11-20 15:51:39 -08003286 device::V3_7::Stream &dst3_7 = requestedConfiguration3_7.streams[i];
Emilian Peevf4816702020-04-03 15:44:51 -07003287 camera3::camera_stream_t *src = config->streams[i];
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003288
Emilian Peev31abd0a2017-05-11 18:37:46 +01003289 Camera3Stream* cam3stream = Camera3Stream::cast(src);
3290 cam3stream->setBufferFreedListener(this);
3291 int streamId = cam3stream->getId();
3292 StreamType streamType;
3293 switch (src->stream_type) {
Emilian Peevf4816702020-04-03 15:44:51 -07003294 case CAMERA_STREAM_OUTPUT:
Emilian Peev31abd0a2017-05-11 18:37:46 +01003295 streamType = StreamType::OUTPUT;
3296 break;
Emilian Peevf4816702020-04-03 15:44:51 -07003297 case CAMERA_STREAM_INPUT:
Emilian Peev31abd0a2017-05-11 18:37:46 +01003298 streamType = StreamType::INPUT;
3299 break;
3300 default:
3301 ALOGE("%s: Stream %d: Unsupported stream type %d",
3302 __FUNCTION__, streamId, config->streams[i]->stream_type);
3303 return BAD_VALUE;
3304 }
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003305 dst3_2.id = streamId;
3306 dst3_2.streamType = streamType;
3307 dst3_2.width = src->width;
3308 dst3_2.height = src->height;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003309 dst3_2.usage = mapToConsumerUsage(cam3stream->getUsage());
Emilian Peevf4816702020-04-03 15:44:51 -07003310 dst3_2.rotation = mapToStreamRotation((camera_stream_rotation_t) src->rotation);
Shuzhen Wang92653952019-05-07 15:11:43 -07003311 // For HidlSession version 3.5 or newer, the format and dataSpace sent
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08003312 // to HAL are original, not the overridden ones.
Shuzhen Wang92653952019-05-07 15:11:43 -07003313 if (mHidlSession_3_5 != nullptr) {
3314 dst3_2.format = mapToPixelFormat(cam3stream->isFormatOverridden() ?
3315 cam3stream->getOriginalFormat() : src->format);
3316 dst3_2.dataSpace = mapToHidlDataspace(cam3stream->isDataSpaceOverridden() ?
3317 cam3stream->getOriginalDataSpace() : src->data_space);
3318 } else {
3319 dst3_2.format = mapToPixelFormat(src->format);
3320 dst3_2.dataSpace = mapToHidlDataspace(src->data_space);
3321 }
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003322 dst3_4.v3_2 = dst3_2;
Emilian Peev192ee832018-01-31 14:46:47 +00003323 dst3_4.bufferSize = bufferSizes[i];
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003324 if (src->physical_camera_id != nullptr) {
3325 dst3_4.physicalCameraId = src->physical_camera_id;
3326 }
Shuzhen Wang83bff122020-11-20 15:51:39 -08003327 dst3_7.v3_4 = dst3_4;
3328 dst3_7.groupId = cam3stream->getHalStreamGroupId();
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08003329 dst3_7.sensorPixelModesUsed.resize(src->sensor_pixel_modes_used.size());
3330 size_t j = 0;
3331 for (int mode : src->sensor_pixel_modes_used) {
3332 dst3_7.sensorPixelModesUsed[j++] =
3333 static_cast<CameraMetadataEnumAndroidSensorPixelMode>(mode);
3334 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003335 activeStreams.insert(streamId);
3336 // Create Buffer ID map if necessary
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003337 mBufferRecords.tryCreateBufferCache(streamId);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003338 }
3339 // remove BufferIdMap for deleted streams
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003340 mBufferRecords.removeInactiveBufferCaches(activeStreams);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003341
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003342 StreamConfigurationMode operationMode;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003343 res = mapToStreamConfigurationMode(
Emilian Peevf4816702020-04-03 15:44:51 -07003344 (camera_stream_configuration_mode_t) config->operation_mode,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003345 /*out*/ &operationMode);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003346 if (res != OK) {
3347 return res;
3348 }
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003349 requestedConfiguration3_2.operationMode = operationMode;
3350 requestedConfiguration3_4.operationMode = operationMode;
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08003351 requestedConfiguration3_7.operationMode = operationMode;
3352 size_t sessionParamSize = get_camera_metadata_size(sessionParams);
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003353 requestedConfiguration3_4.sessionParams.setToExternal(
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003354 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(sessionParams)),
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08003355 sessionParamSize);
Shuzhen Wang83bff122020-11-20 15:51:39 -08003356 requestedConfiguration3_7.operationMode = operationMode;
3357 requestedConfiguration3_7.sessionParams.setToExternal(
3358 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(sessionParams)),
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08003359 sessionParamSize);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003360
Emilian Peev31abd0a2017-05-11 18:37:46 +01003361 // Invoke configureStreams
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003362 device::V3_3::HalStreamConfiguration finalConfiguration;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003363 device::V3_4::HalStreamConfiguration finalConfiguration3_4;
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003364 device::V3_6::HalStreamConfiguration finalConfiguration3_6;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003365 common::V1_0::Status status;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003366
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003367 auto configStream34Cb = [&status, &finalConfiguration3_4]
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003368 (common::V1_0::Status s, const device::V3_4::HalStreamConfiguration& halConfiguration) {
3369 finalConfiguration3_4 = halConfiguration;
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003370 status = s;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003371 };
3372
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003373 auto configStream36Cb = [&status, &finalConfiguration3_6]
3374 (common::V1_0::Status s, const device::V3_6::HalStreamConfiguration& halConfiguration) {
3375 finalConfiguration3_6 = halConfiguration;
3376 status = s;
3377 };
3378
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003379 auto postprocConfigStream34 = [&finalConfiguration, &finalConfiguration3_4]
3380 (hardware::Return<void>& err) -> status_t {
3381 if (!err.isOk()) {
3382 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3383 return DEAD_OBJECT;
3384 }
3385 finalConfiguration.streams.resize(finalConfiguration3_4.streams.size());
3386 for (size_t i = 0; i < finalConfiguration3_4.streams.size(); i++) {
3387 finalConfiguration.streams[i] = finalConfiguration3_4.streams[i].v3_3;
3388 }
3389 return OK;
3390 };
3391
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003392 auto postprocConfigStream36 = [&finalConfiguration, &finalConfiguration3_6]
3393 (hardware::Return<void>& err) -> status_t {
3394 if (!err.isOk()) {
3395 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3396 return DEAD_OBJECT;
3397 }
3398 finalConfiguration.streams.resize(finalConfiguration3_6.streams.size());
3399 for (size_t i = 0; i < finalConfiguration3_6.streams.size(); i++) {
3400 finalConfiguration.streams[i] = finalConfiguration3_6.streams[i].v3_4.v3_3;
3401 }
3402 return OK;
3403 };
3404
Shuzhen Wang92653952019-05-07 15:11:43 -07003405 // See which version of HAL we have
Shuzhen Wang83bff122020-11-20 15:51:39 -08003406 if (mHidlSession_3_7 != nullptr) {
3407 ALOGV("%s: v3.7 device found", __FUNCTION__);
3408 requestedConfiguration3_7.streamConfigCounter = mNextStreamConfigCounter++;
3409 requestedConfiguration3_7.multiResolutionInputImage = config->input_is_multi_resolution;
3410 auto err = mHidlSession_3_7->configureStreams_3_7(
3411 requestedConfiguration3_7, configStream36Cb);
3412 res = postprocConfigStream36(err);
3413 if (res != OK) {
3414 return res;
3415 }
3416 } else if (mHidlSession_3_6 != nullptr) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003417 ALOGV("%s: v3.6 device found", __FUNCTION__);
3418 device::V3_5::StreamConfiguration requestedConfiguration3_5;
3419 requestedConfiguration3_5.v3_4 = requestedConfiguration3_4;
3420 requestedConfiguration3_5.streamConfigCounter = mNextStreamConfigCounter++;
3421 auto err = mHidlSession_3_6->configureStreams_3_6(
3422 requestedConfiguration3_5, configStream36Cb);
3423 res = postprocConfigStream36(err);
3424 if (res != OK) {
3425 return res;
3426 }
3427 } else if (mHidlSession_3_5 != nullptr) {
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003428 ALOGV("%s: v3.5 device found", __FUNCTION__);
3429 device::V3_5::StreamConfiguration requestedConfiguration3_5;
3430 requestedConfiguration3_5.v3_4 = requestedConfiguration3_4;
3431 requestedConfiguration3_5.streamConfigCounter = mNextStreamConfigCounter++;
3432 auto err = mHidlSession_3_5->configureStreams_3_5(
3433 requestedConfiguration3_5, configStream34Cb);
3434 res = postprocConfigStream34(err);
3435 if (res != OK) {
3436 return res;
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003437 }
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003438 } else if (mHidlSession_3_4 != nullptr) {
3439 // We do; use v3.4 for the call
3440 ALOGV("%s: v3.4 device found", __FUNCTION__);
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003441 auto err = mHidlSession_3_4->configureStreams_3_4(
3442 requestedConfiguration3_4, configStream34Cb);
3443 res = postprocConfigStream34(err);
3444 if (res != OK) {
3445 return res;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003446 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003447 } else if (mHidlSession_3_3 != nullptr) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003448 // We do; use v3.3 for the call
3449 ALOGV("%s: v3.3 device found", __FUNCTION__);
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003450 auto err = mHidlSession_3_3->configureStreams_3_3(requestedConfiguration3_2,
Emilian Peev31abd0a2017-05-11 18:37:46 +01003451 [&status, &finalConfiguration]
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003452 (common::V1_0::Status s, const device::V3_3::HalStreamConfiguration& halConfiguration) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003453 finalConfiguration = halConfiguration;
3454 status = s;
3455 });
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003456 if (!err.isOk()) {
3457 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3458 return DEAD_OBJECT;
3459 }
3460 } else {
3461 // We don't; use v3.2 call and construct a v3.3 HalStreamConfiguration
3462 ALOGV("%s: v3.2 device found", __FUNCTION__);
3463 HalStreamConfiguration finalConfiguration_3_2;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003464 auto err = mHidlSession->configureStreams(requestedConfiguration3_2,
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003465 [&status, &finalConfiguration_3_2]
3466 (common::V1_0::Status s, const HalStreamConfiguration& halConfiguration) {
3467 finalConfiguration_3_2 = halConfiguration;
3468 status = s;
3469 });
3470 if (!err.isOk()) {
3471 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3472 return DEAD_OBJECT;
3473 }
3474 finalConfiguration.streams.resize(finalConfiguration_3_2.streams.size());
3475 for (size_t i = 0; i < finalConfiguration_3_2.streams.size(); i++) {
3476 finalConfiguration.streams[i].v3_2 = finalConfiguration_3_2.streams[i];
3477 finalConfiguration.streams[i].overrideDataSpace =
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003478 requestedConfiguration3_2.streams[i].dataSpace;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003479 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003480 }
3481
3482 if (status != common::V1_0::Status::OK ) {
3483 return CameraProviderManager::mapToStatusT(status);
3484 }
3485
3486 // And convert output stream configuration from HIDL
3487
3488 for (size_t i = 0; i < config->num_streams; i++) {
Emilian Peevf4816702020-04-03 15:44:51 -07003489 camera3::camera_stream_t *dst = config->streams[i];
Emilian Peev31abd0a2017-05-11 18:37:46 +01003490 int streamId = Camera3Stream::cast(dst)->getId();
3491
3492 // Start scan at i, with the assumption that the stream order matches
3493 size_t realIdx = i;
3494 bool found = false;
Eino-Ville Talvala370875f2019-04-12 12:40:27 -07003495 size_t halStreamCount = finalConfiguration.streams.size();
3496 for (size_t idx = 0; idx < halStreamCount; idx++) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003497 if (finalConfiguration.streams[realIdx].v3_2.id == streamId) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003498 found = true;
3499 break;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003500 }
Eino-Ville Talvala370875f2019-04-12 12:40:27 -07003501 realIdx = (realIdx >= halStreamCount - 1) ? 0 : realIdx + 1;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003502 }
3503 if (!found) {
3504 ALOGE("%s: Stream %d not found in stream configuration response from HAL",
3505 __FUNCTION__, streamId);
3506 return INVALID_OPERATION;
3507 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003508 device::V3_3::HalStream &src = finalConfiguration.streams[realIdx];
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003509 device::V3_6::HalStream &src_36 = finalConfiguration3_6.streams[realIdx];
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003510
Emilian Peev710c1422017-08-30 11:19:38 +01003511 Camera3Stream* dstStream = Camera3Stream::cast(dst);
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003512 int overrideFormat = mapToFrameworkFormat(src.v3_2.overrideFormat);
3513 android_dataspace overrideDataSpace = mapToFrameworkDataspace(src.overrideDataSpace);
3514
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003515 if (mHidlSession_3_6 != nullptr) {
3516 dstStream->setOfflineProcessingSupport(src_36.supportOffline);
3517 }
3518
Yin-Chia Yeh90667662019-07-01 15:45:00 -07003519 if (dstStream->getOriginalFormat() != HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
Shuzhen Wang92653952019-05-07 15:11:43 -07003520 dstStream->setFormatOverride(false);
3521 dstStream->setDataSpaceOverride(false);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003522 if (dst->format != overrideFormat) {
3523 ALOGE("%s: Stream %d: Format override not allowed for format 0x%x", __FUNCTION__,
3524 streamId, dst->format);
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003525 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003526 if (dst->data_space != overrideDataSpace) {
3527 ALOGE("%s: Stream %d: DataSpace override not allowed for format 0x%x", __FUNCTION__,
3528 streamId, dst->format);
3529 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003530 } else {
Shuzhen Wang92653952019-05-07 15:11:43 -07003531 bool needFormatOverride =
3532 requestedConfiguration3_2.streams[i].format != src.v3_2.overrideFormat;
3533 bool needDataspaceOverride =
3534 requestedConfiguration3_2.streams[i].dataSpace != src.overrideDataSpace;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003535 // Override allowed with IMPLEMENTATION_DEFINED
Shuzhen Wang92653952019-05-07 15:11:43 -07003536 dstStream->setFormatOverride(needFormatOverride);
3537 dstStream->setDataSpaceOverride(needDataspaceOverride);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003538 dst->format = overrideFormat;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003539 dst->data_space = overrideDataSpace;
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003540 }
3541
Emilian Peevf4816702020-04-03 15:44:51 -07003542 if (dst->stream_type == CAMERA_STREAM_INPUT) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003543 if (src.v3_2.producerUsage != 0) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003544 ALOGE("%s: Stream %d: INPUT streams must have 0 for producer usage",
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003545 __FUNCTION__, streamId);
3546 return INVALID_OPERATION;
3547 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003548 dstStream->setUsage(
3549 mapConsumerToFrameworkUsage(src.v3_2.consumerUsage));
Emilian Peev31abd0a2017-05-11 18:37:46 +01003550 } else {
3551 // OUTPUT
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003552 if (src.v3_2.consumerUsage != 0) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003553 ALOGE("%s: Stream %d: OUTPUT streams must have 0 for consumer usage",
3554 __FUNCTION__, streamId);
3555 return INVALID_OPERATION;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003556 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003557 dstStream->setUsage(
3558 mapProducerToFrameworkUsage(src.v3_2.producerUsage));
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003559 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003560 dst->max_buffers = src.v3_2.maxBuffers;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003561 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003562
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003563 return res;
3564}
3565
Cliff Wuc2ad9c82021-04-21 00:58:58 +08003566status_t Camera3Device::HalInterface::configureInjectedStreams(
3567 const camera_metadata_t* sessionParams, camera_stream_configuration* config,
3568 const std::vector<uint32_t>& bufferSizes,
3569 const CameraMetadata& cameraCharacteristics) {
3570 ATRACE_NAME("InjectionCameraHal::configureStreams");
3571 if (!valid()) return INVALID_OPERATION;
3572 status_t res = OK;
3573
3574 if (config->input_is_multi_resolution) {
3575 ALOGE("%s: Injection camera device doesn't support multi-resolution input "
3576 "stream", __FUNCTION__);
3577 return BAD_VALUE;
3578 }
3579
3580 // Convert stream config to HIDL
3581 std::set<int> activeStreams;
3582 device::V3_2::StreamConfiguration requestedConfiguration3_2;
3583 device::V3_4::StreamConfiguration requestedConfiguration3_4;
3584 device::V3_7::StreamConfiguration requestedConfiguration3_7;
3585 requestedConfiguration3_2.streams.resize(config->num_streams);
3586 requestedConfiguration3_4.streams.resize(config->num_streams);
3587 requestedConfiguration3_7.streams.resize(config->num_streams);
3588 for (size_t i = 0; i < config->num_streams; i++) {
3589 device::V3_2::Stream& dst3_2 = requestedConfiguration3_2.streams[i];
3590 device::V3_4::Stream& dst3_4 = requestedConfiguration3_4.streams[i];
3591 device::V3_7::Stream& dst3_7 = requestedConfiguration3_7.streams[i];
3592 camera3::camera_stream_t* src = config->streams[i];
3593
3594 Camera3Stream* cam3stream = Camera3Stream::cast(src);
3595 cam3stream->setBufferFreedListener(this);
3596 int streamId = cam3stream->getId();
3597 StreamType streamType;
3598 switch (src->stream_type) {
3599 case CAMERA_STREAM_OUTPUT:
3600 streamType = StreamType::OUTPUT;
3601 break;
3602 case CAMERA_STREAM_INPUT:
3603 streamType = StreamType::INPUT;
3604 break;
3605 default:
3606 ALOGE("%s: Stream %d: Unsupported stream type %d", __FUNCTION__,
3607 streamId, config->streams[i]->stream_type);
3608 return BAD_VALUE;
3609 }
3610 dst3_2.id = streamId;
3611 dst3_2.streamType = streamType;
3612 dst3_2.width = src->width;
3613 dst3_2.height = src->height;
3614 dst3_2.usage = mapToConsumerUsage(cam3stream->getUsage());
3615 dst3_2.rotation =
3616 mapToStreamRotation((camera_stream_rotation_t)src->rotation);
3617 // For HidlSession version 3.5 or newer, the format and dataSpace sent
3618 // to HAL are original, not the overridden ones.
3619 if (mHidlSession_3_5 != nullptr) {
3620 dst3_2.format = mapToPixelFormat(cam3stream->isFormatOverridden()
3621 ? cam3stream->getOriginalFormat()
3622 : src->format);
3623 dst3_2.dataSpace =
3624 mapToHidlDataspace(cam3stream->isDataSpaceOverridden()
3625 ? cam3stream->getOriginalDataSpace()
3626 : src->data_space);
3627 } else {
3628 dst3_2.format = mapToPixelFormat(src->format);
3629 dst3_2.dataSpace = mapToHidlDataspace(src->data_space);
3630 }
3631 dst3_4.v3_2 = dst3_2;
3632 dst3_4.bufferSize = bufferSizes[i];
3633 if (src->physical_camera_id != nullptr) {
3634 dst3_4.physicalCameraId = src->physical_camera_id;
3635 }
3636 dst3_7.v3_4 = dst3_4;
3637 dst3_7.groupId = cam3stream->getHalStreamGroupId();
3638 dst3_7.sensorPixelModesUsed.resize(src->sensor_pixel_modes_used.size());
3639 size_t j = 0;
3640 for (int mode : src->sensor_pixel_modes_used) {
3641 dst3_7.sensorPixelModesUsed[j++] =
3642 static_cast<CameraMetadataEnumAndroidSensorPixelMode>(mode);
3643 }
3644 activeStreams.insert(streamId);
3645 // Create Buffer ID map if necessary
3646 mBufferRecords.tryCreateBufferCache(streamId);
3647 }
3648 // remove BufferIdMap for deleted streams
3649 mBufferRecords.removeInactiveBufferCaches(activeStreams);
3650
3651 StreamConfigurationMode operationMode;
3652 res = mapToStreamConfigurationMode(
3653 (camera_stream_configuration_mode_t)config->operation_mode,
3654 /*out*/ &operationMode);
3655 if (res != OK) {
3656 return res;
3657 }
3658 requestedConfiguration3_7.operationMode = operationMode;
3659 size_t sessionParamSize = get_camera_metadata_size(sessionParams);
3660 requestedConfiguration3_7.operationMode = operationMode;
3661 requestedConfiguration3_7.sessionParams.setToExternal(
3662 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(sessionParams)),
3663 sessionParamSize);
3664
3665 // See which version of HAL we have
3666 if (mHidlSession_3_7 != nullptr) {
3667 requestedConfiguration3_7.streamConfigCounter = mNextStreamConfigCounter++;
3668 requestedConfiguration3_7.multiResolutionInputImage =
3669 config->input_is_multi_resolution;
3670
3671 const camera_metadata_t* rawMetadata = cameraCharacteristics.getAndLock();
3672 ::android::hardware::camera::device::V3_2::CameraMetadata hidlChars = {};
3673 hidlChars.setToExternal(
3674 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(rawMetadata)),
3675 get_camera_metadata_size(rawMetadata));
3676 cameraCharacteristics.unlock(rawMetadata);
3677
3678 sp<hardware::camera::device::V3_7::ICameraInjectionSession>
3679 hidlInjectionSession_3_7;
3680 auto castInjectionResult_3_7 =
3681 device::V3_7::ICameraInjectionSession::castFrom(mHidlSession_3_7);
3682 if (castInjectionResult_3_7.isOk()) {
3683 hidlInjectionSession_3_7 = castInjectionResult_3_7;
3684 } else {
3685 ALOGE("%s: Transaction error: %s", __FUNCTION__,
3686 castInjectionResult_3_7.description().c_str());
3687 return DEAD_OBJECT;
3688 }
3689
3690 auto err = hidlInjectionSession_3_7->configureInjectionStreams(
3691 requestedConfiguration3_7, hidlChars);
3692 if (!err.isOk()) {
3693 ALOGE("%s: Transaction error: %s", __FUNCTION__,
3694 err.description().c_str());
3695 return DEAD_OBJECT;
3696 }
3697 } else {
3698 ALOGE("%s: mHidlSession_3_7 does not exist, the lowest version of injection "
3699 "session is 3.7", __FUNCTION__);
3700 return DEAD_OBJECT;
3701 }
3702
3703 return res;
3704}
3705
Emilian Peevf4816702020-04-03 15:44:51 -07003706status_t Camera3Device::HalInterface::wrapAsHidlRequest(camera_capture_request_t* request,
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003707 /*out*/device::V3_2::CaptureRequest* captureRequest,
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003708 /*out*/std::vector<native_handle_t*>* handlesCreated,
3709 /*out*/std::vector<std::pair<int32_t, int32_t>>* inflightBuffers) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003710 ATRACE_CALL();
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003711 if (captureRequest == nullptr || handlesCreated == nullptr || inflightBuffers == nullptr) {
3712 ALOGE("%s: captureRequest (%p), handlesCreated (%p), and inflightBuffers(%p) "
3713 "must not be null", __FUNCTION__, captureRequest, handlesCreated, inflightBuffers);
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003714 return BAD_VALUE;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003715 }
3716
3717 captureRequest->frameNumber = request->frame_number;
Yifan Hongf79b5542017-04-11 14:44:25 -07003718
3719 captureRequest->fmqSettingsSize = 0;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003720
3721 {
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003722 if (request->input_buffer != nullptr) {
3723 int32_t streamId = Camera3Stream::cast(request->input_buffer->stream)->getId();
3724 buffer_handle_t buf = *(request->input_buffer->buffer);
3725 auto pair = getBufferId(buf, streamId);
3726 bool isNewBuffer = pair.first;
3727 uint64_t bufferId = pair.second;
3728 captureRequest->inputBuffer.streamId = streamId;
3729 captureRequest->inputBuffer.bufferId = bufferId;
3730 captureRequest->inputBuffer.buffer = (isNewBuffer) ? buf : nullptr;
3731 captureRequest->inputBuffer.status = BufferStatus::OK;
3732 native_handle_t *acquireFence = nullptr;
3733 if (request->input_buffer->acquire_fence != -1) {
3734 acquireFence = native_handle_create(1,0);
3735 acquireFence->data[0] = request->input_buffer->acquire_fence;
3736 handlesCreated->push_back(acquireFence);
3737 }
3738 captureRequest->inputBuffer.acquireFence = acquireFence;
3739 captureRequest->inputBuffer.releaseFence = nullptr;
3740
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003741 mBufferRecords.pushInflightBuffer(captureRequest->frameNumber, streamId,
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003742 request->input_buffer->buffer);
3743 inflightBuffers->push_back(std::make_pair(captureRequest->frameNumber, streamId));
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003744 } else {
3745 captureRequest->inputBuffer.streamId = -1;
3746 captureRequest->inputBuffer.bufferId = BUFFER_ID_NO_BUFFER;
3747 }
3748
3749 captureRequest->outputBuffers.resize(request->num_output_buffers);
3750 for (size_t i = 0; i < request->num_output_buffers; i++) {
Emilian Peevf4816702020-04-03 15:44:51 -07003751 const camera_stream_buffer_t *src = request->output_buffers + i;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003752 StreamBuffer &dst = captureRequest->outputBuffers[i];
3753 int32_t streamId = Camera3Stream::cast(src->stream)->getId();
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003754 if (src->buffer != nullptr) {
3755 buffer_handle_t buf = *(src->buffer);
3756 auto pair = getBufferId(buf, streamId);
3757 bool isNewBuffer = pair.first;
3758 dst.bufferId = pair.second;
3759 dst.buffer = isNewBuffer ? buf : nullptr;
3760 native_handle_t *acquireFence = nullptr;
3761 if (src->acquire_fence != -1) {
3762 acquireFence = native_handle_create(1,0);
3763 acquireFence->data[0] = src->acquire_fence;
3764 handlesCreated->push_back(acquireFence);
3765 }
3766 dst.acquireFence = acquireFence;
3767 } else if (mUseHalBufManager) {
3768 // HAL buffer management path
3769 dst.bufferId = BUFFER_ID_NO_BUFFER;
3770 dst.buffer = nullptr;
3771 dst.acquireFence = nullptr;
3772 } else {
3773 ALOGE("%s: cannot send a null buffer in capture request!", __FUNCTION__);
3774 return BAD_VALUE;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003775 }
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003776 dst.streamId = streamId;
3777 dst.status = BufferStatus::OK;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003778 dst.releaseFence = nullptr;
3779
Yin-Chia Yeh5f840f82019-03-05 11:59:04 -08003780 // Output buffers are empty when using HAL buffer manager
3781 if (!mUseHalBufManager) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003782 mBufferRecords.pushInflightBuffer(
3783 captureRequest->frameNumber, streamId, src->buffer);
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003784 inflightBuffers->push_back(std::make_pair(captureRequest->frameNumber, streamId));
Yin-Chia Yeh5f840f82019-03-05 11:59:04 -08003785 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003786 }
3787 }
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003788 return OK;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003789}
3790
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003791void Camera3Device::HalInterface::cleanupNativeHandles(
3792 std::vector<native_handle_t*> *handles, bool closeFd) {
3793 if (handles == nullptr) {
3794 return;
3795 }
3796 if (closeFd) {
3797 for (auto& handle : *handles) {
3798 native_handle_close(handle);
3799 }
3800 }
3801 for (auto& handle : *handles) {
3802 native_handle_delete(handle);
3803 }
3804 handles->clear();
3805 return;
3806}
3807
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003808status_t Camera3Device::HalInterface::processBatchCaptureRequests(
Emilian Peevf4816702020-04-03 15:44:51 -07003809 std::vector<camera_capture_request_t*>& requests,/*out*/uint32_t* numRequestProcessed) {
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003810 ATRACE_NAME("CameraHal::processBatchCaptureRequests");
3811 if (!valid()) return INVALID_OPERATION;
3812
Emilian Peevaebbe412018-01-15 13:53:24 +00003813 sp<device::V3_4::ICameraDeviceSession> hidlSession_3_4;
Shuzhen Wang83bff122020-11-20 15:51:39 -08003814 sp<device::V3_7::ICameraDeviceSession> hidlSession_3_7;
3815 auto castResult_3_7 = device::V3_7::ICameraDeviceSession::castFrom(mHidlSession);
3816 if (castResult_3_7.isOk()) {
3817 hidlSession_3_7 = castResult_3_7;
3818 }
Emilian Peevaebbe412018-01-15 13:53:24 +00003819 auto castResult_3_4 = device::V3_4::ICameraDeviceSession::castFrom(mHidlSession);
3820 if (castResult_3_4.isOk()) {
3821 hidlSession_3_4 = castResult_3_4;
3822 }
3823
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003824 hardware::hidl_vec<device::V3_2::CaptureRequest> captureRequests;
Emilian Peevaebbe412018-01-15 13:53:24 +00003825 hardware::hidl_vec<device::V3_4::CaptureRequest> captureRequests_3_4;
Shuzhen Wang83bff122020-11-20 15:51:39 -08003826 hardware::hidl_vec<device::V3_7::CaptureRequest> captureRequests_3_7;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003827 size_t batchSize = requests.size();
Shuzhen Wang83bff122020-11-20 15:51:39 -08003828 if (hidlSession_3_7 != nullptr) {
3829 captureRequests_3_7.resize(batchSize);
3830 } else if (hidlSession_3_4 != nullptr) {
Emilian Peevaebbe412018-01-15 13:53:24 +00003831 captureRequests_3_4.resize(batchSize);
3832 } else {
3833 captureRequests.resize(batchSize);
3834 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003835 std::vector<native_handle_t*> handlesCreated;
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003836 std::vector<std::pair<int32_t, int32_t>> inflightBuffers;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003837
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003838 status_t res = OK;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003839 for (size_t i = 0; i < batchSize; i++) {
Shuzhen Wang83bff122020-11-20 15:51:39 -08003840 if (hidlSession_3_7 != nullptr) {
3841 res = wrapAsHidlRequest(requests[i], /*out*/&captureRequests_3_7[i].v3_4.v3_2,
3842 /*out*/&handlesCreated, /*out*/&inflightBuffers);
3843 } else if (hidlSession_3_4 != nullptr) {
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003844 res = wrapAsHidlRequest(requests[i], /*out*/&captureRequests_3_4[i].v3_2,
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003845 /*out*/&handlesCreated, /*out*/&inflightBuffers);
Emilian Peevaebbe412018-01-15 13:53:24 +00003846 } else {
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003847 res = wrapAsHidlRequest(requests[i], /*out*/&captureRequests[i],
3848 /*out*/&handlesCreated, /*out*/&inflightBuffers);
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003849 }
3850 if (res != OK) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003851 mBufferRecords.popInflightBuffers(inflightBuffers);
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003852 cleanupNativeHandles(&handlesCreated);
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003853 return res;
Emilian Peevaebbe412018-01-15 13:53:24 +00003854 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003855 }
3856
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003857 std::vector<device::V3_2::BufferCache> cachesToRemove;
3858 {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003859 std::lock_guard<std::mutex> lock(mFreedBuffersLock);
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003860 for (auto& pair : mFreedBuffers) {
3861 // The stream might have been removed since onBufferFreed
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003862 if (mBufferRecords.isStreamCached(pair.first)) {
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003863 cachesToRemove.push_back({pair.first, pair.second});
3864 }
3865 }
3866 mFreedBuffers.clear();
3867 }
3868
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003869 common::V1_0::Status status = common::V1_0::Status::INTERNAL_ERROR;
3870 *numRequestProcessed = 0;
Yifan Hongf79b5542017-04-11 14:44:25 -07003871
3872 // Write metadata to FMQ.
3873 for (size_t i = 0; i < batchSize; i++) {
Emilian Peevf4816702020-04-03 15:44:51 -07003874 camera_capture_request_t* request = requests[i];
Emilian Peevaebbe412018-01-15 13:53:24 +00003875 device::V3_2::CaptureRequest* captureRequest;
Shuzhen Wang83bff122020-11-20 15:51:39 -08003876 if (hidlSession_3_7 != nullptr) {
3877 captureRequest = &captureRequests_3_7[i].v3_4.v3_2;
3878 } else if (hidlSession_3_4 != nullptr) {
Emilian Peevaebbe412018-01-15 13:53:24 +00003879 captureRequest = &captureRequests_3_4[i].v3_2;
3880 } else {
3881 captureRequest = &captureRequests[i];
3882 }
Yifan Hongf79b5542017-04-11 14:44:25 -07003883
3884 if (request->settings != nullptr) {
3885 size_t settingsSize = get_camera_metadata_size(request->settings);
3886 if (mRequestMetadataQueue != nullptr && mRequestMetadataQueue->write(
3887 reinterpret_cast<const uint8_t*>(request->settings), settingsSize)) {
3888 captureRequest->settings.resize(0);
3889 captureRequest->fmqSettingsSize = settingsSize;
3890 } else {
3891 if (mRequestMetadataQueue != nullptr) {
3892 ALOGW("%s: couldn't utilize fmq, fallback to hwbinder", __FUNCTION__);
3893 }
3894 captureRequest->settings.setToExternal(
3895 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(request->settings)),
3896 get_camera_metadata_size(request->settings));
3897 captureRequest->fmqSettingsSize = 0u;
3898 }
3899 } else {
3900 // A null request settings maps to a size-0 CameraMetadata
3901 captureRequest->settings.resize(0);
3902 captureRequest->fmqSettingsSize = 0u;
3903 }
Emilian Peevaebbe412018-01-15 13:53:24 +00003904
Shuzhen Wang83bff122020-11-20 15:51:39 -08003905 // hidl session 3.7 specific handling.
3906 if (hidlSession_3_7 != nullptr) {
3907 captureRequests_3_7[i].inputWidth = request->input_width;
3908 captureRequests_3_7[i].inputHeight = request->input_height;
3909 }
3910
3911 // hidl session 3.7 and 3.4 specific handling.
3912 if (hidlSession_3_7 != nullptr || hidlSession_3_4 != nullptr) {
3913 hardware::hidl_vec<device::V3_4::PhysicalCameraSetting>& physicalCameraSettings =
3914 (hidlSession_3_7 != nullptr) ?
3915 captureRequests_3_7[i].v3_4.physicalCameraSettings :
3916 captureRequests_3_4[i].physicalCameraSettings;
3917 physicalCameraSettings.resize(request->num_physcam_settings);
Emilian Peevaebbe412018-01-15 13:53:24 +00003918 for (size_t j = 0; j < request->num_physcam_settings; j++) {
Emilian Peev00420d22018-02-05 21:33:13 +00003919 if (request->physcam_settings != nullptr) {
3920 size_t settingsSize = get_camera_metadata_size(request->physcam_settings[j]);
3921 if (mRequestMetadataQueue != nullptr && mRequestMetadataQueue->write(
3922 reinterpret_cast<const uint8_t*>(request->physcam_settings[j]),
3923 settingsSize)) {
Shuzhen Wang83bff122020-11-20 15:51:39 -08003924 physicalCameraSettings[j].settings.resize(0);
3925 physicalCameraSettings[j].fmqSettingsSize = settingsSize;
Emilian Peev00420d22018-02-05 21:33:13 +00003926 } else {
3927 if (mRequestMetadataQueue != nullptr) {
3928 ALOGW("%s: couldn't utilize fmq, fallback to hwbinder", __FUNCTION__);
3929 }
Shuzhen Wang83bff122020-11-20 15:51:39 -08003930 physicalCameraSettings[j].settings.setToExternal(
Emilian Peev00420d22018-02-05 21:33:13 +00003931 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(
3932 request->physcam_settings[j])),
3933 get_camera_metadata_size(request->physcam_settings[j]));
Shuzhen Wang83bff122020-11-20 15:51:39 -08003934 physicalCameraSettings[j].fmqSettingsSize = 0u;
Emilian Peevaebbe412018-01-15 13:53:24 +00003935 }
Emilian Peev00420d22018-02-05 21:33:13 +00003936 } else {
Yin-Chia Yeha2849702021-03-10 10:11:33 -08003937 physicalCameraSettings[j].fmqSettingsSize = 0u;
3938 physicalCameraSettings[j].settings.resize(0);
Emilian Peevaebbe412018-01-15 13:53:24 +00003939 }
Shuzhen Wang83bff122020-11-20 15:51:39 -08003940 physicalCameraSettings[j].physicalCameraId = request->physcam_id[j];
Emilian Peevaebbe412018-01-15 13:53:24 +00003941 }
3942 }
Yifan Hongf79b5542017-04-11 14:44:25 -07003943 }
Emilian Peevaebbe412018-01-15 13:53:24 +00003944
3945 hardware::details::return_status err;
Jayant Chowdharyc8d581e2018-07-16 14:46:23 -07003946 auto resultCallback =
3947 [&status, &numRequestProcessed] (auto s, uint32_t n) {
3948 status = s;
3949 *numRequestProcessed = n;
3950 };
Shuzhen Wang83bff122020-11-20 15:51:39 -08003951 if (hidlSession_3_7 != nullptr) {
3952 err = hidlSession_3_7->processCaptureRequest_3_7(captureRequests_3_7, cachesToRemove,
3953 resultCallback);
3954 } else if (hidlSession_3_4 != nullptr) {
Emilian Peevaebbe412018-01-15 13:53:24 +00003955 err = hidlSession_3_4->processCaptureRequest_3_4(captureRequests_3_4, cachesToRemove,
Jayant Chowdharyc8d581e2018-07-16 14:46:23 -07003956 resultCallback);
Emilian Peevaebbe412018-01-15 13:53:24 +00003957 } else {
3958 err = mHidlSession->processCaptureRequest(captureRequests, cachesToRemove,
Jayant Chowdharyc8d581e2018-07-16 14:46:23 -07003959 resultCallback);
Emilian Peevaebbe412018-01-15 13:53:24 +00003960 }
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -07003961 if (!err.isOk()) {
3962 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003963 status = common::V1_0::Status::CAMERA_DISCONNECTED;
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -07003964 }
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003965
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003966 if (status == common::V1_0::Status::OK && *numRequestProcessed != batchSize) {
3967 ALOGE("%s: processCaptureRequest returns OK but processed %d/%zu requests",
3968 __FUNCTION__, *numRequestProcessed, batchSize);
3969 status = common::V1_0::Status::INTERNAL_ERROR;
3970 }
3971
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003972 res = CameraProviderManager::mapToStatusT(status);
3973 if (res == OK) {
3974 if (mHidlSession->isRemote()) {
3975 // Only close acquire fence FDs when the HIDL transaction succeeds (so the FDs have been
3976 // sent to camera HAL processes)
3977 cleanupNativeHandles(&handlesCreated, /*closeFd*/true);
3978 } else {
3979 // In passthrough mode the FDs are now owned by HAL
3980 cleanupNativeHandles(&handlesCreated);
3981 }
3982 } else {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003983 mBufferRecords.popInflightBuffers(inflightBuffers);
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003984 cleanupNativeHandles(&handlesCreated);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003985 }
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003986 return res;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003987}
3988
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003989status_t Camera3Device::HalInterface::flush() {
3990 ATRACE_NAME("CameraHal::flush");
3991 if (!valid()) return INVALID_OPERATION;
3992 status_t res = OK;
3993
Emilian Peev31abd0a2017-05-11 18:37:46 +01003994 auto err = mHidlSession->flush();
3995 if (!err.isOk()) {
3996 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3997 res = DEAD_OBJECT;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003998 } else {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003999 res = CameraProviderManager::mapToStatusT(err);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004000 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01004001
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004002 return res;
4003}
4004
Emilian Peev31abd0a2017-05-11 18:37:46 +01004005status_t Camera3Device::HalInterface::dump(int /*fd*/) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004006 ATRACE_NAME("CameraHal::dump");
4007 if (!valid()) return INVALID_OPERATION;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004008
Emilian Peev31abd0a2017-05-11 18:37:46 +01004009 // Handled by CameraProviderManager::dump
4010
4011 return OK;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004012}
4013
4014status_t Camera3Device::HalInterface::close() {
4015 ATRACE_NAME("CameraHal::close()");
4016 if (!valid()) return INVALID_OPERATION;
4017 status_t res = OK;
4018
Emilian Peev31abd0a2017-05-11 18:37:46 +01004019 auto err = mHidlSession->close();
4020 // Interface will be dead shortly anyway, so don't log errors
4021 if (!err.isOk()) {
4022 res = DEAD_OBJECT;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004023 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01004024
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004025 return res;
4026}
4027
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004028void Camera3Device::HalInterface::signalPipelineDrain(const std::vector<int>& streamIds) {
4029 ATRACE_NAME("CameraHal::signalPipelineDrain");
4030 if (!valid() || mHidlSession_3_5 == nullptr) {
4031 ALOGE("%s called on invalid camera!", __FUNCTION__);
4032 return;
4033 }
4034
Yin-Chia Yehc300a072019-02-13 14:56:57 -08004035 auto err = mHidlSession_3_5->signalStreamFlush(streamIds, mNextStreamConfigCounter - 1);
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004036 if (!err.isOk()) {
4037 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
4038 return;
4039 }
4040}
4041
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004042status_t Camera3Device::HalInterface::switchToOffline(
4043 const std::vector<int32_t>& streamsToKeep,
4044 /*out*/hardware::camera::device::V3_6::CameraOfflineSessionInfo* offlineSessionInfo,
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004045 /*out*/sp<hardware::camera::device::V3_6::ICameraOfflineSession>* offlineSession,
4046 /*out*/camera3::BufferRecords* bufferRecords) {
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004047 ATRACE_NAME("CameraHal::switchToOffline");
4048 if (!valid() || mHidlSession_3_6 == nullptr) {
4049 ALOGE("%s called on invalid camera!", __FUNCTION__);
4050 return INVALID_OPERATION;
4051 }
4052
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004053 if (offlineSessionInfo == nullptr || offlineSession == nullptr || bufferRecords == nullptr) {
4054 ALOGE("%s: output arguments must not be null!", __FUNCTION__);
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004055 return INVALID_OPERATION;
4056 }
4057
4058 common::V1_0::Status status = common::V1_0::Status::INTERNAL_ERROR;
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004059 auto resultCallback =
4060 [&status, &offlineSessionInfo, &offlineSession] (auto s, auto info, auto session) {
4061 status = s;
4062 *offlineSessionInfo = info;
4063 *offlineSession = session;
4064 };
4065 auto err = mHidlSession_3_6->switchToOffline(streamsToKeep, resultCallback);
4066
4067 if (!err.isOk()) {
4068 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
4069 return DEAD_OBJECT;
4070 }
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004071
4072 status_t ret = CameraProviderManager::mapToStatusT(status);
4073 if (ret != OK) {
4074 return ret;
4075 }
4076
4077 // TODO: assert no ongoing requestBuffer/returnBuffer call here
4078 // TODO: update RequestBufferStateMachine to block requestBuffer/returnBuffer once HAL
4079 // returns from switchToOffline.
4080
4081
4082 // Validate buffer caches
4083 std::vector<int32_t> streams;
4084 streams.reserve(offlineSessionInfo->offlineStreams.size());
4085 for (auto offlineStream : offlineSessionInfo->offlineStreams) {
4086 int32_t id = offlineStream.id;
4087 streams.push_back(id);
4088 // Verify buffer caches
4089 std::vector<uint64_t> bufIds(offlineStream.circulatingBufferIds.begin(),
4090 offlineStream.circulatingBufferIds.end());
4091 if (!verifyBufferIds(id, bufIds)) {
4092 ALOGE("%s: stream ID %d buffer cache records mismatch!", __FUNCTION__, id);
4093 return UNKNOWN_ERROR;
4094 }
4095 }
4096
4097 // Move buffer records
4098 bufferRecords->takeBufferCaches(mBufferRecords, streams);
4099 bufferRecords->takeInflightBufferMap(mBufferRecords);
4100 bufferRecords->takeRequestedBufferMap(mBufferRecords);
4101 return ret;
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004102}
4103
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07004104void Camera3Device::HalInterface::getInflightBufferKeys(
4105 std::vector<std::pair<int32_t, int32_t>>* out) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004106 mBufferRecords.getInflightBufferKeys(out);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07004107 return;
4108}
4109
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08004110void Camera3Device::HalInterface::getInflightRequestBufferKeys(
4111 std::vector<uint64_t>* out) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004112 mBufferRecords.getInflightRequestBufferKeys(out);
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08004113 return;
4114}
4115
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004116bool Camera3Device::HalInterface::verifyBufferIds(
4117 int32_t streamId, std::vector<uint64_t>& bufIds) {
4118 return mBufferRecords.verifyBufferIds(streamId, bufIds);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004119}
4120
4121status_t Camera3Device::HalInterface::popInflightBuffer(
Yin-Chia Yehf4650602017-01-10 13:13:39 -08004122 int32_t frameNumber, int32_t streamId,
4123 /*out*/ buffer_handle_t **buffer) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004124 return mBufferRecords.popInflightBuffer(frameNumber, streamId, buffer);
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07004125}
4126
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004127status_t Camera3Device::HalInterface::pushInflightRequestBuffer(
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08004128 uint64_t bufferId, buffer_handle_t* buf, int32_t streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004129 return mBufferRecords.pushInflightRequestBuffer(bufferId, buf, streamId);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004130}
4131
4132// Find and pop a buffer_handle_t based on bufferId
4133status_t Camera3Device::HalInterface::popInflightRequestBuffer(
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08004134 uint64_t bufferId,
4135 /*out*/ buffer_handle_t** buffer,
4136 /*optional out*/ int32_t* streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004137 return mBufferRecords.popInflightRequestBuffer(bufferId, buffer, streamId);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004138}
4139
Yin-Chia Yeh77327052017-01-09 18:23:07 -08004140std::pair<bool, uint64_t> Camera3Device::HalInterface::getBufferId(
4141 const buffer_handle_t& buf, int streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004142 return mBufferRecords.getBufferId(buf, streamId);
Yin-Chia Yeh77327052017-01-09 18:23:07 -08004143}
4144
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07004145void Camera3Device::HalInterface::onBufferFreed(
4146 int streamId, const native_handle_t* handle) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004147 uint32_t bufferId = mBufferRecords.removeOneBufferCache(streamId, handle);
4148 std::lock_guard<std::mutex> lock(mFreedBuffersLock);
4149 if (bufferId != BUFFER_ID_NO_BUFFER) {
4150 mFreedBuffers.push_back(std::make_pair(streamId, bufferId));
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07004151 }
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07004152}
4153
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07004154void Camera3Device::HalInterface::onStreamReConfigured(int streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004155 std::vector<uint64_t> bufIds = mBufferRecords.clearBufferCaches(streamId);
4156 std::lock_guard<std::mutex> lock(mFreedBuffersLock);
4157 for (auto bufferId : bufIds) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07004158 mFreedBuffers.push_back(std::make_pair(streamId, bufferId));
4159 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07004160}
4161
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004162/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004163 * RequestThread inner class methods
4164 */
4165
4166Camera3Device::RequestThread::RequestThread(wp<Camera3Device> parent,
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004167 sp<StatusTracker> statusTracker,
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004168 sp<HalInterface> interface, const Vector<int32_t>& sessionParamKeys,
4169 bool useHalBufManager) :
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004170 Thread(/*canCallJava*/false),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004171 mParent(parent),
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004172 mStatusTracker(statusTracker),
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004173 mInterface(interface),
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07004174 mListener(nullptr),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004175 mId(getId(parent)),
Shuzhen Wang316781a2020-08-18 18:11:01 -07004176 mFirstRepeating(false),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004177 mReconfigured(false),
4178 mDoPause(false),
4179 mPaused(true),
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004180 mNotifyPipelineDrain(false),
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004181 mFrameNumber(0),
Jianing Weicb0652e2014-03-12 18:29:36 -07004182 mLatestRequestId(NAME_NOT_FOUND),
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07004183 mCurrentAfTriggerId(0),
4184 mCurrentPreCaptureTriggerId(0),
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004185 mRotateAndCropOverride(ANDROID_SCALER_ROTATE_AND_CROP_NONE),
Eino-Ville Talvala11afe4f2021-05-27 14:45:31 -07004186 mCameraMute(ANDROID_SENSOR_TEST_PATTERN_MODE_OFF),
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004187 mCameraMuteChanged(false),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004188 mRepeatingLastFrameNumber(
4189 hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES),
Shuzhen Wang686f6442017-06-20 16:16:04 -07004190 mPrepareVideoStream(false),
Emilian Peeva14b4dd2018-05-15 11:00:31 +01004191 mConstrainedMode(false),
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004192 mRequestLatency(kRequestLatencyBinSize),
4193 mSessionParamKeys(sessionParamKeys),
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004194 mLatestSessionParams(sessionParamKeys.size()),
4195 mUseHalBufManager(useHalBufManager) {
Yin-Chia Yeh87b3ec02019-06-03 10:44:39 -07004196 mStatusId = statusTracker->addComponent("RequestThread");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004197}
4198
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004199Camera3Device::RequestThread::~RequestThread() {}
4200
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004201void Camera3Device::RequestThread::setNotificationListener(
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004202 wp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004203 ATRACE_CALL();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004204 Mutex::Autolock l(mRequestLock);
4205 mListener = listener;
4206}
4207
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004208void Camera3Device::RequestThread::configurationComplete(bool isConstrainedHighSpeed,
Shuzhen Wang99080502021-03-07 21:08:20 -08004209 const CameraMetadata& sessionParams,
4210 const std::map<int32_t, std::set<String8>>& groupIdPhysicalCameraMap) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004211 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004212 Mutex::Autolock l(mRequestLock);
4213 mReconfigured = true;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004214 mLatestSessionParams = sessionParams;
Shuzhen Wang99080502021-03-07 21:08:20 -08004215 mGroupIdPhysicalCameraMap = groupIdPhysicalCameraMap;
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07004216 // Prepare video stream for high speed recording.
4217 mPrepareVideoStream = isConstrainedHighSpeed;
Emilian Peeva14b4dd2018-05-15 11:00:31 +01004218 mConstrainedMode = isConstrainedHighSpeed;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004219}
4220
Jianing Wei90e59c92014-03-12 18:29:36 -07004221status_t Camera3Device::RequestThread::queueRequestList(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004222 List<sp<CaptureRequest> > &requests,
4223 /*out*/
4224 int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004225 ATRACE_CALL();
Jianing Wei90e59c92014-03-12 18:29:36 -07004226 Mutex::Autolock l(mRequestLock);
4227 for (List<sp<CaptureRequest> >::iterator it = requests.begin(); it != requests.end();
4228 ++it) {
4229 mRequestQueue.push_back(*it);
4230 }
4231
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004232 if (lastFrameNumber != NULL) {
4233 *lastFrameNumber = mFrameNumber + mRequestQueue.size() - 1;
4234 ALOGV("%s: requestId %d, mFrameNumber %" PRId32 ", lastFrameNumber %" PRId64 ".",
4235 __FUNCTION__, (*(requests.begin()))->mResultExtras.requestId, mFrameNumber,
4236 *lastFrameNumber);
4237 }
Jianing Weicb0652e2014-03-12 18:29:36 -07004238
Jianing Wei90e59c92014-03-12 18:29:36 -07004239 unpauseForNewRequests();
4240
4241 return OK;
4242}
4243
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004244
4245status_t Camera3Device::RequestThread::queueTrigger(
4246 RequestTrigger trigger[],
4247 size_t count) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004248 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004249 Mutex::Autolock l(mTriggerMutex);
4250 status_t ret;
4251
4252 for (size_t i = 0; i < count; ++i) {
4253 ret = queueTriggerLocked(trigger[i]);
4254
4255 if (ret != OK) {
4256 return ret;
4257 }
4258 }
4259
4260 return OK;
4261}
4262
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004263const String8& Camera3Device::RequestThread::getId(const wp<Camera3Device> &device) {
4264 static String8 deadId("<DeadDevice>");
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004265 sp<Camera3Device> d = device.promote();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004266 if (d != nullptr) return d->mId;
4267 return deadId;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004268}
4269
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004270status_t Camera3Device::RequestThread::queueTriggerLocked(
4271 RequestTrigger trigger) {
4272
4273 uint32_t tag = trigger.metadataTag;
4274 ssize_t index = mTriggerMap.indexOfKey(tag);
4275
4276 switch (trigger.getTagType()) {
4277 case TYPE_BYTE:
4278 // fall-through
4279 case TYPE_INT32:
4280 break;
4281 default:
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004282 ALOGE("%s: Type not supported: 0x%x", __FUNCTION__,
4283 trigger.getTagType());
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004284 return INVALID_OPERATION;
4285 }
4286
4287 /**
4288 * Collect only the latest trigger, since we only have 1 field
4289 * in the request settings per trigger tag, and can't send more than 1
4290 * trigger per request.
4291 */
4292 if (index != NAME_NOT_FOUND) {
4293 mTriggerMap.editValueAt(index) = trigger;
4294 } else {
4295 mTriggerMap.add(tag, trigger);
4296 }
4297
4298 return OK;
4299}
4300
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004301status_t Camera3Device::RequestThread::setRepeatingRequests(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004302 const RequestList &requests,
4303 /*out*/
4304 int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004305 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004306 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004307 if (lastFrameNumber != NULL) {
4308 *lastFrameNumber = mRepeatingLastFrameNumber;
4309 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004310 mRepeatingRequests.clear();
Shuzhen Wang316781a2020-08-18 18:11:01 -07004311 mFirstRepeating = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004312 mRepeatingRequests.insert(mRepeatingRequests.begin(),
4313 requests.begin(), requests.end());
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004314
4315 unpauseForNewRequests();
4316
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004317 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004318 return OK;
4319}
4320
Chih-Hung Hsieh8b0b9712016-08-09 14:25:53 -07004321bool Camera3Device::RequestThread::isRepeatingRequestLocked(const sp<CaptureRequest>& requestIn) {
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07004322 if (mRepeatingRequests.empty()) {
4323 return false;
4324 }
4325 int32_t requestId = requestIn->mResultExtras.requestId;
4326 const RequestList &repeatRequests = mRepeatingRequests;
4327 // All repeating requests are guaranteed to have same id so only check first quest
4328 const sp<CaptureRequest> firstRequest = *repeatRequests.begin();
4329 return (firstRequest->mResultExtras.requestId == requestId);
4330}
4331
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004332status_t Camera3Device::RequestThread::clearRepeatingRequests(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004333 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004334 Mutex::Autolock l(mRequestLock);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004335 return clearRepeatingRequestsLocked(lastFrameNumber);
4336
4337}
4338
4339status_t Camera3Device::RequestThread::clearRepeatingRequestsLocked(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004340 mRepeatingRequests.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004341 if (lastFrameNumber != NULL) {
4342 *lastFrameNumber = mRepeatingLastFrameNumber;
4343 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004344 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004345 return OK;
4346}
4347
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004348status_t Camera3Device::RequestThread::clear(
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004349 /*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004350 ATRACE_CALL();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004351 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004352 ALOGV("RequestThread::%s:", __FUNCTION__);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004353
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004354 mRepeatingRequests.clear();
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07004355
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004356 // Send errors for all requests pending in the request queue, including
4357 // pending repeating requests
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004358 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004359 if (listener != NULL) {
4360 for (RequestList::iterator it = mRequestQueue.begin();
4361 it != mRequestQueue.end(); ++it) {
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004362 // Abort the input buffers for reprocess requests.
4363 if ((*it)->mInputStream != NULL) {
Emilian Peevf4816702020-04-03 15:44:51 -07004364 camera_stream_buffer_t inputBuffer;
Shuzhen Wang83bff122020-11-20 15:51:39 -08004365 camera3::Size inputBufferSize;
Eino-Ville Talvalaba435252017-06-21 16:07:25 -07004366 status_t res = (*it)->mInputStream->getInputBuffer(&inputBuffer,
Shuzhen Wang83bff122020-11-20 15:51:39 -08004367 &inputBufferSize, /*respectHalLimit*/ false);
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004368 if (res != OK) {
4369 ALOGW("%s: %d: couldn't get input buffer while clearing the request "
4370 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
4371 } else {
Emilian Peevf4816702020-04-03 15:44:51 -07004372 inputBuffer.status = CAMERA_BUFFER_STATUS_ERROR;
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004373 res = (*it)->mInputStream->returnInputBuffer(inputBuffer);
4374 if (res != OK) {
4375 ALOGE("%s: %d: couldn't return input buffer while clearing the request "
4376 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
4377 }
4378 }
4379 }
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004380 // Set the frame number this request would have had, if it
4381 // had been submitted; this frame number will not be reused.
4382 // The requestId and burstId fields were set when the request was
4383 // submitted originally (in convertMetadataListToRequestListLocked)
4384 (*it)->mResultExtras.frameNumber = mFrameNumber++;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004385 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004386 (*it)->mResultExtras);
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07004387 }
4388 }
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004389 mRequestQueue.clear();
Jinguang Dongb26e7a02016-11-14 16:04:02 +08004390
4391 Mutex::Autolock al(mTriggerMutex);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004392 mTriggerMap.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004393 if (lastFrameNumber != NULL) {
4394 *lastFrameNumber = mRepeatingLastFrameNumber;
4395 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004396 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Emilian Peev8dae54c2019-12-02 15:17:17 -08004397 mRequestSignal.signal();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004398 return OK;
4399}
4400
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004401status_t Camera3Device::RequestThread::flush() {
4402 ATRACE_CALL();
4403 Mutex::Autolock l(mFlushLock);
4404
Emilian Peev08dd2452017-04-06 16:55:14 +01004405 return mInterface->flush();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004406}
4407
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004408void Camera3Device::RequestThread::setPaused(bool paused) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004409 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004410 Mutex::Autolock l(mPauseLock);
4411 mDoPause = paused;
4412 mDoPauseSignal.signal();
4413}
4414
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004415status_t Camera3Device::RequestThread::waitUntilRequestProcessed(
4416 int32_t requestId, nsecs_t timeout) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004417 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004418 Mutex::Autolock l(mLatestRequestMutex);
4419 status_t res;
4420 while (mLatestRequestId != requestId) {
4421 nsecs_t startTime = systemTime();
4422
4423 res = mLatestRequestSignal.waitRelative(mLatestRequestMutex, timeout);
4424 if (res != OK) return res;
4425
4426 timeout -= (systemTime() - startTime);
4427 }
4428
4429 return OK;
4430}
4431
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004432void Camera3Device::RequestThread::requestExit() {
4433 // Call parent to set up shutdown
4434 Thread::requestExit();
4435 // The exit from any possible waits
4436 mDoPauseSignal.signal();
4437 mRequestSignal.signal();
Shuzhen Wang686f6442017-06-20 16:16:04 -07004438
4439 mRequestLatency.log("ProcessCaptureRequest latency histogram");
4440 mRequestLatency.reset();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004441}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004442
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004443void Camera3Device::RequestThread::checkAndStopRepeatingRequest() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004444 ATRACE_CALL();
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07004445 bool surfaceAbandoned = false;
4446 int64_t lastFrameNumber = 0;
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004447 sp<NotificationListener> listener;
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07004448 {
4449 Mutex::Autolock l(mRequestLock);
4450 // Check all streams needed by repeating requests are still valid. Otherwise, stop
4451 // repeating requests.
4452 for (const auto& request : mRepeatingRequests) {
4453 for (const auto& s : request->mOutputStreams) {
4454 if (s->isAbandoned()) {
4455 surfaceAbandoned = true;
4456 clearRepeatingRequestsLocked(&lastFrameNumber);
4457 break;
4458 }
4459 }
4460 if (surfaceAbandoned) {
4461 break;
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004462 }
4463 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004464 listener = mListener.promote();
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004465 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004466
4467 if (listener != NULL && surfaceAbandoned) {
4468 listener->notifyRepeatingRequestError(lastFrameNumber);
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07004469 }
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004470}
4471
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004472bool Camera3Device::RequestThread::sendRequestsBatch() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004473 ATRACE_CALL();
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004474 status_t res;
4475 size_t batchSize = mNextRequests.size();
Emilian Peevf4816702020-04-03 15:44:51 -07004476 std::vector<camera_capture_request_t*> requests(batchSize);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004477 uint32_t numRequestProcessed = 0;
4478 for (size_t i = 0; i < batchSize; i++) {
4479 requests[i] = &mNextRequests.editItemAt(i).halRequest;
Yin-Chia Yeh885691c2018-05-01 15:54:24 -07004480 ATRACE_ASYNC_BEGIN("frame capture", mNextRequests[i].halRequest.frame_number);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004481 }
4482
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004483 res = mInterface->processBatchCaptureRequests(requests, &numRequestProcessed);
4484
4485 bool triggerRemoveFailed = false;
4486 NextRequest& triggerFailedRequest = mNextRequests.editItemAt(0);
4487 for (size_t i = 0; i < numRequestProcessed; i++) {
4488 NextRequest& nextRequest = mNextRequests.editItemAt(i);
4489 nextRequest.submitted = true;
4490
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004491 updateNextRequest(nextRequest);
Emilian Peevaebbe412018-01-15 13:53:24 +00004492
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004493 if (!triggerRemoveFailed) {
4494 // Remove any previously queued triggers (after unlock)
4495 status_t removeTriggerRes = removeTriggers(mPrevRequest);
4496 if (removeTriggerRes != OK) {
4497 triggerRemoveFailed = true;
4498 triggerFailedRequest = nextRequest;
4499 }
4500 }
4501 }
4502
4503 if (triggerRemoveFailed) {
4504 SET_ERR("RequestThread: Unable to remove triggers "
4505 "(capture request %d, HAL device: %s (%d)",
4506 triggerFailedRequest.halRequest.frame_number, strerror(-res), res);
4507 cleanUpFailedRequests(/*sendRequestError*/ false);
4508 return false;
4509 }
4510
4511 if (res != OK) {
4512 // Should only get a failure here for malformed requests or device-level
4513 // errors, so consider all errors fatal. Bad metadata failures should
4514 // come through notify.
4515 SET_ERR("RequestThread: Unable to submit capture request %d to HAL device: %s (%d)",
4516 mNextRequests[numRequestProcessed].halRequest.frame_number,
4517 strerror(-res), res);
4518 cleanUpFailedRequests(/*sendRequestError*/ false);
4519 return false;
4520 }
4521 return true;
4522}
4523
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07004524nsecs_t Camera3Device::RequestThread::calculateMaxExpectedDuration(const camera_metadata_t *request) {
4525 nsecs_t maxExpectedDuration = kDefaultExpectedDuration;
4526 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
4527 find_camera_metadata_ro_entry(request,
4528 ANDROID_CONTROL_AE_MODE,
4529 &e);
4530 if (e.count == 0) return maxExpectedDuration;
4531
4532 switch (e.data.u8[0]) {
4533 case ANDROID_CONTROL_AE_MODE_OFF:
4534 find_camera_metadata_ro_entry(request,
4535 ANDROID_SENSOR_EXPOSURE_TIME,
4536 &e);
4537 if (e.count > 0) {
4538 maxExpectedDuration = e.data.i64[0];
4539 }
4540 find_camera_metadata_ro_entry(request,
4541 ANDROID_SENSOR_FRAME_DURATION,
4542 &e);
4543 if (e.count > 0) {
4544 maxExpectedDuration = std::max(e.data.i64[0], maxExpectedDuration);
4545 }
4546 break;
4547 default:
4548 find_camera_metadata_ro_entry(request,
4549 ANDROID_CONTROL_AE_TARGET_FPS_RANGE,
4550 &e);
4551 if (e.count > 1) {
4552 maxExpectedDuration = 1e9 / e.data.u8[0];
4553 }
4554 break;
4555 }
4556
4557 return maxExpectedDuration;
4558}
4559
Emilian Peeva14b4dd2018-05-15 11:00:31 +01004560bool Camera3Device::RequestThread::skipHFRTargetFPSUpdate(int32_t tag,
4561 const camera_metadata_ro_entry_t& newEntry, const camera_metadata_entry_t& currentEntry) {
4562 if (mConstrainedMode && (ANDROID_CONTROL_AE_TARGET_FPS_RANGE == tag) &&
4563 (newEntry.count == currentEntry.count) && (currentEntry.count == 2) &&
4564 (currentEntry.data.i32[1] == newEntry.data.i32[1])) {
4565 return true;
4566 }
4567
4568 return false;
4569}
4570
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004571void Camera3Device::RequestThread::updateNextRequest(NextRequest& nextRequest) {
4572 // Update the latest request sent to HAL
Shuzhen Wang83bff122020-11-20 15:51:39 -08004573 camera_capture_request_t& halRequest = nextRequest.halRequest;
4574 if (halRequest.settings != NULL) { // Don't update if they were unchanged
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004575 Mutex::Autolock al(mLatestRequestMutex);
4576
Shuzhen Wang83bff122020-11-20 15:51:39 -08004577 camera_metadata_t* cloned = clone_camera_metadata(halRequest.settings);
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004578 mLatestRequest.acquire(cloned);
4579
4580 mLatestPhysicalRequest.clear();
Shuzhen Wang83bff122020-11-20 15:51:39 -08004581 for (uint32_t i = 0; i < halRequest.num_physcam_settings; i++) {
4582 cloned = clone_camera_metadata(halRequest.physcam_settings[i]);
4583 mLatestPhysicalRequest.emplace(halRequest.physcam_id[i],
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004584 CameraMetadata(cloned));
4585 }
4586
4587 sp<Camera3Device> parent = mParent.promote();
4588 if (parent != NULL) {
4589 parent->monitorMetadata(TagMonitor::REQUEST,
Shuzhen Wang83bff122020-11-20 15:51:39 -08004590 halRequest.frame_number,
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004591 0, mLatestRequest, mLatestPhysicalRequest);
4592 }
4593 }
4594
Shuzhen Wang83bff122020-11-20 15:51:39 -08004595 if (halRequest.settings != NULL) {
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004596 nextRequest.captureRequest->mSettingsList.begin()->metadata.unlock(
Shuzhen Wang83bff122020-11-20 15:51:39 -08004597 halRequest.settings);
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004598 }
4599
Shuzhen Wang83bff122020-11-20 15:51:39 -08004600 cleanupPhysicalSettings(nextRequest.captureRequest, &halRequest);
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004601}
4602
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004603bool Camera3Device::RequestThread::updateSessionParameters(const CameraMetadata& settings) {
4604 ATRACE_CALL();
4605 bool updatesDetected = false;
4606
Emilian Peev4ec17882019-01-24 17:16:58 -08004607 CameraMetadata updatedParams(mLatestSessionParams);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004608 for (auto tag : mSessionParamKeys) {
4609 camera_metadata_ro_entry entry = settings.find(tag);
Emilian Peev4ec17882019-01-24 17:16:58 -08004610 camera_metadata_entry lastEntry = updatedParams.find(tag);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004611
4612 if (entry.count > 0) {
4613 bool isDifferent = false;
4614 if (lastEntry.count > 0) {
4615 // Have a last value, compare to see if changed
4616 if (lastEntry.type == entry.type &&
4617 lastEntry.count == entry.count) {
4618 // Same type and count, compare values
4619 size_t bytesPerValue = camera_metadata_type_size[lastEntry.type];
4620 size_t entryBytes = bytesPerValue * lastEntry.count;
4621 int cmp = memcmp(entry.data.u8, lastEntry.data.u8, entryBytes);
4622 if (cmp != 0) {
4623 isDifferent = true;
4624 }
4625 } else {
4626 // Count or type has changed
4627 isDifferent = true;
4628 }
4629 } else {
4630 // No last entry, so always consider to be different
4631 isDifferent = true;
4632 }
4633
4634 if (isDifferent) {
4635 ALOGV("%s: Session parameter tag id %d changed", __FUNCTION__, tag);
Emilian Peeva14b4dd2018-05-15 11:00:31 +01004636 if (!skipHFRTargetFPSUpdate(tag, entry, lastEntry)) {
4637 updatesDetected = true;
4638 }
Emilian Peev4ec17882019-01-24 17:16:58 -08004639 updatedParams.update(entry);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004640 }
4641 } else if (lastEntry.count > 0) {
4642 // Value has been removed
4643 ALOGV("%s: Session parameter tag id %d removed", __FUNCTION__, tag);
Emilian Peev4ec17882019-01-24 17:16:58 -08004644 updatedParams.erase(tag);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004645 updatesDetected = true;
4646 }
4647 }
4648
Emilian Peev4ec17882019-01-24 17:16:58 -08004649 bool reconfigureRequired;
4650 if (updatesDetected) {
4651 reconfigureRequired = mInterface->isReconfigurationRequired(mLatestSessionParams,
4652 updatedParams);
4653 mLatestSessionParams = updatedParams;
4654 } else {
4655 reconfigureRequired = false;
4656 }
4657
4658 return reconfigureRequired;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004659}
4660
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004661bool Camera3Device::RequestThread::threadLoop() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004662 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004663 status_t res;
Jayant Chowdhary37eca242019-11-18 08:55:56 -08004664 // Any function called from threadLoop() must not hold mInterfaceLock since
4665 // it could lead to deadlocks (disconnect() -> hold mInterfaceMutex -> wait for request thread
4666 // to finish -> request thread waits on mInterfaceMutex) http://b/143513518
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004667
4668 // Handle paused state.
4669 if (waitIfPaused()) {
4670 return true;
4671 }
4672
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004673 // Wait for the next batch of requests.
4674 waitForNextRequestBatch();
4675 if (mNextRequests.size() == 0) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004676 return true;
4677 }
4678
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004679 // Get the latest request ID, if any
4680 int latestRequestId;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004681 camera_metadata_entry_t requestIdEntry = mNextRequests[mNextRequests.size() - 1].
Emilian Peevaebbe412018-01-15 13:53:24 +00004682 captureRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_ID);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004683 if (requestIdEntry.count > 0) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004684 latestRequestId = requestIdEntry.data.i32[0];
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004685 } else {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004686 ALOGW("%s: Did not have android.request.id set in the request.", __FUNCTION__);
4687 latestRequestId = NAME_NOT_FOUND;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004688 }
4689
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004690 // 'mNextRequests' will at this point contain either a set of HFR batched requests
4691 // or a single request from streaming or burst. In either case the first element
4692 // should contain the latest camera settings that we need to check for any session
4693 // parameter updates.
Emilian Peevaebbe412018-01-15 13:53:24 +00004694 if (updateSessionParameters(mNextRequests[0].captureRequest->mSettingsList.begin()->metadata)) {
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004695 res = OK;
4696
4697 //Input stream buffers are already acquired at this point so an input stream
4698 //will not be able to move to idle state unless we force it.
4699 if (mNextRequests[0].captureRequest->mInputStream != nullptr) {
4700 res = mNextRequests[0].captureRequest->mInputStream->forceToIdle();
4701 if (res != OK) {
4702 ALOGE("%s: Failed to force idle input stream: %d", __FUNCTION__, res);
4703 cleanUpFailedRequests(/*sendRequestError*/ false);
4704 return false;
4705 }
4706 }
4707
4708 if (res == OK) {
Emilian Peev3bead5f2020-05-28 17:29:08 -07004709 sp<Camera3Device> parent = mParent.promote();
4710 if (parent != nullptr) {
4711 mReconfigured |= parent->reconfigureCamera(mLatestSessionParams, mStatusId);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004712 }
Emilian Peev3bead5f2020-05-28 17:29:08 -07004713 setPaused(false);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004714
4715 if (mNextRequests[0].captureRequest->mInputStream != nullptr) {
4716 mNextRequests[0].captureRequest->mInputStream->restoreConfiguredState();
4717 if (res != OK) {
4718 ALOGE("%s: Failed to restore configured input stream: %d", __FUNCTION__, res);
4719 cleanUpFailedRequests(/*sendRequestError*/ false);
4720 return false;
4721 }
4722 }
4723 }
4724 }
4725
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004726 // Prepare a batch of HAL requests and output buffers.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004727 res = prepareHalRequests();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004728 if (res == TIMED_OUT) {
4729 // Not a fatal error if getting output buffers time out.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004730 cleanUpFailedRequests(/*sendRequestError*/ true);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004731 // Check if any stream is abandoned.
4732 checkAndStopRepeatingRequest();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004733 return true;
4734 } else if (res != OK) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004735 cleanUpFailedRequests(/*sendRequestError*/ false);
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004736 return false;
4737 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004738
Zhijun Hecc27e112013-10-03 16:12:43 -07004739 // Inform waitUntilRequestProcessed thread of a new request ID
4740 {
4741 Mutex::Autolock al(mLatestRequestMutex);
4742
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004743 mLatestRequestId = latestRequestId;
Zhijun Hecc27e112013-10-03 16:12:43 -07004744 mLatestRequestSignal.signal();
4745 }
4746
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004747 // Submit a batch of requests to HAL.
4748 // Use flush lock only when submitting multilple requests in a batch.
4749 // TODO: The problem with flush lock is flush() will be blocked by process_capture_request()
4750 // which may take a long time to finish so synchronizing flush() and
4751 // process_capture_request() defeats the purpose of cancelling requests ASAP with flush().
4752 // For now, only synchronize for high speed recording and we should figure something out for
4753 // removing the synchronization.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004754 bool useFlushLock = mNextRequests.size() > 1;
Eino-Ville Talvala17a61ad2013-06-03 16:53:32 -07004755
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004756 if (useFlushLock) {
4757 mFlushLock.lock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004758 }
4759
Zhijun Hef0645c12016-08-02 00:58:11 -07004760 ALOGVV("%s: %d: submitting %zu requests in a batch.", __FUNCTION__, __LINE__,
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004761 mNextRequests.size());
Igor Murashkin1e479c02013-09-06 16:55:14 -07004762
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08004763 sp<Camera3Device> parent = mParent.promote();
4764 if (parent != nullptr) {
4765 parent->mRequestBufferSM.onSubmittingRequest();
4766 }
4767
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004768 bool submitRequestSuccess = false;
Shuzhen Wang686f6442017-06-20 16:16:04 -07004769 nsecs_t tRequestStart = systemTime(SYSTEM_TIME_MONOTONIC);
Yin-Chia Yeh11648852019-05-16 10:42:54 -07004770 submitRequestSuccess = sendRequestsBatch();
4771
Shuzhen Wang686f6442017-06-20 16:16:04 -07004772 nsecs_t tRequestEnd = systemTime(SYSTEM_TIME_MONOTONIC);
4773 mRequestLatency.add(tRequestStart, tRequestEnd);
Igor Murashkin1e479c02013-09-06 16:55:14 -07004774
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004775 if (useFlushLock) {
4776 mFlushLock.unlock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004777 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004778
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004779 // Unset as current request
4780 {
4781 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004782 mNextRequests.clear();
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004783 }
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004784 mRequestSubmittedSignal.signal();
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004785
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004786 return submitRequestSuccess;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004787}
4788
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004789status_t Camera3Device::RequestThread::prepareHalRequests() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004790 ATRACE_CALL();
4791
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07004792 bool batchedRequest = mNextRequests[0].captureRequest->mBatchSize > 1;
Shuzhen Wang4a472662017-02-26 23:29:04 -08004793 for (size_t i = 0; i < mNextRequests.size(); i++) {
4794 auto& nextRequest = mNextRequests.editItemAt(i);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004795 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
Emilian Peevf4816702020-04-03 15:44:51 -07004796 camera_capture_request_t* halRequest = &nextRequest.halRequest;
4797 Vector<camera_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004798
4799 // Prepare a request to HAL
4800 halRequest->frame_number = captureRequest->mResultExtras.frameNumber;
4801
4802 // Insert any queued triggers (before metadata is locked)
4803 status_t res = insertTriggers(captureRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004804 if (res < 0) {
4805 SET_ERR("RequestThread: Unable to insert triggers "
4806 "(capture request %d, HAL device: %s (%d)",
4807 halRequest->frame_number, strerror(-res), res);
4808 return INVALID_OPERATION;
4809 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07004810
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004811 int triggerCount = res;
4812 bool triggersMixedIn = (triggerCount > 0 || mPrevTriggers > 0);
4813 mPrevTriggers = triggerCount;
4814
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004815 bool rotateAndCropChanged = overrideAutoRotateAndCrop(captureRequest);
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004816 bool testPatternChanged = overrideTestPattern(captureRequest);
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004817
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004818 // If the request is the same as last, or we had triggers now or last time or
4819 // changing overrides this time
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004820 bool newRequest =
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004821 (mPrevRequest != captureRequest || triggersMixedIn ||
4822 rotateAndCropChanged || testPatternChanged) &&
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07004823 // Request settings are all the same within one batch, so only treat the first
4824 // request in a batch as new
Zhijun He54c36822018-07-18 09:33:39 -07004825 !(batchedRequest && i > 0);
Emilian Peev00420d22018-02-05 21:33:13 +00004826 if (newRequest) {
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08004827 std::set<std::string> cameraIdsWithZoom;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004828 /**
4829 * HAL workaround:
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004830 * Insert a fake trigger ID if a trigger is set but no trigger ID is
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004831 */
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004832 res = addFakeTriggerIds(captureRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004833 if (res != OK) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004834 SET_ERR("RequestThread: Unable to insert fake trigger IDs "
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004835 "(capture request %d, HAL device: %s (%d)",
4836 halRequest->frame_number, strerror(-res), res);
4837 return INVALID_OPERATION;
4838 }
4839
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07004840 {
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07004841 sp<Camera3Device> parent = mParent.promote();
4842 if (parent != nullptr) {
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -07004843 List<PhysicalCameraSettings>::iterator it;
4844 for (it = captureRequest->mSettingsList.begin();
4845 it != captureRequest->mSettingsList.end(); it++) {
Jayant Chowdhary9255ce02021-07-15 11:18:17 -07004846 if (parent->mUHRCropAndMeteringRegionMappers.find(it->cameraId) ==
4847 parent->mUHRCropAndMeteringRegionMappers.end()) {
4848 continue;
4849 }
4850
4851 if (!captureRequest->mUHRCropAndMeteringRegionsUpdated) {
4852 res = parent->mUHRCropAndMeteringRegionMappers[it->cameraId].
4853 updateCaptureRequest(&(it->metadata));
4854 if (res != OK) {
4855 SET_ERR("RequestThread: Unable to correct capture requests "
4856 "for scaler crop region and metering regions for request "
4857 "%d: %s (%d)", halRequest->frame_number, strerror(-res),
4858 res);
4859 return INVALID_OPERATION;
4860 }
4861 captureRequest->mUHRCropAndMeteringRegionsUpdated = true;
4862 }
4863 }
4864
4865 // Correct metadata regions for distortion correction if enabled
4866 for (it = captureRequest->mSettingsList.begin();
4867 it != captureRequest->mSettingsList.end(); it++) {
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -07004868 if (parent->mDistortionMappers.find(it->cameraId) ==
4869 parent->mDistortionMappers.end()) {
4870 continue;
4871 }
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07004872
4873 if (!captureRequest->mDistortionCorrectionUpdated) {
4874 res = parent->mDistortionMappers[it->cameraId].correctCaptureRequest(
4875 &(it->metadata));
4876 if (res != OK) {
4877 SET_ERR("RequestThread: Unable to correct capture requests "
4878 "for lens distortion for request %d: %s (%d)",
4879 halRequest->frame_number, strerror(-res), res);
4880 return INVALID_OPERATION;
4881 }
4882 captureRequest->mDistortionCorrectionUpdated = true;
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -07004883 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07004884 }
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08004885
4886 for (it = captureRequest->mSettingsList.begin();
4887 it != captureRequest->mSettingsList.end(); it++) {
4888 if (parent->mZoomRatioMappers.find(it->cameraId) ==
4889 parent->mZoomRatioMappers.end()) {
4890 continue;
4891 }
4892
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07004893 if (!captureRequest->mZoomRatioIs1x) {
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08004894 cameraIdsWithZoom.insert(it->cameraId);
4895 }
4896
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07004897 if (!captureRequest->mZoomRatioUpdated) {
4898 res = parent->mZoomRatioMappers[it->cameraId].updateCaptureRequest(
4899 &(it->metadata));
4900 if (res != OK) {
4901 SET_ERR("RequestThread: Unable to correct capture requests "
4902 "for zoom ratio for request %d: %s (%d)",
4903 halRequest->frame_number, strerror(-res), res);
4904 return INVALID_OPERATION;
4905 }
4906 captureRequest->mZoomRatioUpdated = true;
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08004907 }
4908 }
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07004909 if (captureRequest->mRotateAndCropAuto &&
4910 !captureRequest->mRotationAndCropUpdated) {
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004911 for (it = captureRequest->mSettingsList.begin();
4912 it != captureRequest->mSettingsList.end(); it++) {
4913 auto mapper = parent->mRotateAndCropMappers.find(it->cameraId);
4914 if (mapper != parent->mRotateAndCropMappers.end()) {
4915 res = mapper->second.updateCaptureRequest(&(it->metadata));
4916 if (res != OK) {
4917 SET_ERR("RequestThread: Unable to correct capture requests "
4918 "for rotate-and-crop for request %d: %s (%d)",
4919 halRequest->frame_number, strerror(-res), res);
4920 return INVALID_OPERATION;
4921 }
4922 }
4923 }
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07004924 captureRequest->mRotationAndCropUpdated = true;
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004925 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07004926 }
4927 }
4928
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004929 /**
4930 * The request should be presorted so accesses in HAL
4931 * are O(logn). Sidenote, sorting a sorted metadata is nop.
4932 */
Emilian Peevaebbe412018-01-15 13:53:24 +00004933 captureRequest->mSettingsList.begin()->metadata.sort();
4934 halRequest->settings = captureRequest->mSettingsList.begin()->metadata.getAndLock();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004935 mPrevRequest = captureRequest;
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08004936 mPrevCameraIdsWithZoom = cameraIdsWithZoom;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004937 ALOGVV("%s: Request settings are NEW", __FUNCTION__);
4938
4939 IF_ALOGV() {
4940 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
4941 find_camera_metadata_ro_entry(
4942 halRequest->settings,
4943 ANDROID_CONTROL_AF_TRIGGER,
4944 &e
4945 );
4946 if (e.count > 0) {
4947 ALOGV("%s: Request (frame num %d) had AF trigger 0x%x",
4948 __FUNCTION__,
4949 halRequest->frame_number,
4950 e.data.u8[0]);
4951 }
4952 }
4953 } else {
4954 // leave request.settings NULL to indicate 'reuse latest given'
4955 ALOGVV("%s: Request settings are REUSED",
4956 __FUNCTION__);
4957 }
4958
Emilian Peevaebbe412018-01-15 13:53:24 +00004959 if (captureRequest->mSettingsList.size() > 1) {
4960 halRequest->num_physcam_settings = captureRequest->mSettingsList.size() - 1;
4961 halRequest->physcam_id = new const char* [halRequest->num_physcam_settings];
Emilian Peev00420d22018-02-05 21:33:13 +00004962 if (newRequest) {
4963 halRequest->physcam_settings =
4964 new const camera_metadata* [halRequest->num_physcam_settings];
4965 } else {
4966 halRequest->physcam_settings = nullptr;
4967 }
Emilian Peevaebbe412018-01-15 13:53:24 +00004968 auto it = ++captureRequest->mSettingsList.begin();
4969 size_t i = 0;
4970 for (; it != captureRequest->mSettingsList.end(); it++, i++) {
4971 halRequest->physcam_id[i] = it->cameraId.c_str();
Emilian Peev00420d22018-02-05 21:33:13 +00004972 if (newRequest) {
4973 it->metadata.sort();
4974 halRequest->physcam_settings[i] = it->metadata.getAndLock();
4975 }
Emilian Peevaebbe412018-01-15 13:53:24 +00004976 }
4977 }
4978
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004979 uint32_t totalNumBuffers = 0;
4980
4981 // Fill in buffers
4982 if (captureRequest->mInputStream != NULL) {
4983 halRequest->input_buffer = &captureRequest->mInputBuffer;
Shuzhen Wang83bff122020-11-20 15:51:39 -08004984
4985 halRequest->input_width = captureRequest->mInputBufferSize.width;
4986 halRequest->input_height = captureRequest->mInputBufferSize.height;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004987 totalNumBuffers += 1;
4988 } else {
4989 halRequest->input_buffer = NULL;
4990 }
4991
Emilian Peevf4816702020-04-03 15:44:51 -07004992 outputBuffers->insertAt(camera_stream_buffer_t(), 0,
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004993 captureRequest->mOutputStreams.size());
4994 halRequest->output_buffers = outputBuffers->array();
Shuzhen Wang99080502021-03-07 21:08:20 -08004995 std::set<std::set<String8>> requestedPhysicalCameras;
Yin-Chia Yehb3a80b12018-09-04 12:13:05 -07004996
4997 sp<Camera3Device> parent = mParent.promote();
4998 if (parent == NULL) {
4999 // Should not happen, and nowhere to send errors to, so just log it
5000 CLOGE("RequestThread: Parent is gone");
5001 return INVALID_OPERATION;
5002 }
5003 nsecs_t waitDuration = kBaseGetBufferWait + parent->getExpectedInFlightDuration();
5004
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005005 SurfaceMap uniqueSurfaceIdMap;
Shuzhen Wang4a472662017-02-26 23:29:04 -08005006 for (size_t j = 0; j < captureRequest->mOutputStreams.size(); j++) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005007 sp<Camera3OutputStreamInterface> outputStream =
5008 captureRequest->mOutputStreams.editItemAt(j);
5009 int streamId = outputStream->getId();
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07005010
5011 // Prepare video buffers for high speed recording on the first video request.
5012 if (mPrepareVideoStream && outputStream->isVideoStream()) {
5013 // Only try to prepare video stream on the first video request.
5014 mPrepareVideoStream = false;
5015
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07005016 res = outputStream->startPrepare(Camera3StreamInterface::ALLOCATE_PIPELINE_MAX,
5017 false /*blockRequest*/);
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07005018 while (res == NOT_ENOUGH_DATA) {
5019 res = outputStream->prepareNextBuffer();
5020 }
5021 if (res != OK) {
5022 ALOGW("%s: Preparing video buffers for high speed failed: %s (%d)",
5023 __FUNCTION__, strerror(-res), res);
5024 outputStream->cancelPrepare();
5025 }
5026 }
5027
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005028 std::vector<size_t> uniqueSurfaceIds;
5029 res = outputStream->getUniqueSurfaceIds(
5030 captureRequest->mOutputSurfaces[streamId],
5031 &uniqueSurfaceIds);
5032 // INVALID_OPERATION is normal output for streams not supporting surfaceIds
5033 if (res != OK && res != INVALID_OPERATION) {
5034 ALOGE("%s: failed to query stream %d unique surface IDs",
5035 __FUNCTION__, streamId);
5036 return res;
5037 }
5038 if (res == OK) {
5039 uniqueSurfaceIdMap.insert({streamId, std::move(uniqueSurfaceIds)});
5040 }
5041
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07005042 if (mUseHalBufManager) {
Yin-Chia Yeh110342b2018-11-19 11:47:46 -08005043 if (outputStream->isAbandoned()) {
Yin-Chia Yeha1b56c82019-03-27 15:50:39 -07005044 ALOGV("%s: stream %d is abandoned, skipping request", __FUNCTION__, streamId);
Yin-Chia Yeh110342b2018-11-19 11:47:46 -08005045 return TIMED_OUT;
5046 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07005047 // HAL will request buffer through requestStreamBuffer API
Emilian Peevf4816702020-04-03 15:44:51 -07005048 camera_stream_buffer_t& buffer = outputBuffers->editItemAt(j);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07005049 buffer.stream = outputStream->asHalStream();
5050 buffer.buffer = nullptr;
Emilian Peevf4816702020-04-03 15:44:51 -07005051 buffer.status = CAMERA_BUFFER_STATUS_OK;
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07005052 buffer.acquire_fence = -1;
5053 buffer.release_fence = -1;
Emilian Peevf0348ae2021-01-13 13:39:45 -08005054 // Mark the output stream as unpreparable to block clients from calling
5055 // 'prepare' after this request reaches CameraHal and before the respective
5056 // buffers are requested.
5057 outputStream->markUnpreparable();
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07005058 } else {
5059 res = outputStream->getBuffer(&outputBuffers->editItemAt(j),
5060 waitDuration,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005061 captureRequest->mOutputSurfaces[streamId]);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07005062 if (res != OK) {
5063 // Can't get output buffer from gralloc queue - this could be due to
5064 // abandoned queue or other consumer misbehavior, so not a fatal
5065 // error
Yin-Chia Yeha1b56c82019-03-27 15:50:39 -07005066 ALOGV("RequestThread: Can't get output buffer, skipping request:"
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07005067 " %s (%d)", strerror(-res), res);
5068
5069 return TIMED_OUT;
5070 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005071 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08005072
5073 {
5074 sp<Camera3Device> parent = mParent.promote();
5075 if (parent != nullptr) {
5076 const String8& streamCameraId = outputStream->getPhysicalCameraId();
5077 for (const auto& settings : captureRequest->mSettingsList) {
5078 if ((streamCameraId.isEmpty() &&
5079 parent->getId() == settings.cameraId.c_str()) ||
5080 streamCameraId == settings.cameraId.c_str()) {
5081 outputStream->fireBufferRequestForFrameNumber(
5082 captureRequest->mResultExtras.frameNumber,
5083 settings.metadata);
5084 }
5085 }
5086 }
5087 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07005088
Shuzhen Wang5c22c152017-12-31 17:12:25 -08005089 String8 physicalCameraId = outputStream->getPhysicalCameraId();
Shuzhen Wang99080502021-03-07 21:08:20 -08005090 int32_t streamGroupId = outputStream->getHalStreamGroupId();
5091 if (streamGroupId != -1 && mGroupIdPhysicalCameraMap.count(streamGroupId) == 1) {
5092 requestedPhysicalCameras.insert(mGroupIdPhysicalCameraMap[streamGroupId]);
5093 } else if (!physicalCameraId.isEmpty()) {
5094 requestedPhysicalCameras.insert(std::set<String8>({physicalCameraId}));
Shuzhen Wang5c22c152017-12-31 17:12:25 -08005095 }
5096 halRequest->num_output_buffers++;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005097 }
5098 totalNumBuffers += halRequest->num_output_buffers;
5099
5100 // Log request in the in-flight queue
Shuzhen Wang4a472662017-02-26 23:29:04 -08005101 // If this request list is for constrained high speed recording (not
5102 // preview), and the current request is not the last one in the batch,
5103 // do not send callback to the app.
5104 bool hasCallback = true;
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07005105 if (batchedRequest && i != mNextRequests.size()-1) {
Shuzhen Wang4a472662017-02-26 23:29:04 -08005106 hasCallback = false;
5107 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01005108 bool isStillCapture = false;
Shuzhen Wang26abaf42018-08-28 15:41:20 -07005109 bool isZslCapture = false;
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08005110 const camera_metadata_t* settings = halRequest->settings;
5111 bool shouldUnlockSettings = false;
5112 if (settings == nullptr) {
5113 shouldUnlockSettings = true;
5114 settings = captureRequest->mSettingsList.begin()->metadata.getAndLock();
5115 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01005116 if (!mNextRequests[0].captureRequest->mSettingsList.begin()->metadata.isEmpty()) {
5117 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08005118 find_camera_metadata_ro_entry(settings, ANDROID_CONTROL_CAPTURE_INTENT, &e);
Emilian Peev9dd21f42018-08-03 13:39:29 +01005119 if ((e.count > 0) && (e.data.u8[0] == ANDROID_CONTROL_CAPTURE_INTENT_STILL_CAPTURE)) {
5120 isStillCapture = true;
5121 ATRACE_ASYNC_BEGIN("still capture", mNextRequests[i].halRequest.frame_number);
5122 }
Shuzhen Wang26abaf42018-08-28 15:41:20 -07005123
Emilian Peevaf8416e2021-02-04 17:52:43 -08005124 e = camera_metadata_ro_entry_t();
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08005125 find_camera_metadata_ro_entry(settings, ANDROID_CONTROL_ENABLE_ZSL, &e);
Shuzhen Wang26abaf42018-08-28 15:41:20 -07005126 if ((e.count > 0) && (e.data.u8[0] == ANDROID_CONTROL_ENABLE_ZSL_TRUE)) {
5127 isZslCapture = true;
5128 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01005129 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005130 res = parent->registerInFlight(halRequest->frame_number,
5131 totalNumBuffers, captureRequest->mResultExtras,
5132 /*hasInput*/halRequest->input_buffer != NULL,
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07005133 hasCallback,
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08005134 calculateMaxExpectedDuration(settings),
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005135 requestedPhysicalCameras, isStillCapture, isZslCapture,
5136 captureRequest->mRotateAndCropAuto, mPrevCameraIdsWithZoom,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005137 (mUseHalBufManager) ? uniqueSurfaceIdMap :
Shuzhen Wang316781a2020-08-18 18:11:01 -07005138 SurfaceMap{}, captureRequest->mRequestTimeNs);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005139 ALOGVV("%s: registered in flight requestId = %" PRId32 ", frameNumber = %" PRId64
5140 ", burstId = %" PRId32 ".",
5141 __FUNCTION__,
5142 captureRequest->mResultExtras.requestId, captureRequest->mResultExtras.frameNumber,
5143 captureRequest->mResultExtras.burstId);
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08005144
5145 if (shouldUnlockSettings) {
5146 captureRequest->mSettingsList.begin()->metadata.unlock(settings);
5147 }
5148
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005149 if (res != OK) {
5150 SET_ERR("RequestThread: Unable to register new in-flight request:"
5151 " %s (%d)", strerror(-res), res);
5152 return INVALID_OPERATION;
5153 }
5154 }
5155
5156 return OK;
5157}
5158
Igor Murashkin1e479c02013-09-06 16:55:14 -07005159CameraMetadata Camera3Device::RequestThread::getLatestRequest() const {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005160 ATRACE_CALL();
Igor Murashkin1e479c02013-09-06 16:55:14 -07005161 Mutex::Autolock al(mLatestRequestMutex);
5162
5163 ALOGV("RequestThread::%s", __FUNCTION__);
5164
5165 return mLatestRequest;
5166}
5167
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005168bool Camera3Device::RequestThread::isStreamPending(
5169 sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005170 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005171 Mutex::Autolock l(mRequestLock);
5172
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005173 for (const auto& nextRequest : mNextRequests) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005174 if (!nextRequest.submitted) {
5175 for (const auto& s : nextRequest.captureRequest->mOutputStreams) {
5176 if (stream == s) return true;
5177 }
5178 if (stream == nextRequest.captureRequest->mInputStream) return true;
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07005179 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07005180 }
5181
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005182 for (const auto& request : mRequestQueue) {
5183 for (const auto& s : request->mOutputStreams) {
5184 if (stream == s) return true;
5185 }
5186 if (stream == request->mInputStream) return true;
5187 }
5188
5189 for (const auto& request : mRepeatingRequests) {
5190 for (const auto& s : request->mOutputStreams) {
5191 if (stream == s) return true;
5192 }
5193 if (stream == request->mInputStream) return true;
5194 }
5195
5196 return false;
5197}
Jianing Weicb0652e2014-03-12 18:29:36 -07005198
Emilian Peev40ead602017-09-26 15:46:36 +01005199bool Camera3Device::RequestThread::isOutputSurfacePending(int streamId, size_t surfaceId) {
5200 ATRACE_CALL();
5201 Mutex::Autolock l(mRequestLock);
5202
5203 for (const auto& nextRequest : mNextRequests) {
5204 for (const auto& s : nextRequest.captureRequest->mOutputSurfaces) {
5205 if (s.first == streamId) {
5206 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
5207 if (it != s.second.end()) {
5208 return true;
5209 }
5210 }
5211 }
5212 }
5213
5214 for (const auto& request : mRequestQueue) {
5215 for (const auto& s : request->mOutputSurfaces) {
5216 if (s.first == streamId) {
5217 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
5218 if (it != s.second.end()) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005219 return true;
Emilian Peev40ead602017-09-26 15:46:36 +01005220 }
5221 }
5222 }
5223 }
5224
5225 for (const auto& request : mRepeatingRequests) {
5226 for (const auto& s : request->mOutputSurfaces) {
5227 if (s.first == streamId) {
5228 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
5229 if (it != s.second.end()) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005230 return true;
Emilian Peev40ead602017-09-26 15:46:36 +01005231 }
5232 }
5233 }
5234 }
5235
5236 return false;
5237}
5238
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07005239void Camera3Device::RequestThread::signalPipelineDrain(const std::vector<int>& streamIds) {
5240 if (!mUseHalBufManager) {
5241 ALOGE("%s called for camera device not supporting HAL buffer management", __FUNCTION__);
5242 return;
5243 }
5244
5245 Mutex::Autolock pl(mPauseLock);
5246 if (mPaused) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005247 mInterface->signalPipelineDrain(streamIds);
5248 return;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07005249 }
5250 // If request thread is still busy, wait until paused then notify HAL
5251 mNotifyPipelineDrain = true;
5252 mStreamIdsToBeDrained = streamIds;
5253}
5254
Yin-Chia Yehe52b8fa2020-07-28 00:17:58 -07005255void Camera3Device::RequestThread::resetPipelineDrain() {
5256 Mutex::Autolock pl(mPauseLock);
5257 mNotifyPipelineDrain = false;
5258 mStreamIdsToBeDrained.clear();
5259}
5260
Emilian Peevc0fe54c2020-03-11 14:05:07 -07005261void Camera3Device::RequestThread::clearPreviousRequest() {
5262 Mutex::Autolock l(mRequestLock);
5263 mPrevRequest.clear();
5264}
5265
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005266status_t Camera3Device::RequestThread::switchToOffline(
5267 const std::vector<int32_t>& streamsToKeep,
5268 /*out*/hardware::camera::device::V3_6::CameraOfflineSessionInfo* offlineSessionInfo,
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005269 /*out*/sp<hardware::camera::device::V3_6::ICameraOfflineSession>* offlineSession,
5270 /*out*/camera3::BufferRecords* bufferRecords) {
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005271 Mutex::Autolock l(mRequestLock);
5272 clearRepeatingRequestsLocked(/*lastFrameNumber*/nullptr);
5273
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005274 // Wait until request thread is fully stopped
5275 // TBD: check if request thread is being paused by other APIs (shouldn't be)
5276
5277 // We could also check for mRepeatingRequests.empty(), but the API interface
5278 // is serialized by Camera3Device::mInterfaceLock so no one should be able to submit any
5279 // new requests during the call; hence skip that check.
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005280 bool queueEmpty = mNextRequests.empty() && mRequestQueue.empty();
5281 while (!queueEmpty) {
5282 status_t res = mRequestSubmittedSignal.waitRelative(mRequestLock, kRequestSubmitTimeout);
5283 if (res == TIMED_OUT) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005284 ALOGE("%s: request thread failed to submit one request within timeout!", __FUNCTION__);
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005285 return res;
5286 } else if (res != OK) {
5287 ALOGE("%s: request thread failed to submit a request: %s (%d)!",
5288 __FUNCTION__, strerror(-res), res);
5289 return res;
5290 }
5291 queueEmpty = mNextRequests.empty() && mRequestQueue.empty();
5292 }
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005293
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005294 return mInterface->switchToOffline(
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005295 streamsToKeep, offlineSessionInfo, offlineSession, bufferRecords);
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005296}
5297
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005298status_t Camera3Device::RequestThread::setRotateAndCropAutoBehavior(
5299 camera_metadata_enum_android_scaler_rotate_and_crop_t rotateAndCropValue) {
5300 ATRACE_CALL();
5301 Mutex::Autolock l(mTriggerMutex);
5302 if (rotateAndCropValue == ANDROID_SCALER_ROTATE_AND_CROP_AUTO) {
5303 return BAD_VALUE;
5304 }
5305 mRotateAndCropOverride = rotateAndCropValue;
5306 return OK;
5307}
5308
Eino-Ville Talvala11afe4f2021-05-27 14:45:31 -07005309status_t Camera3Device::RequestThread::setCameraMute(int32_t muteMode) {
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005310 ATRACE_CALL();
5311 Mutex::Autolock l(mTriggerMutex);
Eino-Ville Talvala11afe4f2021-05-27 14:45:31 -07005312 if (muteMode != mCameraMute) {
5313 mCameraMute = muteMode;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005314 mCameraMuteChanged = true;
5315 }
5316 return OK;
5317}
5318
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07005319nsecs_t Camera3Device::getExpectedInFlightDuration() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005320 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005321 std::lock_guard<std::mutex> l(mInFlightLock);
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07005322 return mExpectedInflightDuration > kMinInflightDuration ?
5323 mExpectedInflightDuration : kMinInflightDuration;
5324}
5325
Emilian Peevaebbe412018-01-15 13:53:24 +00005326void Camera3Device::RequestThread::cleanupPhysicalSettings(sp<CaptureRequest> request,
Emilian Peevf4816702020-04-03 15:44:51 -07005327 camera_capture_request_t *halRequest) {
Emilian Peevaebbe412018-01-15 13:53:24 +00005328 if ((request == nullptr) || (halRequest == nullptr)) {
5329 ALOGE("%s: Invalid request!", __FUNCTION__);
5330 return;
5331 }
5332
5333 if (halRequest->num_physcam_settings > 0) {
5334 if (halRequest->physcam_id != nullptr) {
5335 delete [] halRequest->physcam_id;
5336 halRequest->physcam_id = nullptr;
5337 }
5338 if (halRequest->physcam_settings != nullptr) {
5339 auto it = ++(request->mSettingsList.begin());
5340 size_t i = 0;
5341 for (; it != request->mSettingsList.end(); it++, i++) {
5342 it->metadata.unlock(halRequest->physcam_settings[i]);
5343 }
5344 delete [] halRequest->physcam_settings;
5345 halRequest->physcam_settings = nullptr;
5346 }
5347 }
5348}
5349
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005350void Camera3Device::RequestThread::cleanUpFailedRequests(bool sendRequestError) {
5351 if (mNextRequests.empty()) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005352 return;
5353 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005354
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005355 for (auto& nextRequest : mNextRequests) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005356 // Skip the ones that have been submitted successfully.
5357 if (nextRequest.submitted) {
5358 continue;
5359 }
5360
5361 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
Emilian Peevf4816702020-04-03 15:44:51 -07005362 camera_capture_request_t* halRequest = &nextRequest.halRequest;
5363 Vector<camera_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005364
5365 if (halRequest->settings != NULL) {
Emilian Peevaebbe412018-01-15 13:53:24 +00005366 captureRequest->mSettingsList.begin()->metadata.unlock(halRequest->settings);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005367 }
5368
Emilian Peevaebbe412018-01-15 13:53:24 +00005369 cleanupPhysicalSettings(captureRequest, halRequest);
5370
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005371 if (captureRequest->mInputStream != NULL) {
Emilian Peevf4816702020-04-03 15:44:51 -07005372 captureRequest->mInputBuffer.status = CAMERA_BUFFER_STATUS_ERROR;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005373 captureRequest->mInputStream->returnInputBuffer(captureRequest->mInputBuffer);
5374 }
5375
Yin-Chia Yeh21cb47b2019-01-18 15:08:17 -08005376 // No output buffer can be returned when using HAL buffer manager
5377 if (!mUseHalBufManager) {
5378 for (size_t i = 0; i < halRequest->num_output_buffers; i++) {
5379 //Buffers that failed processing could still have
5380 //valid acquire fence.
5381 int acquireFence = (*outputBuffers)[i].acquire_fence;
5382 if (0 <= acquireFence) {
5383 close(acquireFence);
5384 outputBuffers->editItemAt(i).acquire_fence = -1;
5385 }
Emilian Peevf4816702020-04-03 15:44:51 -07005386 outputBuffers->editItemAt(i).status = CAMERA_BUFFER_STATUS_ERROR;
Yin-Chia Yeh21cb47b2019-01-18 15:08:17 -08005387 captureRequest->mOutputStreams.editItemAt(i)->returnBuffer((*outputBuffers)[i], 0,
5388 /*timestampIncreasing*/true, std::vector<size_t> (),
5389 captureRequest->mResultExtras.frameNumber);
Emilian Peevc58cf4c2017-05-11 17:23:41 +01005390 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005391 }
5392
5393 if (sendRequestError) {
5394 Mutex::Autolock l(mRequestLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005395 sp<NotificationListener> listener = mListener.promote();
5396 if (listener != NULL) {
5397 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08005398 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005399 captureRequest->mResultExtras);
5400 }
5401 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07005402
5403 // Remove yet-to-be submitted inflight request from inflightMap
5404 {
5405 sp<Camera3Device> parent = mParent.promote();
5406 if (parent != NULL) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005407 std::lock_guard<std::mutex> l(parent->mInFlightLock);
Shuzhen Wangcadb3302016-11-04 14:17:56 -07005408 ssize_t idx = parent->mInFlightMap.indexOfKey(captureRequest->mResultExtras.frameNumber);
5409 if (idx >= 0) {
5410 ALOGV("%s: Remove inflight request from queue: frameNumber %" PRId64,
5411 __FUNCTION__, captureRequest->mResultExtras.frameNumber);
5412 parent->removeInFlightMapEntryLocked(idx);
5413 }
5414 }
5415 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005416 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07005417
5418 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005419 mNextRequests.clear();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005420}
5421
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005422void Camera3Device::RequestThread::waitForNextRequestBatch() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005423 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005424 // Optimized a bit for the simple steady-state case (single repeating
5425 // request), to avoid putting that request in the queue temporarily.
5426 Mutex::Autolock l(mRequestLock);
5427
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005428 assert(mNextRequests.empty());
5429
5430 NextRequest nextRequest;
5431 nextRequest.captureRequest = waitForNextRequestLocked();
5432 if (nextRequest.captureRequest == nullptr) {
5433 return;
5434 }
5435
Emilian Peevf4816702020-04-03 15:44:51 -07005436 nextRequest.halRequest = camera_capture_request_t();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005437 nextRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005438 mNextRequests.add(nextRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005439
5440 // Wait for additional requests
5441 const size_t batchSize = nextRequest.captureRequest->mBatchSize;
5442
5443 for (size_t i = 1; i < batchSize; i++) {
5444 NextRequest additionalRequest;
5445 additionalRequest.captureRequest = waitForNextRequestLocked();
5446 if (additionalRequest.captureRequest == nullptr) {
5447 break;
5448 }
5449
Emilian Peevf4816702020-04-03 15:44:51 -07005450 additionalRequest.halRequest = camera_capture_request_t();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005451 additionalRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005452 mNextRequests.add(additionalRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005453 }
5454
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005455 if (mNextRequests.size() < batchSize) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08005456 ALOGE("RequestThread: only get %zu out of %zu requests. Skipping requests.",
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005457 mNextRequests.size(), batchSize);
5458 cleanUpFailedRequests(/*sendRequestError*/true);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005459 }
5460
5461 return;
5462}
5463
5464sp<Camera3Device::CaptureRequest>
5465 Camera3Device::RequestThread::waitForNextRequestLocked() {
5466 status_t res;
5467 sp<CaptureRequest> nextRequest;
5468
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005469 while (mRequestQueue.empty()) {
5470 if (!mRepeatingRequests.empty()) {
5471 // Always atomically enqueue all requests in a repeating request
5472 // list. Guarantees a complete in-sequence set of captures to
5473 // application.
5474 const RequestList &requests = mRepeatingRequests;
Shuzhen Wang316781a2020-08-18 18:11:01 -07005475 if (mFirstRepeating) {
5476 mFirstRepeating = false;
5477 } else {
5478 for (auto& request : requests) {
5479 // For repeating requests, override timestamp request using
5480 // the time a request is inserted into the request queue,
5481 // because the original repeating request will have an old
5482 // fixed timestamp.
5483 request->mRequestTimeNs = systemTime();
5484 }
5485 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005486 RequestList::const_iterator firstRequest =
5487 requests.begin();
5488 nextRequest = *firstRequest;
5489 mRequestQueue.insert(mRequestQueue.end(),
5490 ++firstRequest,
5491 requests.end());
5492 // No need to wait any longer
Jianing Weicb0652e2014-03-12 18:29:36 -07005493
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005494 mRepeatingLastFrameNumber = mFrameNumber + requests.size() - 1;
Jianing Weicb0652e2014-03-12 18:29:36 -07005495
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005496 break;
5497 }
5498
5499 res = mRequestSignal.waitRelative(mRequestLock, kRequestTimeout);
5500
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005501 if ((mRequestQueue.empty() && mRepeatingRequests.empty()) ||
5502 exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005503 Mutex::Autolock pl(mPauseLock);
5504 if (mPaused == false) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005505 ALOGV("%s: RequestThread: Going idle", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005506 mPaused = true;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07005507 if (mNotifyPipelineDrain) {
5508 mInterface->signalPipelineDrain(mStreamIdsToBeDrained);
5509 mNotifyPipelineDrain = false;
5510 mStreamIdsToBeDrained.clear();
5511 }
Yin-Chia Yehc300a072019-02-13 14:56:57 -08005512 // Let the tracker know
5513 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5514 if (statusTracker != 0) {
5515 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
5516 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005517 sp<Camera3Device> parent = mParent.promote();
5518 if (parent != nullptr) {
5519 parent->mRequestBufferSM.onRequestThreadPaused();
5520 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005521 }
5522 // Stop waiting for now and let thread management happen
5523 return NULL;
5524 }
5525 }
5526
5527 if (nextRequest == NULL) {
5528 // Don't have a repeating request already in hand, so queue
5529 // must have an entry now.
5530 RequestList::iterator firstRequest =
5531 mRequestQueue.begin();
5532 nextRequest = *firstRequest;
5533 mRequestQueue.erase(firstRequest);
Shuzhen Wang9d066012016-09-30 11:30:20 -07005534 if (mRequestQueue.empty() && !nextRequest->mRepeating) {
5535 sp<NotificationListener> listener = mListener.promote();
5536 if (listener != NULL) {
5537 listener->notifyRequestQueueEmpty();
5538 }
5539 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005540 }
5541
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005542 // In case we've been unpaused by setPaused clearing mDoPause, need to
5543 // update internal pause state (capture/setRepeatingRequest unpause
5544 // directly).
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005545 Mutex::Autolock pl(mPauseLock);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005546 if (mPaused) {
5547 ALOGV("%s: RequestThread: Unpaused", __FUNCTION__);
5548 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5549 if (statusTracker != 0) {
5550 statusTracker->markComponentActive(mStatusId);
5551 }
5552 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005553 mPaused = false;
5554
5555 // Check if we've reconfigured since last time, and reset the preview
5556 // request if so. Can't use 'NULL request == repeat' across configure calls.
5557 if (mReconfigured) {
5558 mPrevRequest.clear();
5559 mReconfigured = false;
5560 }
5561
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005562 if (nextRequest != NULL) {
5563 nextRequest->mResultExtras.frameNumber = mFrameNumber++;
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07005564 nextRequest->mResultExtras.afTriggerId = mCurrentAfTriggerId;
5565 nextRequest->mResultExtras.precaptureTriggerId = mCurrentPreCaptureTriggerId;
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07005566
5567 // Since RequestThread::clear() removes buffers from the input stream,
5568 // get the right buffer here before unlocking mRequestLock
5569 if (nextRequest->mInputStream != NULL) {
Shuzhen Wang83bff122020-11-20 15:51:39 -08005570 res = nextRequest->mInputStream->getInputBuffer(&nextRequest->mInputBuffer,
5571 &nextRequest->mInputBufferSize);
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07005572 if (res != OK) {
5573 // Can't get input buffer from gralloc queue - this could be due to
5574 // disconnected queue or other producer misbehavior, so not a fatal
5575 // error
5576 ALOGE("%s: Can't get input buffer, skipping request:"
5577 " %s (%d)", __FUNCTION__, strerror(-res), res);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005578
5579 sp<NotificationListener> listener = mListener.promote();
5580 if (listener != NULL) {
5581 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08005582 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07005583 nextRequest->mResultExtras);
5584 }
5585 return NULL;
5586 }
5587 }
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005588 }
Chien-Yu Chend196d612015-06-22 19:49:01 -07005589
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005590 return nextRequest;
5591}
5592
5593bool Camera3Device::RequestThread::waitIfPaused() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005594 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005595 status_t res;
5596 Mutex::Autolock l(mPauseLock);
5597 while (mDoPause) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005598 if (mPaused == false) {
5599 mPaused = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005600 ALOGV("%s: RequestThread: Paused", __FUNCTION__);
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07005601 if (mNotifyPipelineDrain) {
5602 mInterface->signalPipelineDrain(mStreamIdsToBeDrained);
5603 mNotifyPipelineDrain = false;
5604 mStreamIdsToBeDrained.clear();
5605 }
Yin-Chia Yehc300a072019-02-13 14:56:57 -08005606 // Let the tracker know
5607 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5608 if (statusTracker != 0) {
5609 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
5610 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005611 sp<Camera3Device> parent = mParent.promote();
5612 if (parent != nullptr) {
5613 parent->mRequestBufferSM.onRequestThreadPaused();
5614 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005615 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005616
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005617 res = mDoPauseSignal.waitRelative(mPauseLock, kRequestTimeout);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005618 if (res == TIMED_OUT || exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005619 return true;
5620 }
5621 }
5622 // We don't set mPaused to false here, because waitForNextRequest needs
5623 // to further manage the paused state in case of starvation.
5624 return false;
5625}
5626
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005627void Camera3Device::RequestThread::unpauseForNewRequests() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005628 ATRACE_CALL();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005629 // With work to do, mark thread as unpaused.
5630 // If paused by request (setPaused), don't resume, to avoid
5631 // extra signaling/waiting overhead to waitUntilPaused
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005632 mRequestSignal.signal();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005633 Mutex::Autolock p(mPauseLock);
5634 if (!mDoPause) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005635 ALOGV("%s: RequestThread: Going active", __FUNCTION__);
5636 if (mPaused) {
5637 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5638 if (statusTracker != 0) {
5639 statusTracker->markComponentActive(mStatusId);
5640 }
5641 }
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005642 mPaused = false;
5643 }
5644}
5645
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07005646void Camera3Device::RequestThread::setErrorState(const char *fmt, ...) {
5647 sp<Camera3Device> parent = mParent.promote();
5648 if (parent != NULL) {
5649 va_list args;
5650 va_start(args, fmt);
5651
5652 parent->setErrorStateV(fmt, args);
5653
5654 va_end(args);
5655 }
5656}
5657
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005658status_t Camera3Device::RequestThread::insertTriggers(
5659 const sp<CaptureRequest> &request) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005660 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005661 Mutex::Autolock al(mTriggerMutex);
5662
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07005663 sp<Camera3Device> parent = mParent.promote();
5664 if (parent == NULL) {
5665 CLOGE("RequestThread: Parent is gone");
5666 return DEAD_OBJECT;
5667 }
5668
Emilian Peevaebbe412018-01-15 13:53:24 +00005669 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005670 size_t count = mTriggerMap.size();
5671
5672 for (size_t i = 0; i < count; ++i) {
5673 RequestTrigger trigger = mTriggerMap.valueAt(i);
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005674 uint32_t tag = trigger.metadataTag;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07005675
5676 if (tag == ANDROID_CONTROL_AF_TRIGGER_ID || tag == ANDROID_CONTROL_AE_PRECAPTURE_ID) {
5677 bool isAeTrigger = (trigger.metadataTag == ANDROID_CONTROL_AE_PRECAPTURE_ID);
5678 uint32_t triggerId = static_cast<uint32_t>(trigger.entryValue);
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07005679 if (isAeTrigger) {
5680 request->mResultExtras.precaptureTriggerId = triggerId;
5681 mCurrentPreCaptureTriggerId = triggerId;
5682 } else {
5683 request->mResultExtras.afTriggerId = triggerId;
5684 mCurrentAfTriggerId = triggerId;
5685 }
Emilian Peev7e25e5e2017-04-07 15:48:49 +01005686 continue;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07005687 }
5688
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005689 camera_metadata_entry entry = metadata.find(tag);
5690
5691 if (entry.count > 0) {
5692 /**
5693 * Already has an entry for this trigger in the request.
5694 * Rewrite it with our requested trigger value.
5695 */
5696 RequestTrigger oldTrigger = trigger;
5697
5698 oldTrigger.entryValue = entry.data.u8[0];
5699
5700 mTriggerReplacedMap.add(tag, oldTrigger);
5701 } else {
5702 /**
5703 * More typical, no trigger entry, so we just add it
5704 */
5705 mTriggerRemovedMap.add(tag, trigger);
5706 }
5707
5708 status_t res;
5709
5710 switch (trigger.getTagType()) {
5711 case TYPE_BYTE: {
5712 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
5713 res = metadata.update(tag,
5714 &entryValue,
5715 /*count*/1);
5716 break;
5717 }
5718 case TYPE_INT32:
5719 res = metadata.update(tag,
5720 &trigger.entryValue,
5721 /*count*/1);
5722 break;
5723 default:
5724 ALOGE("%s: Type not supported: 0x%x",
5725 __FUNCTION__,
5726 trigger.getTagType());
5727 return INVALID_OPERATION;
5728 }
5729
5730 if (res != OK) {
5731 ALOGE("%s: Failed to update request metadata with trigger tag %s"
5732 ", value %d", __FUNCTION__, trigger.getTagName(),
5733 trigger.entryValue);
5734 return res;
5735 }
5736
5737 ALOGV("%s: Mixed in trigger %s, value %d", __FUNCTION__,
5738 trigger.getTagName(),
5739 trigger.entryValue);
5740 }
5741
5742 mTriggerMap.clear();
5743
5744 return count;
5745}
5746
5747status_t Camera3Device::RequestThread::removeTriggers(
5748 const sp<CaptureRequest> &request) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005749 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005750 Mutex::Autolock al(mTriggerMutex);
5751
Emilian Peevaebbe412018-01-15 13:53:24 +00005752 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005753
5754 /**
5755 * Replace all old entries with their old values.
5756 */
5757 for (size_t i = 0; i < mTriggerReplacedMap.size(); ++i) {
5758 RequestTrigger trigger = mTriggerReplacedMap.valueAt(i);
5759
5760 status_t res;
5761
5762 uint32_t tag = trigger.metadataTag;
5763 switch (trigger.getTagType()) {
5764 case TYPE_BYTE: {
5765 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
5766 res = metadata.update(tag,
5767 &entryValue,
5768 /*count*/1);
5769 break;
5770 }
5771 case TYPE_INT32:
5772 res = metadata.update(tag,
5773 &trigger.entryValue,
5774 /*count*/1);
5775 break;
5776 default:
5777 ALOGE("%s: Type not supported: 0x%x",
5778 __FUNCTION__,
5779 trigger.getTagType());
5780 return INVALID_OPERATION;
5781 }
5782
5783 if (res != OK) {
5784 ALOGE("%s: Failed to restore request metadata with trigger tag %s"
5785 ", trigger value %d", __FUNCTION__,
5786 trigger.getTagName(), trigger.entryValue);
5787 return res;
5788 }
5789 }
5790 mTriggerReplacedMap.clear();
5791
5792 /**
5793 * Remove all new entries.
5794 */
5795 for (size_t i = 0; i < mTriggerRemovedMap.size(); ++i) {
5796 RequestTrigger trigger = mTriggerRemovedMap.valueAt(i);
5797 status_t res = metadata.erase(trigger.metadataTag);
5798
5799 if (res != OK) {
5800 ALOGE("%s: Failed to erase metadata with trigger tag %s"
5801 ", trigger value %d", __FUNCTION__,
5802 trigger.getTagName(), trigger.entryValue);
5803 return res;
5804 }
5805 }
5806 mTriggerRemovedMap.clear();
5807
5808 return OK;
5809}
5810
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04005811status_t Camera3Device::RequestThread::addFakeTriggerIds(
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005812 const sp<CaptureRequest> &request) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08005813 // Trigger ID 0 had special meaning in the HAL2 spec, so avoid it here
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04005814 static const int32_t fakeTriggerId = 1;
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005815 status_t res;
5816
Emilian Peevaebbe412018-01-15 13:53:24 +00005817 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005818
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04005819 // If AF trigger is active, insert a fake AF trigger ID if none already
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005820 // exists
5821 camera_metadata_entry afTrigger = metadata.find(ANDROID_CONTROL_AF_TRIGGER);
5822 camera_metadata_entry afId = metadata.find(ANDROID_CONTROL_AF_TRIGGER_ID);
5823 if (afTrigger.count > 0 &&
5824 afTrigger.data.u8[0] != ANDROID_CONTROL_AF_TRIGGER_IDLE &&
5825 afId.count == 0) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04005826 res = metadata.update(ANDROID_CONTROL_AF_TRIGGER_ID, &fakeTriggerId, 1);
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005827 if (res != OK) return res;
5828 }
5829
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04005830 // If AE precapture trigger is active, insert a fake precapture trigger ID
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005831 // if none already exists
5832 camera_metadata_entry pcTrigger =
5833 metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER);
5834 camera_metadata_entry pcId = metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_ID);
5835 if (pcTrigger.count > 0 &&
5836 pcTrigger.data.u8[0] != ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_IDLE &&
5837 pcId.count == 0) {
5838 res = metadata.update(ANDROID_CONTROL_AE_PRECAPTURE_ID,
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04005839 &fakeTriggerId, 1);
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005840 if (res != OK) return res;
5841 }
5842
5843 return OK;
5844}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005845
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005846bool Camera3Device::RequestThread::overrideAutoRotateAndCrop(
5847 const sp<CaptureRequest> &request) {
5848 ATRACE_CALL();
5849
5850 if (request->mRotateAndCropAuto) {
5851 Mutex::Autolock l(mTriggerMutex);
5852 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
5853
5854 auto rotateAndCropEntry = metadata.find(ANDROID_SCALER_ROTATE_AND_CROP);
5855 if (rotateAndCropEntry.count > 0) {
5856 if (rotateAndCropEntry.data.u8[0] == mRotateAndCropOverride) {
5857 return false;
5858 } else {
5859 rotateAndCropEntry.data.u8[0] = mRotateAndCropOverride;
5860 return true;
5861 }
5862 } else {
5863 uint8_t rotateAndCrop_u8 = mRotateAndCropOverride;
5864 metadata.update(ANDROID_SCALER_ROTATE_AND_CROP,
5865 &rotateAndCrop_u8, 1);
5866 return true;
5867 }
5868 }
5869 return false;
5870}
5871
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005872bool Camera3Device::RequestThread::overrideTestPattern(
5873 const sp<CaptureRequest> &request) {
5874 ATRACE_CALL();
5875
5876 Mutex::Autolock l(mTriggerMutex);
5877
5878 bool changed = false;
5879
5880 int32_t testPatternMode = request->mOriginalTestPatternMode;
5881 int32_t testPatternData[4] = {
5882 request->mOriginalTestPatternData[0],
5883 request->mOriginalTestPatternData[1],
5884 request->mOriginalTestPatternData[2],
5885 request->mOriginalTestPatternData[3]
5886 };
5887
Eino-Ville Talvala11afe4f2021-05-27 14:45:31 -07005888 if (mCameraMute != ANDROID_SENSOR_TEST_PATTERN_MODE_OFF) {
5889 testPatternMode = mCameraMute;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005890 testPatternData[0] = 0;
5891 testPatternData[1] = 0;
5892 testPatternData[2] = 0;
5893 testPatternData[3] = 0;
5894 }
5895
5896 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
5897
5898 auto testPatternEntry = metadata.find(ANDROID_SENSOR_TEST_PATTERN_MODE);
5899 if (testPatternEntry.count > 0) {
5900 if (testPatternEntry.data.i32[0] != testPatternMode) {
5901 testPatternEntry.data.i32[0] = testPatternMode;
5902 changed = true;
5903 }
5904 } else {
5905 metadata.update(ANDROID_SENSOR_TEST_PATTERN_MODE,
5906 &testPatternMode, 1);
5907 changed = true;
5908 }
5909
5910 auto testPatternColor = metadata.find(ANDROID_SENSOR_TEST_PATTERN_DATA);
5911 if (testPatternColor.count > 0) {
5912 for (size_t i = 0; i < 4; i++) {
5913 if (testPatternColor.data.i32[i] != (int32_t)testPatternData[i]) {
5914 testPatternColor.data.i32[i] = testPatternData[i];
5915 changed = true;
5916 }
5917 }
5918 } else {
5919 metadata.update(ANDROID_SENSOR_TEST_PATTERN_DATA,
5920 (int32_t*)testPatternData, 4);
5921 changed = true;
5922 }
5923
5924 return changed;
5925}
5926
Cliff Wuc2ad9c82021-04-21 00:58:58 +08005927status_t Camera3Device::RequestThread::setHalInterface(
5928 sp<HalInterface> newHalInterface) {
5929 if (newHalInterface.get() == nullptr) {
5930 ALOGE("%s: The newHalInterface does not exist!", __FUNCTION__);
5931 return DEAD_OBJECT;
5932 }
5933
5934 mInterface = newHalInterface;
5935
5936 return OK;
5937}
5938
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005939/**
5940 * PreparerThread inner class methods
5941 */
5942
5943Camera3Device::PreparerThread::PreparerThread() :
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07005944 Thread(/*canCallJava*/false), mListener(nullptr),
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005945 mActive(false), mCancelNow(false), mCurrentMaxCount(0), mCurrentPrepareComplete(false) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005946}
5947
5948Camera3Device::PreparerThread::~PreparerThread() {
5949 Thread::requestExitAndWait();
5950 if (mCurrentStream != nullptr) {
5951 mCurrentStream->cancelPrepare();
5952 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
5953 mCurrentStream.clear();
5954 }
5955 clear();
5956}
5957
Ruben Brunkc78ac262015-08-13 17:58:46 -07005958status_t Camera3Device::PreparerThread::prepare(int maxCount, sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005959 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005960 status_t res;
5961
5962 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005963 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005964
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07005965 res = stream->startPrepare(maxCount, true /*blockRequest*/);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005966 if (res == OK) {
5967 // No preparation needed, fire listener right off
5968 ALOGV("%s: Stream %d already prepared", __FUNCTION__, stream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005969 if (listener != NULL) {
5970 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005971 }
5972 return OK;
5973 } else if (res != NOT_ENOUGH_DATA) {
5974 return res;
5975 }
5976
5977 // Need to prepare, start up thread if necessary
5978 if (!mActive) {
5979 // mRunning will change to false before the thread fully shuts down, so wait to be sure it
5980 // isn't running
5981 Thread::requestExitAndWait();
5982 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
5983 if (res != OK) {
5984 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__, res, strerror(-res));
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005985 if (listener != NULL) {
5986 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005987 }
5988 return res;
5989 }
5990 mCancelNow = false;
5991 mActive = true;
5992 ALOGV("%s: Preparer stream started", __FUNCTION__);
5993 }
5994
5995 // queue up the work
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005996 mPendingStreams.emplace(maxCount, stream);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005997 ALOGV("%s: Stream %d queued for preparing", __FUNCTION__, stream->getId());
5998
5999 return OK;
6000}
6001
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006002void Camera3Device::PreparerThread::pause() {
6003 ATRACE_CALL();
6004
6005 Mutex::Autolock l(mLock);
6006
6007 std::unordered_map<int, sp<camera3::Camera3StreamInterface> > pendingStreams;
6008 pendingStreams.insert(mPendingStreams.begin(), mPendingStreams.end());
6009 sp<camera3::Camera3StreamInterface> currentStream = mCurrentStream;
6010 int currentMaxCount = mCurrentMaxCount;
6011 mPendingStreams.clear();
6012 mCancelNow = true;
6013 while (mActive) {
6014 auto res = mThreadActiveSignal.waitRelative(mLock, kActiveTimeout);
6015 if (res == TIMED_OUT) {
6016 ALOGE("%s: Timed out waiting on prepare thread!", __FUNCTION__);
6017 return;
6018 } else if (res != OK) {
6019 ALOGE("%s: Encountered an error: %d waiting on prepare thread!", __FUNCTION__, res);
6020 return;
6021 }
6022 }
6023
6024 //Check whether the prepare thread was able to complete the current
6025 //stream. In case work is still pending emplace it along with the rest
6026 //of the streams in the pending list.
6027 if (currentStream != nullptr) {
6028 if (!mCurrentPrepareComplete) {
6029 pendingStreams.emplace(currentMaxCount, currentStream);
6030 }
6031 }
6032
6033 mPendingStreams.insert(pendingStreams.begin(), pendingStreams.end());
6034 for (const auto& it : mPendingStreams) {
6035 it.second->cancelPrepare();
6036 }
6037}
6038
6039status_t Camera3Device::PreparerThread::resume() {
6040 ATRACE_CALL();
6041 status_t res;
6042
6043 Mutex::Autolock l(mLock);
6044 sp<NotificationListener> listener = mListener.promote();
6045
6046 if (mActive) {
6047 ALOGE("%s: Trying to resume an already active prepare thread!", __FUNCTION__);
6048 return NO_INIT;
6049 }
6050
6051 auto it = mPendingStreams.begin();
6052 for (; it != mPendingStreams.end();) {
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07006053 res = it->second->startPrepare(it->first, true /*blockRequest*/);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006054 if (res == OK) {
6055 if (listener != NULL) {
6056 listener->notifyPrepared(it->second->getId());
6057 }
6058 it = mPendingStreams.erase(it);
6059 } else if (res != NOT_ENOUGH_DATA) {
6060 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__,
6061 res, strerror(-res));
6062 it = mPendingStreams.erase(it);
6063 } else {
6064 it++;
6065 }
6066 }
6067
6068 if (mPendingStreams.empty()) {
6069 return OK;
6070 }
6071
6072 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
6073 if (res != OK) {
6074 ALOGE("%s: Unable to start preparer stream: %d (%s)",
6075 __FUNCTION__, res, strerror(-res));
6076 return res;
6077 }
6078 mCancelNow = false;
6079 mActive = true;
6080 ALOGV("%s: Preparer stream started", __FUNCTION__);
6081
6082 return OK;
6083}
6084
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006085status_t Camera3Device::PreparerThread::clear() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07006086 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006087 Mutex::Autolock l(mLock);
6088
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006089 for (const auto& it : mPendingStreams) {
6090 it.second->cancelPrepare();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006091 }
6092 mPendingStreams.clear();
6093 mCancelNow = true;
6094
6095 return OK;
6096}
6097
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006098void Camera3Device::PreparerThread::setNotificationListener(wp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07006099 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006100 Mutex::Autolock l(mLock);
6101 mListener = listener;
6102}
6103
6104bool Camera3Device::PreparerThread::threadLoop() {
6105 status_t res;
6106 {
6107 Mutex::Autolock l(mLock);
6108 if (mCurrentStream == nullptr) {
6109 // End thread if done with work
6110 if (mPendingStreams.empty()) {
6111 ALOGV("%s: Preparer stream out of work", __FUNCTION__);
6112 // threadLoop _must not_ re-acquire mLock after it sets mActive to false; would
6113 // cause deadlock with prepare()'s requestExitAndWait triggered by !mActive.
6114 mActive = false;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006115 mThreadActiveSignal.signal();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006116 return false;
6117 }
6118
6119 // Get next stream to prepare
6120 auto it = mPendingStreams.begin();
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006121 mCurrentStream = it->second;
6122 mCurrentMaxCount = it->first;
6123 mCurrentPrepareComplete = false;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006124 mPendingStreams.erase(it);
6125 ATRACE_ASYNC_BEGIN("stream prepare", mCurrentStream->getId());
6126 ALOGV("%s: Preparing stream %d", __FUNCTION__, mCurrentStream->getId());
6127 } else if (mCancelNow) {
6128 mCurrentStream->cancelPrepare();
6129 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
6130 ALOGV("%s: Cancelling stream %d prepare", __FUNCTION__, mCurrentStream->getId());
6131 mCurrentStream.clear();
6132 mCancelNow = false;
6133 return true;
6134 }
6135 }
6136
6137 res = mCurrentStream->prepareNextBuffer();
6138 if (res == NOT_ENOUGH_DATA) return true;
6139 if (res != OK) {
6140 // Something bad happened; try to recover by cancelling prepare and
6141 // signalling listener anyway
6142 ALOGE("%s: Stream %d returned error %d (%s) during prepare", __FUNCTION__,
6143 mCurrentStream->getId(), res, strerror(-res));
6144 mCurrentStream->cancelPrepare();
6145 }
6146
6147 // This stream has finished, notify listener
6148 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006149 sp<NotificationListener> listener = mListener.promote();
6150 if (listener != NULL) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006151 ALOGV("%s: Stream %d prepare done, signaling listener", __FUNCTION__,
6152 mCurrentStream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006153 listener->notifyPrepared(mCurrentStream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006154 }
6155
6156 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
6157 mCurrentStream.clear();
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006158 mCurrentPrepareComplete = true;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006159
6160 return true;
6161}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07006162
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006163status_t Camera3Device::RequestBufferStateMachine::initialize(
6164 sp<camera3::StatusTracker> statusTracker) {
6165 if (statusTracker == nullptr) {
6166 ALOGE("%s: statusTracker is null", __FUNCTION__);
6167 return BAD_VALUE;
6168 }
6169
6170 std::lock_guard<std::mutex> lock(mLock);
6171 mStatusTracker = statusTracker;
Yin-Chia Yeh87b3ec02019-06-03 10:44:39 -07006172 mRequestBufferStatusId = statusTracker->addComponent("BufferRequestSM");
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006173 return OK;
6174}
6175
6176bool Camera3Device::RequestBufferStateMachine::startRequestBuffer() {
6177 std::lock_guard<std::mutex> lock(mLock);
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08006178 if (mStatus == RB_STATUS_READY || mStatus == RB_STATUS_PENDING_STOP) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006179 mRequestBufferOngoing = true;
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08006180 notifyTrackerLocked(/*active*/true);
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006181 return true;
6182 }
6183 return false;
6184}
6185
6186void Camera3Device::RequestBufferStateMachine::endRequestBuffer() {
6187 std::lock_guard<std::mutex> lock(mLock);
6188 if (!mRequestBufferOngoing) {
6189 ALOGE("%s called without a successful startRequestBuffer call first!", __FUNCTION__);
6190 return;
6191 }
6192 mRequestBufferOngoing = false;
6193 if (mStatus == RB_STATUS_PENDING_STOP) {
6194 checkSwitchToStopLocked();
6195 }
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08006196 notifyTrackerLocked(/*active*/false);
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006197}
6198
6199void Camera3Device::RequestBufferStateMachine::onStreamsConfigured() {
6200 std::lock_guard<std::mutex> lock(mLock);
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006201 mSwitchedToOffline = false;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006202 mStatus = RB_STATUS_READY;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006203 return;
6204}
6205
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08006206void Camera3Device::RequestBufferStateMachine::onSubmittingRequest() {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006207 std::lock_guard<std::mutex> lock(mLock);
6208 mRequestThreadPaused = false;
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08006209 // inflight map register actually happens in prepareHalRequest now, but it is close enough
6210 // approximation.
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006211 mInflightMapEmpty = false;
6212 if (mStatus == RB_STATUS_STOPPED) {
6213 mStatus = RB_STATUS_READY;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006214 }
6215 return;
6216}
6217
6218void Camera3Device::RequestBufferStateMachine::onRequestThreadPaused() {
6219 std::lock_guard<std::mutex> lock(mLock);
6220 mRequestThreadPaused = true;
6221 if (mStatus == RB_STATUS_PENDING_STOP) {
6222 checkSwitchToStopLocked();
6223 }
6224 return;
6225}
6226
6227void Camera3Device::RequestBufferStateMachine::onInflightMapEmpty() {
6228 std::lock_guard<std::mutex> lock(mLock);
6229 mInflightMapEmpty = true;
6230 if (mStatus == RB_STATUS_PENDING_STOP) {
6231 checkSwitchToStopLocked();
6232 }
6233 return;
6234}
6235
6236void Camera3Device::RequestBufferStateMachine::onWaitUntilIdle() {
6237 std::lock_guard<std::mutex> lock(mLock);
6238 if (!checkSwitchToStopLocked()) {
6239 mStatus = RB_STATUS_PENDING_STOP;
6240 }
6241 return;
6242}
6243
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006244bool Camera3Device::RequestBufferStateMachine::onSwitchToOfflineSuccess() {
6245 std::lock_guard<std::mutex> lock(mLock);
6246 if (mRequestBufferOngoing) {
6247 ALOGE("%s: HAL must not be requesting buffer after HAL returns switchToOffline!",
6248 __FUNCTION__);
6249 return false;
6250 }
6251 mSwitchedToOffline = true;
6252 mInflightMapEmpty = true;
6253 mRequestThreadPaused = true;
6254 mStatus = RB_STATUS_STOPPED;
6255 return true;
6256}
6257
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006258void Camera3Device::RequestBufferStateMachine::notifyTrackerLocked(bool active) {
6259 sp<StatusTracker> statusTracker = mStatusTracker.promote();
6260 if (statusTracker != nullptr) {
6261 if (active) {
6262 statusTracker->markComponentActive(mRequestBufferStatusId);
6263 } else {
6264 statusTracker->markComponentIdle(mRequestBufferStatusId, Fence::NO_FENCE);
6265 }
6266 }
6267}
6268
6269bool Camera3Device::RequestBufferStateMachine::checkSwitchToStopLocked() {
6270 if (mInflightMapEmpty && mRequestThreadPaused && !mRequestBufferOngoing) {
6271 mStatus = RB_STATUS_STOPPED;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006272 return true;
6273 }
6274 return false;
6275}
6276
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006277bool Camera3Device::startRequestBuffer() {
6278 return mRequestBufferSM.startRequestBuffer();
6279}
Shuzhen Wang268a1362018-10-16 16:32:59 -07006280
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006281void Camera3Device::endRequestBuffer() {
6282 mRequestBufferSM.endRequestBuffer();
6283}
Shuzhen Wang268a1362018-10-16 16:32:59 -07006284
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006285nsecs_t Camera3Device::getWaitDuration() {
6286 return kBaseGetBufferWait + getExpectedInFlightDuration();
6287}
Shuzhen Wang268a1362018-10-16 16:32:59 -07006288
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006289void Camera3Device::getInflightBufferKeys(std::vector<std::pair<int32_t, int32_t>>* out) {
6290 mInterface->getInflightBufferKeys(out);
6291}
Shuzhen Wang268a1362018-10-16 16:32:59 -07006292
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006293void Camera3Device::getInflightRequestBufferKeys(std::vector<uint64_t>* out) {
6294 mInterface->getInflightRequestBufferKeys(out);
6295}
Shuzhen Wang268a1362018-10-16 16:32:59 -07006296
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006297std::vector<sp<Camera3StreamInterface>> Camera3Device::getAllStreams() {
6298 std::vector<sp<Camera3StreamInterface>> ret;
6299 bool hasInputStream = mInputStream != nullptr;
6300 ret.reserve(mOutputStreams.size() + mDeletedStreams.size() + ((hasInputStream) ? 1 : 0));
6301 if (hasInputStream) {
6302 ret.push_back(mInputStream);
Shuzhen Wang268a1362018-10-16 16:32:59 -07006303 }
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006304 for (size_t i = 0; i < mOutputStreams.size(); i++) {
6305 ret.push_back(mOutputStreams[i]);
6306 }
6307 for (size_t i = 0; i < mDeletedStreams.size(); i++) {
6308 ret.push_back(mDeletedStreams[i]);
6309 }
6310 return ret;
Shuzhen Wang268a1362018-10-16 16:32:59 -07006311}
6312
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006313status_t Camera3Device::switchToOffline(
6314 const std::vector<int32_t>& streamsToKeep,
6315 /*out*/ sp<CameraOfflineSessionBase>* session) {
6316 ATRACE_CALL();
6317 if (session == nullptr) {
6318 ALOGE("%s: session must not be null", __FUNCTION__);
6319 return BAD_VALUE;
6320 }
6321
6322 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006323
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006324 bool hasInputStream = mInputStream != nullptr;
6325 int32_t inputStreamId = hasInputStream ? mInputStream->getId() : -1;
6326 bool inputStreamSupportsOffline = hasInputStream ?
6327 mInputStream->getOfflineProcessingSupport() : false;
6328 auto outputStreamIds = mOutputStreams.getStreamIds();
6329 auto streamIds = outputStreamIds;
6330 if (hasInputStream) {
6331 streamIds.push_back(mInputStream->getId());
6332 }
6333
6334 // Check all streams in streamsToKeep supports offline mode
6335 for (auto id : streamsToKeep) {
6336 if (std::find(streamIds.begin(), streamIds.end(), id) == streamIds.end()) {
6337 ALOGE("%s: Unknown stream ID %d", __FUNCTION__, id);
6338 return BAD_VALUE;
6339 } else if (id == inputStreamId) {
6340 if (!inputStreamSupportsOffline) {
6341 ALOGE("%s: input stream %d cannot be switched to offline",
6342 __FUNCTION__, id);
6343 return BAD_VALUE;
6344 }
6345 } else {
6346 sp<camera3::Camera3OutputStreamInterface> stream = mOutputStreams.get(id);
6347 if (!stream->getOfflineProcessingSupport()) {
6348 ALOGE("%s: output stream %d cannot be switched to offline",
6349 __FUNCTION__, id);
6350 return BAD_VALUE;
6351 }
6352 }
6353 }
6354
6355 // TODO: block surface sharing and surface group streams until we can support them
6356
6357 // Stop repeating request, wait until all remaining requests are submitted, then call into
6358 // HAL switchToOffline
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006359 hardware::camera::device::V3_6::CameraOfflineSessionInfo offlineSessionInfo;
6360 sp<hardware::camera::device::V3_6::ICameraOfflineSession> offlineSession;
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006361 camera3::BufferRecords bufferRecords;
6362 status_t ret = mRequestThread->switchToOffline(
6363 streamsToKeep, &offlineSessionInfo, &offlineSession, &bufferRecords);
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006364
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006365 if (ret != OK) {
6366 SET_ERR("Switch to offline failed: %s (%d)", strerror(-ret), ret);
6367 return ret;
6368 }
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006369
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006370 bool succ = mRequestBufferSM.onSwitchToOfflineSuccess();
6371 if (!succ) {
6372 SET_ERR("HAL must not be calling requestStreamBuffers call");
6373 // TODO: block ALL callbacks from HAL till app configured new streams?
6374 return UNKNOWN_ERROR;
6375 }
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006376
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006377 // Verify offlineSessionInfo
6378 std::vector<int32_t> offlineStreamIds;
6379 offlineStreamIds.reserve(offlineSessionInfo.offlineStreams.size());
6380 for (auto offlineStream : offlineSessionInfo.offlineStreams) {
6381 // verify stream IDs
6382 int32_t id = offlineStream.id;
6383 if (std::find(streamIds.begin(), streamIds.end(), id) == streamIds.end()) {
6384 SET_ERR("stream ID %d not found!", id);
6385 return UNKNOWN_ERROR;
6386 }
6387
6388 // When not using HAL buf manager, only allow streams requested by app to be preserved
6389 if (!mUseHalBufManager) {
6390 if (std::find(streamsToKeep.begin(), streamsToKeep.end(), id) == streamsToKeep.end()) {
6391 SET_ERR("stream ID %d must not be switched to offline!", id);
6392 return UNKNOWN_ERROR;
6393 }
6394 }
6395
6396 offlineStreamIds.push_back(id);
6397 sp<Camera3StreamInterface> stream = (id == inputStreamId) ?
6398 static_cast<sp<Camera3StreamInterface>>(mInputStream) :
6399 static_cast<sp<Camera3StreamInterface>>(mOutputStreams.get(id));
6400 // Verify number of outstanding buffers
6401 if (stream->getOutstandingBuffersCount() != offlineStream.numOutstandingBuffers) {
6402 SET_ERR("Offline stream %d # of remaining buffer mismatch: (%zu,%d) (service/HAL)",
6403 id, stream->getOutstandingBuffersCount(), offlineStream.numOutstandingBuffers);
6404 return UNKNOWN_ERROR;
6405 }
6406 }
6407
6408 // Verify all streams to be deleted don't have any outstanding buffers
6409 if (hasInputStream && std::find(offlineStreamIds.begin(), offlineStreamIds.end(),
6410 inputStreamId) == offlineStreamIds.end()) {
6411 if (mInputStream->hasOutstandingBuffers()) {
6412 SET_ERR("Input stream %d still has %zu outstanding buffer!",
6413 inputStreamId, mInputStream->getOutstandingBuffersCount());
6414 return UNKNOWN_ERROR;
6415 }
6416 }
6417
6418 for (const auto& outStreamId : outputStreamIds) {
6419 if (std::find(offlineStreamIds.begin(), offlineStreamIds.end(),
6420 outStreamId) == offlineStreamIds.end()) {
6421 auto outStream = mOutputStreams.get(outStreamId);
6422 if (outStream->hasOutstandingBuffers()) {
6423 SET_ERR("Output stream %d still has %zu outstanding buffer!",
6424 outStreamId, outStream->getOutstandingBuffersCount());
6425 return UNKNOWN_ERROR;
6426 }
6427 }
6428 }
6429
6430 InFlightRequestMap offlineReqs;
6431 // Verify inflight requests and their pending buffers
6432 {
6433 std::lock_guard<std::mutex> l(mInFlightLock);
6434 for (auto offlineReq : offlineSessionInfo.offlineRequests) {
6435 int idx = mInFlightMap.indexOfKey(offlineReq.frameNumber);
6436 if (idx == NAME_NOT_FOUND) {
6437 SET_ERR("Offline request frame number %d not found!", offlineReq.frameNumber);
6438 return UNKNOWN_ERROR;
6439 }
6440
6441 const auto& inflightReq = mInFlightMap.valueAt(idx);
6442 // TODO: check specific stream IDs
6443 size_t numBuffersLeft = static_cast<size_t>(inflightReq.numBuffersLeft);
6444 if (numBuffersLeft != offlineReq.pendingStreams.size()) {
6445 SET_ERR("Offline request # of remaining buffer mismatch: (%d,%d) (service/HAL)",
6446 inflightReq.numBuffersLeft, offlineReq.pendingStreams.size());
6447 return UNKNOWN_ERROR;
6448 }
6449 offlineReqs.add(offlineReq.frameNumber, inflightReq);
6450 }
6451 }
6452
6453 // Create Camera3OfflineSession and transfer object ownership
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006454 // (streams, inflight requests, buffer caches)
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006455 camera3::StreamSet offlineStreamSet;
6456 sp<camera3::Camera3Stream> inputStream;
6457 for (auto offlineStream : offlineSessionInfo.offlineStreams) {
6458 int32_t id = offlineStream.id;
6459 if (mInputStream != nullptr && id == mInputStream->getId()) {
6460 inputStream = mInputStream;
6461 } else {
6462 offlineStreamSet.add(id, mOutputStreams.get(id));
6463 }
6464 }
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006465
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006466 // TODO: check if we need to lock before copying states
6467 // though technically no other thread should be talking to Camera3Device at this point
6468 Camera3OfflineStates offlineStates(
6469 mTagMonitor, mVendorTagId, mUseHalBufManager, mNeedFixupMonochromeTags,
Shuzhen Wangb7b42652020-05-07 11:59:02 -07006470 mUsePartialResult, mNumPartialResults, mLastCompletedRegularFrameNumber,
6471 mLastCompletedReprocessFrameNumber, mLastCompletedZslFrameNumber,
6472 mNextResultFrameNumber, mNextReprocessResultFrameNumber,
6473 mNextZslStillResultFrameNumber, mNextShutterFrameNumber,
6474 mNextReprocessShutterFrameNumber, mNextZslStillShutterFrameNumber,
6475 mDeviceInfo, mPhysicalDeviceInfoMap, mDistortionMappers,
6476 mZoomRatioMappers, mRotateAndCropMappers);
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006477
6478 *session = new Camera3OfflineSession(mId, inputStream, offlineStreamSet,
6479 std::move(bufferRecords), offlineReqs, offlineStates, offlineSession);
6480
6481 // Delete all streams that has been transferred to offline session
6482 Mutex::Autolock l(mLock);
6483 for (auto offlineStream : offlineSessionInfo.offlineStreams) {
6484 int32_t id = offlineStream.id;
6485 if (mInputStream != nullptr && id == mInputStream->getId()) {
6486 mInputStream.clear();
6487 } else {
6488 mOutputStreams.remove(id);
6489 }
6490 }
6491
6492 // disconnect all other streams and switch to UNCONFIGURED state
6493 if (mInputStream != nullptr) {
6494 ret = mInputStream->disconnect();
6495 if (ret != OK) {
6496 SET_ERR_L("disconnect input stream failed!");
6497 return UNKNOWN_ERROR;
6498 }
6499 }
6500
6501 for (auto streamId : mOutputStreams.getStreamIds()) {
6502 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
6503 ret = stream->disconnect();
6504 if (ret != OK) {
6505 SET_ERR_L("disconnect output stream %d failed!", streamId);
6506 return UNKNOWN_ERROR;
6507 }
6508 }
6509
6510 mInputStream.clear();
6511 mOutputStreams.clear();
6512 mNeedConfig = true;
6513 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
6514 mOperatingMode = NO_MODE;
6515 mIsConstrainedHighSpeedConfiguration = false;
Emilian Peevc0fe54c2020-03-11 14:05:07 -07006516 mRequestThread->clearPreviousRequest();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006517
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006518 return OK;
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006519 // TO be done by CameraDeviceClient/Camera3OfflineSession
6520 // register the offline client to camera service
6521 // Setup result passthing threads etc
6522 // Initialize offline session so HAL can start sending callback to it (result Fmq)
6523 // TODO: check how many onIdle callback will be sent
6524 // Java side to make sure the CameraCaptureSession is properly closed
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006525}
6526
Emilian Peevcc0b7952020-01-07 13:54:47 -08006527void Camera3Device::getOfflineStreamIds(std::vector<int> *offlineStreamIds) {
6528 ATRACE_CALL();
6529
6530 if (offlineStreamIds == nullptr) {
6531 return;
6532 }
6533
6534 Mutex::Autolock il(mInterfaceLock);
6535
6536 auto streamIds = mOutputStreams.getStreamIds();
6537 bool hasInputStream = mInputStream != nullptr;
6538 if (hasInputStream && mInputStream->getOfflineProcessingSupport()) {
6539 offlineStreamIds->push_back(mInputStream->getId());
6540 }
6541
6542 for (const auto & streamId : streamIds) {
6543 sp<camera3::Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
6544 // Streams that use the camera buffer manager are currently not supported in
6545 // offline mode
6546 if (stream->getOfflineProcessingSupport() &&
6547 (stream->getStreamSetId() == CAMERA3_STREAM_SET_ID_INVALID)) {
6548 offlineStreamIds->push_back(streamId);
6549 }
6550 }
6551}
6552
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08006553status_t Camera3Device::setRotateAndCropAutoBehavior(
6554 camera_metadata_enum_android_scaler_rotate_and_crop_t rotateAndCropValue) {
6555 ATRACE_CALL();
6556 Mutex::Autolock il(mInterfaceLock);
6557 Mutex::Autolock l(mLock);
6558 if (mRequestThread == nullptr) {
6559 return INVALID_OPERATION;
6560 }
6561 return mRequestThread->setRotateAndCropAutoBehavior(rotateAndCropValue);
6562}
6563
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08006564bool Camera3Device::supportsCameraMute() {
6565 Mutex::Autolock il(mInterfaceLock);
6566 Mutex::Autolock l(mLock);
6567
6568 return mSupportCameraMute;
6569}
6570
6571status_t Camera3Device::setCameraMute(bool enabled) {
6572 ATRACE_CALL();
6573 Mutex::Autolock il(mInterfaceLock);
6574 Mutex::Autolock l(mLock);
6575
6576 if (mRequestThread == nullptr || !mSupportCameraMute) {
6577 return INVALID_OPERATION;
6578 }
Eino-Ville Talvala11afe4f2021-05-27 14:45:31 -07006579 int32_t muteMode =
6580 !enabled ? ANDROID_SENSOR_TEST_PATTERN_MODE_OFF :
6581 mSupportTestPatternSolidColor ? ANDROID_SENSOR_TEST_PATTERN_MODE_SOLID_COLOR :
6582 ANDROID_SENSOR_TEST_PATTERN_MODE_BLACK;
6583 return mRequestThread->setCameraMute(muteMode);
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08006584}
6585
Cliff Wuc2ad9c82021-04-21 00:58:58 +08006586status_t Camera3Device::injectCamera(const String8& injectedCamId,
6587 sp<CameraProviderManager> manager) {
6588 ALOGI("%s Injection camera: injectedCamId = %s", __FUNCTION__, injectedCamId.string());
6589 ATRACE_CALL();
6590 Mutex::Autolock il(mInterfaceLock);
6591
6592 status_t res = NO_ERROR;
6593 if (mInjectionMethods->isInjecting()) {
6594 if (injectedCamId == mInjectionMethods->getInjectedCamId()) {
6595 return OK;
6596 } else {
6597 res = mInjectionMethods->stopInjection();
6598 if (res != OK) {
6599 ALOGE("%s: Failed to stop the injection camera! ret != NO_ERROR: %d",
6600 __FUNCTION__, res);
6601 return res;
6602 }
6603 }
6604 }
6605
6606 res = mInjectionMethods->injectionInitialize(injectedCamId, manager, this);
6607 if (res != OK) {
6608 ALOGE("%s: Failed to initialize the injection camera! ret != NO_ERROR: %d",
6609 __FUNCTION__, res);
6610 return res;
6611 }
6612
6613 camera3::camera_stream_configuration injectionConfig;
6614 std::vector<uint32_t> injectionBufferSizes;
6615 mInjectionMethods->getInjectionConfig(&injectionConfig, &injectionBufferSizes);
6616 // When the second display of android is cast to the remote device, and the opened camera is
6617 // also cast to the second display, in this case, because the camera has configured the streams
6618 // at this time, we can directly call injectCamera() to replace the internal camera with
6619 // injection camera.
6620 if (mOperatingMode >= 0 && injectionConfig.num_streams > 0
6621 && injectionBufferSizes.size() > 0) {
6622 ALOGV("%s: The opened camera is directly cast to the remote device.", __FUNCTION__);
6623 res = mInjectionMethods->injectCamera(
6624 injectionConfig, injectionBufferSizes);
6625 if (res != OK) {
6626 ALOGE("Can't finish inject camera process!");
6627 return res;
6628 }
6629 }
6630
6631 return OK;
6632}
6633
6634status_t Camera3Device::stopInjection() {
6635 ALOGI("%s: Injection camera: stopInjection", __FUNCTION__);
6636 Mutex::Autolock il(mInterfaceLock);
6637 return mInjectionMethods->stopInjection();
6638}
6639
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08006640}; // namespace android