blob: a4288cd87636e0481e060807e867a64f79a3b836 [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
Eino-Ville Talvala1646c3c2021-07-29 13:48:40 -0700309 camera_metadata_entry_t availableTestPatternModes = mDeviceInfo.find(
310 ANDROID_SENSOR_AVAILABLE_TEST_PATTERN_MODES);
311 for (size_t i = 0; i < availableTestPatternModes.count; i++) {
312 if (availableTestPatternModes.data.i32[i] ==
313 ANDROID_SENSOR_TEST_PATTERN_MODE_SOLID_COLOR) {
314 mSupportCameraMute = true;
315 mSupportTestPatternSolidColor = true;
316 break;
317 } else if (availableTestPatternModes.data.i32[i] ==
318 ANDROID_SENSOR_TEST_PATTERN_MODE_BLACK) {
319 mSupportCameraMute = true;
320 mSupportTestPatternSolidColor = false;
321 }
322 }
323
Chien-Yu Chenab5135b2015-06-30 11:20:58 -0700324 /** Start up request queue thread */
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -0700325 mRequestThread = new RequestThread(
Eino-Ville Talvala1646c3c2021-07-29 13:48:40 -0700326 this, mStatusTracker, mInterface, sessionParamKeys,
327 mUseHalBufManager, mSupportCameraMute);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800328 res = mRequestThread->run(String8::format("C3Dev-%s-ReqQueue", mId.string()).string());
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800329 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700330 SET_ERR_L("Unable to start request queue thread: %s (%d)",
331 strerror(-res), res);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800332 mInterface->close();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800333 mRequestThread.clear();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800334 return res;
335 }
336
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -0700337 mPreparerThread = new PreparerThread();
338
Ruben Brunk183f0562015-08-12 12:55:02 -0700339 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800340 mNextStreamId = 0;
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -0400341 mFakeStreamId = NO_STREAM;
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -0700342 mNeedConfig = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700343 mPauseStateNotify = false;
Shuzhen Wang83bff122020-11-20 15:51:39 -0800344 mIsInputStreamMultiResolution = false;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800345
Shuzhen Wangc28dccc2016-02-11 23:48:46 -0800346 // Measure the clock domain offset between camera and video/hw_composer
347 camera_metadata_entry timestampSource =
348 mDeviceInfo.find(ANDROID_SENSOR_INFO_TIMESTAMP_SOURCE);
349 if (timestampSource.count > 0 && timestampSource.data.u8[0] ==
350 ANDROID_SENSOR_INFO_TIMESTAMP_SOURCE_REALTIME) {
351 mTimestampOffset = getMonoToBoottimeOffset();
352 }
353
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -0700354 // Will the HAL be sending in early partial result metadata?
Emilian Peev08dd2452017-04-06 16:55:14 +0100355 camera_metadata_entry partialResultsCount =
356 mDeviceInfo.find(ANDROID_REQUEST_PARTIAL_RESULT_COUNT);
357 if (partialResultsCount.count > 0) {
358 mNumPartialResults = partialResultsCount.data.i32[0];
359 mUsePartialResult = (mNumPartialResults > 1);
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -0700360 }
361
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800362 bool usePrecorrectArray = DistortionMapper::isDistortionSupported(mDeviceInfo);
363 if (usePrecorrectArray) {
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -0700364 res = mDistortionMappers[mId.c_str()].setupStaticInfo(mDeviceInfo);
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -0700365 if (res != OK) {
366 SET_ERR_L("Unable to read necessary calibration fields for distortion correction");
367 return res;
368 }
369 }
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800370
Shuzhen Wang1c834da2019-12-18 11:17:03 -0800371 mZoomRatioMappers[mId.c_str()] = ZoomRatioMapper(&mDeviceInfo,
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800372 mSupportNativeZoomRatio, usePrecorrectArray);
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800373
Jayant Chowdhary9255ce02021-07-15 11:18:17 -0700374 if (SessionConfigurationUtils::isUltraHighResolutionSensor(mDeviceInfo)) {
375 mUHRCropAndMeteringRegionMappers[mId.c_str()] =
376 UHRCropAndMeteringRegionMapper(mDeviceInfo, usePrecorrectArray);
377 }
378
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -0800379 if (RotateAndCropMapper::isNeeded(&mDeviceInfo)) {
380 mRotateAndCropMappers.emplace(mId.c_str(), &mDeviceInfo);
381 }
382
Cliff Wuc2ad9c82021-04-21 00:58:58 +0800383 mInjectionMethods = new Camera3DeviceInjectionMethods(this);
384
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800385 return OK;
386}
387
388status_t Camera3Device::disconnect() {
Yin-Chia Yehc5248132018-08-15 12:19:20 -0700389 return disconnectImpl();
390}
391
392status_t Camera3Device::disconnectImpl() {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800393 ATRACE_CALL();
Yin-Chia Yehe1c80632016-08-08 14:48:05 -0700394 ALOGI("%s: E", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800395
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700396 status_t res = OK;
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700397 std::vector<wp<Camera3StreamInterface>> streams;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700398 {
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800399 Mutex::Autolock il(mInterfaceLock);
400 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
401 {
402 Mutex::Autolock l(mLock);
403 if (mStatus == STATUS_UNINITIALIZED) return res;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700404
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800405 if (mStatus == STATUS_ACTIVE ||
406 (mStatus == STATUS_ERROR && mRequestThread != NULL)) {
407 res = mRequestThread->clearRepeatingRequests();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700408 if (res != OK) {
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800409 SET_ERR_L("Can't stop streaming");
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700410 // Continue to close device even in case of error
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800411 } else {
412 res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
413 if (res != OK) {
414 SET_ERR_L("Timeout waiting for HAL to drain (% " PRIi64 " ns)",
415 maxExpectedDuration);
416 // Continue to close device even in case of error
417 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700418 }
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700419 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800420
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800421 if (mStatus == STATUS_ERROR) {
422 CLOGE("Shutting down in an error state");
423 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700424
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800425 if (mStatusTracker != NULL) {
426 mStatusTracker->requestExit();
427 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700428
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800429 if (mRequestThread != NULL) {
430 mRequestThread->requestExit();
431 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700432
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800433 streams.reserve(mOutputStreams.size() + (mInputStream != nullptr ? 1 : 0));
434 for (size_t i = 0; i < mOutputStreams.size(); i++) {
435 streams.push_back(mOutputStreams[i]);
436 }
437 if (mInputStream != nullptr) {
438 streams.push_back(mInputStream);
439 }
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700440 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700441 }
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800442 // Joining done without holding mLock and mInterfaceLock, otherwise deadlocks may ensue
443 // as the threads try to access parent state (b/143513518)
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700444 if (mRequestThread != NULL && mStatus != STATUS_ERROR) {
445 // HAL may be in a bad state, so waiting for request thread
446 // (which may be stuck in the HAL processCaptureRequest call)
447 // could be dangerous.
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800448 // give up mInterfaceLock here and then lock it again. Could this lead
449 // to other deadlocks
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700450 mRequestThread->join();
451 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700452 {
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800453 Mutex::Autolock il(mInterfaceLock);
454 if (mStatusTracker != NULL) {
455 mStatusTracker->join();
456 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800457
Cliff Wuc2ad9c82021-04-21 00:58:58 +0800458 if (mInjectionMethods->isInjecting()) {
459 mInjectionMethods->stopInjection();
460 }
461
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800462 HalInterface* interface;
463 {
464 Mutex::Autolock l(mLock);
465 mRequestThread.clear();
466 Mutex::Autolock stLock(mTrackerLock);
467 mStatusTracker.clear();
468 interface = mInterface.get();
469 }
Eino-Ville Talvalaefff1c42015-08-28 16:27:27 -0700470
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800471 // Call close without internal mutex held, as the HAL close may need to
472 // wait on assorted callbacks,etc, to complete before it can return.
473 interface->close();
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700474
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800475 flushInflightRequests();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800476
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800477 {
478 Mutex::Autolock l(mLock);
479 mInterface->clear();
480 mOutputStreams.clear();
481 mInputStream.clear();
482 mDeletedStreams.clear();
483 mBufferManager.clear();
484 internalUpdateStatusLocked(STATUS_UNINITIALIZED);
485 }
486
487 for (auto& weakStream : streams) {
488 sp<Camera3StreamInterface> stream = weakStream.promote();
489 if (stream != nullptr) {
490 ALOGE("%s: Stream %d leaked! strong reference (%d)!",
491 __FUNCTION__, stream->getId(), stream->getStrongCount() - 1);
492 }
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700493 }
494 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -0700495 ALOGI("%s: X", __FUNCTION__);
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700496 return res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800497}
498
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700499// For dumping/debugging only -
500// try to acquire a lock a few times, eventually give up to proceed with
501// debug/dump operations
502bool Camera3Device::tryLockSpinRightRound(Mutex& lock) {
503 bool gotLock = false;
504 for (size_t i = 0; i < kDumpLockAttempts; ++i) {
505 if (lock.tryLock() == NO_ERROR) {
506 gotLock = true;
507 break;
508 } else {
509 usleep(kDumpSleepDuration);
510 }
511 }
512 return gotLock;
513}
514
Shuzhen Wangc28dccc2016-02-11 23:48:46 -0800515nsecs_t Camera3Device::getMonoToBoottimeOffset() {
516 // try three times to get the clock offset, choose the one
517 // with the minimum gap in measurements.
518 const int tries = 3;
519 nsecs_t bestGap, measured;
520 for (int i = 0; i < tries; ++i) {
521 const nsecs_t tmono = systemTime(SYSTEM_TIME_MONOTONIC);
522 const nsecs_t tbase = systemTime(SYSTEM_TIME_BOOTTIME);
523 const nsecs_t tmono2 = systemTime(SYSTEM_TIME_MONOTONIC);
524 const nsecs_t gap = tmono2 - tmono;
525 if (i == 0 || gap < bestGap) {
526 bestGap = gap;
527 measured = tbase - ((tmono + tmono2) >> 1);
528 }
529 }
530 return measured;
531}
532
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800533hardware::graphics::common::V1_0::PixelFormat Camera3Device::mapToPixelFormat(
534 int frameworkFormat) {
535 return (hardware::graphics::common::V1_0::PixelFormat) frameworkFormat;
536}
537
538DataspaceFlags Camera3Device::mapToHidlDataspace(
539 android_dataspace dataSpace) {
540 return dataSpace;
541}
542
Chia-I Wu67a0c0e2017-04-06 13:37:01 -0700543BufferUsageFlags Camera3Device::mapToConsumerUsage(
Emilian Peev050f5dc2017-05-18 14:43:56 +0100544 uint64_t usage) {
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -0700545 return usage;
546}
547
Emilian Peevf4816702020-04-03 15:44:51 -0700548StreamRotation Camera3Device::mapToStreamRotation(camera_stream_rotation_t rotation) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800549 switch (rotation) {
Emilian Peevf4816702020-04-03 15:44:51 -0700550 case CAMERA_STREAM_ROTATION_0:
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800551 return StreamRotation::ROTATION_0;
Emilian Peevf4816702020-04-03 15:44:51 -0700552 case CAMERA_STREAM_ROTATION_90:
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800553 return StreamRotation::ROTATION_90;
Emilian Peevf4816702020-04-03 15:44:51 -0700554 case CAMERA_STREAM_ROTATION_180:
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800555 return StreamRotation::ROTATION_180;
Emilian Peevf4816702020-04-03 15:44:51 -0700556 case CAMERA_STREAM_ROTATION_270:
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800557 return StreamRotation::ROTATION_270;
558 }
559 ALOGE("%s: Unknown stream rotation %d", __FUNCTION__, rotation);
560 return StreamRotation::ROTATION_0;
561}
562
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800563status_t Camera3Device::mapToStreamConfigurationMode(
Emilian Peevf4816702020-04-03 15:44:51 -0700564 camera_stream_configuration_mode_t operationMode, StreamConfigurationMode *mode) {
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800565 if (mode == nullptr) return BAD_VALUE;
Emilian Peevf4816702020-04-03 15:44:51 -0700566 if (operationMode < CAMERA_VENDOR_STREAM_CONFIGURATION_MODE_START) {
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800567 switch(operationMode) {
Emilian Peevf4816702020-04-03 15:44:51 -0700568 case CAMERA_STREAM_CONFIGURATION_NORMAL_MODE:
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800569 *mode = StreamConfigurationMode::NORMAL_MODE;
570 break;
Emilian Peevf4816702020-04-03 15:44:51 -0700571 case CAMERA_STREAM_CONFIGURATION_CONSTRAINED_HIGH_SPEED_MODE:
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800572 *mode = StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE;
573 break;
574 default:
575 ALOGE("%s: Unknown stream configuration mode %d", __FUNCTION__, operationMode);
576 return BAD_VALUE;
577 }
578 } else {
579 *mode = static_cast<StreamConfigurationMode>(operationMode);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800580 }
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800581 return OK;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800582}
583
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800584int Camera3Device::mapToFrameworkFormat(
585 hardware::graphics::common::V1_0::PixelFormat pixelFormat) {
586 return static_cast<uint32_t>(pixelFormat);
587}
588
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -0700589android_dataspace Camera3Device::mapToFrameworkDataspace(
590 DataspaceFlags dataSpace) {
591 return static_cast<android_dataspace>(dataSpace);
592}
593
Emilian Peev050f5dc2017-05-18 14:43:56 +0100594uint64_t Camera3Device::mapConsumerToFrameworkUsage(
Chia-I Wu67a0c0e2017-04-06 13:37:01 -0700595 BufferUsageFlags usage) {
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -0700596 return usage;
597}
598
Emilian Peev050f5dc2017-05-18 14:43:56 +0100599uint64_t Camera3Device::mapProducerToFrameworkUsage(
Chia-I Wu67a0c0e2017-04-06 13:37:01 -0700600 BufferUsageFlags usage) {
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -0700601 return usage;
602}
603
Zhijun Hef7da0962014-04-24 13:27:56 -0700604ssize_t Camera3Device::getJpegBufferSize(uint32_t width, uint32_t height) const {
Jayant Chowdharycd3d36b2021-07-10 10:53:53 -0700605 // Get max jpeg size (area-wise) for default sensor pixel mode
606 camera3::Size maxDefaultJpegResolution =
607 SessionConfigurationUtils::getMaxJpegResolution(mDeviceInfo,
608 /*isUltraHighResolutionSensor*/false);
609 // Get max jpeg size (area-wise) for max resolution sensor pixel mode / 0 if
610 // not ultra high res sensor
611 camera3::Size uhrMaxJpegResolution =
612 SessionConfigurationUtils::getMaxJpegResolution(mDeviceInfo,
613 /*isUltraHighResolution*/true);
614 if (maxDefaultJpegResolution.width == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800615 ALOGE("%s: Camera %s: Can't find valid available jpeg sizes in static metadata!",
616 __FUNCTION__, mId.string());
Zhijun Hef7da0962014-04-24 13:27:56 -0700617 return BAD_VALUE;
618 }
Jayant Chowdharycd3d36b2021-07-10 10:53:53 -0700619 bool useMaxSensorPixelModeThreshold = false;
620 if (uhrMaxJpegResolution.width != 0 &&
621 width * height > maxDefaultJpegResolution.width * maxDefaultJpegResolution.height) {
622 // Use the ultra high res max jpeg size and max jpeg buffer size
623 useMaxSensorPixelModeThreshold = true;
624 }
Zhijun Hef7da0962014-04-24 13:27:56 -0700625
Zhijun Hef7da0962014-04-24 13:27:56 -0700626 // Get max jpeg buffer size
627 ssize_t maxJpegBufferSize = 0;
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700628 camera_metadata_ro_entry jpegBufMaxSize = mDeviceInfo.find(ANDROID_JPEG_MAX_SIZE);
629 if (jpegBufMaxSize.count == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800630 ALOGE("%s: Camera %s: Can't find maximum JPEG size in static metadata!", __FUNCTION__,
631 mId.string());
Zhijun Hef7da0962014-04-24 13:27:56 -0700632 return BAD_VALUE;
633 }
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700634 maxJpegBufferSize = jpegBufMaxSize.data.i32[0];
Jayant Chowdharycd3d36b2021-07-10 10:53:53 -0700635
636 camera3::Size chosenMaxJpegResolution = maxDefaultJpegResolution;
637 if (useMaxSensorPixelModeThreshold) {
638 maxJpegBufferSize =
639 SessionConfigurationUtils::getUHRMaxJpegBufferSize(uhrMaxJpegResolution,
640 maxDefaultJpegResolution, maxJpegBufferSize);
641 chosenMaxJpegResolution = uhrMaxJpegResolution;
642 }
Yin-Chia Yeh0c4e56d2015-01-09 15:21:27 -0800643 assert(kMinJpegBufferSize < maxJpegBufferSize);
Zhijun Hef7da0962014-04-24 13:27:56 -0700644
645 // Calculate final jpeg buffer size for the given resolution.
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700646 float scaleFactor = ((float) (width * height)) /
Jayant Chowdharycd3d36b2021-07-10 10:53:53 -0700647 (chosenMaxJpegResolution.width * chosenMaxJpegResolution.height);
Yin-Chia Yeh0c4e56d2015-01-09 15:21:27 -0800648 ssize_t jpegBufferSize = scaleFactor * (maxJpegBufferSize - kMinJpegBufferSize) +
649 kMinJpegBufferSize;
Zhijun Hef7da0962014-04-24 13:27:56 -0700650 if (jpegBufferSize > maxJpegBufferSize) {
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -0800651 ALOGI("%s: jpeg buffer size calculated is > maxJpeg bufferSize(%zd), clamping",
652 __FUNCTION__, maxJpegBufferSize);
Zhijun Hef7da0962014-04-24 13:27:56 -0700653 jpegBufferSize = maxJpegBufferSize;
Zhijun Hef7da0962014-04-24 13:27:56 -0700654 }
Zhijun Hef7da0962014-04-24 13:27:56 -0700655 return jpegBufferSize;
656}
657
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700658ssize_t Camera3Device::getPointCloudBufferSize() const {
659 const int FLOATS_PER_POINT=4;
660 camera_metadata_ro_entry maxPointCount = mDeviceInfo.find(ANDROID_DEPTH_MAX_DEPTH_SAMPLES);
661 if (maxPointCount.count == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800662 ALOGE("%s: Camera %s: Can't find maximum depth point cloud size in static metadata!",
663 __FUNCTION__, mId.string());
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700664 return BAD_VALUE;
665 }
666 ssize_t maxBytesForPointCloud = sizeof(android_depth_points) +
667 maxPointCount.data.i32[0] * sizeof(float) * FLOATS_PER_POINT;
668 return maxBytesForPointCloud;
669}
670
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -0800671ssize_t Camera3Device::getRawOpaqueBufferSize(int32_t width, int32_t height,
672 bool maxResolution) const {
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800673 const int PER_CONFIGURATION_SIZE = 3;
674 const int WIDTH_OFFSET = 0;
675 const int HEIGHT_OFFSET = 1;
676 const int SIZE_OFFSET = 2;
677 camera_metadata_ro_entry rawOpaqueSizes =
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -0800678 mDeviceInfo.find(
679 camera3::SessionConfigurationUtils::getAppropriateModeTag(
680 ANDROID_SENSOR_OPAQUE_RAW_SIZE,
681 maxResolution));
Aurimas Liutikasbc57b122016-02-16 09:59:16 -0800682 size_t count = rawOpaqueSizes.count;
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800683 if (count == 0 || (count % PER_CONFIGURATION_SIZE)) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800684 ALOGE("%s: Camera %s: bad opaque RAW size static metadata length(%zu)!",
685 __FUNCTION__, mId.string(), count);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800686 return BAD_VALUE;
687 }
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700688
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800689 for (size_t i = 0; i < count; i += PER_CONFIGURATION_SIZE) {
690 if (width == rawOpaqueSizes.data.i32[i + WIDTH_OFFSET] &&
691 height == rawOpaqueSizes.data.i32[i + HEIGHT_OFFSET]) {
692 return rawOpaqueSizes.data.i32[i + SIZE_OFFSET];
693 }
694 }
695
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800696 ALOGE("%s: Camera %s: cannot find size for %dx%d opaque RAW image!",
697 __FUNCTION__, mId.string(), width, height);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800698 return BAD_VALUE;
699}
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700700
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800701status_t Camera3Device::dump(int fd, const Vector<String16> &args) {
702 ATRACE_CALL();
703 (void)args;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700704
705 // Try to lock, but continue in case of failure (to avoid blocking in
706 // deadlocks)
707 bool gotInterfaceLock = tryLockSpinRightRound(mInterfaceLock);
708 bool gotLock = tryLockSpinRightRound(mLock);
709
710 ALOGW_IF(!gotInterfaceLock,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800711 "Camera %s: %s: Unable to lock interface lock, proceeding anyway",
712 mId.string(), __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700713 ALOGW_IF(!gotLock,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800714 "Camera %s: %s: Unable to lock main lock, proceeding anyway",
715 mId.string(), __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700716
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800717 bool dumpTemplates = false;
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700718
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800719 String16 templatesOption("-t");
720 int n = args.size();
721 for (int i = 0; i < n; i++) {
722 if (args[i] == templatesOption) {
723 dumpTemplates = true;
724 }
Emilian Peevbd8c5032018-02-14 23:05:40 +0000725 if (args[i] == TagMonitor::kMonitorOption) {
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700726 if (i + 1 < n) {
727 String8 monitorTags = String8(args[i + 1]);
728 if (monitorTags == "off") {
729 mTagMonitor.disableMonitoring();
730 } else {
731 mTagMonitor.parseTagsToMonitor(monitorTags);
732 }
733 } else {
734 mTagMonitor.disableMonitoring();
735 }
736 }
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800737 }
738
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800739 String8 lines;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800740
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800741 const char *status =
742 mStatus == STATUS_ERROR ? "ERROR" :
743 mStatus == STATUS_UNINITIALIZED ? "UNINITIALIZED" :
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700744 mStatus == STATUS_UNCONFIGURED ? "UNCONFIGURED" :
745 mStatus == STATUS_CONFIGURED ? "CONFIGURED" :
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800746 mStatus == STATUS_ACTIVE ? "ACTIVE" :
747 "Unknown";
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700748
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800749 lines.appendFormat(" Device status: %s\n", status);
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700750 if (mStatus == STATUS_ERROR) {
751 lines.appendFormat(" Error cause: %s\n", mErrorCause.string());
752 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800753 lines.appendFormat(" Stream configuration:\n");
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800754 const char *mode =
755 mOperatingMode == static_cast<int>(StreamConfigurationMode::NORMAL_MODE) ? "NORMAL" :
756 mOperatingMode == static_cast<int>(
757 StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE) ? "CONSTRAINED_HIGH_SPEED" :
758 "CUSTOM";
759 lines.appendFormat(" Operation mode: %s (%d) \n", mode, mOperatingMode);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800760
761 if (mInputStream != NULL) {
762 write(fd, lines.string(), lines.size());
763 mInputStream->dump(fd, args);
764 } else {
765 lines.appendFormat(" No input stream.\n");
766 write(fd, lines.string(), lines.size());
767 }
768 for (size_t i = 0; i < mOutputStreams.size(); i++) {
769 mOutputStreams[i]->dump(fd,args);
770 }
771
Zhijun He431503c2016-03-07 17:30:16 -0800772 if (mBufferManager != NULL) {
773 lines = String8(" Camera3 Buffer Manager:\n");
774 write(fd, lines.string(), lines.size());
775 mBufferManager->dump(fd, args);
776 }
Zhijun He125684a2015-12-26 15:07:30 -0800777
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700778 lines = String8(" In-flight requests:\n");
Emilian Peeva6138c52021-06-24 12:52:38 -0700779 if (mInFlightLock.try_lock()) {
780 if (mInFlightMap.size() == 0) {
781 lines.append(" None\n");
782 } else {
783 for (size_t i = 0; i < mInFlightMap.size(); i++) {
784 InFlightRequest r = mInFlightMap.valueAt(i);
785 lines.appendFormat(" Frame %d | Timestamp: %" PRId64 ", metadata"
786 " arrived: %s, buffers left: %d\n", mInFlightMap.keyAt(i),
787 r.shutterTimestamp, r.haveResultMetadata ? "true" : "false",
788 r.numBuffersLeft);
789 }
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700790 }
Emilian Peeva6138c52021-06-24 12:52:38 -0700791 mInFlightLock.unlock();
792 } else {
793 lines.append(" Failed to acquire In-flight lock!\n");
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700794 }
795 write(fd, lines.string(), lines.size());
796
Shuzhen Wang686f6442017-06-20 16:16:04 -0700797 if (mRequestThread != NULL) {
798 mRequestThread->dumpCaptureRequestLatency(fd,
799 " ProcessCaptureRequest latency histogram:");
800 }
801
Igor Murashkin1e479c02013-09-06 16:55:14 -0700802 {
803 lines = String8(" Last request sent:\n");
804 write(fd, lines.string(), lines.size());
805
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700806 CameraMetadata lastRequest = getLatestRequestLocked();
Igor Murashkin1e479c02013-09-06 16:55:14 -0700807 lastRequest.dump(fd, /*verbosity*/2, /*indentation*/6);
808 }
809
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800810 if (dumpTemplates) {
Emilian Peevf4816702020-04-03 15:44:51 -0700811 const char *templateNames[CAMERA_TEMPLATE_COUNT] = {
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800812 "TEMPLATE_PREVIEW",
813 "TEMPLATE_STILL_CAPTURE",
814 "TEMPLATE_VIDEO_RECORD",
815 "TEMPLATE_VIDEO_SNAPSHOT",
816 "TEMPLATE_ZERO_SHUTTER_LAG",
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -0800817 "TEMPLATE_MANUAL",
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800818 };
819
Emilian Peevf4816702020-04-03 15:44:51 -0700820 for (int i = 1; i < CAMERA_TEMPLATE_COUNT; i++) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800821 camera_metadata_t *templateRequest = nullptr;
822 mInterface->constructDefaultRequestSettings(
Emilian Peevf4816702020-04-03 15:44:51 -0700823 (camera_request_template_t) i, &templateRequest);
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800824 lines = String8::format(" HAL Request %s:\n", templateNames[i-1]);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800825 if (templateRequest == nullptr) {
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800826 lines.append(" Not supported\n");
827 write(fd, lines.string(), lines.size());
828 } else {
829 write(fd, lines.string(), lines.size());
830 dump_indented_camera_metadata(templateRequest,
831 fd, /*verbosity*/2, /*indentation*/8);
832 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800833 free_camera_metadata(templateRequest);
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800834 }
835 }
836
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700837 mTagMonitor.dumpMonitoredMetadata(fd);
838
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800839 if (mInterface->valid()) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -0800840 lines = String8(" HAL device dump:\n");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800841 write(fd, lines.string(), lines.size());
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800842 mInterface->dump(fd);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800843 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800844
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700845 if (gotLock) mLock.unlock();
846 if (gotInterfaceLock) mInterfaceLock.unlock();
847
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800848 return OK;
849}
850
Emilian Peevfaa4bde2020-01-23 12:19:37 -0800851const CameraMetadata& Camera3Device::infoPhysical(const String8& physicalId) const {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800852 ALOGVV("%s: E", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800853 if (CC_UNLIKELY(mStatus == STATUS_UNINITIALIZED ||
854 mStatus == STATUS_ERROR)) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700855 ALOGW("%s: Access to static info %s!", __FUNCTION__,
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800856 mStatus == STATUS_ERROR ?
857 "when in error state" : "before init");
858 }
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700859 if (physicalId.isEmpty()) {
860 return mDeviceInfo;
861 } else {
862 std::string id(physicalId.c_str());
863 if (mPhysicalDeviceInfoMap.find(id) != mPhysicalDeviceInfoMap.end()) {
864 return mPhysicalDeviceInfoMap.at(id);
865 } else {
866 ALOGE("%s: Invalid physical camera id %s", __FUNCTION__, physicalId.c_str());
867 return mDeviceInfo;
868 }
869 }
870}
871
872const CameraMetadata& Camera3Device::info() const {
873 String8 emptyId;
Emilian Peevfaa4bde2020-01-23 12:19:37 -0800874 return infoPhysical(emptyId);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800875}
876
Jianing Wei90e59c92014-03-12 18:29:36 -0700877status_t Camera3Device::checkStatusOkToCaptureLocked() {
878 switch (mStatus) {
879 case STATUS_ERROR:
880 CLOGE("Device has encountered a serious error");
881 return INVALID_OPERATION;
882 case STATUS_UNINITIALIZED:
883 CLOGE("Device not initialized");
884 return INVALID_OPERATION;
885 case STATUS_UNCONFIGURED:
886 case STATUS_CONFIGURED:
887 case STATUS_ACTIVE:
888 // OK
889 break;
890 default:
891 SET_ERR_L("Unexpected status: %d", mStatus);
892 return INVALID_OPERATION;
893 }
894 return OK;
895}
896
897status_t Camera3Device::convertMetadataListToRequestListLocked(
Emilian Peevaebbe412018-01-15 13:53:24 +0000898 const List<const PhysicalCameraSettingsList> &metadataList,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700899 const std::list<const SurfaceMap> &surfaceMaps,
Shuzhen Wang316781a2020-08-18 18:11:01 -0700900 bool repeating, nsecs_t requestTimeNs,
Shuzhen Wang9d066012016-09-30 11:30:20 -0700901 RequestList *requestList) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700902 if (requestList == NULL) {
903 CLOGE("requestList cannot be NULL.");
904 return BAD_VALUE;
905 }
906
Jianing Weicb0652e2014-03-12 18:29:36 -0700907 int32_t burstId = 0;
Emilian Peevaebbe412018-01-15 13:53:24 +0000908 List<const PhysicalCameraSettingsList>::const_iterator metadataIt = metadataList.begin();
Shuzhen Wang0129d522016-10-30 22:43:41 -0700909 std::list<const SurfaceMap>::const_iterator surfaceMapIt = surfaceMaps.begin();
910 for (; metadataIt != metadataList.end() && surfaceMapIt != surfaceMaps.end();
911 ++metadataIt, ++surfaceMapIt) {
912 sp<CaptureRequest> newRequest = setUpRequestLocked(*metadataIt, *surfaceMapIt);
Jianing Wei90e59c92014-03-12 18:29:36 -0700913 if (newRequest == 0) {
914 CLOGE("Can't create capture request");
915 return BAD_VALUE;
916 }
Jianing Weicb0652e2014-03-12 18:29:36 -0700917
Shuzhen Wang9d066012016-09-30 11:30:20 -0700918 newRequest->mRepeating = repeating;
Shuzhen Wang316781a2020-08-18 18:11:01 -0700919 newRequest->mRequestTimeNs = requestTimeNs;
Shuzhen Wang9d066012016-09-30 11:30:20 -0700920
Jianing Weicb0652e2014-03-12 18:29:36 -0700921 // Setup burst Id and request Id
922 newRequest->mResultExtras.burstId = burstId++;
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -0800923 auto requestIdEntry = metadataIt->begin()->metadata.find(ANDROID_REQUEST_ID);
924 if (requestIdEntry.count == 0) {
Jianing Weicb0652e2014-03-12 18:29:36 -0700925 CLOGE("RequestID does not exist in metadata");
926 return BAD_VALUE;
927 }
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -0800928 newRequest->mResultExtras.requestId = requestIdEntry.data.i32[0];
Jianing Weicb0652e2014-03-12 18:29:36 -0700929
Jianing Wei90e59c92014-03-12 18:29:36 -0700930 requestList->push_back(newRequest);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700931
932 ALOGV("%s: requestId = %" PRId32, __FUNCTION__, newRequest->mResultExtras.requestId);
Jianing Wei90e59c92014-03-12 18:29:36 -0700933 }
Shuzhen Wang0129d522016-10-30 22:43:41 -0700934 if (metadataIt != metadataList.end() || surfaceMapIt != surfaceMaps.end()) {
935 ALOGE("%s: metadataList and surfaceMaps are not the same size!", __FUNCTION__);
936 return BAD_VALUE;
937 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -0700938
939 // Setup batch size if this is a high speed video recording request.
940 if (mIsConstrainedHighSpeedConfiguration && requestList->size() > 0) {
941 auto firstRequest = requestList->begin();
942 for (auto& outputStream : (*firstRequest)->mOutputStreams) {
943 if (outputStream->isVideoStream()) {
944 (*firstRequest)->mBatchSize = requestList->size();
Yin-Chia Yeh14ef48d2020-02-10 15:06:37 -0800945 outputStream->setBatchSize(requestList->size());
Chien-Yu Chen85a64552015-08-28 15:46:12 -0700946 break;
947 }
948 }
949 }
950
Jianing Wei90e59c92014-03-12 18:29:36 -0700951 return OK;
952}
953
Yin-Chia Yeh7e5a2042019-02-06 16:01:06 -0800954status_t Camera3Device::capture(CameraMetadata &request, int64_t* lastFrameNumber) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800955 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800956
Emilian Peevaebbe412018-01-15 13:53:24 +0000957 List<const PhysicalCameraSettingsList> requestsList;
Shuzhen Wang0129d522016-10-30 22:43:41 -0700958 std::list<const SurfaceMap> surfaceMaps;
Emilian Peevaebbe412018-01-15 13:53:24 +0000959 convertToRequestList(requestsList, surfaceMaps, request);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700960
Yin-Chia Yeh7e5a2042019-02-06 16:01:06 -0800961 return captureList(requestsList, surfaceMaps, lastFrameNumber);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700962}
963
Emilian Peevaebbe412018-01-15 13:53:24 +0000964void Camera3Device::convertToRequestList(List<const PhysicalCameraSettingsList>& requestsList,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700965 std::list<const SurfaceMap>& surfaceMaps,
966 const CameraMetadata& request) {
Emilian Peevaebbe412018-01-15 13:53:24 +0000967 PhysicalCameraSettingsList requestList;
968 requestList.push_back({std::string(getId().string()), request});
969 requestsList.push_back(requestList);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700970
971 SurfaceMap surfaceMap;
972 camera_metadata_ro_entry streams = request.find(ANDROID_REQUEST_OUTPUT_STREAMS);
973 // With no surface list passed in, stream and surface will have 1-to-1
974 // mapping. So the surface index is 0 for each stream in the surfaceMap.
975 for (size_t i = 0; i < streams.count; i++) {
976 surfaceMap[streams.data.i32[i]].push_back(0);
977 }
978 surfaceMaps.push_back(surfaceMap);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800979}
980
Jianing Wei90e59c92014-03-12 18:29:36 -0700981status_t Camera3Device::submitRequestsHelper(
Emilian Peevaebbe412018-01-15 13:53:24 +0000982 const List<const PhysicalCameraSettingsList> &requests,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700983 const std::list<const SurfaceMap> &surfaceMaps,
984 bool repeating,
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700985 /*out*/
986 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700987 ATRACE_CALL();
Shuzhen Wang316781a2020-08-18 18:11:01 -0700988 nsecs_t requestTimeNs = systemTime();
989
Jianing Wei90e59c92014-03-12 18:29:36 -0700990 Mutex::Autolock il(mInterfaceLock);
991 Mutex::Autolock l(mLock);
992
993 status_t res = checkStatusOkToCaptureLocked();
994 if (res != OK) {
995 // error logged by previous call
996 return res;
997 }
998
999 RequestList requestList;
1000
Shuzhen Wang0129d522016-10-30 22:43:41 -07001001 res = convertMetadataListToRequestListLocked(requests, surfaceMaps,
Shuzhen Wang316781a2020-08-18 18:11:01 -07001002 repeating, requestTimeNs, /*out*/&requestList);
Jianing Wei90e59c92014-03-12 18:29:36 -07001003 if (res != OK) {
1004 // error logged by previous call
1005 return res;
1006 }
1007
1008 if (repeating) {
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07001009 res = mRequestThread->setRepeatingRequests(requestList, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -07001010 } else {
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07001011 res = mRequestThread->queueRequestList(requestList, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -07001012 }
1013
1014 if (res == OK) {
1015 waitUntilStateThenRelock(/*active*/true, kActiveTimeout);
1016 if (res != OK) {
1017 SET_ERR_L("Can't transition to active in %f seconds!",
1018 kActiveTimeout/1e9);
1019 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001020 ALOGV("Camera %s: Capture request %" PRId32 " enqueued", mId.string(),
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07001021 (*(requestList.begin()))->mResultExtras.requestId);
Jianing Wei90e59c92014-03-12 18:29:36 -07001022 } else {
1023 CLOGE("Cannot queue request. Impossible.");
1024 return BAD_VALUE;
1025 }
1026
1027 return res;
1028}
1029
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001030hardware::Return<void> Camera3Device::requestStreamBuffers(
1031 const hardware::hidl_vec<hardware::camera::device::V3_5::BufferRequest>& bufReqs,
1032 requestStreamBuffers_cb _hidl_cb) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001033 RequestBufferStates states {
Shuzhen Wang316781a2020-08-18 18:11:01 -07001034 mId, mRequestBufferInterfaceLock, mUseHalBufManager, mOutputStreams, mSessionStatsBuilder,
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001035 *this, *mInterface, *this};
1036 camera3::requestStreamBuffers(states, bufReqs, _hidl_cb);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001037 return hardware::Void();
1038}
1039
1040hardware::Return<void> Camera3Device::returnStreamBuffers(
1041 const hardware::hidl_vec<hardware::camera::device::V3_2::StreamBuffer>& buffers) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001042 ReturnBufferStates states {
Shuzhen Wang316781a2020-08-18 18:11:01 -07001043 mId, mUseHalBufManager, mOutputStreams, mSessionStatsBuilder, *mInterface};
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001044 camera3::returnStreamBuffers(states, buffers);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001045 return hardware::Void();
1046}
1047
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001048hardware::Return<void> Camera3Device::processCaptureResult_3_4(
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001049 const hardware::hidl_vec<
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001050 hardware::camera::device::V3_4::CaptureResult>& results) {
Yin-Chia Yeh657c1872017-07-18 18:09:57 -07001051 // Ideally we should grab mLock, but that can lead to deadlock, and
1052 // it's not super important to get up to date value of mStatus for this
1053 // warning print, hence skipping the lock here
1054 if (mStatus == STATUS_ERROR) {
1055 // Per API contract, HAL should act as closed after device error
1056 // But mStatus can be set to error by framework as well, so just log
1057 // a warning here.
1058 ALOGW("%s: received capture result in error state.", __FUNCTION__);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07001059 }
Yifan Honga640c5a2017-04-12 16:30:31 -07001060
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001061 sp<NotificationListener> listener;
1062 {
1063 std::lock_guard<std::mutex> l(mOutputLock);
1064 listener = mListener.promote();
1065 }
1066
Yifan Honga640c5a2017-04-12 16:30:31 -07001067 if (mProcessCaptureResultLock.tryLock() != OK) {
1068 // This should never happen; it indicates a wrong client implementation
1069 // that doesn't follow the contract. But, we can be tolerant here.
1070 ALOGE("%s: callback overlapped! waiting 1s...",
1071 __FUNCTION__);
1072 if (mProcessCaptureResultLock.timedLock(1000000000 /* 1s */) != OK) {
1073 ALOGE("%s: cannot acquire lock in 1s, dropping results",
1074 __FUNCTION__);
1075 // really don't know what to do, so bail out.
1076 return hardware::Void();
1077 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001078 }
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001079 CaptureOutputStates states {
1080 mId,
Shuzhen Wangb7b42652020-05-07 11:59:02 -07001081 mInFlightLock, mLastCompletedRegularFrameNumber,
1082 mLastCompletedReprocessFrameNumber, mLastCompletedZslFrameNumber,
1083 mInFlightMap, mOutputLock, mResultQueue, mResultSignal,
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001084 mNextShutterFrameNumber,
1085 mNextReprocessShutterFrameNumber, mNextZslStillShutterFrameNumber,
1086 mNextResultFrameNumber,
1087 mNextReprocessResultFrameNumber, mNextZslStillResultFrameNumber,
1088 mUseHalBufManager, mUsePartialResult, mNeedFixupMonochromeTags,
1089 mNumPartialResults, mVendorTagId, mDeviceInfo, mPhysicalDeviceInfoMap,
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08001090 mResultMetadataQueue, mDistortionMappers, mZoomRatioMappers, mRotateAndCropMappers,
Shuzhen Wang316781a2020-08-18 18:11:01 -07001091 mTagMonitor, mInputStream, mOutputStreams, mSessionStatsBuilder, listener, *this, *this,
1092 *mInterface
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001093 };
1094
Yifan Honga640c5a2017-04-12 16:30:31 -07001095 for (const auto& result : results) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001096 processOneCaptureResultLocked(states, result.v3_2, result.physicalCameraMetadata);
Yifan Honga640c5a2017-04-12 16:30:31 -07001097 }
1098 mProcessCaptureResultLock.unlock();
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001099 return hardware::Void();
1100}
1101
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001102// Only one processCaptureResult should be called at a time, so
1103// the locks won't block. The locks are present here simply to enforce this.
1104hardware::Return<void> Camera3Device::processCaptureResult(
1105 const hardware::hidl_vec<
1106 hardware::camera::device::V3_2::CaptureResult>& results) {
1107 hardware::hidl_vec<hardware::camera::device::V3_4::PhysicalCameraMetadata> noPhysMetadata;
1108
1109 // Ideally we should grab mLock, but that can lead to deadlock, and
1110 // it's not super important to get up to date value of mStatus for this
1111 // warning print, hence skipping the lock here
1112 if (mStatus == STATUS_ERROR) {
1113 // Per API contract, HAL should act as closed after device error
1114 // But mStatus can be set to error by framework as well, so just log
1115 // a warning here.
1116 ALOGW("%s: received capture result in error state.", __FUNCTION__);
1117 }
1118
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001119 sp<NotificationListener> listener;
1120 {
1121 std::lock_guard<std::mutex> l(mOutputLock);
1122 listener = mListener.promote();
1123 }
1124
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001125 if (mProcessCaptureResultLock.tryLock() != OK) {
1126 // This should never happen; it indicates a wrong client implementation
1127 // that doesn't follow the contract. But, we can be tolerant here.
1128 ALOGE("%s: callback overlapped! waiting 1s...",
1129 __FUNCTION__);
1130 if (mProcessCaptureResultLock.timedLock(1000000000 /* 1s */) != OK) {
1131 ALOGE("%s: cannot acquire lock in 1s, dropping results",
1132 __FUNCTION__);
1133 // really don't know what to do, so bail out.
1134 return hardware::Void();
1135 }
1136 }
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001137
1138 CaptureOutputStates states {
1139 mId,
Shuzhen Wangb7b42652020-05-07 11:59:02 -07001140 mInFlightLock, mLastCompletedRegularFrameNumber,
1141 mLastCompletedReprocessFrameNumber, mLastCompletedZslFrameNumber,
1142 mInFlightMap, mOutputLock, mResultQueue, mResultSignal,
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001143 mNextShutterFrameNumber,
1144 mNextReprocessShutterFrameNumber, mNextZslStillShutterFrameNumber,
1145 mNextResultFrameNumber,
1146 mNextReprocessResultFrameNumber, mNextZslStillResultFrameNumber,
1147 mUseHalBufManager, mUsePartialResult, mNeedFixupMonochromeTags,
1148 mNumPartialResults, mVendorTagId, mDeviceInfo, mPhysicalDeviceInfoMap,
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08001149 mResultMetadataQueue, mDistortionMappers, mZoomRatioMappers, mRotateAndCropMappers,
Shuzhen Wang316781a2020-08-18 18:11:01 -07001150 mTagMonitor, mInputStream, mOutputStreams, mSessionStatsBuilder, listener, *this, *this,
1151 *mInterface
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001152 };
1153
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001154 for (const auto& result : results) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001155 processOneCaptureResultLocked(states, result, noPhysMetadata);
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001156 }
1157 mProcessCaptureResultLock.unlock();
1158 return hardware::Void();
1159}
1160
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001161hardware::Return<void> Camera3Device::notify(
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001162 const hardware::hidl_vec<hardware::camera::device::V3_2::NotifyMsg>& msgs) {
Yin-Chia Yeh657c1872017-07-18 18:09:57 -07001163 // Ideally we should grab mLock, but that can lead to deadlock, and
1164 // it's not super important to get up to date value of mStatus for this
1165 // warning print, hence skipping the lock here
1166 if (mStatus == STATUS_ERROR) {
1167 // Per API contract, HAL should act as closed after device error
1168 // But mStatus can be set to error by framework as well, so just log
1169 // a warning here.
1170 ALOGW("%s: received notify message in error state.", __FUNCTION__);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07001171 }
Yin-Chia Yeh657c1872017-07-18 18:09:57 -07001172
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001173 sp<NotificationListener> listener;
1174 {
1175 std::lock_guard<std::mutex> l(mOutputLock);
1176 listener = mListener.promote();
1177 }
1178
1179 CaptureOutputStates states {
1180 mId,
Shuzhen Wangb7b42652020-05-07 11:59:02 -07001181 mInFlightLock, mLastCompletedRegularFrameNumber,
1182 mLastCompletedReprocessFrameNumber, mLastCompletedZslFrameNumber,
1183 mInFlightMap, mOutputLock, mResultQueue, mResultSignal,
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001184 mNextShutterFrameNumber,
1185 mNextReprocessShutterFrameNumber, mNextZslStillShutterFrameNumber,
1186 mNextResultFrameNumber,
1187 mNextReprocessResultFrameNumber, mNextZslStillResultFrameNumber,
1188 mUseHalBufManager, mUsePartialResult, mNeedFixupMonochromeTags,
1189 mNumPartialResults, mVendorTagId, mDeviceInfo, mPhysicalDeviceInfoMap,
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08001190 mResultMetadataQueue, mDistortionMappers, mZoomRatioMappers, mRotateAndCropMappers,
Shuzhen Wang316781a2020-08-18 18:11:01 -07001191 mTagMonitor, mInputStream, mOutputStreams, mSessionStatsBuilder, listener, *this, *this,
1192 *mInterface
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001193 };
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001194 for (const auto& msg : msgs) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001195 camera3::notify(states, msg);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001196 }
1197 return hardware::Void();
1198}
1199
Emilian Peevaebbe412018-01-15 13:53:24 +00001200status_t Camera3Device::captureList(const List<const PhysicalCameraSettingsList> &requestsList,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001201 const std::list<const SurfaceMap> &surfaceMaps,
Jianing Weicb0652e2014-03-12 18:29:36 -07001202 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -07001203 ATRACE_CALL();
1204
Emilian Peevaebbe412018-01-15 13:53:24 +00001205 return submitRequestsHelper(requestsList, surfaceMaps, /*repeating*/false, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -07001206}
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001207
Jianing Weicb0652e2014-03-12 18:29:36 -07001208status_t Camera3Device::setStreamingRequest(const CameraMetadata &request,
1209 int64_t* /*lastFrameNumber*/) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001210 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001211
Emilian Peevaebbe412018-01-15 13:53:24 +00001212 List<const PhysicalCameraSettingsList> requestsList;
Shuzhen Wang0129d522016-10-30 22:43:41 -07001213 std::list<const SurfaceMap> surfaceMaps;
Emilian Peevaebbe412018-01-15 13:53:24 +00001214 convertToRequestList(requestsList, surfaceMaps, request);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001215
Emilian Peevaebbe412018-01-15 13:53:24 +00001216 return setStreamingRequestList(requestsList, /*surfaceMap*/surfaceMaps,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001217 /*lastFrameNumber*/NULL);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001218}
1219
Emilian Peevaebbe412018-01-15 13:53:24 +00001220status_t Camera3Device::setStreamingRequestList(
1221 const List<const PhysicalCameraSettingsList> &requestsList,
1222 const std::list<const SurfaceMap> &surfaceMaps, int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -07001223 ATRACE_CALL();
1224
Emilian Peevaebbe412018-01-15 13:53:24 +00001225 return submitRequestsHelper(requestsList, surfaceMaps, /*repeating*/true, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -07001226}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001227
1228sp<Camera3Device::CaptureRequest> Camera3Device::setUpRequestLocked(
Emilian Peevaebbe412018-01-15 13:53:24 +00001229 const PhysicalCameraSettingsList &request, const SurfaceMap &surfaceMap) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001230 status_t res;
1231
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001232 if (mStatus == STATUS_UNCONFIGURED || mNeedConfig) {
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08001233 // This point should only be reached via API1 (API2 must explicitly call configureStreams)
1234 // so unilaterally select normal operating mode.
Emilian Peevaebbe412018-01-15 13:53:24 +00001235 res = filterParamsAndConfigureLocked(request.begin()->metadata,
Emilian Peevf4816702020-04-03 15:44:51 -07001236 CAMERA_STREAM_CONFIGURATION_NORMAL_MODE);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001237 // Stream configuration failed. Client might try other configuraitons.
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001238 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001239 CLOGE("Can't set up streams: %s (%d)", strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001240 return NULL;
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001241 } else if (mStatus == STATUS_UNCONFIGURED) {
1242 // Stream configuration successfully configure to empty stream configuration.
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001243 CLOGE("No streams configured");
1244 return NULL;
1245 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001246 }
1247
Shuzhen Wang0129d522016-10-30 22:43:41 -07001248 sp<CaptureRequest> newRequest = createCaptureRequest(request, surfaceMap);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001249 return newRequest;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001250}
1251
Jianing Weicb0652e2014-03-12 18:29:36 -07001252status_t Camera3Device::clearStreamingRequest(int64_t *lastFrameNumber) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001253 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001254 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001255 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001256
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001257 switch (mStatus) {
1258 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001259 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001260 return INVALID_OPERATION;
1261 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001262 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001263 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001264 case STATUS_UNCONFIGURED:
1265 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001266 case STATUS_ACTIVE:
1267 // OK
1268 break;
1269 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001270 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001271 return INVALID_OPERATION;
1272 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001273 ALOGV("Camera %s: Clearing repeating request", mId.string());
Jianing Weicb0652e2014-03-12 18:29:36 -07001274
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07001275 return mRequestThread->clearRepeatingRequests(lastFrameNumber);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001276}
1277
1278status_t Camera3Device::waitUntilRequestReceived(int32_t requestId, nsecs_t timeout) {
1279 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001280 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001281
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001282 return mRequestThread->waitUntilRequestProcessed(requestId, timeout);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001283}
1284
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001285status_t Camera3Device::createInputStream(
Shuzhen Wang83bff122020-11-20 15:51:39 -08001286 uint32_t width, uint32_t height, int format, bool isMultiResolution, int *id) {
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001287 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001288 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001289 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001290 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001291 ALOGV("Camera %s: Creating new input stream %d: %d x %d, format %d",
1292 mId.string(), mNextStreamId, width, height, format);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001293
1294 status_t res;
1295 bool wasActive = false;
1296
1297 switch (mStatus) {
1298 case STATUS_ERROR:
1299 ALOGE("%s: Device has encountered a serious error", __FUNCTION__);
1300 return INVALID_OPERATION;
1301 case STATUS_UNINITIALIZED:
1302 ALOGE("%s: Device not initialized", __FUNCTION__);
1303 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001304 case STATUS_UNCONFIGURED:
1305 case STATUS_CONFIGURED:
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001306 // OK
1307 break;
1308 case STATUS_ACTIVE:
1309 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001310 res = internalPauseAndWaitLocked(maxExpectedDuration);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001311 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001312 SET_ERR_L("Can't pause captures to reconfigure streams!");
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001313 return res;
1314 }
1315 wasActive = true;
1316 break;
1317 default:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001318 SET_ERR_L("%s: Unexpected status: %d", mStatus);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001319 return INVALID_OPERATION;
1320 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001321 assert(mStatus != STATUS_ACTIVE);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001322
1323 if (mInputStream != 0) {
1324 ALOGE("%s: Cannot create more than 1 input stream", __FUNCTION__);
1325 return INVALID_OPERATION;
1326 }
1327
1328 sp<Camera3InputStream> newStream = new Camera3InputStream(mNextStreamId,
1329 width, height, format);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001330 newStream->setStatusTracker(mStatusTracker);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001331
1332 mInputStream = newStream;
Shuzhen Wang83bff122020-11-20 15:51:39 -08001333 mIsInputStreamMultiResolution = isMultiResolution;
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001334
1335 *id = mNextStreamId++;
1336
1337 // Continue captures if active at start
1338 if (wasActive) {
1339 ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001340 // Reuse current operating mode and session parameters for new stream config
1341 res = configureStreamsLocked(mOperatingMode, mSessionParams);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001342 if (res != OK) {
1343 ALOGE("%s: Can't reconfigure device for new stream %d: %s (%d)",
1344 __FUNCTION__, mNextStreamId, strerror(-res), res);
1345 return res;
1346 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001347 internalResumeLocked();
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001348 }
1349
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001350 ALOGV("Camera %s: Created input stream", mId.string());
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001351 return OK;
1352}
1353
Eino-Ville Talvala727d1722015-06-09 13:44:19 -07001354status_t Camera3Device::createStream(sp<Surface> consumer,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001355 uint32_t width, uint32_t height, int format,
Emilian Peevf4816702020-04-03 15:44:51 -07001356 android_dataspace dataSpace, camera_stream_rotation_t rotation, int *id,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001357 const String8& physicalCameraId,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001358 const std::unordered_set<int32_t> &sensorPixelModesUsed,
1359 std::vector<int> *surfaceIds, int streamSetId, bool isShared, bool isMultiResolution,
1360 uint64_t consumerUsage) {
Shuzhen Wang0129d522016-10-30 22:43:41 -07001361 ATRACE_CALL();
1362
1363 if (consumer == nullptr) {
1364 ALOGE("%s: consumer must not be null", __FUNCTION__);
1365 return BAD_VALUE;
1366 }
1367
1368 std::vector<sp<Surface>> consumers;
1369 consumers.push_back(consumer);
1370
1371 return createStream(consumers, /*hasDeferredConsumer*/ false, width, height,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001372 format, dataSpace, rotation, id, physicalCameraId, sensorPixelModesUsed, surfaceIds,
1373 streamSetId, isShared, isMultiResolution, consumerUsage);
1374}
1375
1376static bool isRawFormat(int format) {
1377 switch (format) {
1378 case HAL_PIXEL_FORMAT_RAW16:
1379 case HAL_PIXEL_FORMAT_RAW12:
1380 case HAL_PIXEL_FORMAT_RAW10:
1381 case HAL_PIXEL_FORMAT_RAW_OPAQUE:
1382 return true;
1383 default:
1384 return false;
1385 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001386}
1387
1388status_t Camera3Device::createStream(const std::vector<sp<Surface>>& consumers,
1389 bool hasDeferredConsumer, uint32_t width, uint32_t height, int format,
Emilian Peevf4816702020-04-03 15:44:51 -07001390 android_dataspace dataSpace, camera_stream_rotation_t rotation, int *id,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001391 const String8& physicalCameraId, const std::unordered_set<int32_t> &sensorPixelModesUsed,
Shuzhen Wang83bff122020-11-20 15:51:39 -08001392 std::vector<int> *surfaceIds, int streamSetId, bool isShared, bool isMultiResolution,
1393 uint64_t consumerUsage) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001394 ATRACE_CALL();
Emilian Peev40ead602017-09-26 15:46:36 +01001395
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001396 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001397 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001398 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001399 ALOGV("Camera %s: Creating new stream %d: %d x %d, format %d, dataspace %d rotation %d"
Shuzhen Wang83bff122020-11-20 15:51:39 -08001400 " consumer usage %" PRIu64 ", isShared %d, physicalCameraId %s, isMultiResolution %d",
1401 mId.string(), mNextStreamId, width, height, format, dataSpace, rotation,
1402 consumerUsage, isShared, physicalCameraId.string(), isMultiResolution);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001403
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001404 status_t res;
1405 bool wasActive = false;
1406
1407 switch (mStatus) {
1408 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001409 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001410 return INVALID_OPERATION;
1411 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001412 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001413 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001414 case STATUS_UNCONFIGURED:
1415 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001416 // OK
1417 break;
1418 case STATUS_ACTIVE:
1419 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001420 res = internalPauseAndWaitLocked(maxExpectedDuration);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001421 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001422 SET_ERR_L("Can't pause captures to reconfigure streams!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001423 return res;
1424 }
1425 wasActive = true;
1426 break;
1427 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001428 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001429 return INVALID_OPERATION;
1430 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001431 assert(mStatus != STATUS_ACTIVE);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001432
1433 sp<Camera3OutputStream> newStream;
Zhijun He5d677d12016-05-29 16:52:39 -07001434
Shuzhen Wang0129d522016-10-30 22:43:41 -07001435 if (consumers.size() == 0 && !hasDeferredConsumer) {
1436 ALOGE("%s: Number of consumers cannot be smaller than 1", __FUNCTION__);
1437 return BAD_VALUE;
1438 }
Zhijun He5d677d12016-05-29 16:52:39 -07001439
Shuzhen Wang0129d522016-10-30 22:43:41 -07001440 if (hasDeferredConsumer && format != HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
Zhijun He5d677d12016-05-29 16:52:39 -07001441 ALOGE("Deferred consumer stream creation only support IMPLEMENTATION_DEFINED format");
1442 return BAD_VALUE;
1443 }
1444
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001445 if (isRawFormat(format) && sensorPixelModesUsed.size() > 1) {
1446 // We can't use one stream with a raw format in both sensor pixel modes since its going to
1447 // be found in only one sensor pixel mode.
1448 ALOGE("%s: RAW opaque stream cannot be used with > 1 sensor pixel modes", __FUNCTION__);
1449 return BAD_VALUE;
1450 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001451 if (format == HAL_PIXEL_FORMAT_BLOB) {
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -07001452 ssize_t blobBufferSize;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001453 if (dataSpace == HAL_DATASPACE_DEPTH) {
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -07001454 blobBufferSize = getPointCloudBufferSize();
1455 if (blobBufferSize <= 0) {
1456 SET_ERR_L("Invalid point cloud buffer size %zd", blobBufferSize);
1457 return BAD_VALUE;
1458 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001459 } else if (dataSpace == static_cast<android_dataspace>(HAL_DATASPACE_JPEG_APP_SEGMENTS)) {
1460 blobBufferSize = width * height;
1461 } else {
1462 blobBufferSize = getJpegBufferSize(width, height);
1463 if (blobBufferSize <= 0) {
1464 SET_ERR_L("Invalid jpeg buffer size %zd", blobBufferSize);
1465 return BAD_VALUE;
1466 }
Zhijun Hef7da0962014-04-24 13:27:56 -07001467 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001468 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001469 width, height, blobBufferSize, format, dataSpace, rotation,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001470 mTimestampOffset, physicalCameraId, sensorPixelModesUsed, streamSetId,
1471 isMultiResolution);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -08001472 } else if (format == HAL_PIXEL_FORMAT_RAW_OPAQUE) {
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001473 bool maxResolution =
1474 sensorPixelModesUsed.find(ANDROID_SENSOR_PIXEL_MODE_MAXIMUM_RESOLUTION) !=
1475 sensorPixelModesUsed.end();
1476 ssize_t rawOpaqueBufferSize = getRawOpaqueBufferSize(width, height, maxResolution);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -08001477 if (rawOpaqueBufferSize <= 0) {
1478 SET_ERR_L("Invalid RAW opaque buffer size %zd", rawOpaqueBufferSize);
1479 return BAD_VALUE;
1480 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001481 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001482 width, height, rawOpaqueBufferSize, format, dataSpace, rotation,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001483 mTimestampOffset, physicalCameraId, sensorPixelModesUsed, streamSetId,
1484 isMultiResolution);
Shuzhen Wang758c2152017-01-10 18:26:18 -08001485 } else if (isShared) {
1486 newStream = new Camera3SharedOutputStream(mNextStreamId, consumers,
1487 width, height, format, consumerUsage, dataSpace, rotation,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001488 mTimestampOffset, physicalCameraId, sensorPixelModesUsed, streamSetId,
1489 mUseHalBufManager);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001490 } else if (consumers.size() == 0 && hasDeferredConsumer) {
Zhijun He5d677d12016-05-29 16:52:39 -07001491 newStream = new Camera3OutputStream(mNextStreamId,
1492 width, height, format, consumerUsage, dataSpace, rotation,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001493 mTimestampOffset, physicalCameraId, sensorPixelModesUsed, streamSetId,
1494 isMultiResolution);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001495 } else {
Shuzhen Wang0129d522016-10-30 22:43:41 -07001496 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001497 width, height, format, dataSpace, rotation,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001498 mTimestampOffset, physicalCameraId, sensorPixelModesUsed, streamSetId,
1499 isMultiResolution);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001500 }
Emilian Peev40ead602017-09-26 15:46:36 +01001501
1502 size_t consumerCount = consumers.size();
1503 for (size_t i = 0; i < consumerCount; i++) {
1504 int id = newStream->getSurfaceId(consumers[i]);
1505 if (id < 0) {
1506 SET_ERR_L("Invalid surface id");
1507 return BAD_VALUE;
1508 }
1509 if (surfaceIds != nullptr) {
1510 surfaceIds->push_back(id);
1511 }
1512 }
1513
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001514 newStream->setStatusTracker(mStatusTracker);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001515
Emilian Peev08dd2452017-04-06 16:55:14 +01001516 newStream->setBufferManager(mBufferManager);
Zhijun He125684a2015-12-26 15:07:30 -08001517
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08001518 newStream->setImageDumpMask(mImageDumpMask);
1519
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001520 res = mOutputStreams.add(mNextStreamId, newStream);
1521 if (res < 0) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001522 SET_ERR_L("Can't add new stream to set: %s (%d)", strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001523 return res;
1524 }
1525
Shuzhen Wang316781a2020-08-18 18:11:01 -07001526 mSessionStatsBuilder.addStream(mNextStreamId);
1527
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001528 *id = mNextStreamId++;
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07001529 mNeedConfig = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001530
1531 // Continue captures if active at start
1532 if (wasActive) {
1533 ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001534 // Reuse current operating mode and session parameters for new stream config
1535 res = configureStreamsLocked(mOperatingMode, mSessionParams);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001536 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001537 CLOGE("Can't reconfigure device for new stream %d: %s (%d)",
1538 mNextStreamId, strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001539 return res;
1540 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001541 internalResumeLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001542 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001543 ALOGV("Camera %s: Created new stream", mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001544 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001545}
1546
Emilian Peev710c1422017-08-30 11:19:38 +01001547status_t Camera3Device::getStreamInfo(int id, StreamInfo *streamInfo) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001548 ATRACE_CALL();
Emilian Peev710c1422017-08-30 11:19:38 +01001549 if (nullptr == streamInfo) {
1550 return BAD_VALUE;
1551 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001552 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001553 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001554
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001555 switch (mStatus) {
1556 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001557 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001558 return INVALID_OPERATION;
1559 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001560 CLOGE("Device not initialized!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001561 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001562 case STATUS_UNCONFIGURED:
1563 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001564 case STATUS_ACTIVE:
1565 // OK
1566 break;
1567 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001568 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001569 return INVALID_OPERATION;
1570 }
1571
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001572 sp<Camera3StreamInterface> stream = mOutputStreams.get(id);
1573 if (stream == nullptr) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001574 CLOGE("Stream %d is unknown", id);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001575 return BAD_VALUE;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001576 }
1577
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001578 streamInfo->width = stream->getWidth();
1579 streamInfo->height = stream->getHeight();
1580 streamInfo->format = stream->getFormat();
1581 streamInfo->dataSpace = stream->getDataSpace();
1582 streamInfo->formatOverridden = stream->isFormatOverridden();
1583 streamInfo->originalFormat = stream->getOriginalFormat();
1584 streamInfo->dataSpaceOverridden = stream->isDataSpaceOverridden();
1585 streamInfo->originalDataSpace = stream->getOriginalDataSpace();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001586 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001587}
1588
1589status_t Camera3Device::setStreamTransform(int id,
1590 int transform) {
1591 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001592 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001593 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001594
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001595 switch (mStatus) {
1596 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001597 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001598 return INVALID_OPERATION;
1599 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001600 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001601 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001602 case STATUS_UNCONFIGURED:
1603 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001604 case STATUS_ACTIVE:
1605 // OK
1606 break;
1607 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001608 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001609 return INVALID_OPERATION;
1610 }
1611
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001612 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(id);
1613 if (stream == nullptr) {
1614 CLOGE("Stream %d does not exist", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001615 return BAD_VALUE;
1616 }
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001617 return stream->setTransform(transform);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001618}
1619
1620status_t Camera3Device::deleteStream(int id) {
1621 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001622 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001623 Mutex::Autolock l(mLock);
1624 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001625
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001626 ALOGV("%s: Camera %s: Deleting stream %d", __FUNCTION__, mId.string(), id);
Igor Murashkine2172be2013-05-28 15:31:39 -07001627
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001628 // CameraDevice semantics require device to already be idle before
1629 // deleteStream is called, unlike for createStream.
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001630 if (mStatus == STATUS_ACTIVE) {
Yin-Chia Yeh693047d2018-03-08 12:14:19 -08001631 ALOGW("%s: Camera %s: Device not idle", __FUNCTION__, mId.string());
Igor Murashkin52827132013-05-13 14:53:44 -07001632 return -EBUSY;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001633 }
1634
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07001635 if (mStatus == STATUS_ERROR) {
1636 ALOGW("%s: Camera %s: deleteStream not allowed in ERROR state",
1637 __FUNCTION__, mId.string());
1638 return -EBUSY;
1639 }
1640
Igor Murashkin2fba5842013-04-22 14:03:54 -07001641 sp<Camera3StreamInterface> deletedStream;
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001642 sp<Camera3StreamInterface> stream = mOutputStreams.get(id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001643 if (mInputStream != NULL && id == mInputStream->getId()) {
1644 deletedStream = mInputStream;
1645 mInputStream.clear();
1646 } else {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001647 if (stream == nullptr) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001648 CLOGE("Stream %d does not exist", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001649 return BAD_VALUE;
1650 }
Shuzhen Wang316781a2020-08-18 18:11:01 -07001651 mSessionStatsBuilder.removeStream(id);
Zhijun He5f446352014-01-22 09:49:33 -08001652 }
1653
1654 // Delete output stream or the output part of a bi-directional stream.
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001655 if (stream != nullptr) {
1656 deletedStream = stream;
1657 mOutputStreams.remove(id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001658 }
1659
1660 // Free up the stream endpoint so that it can be used by some other stream
1661 res = deletedStream->disconnect();
1662 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001663 SET_ERR_L("Can't disconnect deleted stream %d", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001664 // fall through since we want to still list the stream as deleted.
1665 }
1666 mDeletedStreams.add(deletedStream);
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07001667 mNeedConfig = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001668
1669 return res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001670}
1671
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001672status_t Camera3Device::configureStreams(const CameraMetadata& sessionParams, int operatingMode) {
Igor Murashkine2d167e2014-08-19 16:19:59 -07001673 ATRACE_CALL();
1674 ALOGV("%s: E", __FUNCTION__);
1675
1676 Mutex::Autolock il(mInterfaceLock);
1677 Mutex::Autolock l(mLock);
Chien-Yu Chen17338fc2015-06-18 16:30:12 -07001678
Emilian Peev811d2952018-05-25 11:08:40 +01001679 // In case the client doesn't include any session parameter, try a
1680 // speculative configuration using the values from the last cached
1681 // default request.
1682 if (sessionParams.isEmpty() &&
Emilian Peevf4816702020-04-03 15:44:51 -07001683 ((mLastTemplateId > 0) && (mLastTemplateId < CAMERA_TEMPLATE_COUNT)) &&
Emilian Peev811d2952018-05-25 11:08:40 +01001684 (!mRequestTemplateCache[mLastTemplateId].isEmpty())) {
1685 ALOGV("%s: Speculative session param configuration with template id: %d", __func__,
1686 mLastTemplateId);
1687 return filterParamsAndConfigureLocked(mRequestTemplateCache[mLastTemplateId],
1688 operatingMode);
1689 }
1690
Emilian Peevac3ce6c2017-12-12 15:27:02 +00001691 return filterParamsAndConfigureLocked(sessionParams, operatingMode);
1692}
1693
1694status_t Camera3Device::filterParamsAndConfigureLocked(const CameraMetadata& sessionParams,
1695 int operatingMode) {
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001696 //Filter out any incoming session parameters
1697 const CameraMetadata params(sessionParams);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001698 camera_metadata_entry_t availableSessionKeys = mDeviceInfo.find(
1699 ANDROID_REQUEST_AVAILABLE_SESSION_KEYS);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00001700 CameraMetadata filteredParams(availableSessionKeys.count);
1701 camera_metadata_t *meta = const_cast<camera_metadata_t *>(
1702 filteredParams.getAndLock());
1703 set_camera_metadata_vendor_id(meta, mVendorTagId);
1704 filteredParams.unlock(meta);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001705 if (availableSessionKeys.count > 0) {
1706 for (size_t i = 0; i < availableSessionKeys.count; i++) {
1707 camera_metadata_ro_entry entry = params.find(
1708 availableSessionKeys.data.i32[i]);
1709 if (entry.count > 0) {
1710 filteredParams.update(entry);
1711 }
1712 }
1713 }
1714
1715 return configureStreamsLocked(operatingMode, filteredParams);
Igor Murashkine2d167e2014-08-19 16:19:59 -07001716}
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001717
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07001718status_t Camera3Device::getInputBufferProducer(
1719 sp<IGraphicBufferProducer> *producer) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07001720 ATRACE_CALL();
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07001721 Mutex::Autolock il(mInterfaceLock);
1722 Mutex::Autolock l(mLock);
1723
1724 if (producer == NULL) {
1725 return BAD_VALUE;
1726 } else if (mInputStream == NULL) {
1727 return INVALID_OPERATION;
1728 }
1729
1730 return mInputStream->getInputBufferProducer(producer);
1731}
1732
Emilian Peevf4816702020-04-03 15:44:51 -07001733status_t Camera3Device::createDefaultRequest(camera_request_template_t templateId,
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001734 CameraMetadata *request) {
1735 ATRACE_CALL();
Alex Rayfe7e0c62013-05-30 00:12:13 -07001736 ALOGV("%s: for template %d", __FUNCTION__, templateId);
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08001737
Emilian Peevf4816702020-04-03 15:44:51 -07001738 if (templateId <= 0 || templateId >= CAMERA_TEMPLATE_COUNT) {
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08001739 android_errorWriteWithInfoLog(CameraService::SN_EVENT_LOG_ID, "26866110",
Jayant Chowdhary12361932018-08-27 14:46:13 -07001740 CameraThreadState::getCallingUid(), nullptr, 0);
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08001741 return BAD_VALUE;
1742 }
1743
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001744 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001745
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001746 {
1747 Mutex::Autolock l(mLock);
1748 switch (mStatus) {
1749 case STATUS_ERROR:
1750 CLOGE("Device has encountered a serious error");
1751 return INVALID_OPERATION;
1752 case STATUS_UNINITIALIZED:
1753 CLOGE("Device is not initialized!");
1754 return INVALID_OPERATION;
1755 case STATUS_UNCONFIGURED:
1756 case STATUS_CONFIGURED:
1757 case STATUS_ACTIVE:
1758 // OK
1759 break;
1760 default:
1761 SET_ERR_L("Unexpected status: %d", mStatus);
1762 return INVALID_OPERATION;
1763 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001764
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001765 if (!mRequestTemplateCache[templateId].isEmpty()) {
1766 *request = mRequestTemplateCache[templateId];
Emilian Peev811d2952018-05-25 11:08:40 +01001767 mLastTemplateId = templateId;
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001768 return OK;
1769 }
Zhijun Hea1530f12014-09-14 12:44:20 -07001770 }
1771
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001772 camera_metadata_t *rawRequest;
1773 status_t res = mInterface->constructDefaultRequestSettings(
Emilian Peevf4816702020-04-03 15:44:51 -07001774 (camera_request_template_t) templateId, &rawRequest);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001775
1776 {
1777 Mutex::Autolock l(mLock);
1778 if (res == BAD_VALUE) {
1779 ALOGI("%s: template %d is not supported on this camera device",
1780 __FUNCTION__, templateId);
1781 return res;
1782 } else if (res != OK) {
1783 CLOGE("Unable to construct request template %d: %s (%d)",
1784 templateId, strerror(-res), res);
1785 return res;
1786 }
1787
1788 set_camera_metadata_vendor_id(rawRequest, mVendorTagId);
1789 mRequestTemplateCache[templateId].acquire(rawRequest);
1790
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08001791 // Override the template request with zoomRatioMapper
1792 res = mZoomRatioMappers[mId.c_str()].initZoomRatioInTemplate(
1793 &mRequestTemplateCache[templateId]);
1794 if (res != OK) {
1795 CLOGE("Failed to update zoom ratio for template %d: %s (%d)",
1796 templateId, strerror(-res), res);
1797 return res;
1798 }
1799
Shuzhen Wangd25dc972020-03-24 17:11:43 -07001800 // Fill in JPEG_QUALITY if not available
1801 if (!mRequestTemplateCache[templateId].exists(ANDROID_JPEG_QUALITY)) {
1802 static const uint8_t kDefaultJpegQuality = 95;
1803 mRequestTemplateCache[templateId].update(ANDROID_JPEG_QUALITY,
1804 &kDefaultJpegQuality, 1);
1805 }
1806
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001807 *request = mRequestTemplateCache[templateId];
Emilian Peev811d2952018-05-25 11:08:40 +01001808 mLastTemplateId = templateId;
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001809 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001810 return OK;
1811}
1812
1813status_t Camera3Device::waitUntilDrained() {
1814 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001815 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001816 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001817 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001818
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001819 return waitUntilDrainedLocked(maxExpectedDuration);
Zhijun He69a37482014-03-23 18:44:49 -07001820}
1821
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001822status_t Camera3Device::waitUntilDrainedLocked(nsecs_t maxExpectedDuration) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001823 switch (mStatus) {
1824 case STATUS_UNINITIALIZED:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001825 case STATUS_UNCONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001826 ALOGV("%s: Already idle", __FUNCTION__);
1827 return OK;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001828 case STATUS_CONFIGURED:
1829 // To avoid race conditions, check with tracker to be sure
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001830 case STATUS_ERROR:
1831 case STATUS_ACTIVE:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001832 // Need to verify shut down
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001833 break;
1834 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001835 SET_ERR_L("Unexpected status: %d",mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001836 return INVALID_OPERATION;
1837 }
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07001838 ALOGV("%s: Camera %s: Waiting until idle (%" PRIi64 "ns)", __FUNCTION__, mId.string(),
1839 maxExpectedDuration);
1840 status_t res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
Eino-Ville Talvala9c8a0912014-09-14 14:52:19 -07001841 if (res != OK) {
Yin-Chia Yeh87b3ec02019-06-03 10:44:39 -07001842 mStatusTracker->dumpActiveComponents();
Eino-Ville Talvala9c8a0912014-09-14 14:52:19 -07001843 SET_ERR_L("Error waiting for HAL to drain: %s (%d)", strerror(-res),
1844 res);
1845 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001846 return res;
1847}
1848
Ruben Brunk183f0562015-08-12 12:55:02 -07001849void Camera3Device::internalUpdateStatusLocked(Status status) {
1850 mStatus = status;
1851 mRecentStatusUpdates.add(mStatus);
1852 mStatusChanged.broadcast();
1853}
1854
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001855// Pause to reconfigure
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001856status_t Camera3Device::internalPauseAndWaitLocked(nsecs_t maxExpectedDuration) {
Emilian Peeve86358b2019-02-15 13:51:39 -08001857 if (mRequestThread.get() != nullptr) {
1858 mRequestThread->setPaused(true);
1859 } else {
1860 return NO_INIT;
1861 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001862
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07001863 ALOGV("%s: Camera %s: Internal wait until idle (% " PRIi64 " ns)", __FUNCTION__, mId.string(),
1864 maxExpectedDuration);
1865 status_t res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001866 if (res != OK) {
1867 SET_ERR_L("Can't idle device in %f seconds!",
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07001868 maxExpectedDuration/1e9);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001869 }
1870
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001871 return res;
1872}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001873
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001874// Resume after internalPauseAndWaitLocked
1875status_t Camera3Device::internalResumeLocked() {
1876 status_t res;
1877
1878 mRequestThread->setPaused(false);
1879
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08001880 ALOGV("%s: Camera %s: Internal wait until active (% " PRIi64 " ns)", __FUNCTION__, mId.string(),
1881 kActiveTimeout);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001882 res = waitUntilStateThenRelock(/*active*/ true, kActiveTimeout);
1883 if (res != OK) {
1884 SET_ERR_L("Can't transition to active in %f seconds!",
1885 kActiveTimeout/1e9);
1886 }
1887 mPauseStateNotify = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001888 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001889}
1890
Ruben Brunk183f0562015-08-12 12:55:02 -07001891status_t Camera3Device::waitUntilStateThenRelock(bool active, nsecs_t timeout) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001892 status_t res = OK;
Ruben Brunk183f0562015-08-12 12:55:02 -07001893
1894 size_t startIndex = 0;
1895 if (mStatusWaiters == 0) {
1896 // Clear the list of recent statuses if there are no existing threads waiting on updates to
1897 // this status list
1898 mRecentStatusUpdates.clear();
1899 } else {
1900 // If other threads are waiting on updates to this status list, set the position of the
1901 // first element that this list will check rather than clearing the list.
1902 startIndex = mRecentStatusUpdates.size();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001903 }
1904
Ruben Brunk183f0562015-08-12 12:55:02 -07001905 mStatusWaiters++;
1906
Yin-Chia Yehe52b8fa2020-07-28 00:17:58 -07001907 bool signalPipelineDrain = false;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07001908 if (!active && mUseHalBufManager) {
1909 auto streamIds = mOutputStreams.getStreamIds();
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08001910 if (mStatus == STATUS_ACTIVE) {
1911 mRequestThread->signalPipelineDrain(streamIds);
Yin-Chia Yehe52b8fa2020-07-28 00:17:58 -07001912 signalPipelineDrain = true;
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08001913 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07001914 mRequestBufferSM.onWaitUntilIdle();
1915 }
1916
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001917 bool stateSeen = false;
1918 do {
Ruben Brunk183f0562015-08-12 12:55:02 -07001919 if (active == (mStatus == STATUS_ACTIVE)) {
1920 // Desired state is current
1921 break;
1922 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001923
1924 res = mStatusChanged.waitRelative(mLock, timeout);
1925 if (res != OK) break;
1926
Ruben Brunk183f0562015-08-12 12:55:02 -07001927 // This is impossible, but if not, could result in subtle deadlocks and invalid state
1928 // transitions.
1929 LOG_ALWAYS_FATAL_IF(startIndex > mRecentStatusUpdates.size(),
1930 "%s: Skipping status updates in Camera3Device, may result in deadlock.",
1931 __FUNCTION__);
1932
1933 // Encountered desired state since we began waiting
1934 for (size_t i = startIndex; i < mRecentStatusUpdates.size(); i++) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001935 if (active == (mRecentStatusUpdates[i] == STATUS_ACTIVE) ) {
1936 stateSeen = true;
1937 break;
1938 }
1939 }
1940 } while (!stateSeen);
1941
Yin-Chia Yehe52b8fa2020-07-28 00:17:58 -07001942 if (signalPipelineDrain) {
1943 mRequestThread->resetPipelineDrain();
1944 }
1945
Ruben Brunk183f0562015-08-12 12:55:02 -07001946 mStatusWaiters--;
1947
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001948 return res;
1949}
1950
1951
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001952status_t Camera3Device::setNotifyCallback(wp<NotificationListener> listener) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001953 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001954 std::lock_guard<std::mutex> l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001955
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001956 if (listener != NULL && mListener != NULL) {
1957 ALOGW("%s: Replacing old callback listener", __FUNCTION__);
1958 }
1959 mListener = listener;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001960 mRequestThread->setNotificationListener(listener);
1961 mPreparerThread->setNotificationListener(listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001962
1963 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001964}
1965
Eino-Ville Talvala46910bd2013-07-18 19:15:17 -07001966bool Camera3Device::willNotify3A() {
1967 return false;
1968}
1969
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001970status_t Camera3Device::waitForNextFrame(nsecs_t timeout) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07001971 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001972 std::unique_lock<std::mutex> l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001973
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001974 while (mResultQueue.empty()) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001975 auto st = mResultSignal.wait_for(l, std::chrono::nanoseconds(timeout));
1976 if (st == std::cv_status::timeout) {
1977 return TIMED_OUT;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001978 }
1979 }
1980 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001981}
1982
Jianing Weicb0652e2014-03-12 18:29:36 -07001983status_t Camera3Device::getNextResult(CaptureResult *frame) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001984 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001985 std::lock_guard<std::mutex> l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001986
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001987 if (mResultQueue.empty()) {
1988 return NOT_ENOUGH_DATA;
1989 }
1990
Jianing Weicb0652e2014-03-12 18:29:36 -07001991 if (frame == NULL) {
1992 ALOGE("%s: argument cannot be NULL", __FUNCTION__);
1993 return BAD_VALUE;
1994 }
1995
1996 CaptureResult &result = *(mResultQueue.begin());
1997 frame->mResultExtras = result.mResultExtras;
1998 frame->mMetadata.acquire(result.mMetadata);
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001999 frame->mPhysicalMetadatas = std::move(result.mPhysicalMetadatas);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002000 mResultQueue.erase(mResultQueue.begin());
2001
2002 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002003}
2004
2005status_t Camera3Device::triggerAutofocus(uint32_t id) {
2006 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002007 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002008
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002009 ALOGV("%s: Triggering autofocus, id %d", __FUNCTION__, id);
2010 // Mix-in this trigger into the next request and only the next request.
2011 RequestTrigger trigger[] = {
2012 {
2013 ANDROID_CONTROL_AF_TRIGGER,
2014 ANDROID_CONTROL_AF_TRIGGER_START
2015 },
2016 {
2017 ANDROID_CONTROL_AF_TRIGGER_ID,
2018 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07002019 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002020 };
2021
2022 return mRequestThread->queueTrigger(trigger,
2023 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002024}
2025
2026status_t Camera3Device::triggerCancelAutofocus(uint32_t id) {
2027 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002028 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002029
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002030 ALOGV("%s: Triggering cancel autofocus, id %d", __FUNCTION__, id);
2031 // Mix-in this trigger into the next request and only the next request.
2032 RequestTrigger trigger[] = {
2033 {
2034 ANDROID_CONTROL_AF_TRIGGER,
2035 ANDROID_CONTROL_AF_TRIGGER_CANCEL
2036 },
2037 {
2038 ANDROID_CONTROL_AF_TRIGGER_ID,
2039 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07002040 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002041 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002042
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002043 return mRequestThread->queueTrigger(trigger,
2044 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002045}
2046
2047status_t Camera3Device::triggerPrecaptureMetering(uint32_t id) {
2048 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002049 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002050
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002051 ALOGV("%s: Triggering precapture metering, id %d", __FUNCTION__, id);
2052 // Mix-in this trigger into the next request and only the next request.
2053 RequestTrigger trigger[] = {
2054 {
2055 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER,
2056 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_START
2057 },
2058 {
2059 ANDROID_CONTROL_AE_PRECAPTURE_ID,
2060 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07002061 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002062 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002063
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002064 return mRequestThread->queueTrigger(trigger,
2065 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002066}
2067
Jianing Weicb0652e2014-03-12 18:29:36 -07002068status_t Camera3Device::flush(int64_t *frameNumber) {
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07002069 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002070 ALOGV("%s: Camera %s: Flushing all requests", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002071 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07002072
Zhijun He7ef20392014-04-21 16:04:17 -07002073 {
2074 Mutex::Autolock l(mLock);
Emilian Peeved2ebe42018-09-25 16:59:09 +01002075
2076 // b/116514106 "disconnect()" can get called twice for the same device. The
2077 // camera device will not be initialized during the second run.
2078 if (mStatus == STATUS_UNINITIALIZED) {
2079 return OK;
2080 }
2081
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002082 mRequestThread->clear(/*out*/frameNumber);
Shuzhen Wang316781a2020-08-18 18:11:01 -07002083
2084 // Stop session and stream counter
2085 mSessionStatsBuilder.stopCounter();
Zhijun He7ef20392014-04-21 16:04:17 -07002086 }
2087
Emilian Peev08dd2452017-04-06 16:55:14 +01002088 return mRequestThread->flush();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07002089}
2090
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002091status_t Camera3Device::prepare(int streamId) {
Ruben Brunkc78ac262015-08-13 17:58:46 -07002092 return prepare(camera3::Camera3StreamInterface::ALLOCATE_PIPELINE_MAX, streamId);
2093}
2094
2095status_t Camera3Device::prepare(int maxCount, int streamId) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002096 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002097 ALOGV("%s: Camera %s: Preparing stream %d", __FUNCTION__, mId.string(), streamId);
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07002098 Mutex::Autolock il(mInterfaceLock);
2099 Mutex::Autolock l(mLock);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002100
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002101 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
2102 if (stream == nullptr) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002103 CLOGE("Stream %d does not exist", streamId);
2104 return BAD_VALUE;
2105 }
2106
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002107 if (stream->isUnpreparable() || stream->hasOutstandingBuffers() ) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07002108 CLOGE("Stream %d has already been a request target", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002109 return BAD_VALUE;
2110 }
2111
2112 if (mRequestThread->isStreamPending(stream)) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07002113 CLOGE("Stream %d is already a target in a pending request", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002114 return BAD_VALUE;
2115 }
2116
Ruben Brunkc78ac262015-08-13 17:58:46 -07002117 return mPreparerThread->prepare(maxCount, stream);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002118}
2119
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002120status_t Camera3Device::tearDown(int streamId) {
2121 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002122 ALOGV("%s: Camera %s: Tearing down stream %d", __FUNCTION__, mId.string(), streamId);
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002123 Mutex::Autolock il(mInterfaceLock);
2124 Mutex::Autolock l(mLock);
2125
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002126 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
2127 if (stream == nullptr) {
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002128 CLOGE("Stream %d does not exist", streamId);
2129 return BAD_VALUE;
2130 }
2131
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002132 if (stream->hasOutstandingBuffers() || mRequestThread->isStreamPending(stream)) {
2133 CLOGE("Stream %d is a target of a in-progress request", streamId);
2134 return BAD_VALUE;
2135 }
2136
2137 return stream->tearDown();
2138}
2139
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002140status_t Camera3Device::addBufferListenerForStream(int streamId,
2141 wp<Camera3StreamBufferListener> listener) {
2142 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002143 ALOGV("%s: Camera %s: Adding buffer listener for stream %d", __FUNCTION__, mId.string(), streamId);
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002144 Mutex::Autolock il(mInterfaceLock);
2145 Mutex::Autolock l(mLock);
2146
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002147 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
2148 if (stream == nullptr) {
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002149 CLOGE("Stream %d does not exist", streamId);
2150 return BAD_VALUE;
2151 }
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002152 stream->addBufferListener(listener);
2153
2154 return OK;
2155}
2156
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002157/**
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002158 * Methods called by subclasses
2159 */
2160
2161void Camera3Device::notifyStatus(bool idle) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002162 ATRACE_CALL();
Shuzhen Wang316781a2020-08-18 18:11:01 -07002163 std::vector<int> streamIds;
2164 std::vector<hardware::CameraStreamStats> streamStats;
2165
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002166 {
2167 // Need mLock to safely update state and synchronize to current
2168 // state of methods in flight.
2169 Mutex::Autolock l(mLock);
2170 // We can get various system-idle notices from the status tracker
2171 // while starting up. Only care about them if we've actually sent
2172 // in some requests recently.
2173 if (mStatus != STATUS_ACTIVE && mStatus != STATUS_CONFIGURED) {
2174 return;
2175 }
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08002176 ALOGV("%s: Camera %s: Now %s, pauseState: %s", __FUNCTION__, mId.string(),
2177 idle ? "idle" : "active", mPauseStateNotify ? "true" : "false");
Ruben Brunk183f0562015-08-12 12:55:02 -07002178 internalUpdateStatusLocked(idle ? STATUS_CONFIGURED : STATUS_ACTIVE);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002179
2180 // Skip notifying listener if we're doing some user-transparent
2181 // state changes
2182 if (mPauseStateNotify) return;
Shuzhen Wang316781a2020-08-18 18:11:01 -07002183
2184 // Populate stream statistics in case of Idle
2185 if (idle) {
2186 for (size_t i = 0; i < mOutputStreams.size(); i++) {
2187 auto stream = mOutputStreams[i];
2188 if (stream.get() == nullptr) continue;
2189 streamIds.push_back(stream->getId());
2190 Camera3Stream* camera3Stream = Camera3Stream::cast(stream->asHalStream());
2191 int64_t usage = 0LL;
2192 if (camera3Stream != nullptr) {
2193 usage = camera3Stream->getUsage();
2194 }
2195 streamStats.emplace_back(stream->getWidth(), stream->getHeight(),
2196 stream->getFormat(), stream->getDataSpace(), usage,
2197 stream->getMaxHalBuffers(),
2198 stream->getMaxTotalBuffers() - stream->getMaxHalBuffers());
2199 }
2200 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002201 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002202
2203 sp<NotificationListener> listener;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002204 {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002205 std::lock_guard<std::mutex> l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002206 listener = mListener.promote();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002207 }
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07002208 status_t res = OK;
2209 if (listener != nullptr) {
2210 if (idle) {
2211 // Get session stats from the builder, and notify the listener.
2212 int64_t requestCount, resultErrorCount;
2213 bool deviceError;
2214 std::map<int, StreamStats> streamStatsMap;
2215 mSessionStatsBuilder.buildAndReset(&requestCount, &resultErrorCount,
2216 &deviceError, &streamStatsMap);
2217 for (size_t i = 0; i < streamIds.size(); i++) {
2218 int streamId = streamIds[i];
2219 auto stats = streamStatsMap.find(streamId);
2220 if (stats != streamStatsMap.end()) {
2221 streamStats[i].mRequestCount = stats->second.mRequestedFrameCount;
2222 streamStats[i].mErrorCount = stats->second.mDroppedFrameCount;
2223 streamStats[i].mStartLatencyMs = stats->second.mStartLatencyMs;
2224 streamStats[i].mHistogramType =
2225 hardware::CameraStreamStats::HISTOGRAM_TYPE_CAPTURE_LATENCY;
2226 streamStats[i].mHistogramBins.assign(
2227 stats->second.mCaptureLatencyBins.begin(),
2228 stats->second.mCaptureLatencyBins.end());
2229 streamStats[i].mHistogramCounts.assign(
2230 stats->second.mCaptureLatencyHistogram.begin(),
2231 stats->second.mCaptureLatencyHistogram.end());
2232 }
Shuzhen Wang316781a2020-08-18 18:11:01 -07002233 }
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07002234 listener->notifyIdle(requestCount, resultErrorCount, deviceError, streamStats);
2235 } else {
2236 res = listener->notifyActive();
Shuzhen Wang316781a2020-08-18 18:11:01 -07002237 }
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07002238 }
2239 if (res != OK) {
2240 SET_ERR("Camera access permission lost mid-operation: %s (%d)",
2241 strerror(-res), res);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002242 }
2243}
2244
Shuzhen Wang758c2152017-01-10 18:26:18 -08002245status_t Camera3Device::setConsumerSurfaces(int streamId,
Emilian Peev40ead602017-09-26 15:46:36 +01002246 const std::vector<sp<Surface>>& consumers, std::vector<int> *surfaceIds) {
Zhijun He5d677d12016-05-29 16:52:39 -07002247 ATRACE_CALL();
Shuzhen Wang758c2152017-01-10 18:26:18 -08002248 ALOGV("%s: Camera %s: set consumer surface for stream %d",
2249 __FUNCTION__, mId.string(), streamId);
Emilian Peev40ead602017-09-26 15:46:36 +01002250
2251 if (surfaceIds == nullptr) {
2252 return BAD_VALUE;
2253 }
2254
Zhijun He5d677d12016-05-29 16:52:39 -07002255 Mutex::Autolock il(mInterfaceLock);
2256 Mutex::Autolock l(mLock);
2257
Shuzhen Wang758c2152017-01-10 18:26:18 -08002258 if (consumers.size() == 0) {
2259 CLOGE("No consumer is passed!");
Zhijun He5d677d12016-05-29 16:52:39 -07002260 return BAD_VALUE;
2261 }
2262
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002263 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
2264 if (stream == nullptr) {
Zhijun He5d677d12016-05-29 16:52:39 -07002265 CLOGE("Stream %d is unknown", streamId);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002266 return BAD_VALUE;
Zhijun He5d677d12016-05-29 16:52:39 -07002267 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002268
2269 // isConsumerConfigurationDeferred will be off after setConsumers
2270 bool isDeferred = stream->isConsumerConfigurationDeferred();
Shuzhen Wang758c2152017-01-10 18:26:18 -08002271 status_t res = stream->setConsumers(consumers);
Zhijun He5d677d12016-05-29 16:52:39 -07002272 if (res != OK) {
2273 CLOGE("Stream %d set consumer failed (error %d %s) ", streamId, res, strerror(-res));
2274 return res;
2275 }
2276
Emilian Peev40ead602017-09-26 15:46:36 +01002277 for (auto &consumer : consumers) {
2278 int id = stream->getSurfaceId(consumer);
2279 if (id < 0) {
2280 CLOGE("Invalid surface id!");
2281 return BAD_VALUE;
2282 }
2283 surfaceIds->push_back(id);
2284 }
2285
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002286 if (isDeferred) {
Shuzhen Wang0129d522016-10-30 22:43:41 -07002287 if (!stream->isConfiguring()) {
2288 CLOGE("Stream %d was already fully configured.", streamId);
2289 return INVALID_OPERATION;
2290 }
Zhijun He5d677d12016-05-29 16:52:39 -07002291
Shuzhen Wang0129d522016-10-30 22:43:41 -07002292 res = stream->finishConfiguration();
2293 if (res != OK) {
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002294 // If finishConfiguration fails due to abandoned surface, do not set
2295 // device to error state.
2296 bool isSurfaceAbandoned =
2297 (res == NO_INIT || res == DEAD_OBJECT) && stream->isAbandoned();
2298 if (!isSurfaceAbandoned) {
2299 SET_ERR_L("Can't finish configuring output stream %d: %s (%d)",
2300 stream->getId(), strerror(-res), res);
2301 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07002302 return res;
2303 }
Zhijun He5d677d12016-05-29 16:52:39 -07002304 }
2305
2306 return OK;
2307}
2308
Emilian Peev40ead602017-09-26 15:46:36 +01002309status_t Camera3Device::updateStream(int streamId, const std::vector<sp<Surface>> &newSurfaces,
2310 const std::vector<OutputStreamInfo> &outputInfo,
2311 const std::vector<size_t> &removedSurfaceIds, KeyedVector<sp<Surface>, size_t> *outputMap) {
2312 Mutex::Autolock il(mInterfaceLock);
2313 Mutex::Autolock l(mLock);
2314
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002315 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
2316 if (stream == nullptr) {
Emilian Peev40ead602017-09-26 15:46:36 +01002317 CLOGE("Stream %d is unknown", streamId);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002318 return BAD_VALUE;
Emilian Peev40ead602017-09-26 15:46:36 +01002319 }
2320
2321 for (const auto &it : removedSurfaceIds) {
2322 if (mRequestThread->isOutputSurfacePending(streamId, it)) {
2323 CLOGE("Shared surface still part of a pending request!");
2324 return -EBUSY;
2325 }
2326 }
2327
Emilian Peev40ead602017-09-26 15:46:36 +01002328 status_t res = stream->updateStream(newSurfaces, outputInfo, removedSurfaceIds, outputMap);
2329 if (res != OK) {
2330 CLOGE("Stream %d failed to update stream (error %d %s) ",
2331 streamId, res, strerror(-res));
2332 if (res == UNKNOWN_ERROR) {
2333 SET_ERR_L("%s: Stream update failed to revert to previous output configuration!",
2334 __FUNCTION__);
2335 }
2336 return res;
2337 }
2338
2339 return res;
2340}
2341
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002342status_t Camera3Device::dropStreamBuffers(bool dropping, int streamId) {
2343 Mutex::Autolock il(mInterfaceLock);
2344 Mutex::Autolock l(mLock);
2345
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002346 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
2347 if (stream == nullptr) {
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002348 ALOGE("%s: Stream %d is not found.", __FUNCTION__, streamId);
2349 return BAD_VALUE;
2350 }
Shuzhen Wang316781a2020-08-18 18:11:01 -07002351
2352 if (dropping) {
2353 mSessionStatsBuilder.stopCounter(streamId);
2354 } else {
2355 mSessionStatsBuilder.startCounter(streamId);
2356 }
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002357 return stream->dropBuffers(dropping);
2358}
2359
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002360/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002361 * Camera3Device private methods
2362 */
2363
2364sp<Camera3Device::CaptureRequest> Camera3Device::createCaptureRequest(
Emilian Peevaebbe412018-01-15 13:53:24 +00002365 const PhysicalCameraSettingsList &request, const SurfaceMap &surfaceMap) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002366 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002367
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08002368 sp<CaptureRequest> newRequest = new CaptureRequest();
Emilian Peevaebbe412018-01-15 13:53:24 +00002369 newRequest->mSettingsList = request;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002370
2371 camera_metadata_entry_t inputStreams =
Emilian Peevaebbe412018-01-15 13:53:24 +00002372 newRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_INPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002373 if (inputStreams.count > 0) {
2374 if (mInputStream == NULL ||
Zhijun Hed1d64672013-09-06 15:00:01 -07002375 mInputStream->getId() != inputStreams.data.i32[0]) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002376 CLOGE("Request references unknown input stream %d",
2377 inputStreams.data.u8[0]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002378 return NULL;
2379 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002380
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002381 if (mInputStream->isConfiguring()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002382 SET_ERR_L("%s: input stream %d is not configured!",
2383 __FUNCTION__, mInputStream->getId());
2384 return NULL;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002385 }
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07002386 // Check if stream prepare is blocking requests.
2387 if (mInputStream->isBlockedByPrepare()) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002388 CLOGE("Request references an input stream that's being prepared!");
2389 return NULL;
2390 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002391
2392 newRequest->mInputStream = mInputStream;
Emilian Peevaebbe412018-01-15 13:53:24 +00002393 newRequest->mSettingsList.begin()->metadata.erase(ANDROID_REQUEST_INPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002394 }
2395
2396 camera_metadata_entry_t streams =
Emilian Peevaebbe412018-01-15 13:53:24 +00002397 newRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_OUTPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002398 if (streams.count == 0) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002399 CLOGE("Zero output streams specified!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002400 return NULL;
2401 }
2402
2403 for (size_t i = 0; i < streams.count; i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002404 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streams.data.i32[i]);
2405 if (stream == nullptr) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002406 CLOGE("Request references unknown stream %d",
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002407 streams.data.i32[i]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002408 return NULL;
2409 }
Zhijun He5d677d12016-05-29 16:52:39 -07002410 // It is illegal to include a deferred consumer output stream into a request
Shuzhen Wang0129d522016-10-30 22:43:41 -07002411 auto iter = surfaceMap.find(streams.data.i32[i]);
2412 if (iter != surfaceMap.end()) {
2413 const std::vector<size_t>& surfaces = iter->second;
2414 for (const auto& surface : surfaces) {
2415 if (stream->isConsumerConfigurationDeferred(surface)) {
2416 CLOGE("Stream %d surface %zu hasn't finished configuration yet "
2417 "due to deferred consumer", stream->getId(), surface);
2418 return NULL;
2419 }
2420 }
Yin-Chia Yeh0b287572018-10-15 12:38:13 -07002421 newRequest->mOutputSurfaces[streams.data.i32[i]] = surfaces;
Zhijun He5d677d12016-05-29 16:52:39 -07002422 }
2423
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002424 if (stream->isConfiguring()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002425 SET_ERR_L("%s: stream %d is not configured!", __FUNCTION__, stream->getId());
2426 return NULL;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002427 }
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07002428 // Check if stream prepare is blocking requests.
2429 if (stream->isBlockedByPrepare()) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002430 CLOGE("Request references an output stream that's being prepared!");
2431 return NULL;
2432 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002433
2434 newRequest->mOutputStreams.push(stream);
2435 }
Emilian Peevaebbe412018-01-15 13:53:24 +00002436 newRequest->mSettingsList.begin()->metadata.erase(ANDROID_REQUEST_OUTPUT_STREAMS);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07002437 newRequest->mBatchSize = 1;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002438
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08002439 auto rotateAndCropEntry =
2440 newRequest->mSettingsList.begin()->metadata.find(ANDROID_SCALER_ROTATE_AND_CROP);
2441 if (rotateAndCropEntry.count > 0 &&
2442 rotateAndCropEntry.data.u8[0] == ANDROID_SCALER_ROTATE_AND_CROP_AUTO) {
2443 newRequest->mRotateAndCropAuto = true;
2444 } else {
2445 newRequest->mRotateAndCropAuto = false;
2446 }
2447
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07002448 auto zoomRatioEntry =
2449 newRequest->mSettingsList.begin()->metadata.find(ANDROID_CONTROL_ZOOM_RATIO);
2450 if (zoomRatioEntry.count > 0 &&
2451 zoomRatioEntry.data.f[0] == 1.0f) {
2452 newRequest->mZoomRatioIs1x = true;
2453 } else {
2454 newRequest->mZoomRatioIs1x = false;
2455 }
2456
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08002457 if (mSupportCameraMute) {
2458 auto testPatternModeEntry =
2459 newRequest->mSettingsList.begin()->metadata.find(ANDROID_SENSOR_TEST_PATTERN_MODE);
2460 newRequest->mOriginalTestPatternMode = testPatternModeEntry.count > 0 ?
2461 testPatternModeEntry.data.i32[0] :
2462 ANDROID_SENSOR_TEST_PATTERN_MODE_OFF;
2463
2464 auto testPatternDataEntry =
2465 newRequest->mSettingsList.begin()->metadata.find(ANDROID_SENSOR_TEST_PATTERN_DATA);
Eino-Ville Talvalac2459842021-07-22 16:36:36 -07002466 if (testPatternDataEntry.count >= 4) {
2467 memcpy(newRequest->mOriginalTestPatternData, testPatternDataEntry.data.i32,
2468 sizeof(CaptureRequest::mOriginalTestPatternData));
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08002469 } else {
2470 newRequest->mOriginalTestPatternData[0] = 0;
2471 newRequest->mOriginalTestPatternData[1] = 0;
2472 newRequest->mOriginalTestPatternData[2] = 0;
2473 newRequest->mOriginalTestPatternData[3] = 0;
2474 }
2475 }
2476
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002477 return newRequest;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002478}
2479
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002480void Camera3Device::cancelStreamsConfigurationLocked() {
2481 int res = OK;
2482 if (mInputStream != NULL && mInputStream->isConfiguring()) {
2483 res = mInputStream->cancelConfiguration();
2484 if (res != OK) {
2485 CLOGE("Can't cancel configuring input stream %d: %s (%d)",
2486 mInputStream->getId(), strerror(-res), res);
2487 }
2488 }
2489
2490 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002491 sp<Camera3OutputStreamInterface> outputStream = mOutputStreams[i];
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002492 if (outputStream->isConfiguring()) {
2493 res = outputStream->cancelConfiguration();
2494 if (res != OK) {
2495 CLOGE("Can't cancel configuring output stream %d: %s (%d)",
2496 outputStream->getId(), strerror(-res), res);
2497 }
2498 }
2499 }
2500
2501 // Return state to that at start of call, so that future configures
2502 // properly clean things up
2503 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
2504 mNeedConfig = true;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002505
2506 res = mPreparerThread->resume();
2507 if (res != OK) {
2508 ALOGE("%s: Camera %s: Preparer thread failed to resume!", __FUNCTION__, mId.string());
2509 }
2510}
2511
Emilian Peev0d0191e2020-04-21 17:01:18 -07002512bool Camera3Device::checkAbandonedStreamsLocked() {
2513 if ((mInputStream.get() != nullptr) && (mInputStream->isAbandoned())) {
2514 return true;
2515 }
2516
2517 for (size_t i = 0; i < mOutputStreams.size(); i++) {
2518 auto stream = mOutputStreams[i];
2519 if ((stream.get() != nullptr) && (stream->isAbandoned())) {
2520 return true;
2521 }
2522 }
2523
2524 return false;
2525}
2526
Emilian Peev3bead5f2020-05-28 17:29:08 -07002527bool Camera3Device::reconfigureCamera(const CameraMetadata& sessionParams, int clientStatusId) {
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002528 ATRACE_CALL();
2529 bool ret = false;
2530
Shuzhen Wang316781a2020-08-18 18:11:01 -07002531 nsecs_t startTime = systemTime();
2532
Jayant Chowdhary646c31b2020-01-30 13:09:59 -08002533 Mutex::Autolock il(mInterfaceLock);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002534 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
2535
2536 Mutex::Autolock l(mLock);
Emilian Peev0d0191e2020-04-21 17:01:18 -07002537 if (checkAbandonedStreamsLocked()) {
2538 ALOGW("%s: Abandoned stream detected, session parameters can't be applied correctly!",
2539 __FUNCTION__);
2540 return true;
2541 }
2542
Emilian Peev3bead5f2020-05-28 17:29:08 -07002543 status_t rc = NO_ERROR;
2544 bool markClientActive = false;
2545 if (mStatus == STATUS_ACTIVE) {
2546 markClientActive = true;
2547 mPauseStateNotify = true;
2548 mStatusTracker->markComponentIdle(clientStatusId, Fence::NO_FENCE);
2549
2550 rc = internalPauseAndWaitLocked(maxExpectedDuration);
2551 }
2552
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002553 if (rc == NO_ERROR) {
2554 mNeedConfig = true;
2555 rc = configureStreamsLocked(mOperatingMode, sessionParams, /*notifyRequestThread*/ false);
2556 if (rc == NO_ERROR) {
2557 ret = true;
2558 mPauseStateNotify = false;
2559 //Moving to active state while holding 'mLock' is important.
2560 //There could be pending calls to 'create-/deleteStream' which
2561 //will trigger another stream configuration while the already
2562 //present streams end up with outstanding buffers that will
2563 //not get drained.
2564 internalUpdateStatusLocked(STATUS_ACTIVE);
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002565 } else if (rc == DEAD_OBJECT) {
2566 // DEAD_OBJECT can be returned if either the consumer surface is
2567 // abandoned, or the HAL has died.
2568 // - If the HAL has died, configureStreamsLocked call will set
2569 // device to error state,
2570 // - If surface is abandoned, we should not set device to error
2571 // state.
2572 ALOGE("Failed to re-configure camera due to abandoned surface");
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002573 } else {
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002574 SET_ERR_L("Failed to re-configure camera: %d", rc);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002575 }
2576 } else {
2577 ALOGE("%s: Failed to pause streaming: %d", __FUNCTION__, rc);
2578 }
2579
Shuzhen Wang316781a2020-08-18 18:11:01 -07002580 CameraServiceProxyWrapper::logStreamConfigured(mId, mOperatingMode, true /*internalReconfig*/,
2581 ns2ms(systemTime() - startTime));
2582
Emilian Peev3bead5f2020-05-28 17:29:08 -07002583 if (markClientActive) {
2584 mStatusTracker->markComponentActive(clientStatusId);
2585 }
2586
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002587 return ret;
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002588}
2589
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002590status_t Camera3Device::configureStreamsLocked(int operatingMode,
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002591 const CameraMetadata& sessionParams, bool notifyRequestThread) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002592 ATRACE_CALL();
2593 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002594
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002595 if (mStatus != STATUS_UNCONFIGURED && mStatus != STATUS_CONFIGURED) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002596 CLOGE("Not idle");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002597 return INVALID_OPERATION;
2598 }
2599
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08002600 if (operatingMode < 0) {
2601 CLOGE("Invalid operating mode: %d", operatingMode);
2602 return BAD_VALUE;
2603 }
2604
2605 bool isConstrainedHighSpeed =
2606 static_cast<int>(StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE) ==
2607 operatingMode;
2608
2609 if (mOperatingMode != operatingMode) {
2610 mNeedConfig = true;
2611 mIsConstrainedHighSpeedConfiguration = isConstrainedHighSpeed;
2612 mOperatingMode = operatingMode;
2613 }
2614
Shuzhen Wang0cf01cb2019-09-05 13:33:06 -07002615 // In case called from configureStreams, abort queued input buffers not belonging to
2616 // any pending requests.
2617 if (mInputStream != NULL && notifyRequestThread) {
2618 while (true) {
Emilian Peevf4816702020-04-03 15:44:51 -07002619 camera_stream_buffer_t inputBuffer;
Shuzhen Wang83bff122020-11-20 15:51:39 -08002620 camera3::Size inputBufferSize;
Shuzhen Wang0cf01cb2019-09-05 13:33:06 -07002621 status_t res = mInputStream->getInputBuffer(&inputBuffer,
Shuzhen Wang83bff122020-11-20 15:51:39 -08002622 &inputBufferSize, /*respectHalLimit*/ false);
Shuzhen Wang0cf01cb2019-09-05 13:33:06 -07002623 if (res != OK) {
2624 // Exhausted acquiring all input buffers.
2625 break;
2626 }
2627
Emilian Peevf4816702020-04-03 15:44:51 -07002628 inputBuffer.status = CAMERA_BUFFER_STATUS_ERROR;
Shuzhen Wang0cf01cb2019-09-05 13:33:06 -07002629 res = mInputStream->returnInputBuffer(inputBuffer);
2630 if (res != OK) {
2631 ALOGE("%s: %d: couldn't return input buffer while clearing input queue: "
2632 "%s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
2633 }
2634 }
2635 }
2636
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002637 if (!mNeedConfig) {
2638 ALOGV("%s: Skipping config, no stream changes", __FUNCTION__);
2639 return OK;
2640 }
2641
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002642 // Workaround for device HALv3.2 or older spec bug - zero streams requires
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002643 // adding a fake stream instead.
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002644 // TODO: Bug: 17321404 for fixing the HAL spec and removing this workaround.
2645 if (mOutputStreams.size() == 0) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002646 addFakeStreamLocked();
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002647 } else {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002648 tryRemoveFakeStreamLocked();
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002649 }
2650
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002651 // Start configuring the streams
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002652 ALOGV("%s: Camera %s: Starting stream configuration", __FUNCTION__, mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002653
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002654 mPreparerThread->pause();
2655
Emilian Peevf4816702020-04-03 15:44:51 -07002656 camera_stream_configuration config;
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -08002657 config.operation_mode = mOperatingMode;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002658 config.num_streams = (mInputStream != NULL) + mOutputStreams.size();
Shuzhen Wang83bff122020-11-20 15:51:39 -08002659 config.input_is_multi_resolution = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002660
Emilian Peevf4816702020-04-03 15:44:51 -07002661 Vector<camera3::camera_stream_t*> streams;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002662 streams.setCapacity(config.num_streams);
Emilian Peev192ee832018-01-31 14:46:47 +00002663 std::vector<uint32_t> bufferSizes(config.num_streams, 0);
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002664
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002665
2666 if (mInputStream != NULL) {
Emilian Peevf4816702020-04-03 15:44:51 -07002667 camera3::camera_stream_t *inputStream;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002668 inputStream = mInputStream->startConfiguration();
2669 if (inputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002670 CLOGE("Can't start input stream configuration");
2671 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002672 return INVALID_OPERATION;
2673 }
2674 streams.add(inputStream);
Shuzhen Wang83bff122020-11-20 15:51:39 -08002675
2676 config.input_is_multi_resolution = mIsInputStreamMultiResolution;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002677 }
2678
Shuzhen Wang99080502021-03-07 21:08:20 -08002679 mGroupIdPhysicalCameraMap.clear();
Emilian Peeve23f1d92021-09-20 14:56:01 -07002680 bool composerSurfacePresent = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002681 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Igor Murashkin2fba5842013-04-22 14:03:54 -07002682
2683 // Don't configure bidi streams twice, nor add them twice to the list
2684 if (mOutputStreams[i].get() ==
2685 static_cast<Camera3StreamInterface*>(mInputStream.get())) {
2686
2687 config.num_streams--;
2688 continue;
2689 }
2690
Emilian Peevf4816702020-04-03 15:44:51 -07002691 camera3::camera_stream_t *outputStream;
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002692 outputStream = mOutputStreams[i]->startConfiguration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002693 if (outputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002694 CLOGE("Can't start output stream configuration");
2695 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002696 return INVALID_OPERATION;
2697 }
2698 streams.add(outputStream);
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002699
Shuzhen Wangb7ab1e42019-02-20 15:42:23 -08002700 if (outputStream->format == HAL_PIXEL_FORMAT_BLOB) {
Emilian Peev192ee832018-01-31 14:46:47 +00002701 size_t k = i + ((mInputStream != nullptr) ? 1 : 0); // Input stream if present should
2702 // always occupy the initial entry.
Shuzhen Wangb7ab1e42019-02-20 15:42:23 -08002703 if (outputStream->data_space == HAL_DATASPACE_V0_JFIF) {
2704 bufferSizes[k] = static_cast<uint32_t>(
2705 getJpegBufferSize(outputStream->width, outputStream->height));
2706 } else if (outputStream->data_space ==
2707 static_cast<android_dataspace>(HAL_DATASPACE_JPEG_APP_SEGMENTS)) {
2708 bufferSizes[k] = outputStream->width * outputStream->height;
2709 } else {
2710 ALOGW("%s: Blob dataSpace %d not supported",
2711 __FUNCTION__, outputStream->data_space);
2712 }
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002713 }
Shuzhen Wang99080502021-03-07 21:08:20 -08002714
2715 if (mOutputStreams[i]->isMultiResolution()) {
2716 int32_t streamGroupId = mOutputStreams[i]->getHalStreamGroupId();
2717 const String8& physicalCameraId = mOutputStreams[i]->getPhysicalCameraId();
2718 mGroupIdPhysicalCameraMap[streamGroupId].insert(physicalCameraId);
2719 }
Emilian Peeve23f1d92021-09-20 14:56:01 -07002720
2721 if (outputStream->usage & GraphicBuffer::USAGE_HW_COMPOSER) {
2722 composerSurfacePresent = true;
2723 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002724 }
2725
2726 config.streams = streams.editArray();
2727
2728 // Do the HAL configuration; will potentially touch stream
Shuzhen Wang92653952019-05-07 15:11:43 -07002729 // max_buffers, usage, and priv fields, as well as data_space and format
2730 // fields for IMPLEMENTATION_DEFINED formats.
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002731
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002732 const camera_metadata_t *sessionBuffer = sessionParams.getAndLock();
Emilian Peev192ee832018-01-31 14:46:47 +00002733 res = mInterface->configureStreams(sessionBuffer, &config, bufferSizes);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002734 sessionParams.unlock(sessionBuffer);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002735
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002736 if (res == BAD_VALUE) {
2737 // HAL rejected this set of streams as unsupported, clean up config
2738 // attempt and return to unconfigured state
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002739 CLOGE("Set of requested inputs/outputs not supported by HAL");
2740 cancelStreamsConfigurationLocked();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002741 return BAD_VALUE;
2742 } else if (res != OK) {
2743 // Some other kind of error from configure_streams - this is not
2744 // expected
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002745 SET_ERR_L("Unable to configure streams with HAL: %s (%d)",
2746 strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002747 return res;
2748 }
2749
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002750 // Finish all stream configuration immediately.
2751 // TODO: Try to relax this later back to lazy completion, which should be
2752 // faster
2753
Igor Murashkin073f8572013-05-02 14:59:28 -07002754 if (mInputStream != NULL && mInputStream->isConfiguring()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002755 bool streamReConfigured = false;
2756 res = mInputStream->finishConfiguration(&streamReConfigured);
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002757 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002758 CLOGE("Can't finish configuring input stream %d: %s (%d)",
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002759 mInputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002760 cancelStreamsConfigurationLocked();
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002761 if ((res == NO_INIT || res == DEAD_OBJECT) && mInputStream->isAbandoned()) {
2762 return DEAD_OBJECT;
2763 }
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002764 return BAD_VALUE;
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002765 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002766 if (streamReConfigured) {
2767 mInterface->onStreamReConfigured(mInputStream->getId());
2768 }
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002769 }
2770
2771 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002772 sp<Camera3OutputStreamInterface> outputStream = mOutputStreams[i];
Zhijun He5d677d12016-05-29 16:52:39 -07002773 if (outputStream->isConfiguring() && !outputStream->isConsumerConfigurationDeferred()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002774 bool streamReConfigured = false;
2775 res = outputStream->finishConfiguration(&streamReConfigured);
Igor Murashkin073f8572013-05-02 14:59:28 -07002776 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002777 CLOGE("Can't finish configuring output stream %d: %s (%d)",
Igor Murashkin073f8572013-05-02 14:59:28 -07002778 outputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002779 cancelStreamsConfigurationLocked();
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002780 if ((res == NO_INIT || res == DEAD_OBJECT) && outputStream->isAbandoned()) {
2781 return DEAD_OBJECT;
2782 }
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002783 return BAD_VALUE;
Igor Murashkin073f8572013-05-02 14:59:28 -07002784 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002785 if (streamReConfigured) {
2786 mInterface->onStreamReConfigured(outputStream->getId());
2787 }
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002788 }
2789 }
2790
Emilian Peeve23f1d92021-09-20 14:56:01 -07002791 mRequestThread->setComposerSurface(composerSurfacePresent);
2792
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002793 // Request thread needs to know to avoid using repeat-last-settings protocol
2794 // across configure_streams() calls
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002795 if (notifyRequestThread) {
Shuzhen Wang99080502021-03-07 21:08:20 -08002796 mRequestThread->configurationComplete(mIsConstrainedHighSpeedConfiguration,
2797 sessionParams, mGroupIdPhysicalCameraMap);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002798 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002799
Zhijun He90f7c372016-08-16 16:19:43 -07002800 char value[PROPERTY_VALUE_MAX];
2801 property_get("camera.fifo.disable", value, "0");
2802 int32_t disableFifo = atoi(value);
2803 if (disableFifo != 1) {
2804 // Boost priority of request thread to SCHED_FIFO.
2805 pid_t requestThreadTid = mRequestThread->getTid();
2806 res = requestPriority(getpid(), requestThreadTid,
Mikhail Naganov83f04272017-02-07 10:45:09 -08002807 kRequestThreadPriority, /*isForApp*/ false, /*asynchronous*/ false);
Zhijun He90f7c372016-08-16 16:19:43 -07002808 if (res != OK) {
2809 ALOGW("Can't set realtime priority for request processing thread: %s (%d)",
2810 strerror(-res), res);
2811 } else {
2812 ALOGD("Set real time priority for request queue thread (tid %d)", requestThreadTid);
2813 }
Eino-Ville Talvalaf99498e2015-09-25 16:52:55 -07002814 }
2815
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002816 // Update device state
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002817 const camera_metadata_t *newSessionParams = sessionParams.getAndLock();
2818 const camera_metadata_t *currentSessionParams = mSessionParams.getAndLock();
2819 bool updateSessionParams = (newSessionParams != currentSessionParams) ? true : false;
2820 sessionParams.unlock(newSessionParams);
2821 mSessionParams.unlock(currentSessionParams);
2822 if (updateSessionParams) {
2823 mSessionParams = sessionParams;
2824 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002825
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002826 mNeedConfig = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002827
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002828 internalUpdateStatusLocked((mFakeStreamId == NO_STREAM) ?
Ruben Brunk183f0562015-08-12 12:55:02 -07002829 STATUS_CONFIGURED : STATUS_UNCONFIGURED);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002830
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002831 ALOGV("%s: Camera %s: Stream configuration complete", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002832
Zhijun He0a210512014-07-24 13:45:15 -07002833 // tear down the deleted streams after configure streams.
2834 mDeletedStreams.clear();
2835
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002836 auto rc = mPreparerThread->resume();
2837 if (rc != OK) {
2838 SET_ERR_L("%s: Camera %s: Preparer thread failed to resume!", __FUNCTION__, mId.string());
2839 return rc;
2840 }
2841
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002842 if (mFakeStreamId == NO_STREAM) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07002843 mRequestBufferSM.onStreamsConfigured();
2844 }
2845
Cliff Wuc2ad9c82021-04-21 00:58:58 +08002846 // Since the streams configuration of the injection camera is based on the internal camera, we
2847 // must wait until the internal camera configure streams before calling injectCamera() to
2848 // configure the injection streams.
2849 if (mInjectionMethods->isInjecting()) {
2850 ALOGV("%s: Injection camera %s: Start to configure streams.",
2851 __FUNCTION__, mInjectionMethods->getInjectedCamId().string());
2852 res = mInjectionMethods->injectCamera(config, bufferSizes);
2853 if (res != OK) {
2854 ALOGE("Can't finish inject camera process!");
2855 return res;
2856 }
2857 }
2858
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002859 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002860}
2861
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002862status_t Camera3Device::addFakeStreamLocked() {
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002863 ATRACE_CALL();
2864 status_t res;
2865
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002866 if (mFakeStreamId != NO_STREAM) {
2867 // Should never be adding a second fake stream when one is already
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002868 // active
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002869 SET_ERR_L("%s: Camera %s: A fake stream already exists!",
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002870 __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002871 return INVALID_OPERATION;
2872 }
2873
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002874 ALOGV("%s: Camera %s: Adding a fake stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002875
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002876 sp<Camera3OutputStreamInterface> fakeStream =
2877 new Camera3FakeStream(mNextStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002878
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002879 res = mOutputStreams.add(mNextStreamId, fakeStream);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002880 if (res < 0) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002881 SET_ERR_L("Can't add fake stream to set: %s (%d)", strerror(-res), res);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002882 return res;
2883 }
2884
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002885 mFakeStreamId = mNextStreamId;
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002886 mNextStreamId++;
2887
2888 return OK;
2889}
2890
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002891status_t Camera3Device::tryRemoveFakeStreamLocked() {
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002892 ATRACE_CALL();
2893 status_t res;
2894
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002895 if (mFakeStreamId == NO_STREAM) return OK;
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002896 if (mOutputStreams.size() == 1) return OK;
2897
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002898 ALOGV("%s: Camera %s: Removing the fake stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002899
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002900 // Ok, have a fake stream and there's at least one other output stream,
2901 // so remove the fake
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002902
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002903 sp<Camera3StreamInterface> deletedStream = mOutputStreams.get(mFakeStreamId);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002904 if (deletedStream == nullptr) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002905 SET_ERR_L("Fake stream %d does not appear to exist", mFakeStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002906 return INVALID_OPERATION;
2907 }
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002908 mOutputStreams.remove(mFakeStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002909
2910 // Free up the stream endpoint so that it can be used by some other stream
2911 res = deletedStream->disconnect();
2912 if (res != OK) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002913 SET_ERR_L("Can't disconnect deleted fake stream %d", mFakeStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002914 // fall through since we want to still list the stream as deleted.
2915 }
2916 mDeletedStreams.add(deletedStream);
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002917 mFakeStreamId = NO_STREAM;
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002918
2919 return res;
2920}
2921
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002922void Camera3Device::setErrorState(const char *fmt, ...) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002923 ATRACE_CALL();
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002924 Mutex::Autolock l(mLock);
2925 va_list args;
2926 va_start(args, fmt);
2927
2928 setErrorStateLockedV(fmt, args);
2929
2930 va_end(args);
2931}
2932
2933void Camera3Device::setErrorStateV(const char *fmt, va_list args) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002934 ATRACE_CALL();
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002935 Mutex::Autolock l(mLock);
2936 setErrorStateLockedV(fmt, args);
2937}
2938
2939void Camera3Device::setErrorStateLocked(const char *fmt, ...) {
2940 va_list args;
2941 va_start(args, fmt);
2942
2943 setErrorStateLockedV(fmt, args);
2944
2945 va_end(args);
2946}
2947
2948void Camera3Device::setErrorStateLockedV(const char *fmt, va_list args) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002949 // Print out all error messages to log
2950 String8 errorCause = String8::formatV(fmt, args);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002951 ALOGE("Camera %s: %s", mId.string(), errorCause.string());
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002952
2953 // But only do error state transition steps for the first error
Zhijun Heb05eeae2013-06-06 13:51:22 -07002954 if (mStatus == STATUS_ERROR || mStatus == STATUS_UNINITIALIZED) return;
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002955
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002956 mErrorCause = errorCause;
2957
Yin-Chia Yeh3d145ae2017-07-27 12:47:03 -07002958 if (mRequestThread != nullptr) {
2959 mRequestThread->setPaused(true);
2960 }
Ruben Brunk183f0562015-08-12 12:55:02 -07002961 internalUpdateStatusLocked(STATUS_ERROR);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002962
2963 // Notify upstream about a device error
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002964 sp<NotificationListener> listener = mListener.promote();
2965 if (listener != NULL) {
2966 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002967 CaptureResultExtras());
Shuzhen Wang316781a2020-08-18 18:11:01 -07002968 mSessionStatsBuilder.onDeviceError();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002969 }
2970
2971 // Save stack trace. View by dumping it later.
2972 CameraTraces::saveTrace();
2973 // TODO: consider adding errorCause and client pid/procname
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002974}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002975
2976/**
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002977 * In-flight request management
2978 */
2979
Jianing Weicb0652e2014-03-12 18:29:36 -07002980status_t Camera3Device::registerInFlight(uint32_t frameNumber,
Chien-Yu Chend196d612015-06-22 19:49:01 -07002981 int32_t numBuffers, CaptureResultExtras resultExtras, bool hasInput,
Shuzhen Wang5c22c152017-12-31 17:12:25 -08002982 bool hasAppCallback, nsecs_t maxExpectedDuration,
Shuzhen Wang99080502021-03-07 21:08:20 -08002983 const std::set<std::set<String8>>& physicalCameraIds,
2984 bool isStillCapture, bool isZslCapture, bool rotateAndCropAuto,
2985 const std::set<std::string>& cameraIdsWithZoom,
Shuzhen Wang316781a2020-08-18 18:11:01 -07002986 const SurfaceMap& outputSurfaces, nsecs_t requestTimeNs) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002987 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002988 std::lock_guard<std::mutex> l(mInFlightLock);
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002989
2990 ssize_t res;
Chien-Yu Chend196d612015-06-22 19:49:01 -07002991 res = mInFlightMap.add(frameNumber, InFlightRequest(numBuffers, resultExtras, hasInput,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07002992 hasAppCallback, maxExpectedDuration, physicalCameraIds, isStillCapture, isZslCapture,
Shuzhen Wang316781a2020-08-18 18:11:01 -07002993 rotateAndCropAuto, cameraIdsWithZoom, requestTimeNs, outputSurfaces));
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002994 if (res < 0) return res;
2995
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07002996 if (mInFlightMap.size() == 1) {
Emilian Peev26d975d2018-07-05 14:52:57 +01002997 // Hold a separate dedicated tracker lock to prevent race with disconnect and also
2998 // avoid a deadlock during reprocess requests.
2999 Mutex::Autolock l(mTrackerLock);
Yin-Chia Yeh38dfde52017-06-27 17:13:33 -07003000 if (mStatusTracker != nullptr) {
3001 mStatusTracker->markComponentActive(mInFlightStatusId);
3002 }
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07003003 }
3004
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003005 mExpectedInflightDuration += maxExpectedDuration;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003006 return OK;
3007}
3008
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003009void Camera3Device::onInflightEntryRemovedLocked(nsecs_t duration) {
Shuzhen Wangcadb3302016-11-04 14:17:56 -07003010 // Indicate idle inFlightMap to the status tracker
3011 if (mInFlightMap.size() == 0) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07003012 mRequestBufferSM.onInflightMapEmpty();
Emilian Peev26d975d2018-07-05 14:52:57 +01003013 // Hold a separate dedicated tracker lock to prevent race with disconnect and also
3014 // avoid a deadlock during reprocess requests.
3015 Mutex::Autolock l(mTrackerLock);
Yin-Chia Yeh38dfde52017-06-27 17:13:33 -07003016 if (mStatusTracker != nullptr) {
3017 mStatusTracker->markComponentIdle(mInFlightStatusId, Fence::NO_FENCE);
3018 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07003019 }
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003020 mExpectedInflightDuration -= duration;
Shuzhen Wangcadb3302016-11-04 14:17:56 -07003021}
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003022
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003023void Camera3Device::checkInflightMapLengthLocked() {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04003024 // Validation check - if we have too many in-flight frames with long total inflight duration,
Yin-Chia Yeh99fd0972019-06-27 14:22:44 -07003025 // something has likely gone wrong. This might still be legit only if application send in
3026 // a long burst of long exposure requests.
3027 if (mExpectedInflightDuration > kMinWarnInflightDuration) {
3028 if (!mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() > kInFlightWarnLimit) {
3029 CLOGW("In-flight list too large: %zu, total inflight duration %" PRIu64,
3030 mInFlightMap.size(), mExpectedInflightDuration);
3031 } else if (mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() >
3032 kInFlightWarnLimitHighSpeed) {
3033 CLOGW("In-flight list too large for high speed configuration: %zu,"
3034 "total inflight duration %" PRIu64,
3035 mInFlightMap.size(), mExpectedInflightDuration);
3036 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003037 }
3038}
3039
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003040void Camera3Device::onInflightMapFlushedLocked() {
3041 mExpectedInflightDuration = 0;
3042}
3043
3044void Camera3Device::removeInFlightMapEntryLocked(int idx) {
Jayant Chowdharyd4776262020-06-23 23:45:57 -07003045 ATRACE_HFR_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003046 nsecs_t duration = mInFlightMap.valueAt(idx).maxExpectedDuration;
3047 mInFlightMap.removeItemsAt(idx, 1);
3048
3049 onInflightEntryRemovedLocked(duration);
3050}
3051
3052
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003053void Camera3Device::flushInflightRequests() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003054 ATRACE_CALL();
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003055 sp<NotificationListener> listener;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003056 {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003057 std::lock_guard<std::mutex> l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003058 listener = mListener.promote();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003059 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003060
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003061 FlushInflightReqStates states {
3062 mId, mInFlightLock, mInFlightMap, mUseHalBufManager,
Shuzhen Wang316781a2020-08-18 18:11:01 -07003063 listener, *this, *mInterface, *this, mSessionStatsBuilder};
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003064
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003065 camera3::flushInflightRequests(states);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003066}
3067
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003068CameraMetadata Camera3Device::getLatestRequestLocked() {
Igor Murashkin1e479c02013-09-06 16:55:14 -07003069 ALOGV("%s", __FUNCTION__);
3070
Igor Murashkin1e479c02013-09-06 16:55:14 -07003071 CameraMetadata retVal;
3072
3073 if (mRequestThread != NULL) {
3074 retVal = mRequestThread->getLatestRequest();
3075 }
3076
Igor Murashkin1e479c02013-09-06 16:55:14 -07003077 return retVal;
3078}
3079
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07003080void Camera3Device::monitorMetadata(TagMonitor::eventSource source,
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003081 int64_t frameNumber, nsecs_t timestamp, const CameraMetadata& metadata,
3082 const std::unordered_map<std::string, CameraMetadata>& physicalMetadata) {
3083
3084 mTagMonitor.monitorMetadata(source, frameNumber, timestamp, metadata,
3085 physicalMetadata);
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07003086}
3087
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003088/**
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003089 * HalInterface inner class methods
3090 */
3091
Yifan Hongf79b5542017-04-11 14:44:25 -07003092Camera3Device::HalInterface::HalInterface(
3093 sp<ICameraDeviceSession> &session,
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003094 std::shared_ptr<RequestMetadataQueue> queue,
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003095 bool useHalBufManager, bool supportOfflineProcessing) :
Yifan Hongf79b5542017-04-11 14:44:25 -07003096 mHidlSession(session),
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003097 mRequestMetadataQueue(queue),
Emilian Peev4ec17882019-01-24 17:16:58 -08003098 mUseHalBufManager(useHalBufManager),
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003099 mIsReconfigurationQuerySupported(true),
3100 mSupportOfflineProcessing(supportOfflineProcessing) {
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003101 // Check with hardware service manager if we can downcast these interfaces
3102 // Somewhat expensive, so cache the results at startup
Shuzhen Wang83bff122020-11-20 15:51:39 -08003103 auto castResult_3_7 = device::V3_7::ICameraDeviceSession::castFrom(mHidlSession);
3104 if (castResult_3_7.isOk()) {
3105 mHidlSession_3_7 = castResult_3_7;
3106 }
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003107 auto castResult_3_6 = device::V3_6::ICameraDeviceSession::castFrom(mHidlSession);
3108 if (castResult_3_6.isOk()) {
3109 mHidlSession_3_6 = castResult_3_6;
3110 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003111 auto castResult_3_5 = device::V3_5::ICameraDeviceSession::castFrom(mHidlSession);
3112 if (castResult_3_5.isOk()) {
3113 mHidlSession_3_5 = castResult_3_5;
3114 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003115 auto castResult_3_4 = device::V3_4::ICameraDeviceSession::castFrom(mHidlSession);
3116 if (castResult_3_4.isOk()) {
3117 mHidlSession_3_4 = castResult_3_4;
3118 }
3119 auto castResult_3_3 = device::V3_3::ICameraDeviceSession::castFrom(mHidlSession);
3120 if (castResult_3_3.isOk()) {
3121 mHidlSession_3_3 = castResult_3_3;
3122 }
3123}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003124
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003125Camera3Device::HalInterface::HalInterface() :
3126 mUseHalBufManager(false),
3127 mSupportOfflineProcessing(false) {}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003128
3129Camera3Device::HalInterface::HalInterface(const HalInterface& other) :
Yifan Hongf79b5542017-04-11 14:44:25 -07003130 mHidlSession(other.mHidlSession),
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003131 mRequestMetadataQueue(other.mRequestMetadataQueue),
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003132 mUseHalBufManager(other.mUseHalBufManager),
3133 mSupportOfflineProcessing(other.mSupportOfflineProcessing) {}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003134
3135bool Camera3Device::HalInterface::valid() {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003136 return (mHidlSession != nullptr);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003137}
3138
3139void Camera3Device::HalInterface::clear() {
Shuzhen Wang83bff122020-11-20 15:51:39 -08003140 mHidlSession_3_7.clear();
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003141 mHidlSession_3_6.clear();
Emilian Peev644a3e12018-11-23 13:52:39 +00003142 mHidlSession_3_5.clear();
Emilian Peev9e740b02018-01-30 18:28:03 +00003143 mHidlSession_3_4.clear();
3144 mHidlSession_3_3.clear();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003145 mHidlSession.clear();
3146}
3147
3148status_t Camera3Device::HalInterface::constructDefaultRequestSettings(
Emilian Peevf4816702020-04-03 15:44:51 -07003149 camera_request_template_t templateId,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003150 /*out*/ camera_metadata_t **requestTemplate) {
3151 ATRACE_NAME("CameraHal::constructDefaultRequestSettings");
3152 if (!valid()) return INVALID_OPERATION;
3153 status_t res = OK;
3154
Emilian Peev31abd0a2017-05-11 18:37:46 +01003155 common::V1_0::Status status;
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003156
3157 auto requestCallback = [&status, &requestTemplate]
Emilian Peev31abd0a2017-05-11 18:37:46 +01003158 (common::V1_0::Status s, const device::V3_2::CameraMetadata& request) {
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003159 status = s;
3160 if (status == common::V1_0::Status::OK) {
3161 const camera_metadata *r =
3162 reinterpret_cast<const camera_metadata_t*>(request.data());
3163 size_t expectedSize = request.size();
3164 int ret = validate_camera_metadata_structure(r, &expectedSize);
3165 if (ret == OK || ret == CAMERA_METADATA_VALIDATION_SHIFTED) {
3166 *requestTemplate = clone_camera_metadata(r);
3167 if (*requestTemplate == nullptr) {
3168 ALOGE("%s: Unable to clone camera metadata received from HAL",
3169 __FUNCTION__);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003170 status = common::V1_0::Status::INTERNAL_ERROR;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003171 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003172 } else {
3173 ALOGE("%s: Malformed camera metadata received from HAL", __FUNCTION__);
3174 status = common::V1_0::Status::INTERNAL_ERROR;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003175 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003176 }
3177 };
3178 hardware::Return<void> err;
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003179 RequestTemplate id;
3180 switch (templateId) {
Emilian Peevf4816702020-04-03 15:44:51 -07003181 case CAMERA_TEMPLATE_PREVIEW:
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003182 id = RequestTemplate::PREVIEW;
3183 break;
Emilian Peevf4816702020-04-03 15:44:51 -07003184 case CAMERA_TEMPLATE_STILL_CAPTURE:
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003185 id = RequestTemplate::STILL_CAPTURE;
3186 break;
Emilian Peevf4816702020-04-03 15:44:51 -07003187 case CAMERA_TEMPLATE_VIDEO_RECORD:
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003188 id = RequestTemplate::VIDEO_RECORD;
3189 break;
Emilian Peevf4816702020-04-03 15:44:51 -07003190 case CAMERA_TEMPLATE_VIDEO_SNAPSHOT:
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003191 id = RequestTemplate::VIDEO_SNAPSHOT;
3192 break;
Emilian Peevf4816702020-04-03 15:44:51 -07003193 case CAMERA_TEMPLATE_ZERO_SHUTTER_LAG:
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003194 id = RequestTemplate::ZERO_SHUTTER_LAG;
3195 break;
Emilian Peevf4816702020-04-03 15:44:51 -07003196 case CAMERA_TEMPLATE_MANUAL:
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003197 id = RequestTemplate::MANUAL;
3198 break;
3199 default:
3200 // Unknown template ID, or this HAL is too old to support it
3201 return BAD_VALUE;
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003202 }
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003203 err = mHidlSession->constructDefaultRequestSettings(id, requestCallback);
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003204
Emilian Peev31abd0a2017-05-11 18:37:46 +01003205 if (!err.isOk()) {
3206 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3207 res = DEAD_OBJECT;
3208 } else {
3209 res = CameraProviderManager::mapToStatusT(status);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003210 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003211
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003212 return res;
3213}
3214
Emilian Peev4ec17882019-01-24 17:16:58 -08003215bool Camera3Device::HalInterface::isReconfigurationRequired(CameraMetadata& oldSessionParams,
3216 CameraMetadata& newSessionParams) {
3217 // We do reconfiguration by default;
3218 bool ret = true;
3219 if ((mHidlSession_3_5 != nullptr) && mIsReconfigurationQuerySupported) {
3220 android::hardware::hidl_vec<uint8_t> oldParams, newParams;
3221 camera_metadata_t* oldSessioMeta = const_cast<camera_metadata_t*>(
3222 oldSessionParams.getAndLock());
3223 camera_metadata_t* newSessioMeta = const_cast<camera_metadata_t*>(
3224 newSessionParams.getAndLock());
3225 oldParams.setToExternal(reinterpret_cast<uint8_t*>(oldSessioMeta),
3226 get_camera_metadata_size(oldSessioMeta));
3227 newParams.setToExternal(reinterpret_cast<uint8_t*>(newSessioMeta),
3228 get_camera_metadata_size(newSessioMeta));
3229 hardware::camera::common::V1_0::Status callStatus;
3230 bool required;
3231 auto hidlCb = [&callStatus, &required] (hardware::camera::common::V1_0::Status s,
3232 bool requiredFlag) {
3233 callStatus = s;
3234 required = requiredFlag;
3235 };
3236 auto err = mHidlSession_3_5->isReconfigurationRequired(oldParams, newParams, hidlCb);
3237 oldSessionParams.unlock(oldSessioMeta);
3238 newSessionParams.unlock(newSessioMeta);
3239 if (err.isOk()) {
3240 switch (callStatus) {
3241 case hardware::camera::common::V1_0::Status::OK:
3242 ret = required;
3243 break;
3244 case hardware::camera::common::V1_0::Status::METHOD_NOT_SUPPORTED:
3245 mIsReconfigurationQuerySupported = false;
3246 ret = true;
3247 break;
3248 default:
3249 ALOGV("%s: Reconfiguration query failed: %d", __FUNCTION__, callStatus);
3250 ret = true;
3251 }
3252 } else {
3253 ALOGE("%s: Unexpected binder error: %s", __FUNCTION__, err.description().c_str());
3254 ret = true;
3255 }
3256 }
3257
3258 return ret;
3259}
3260
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003261status_t Camera3Device::HalInterface::configureStreams(const camera_metadata_t *sessionParams,
Emilian Peevf4816702020-04-03 15:44:51 -07003262 camera_stream_configuration *config, const std::vector<uint32_t>& bufferSizes) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003263 ATRACE_NAME("CameraHal::configureStreams");
3264 if (!valid()) return INVALID_OPERATION;
3265 status_t res = OK;
3266
Shuzhen Wang83bff122020-11-20 15:51:39 -08003267 if (config->input_is_multi_resolution && mHidlSession_3_7 == nullptr) {
3268 ALOGE("%s: Camera device doesn't support multi-resolution input stream", __FUNCTION__);
3269 return BAD_VALUE;
3270 }
3271
Emilian Peev31abd0a2017-05-11 18:37:46 +01003272 // Convert stream config to HIDL
3273 std::set<int> activeStreams;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003274 device::V3_2::StreamConfiguration requestedConfiguration3_2;
3275 device::V3_4::StreamConfiguration requestedConfiguration3_4;
Shuzhen Wang83bff122020-11-20 15:51:39 -08003276 device::V3_7::StreamConfiguration requestedConfiguration3_7;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003277 requestedConfiguration3_2.streams.resize(config->num_streams);
3278 requestedConfiguration3_4.streams.resize(config->num_streams);
Shuzhen Wang83bff122020-11-20 15:51:39 -08003279 requestedConfiguration3_7.streams.resize(config->num_streams);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003280 for (size_t i = 0; i < config->num_streams; i++) {
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003281 device::V3_2::Stream &dst3_2 = requestedConfiguration3_2.streams[i];
3282 device::V3_4::Stream &dst3_4 = requestedConfiguration3_4.streams[i];
Shuzhen Wang83bff122020-11-20 15:51:39 -08003283 device::V3_7::Stream &dst3_7 = requestedConfiguration3_7.streams[i];
Emilian Peevf4816702020-04-03 15:44:51 -07003284 camera3::camera_stream_t *src = config->streams[i];
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003285
Emilian Peev31abd0a2017-05-11 18:37:46 +01003286 Camera3Stream* cam3stream = Camera3Stream::cast(src);
3287 cam3stream->setBufferFreedListener(this);
3288 int streamId = cam3stream->getId();
3289 StreamType streamType;
3290 switch (src->stream_type) {
Emilian Peevf4816702020-04-03 15:44:51 -07003291 case CAMERA_STREAM_OUTPUT:
Emilian Peev31abd0a2017-05-11 18:37:46 +01003292 streamType = StreamType::OUTPUT;
3293 break;
Emilian Peevf4816702020-04-03 15:44:51 -07003294 case CAMERA_STREAM_INPUT:
Emilian Peev31abd0a2017-05-11 18:37:46 +01003295 streamType = StreamType::INPUT;
3296 break;
3297 default:
3298 ALOGE("%s: Stream %d: Unsupported stream type %d",
3299 __FUNCTION__, streamId, config->streams[i]->stream_type);
3300 return BAD_VALUE;
3301 }
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003302 dst3_2.id = streamId;
3303 dst3_2.streamType = streamType;
3304 dst3_2.width = src->width;
3305 dst3_2.height = src->height;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003306 dst3_2.usage = mapToConsumerUsage(cam3stream->getUsage());
Emilian Peevf4816702020-04-03 15:44:51 -07003307 dst3_2.rotation = mapToStreamRotation((camera_stream_rotation_t) src->rotation);
Shuzhen Wang92653952019-05-07 15:11:43 -07003308 // For HidlSession version 3.5 or newer, the format and dataSpace sent
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08003309 // to HAL are original, not the overridden ones.
Shuzhen Wang92653952019-05-07 15:11:43 -07003310 if (mHidlSession_3_5 != nullptr) {
3311 dst3_2.format = mapToPixelFormat(cam3stream->isFormatOverridden() ?
3312 cam3stream->getOriginalFormat() : src->format);
3313 dst3_2.dataSpace = mapToHidlDataspace(cam3stream->isDataSpaceOverridden() ?
3314 cam3stream->getOriginalDataSpace() : src->data_space);
3315 } else {
3316 dst3_2.format = mapToPixelFormat(src->format);
3317 dst3_2.dataSpace = mapToHidlDataspace(src->data_space);
3318 }
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003319 dst3_4.v3_2 = dst3_2;
Emilian Peev192ee832018-01-31 14:46:47 +00003320 dst3_4.bufferSize = bufferSizes[i];
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003321 if (src->physical_camera_id != nullptr) {
3322 dst3_4.physicalCameraId = src->physical_camera_id;
3323 }
Shuzhen Wang83bff122020-11-20 15:51:39 -08003324 dst3_7.v3_4 = dst3_4;
3325 dst3_7.groupId = cam3stream->getHalStreamGroupId();
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08003326 dst3_7.sensorPixelModesUsed.resize(src->sensor_pixel_modes_used.size());
3327 size_t j = 0;
3328 for (int mode : src->sensor_pixel_modes_used) {
3329 dst3_7.sensorPixelModesUsed[j++] =
3330 static_cast<CameraMetadataEnumAndroidSensorPixelMode>(mode);
3331 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003332 activeStreams.insert(streamId);
3333 // Create Buffer ID map if necessary
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003334 mBufferRecords.tryCreateBufferCache(streamId);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003335 }
3336 // remove BufferIdMap for deleted streams
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003337 mBufferRecords.removeInactiveBufferCaches(activeStreams);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003338
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003339 StreamConfigurationMode operationMode;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003340 res = mapToStreamConfigurationMode(
Emilian Peevf4816702020-04-03 15:44:51 -07003341 (camera_stream_configuration_mode_t) config->operation_mode,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003342 /*out*/ &operationMode);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003343 if (res != OK) {
3344 return res;
3345 }
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003346 requestedConfiguration3_2.operationMode = operationMode;
3347 requestedConfiguration3_4.operationMode = operationMode;
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08003348 requestedConfiguration3_7.operationMode = operationMode;
3349 size_t sessionParamSize = get_camera_metadata_size(sessionParams);
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003350 requestedConfiguration3_4.sessionParams.setToExternal(
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003351 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(sessionParams)),
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08003352 sessionParamSize);
Shuzhen Wang83bff122020-11-20 15:51:39 -08003353 requestedConfiguration3_7.operationMode = operationMode;
3354 requestedConfiguration3_7.sessionParams.setToExternal(
3355 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(sessionParams)),
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08003356 sessionParamSize);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003357
Emilian Peev31abd0a2017-05-11 18:37:46 +01003358 // Invoke configureStreams
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003359 device::V3_3::HalStreamConfiguration finalConfiguration;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003360 device::V3_4::HalStreamConfiguration finalConfiguration3_4;
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003361 device::V3_6::HalStreamConfiguration finalConfiguration3_6;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003362 common::V1_0::Status status;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003363
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003364 auto configStream34Cb = [&status, &finalConfiguration3_4]
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003365 (common::V1_0::Status s, const device::V3_4::HalStreamConfiguration& halConfiguration) {
3366 finalConfiguration3_4 = halConfiguration;
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003367 status = s;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003368 };
3369
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003370 auto configStream36Cb = [&status, &finalConfiguration3_6]
3371 (common::V1_0::Status s, const device::V3_6::HalStreamConfiguration& halConfiguration) {
3372 finalConfiguration3_6 = halConfiguration;
3373 status = s;
3374 };
3375
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003376 auto postprocConfigStream34 = [&finalConfiguration, &finalConfiguration3_4]
3377 (hardware::Return<void>& err) -> status_t {
3378 if (!err.isOk()) {
3379 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3380 return DEAD_OBJECT;
3381 }
3382 finalConfiguration.streams.resize(finalConfiguration3_4.streams.size());
3383 for (size_t i = 0; i < finalConfiguration3_4.streams.size(); i++) {
3384 finalConfiguration.streams[i] = finalConfiguration3_4.streams[i].v3_3;
3385 }
3386 return OK;
3387 };
3388
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003389 auto postprocConfigStream36 = [&finalConfiguration, &finalConfiguration3_6]
3390 (hardware::Return<void>& err) -> status_t {
3391 if (!err.isOk()) {
3392 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3393 return DEAD_OBJECT;
3394 }
3395 finalConfiguration.streams.resize(finalConfiguration3_6.streams.size());
3396 for (size_t i = 0; i < finalConfiguration3_6.streams.size(); i++) {
3397 finalConfiguration.streams[i] = finalConfiguration3_6.streams[i].v3_4.v3_3;
3398 }
3399 return OK;
3400 };
3401
Shuzhen Wang92653952019-05-07 15:11:43 -07003402 // See which version of HAL we have
Shuzhen Wang83bff122020-11-20 15:51:39 -08003403 if (mHidlSession_3_7 != nullptr) {
3404 ALOGV("%s: v3.7 device found", __FUNCTION__);
3405 requestedConfiguration3_7.streamConfigCounter = mNextStreamConfigCounter++;
3406 requestedConfiguration3_7.multiResolutionInputImage = config->input_is_multi_resolution;
3407 auto err = mHidlSession_3_7->configureStreams_3_7(
3408 requestedConfiguration3_7, configStream36Cb);
3409 res = postprocConfigStream36(err);
3410 if (res != OK) {
3411 return res;
3412 }
3413 } else if (mHidlSession_3_6 != nullptr) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003414 ALOGV("%s: v3.6 device found", __FUNCTION__);
3415 device::V3_5::StreamConfiguration requestedConfiguration3_5;
3416 requestedConfiguration3_5.v3_4 = requestedConfiguration3_4;
3417 requestedConfiguration3_5.streamConfigCounter = mNextStreamConfigCounter++;
3418 auto err = mHidlSession_3_6->configureStreams_3_6(
3419 requestedConfiguration3_5, configStream36Cb);
3420 res = postprocConfigStream36(err);
3421 if (res != OK) {
3422 return res;
3423 }
3424 } else if (mHidlSession_3_5 != nullptr) {
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003425 ALOGV("%s: v3.5 device found", __FUNCTION__);
3426 device::V3_5::StreamConfiguration requestedConfiguration3_5;
3427 requestedConfiguration3_5.v3_4 = requestedConfiguration3_4;
3428 requestedConfiguration3_5.streamConfigCounter = mNextStreamConfigCounter++;
3429 auto err = mHidlSession_3_5->configureStreams_3_5(
3430 requestedConfiguration3_5, configStream34Cb);
3431 res = postprocConfigStream34(err);
3432 if (res != OK) {
3433 return res;
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003434 }
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003435 } else if (mHidlSession_3_4 != nullptr) {
3436 // We do; use v3.4 for the call
3437 ALOGV("%s: v3.4 device found", __FUNCTION__);
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003438 auto err = mHidlSession_3_4->configureStreams_3_4(
3439 requestedConfiguration3_4, configStream34Cb);
3440 res = postprocConfigStream34(err);
3441 if (res != OK) {
3442 return res;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003443 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003444 } else if (mHidlSession_3_3 != nullptr) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003445 // We do; use v3.3 for the call
3446 ALOGV("%s: v3.3 device found", __FUNCTION__);
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003447 auto err = mHidlSession_3_3->configureStreams_3_3(requestedConfiguration3_2,
Emilian Peev31abd0a2017-05-11 18:37:46 +01003448 [&status, &finalConfiguration]
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003449 (common::V1_0::Status s, const device::V3_3::HalStreamConfiguration& halConfiguration) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003450 finalConfiguration = halConfiguration;
3451 status = s;
3452 });
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003453 if (!err.isOk()) {
3454 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3455 return DEAD_OBJECT;
3456 }
3457 } else {
3458 // We don't; use v3.2 call and construct a v3.3 HalStreamConfiguration
3459 ALOGV("%s: v3.2 device found", __FUNCTION__);
3460 HalStreamConfiguration finalConfiguration_3_2;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003461 auto err = mHidlSession->configureStreams(requestedConfiguration3_2,
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003462 [&status, &finalConfiguration_3_2]
3463 (common::V1_0::Status s, const HalStreamConfiguration& halConfiguration) {
3464 finalConfiguration_3_2 = halConfiguration;
3465 status = s;
3466 });
3467 if (!err.isOk()) {
3468 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3469 return DEAD_OBJECT;
3470 }
3471 finalConfiguration.streams.resize(finalConfiguration_3_2.streams.size());
3472 for (size_t i = 0; i < finalConfiguration_3_2.streams.size(); i++) {
3473 finalConfiguration.streams[i].v3_2 = finalConfiguration_3_2.streams[i];
3474 finalConfiguration.streams[i].overrideDataSpace =
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003475 requestedConfiguration3_2.streams[i].dataSpace;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003476 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003477 }
3478
3479 if (status != common::V1_0::Status::OK ) {
3480 return CameraProviderManager::mapToStatusT(status);
3481 }
3482
3483 // And convert output stream configuration from HIDL
3484
3485 for (size_t i = 0; i < config->num_streams; i++) {
Emilian Peevf4816702020-04-03 15:44:51 -07003486 camera3::camera_stream_t *dst = config->streams[i];
Emilian Peev31abd0a2017-05-11 18:37:46 +01003487 int streamId = Camera3Stream::cast(dst)->getId();
3488
3489 // Start scan at i, with the assumption that the stream order matches
3490 size_t realIdx = i;
3491 bool found = false;
Eino-Ville Talvala370875f2019-04-12 12:40:27 -07003492 size_t halStreamCount = finalConfiguration.streams.size();
3493 for (size_t idx = 0; idx < halStreamCount; idx++) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003494 if (finalConfiguration.streams[realIdx].v3_2.id == streamId) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003495 found = true;
3496 break;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003497 }
Eino-Ville Talvala370875f2019-04-12 12:40:27 -07003498 realIdx = (realIdx >= halStreamCount - 1) ? 0 : realIdx + 1;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003499 }
3500 if (!found) {
3501 ALOGE("%s: Stream %d not found in stream configuration response from HAL",
3502 __FUNCTION__, streamId);
3503 return INVALID_OPERATION;
3504 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003505 device::V3_3::HalStream &src = finalConfiguration.streams[realIdx];
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003506 device::V3_6::HalStream &src_36 = finalConfiguration3_6.streams[realIdx];
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003507
Emilian Peev710c1422017-08-30 11:19:38 +01003508 Camera3Stream* dstStream = Camera3Stream::cast(dst);
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003509 int overrideFormat = mapToFrameworkFormat(src.v3_2.overrideFormat);
3510 android_dataspace overrideDataSpace = mapToFrameworkDataspace(src.overrideDataSpace);
3511
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003512 if (mHidlSession_3_6 != nullptr) {
3513 dstStream->setOfflineProcessingSupport(src_36.supportOffline);
3514 }
3515
Yin-Chia Yeh90667662019-07-01 15:45:00 -07003516 if (dstStream->getOriginalFormat() != HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
Shuzhen Wang92653952019-05-07 15:11:43 -07003517 dstStream->setFormatOverride(false);
3518 dstStream->setDataSpaceOverride(false);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003519 if (dst->format != overrideFormat) {
3520 ALOGE("%s: Stream %d: Format override not allowed for format 0x%x", __FUNCTION__,
3521 streamId, dst->format);
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003522 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003523 if (dst->data_space != overrideDataSpace) {
3524 ALOGE("%s: Stream %d: DataSpace override not allowed for format 0x%x", __FUNCTION__,
3525 streamId, dst->format);
3526 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003527 } else {
Shuzhen Wang92653952019-05-07 15:11:43 -07003528 bool needFormatOverride =
3529 requestedConfiguration3_2.streams[i].format != src.v3_2.overrideFormat;
3530 bool needDataspaceOverride =
3531 requestedConfiguration3_2.streams[i].dataSpace != src.overrideDataSpace;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003532 // Override allowed with IMPLEMENTATION_DEFINED
Shuzhen Wang92653952019-05-07 15:11:43 -07003533 dstStream->setFormatOverride(needFormatOverride);
3534 dstStream->setDataSpaceOverride(needDataspaceOverride);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003535 dst->format = overrideFormat;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003536 dst->data_space = overrideDataSpace;
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003537 }
3538
Emilian Peevf4816702020-04-03 15:44:51 -07003539 if (dst->stream_type == CAMERA_STREAM_INPUT) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003540 if (src.v3_2.producerUsage != 0) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003541 ALOGE("%s: Stream %d: INPUT streams must have 0 for producer usage",
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003542 __FUNCTION__, streamId);
3543 return INVALID_OPERATION;
3544 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003545 dstStream->setUsage(
3546 mapConsumerToFrameworkUsage(src.v3_2.consumerUsage));
Emilian Peev31abd0a2017-05-11 18:37:46 +01003547 } else {
3548 // OUTPUT
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003549 if (src.v3_2.consumerUsage != 0) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003550 ALOGE("%s: Stream %d: OUTPUT streams must have 0 for consumer usage",
3551 __FUNCTION__, streamId);
3552 return INVALID_OPERATION;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003553 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003554 dstStream->setUsage(
3555 mapProducerToFrameworkUsage(src.v3_2.producerUsage));
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003556 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003557 dst->max_buffers = src.v3_2.maxBuffers;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003558 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003559
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003560 return res;
3561}
3562
Cliff Wuc2ad9c82021-04-21 00:58:58 +08003563status_t Camera3Device::HalInterface::configureInjectedStreams(
3564 const camera_metadata_t* sessionParams, camera_stream_configuration* config,
3565 const std::vector<uint32_t>& bufferSizes,
3566 const CameraMetadata& cameraCharacteristics) {
3567 ATRACE_NAME("InjectionCameraHal::configureStreams");
3568 if (!valid()) return INVALID_OPERATION;
3569 status_t res = OK;
3570
3571 if (config->input_is_multi_resolution) {
3572 ALOGE("%s: Injection camera device doesn't support multi-resolution input "
3573 "stream", __FUNCTION__);
3574 return BAD_VALUE;
3575 }
3576
3577 // Convert stream config to HIDL
3578 std::set<int> activeStreams;
3579 device::V3_2::StreamConfiguration requestedConfiguration3_2;
3580 device::V3_4::StreamConfiguration requestedConfiguration3_4;
3581 device::V3_7::StreamConfiguration requestedConfiguration3_7;
3582 requestedConfiguration3_2.streams.resize(config->num_streams);
3583 requestedConfiguration3_4.streams.resize(config->num_streams);
3584 requestedConfiguration3_7.streams.resize(config->num_streams);
3585 for (size_t i = 0; i < config->num_streams; i++) {
3586 device::V3_2::Stream& dst3_2 = requestedConfiguration3_2.streams[i];
3587 device::V3_4::Stream& dst3_4 = requestedConfiguration3_4.streams[i];
3588 device::V3_7::Stream& dst3_7 = requestedConfiguration3_7.streams[i];
3589 camera3::camera_stream_t* src = config->streams[i];
3590
3591 Camera3Stream* cam3stream = Camera3Stream::cast(src);
3592 cam3stream->setBufferFreedListener(this);
3593 int streamId = cam3stream->getId();
3594 StreamType streamType;
3595 switch (src->stream_type) {
3596 case CAMERA_STREAM_OUTPUT:
3597 streamType = StreamType::OUTPUT;
3598 break;
3599 case CAMERA_STREAM_INPUT:
3600 streamType = StreamType::INPUT;
3601 break;
3602 default:
3603 ALOGE("%s: Stream %d: Unsupported stream type %d", __FUNCTION__,
3604 streamId, config->streams[i]->stream_type);
3605 return BAD_VALUE;
3606 }
3607 dst3_2.id = streamId;
3608 dst3_2.streamType = streamType;
3609 dst3_2.width = src->width;
3610 dst3_2.height = src->height;
3611 dst3_2.usage = mapToConsumerUsage(cam3stream->getUsage());
3612 dst3_2.rotation =
3613 mapToStreamRotation((camera_stream_rotation_t)src->rotation);
3614 // For HidlSession version 3.5 or newer, the format and dataSpace sent
3615 // to HAL are original, not the overridden ones.
3616 if (mHidlSession_3_5 != nullptr) {
3617 dst3_2.format = mapToPixelFormat(cam3stream->isFormatOverridden()
3618 ? cam3stream->getOriginalFormat()
3619 : src->format);
3620 dst3_2.dataSpace =
3621 mapToHidlDataspace(cam3stream->isDataSpaceOverridden()
3622 ? cam3stream->getOriginalDataSpace()
3623 : src->data_space);
3624 } else {
3625 dst3_2.format = mapToPixelFormat(src->format);
3626 dst3_2.dataSpace = mapToHidlDataspace(src->data_space);
3627 }
3628 dst3_4.v3_2 = dst3_2;
3629 dst3_4.bufferSize = bufferSizes[i];
3630 if (src->physical_camera_id != nullptr) {
3631 dst3_4.physicalCameraId = src->physical_camera_id;
3632 }
3633 dst3_7.v3_4 = dst3_4;
3634 dst3_7.groupId = cam3stream->getHalStreamGroupId();
3635 dst3_7.sensorPixelModesUsed.resize(src->sensor_pixel_modes_used.size());
3636 size_t j = 0;
3637 for (int mode : src->sensor_pixel_modes_used) {
3638 dst3_7.sensorPixelModesUsed[j++] =
3639 static_cast<CameraMetadataEnumAndroidSensorPixelMode>(mode);
3640 }
3641 activeStreams.insert(streamId);
3642 // Create Buffer ID map if necessary
3643 mBufferRecords.tryCreateBufferCache(streamId);
3644 }
3645 // remove BufferIdMap for deleted streams
3646 mBufferRecords.removeInactiveBufferCaches(activeStreams);
3647
3648 StreamConfigurationMode operationMode;
3649 res = mapToStreamConfigurationMode(
3650 (camera_stream_configuration_mode_t)config->operation_mode,
3651 /*out*/ &operationMode);
3652 if (res != OK) {
3653 return res;
3654 }
3655 requestedConfiguration3_7.operationMode = operationMode;
3656 size_t sessionParamSize = get_camera_metadata_size(sessionParams);
3657 requestedConfiguration3_7.operationMode = operationMode;
3658 requestedConfiguration3_7.sessionParams.setToExternal(
3659 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(sessionParams)),
3660 sessionParamSize);
3661
3662 // See which version of HAL we have
3663 if (mHidlSession_3_7 != nullptr) {
3664 requestedConfiguration3_7.streamConfigCounter = mNextStreamConfigCounter++;
3665 requestedConfiguration3_7.multiResolutionInputImage =
3666 config->input_is_multi_resolution;
3667
3668 const camera_metadata_t* rawMetadata = cameraCharacteristics.getAndLock();
3669 ::android::hardware::camera::device::V3_2::CameraMetadata hidlChars = {};
3670 hidlChars.setToExternal(
3671 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(rawMetadata)),
3672 get_camera_metadata_size(rawMetadata));
3673 cameraCharacteristics.unlock(rawMetadata);
3674
3675 sp<hardware::camera::device::V3_7::ICameraInjectionSession>
3676 hidlInjectionSession_3_7;
3677 auto castInjectionResult_3_7 =
3678 device::V3_7::ICameraInjectionSession::castFrom(mHidlSession_3_7);
3679 if (castInjectionResult_3_7.isOk()) {
3680 hidlInjectionSession_3_7 = castInjectionResult_3_7;
3681 } else {
3682 ALOGE("%s: Transaction error: %s", __FUNCTION__,
3683 castInjectionResult_3_7.description().c_str());
3684 return DEAD_OBJECT;
3685 }
3686
3687 auto err = hidlInjectionSession_3_7->configureInjectionStreams(
3688 requestedConfiguration3_7, hidlChars);
3689 if (!err.isOk()) {
3690 ALOGE("%s: Transaction error: %s", __FUNCTION__,
3691 err.description().c_str());
3692 return DEAD_OBJECT;
3693 }
3694 } else {
3695 ALOGE("%s: mHidlSession_3_7 does not exist, the lowest version of injection "
3696 "session is 3.7", __FUNCTION__);
3697 return DEAD_OBJECT;
3698 }
3699
3700 return res;
3701}
3702
Emilian Peevf4816702020-04-03 15:44:51 -07003703status_t Camera3Device::HalInterface::wrapAsHidlRequest(camera_capture_request_t* request,
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003704 /*out*/device::V3_2::CaptureRequest* captureRequest,
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003705 /*out*/std::vector<native_handle_t*>* handlesCreated,
3706 /*out*/std::vector<std::pair<int32_t, int32_t>>* inflightBuffers) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003707 ATRACE_CALL();
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003708 if (captureRequest == nullptr || handlesCreated == nullptr || inflightBuffers == nullptr) {
3709 ALOGE("%s: captureRequest (%p), handlesCreated (%p), and inflightBuffers(%p) "
3710 "must not be null", __FUNCTION__, captureRequest, handlesCreated, inflightBuffers);
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003711 return BAD_VALUE;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003712 }
3713
3714 captureRequest->frameNumber = request->frame_number;
Yifan Hongf79b5542017-04-11 14:44:25 -07003715
3716 captureRequest->fmqSettingsSize = 0;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003717
3718 {
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003719 if (request->input_buffer != nullptr) {
3720 int32_t streamId = Camera3Stream::cast(request->input_buffer->stream)->getId();
3721 buffer_handle_t buf = *(request->input_buffer->buffer);
3722 auto pair = getBufferId(buf, streamId);
3723 bool isNewBuffer = pair.first;
3724 uint64_t bufferId = pair.second;
3725 captureRequest->inputBuffer.streamId = streamId;
3726 captureRequest->inputBuffer.bufferId = bufferId;
3727 captureRequest->inputBuffer.buffer = (isNewBuffer) ? buf : nullptr;
3728 captureRequest->inputBuffer.status = BufferStatus::OK;
3729 native_handle_t *acquireFence = nullptr;
3730 if (request->input_buffer->acquire_fence != -1) {
3731 acquireFence = native_handle_create(1,0);
3732 acquireFence->data[0] = request->input_buffer->acquire_fence;
3733 handlesCreated->push_back(acquireFence);
3734 }
3735 captureRequest->inputBuffer.acquireFence = acquireFence;
3736 captureRequest->inputBuffer.releaseFence = nullptr;
3737
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003738 mBufferRecords.pushInflightBuffer(captureRequest->frameNumber, streamId,
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003739 request->input_buffer->buffer);
3740 inflightBuffers->push_back(std::make_pair(captureRequest->frameNumber, streamId));
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003741 } else {
3742 captureRequest->inputBuffer.streamId = -1;
3743 captureRequest->inputBuffer.bufferId = BUFFER_ID_NO_BUFFER;
3744 }
3745
3746 captureRequest->outputBuffers.resize(request->num_output_buffers);
3747 for (size_t i = 0; i < request->num_output_buffers; i++) {
Emilian Peevf4816702020-04-03 15:44:51 -07003748 const camera_stream_buffer_t *src = request->output_buffers + i;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003749 StreamBuffer &dst = captureRequest->outputBuffers[i];
3750 int32_t streamId = Camera3Stream::cast(src->stream)->getId();
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003751 if (src->buffer != nullptr) {
3752 buffer_handle_t buf = *(src->buffer);
3753 auto pair = getBufferId(buf, streamId);
3754 bool isNewBuffer = pair.first;
3755 dst.bufferId = pair.second;
3756 dst.buffer = isNewBuffer ? buf : nullptr;
3757 native_handle_t *acquireFence = nullptr;
3758 if (src->acquire_fence != -1) {
3759 acquireFence = native_handle_create(1,0);
3760 acquireFence->data[0] = src->acquire_fence;
3761 handlesCreated->push_back(acquireFence);
3762 }
3763 dst.acquireFence = acquireFence;
3764 } else if (mUseHalBufManager) {
3765 // HAL buffer management path
3766 dst.bufferId = BUFFER_ID_NO_BUFFER;
3767 dst.buffer = nullptr;
3768 dst.acquireFence = nullptr;
3769 } else {
3770 ALOGE("%s: cannot send a null buffer in capture request!", __FUNCTION__);
3771 return BAD_VALUE;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003772 }
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003773 dst.streamId = streamId;
3774 dst.status = BufferStatus::OK;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003775 dst.releaseFence = nullptr;
3776
Yin-Chia Yeh5f840f82019-03-05 11:59:04 -08003777 // Output buffers are empty when using HAL buffer manager
3778 if (!mUseHalBufManager) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003779 mBufferRecords.pushInflightBuffer(
3780 captureRequest->frameNumber, streamId, src->buffer);
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003781 inflightBuffers->push_back(std::make_pair(captureRequest->frameNumber, streamId));
Yin-Chia Yeh5f840f82019-03-05 11:59:04 -08003782 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003783 }
3784 }
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003785 return OK;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003786}
3787
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003788void Camera3Device::HalInterface::cleanupNativeHandles(
3789 std::vector<native_handle_t*> *handles, bool closeFd) {
3790 if (handles == nullptr) {
3791 return;
3792 }
3793 if (closeFd) {
3794 for (auto& handle : *handles) {
3795 native_handle_close(handle);
3796 }
3797 }
3798 for (auto& handle : *handles) {
3799 native_handle_delete(handle);
3800 }
3801 handles->clear();
3802 return;
3803}
3804
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003805status_t Camera3Device::HalInterface::processBatchCaptureRequests(
Emilian Peevf4816702020-04-03 15:44:51 -07003806 std::vector<camera_capture_request_t*>& requests,/*out*/uint32_t* numRequestProcessed) {
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003807 ATRACE_NAME("CameraHal::processBatchCaptureRequests");
3808 if (!valid()) return INVALID_OPERATION;
3809
Emilian Peevaebbe412018-01-15 13:53:24 +00003810 sp<device::V3_4::ICameraDeviceSession> hidlSession_3_4;
Shuzhen Wang83bff122020-11-20 15:51:39 -08003811 sp<device::V3_7::ICameraDeviceSession> hidlSession_3_7;
3812 auto castResult_3_7 = device::V3_7::ICameraDeviceSession::castFrom(mHidlSession);
3813 if (castResult_3_7.isOk()) {
3814 hidlSession_3_7 = castResult_3_7;
3815 }
Emilian Peevaebbe412018-01-15 13:53:24 +00003816 auto castResult_3_4 = device::V3_4::ICameraDeviceSession::castFrom(mHidlSession);
3817 if (castResult_3_4.isOk()) {
3818 hidlSession_3_4 = castResult_3_4;
3819 }
3820
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003821 hardware::hidl_vec<device::V3_2::CaptureRequest> captureRequests;
Emilian Peevaebbe412018-01-15 13:53:24 +00003822 hardware::hidl_vec<device::V3_4::CaptureRequest> captureRequests_3_4;
Shuzhen Wang83bff122020-11-20 15:51:39 -08003823 hardware::hidl_vec<device::V3_7::CaptureRequest> captureRequests_3_7;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003824 size_t batchSize = requests.size();
Shuzhen Wang83bff122020-11-20 15:51:39 -08003825 if (hidlSession_3_7 != nullptr) {
3826 captureRequests_3_7.resize(batchSize);
3827 } else if (hidlSession_3_4 != nullptr) {
Emilian Peevaebbe412018-01-15 13:53:24 +00003828 captureRequests_3_4.resize(batchSize);
3829 } else {
3830 captureRequests.resize(batchSize);
3831 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003832 std::vector<native_handle_t*> handlesCreated;
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003833 std::vector<std::pair<int32_t, int32_t>> inflightBuffers;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003834
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003835 status_t res = OK;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003836 for (size_t i = 0; i < batchSize; i++) {
Shuzhen Wang83bff122020-11-20 15:51:39 -08003837 if (hidlSession_3_7 != nullptr) {
3838 res = wrapAsHidlRequest(requests[i], /*out*/&captureRequests_3_7[i].v3_4.v3_2,
3839 /*out*/&handlesCreated, /*out*/&inflightBuffers);
3840 } else if (hidlSession_3_4 != nullptr) {
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003841 res = wrapAsHidlRequest(requests[i], /*out*/&captureRequests_3_4[i].v3_2,
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003842 /*out*/&handlesCreated, /*out*/&inflightBuffers);
Emilian Peevaebbe412018-01-15 13:53:24 +00003843 } else {
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003844 res = wrapAsHidlRequest(requests[i], /*out*/&captureRequests[i],
3845 /*out*/&handlesCreated, /*out*/&inflightBuffers);
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003846 }
3847 if (res != OK) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003848 mBufferRecords.popInflightBuffers(inflightBuffers);
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003849 cleanupNativeHandles(&handlesCreated);
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003850 return res;
Emilian Peevaebbe412018-01-15 13:53:24 +00003851 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003852 }
3853
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003854 std::vector<device::V3_2::BufferCache> cachesToRemove;
3855 {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003856 std::lock_guard<std::mutex> lock(mFreedBuffersLock);
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003857 for (auto& pair : mFreedBuffers) {
3858 // The stream might have been removed since onBufferFreed
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003859 if (mBufferRecords.isStreamCached(pair.first)) {
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003860 cachesToRemove.push_back({pair.first, pair.second});
3861 }
3862 }
3863 mFreedBuffers.clear();
3864 }
3865
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003866 common::V1_0::Status status = common::V1_0::Status::INTERNAL_ERROR;
3867 *numRequestProcessed = 0;
Yifan Hongf79b5542017-04-11 14:44:25 -07003868
3869 // Write metadata to FMQ.
3870 for (size_t i = 0; i < batchSize; i++) {
Emilian Peevf4816702020-04-03 15:44:51 -07003871 camera_capture_request_t* request = requests[i];
Emilian Peevaebbe412018-01-15 13:53:24 +00003872 device::V3_2::CaptureRequest* captureRequest;
Shuzhen Wang83bff122020-11-20 15:51:39 -08003873 if (hidlSession_3_7 != nullptr) {
3874 captureRequest = &captureRequests_3_7[i].v3_4.v3_2;
3875 } else if (hidlSession_3_4 != nullptr) {
Emilian Peevaebbe412018-01-15 13:53:24 +00003876 captureRequest = &captureRequests_3_4[i].v3_2;
3877 } else {
3878 captureRequest = &captureRequests[i];
3879 }
Yifan Hongf79b5542017-04-11 14:44:25 -07003880
3881 if (request->settings != nullptr) {
3882 size_t settingsSize = get_camera_metadata_size(request->settings);
3883 if (mRequestMetadataQueue != nullptr && mRequestMetadataQueue->write(
3884 reinterpret_cast<const uint8_t*>(request->settings), settingsSize)) {
3885 captureRequest->settings.resize(0);
3886 captureRequest->fmqSettingsSize = settingsSize;
3887 } else {
3888 if (mRequestMetadataQueue != nullptr) {
3889 ALOGW("%s: couldn't utilize fmq, fallback to hwbinder", __FUNCTION__);
3890 }
3891 captureRequest->settings.setToExternal(
3892 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(request->settings)),
3893 get_camera_metadata_size(request->settings));
3894 captureRequest->fmqSettingsSize = 0u;
3895 }
3896 } else {
3897 // A null request settings maps to a size-0 CameraMetadata
3898 captureRequest->settings.resize(0);
3899 captureRequest->fmqSettingsSize = 0u;
3900 }
Emilian Peevaebbe412018-01-15 13:53:24 +00003901
Shuzhen Wang83bff122020-11-20 15:51:39 -08003902 // hidl session 3.7 specific handling.
3903 if (hidlSession_3_7 != nullptr) {
3904 captureRequests_3_7[i].inputWidth = request->input_width;
3905 captureRequests_3_7[i].inputHeight = request->input_height;
3906 }
3907
3908 // hidl session 3.7 and 3.4 specific handling.
3909 if (hidlSession_3_7 != nullptr || hidlSession_3_4 != nullptr) {
3910 hardware::hidl_vec<device::V3_4::PhysicalCameraSetting>& physicalCameraSettings =
3911 (hidlSession_3_7 != nullptr) ?
3912 captureRequests_3_7[i].v3_4.physicalCameraSettings :
3913 captureRequests_3_4[i].physicalCameraSettings;
3914 physicalCameraSettings.resize(request->num_physcam_settings);
Emilian Peevaebbe412018-01-15 13:53:24 +00003915 for (size_t j = 0; j < request->num_physcam_settings; j++) {
Emilian Peev00420d22018-02-05 21:33:13 +00003916 if (request->physcam_settings != nullptr) {
3917 size_t settingsSize = get_camera_metadata_size(request->physcam_settings[j]);
3918 if (mRequestMetadataQueue != nullptr && mRequestMetadataQueue->write(
3919 reinterpret_cast<const uint8_t*>(request->physcam_settings[j]),
3920 settingsSize)) {
Shuzhen Wang83bff122020-11-20 15:51:39 -08003921 physicalCameraSettings[j].settings.resize(0);
3922 physicalCameraSettings[j].fmqSettingsSize = settingsSize;
Emilian Peev00420d22018-02-05 21:33:13 +00003923 } else {
3924 if (mRequestMetadataQueue != nullptr) {
3925 ALOGW("%s: couldn't utilize fmq, fallback to hwbinder", __FUNCTION__);
3926 }
Shuzhen Wang83bff122020-11-20 15:51:39 -08003927 physicalCameraSettings[j].settings.setToExternal(
Emilian Peev00420d22018-02-05 21:33:13 +00003928 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(
3929 request->physcam_settings[j])),
3930 get_camera_metadata_size(request->physcam_settings[j]));
Shuzhen Wang83bff122020-11-20 15:51:39 -08003931 physicalCameraSettings[j].fmqSettingsSize = 0u;
Emilian Peevaebbe412018-01-15 13:53:24 +00003932 }
Emilian Peev00420d22018-02-05 21:33:13 +00003933 } else {
Yin-Chia Yeha2849702021-03-10 10:11:33 -08003934 physicalCameraSettings[j].fmqSettingsSize = 0u;
3935 physicalCameraSettings[j].settings.resize(0);
Emilian Peevaebbe412018-01-15 13:53:24 +00003936 }
Shuzhen Wang83bff122020-11-20 15:51:39 -08003937 physicalCameraSettings[j].physicalCameraId = request->physcam_id[j];
Emilian Peevaebbe412018-01-15 13:53:24 +00003938 }
3939 }
Yifan Hongf79b5542017-04-11 14:44:25 -07003940 }
Emilian Peevaebbe412018-01-15 13:53:24 +00003941
3942 hardware::details::return_status err;
Jayant Chowdharyc8d581e2018-07-16 14:46:23 -07003943 auto resultCallback =
3944 [&status, &numRequestProcessed] (auto s, uint32_t n) {
3945 status = s;
3946 *numRequestProcessed = n;
3947 };
Shuzhen Wang83bff122020-11-20 15:51:39 -08003948 if (hidlSession_3_7 != nullptr) {
3949 err = hidlSession_3_7->processCaptureRequest_3_7(captureRequests_3_7, cachesToRemove,
3950 resultCallback);
3951 } else if (hidlSession_3_4 != nullptr) {
Emilian Peevaebbe412018-01-15 13:53:24 +00003952 err = hidlSession_3_4->processCaptureRequest_3_4(captureRequests_3_4, cachesToRemove,
Jayant Chowdharyc8d581e2018-07-16 14:46:23 -07003953 resultCallback);
Emilian Peevaebbe412018-01-15 13:53:24 +00003954 } else {
3955 err = mHidlSession->processCaptureRequest(captureRequests, cachesToRemove,
Jayant Chowdharyc8d581e2018-07-16 14:46:23 -07003956 resultCallback);
Emilian Peevaebbe412018-01-15 13:53:24 +00003957 }
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -07003958 if (!err.isOk()) {
3959 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003960 status = common::V1_0::Status::CAMERA_DISCONNECTED;
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -07003961 }
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003962
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003963 if (status == common::V1_0::Status::OK && *numRequestProcessed != batchSize) {
3964 ALOGE("%s: processCaptureRequest returns OK but processed %d/%zu requests",
3965 __FUNCTION__, *numRequestProcessed, batchSize);
3966 status = common::V1_0::Status::INTERNAL_ERROR;
3967 }
3968
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003969 res = CameraProviderManager::mapToStatusT(status);
3970 if (res == OK) {
3971 if (mHidlSession->isRemote()) {
3972 // Only close acquire fence FDs when the HIDL transaction succeeds (so the FDs have been
3973 // sent to camera HAL processes)
3974 cleanupNativeHandles(&handlesCreated, /*closeFd*/true);
3975 } else {
3976 // In passthrough mode the FDs are now owned by HAL
3977 cleanupNativeHandles(&handlesCreated);
3978 }
3979 } else {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003980 mBufferRecords.popInflightBuffers(inflightBuffers);
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003981 cleanupNativeHandles(&handlesCreated);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003982 }
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003983 return res;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003984}
3985
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003986status_t Camera3Device::HalInterface::flush() {
3987 ATRACE_NAME("CameraHal::flush");
3988 if (!valid()) return INVALID_OPERATION;
3989 status_t res = OK;
3990
Emilian Peev31abd0a2017-05-11 18:37:46 +01003991 auto err = mHidlSession->flush();
3992 if (!err.isOk()) {
3993 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3994 res = DEAD_OBJECT;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003995 } else {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003996 res = CameraProviderManager::mapToStatusT(err);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003997 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003998
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003999 return res;
4000}
4001
Emilian Peev31abd0a2017-05-11 18:37:46 +01004002status_t Camera3Device::HalInterface::dump(int /*fd*/) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004003 ATRACE_NAME("CameraHal::dump");
4004 if (!valid()) return INVALID_OPERATION;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004005
Emilian Peev31abd0a2017-05-11 18:37:46 +01004006 // Handled by CameraProviderManager::dump
4007
4008 return OK;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004009}
4010
4011status_t Camera3Device::HalInterface::close() {
4012 ATRACE_NAME("CameraHal::close()");
4013 if (!valid()) return INVALID_OPERATION;
4014 status_t res = OK;
4015
Emilian Peev31abd0a2017-05-11 18:37:46 +01004016 auto err = mHidlSession->close();
4017 // Interface will be dead shortly anyway, so don't log errors
4018 if (!err.isOk()) {
4019 res = DEAD_OBJECT;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004020 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01004021
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004022 return res;
4023}
4024
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004025void Camera3Device::HalInterface::signalPipelineDrain(const std::vector<int>& streamIds) {
4026 ATRACE_NAME("CameraHal::signalPipelineDrain");
4027 if (!valid() || mHidlSession_3_5 == nullptr) {
4028 ALOGE("%s called on invalid camera!", __FUNCTION__);
4029 return;
4030 }
4031
Yin-Chia Yehc300a072019-02-13 14:56:57 -08004032 auto err = mHidlSession_3_5->signalStreamFlush(streamIds, mNextStreamConfigCounter - 1);
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004033 if (!err.isOk()) {
4034 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
4035 return;
4036 }
4037}
4038
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004039status_t Camera3Device::HalInterface::switchToOffline(
4040 const std::vector<int32_t>& streamsToKeep,
4041 /*out*/hardware::camera::device::V3_6::CameraOfflineSessionInfo* offlineSessionInfo,
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004042 /*out*/sp<hardware::camera::device::V3_6::ICameraOfflineSession>* offlineSession,
4043 /*out*/camera3::BufferRecords* bufferRecords) {
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004044 ATRACE_NAME("CameraHal::switchToOffline");
4045 if (!valid() || mHidlSession_3_6 == nullptr) {
4046 ALOGE("%s called on invalid camera!", __FUNCTION__);
4047 return INVALID_OPERATION;
4048 }
4049
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004050 if (offlineSessionInfo == nullptr || offlineSession == nullptr || bufferRecords == nullptr) {
4051 ALOGE("%s: output arguments must not be null!", __FUNCTION__);
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004052 return INVALID_OPERATION;
4053 }
4054
4055 common::V1_0::Status status = common::V1_0::Status::INTERNAL_ERROR;
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004056 auto resultCallback =
4057 [&status, &offlineSessionInfo, &offlineSession] (auto s, auto info, auto session) {
4058 status = s;
4059 *offlineSessionInfo = info;
4060 *offlineSession = session;
4061 };
4062 auto err = mHidlSession_3_6->switchToOffline(streamsToKeep, resultCallback);
4063
4064 if (!err.isOk()) {
4065 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
4066 return DEAD_OBJECT;
4067 }
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004068
4069 status_t ret = CameraProviderManager::mapToStatusT(status);
4070 if (ret != OK) {
4071 return ret;
4072 }
4073
4074 // TODO: assert no ongoing requestBuffer/returnBuffer call here
4075 // TODO: update RequestBufferStateMachine to block requestBuffer/returnBuffer once HAL
4076 // returns from switchToOffline.
4077
4078
4079 // Validate buffer caches
4080 std::vector<int32_t> streams;
4081 streams.reserve(offlineSessionInfo->offlineStreams.size());
4082 for (auto offlineStream : offlineSessionInfo->offlineStreams) {
4083 int32_t id = offlineStream.id;
4084 streams.push_back(id);
4085 // Verify buffer caches
4086 std::vector<uint64_t> bufIds(offlineStream.circulatingBufferIds.begin(),
4087 offlineStream.circulatingBufferIds.end());
4088 if (!verifyBufferIds(id, bufIds)) {
4089 ALOGE("%s: stream ID %d buffer cache records mismatch!", __FUNCTION__, id);
4090 return UNKNOWN_ERROR;
4091 }
4092 }
4093
4094 // Move buffer records
4095 bufferRecords->takeBufferCaches(mBufferRecords, streams);
4096 bufferRecords->takeInflightBufferMap(mBufferRecords);
4097 bufferRecords->takeRequestedBufferMap(mBufferRecords);
4098 return ret;
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004099}
4100
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07004101void Camera3Device::HalInterface::getInflightBufferKeys(
4102 std::vector<std::pair<int32_t, int32_t>>* out) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004103 mBufferRecords.getInflightBufferKeys(out);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07004104 return;
4105}
4106
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08004107void Camera3Device::HalInterface::getInflightRequestBufferKeys(
4108 std::vector<uint64_t>* out) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004109 mBufferRecords.getInflightRequestBufferKeys(out);
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08004110 return;
4111}
4112
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004113bool Camera3Device::HalInterface::verifyBufferIds(
4114 int32_t streamId, std::vector<uint64_t>& bufIds) {
4115 return mBufferRecords.verifyBufferIds(streamId, bufIds);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004116}
4117
4118status_t Camera3Device::HalInterface::popInflightBuffer(
Yin-Chia Yehf4650602017-01-10 13:13:39 -08004119 int32_t frameNumber, int32_t streamId,
4120 /*out*/ buffer_handle_t **buffer) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004121 return mBufferRecords.popInflightBuffer(frameNumber, streamId, buffer);
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07004122}
4123
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004124status_t Camera3Device::HalInterface::pushInflightRequestBuffer(
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08004125 uint64_t bufferId, buffer_handle_t* buf, int32_t streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004126 return mBufferRecords.pushInflightRequestBuffer(bufferId, buf, streamId);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004127}
4128
4129// Find and pop a buffer_handle_t based on bufferId
4130status_t Camera3Device::HalInterface::popInflightRequestBuffer(
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08004131 uint64_t bufferId,
4132 /*out*/ buffer_handle_t** buffer,
4133 /*optional out*/ int32_t* streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004134 return mBufferRecords.popInflightRequestBuffer(bufferId, buffer, streamId);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004135}
4136
Yin-Chia Yeh77327052017-01-09 18:23:07 -08004137std::pair<bool, uint64_t> Camera3Device::HalInterface::getBufferId(
4138 const buffer_handle_t& buf, int streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004139 return mBufferRecords.getBufferId(buf, streamId);
Yin-Chia Yeh77327052017-01-09 18:23:07 -08004140}
4141
Shuzhen Wangcd5b1822021-09-07 11:52:48 -07004142uint64_t Camera3Device::HalInterface::removeOneBufferCache(int streamId,
4143 const native_handle_t* handle) {
4144 return mBufferRecords.removeOneBufferCache(streamId, handle);
4145}
4146
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07004147void Camera3Device::HalInterface::onBufferFreed(
4148 int streamId, const native_handle_t* handle) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004149 uint32_t bufferId = mBufferRecords.removeOneBufferCache(streamId, handle);
4150 std::lock_guard<std::mutex> lock(mFreedBuffersLock);
4151 if (bufferId != BUFFER_ID_NO_BUFFER) {
4152 mFreedBuffers.push_back(std::make_pair(streamId, bufferId));
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07004153 }
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07004154}
4155
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07004156void Camera3Device::HalInterface::onStreamReConfigured(int streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004157 std::vector<uint64_t> bufIds = mBufferRecords.clearBufferCaches(streamId);
4158 std::lock_guard<std::mutex> lock(mFreedBuffersLock);
4159 for (auto bufferId : bufIds) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07004160 mFreedBuffers.push_back(std::make_pair(streamId, bufferId));
4161 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07004162}
4163
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004164/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004165 * RequestThread inner class methods
4166 */
4167
4168Camera3Device::RequestThread::RequestThread(wp<Camera3Device> parent,
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004169 sp<StatusTracker> statusTracker,
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004170 sp<HalInterface> interface, const Vector<int32_t>& sessionParamKeys,
Eino-Ville Talvala1646c3c2021-07-29 13:48:40 -07004171 bool useHalBufManager,
4172 bool supportCameraMute) :
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004173 Thread(/*canCallJava*/false),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004174 mParent(parent),
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004175 mStatusTracker(statusTracker),
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004176 mInterface(interface),
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07004177 mListener(nullptr),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004178 mId(getId(parent)),
Shuzhen Wang316781a2020-08-18 18:11:01 -07004179 mFirstRepeating(false),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004180 mReconfigured(false),
4181 mDoPause(false),
4182 mPaused(true),
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004183 mNotifyPipelineDrain(false),
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004184 mFrameNumber(0),
Jianing Weicb0652e2014-03-12 18:29:36 -07004185 mLatestRequestId(NAME_NOT_FOUND),
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07004186 mCurrentAfTriggerId(0),
4187 mCurrentPreCaptureTriggerId(0),
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004188 mRotateAndCropOverride(ANDROID_SCALER_ROTATE_AND_CROP_NONE),
Emilian Peeve23f1d92021-09-20 14:56:01 -07004189 mComposerOutput(false),
Eino-Ville Talvala11afe4f2021-05-27 14:45:31 -07004190 mCameraMute(ANDROID_SENSOR_TEST_PATTERN_MODE_OFF),
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004191 mCameraMuteChanged(false),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004192 mRepeatingLastFrameNumber(
4193 hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES),
Shuzhen Wang686f6442017-06-20 16:16:04 -07004194 mPrepareVideoStream(false),
Emilian Peeva14b4dd2018-05-15 11:00:31 +01004195 mConstrainedMode(false),
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004196 mRequestLatency(kRequestLatencyBinSize),
4197 mSessionParamKeys(sessionParamKeys),
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004198 mLatestSessionParams(sessionParamKeys.size()),
Eino-Ville Talvala1646c3c2021-07-29 13:48:40 -07004199 mUseHalBufManager(useHalBufManager),
4200 mSupportCameraMute(supportCameraMute){
Yin-Chia Yeh87b3ec02019-06-03 10:44:39 -07004201 mStatusId = statusTracker->addComponent("RequestThread");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004202}
4203
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004204Camera3Device::RequestThread::~RequestThread() {}
4205
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004206void Camera3Device::RequestThread::setNotificationListener(
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004207 wp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004208 ATRACE_CALL();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004209 Mutex::Autolock l(mRequestLock);
4210 mListener = listener;
4211}
4212
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004213void Camera3Device::RequestThread::configurationComplete(bool isConstrainedHighSpeed,
Shuzhen Wang99080502021-03-07 21:08:20 -08004214 const CameraMetadata& sessionParams,
4215 const std::map<int32_t, std::set<String8>>& groupIdPhysicalCameraMap) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004216 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004217 Mutex::Autolock l(mRequestLock);
4218 mReconfigured = true;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004219 mLatestSessionParams = sessionParams;
Shuzhen Wang99080502021-03-07 21:08:20 -08004220 mGroupIdPhysicalCameraMap = groupIdPhysicalCameraMap;
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07004221 // Prepare video stream for high speed recording.
4222 mPrepareVideoStream = isConstrainedHighSpeed;
Emilian Peeva14b4dd2018-05-15 11:00:31 +01004223 mConstrainedMode = isConstrainedHighSpeed;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004224}
4225
Jianing Wei90e59c92014-03-12 18:29:36 -07004226status_t Camera3Device::RequestThread::queueRequestList(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004227 List<sp<CaptureRequest> > &requests,
4228 /*out*/
4229 int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004230 ATRACE_CALL();
Jianing Wei90e59c92014-03-12 18:29:36 -07004231 Mutex::Autolock l(mRequestLock);
4232 for (List<sp<CaptureRequest> >::iterator it = requests.begin(); it != requests.end();
4233 ++it) {
4234 mRequestQueue.push_back(*it);
4235 }
4236
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004237 if (lastFrameNumber != NULL) {
4238 *lastFrameNumber = mFrameNumber + mRequestQueue.size() - 1;
4239 ALOGV("%s: requestId %d, mFrameNumber %" PRId32 ", lastFrameNumber %" PRId64 ".",
4240 __FUNCTION__, (*(requests.begin()))->mResultExtras.requestId, mFrameNumber,
4241 *lastFrameNumber);
4242 }
Jianing Weicb0652e2014-03-12 18:29:36 -07004243
Jianing Wei90e59c92014-03-12 18:29:36 -07004244 unpauseForNewRequests();
4245
4246 return OK;
4247}
4248
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004249
4250status_t Camera3Device::RequestThread::queueTrigger(
4251 RequestTrigger trigger[],
4252 size_t count) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004253 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004254 Mutex::Autolock l(mTriggerMutex);
4255 status_t ret;
4256
4257 for (size_t i = 0; i < count; ++i) {
4258 ret = queueTriggerLocked(trigger[i]);
4259
4260 if (ret != OK) {
4261 return ret;
4262 }
4263 }
4264
4265 return OK;
4266}
4267
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004268const String8& Camera3Device::RequestThread::getId(const wp<Camera3Device> &device) {
4269 static String8 deadId("<DeadDevice>");
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004270 sp<Camera3Device> d = device.promote();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004271 if (d != nullptr) return d->mId;
4272 return deadId;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004273}
4274
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004275status_t Camera3Device::RequestThread::queueTriggerLocked(
4276 RequestTrigger trigger) {
4277
4278 uint32_t tag = trigger.metadataTag;
4279 ssize_t index = mTriggerMap.indexOfKey(tag);
4280
4281 switch (trigger.getTagType()) {
4282 case TYPE_BYTE:
4283 // fall-through
4284 case TYPE_INT32:
4285 break;
4286 default:
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004287 ALOGE("%s: Type not supported: 0x%x", __FUNCTION__,
4288 trigger.getTagType());
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004289 return INVALID_OPERATION;
4290 }
4291
4292 /**
4293 * Collect only the latest trigger, since we only have 1 field
4294 * in the request settings per trigger tag, and can't send more than 1
4295 * trigger per request.
4296 */
4297 if (index != NAME_NOT_FOUND) {
4298 mTriggerMap.editValueAt(index) = trigger;
4299 } else {
4300 mTriggerMap.add(tag, trigger);
4301 }
4302
4303 return OK;
4304}
4305
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004306status_t Camera3Device::RequestThread::setRepeatingRequests(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004307 const RequestList &requests,
4308 /*out*/
4309 int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004310 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004311 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004312 if (lastFrameNumber != NULL) {
4313 *lastFrameNumber = mRepeatingLastFrameNumber;
4314 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004315 mRepeatingRequests.clear();
Shuzhen Wang316781a2020-08-18 18:11:01 -07004316 mFirstRepeating = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004317 mRepeatingRequests.insert(mRepeatingRequests.begin(),
4318 requests.begin(), requests.end());
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004319
4320 unpauseForNewRequests();
4321
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004322 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004323 return OK;
4324}
4325
Chih-Hung Hsieh8b0b9712016-08-09 14:25:53 -07004326bool Camera3Device::RequestThread::isRepeatingRequestLocked(const sp<CaptureRequest>& requestIn) {
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07004327 if (mRepeatingRequests.empty()) {
4328 return false;
4329 }
4330 int32_t requestId = requestIn->mResultExtras.requestId;
4331 const RequestList &repeatRequests = mRepeatingRequests;
4332 // All repeating requests are guaranteed to have same id so only check first quest
4333 const sp<CaptureRequest> firstRequest = *repeatRequests.begin();
4334 return (firstRequest->mResultExtras.requestId == requestId);
4335}
4336
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004337status_t Camera3Device::RequestThread::clearRepeatingRequests(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004338 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004339 Mutex::Autolock l(mRequestLock);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004340 return clearRepeatingRequestsLocked(lastFrameNumber);
4341
4342}
4343
4344status_t Camera3Device::RequestThread::clearRepeatingRequestsLocked(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004345 mRepeatingRequests.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004346 if (lastFrameNumber != NULL) {
4347 *lastFrameNumber = mRepeatingLastFrameNumber;
4348 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004349 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004350 return OK;
4351}
4352
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004353status_t Camera3Device::RequestThread::clear(
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004354 /*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004355 ATRACE_CALL();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004356 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004357 ALOGV("RequestThread::%s:", __FUNCTION__);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004358
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004359 mRepeatingRequests.clear();
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07004360
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004361 // Send errors for all requests pending in the request queue, including
4362 // pending repeating requests
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004363 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004364 if (listener != NULL) {
4365 for (RequestList::iterator it = mRequestQueue.begin();
4366 it != mRequestQueue.end(); ++it) {
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004367 // Abort the input buffers for reprocess requests.
4368 if ((*it)->mInputStream != NULL) {
Emilian Peevf4816702020-04-03 15:44:51 -07004369 camera_stream_buffer_t inputBuffer;
Shuzhen Wang83bff122020-11-20 15:51:39 -08004370 camera3::Size inputBufferSize;
Eino-Ville Talvalaba435252017-06-21 16:07:25 -07004371 status_t res = (*it)->mInputStream->getInputBuffer(&inputBuffer,
Shuzhen Wang83bff122020-11-20 15:51:39 -08004372 &inputBufferSize, /*respectHalLimit*/ false);
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004373 if (res != OK) {
4374 ALOGW("%s: %d: couldn't get input buffer while clearing the request "
4375 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
4376 } else {
Emilian Peevf4816702020-04-03 15:44:51 -07004377 inputBuffer.status = CAMERA_BUFFER_STATUS_ERROR;
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004378 res = (*it)->mInputStream->returnInputBuffer(inputBuffer);
4379 if (res != OK) {
4380 ALOGE("%s: %d: couldn't return input buffer while clearing the request "
4381 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
4382 }
4383 }
4384 }
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004385 // Set the frame number this request would have had, if it
4386 // had been submitted; this frame number will not be reused.
4387 // The requestId and burstId fields were set when the request was
4388 // submitted originally (in convertMetadataListToRequestListLocked)
4389 (*it)->mResultExtras.frameNumber = mFrameNumber++;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004390 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004391 (*it)->mResultExtras);
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07004392 }
4393 }
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004394 mRequestQueue.clear();
Jinguang Dongb26e7a02016-11-14 16:04:02 +08004395
4396 Mutex::Autolock al(mTriggerMutex);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004397 mTriggerMap.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004398 if (lastFrameNumber != NULL) {
4399 *lastFrameNumber = mRepeatingLastFrameNumber;
4400 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004401 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Emilian Peev8dae54c2019-12-02 15:17:17 -08004402 mRequestSignal.signal();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004403 return OK;
4404}
4405
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004406status_t Camera3Device::RequestThread::flush() {
4407 ATRACE_CALL();
4408 Mutex::Autolock l(mFlushLock);
4409
Emilian Peev08dd2452017-04-06 16:55:14 +01004410 return mInterface->flush();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004411}
4412
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004413void Camera3Device::RequestThread::setPaused(bool paused) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004414 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004415 Mutex::Autolock l(mPauseLock);
4416 mDoPause = paused;
4417 mDoPauseSignal.signal();
4418}
4419
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004420status_t Camera3Device::RequestThread::waitUntilRequestProcessed(
4421 int32_t requestId, nsecs_t timeout) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004422 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004423 Mutex::Autolock l(mLatestRequestMutex);
4424 status_t res;
4425 while (mLatestRequestId != requestId) {
4426 nsecs_t startTime = systemTime();
4427
4428 res = mLatestRequestSignal.waitRelative(mLatestRequestMutex, timeout);
4429 if (res != OK) return res;
4430
4431 timeout -= (systemTime() - startTime);
4432 }
4433
4434 return OK;
4435}
4436
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004437void Camera3Device::RequestThread::requestExit() {
4438 // Call parent to set up shutdown
4439 Thread::requestExit();
4440 // The exit from any possible waits
4441 mDoPauseSignal.signal();
4442 mRequestSignal.signal();
Shuzhen Wang686f6442017-06-20 16:16:04 -07004443
4444 mRequestLatency.log("ProcessCaptureRequest latency histogram");
4445 mRequestLatency.reset();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004446}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004447
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004448void Camera3Device::RequestThread::checkAndStopRepeatingRequest() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004449 ATRACE_CALL();
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07004450 bool surfaceAbandoned = false;
4451 int64_t lastFrameNumber = 0;
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004452 sp<NotificationListener> listener;
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07004453 {
4454 Mutex::Autolock l(mRequestLock);
4455 // Check all streams needed by repeating requests are still valid. Otherwise, stop
4456 // repeating requests.
4457 for (const auto& request : mRepeatingRequests) {
4458 for (const auto& s : request->mOutputStreams) {
4459 if (s->isAbandoned()) {
4460 surfaceAbandoned = true;
4461 clearRepeatingRequestsLocked(&lastFrameNumber);
4462 break;
4463 }
4464 }
4465 if (surfaceAbandoned) {
4466 break;
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004467 }
4468 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004469 listener = mListener.promote();
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004470 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004471
4472 if (listener != NULL && surfaceAbandoned) {
4473 listener->notifyRepeatingRequestError(lastFrameNumber);
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07004474 }
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004475}
4476
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004477bool Camera3Device::RequestThread::sendRequestsBatch() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004478 ATRACE_CALL();
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004479 status_t res;
4480 size_t batchSize = mNextRequests.size();
Emilian Peevf4816702020-04-03 15:44:51 -07004481 std::vector<camera_capture_request_t*> requests(batchSize);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004482 uint32_t numRequestProcessed = 0;
4483 for (size_t i = 0; i < batchSize; i++) {
4484 requests[i] = &mNextRequests.editItemAt(i).halRequest;
Yin-Chia Yeh885691c2018-05-01 15:54:24 -07004485 ATRACE_ASYNC_BEGIN("frame capture", mNextRequests[i].halRequest.frame_number);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004486 }
4487
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004488 res = mInterface->processBatchCaptureRequests(requests, &numRequestProcessed);
4489
4490 bool triggerRemoveFailed = false;
4491 NextRequest& triggerFailedRequest = mNextRequests.editItemAt(0);
4492 for (size_t i = 0; i < numRequestProcessed; i++) {
4493 NextRequest& nextRequest = mNextRequests.editItemAt(i);
4494 nextRequest.submitted = true;
4495
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004496 updateNextRequest(nextRequest);
Emilian Peevaebbe412018-01-15 13:53:24 +00004497
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004498 if (!triggerRemoveFailed) {
4499 // Remove any previously queued triggers (after unlock)
4500 status_t removeTriggerRes = removeTriggers(mPrevRequest);
4501 if (removeTriggerRes != OK) {
4502 triggerRemoveFailed = true;
4503 triggerFailedRequest = nextRequest;
4504 }
4505 }
4506 }
4507
4508 if (triggerRemoveFailed) {
4509 SET_ERR("RequestThread: Unable to remove triggers "
4510 "(capture request %d, HAL device: %s (%d)",
4511 triggerFailedRequest.halRequest.frame_number, strerror(-res), res);
4512 cleanUpFailedRequests(/*sendRequestError*/ false);
4513 return false;
4514 }
4515
4516 if (res != OK) {
4517 // Should only get a failure here for malformed requests or device-level
4518 // errors, so consider all errors fatal. Bad metadata failures should
4519 // come through notify.
4520 SET_ERR("RequestThread: Unable to submit capture request %d to HAL device: %s (%d)",
4521 mNextRequests[numRequestProcessed].halRequest.frame_number,
4522 strerror(-res), res);
4523 cleanUpFailedRequests(/*sendRequestError*/ false);
4524 return false;
4525 }
4526 return true;
4527}
4528
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07004529nsecs_t Camera3Device::RequestThread::calculateMaxExpectedDuration(const camera_metadata_t *request) {
4530 nsecs_t maxExpectedDuration = kDefaultExpectedDuration;
4531 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
4532 find_camera_metadata_ro_entry(request,
4533 ANDROID_CONTROL_AE_MODE,
4534 &e);
4535 if (e.count == 0) return maxExpectedDuration;
4536
4537 switch (e.data.u8[0]) {
4538 case ANDROID_CONTROL_AE_MODE_OFF:
4539 find_camera_metadata_ro_entry(request,
4540 ANDROID_SENSOR_EXPOSURE_TIME,
4541 &e);
4542 if (e.count > 0) {
4543 maxExpectedDuration = e.data.i64[0];
4544 }
4545 find_camera_metadata_ro_entry(request,
4546 ANDROID_SENSOR_FRAME_DURATION,
4547 &e);
4548 if (e.count > 0) {
4549 maxExpectedDuration = std::max(e.data.i64[0], maxExpectedDuration);
4550 }
4551 break;
4552 default:
4553 find_camera_metadata_ro_entry(request,
4554 ANDROID_CONTROL_AE_TARGET_FPS_RANGE,
4555 &e);
4556 if (e.count > 1) {
4557 maxExpectedDuration = 1e9 / e.data.u8[0];
4558 }
4559 break;
4560 }
4561
4562 return maxExpectedDuration;
4563}
4564
Emilian Peeva14b4dd2018-05-15 11:00:31 +01004565bool Camera3Device::RequestThread::skipHFRTargetFPSUpdate(int32_t tag,
4566 const camera_metadata_ro_entry_t& newEntry, const camera_metadata_entry_t& currentEntry) {
4567 if (mConstrainedMode && (ANDROID_CONTROL_AE_TARGET_FPS_RANGE == tag) &&
4568 (newEntry.count == currentEntry.count) && (currentEntry.count == 2) &&
4569 (currentEntry.data.i32[1] == newEntry.data.i32[1])) {
4570 return true;
4571 }
4572
4573 return false;
4574}
4575
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004576void Camera3Device::RequestThread::updateNextRequest(NextRequest& nextRequest) {
4577 // Update the latest request sent to HAL
Shuzhen Wang83bff122020-11-20 15:51:39 -08004578 camera_capture_request_t& halRequest = nextRequest.halRequest;
4579 if (halRequest.settings != NULL) { // Don't update if they were unchanged
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004580 Mutex::Autolock al(mLatestRequestMutex);
4581
Shuzhen Wang83bff122020-11-20 15:51:39 -08004582 camera_metadata_t* cloned = clone_camera_metadata(halRequest.settings);
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004583 mLatestRequest.acquire(cloned);
4584
4585 mLatestPhysicalRequest.clear();
Shuzhen Wang83bff122020-11-20 15:51:39 -08004586 for (uint32_t i = 0; i < halRequest.num_physcam_settings; i++) {
4587 cloned = clone_camera_metadata(halRequest.physcam_settings[i]);
4588 mLatestPhysicalRequest.emplace(halRequest.physcam_id[i],
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004589 CameraMetadata(cloned));
4590 }
4591
4592 sp<Camera3Device> parent = mParent.promote();
4593 if (parent != NULL) {
4594 parent->monitorMetadata(TagMonitor::REQUEST,
Shuzhen Wang83bff122020-11-20 15:51:39 -08004595 halRequest.frame_number,
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004596 0, mLatestRequest, mLatestPhysicalRequest);
4597 }
4598 }
4599
Shuzhen Wang83bff122020-11-20 15:51:39 -08004600 if (halRequest.settings != NULL) {
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004601 nextRequest.captureRequest->mSettingsList.begin()->metadata.unlock(
Shuzhen Wang83bff122020-11-20 15:51:39 -08004602 halRequest.settings);
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004603 }
4604
Shuzhen Wang83bff122020-11-20 15:51:39 -08004605 cleanupPhysicalSettings(nextRequest.captureRequest, &halRequest);
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004606}
4607
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004608bool Camera3Device::RequestThread::updateSessionParameters(const CameraMetadata& settings) {
4609 ATRACE_CALL();
4610 bool updatesDetected = false;
4611
Emilian Peev4ec17882019-01-24 17:16:58 -08004612 CameraMetadata updatedParams(mLatestSessionParams);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004613 for (auto tag : mSessionParamKeys) {
4614 camera_metadata_ro_entry entry = settings.find(tag);
Emilian Peev4ec17882019-01-24 17:16:58 -08004615 camera_metadata_entry lastEntry = updatedParams.find(tag);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004616
4617 if (entry.count > 0) {
4618 bool isDifferent = false;
4619 if (lastEntry.count > 0) {
4620 // Have a last value, compare to see if changed
4621 if (lastEntry.type == entry.type &&
4622 lastEntry.count == entry.count) {
4623 // Same type and count, compare values
4624 size_t bytesPerValue = camera_metadata_type_size[lastEntry.type];
4625 size_t entryBytes = bytesPerValue * lastEntry.count;
4626 int cmp = memcmp(entry.data.u8, lastEntry.data.u8, entryBytes);
4627 if (cmp != 0) {
4628 isDifferent = true;
4629 }
4630 } else {
4631 // Count or type has changed
4632 isDifferent = true;
4633 }
4634 } else {
4635 // No last entry, so always consider to be different
4636 isDifferent = true;
4637 }
4638
4639 if (isDifferent) {
4640 ALOGV("%s: Session parameter tag id %d changed", __FUNCTION__, tag);
Emilian Peeva14b4dd2018-05-15 11:00:31 +01004641 if (!skipHFRTargetFPSUpdate(tag, entry, lastEntry)) {
4642 updatesDetected = true;
4643 }
Emilian Peev4ec17882019-01-24 17:16:58 -08004644 updatedParams.update(entry);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004645 }
4646 } else if (lastEntry.count > 0) {
4647 // Value has been removed
4648 ALOGV("%s: Session parameter tag id %d removed", __FUNCTION__, tag);
Emilian Peev4ec17882019-01-24 17:16:58 -08004649 updatedParams.erase(tag);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004650 updatesDetected = true;
4651 }
4652 }
4653
Emilian Peev4ec17882019-01-24 17:16:58 -08004654 bool reconfigureRequired;
4655 if (updatesDetected) {
4656 reconfigureRequired = mInterface->isReconfigurationRequired(mLatestSessionParams,
4657 updatedParams);
4658 mLatestSessionParams = updatedParams;
4659 } else {
4660 reconfigureRequired = false;
4661 }
4662
4663 return reconfigureRequired;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004664}
4665
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004666bool Camera3Device::RequestThread::threadLoop() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004667 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004668 status_t res;
Jayant Chowdhary37eca242019-11-18 08:55:56 -08004669 // Any function called from threadLoop() must not hold mInterfaceLock since
4670 // it could lead to deadlocks (disconnect() -> hold mInterfaceMutex -> wait for request thread
4671 // to finish -> request thread waits on mInterfaceMutex) http://b/143513518
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004672
4673 // Handle paused state.
4674 if (waitIfPaused()) {
4675 return true;
4676 }
4677
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004678 // Wait for the next batch of requests.
4679 waitForNextRequestBatch();
4680 if (mNextRequests.size() == 0) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004681 return true;
4682 }
4683
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004684 // Get the latest request ID, if any
4685 int latestRequestId;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004686 camera_metadata_entry_t requestIdEntry = mNextRequests[mNextRequests.size() - 1].
Emilian Peevaebbe412018-01-15 13:53:24 +00004687 captureRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_ID);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004688 if (requestIdEntry.count > 0) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004689 latestRequestId = requestIdEntry.data.i32[0];
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004690 } else {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004691 ALOGW("%s: Did not have android.request.id set in the request.", __FUNCTION__);
4692 latestRequestId = NAME_NOT_FOUND;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004693 }
4694
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004695 // 'mNextRequests' will at this point contain either a set of HFR batched requests
4696 // or a single request from streaming or burst. In either case the first element
4697 // should contain the latest camera settings that we need to check for any session
4698 // parameter updates.
Emilian Peevaebbe412018-01-15 13:53:24 +00004699 if (updateSessionParameters(mNextRequests[0].captureRequest->mSettingsList.begin()->metadata)) {
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004700 res = OK;
4701
4702 //Input stream buffers are already acquired at this point so an input stream
4703 //will not be able to move to idle state unless we force it.
4704 if (mNextRequests[0].captureRequest->mInputStream != nullptr) {
4705 res = mNextRequests[0].captureRequest->mInputStream->forceToIdle();
4706 if (res != OK) {
4707 ALOGE("%s: Failed to force idle input stream: %d", __FUNCTION__, res);
4708 cleanUpFailedRequests(/*sendRequestError*/ false);
4709 return false;
4710 }
4711 }
4712
4713 if (res == OK) {
Emilian Peev3bead5f2020-05-28 17:29:08 -07004714 sp<Camera3Device> parent = mParent.promote();
4715 if (parent != nullptr) {
4716 mReconfigured |= parent->reconfigureCamera(mLatestSessionParams, mStatusId);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004717 }
Emilian Peev3bead5f2020-05-28 17:29:08 -07004718 setPaused(false);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004719
4720 if (mNextRequests[0].captureRequest->mInputStream != nullptr) {
4721 mNextRequests[0].captureRequest->mInputStream->restoreConfiguredState();
4722 if (res != OK) {
4723 ALOGE("%s: Failed to restore configured input stream: %d", __FUNCTION__, res);
4724 cleanUpFailedRequests(/*sendRequestError*/ false);
4725 return false;
4726 }
4727 }
4728 }
4729 }
4730
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004731 // Prepare a batch of HAL requests and output buffers.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004732 res = prepareHalRequests();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004733 if (res == TIMED_OUT) {
4734 // Not a fatal error if getting output buffers time out.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004735 cleanUpFailedRequests(/*sendRequestError*/ true);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004736 // Check if any stream is abandoned.
4737 checkAndStopRepeatingRequest();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004738 return true;
4739 } else if (res != OK) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004740 cleanUpFailedRequests(/*sendRequestError*/ false);
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004741 return false;
4742 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004743
Zhijun Hecc27e112013-10-03 16:12:43 -07004744 // Inform waitUntilRequestProcessed thread of a new request ID
4745 {
4746 Mutex::Autolock al(mLatestRequestMutex);
4747
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004748 mLatestRequestId = latestRequestId;
Zhijun Hecc27e112013-10-03 16:12:43 -07004749 mLatestRequestSignal.signal();
4750 }
4751
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004752 // Submit a batch of requests to HAL.
4753 // Use flush lock only when submitting multilple requests in a batch.
4754 // TODO: The problem with flush lock is flush() will be blocked by process_capture_request()
4755 // which may take a long time to finish so synchronizing flush() and
4756 // process_capture_request() defeats the purpose of cancelling requests ASAP with flush().
4757 // For now, only synchronize for high speed recording and we should figure something out for
4758 // removing the synchronization.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004759 bool useFlushLock = mNextRequests.size() > 1;
Eino-Ville Talvala17a61ad2013-06-03 16:53:32 -07004760
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004761 if (useFlushLock) {
4762 mFlushLock.lock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004763 }
4764
Zhijun Hef0645c12016-08-02 00:58:11 -07004765 ALOGVV("%s: %d: submitting %zu requests in a batch.", __FUNCTION__, __LINE__,
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004766 mNextRequests.size());
Igor Murashkin1e479c02013-09-06 16:55:14 -07004767
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08004768 sp<Camera3Device> parent = mParent.promote();
4769 if (parent != nullptr) {
4770 parent->mRequestBufferSM.onSubmittingRequest();
4771 }
4772
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004773 bool submitRequestSuccess = false;
Shuzhen Wang686f6442017-06-20 16:16:04 -07004774 nsecs_t tRequestStart = systemTime(SYSTEM_TIME_MONOTONIC);
Yin-Chia Yeh11648852019-05-16 10:42:54 -07004775 submitRequestSuccess = sendRequestsBatch();
4776
Shuzhen Wang686f6442017-06-20 16:16:04 -07004777 nsecs_t tRequestEnd = systemTime(SYSTEM_TIME_MONOTONIC);
4778 mRequestLatency.add(tRequestStart, tRequestEnd);
Igor Murashkin1e479c02013-09-06 16:55:14 -07004779
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004780 if (useFlushLock) {
4781 mFlushLock.unlock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004782 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004783
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004784 // Unset as current request
4785 {
4786 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004787 mNextRequests.clear();
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004788 }
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004789 mRequestSubmittedSignal.signal();
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004790
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004791 return submitRequestSuccess;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004792}
4793
Jayant Chowdhary65c9bf02021-09-03 16:44:16 +00004794status_t Camera3Device::removeFwkOnlyRegionKeys(CameraMetadata *request) {
4795 static const std::array<uint32_t, 4> kFwkOnlyRegionKeys = {ANDROID_CONTROL_AF_REGIONS_SET,
4796 ANDROID_CONTROL_AE_REGIONS_SET, ANDROID_CONTROL_AWB_REGIONS_SET,
4797 ANDROID_SCALER_CROP_REGION_SET};
4798 if (request == nullptr) {
4799 ALOGE("%s request metadata nullptr", __FUNCTION__);
4800 return BAD_VALUE;
4801 }
4802 status_t res = OK;
4803 for (const auto &key : kFwkOnlyRegionKeys) {
4804 if (request->exists(key)) {
4805 res = request->erase(key);
4806 if (res != OK) {
4807 return res;
4808 }
4809 }
4810 }
4811 return OK;
4812}
4813
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004814status_t Camera3Device::RequestThread::prepareHalRequests() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004815 ATRACE_CALL();
4816
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07004817 bool batchedRequest = mNextRequests[0].captureRequest->mBatchSize > 1;
Shuzhen Wang4a472662017-02-26 23:29:04 -08004818 for (size_t i = 0; i < mNextRequests.size(); i++) {
4819 auto& nextRequest = mNextRequests.editItemAt(i);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004820 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
Emilian Peevf4816702020-04-03 15:44:51 -07004821 camera_capture_request_t* halRequest = &nextRequest.halRequest;
4822 Vector<camera_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004823
4824 // Prepare a request to HAL
4825 halRequest->frame_number = captureRequest->mResultExtras.frameNumber;
4826
4827 // Insert any queued triggers (before metadata is locked)
4828 status_t res = insertTriggers(captureRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004829 if (res < 0) {
4830 SET_ERR("RequestThread: Unable to insert triggers "
4831 "(capture request %d, HAL device: %s (%d)",
4832 halRequest->frame_number, strerror(-res), res);
4833 return INVALID_OPERATION;
4834 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07004835
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004836 int triggerCount = res;
4837 bool triggersMixedIn = (triggerCount > 0 || mPrevTriggers > 0);
4838 mPrevTriggers = triggerCount;
4839
Emilian Peeve23f1d92021-09-20 14:56:01 -07004840 // Do not override rotate&crop for stream configurations that include
4841 // SurfaceViews(HW_COMPOSER) output. The display rotation there will be
4842 // compensated by NATIVE_WINDOW_TRANSFORM_INVERSE_DISPLAY
4843 bool rotateAndCropChanged = mComposerOutput ? false :
4844 overrideAutoRotateAndCrop(captureRequest);
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004845 bool testPatternChanged = overrideTestPattern(captureRequest);
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004846
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004847 // If the request is the same as last, or we had triggers now or last time or
4848 // changing overrides this time
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004849 bool newRequest =
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004850 (mPrevRequest != captureRequest || triggersMixedIn ||
4851 rotateAndCropChanged || testPatternChanged) &&
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07004852 // Request settings are all the same within one batch, so only treat the first
4853 // request in a batch as new
Zhijun He54c36822018-07-18 09:33:39 -07004854 !(batchedRequest && i > 0);
Emilian Peev00420d22018-02-05 21:33:13 +00004855 if (newRequest) {
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08004856 std::set<std::string> cameraIdsWithZoom;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004857 /**
4858 * HAL workaround:
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004859 * Insert a fake trigger ID if a trigger is set but no trigger ID is
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004860 */
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004861 res = addFakeTriggerIds(captureRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004862 if (res != OK) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004863 SET_ERR("RequestThread: Unable to insert fake trigger IDs "
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004864 "(capture request %d, HAL device: %s (%d)",
4865 halRequest->frame_number, strerror(-res), res);
4866 return INVALID_OPERATION;
4867 }
4868
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07004869 {
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07004870 sp<Camera3Device> parent = mParent.promote();
4871 if (parent != nullptr) {
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -07004872 List<PhysicalCameraSettings>::iterator it;
4873 for (it = captureRequest->mSettingsList.begin();
4874 it != captureRequest->mSettingsList.end(); it++) {
Jayant Chowdhary9255ce02021-07-15 11:18:17 -07004875 if (parent->mUHRCropAndMeteringRegionMappers.find(it->cameraId) ==
4876 parent->mUHRCropAndMeteringRegionMappers.end()) {
Jayant Chowdhary65c9bf02021-09-03 16:44:16 +00004877 if (removeFwkOnlyRegionKeys(&(it->metadata)) != OK) {
4878 SET_ERR("RequestThread: Unable to remove fwk-only keys from request"
4879 "%d: %s (%d)", halRequest->frame_number, strerror(-res),
4880 res);
4881 return INVALID_OPERATION;
4882 }
Jayant Chowdhary9255ce02021-07-15 11:18:17 -07004883 continue;
4884 }
4885
4886 if (!captureRequest->mUHRCropAndMeteringRegionsUpdated) {
4887 res = parent->mUHRCropAndMeteringRegionMappers[it->cameraId].
4888 updateCaptureRequest(&(it->metadata));
4889 if (res != OK) {
4890 SET_ERR("RequestThread: Unable to correct capture requests "
4891 "for scaler crop region and metering regions for request "
4892 "%d: %s (%d)", halRequest->frame_number, strerror(-res),
4893 res);
4894 return INVALID_OPERATION;
4895 }
4896 captureRequest->mUHRCropAndMeteringRegionsUpdated = true;
Jayant Chowdhary65c9bf02021-09-03 16:44:16 +00004897 if (removeFwkOnlyRegionKeys(&(it->metadata)) != OK) {
4898 SET_ERR("RequestThread: Unable to remove fwk-only keys from request"
4899 "%d: %s (%d)", halRequest->frame_number, strerror(-res),
4900 res);
4901 return INVALID_OPERATION;
4902 }
Jayant Chowdhary9255ce02021-07-15 11:18:17 -07004903 }
4904 }
4905
4906 // Correct metadata regions for distortion correction if enabled
4907 for (it = captureRequest->mSettingsList.begin();
4908 it != captureRequest->mSettingsList.end(); it++) {
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -07004909 if (parent->mDistortionMappers.find(it->cameraId) ==
4910 parent->mDistortionMappers.end()) {
4911 continue;
4912 }
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07004913
4914 if (!captureRequest->mDistortionCorrectionUpdated) {
4915 res = parent->mDistortionMappers[it->cameraId].correctCaptureRequest(
4916 &(it->metadata));
4917 if (res != OK) {
4918 SET_ERR("RequestThread: Unable to correct capture requests "
4919 "for lens distortion for request %d: %s (%d)",
4920 halRequest->frame_number, strerror(-res), res);
4921 return INVALID_OPERATION;
4922 }
4923 captureRequest->mDistortionCorrectionUpdated = true;
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -07004924 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07004925 }
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08004926
4927 for (it = captureRequest->mSettingsList.begin();
4928 it != captureRequest->mSettingsList.end(); it++) {
4929 if (parent->mZoomRatioMappers.find(it->cameraId) ==
4930 parent->mZoomRatioMappers.end()) {
4931 continue;
4932 }
4933
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07004934 if (!captureRequest->mZoomRatioIs1x) {
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08004935 cameraIdsWithZoom.insert(it->cameraId);
4936 }
4937
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07004938 if (!captureRequest->mZoomRatioUpdated) {
4939 res = parent->mZoomRatioMappers[it->cameraId].updateCaptureRequest(
4940 &(it->metadata));
4941 if (res != OK) {
4942 SET_ERR("RequestThread: Unable to correct capture requests "
4943 "for zoom ratio for request %d: %s (%d)",
4944 halRequest->frame_number, strerror(-res), res);
4945 return INVALID_OPERATION;
4946 }
4947 captureRequest->mZoomRatioUpdated = true;
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08004948 }
4949 }
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07004950 if (captureRequest->mRotateAndCropAuto &&
4951 !captureRequest->mRotationAndCropUpdated) {
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004952 for (it = captureRequest->mSettingsList.begin();
4953 it != captureRequest->mSettingsList.end(); it++) {
4954 auto mapper = parent->mRotateAndCropMappers.find(it->cameraId);
4955 if (mapper != parent->mRotateAndCropMappers.end()) {
4956 res = mapper->second.updateCaptureRequest(&(it->metadata));
4957 if (res != OK) {
4958 SET_ERR("RequestThread: Unable to correct capture requests "
4959 "for rotate-and-crop for request %d: %s (%d)",
4960 halRequest->frame_number, strerror(-res), res);
4961 return INVALID_OPERATION;
4962 }
4963 }
4964 }
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07004965 captureRequest->mRotationAndCropUpdated = true;
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004966 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07004967 }
4968 }
4969
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004970 /**
4971 * The request should be presorted so accesses in HAL
4972 * are O(logn). Sidenote, sorting a sorted metadata is nop.
4973 */
Emilian Peevaebbe412018-01-15 13:53:24 +00004974 captureRequest->mSettingsList.begin()->metadata.sort();
4975 halRequest->settings = captureRequest->mSettingsList.begin()->metadata.getAndLock();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004976 mPrevRequest = captureRequest;
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08004977 mPrevCameraIdsWithZoom = cameraIdsWithZoom;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004978 ALOGVV("%s: Request settings are NEW", __FUNCTION__);
4979
4980 IF_ALOGV() {
4981 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
4982 find_camera_metadata_ro_entry(
4983 halRequest->settings,
4984 ANDROID_CONTROL_AF_TRIGGER,
4985 &e
4986 );
4987 if (e.count > 0) {
4988 ALOGV("%s: Request (frame num %d) had AF trigger 0x%x",
4989 __FUNCTION__,
4990 halRequest->frame_number,
4991 e.data.u8[0]);
4992 }
4993 }
4994 } else {
4995 // leave request.settings NULL to indicate 'reuse latest given'
4996 ALOGVV("%s: Request settings are REUSED",
4997 __FUNCTION__);
4998 }
4999
Emilian Peevaebbe412018-01-15 13:53:24 +00005000 if (captureRequest->mSettingsList.size() > 1) {
5001 halRequest->num_physcam_settings = captureRequest->mSettingsList.size() - 1;
5002 halRequest->physcam_id = new const char* [halRequest->num_physcam_settings];
Emilian Peev00420d22018-02-05 21:33:13 +00005003 if (newRequest) {
5004 halRequest->physcam_settings =
5005 new const camera_metadata* [halRequest->num_physcam_settings];
5006 } else {
5007 halRequest->physcam_settings = nullptr;
5008 }
Emilian Peevaebbe412018-01-15 13:53:24 +00005009 auto it = ++captureRequest->mSettingsList.begin();
5010 size_t i = 0;
5011 for (; it != captureRequest->mSettingsList.end(); it++, i++) {
5012 halRequest->physcam_id[i] = it->cameraId.c_str();
Emilian Peev00420d22018-02-05 21:33:13 +00005013 if (newRequest) {
5014 it->metadata.sort();
5015 halRequest->physcam_settings[i] = it->metadata.getAndLock();
5016 }
Emilian Peevaebbe412018-01-15 13:53:24 +00005017 }
5018 }
5019
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005020 uint32_t totalNumBuffers = 0;
5021
5022 // Fill in buffers
5023 if (captureRequest->mInputStream != NULL) {
5024 halRequest->input_buffer = &captureRequest->mInputBuffer;
Shuzhen Wang83bff122020-11-20 15:51:39 -08005025
5026 halRequest->input_width = captureRequest->mInputBufferSize.width;
5027 halRequest->input_height = captureRequest->mInputBufferSize.height;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005028 totalNumBuffers += 1;
5029 } else {
5030 halRequest->input_buffer = NULL;
5031 }
5032
Emilian Peevf4816702020-04-03 15:44:51 -07005033 outputBuffers->insertAt(camera_stream_buffer_t(), 0,
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005034 captureRequest->mOutputStreams.size());
5035 halRequest->output_buffers = outputBuffers->array();
Shuzhen Wang99080502021-03-07 21:08:20 -08005036 std::set<std::set<String8>> requestedPhysicalCameras;
Yin-Chia Yehb3a80b12018-09-04 12:13:05 -07005037
5038 sp<Camera3Device> parent = mParent.promote();
5039 if (parent == NULL) {
5040 // Should not happen, and nowhere to send errors to, so just log it
5041 CLOGE("RequestThread: Parent is gone");
5042 return INVALID_OPERATION;
5043 }
5044 nsecs_t waitDuration = kBaseGetBufferWait + parent->getExpectedInFlightDuration();
5045
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005046 SurfaceMap uniqueSurfaceIdMap;
Shuzhen Wang4a472662017-02-26 23:29:04 -08005047 for (size_t j = 0; j < captureRequest->mOutputStreams.size(); j++) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005048 sp<Camera3OutputStreamInterface> outputStream =
5049 captureRequest->mOutputStreams.editItemAt(j);
5050 int streamId = outputStream->getId();
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07005051
5052 // Prepare video buffers for high speed recording on the first video request.
5053 if (mPrepareVideoStream && outputStream->isVideoStream()) {
5054 // Only try to prepare video stream on the first video request.
5055 mPrepareVideoStream = false;
5056
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07005057 res = outputStream->startPrepare(Camera3StreamInterface::ALLOCATE_PIPELINE_MAX,
5058 false /*blockRequest*/);
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07005059 while (res == NOT_ENOUGH_DATA) {
5060 res = outputStream->prepareNextBuffer();
5061 }
5062 if (res != OK) {
5063 ALOGW("%s: Preparing video buffers for high speed failed: %s (%d)",
5064 __FUNCTION__, strerror(-res), res);
5065 outputStream->cancelPrepare();
5066 }
5067 }
5068
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005069 std::vector<size_t> uniqueSurfaceIds;
5070 res = outputStream->getUniqueSurfaceIds(
5071 captureRequest->mOutputSurfaces[streamId],
5072 &uniqueSurfaceIds);
5073 // INVALID_OPERATION is normal output for streams not supporting surfaceIds
5074 if (res != OK && res != INVALID_OPERATION) {
5075 ALOGE("%s: failed to query stream %d unique surface IDs",
5076 __FUNCTION__, streamId);
5077 return res;
5078 }
5079 if (res == OK) {
5080 uniqueSurfaceIdMap.insert({streamId, std::move(uniqueSurfaceIds)});
5081 }
5082
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07005083 if (mUseHalBufManager) {
Yin-Chia Yeh110342b2018-11-19 11:47:46 -08005084 if (outputStream->isAbandoned()) {
Yin-Chia Yeha1b56c82019-03-27 15:50:39 -07005085 ALOGV("%s: stream %d is abandoned, skipping request", __FUNCTION__, streamId);
Yin-Chia Yeh110342b2018-11-19 11:47:46 -08005086 return TIMED_OUT;
5087 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07005088 // HAL will request buffer through requestStreamBuffer API
Emilian Peevf4816702020-04-03 15:44:51 -07005089 camera_stream_buffer_t& buffer = outputBuffers->editItemAt(j);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07005090 buffer.stream = outputStream->asHalStream();
5091 buffer.buffer = nullptr;
Emilian Peevf4816702020-04-03 15:44:51 -07005092 buffer.status = CAMERA_BUFFER_STATUS_OK;
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07005093 buffer.acquire_fence = -1;
5094 buffer.release_fence = -1;
Emilian Peevf0348ae2021-01-13 13:39:45 -08005095 // Mark the output stream as unpreparable to block clients from calling
5096 // 'prepare' after this request reaches CameraHal and before the respective
5097 // buffers are requested.
5098 outputStream->markUnpreparable();
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07005099 } else {
5100 res = outputStream->getBuffer(&outputBuffers->editItemAt(j),
5101 waitDuration,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005102 captureRequest->mOutputSurfaces[streamId]);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07005103 if (res != OK) {
5104 // Can't get output buffer from gralloc queue - this could be due to
5105 // abandoned queue or other consumer misbehavior, so not a fatal
5106 // error
Yin-Chia Yeha1b56c82019-03-27 15:50:39 -07005107 ALOGV("RequestThread: Can't get output buffer, skipping request:"
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07005108 " %s (%d)", strerror(-res), res);
5109
5110 return TIMED_OUT;
5111 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005112 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08005113
5114 {
5115 sp<Camera3Device> parent = mParent.promote();
5116 if (parent != nullptr) {
5117 const String8& streamCameraId = outputStream->getPhysicalCameraId();
5118 for (const auto& settings : captureRequest->mSettingsList) {
5119 if ((streamCameraId.isEmpty() &&
5120 parent->getId() == settings.cameraId.c_str()) ||
5121 streamCameraId == settings.cameraId.c_str()) {
5122 outputStream->fireBufferRequestForFrameNumber(
5123 captureRequest->mResultExtras.frameNumber,
5124 settings.metadata);
5125 }
5126 }
5127 }
5128 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07005129
Shuzhen Wang5c22c152017-12-31 17:12:25 -08005130 String8 physicalCameraId = outputStream->getPhysicalCameraId();
Shuzhen Wang99080502021-03-07 21:08:20 -08005131 int32_t streamGroupId = outputStream->getHalStreamGroupId();
5132 if (streamGroupId != -1 && mGroupIdPhysicalCameraMap.count(streamGroupId) == 1) {
5133 requestedPhysicalCameras.insert(mGroupIdPhysicalCameraMap[streamGroupId]);
5134 } else if (!physicalCameraId.isEmpty()) {
5135 requestedPhysicalCameras.insert(std::set<String8>({physicalCameraId}));
Shuzhen Wang5c22c152017-12-31 17:12:25 -08005136 }
5137 halRequest->num_output_buffers++;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005138 }
5139 totalNumBuffers += halRequest->num_output_buffers;
5140
5141 // Log request in the in-flight queue
Shuzhen Wang4a472662017-02-26 23:29:04 -08005142 // If this request list is for constrained high speed recording (not
5143 // preview), and the current request is not the last one in the batch,
5144 // do not send callback to the app.
5145 bool hasCallback = true;
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07005146 if (batchedRequest && i != mNextRequests.size()-1) {
Shuzhen Wang4a472662017-02-26 23:29:04 -08005147 hasCallback = false;
5148 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01005149 bool isStillCapture = false;
Shuzhen Wang26abaf42018-08-28 15:41:20 -07005150 bool isZslCapture = false;
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08005151 const camera_metadata_t* settings = halRequest->settings;
5152 bool shouldUnlockSettings = false;
5153 if (settings == nullptr) {
5154 shouldUnlockSettings = true;
5155 settings = captureRequest->mSettingsList.begin()->metadata.getAndLock();
5156 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01005157 if (!mNextRequests[0].captureRequest->mSettingsList.begin()->metadata.isEmpty()) {
5158 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08005159 find_camera_metadata_ro_entry(settings, ANDROID_CONTROL_CAPTURE_INTENT, &e);
Emilian Peev9dd21f42018-08-03 13:39:29 +01005160 if ((e.count > 0) && (e.data.u8[0] == ANDROID_CONTROL_CAPTURE_INTENT_STILL_CAPTURE)) {
5161 isStillCapture = true;
5162 ATRACE_ASYNC_BEGIN("still capture", mNextRequests[i].halRequest.frame_number);
5163 }
Shuzhen Wang26abaf42018-08-28 15:41:20 -07005164
Emilian Peevaf8416e2021-02-04 17:52:43 -08005165 e = camera_metadata_ro_entry_t();
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08005166 find_camera_metadata_ro_entry(settings, ANDROID_CONTROL_ENABLE_ZSL, &e);
Shuzhen Wang26abaf42018-08-28 15:41:20 -07005167 if ((e.count > 0) && (e.data.u8[0] == ANDROID_CONTROL_ENABLE_ZSL_TRUE)) {
5168 isZslCapture = true;
5169 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01005170 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005171 res = parent->registerInFlight(halRequest->frame_number,
5172 totalNumBuffers, captureRequest->mResultExtras,
5173 /*hasInput*/halRequest->input_buffer != NULL,
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07005174 hasCallback,
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08005175 calculateMaxExpectedDuration(settings),
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005176 requestedPhysicalCameras, isStillCapture, isZslCapture,
5177 captureRequest->mRotateAndCropAuto, mPrevCameraIdsWithZoom,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005178 (mUseHalBufManager) ? uniqueSurfaceIdMap :
Shuzhen Wang316781a2020-08-18 18:11:01 -07005179 SurfaceMap{}, captureRequest->mRequestTimeNs);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005180 ALOGVV("%s: registered in flight requestId = %" PRId32 ", frameNumber = %" PRId64
5181 ", burstId = %" PRId32 ".",
5182 __FUNCTION__,
5183 captureRequest->mResultExtras.requestId, captureRequest->mResultExtras.frameNumber,
5184 captureRequest->mResultExtras.burstId);
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08005185
5186 if (shouldUnlockSettings) {
5187 captureRequest->mSettingsList.begin()->metadata.unlock(settings);
5188 }
5189
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005190 if (res != OK) {
5191 SET_ERR("RequestThread: Unable to register new in-flight request:"
5192 " %s (%d)", strerror(-res), res);
5193 return INVALID_OPERATION;
5194 }
5195 }
5196
5197 return OK;
5198}
5199
Igor Murashkin1e479c02013-09-06 16:55:14 -07005200CameraMetadata Camera3Device::RequestThread::getLatestRequest() const {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005201 ATRACE_CALL();
Igor Murashkin1e479c02013-09-06 16:55:14 -07005202 Mutex::Autolock al(mLatestRequestMutex);
5203
5204 ALOGV("RequestThread::%s", __FUNCTION__);
5205
5206 return mLatestRequest;
5207}
5208
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005209bool Camera3Device::RequestThread::isStreamPending(
5210 sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005211 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005212 Mutex::Autolock l(mRequestLock);
5213
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005214 for (const auto& nextRequest : mNextRequests) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005215 if (!nextRequest.submitted) {
5216 for (const auto& s : nextRequest.captureRequest->mOutputStreams) {
5217 if (stream == s) return true;
5218 }
5219 if (stream == nextRequest.captureRequest->mInputStream) return true;
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07005220 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07005221 }
5222
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005223 for (const auto& request : mRequestQueue) {
5224 for (const auto& s : request->mOutputStreams) {
5225 if (stream == s) return true;
5226 }
5227 if (stream == request->mInputStream) return true;
5228 }
5229
5230 for (const auto& request : mRepeatingRequests) {
5231 for (const auto& s : request->mOutputStreams) {
5232 if (stream == s) return true;
5233 }
5234 if (stream == request->mInputStream) return true;
5235 }
5236
5237 return false;
5238}
Jianing Weicb0652e2014-03-12 18:29:36 -07005239
Emilian Peev40ead602017-09-26 15:46:36 +01005240bool Camera3Device::RequestThread::isOutputSurfacePending(int streamId, size_t surfaceId) {
5241 ATRACE_CALL();
5242 Mutex::Autolock l(mRequestLock);
5243
5244 for (const auto& nextRequest : mNextRequests) {
5245 for (const auto& s : nextRequest.captureRequest->mOutputSurfaces) {
5246 if (s.first == streamId) {
5247 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
5248 if (it != s.second.end()) {
5249 return true;
5250 }
5251 }
5252 }
5253 }
5254
5255 for (const auto& request : mRequestQueue) {
5256 for (const auto& s : request->mOutputSurfaces) {
5257 if (s.first == streamId) {
5258 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
5259 if (it != s.second.end()) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005260 return true;
Emilian Peev40ead602017-09-26 15:46:36 +01005261 }
5262 }
5263 }
5264 }
5265
5266 for (const auto& request : mRepeatingRequests) {
5267 for (const auto& s : request->mOutputSurfaces) {
5268 if (s.first == streamId) {
5269 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
5270 if (it != s.second.end()) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005271 return true;
Emilian Peev40ead602017-09-26 15:46:36 +01005272 }
5273 }
5274 }
5275 }
5276
5277 return false;
5278}
5279
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07005280void Camera3Device::RequestThread::signalPipelineDrain(const std::vector<int>& streamIds) {
5281 if (!mUseHalBufManager) {
5282 ALOGE("%s called for camera device not supporting HAL buffer management", __FUNCTION__);
5283 return;
5284 }
5285
5286 Mutex::Autolock pl(mPauseLock);
5287 if (mPaused) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005288 mInterface->signalPipelineDrain(streamIds);
5289 return;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07005290 }
5291 // If request thread is still busy, wait until paused then notify HAL
5292 mNotifyPipelineDrain = true;
5293 mStreamIdsToBeDrained = streamIds;
5294}
5295
Yin-Chia Yehe52b8fa2020-07-28 00:17:58 -07005296void Camera3Device::RequestThread::resetPipelineDrain() {
5297 Mutex::Autolock pl(mPauseLock);
5298 mNotifyPipelineDrain = false;
5299 mStreamIdsToBeDrained.clear();
5300}
5301
Emilian Peevc0fe54c2020-03-11 14:05:07 -07005302void Camera3Device::RequestThread::clearPreviousRequest() {
5303 Mutex::Autolock l(mRequestLock);
5304 mPrevRequest.clear();
5305}
5306
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005307status_t Camera3Device::RequestThread::switchToOffline(
5308 const std::vector<int32_t>& streamsToKeep,
5309 /*out*/hardware::camera::device::V3_6::CameraOfflineSessionInfo* offlineSessionInfo,
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005310 /*out*/sp<hardware::camera::device::V3_6::ICameraOfflineSession>* offlineSession,
5311 /*out*/camera3::BufferRecords* bufferRecords) {
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005312 Mutex::Autolock l(mRequestLock);
5313 clearRepeatingRequestsLocked(/*lastFrameNumber*/nullptr);
5314
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005315 // Wait until request thread is fully stopped
5316 // TBD: check if request thread is being paused by other APIs (shouldn't be)
5317
5318 // We could also check for mRepeatingRequests.empty(), but the API interface
5319 // is serialized by Camera3Device::mInterfaceLock so no one should be able to submit any
5320 // new requests during the call; hence skip that check.
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005321 bool queueEmpty = mNextRequests.empty() && mRequestQueue.empty();
5322 while (!queueEmpty) {
5323 status_t res = mRequestSubmittedSignal.waitRelative(mRequestLock, kRequestSubmitTimeout);
5324 if (res == TIMED_OUT) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005325 ALOGE("%s: request thread failed to submit one request within timeout!", __FUNCTION__);
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005326 return res;
5327 } else if (res != OK) {
5328 ALOGE("%s: request thread failed to submit a request: %s (%d)!",
5329 __FUNCTION__, strerror(-res), res);
5330 return res;
5331 }
5332 queueEmpty = mNextRequests.empty() && mRequestQueue.empty();
5333 }
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005334
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005335 return mInterface->switchToOffline(
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005336 streamsToKeep, offlineSessionInfo, offlineSession, bufferRecords);
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005337}
5338
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005339status_t Camera3Device::RequestThread::setRotateAndCropAutoBehavior(
5340 camera_metadata_enum_android_scaler_rotate_and_crop_t rotateAndCropValue) {
5341 ATRACE_CALL();
5342 Mutex::Autolock l(mTriggerMutex);
5343 if (rotateAndCropValue == ANDROID_SCALER_ROTATE_AND_CROP_AUTO) {
5344 return BAD_VALUE;
5345 }
5346 mRotateAndCropOverride = rotateAndCropValue;
5347 return OK;
5348}
5349
Emilian Peeve23f1d92021-09-20 14:56:01 -07005350status_t Camera3Device::RequestThread::setComposerSurface(bool composerSurfacePresent) {
5351 ATRACE_CALL();
5352 Mutex::Autolock l(mTriggerMutex);
5353 mComposerOutput = composerSurfacePresent;
5354 return OK;
5355}
5356
Eino-Ville Talvala11afe4f2021-05-27 14:45:31 -07005357status_t Camera3Device::RequestThread::setCameraMute(int32_t muteMode) {
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005358 ATRACE_CALL();
5359 Mutex::Autolock l(mTriggerMutex);
Eino-Ville Talvala11afe4f2021-05-27 14:45:31 -07005360 if (muteMode != mCameraMute) {
5361 mCameraMute = muteMode;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005362 mCameraMuteChanged = true;
5363 }
5364 return OK;
5365}
5366
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07005367nsecs_t Camera3Device::getExpectedInFlightDuration() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005368 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005369 std::lock_guard<std::mutex> l(mInFlightLock);
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07005370 return mExpectedInflightDuration > kMinInflightDuration ?
5371 mExpectedInflightDuration : kMinInflightDuration;
5372}
5373
Emilian Peevaebbe412018-01-15 13:53:24 +00005374void Camera3Device::RequestThread::cleanupPhysicalSettings(sp<CaptureRequest> request,
Emilian Peevf4816702020-04-03 15:44:51 -07005375 camera_capture_request_t *halRequest) {
Emilian Peevaebbe412018-01-15 13:53:24 +00005376 if ((request == nullptr) || (halRequest == nullptr)) {
5377 ALOGE("%s: Invalid request!", __FUNCTION__);
5378 return;
5379 }
5380
5381 if (halRequest->num_physcam_settings > 0) {
5382 if (halRequest->physcam_id != nullptr) {
5383 delete [] halRequest->physcam_id;
5384 halRequest->physcam_id = nullptr;
5385 }
5386 if (halRequest->physcam_settings != nullptr) {
5387 auto it = ++(request->mSettingsList.begin());
5388 size_t i = 0;
5389 for (; it != request->mSettingsList.end(); it++, i++) {
5390 it->metadata.unlock(halRequest->physcam_settings[i]);
5391 }
5392 delete [] halRequest->physcam_settings;
5393 halRequest->physcam_settings = nullptr;
5394 }
5395 }
5396}
5397
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005398void Camera3Device::RequestThread::cleanUpFailedRequests(bool sendRequestError) {
5399 if (mNextRequests.empty()) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005400 return;
5401 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005402
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005403 for (auto& nextRequest : mNextRequests) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005404 // Skip the ones that have been submitted successfully.
5405 if (nextRequest.submitted) {
5406 continue;
5407 }
5408
5409 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
Emilian Peevf4816702020-04-03 15:44:51 -07005410 camera_capture_request_t* halRequest = &nextRequest.halRequest;
5411 Vector<camera_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005412
5413 if (halRequest->settings != NULL) {
Emilian Peevaebbe412018-01-15 13:53:24 +00005414 captureRequest->mSettingsList.begin()->metadata.unlock(halRequest->settings);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005415 }
5416
Emilian Peevaebbe412018-01-15 13:53:24 +00005417 cleanupPhysicalSettings(captureRequest, halRequest);
5418
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005419 if (captureRequest->mInputStream != NULL) {
Emilian Peevf4816702020-04-03 15:44:51 -07005420 captureRequest->mInputBuffer.status = CAMERA_BUFFER_STATUS_ERROR;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005421 captureRequest->mInputStream->returnInputBuffer(captureRequest->mInputBuffer);
5422 }
5423
Yin-Chia Yeh21cb47b2019-01-18 15:08:17 -08005424 // No output buffer can be returned when using HAL buffer manager
5425 if (!mUseHalBufManager) {
5426 for (size_t i = 0; i < halRequest->num_output_buffers; i++) {
5427 //Buffers that failed processing could still have
5428 //valid acquire fence.
5429 int acquireFence = (*outputBuffers)[i].acquire_fence;
5430 if (0 <= acquireFence) {
5431 close(acquireFence);
5432 outputBuffers->editItemAt(i).acquire_fence = -1;
5433 }
Emilian Peevf4816702020-04-03 15:44:51 -07005434 outputBuffers->editItemAt(i).status = CAMERA_BUFFER_STATUS_ERROR;
Yin-Chia Yeh21cb47b2019-01-18 15:08:17 -08005435 captureRequest->mOutputStreams.editItemAt(i)->returnBuffer((*outputBuffers)[i], 0,
5436 /*timestampIncreasing*/true, std::vector<size_t> (),
5437 captureRequest->mResultExtras.frameNumber);
Emilian Peevc58cf4c2017-05-11 17:23:41 +01005438 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005439 }
5440
5441 if (sendRequestError) {
5442 Mutex::Autolock l(mRequestLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005443 sp<NotificationListener> listener = mListener.promote();
5444 if (listener != NULL) {
5445 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08005446 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005447 captureRequest->mResultExtras);
5448 }
5449 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07005450
5451 // Remove yet-to-be submitted inflight request from inflightMap
5452 {
5453 sp<Camera3Device> parent = mParent.promote();
5454 if (parent != NULL) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005455 std::lock_guard<std::mutex> l(parent->mInFlightLock);
Shuzhen Wangcadb3302016-11-04 14:17:56 -07005456 ssize_t idx = parent->mInFlightMap.indexOfKey(captureRequest->mResultExtras.frameNumber);
5457 if (idx >= 0) {
5458 ALOGV("%s: Remove inflight request from queue: frameNumber %" PRId64,
5459 __FUNCTION__, captureRequest->mResultExtras.frameNumber);
5460 parent->removeInFlightMapEntryLocked(idx);
5461 }
5462 }
5463 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005464 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07005465
5466 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005467 mNextRequests.clear();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005468}
5469
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005470void Camera3Device::RequestThread::waitForNextRequestBatch() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005471 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005472 // Optimized a bit for the simple steady-state case (single repeating
5473 // request), to avoid putting that request in the queue temporarily.
5474 Mutex::Autolock l(mRequestLock);
5475
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005476 assert(mNextRequests.empty());
5477
5478 NextRequest nextRequest;
5479 nextRequest.captureRequest = waitForNextRequestLocked();
5480 if (nextRequest.captureRequest == nullptr) {
5481 return;
5482 }
5483
Emilian Peevf4816702020-04-03 15:44:51 -07005484 nextRequest.halRequest = camera_capture_request_t();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005485 nextRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005486 mNextRequests.add(nextRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005487
5488 // Wait for additional requests
5489 const size_t batchSize = nextRequest.captureRequest->mBatchSize;
5490
5491 for (size_t i = 1; i < batchSize; i++) {
5492 NextRequest additionalRequest;
5493 additionalRequest.captureRequest = waitForNextRequestLocked();
5494 if (additionalRequest.captureRequest == nullptr) {
5495 break;
5496 }
5497
Emilian Peevf4816702020-04-03 15:44:51 -07005498 additionalRequest.halRequest = camera_capture_request_t();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005499 additionalRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005500 mNextRequests.add(additionalRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005501 }
5502
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005503 if (mNextRequests.size() < batchSize) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08005504 ALOGE("RequestThread: only get %zu out of %zu requests. Skipping requests.",
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005505 mNextRequests.size(), batchSize);
5506 cleanUpFailedRequests(/*sendRequestError*/true);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005507 }
5508
5509 return;
5510}
5511
5512sp<Camera3Device::CaptureRequest>
5513 Camera3Device::RequestThread::waitForNextRequestLocked() {
5514 status_t res;
5515 sp<CaptureRequest> nextRequest;
5516
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005517 while (mRequestQueue.empty()) {
5518 if (!mRepeatingRequests.empty()) {
5519 // Always atomically enqueue all requests in a repeating request
5520 // list. Guarantees a complete in-sequence set of captures to
5521 // application.
5522 const RequestList &requests = mRepeatingRequests;
Shuzhen Wang316781a2020-08-18 18:11:01 -07005523 if (mFirstRepeating) {
5524 mFirstRepeating = false;
5525 } else {
5526 for (auto& request : requests) {
5527 // For repeating requests, override timestamp request using
5528 // the time a request is inserted into the request queue,
5529 // because the original repeating request will have an old
5530 // fixed timestamp.
5531 request->mRequestTimeNs = systemTime();
5532 }
5533 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005534 RequestList::const_iterator firstRequest =
5535 requests.begin();
5536 nextRequest = *firstRequest;
5537 mRequestQueue.insert(mRequestQueue.end(),
5538 ++firstRequest,
5539 requests.end());
5540 // No need to wait any longer
Jianing Weicb0652e2014-03-12 18:29:36 -07005541
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005542 mRepeatingLastFrameNumber = mFrameNumber + requests.size() - 1;
Jianing Weicb0652e2014-03-12 18:29:36 -07005543
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005544 break;
5545 }
5546
5547 res = mRequestSignal.waitRelative(mRequestLock, kRequestTimeout);
5548
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005549 if ((mRequestQueue.empty() && mRepeatingRequests.empty()) ||
5550 exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005551 Mutex::Autolock pl(mPauseLock);
5552 if (mPaused == false) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005553 ALOGV("%s: RequestThread: Going idle", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005554 mPaused = true;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07005555 if (mNotifyPipelineDrain) {
5556 mInterface->signalPipelineDrain(mStreamIdsToBeDrained);
5557 mNotifyPipelineDrain = false;
5558 mStreamIdsToBeDrained.clear();
5559 }
Yin-Chia Yehc300a072019-02-13 14:56:57 -08005560 // Let the tracker know
5561 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5562 if (statusTracker != 0) {
5563 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
5564 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005565 sp<Camera3Device> parent = mParent.promote();
5566 if (parent != nullptr) {
5567 parent->mRequestBufferSM.onRequestThreadPaused();
5568 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005569 }
5570 // Stop waiting for now and let thread management happen
5571 return NULL;
5572 }
5573 }
5574
5575 if (nextRequest == NULL) {
5576 // Don't have a repeating request already in hand, so queue
5577 // must have an entry now.
5578 RequestList::iterator firstRequest =
5579 mRequestQueue.begin();
5580 nextRequest = *firstRequest;
5581 mRequestQueue.erase(firstRequest);
Shuzhen Wang9d066012016-09-30 11:30:20 -07005582 if (mRequestQueue.empty() && !nextRequest->mRepeating) {
5583 sp<NotificationListener> listener = mListener.promote();
5584 if (listener != NULL) {
5585 listener->notifyRequestQueueEmpty();
5586 }
5587 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005588 }
5589
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005590 // In case we've been unpaused by setPaused clearing mDoPause, need to
5591 // update internal pause state (capture/setRepeatingRequest unpause
5592 // directly).
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005593 Mutex::Autolock pl(mPauseLock);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005594 if (mPaused) {
5595 ALOGV("%s: RequestThread: Unpaused", __FUNCTION__);
5596 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5597 if (statusTracker != 0) {
5598 statusTracker->markComponentActive(mStatusId);
5599 }
5600 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005601 mPaused = false;
5602
5603 // Check if we've reconfigured since last time, and reset the preview
5604 // request if so. Can't use 'NULL request == repeat' across configure calls.
5605 if (mReconfigured) {
5606 mPrevRequest.clear();
5607 mReconfigured = false;
5608 }
5609
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005610 if (nextRequest != NULL) {
5611 nextRequest->mResultExtras.frameNumber = mFrameNumber++;
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07005612 nextRequest->mResultExtras.afTriggerId = mCurrentAfTriggerId;
5613 nextRequest->mResultExtras.precaptureTriggerId = mCurrentPreCaptureTriggerId;
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07005614
5615 // Since RequestThread::clear() removes buffers from the input stream,
5616 // get the right buffer here before unlocking mRequestLock
5617 if (nextRequest->mInputStream != NULL) {
Shuzhen Wang83bff122020-11-20 15:51:39 -08005618 res = nextRequest->mInputStream->getInputBuffer(&nextRequest->mInputBuffer,
5619 &nextRequest->mInputBufferSize);
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07005620 if (res != OK) {
5621 // Can't get input buffer from gralloc queue - this could be due to
5622 // disconnected queue or other producer misbehavior, so not a fatal
5623 // error
5624 ALOGE("%s: Can't get input buffer, skipping request:"
5625 " %s (%d)", __FUNCTION__, strerror(-res), res);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005626
5627 sp<NotificationListener> listener = mListener.promote();
5628 if (listener != NULL) {
5629 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08005630 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07005631 nextRequest->mResultExtras);
5632 }
5633 return NULL;
5634 }
5635 }
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005636 }
Chien-Yu Chend196d612015-06-22 19:49:01 -07005637
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005638 return nextRequest;
5639}
5640
5641bool Camera3Device::RequestThread::waitIfPaused() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005642 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005643 status_t res;
5644 Mutex::Autolock l(mPauseLock);
5645 while (mDoPause) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005646 if (mPaused == false) {
5647 mPaused = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005648 ALOGV("%s: RequestThread: Paused", __FUNCTION__);
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07005649 if (mNotifyPipelineDrain) {
5650 mInterface->signalPipelineDrain(mStreamIdsToBeDrained);
5651 mNotifyPipelineDrain = false;
5652 mStreamIdsToBeDrained.clear();
5653 }
Yin-Chia Yehc300a072019-02-13 14:56:57 -08005654 // Let the tracker know
5655 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5656 if (statusTracker != 0) {
5657 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
5658 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005659 sp<Camera3Device> parent = mParent.promote();
5660 if (parent != nullptr) {
5661 parent->mRequestBufferSM.onRequestThreadPaused();
5662 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005663 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005664
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005665 res = mDoPauseSignal.waitRelative(mPauseLock, kRequestTimeout);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005666 if (res == TIMED_OUT || exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005667 return true;
5668 }
5669 }
5670 // We don't set mPaused to false here, because waitForNextRequest needs
5671 // to further manage the paused state in case of starvation.
5672 return false;
5673}
5674
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005675void Camera3Device::RequestThread::unpauseForNewRequests() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005676 ATRACE_CALL();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005677 // With work to do, mark thread as unpaused.
5678 // If paused by request (setPaused), don't resume, to avoid
5679 // extra signaling/waiting overhead to waitUntilPaused
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005680 mRequestSignal.signal();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005681 Mutex::Autolock p(mPauseLock);
5682 if (!mDoPause) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005683 ALOGV("%s: RequestThread: Going active", __FUNCTION__);
5684 if (mPaused) {
5685 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5686 if (statusTracker != 0) {
5687 statusTracker->markComponentActive(mStatusId);
5688 }
5689 }
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005690 mPaused = false;
5691 }
5692}
5693
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07005694void Camera3Device::RequestThread::setErrorState(const char *fmt, ...) {
5695 sp<Camera3Device> parent = mParent.promote();
5696 if (parent != NULL) {
5697 va_list args;
5698 va_start(args, fmt);
5699
5700 parent->setErrorStateV(fmt, args);
5701
5702 va_end(args);
5703 }
5704}
5705
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005706status_t Camera3Device::RequestThread::insertTriggers(
5707 const sp<CaptureRequest> &request) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005708 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005709 Mutex::Autolock al(mTriggerMutex);
5710
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07005711 sp<Camera3Device> parent = mParent.promote();
5712 if (parent == NULL) {
5713 CLOGE("RequestThread: Parent is gone");
5714 return DEAD_OBJECT;
5715 }
5716
Emilian Peevaebbe412018-01-15 13:53:24 +00005717 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005718 size_t count = mTriggerMap.size();
5719
5720 for (size_t i = 0; i < count; ++i) {
5721 RequestTrigger trigger = mTriggerMap.valueAt(i);
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005722 uint32_t tag = trigger.metadataTag;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07005723
5724 if (tag == ANDROID_CONTROL_AF_TRIGGER_ID || tag == ANDROID_CONTROL_AE_PRECAPTURE_ID) {
5725 bool isAeTrigger = (trigger.metadataTag == ANDROID_CONTROL_AE_PRECAPTURE_ID);
5726 uint32_t triggerId = static_cast<uint32_t>(trigger.entryValue);
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07005727 if (isAeTrigger) {
5728 request->mResultExtras.precaptureTriggerId = triggerId;
5729 mCurrentPreCaptureTriggerId = triggerId;
5730 } else {
5731 request->mResultExtras.afTriggerId = triggerId;
5732 mCurrentAfTriggerId = triggerId;
5733 }
Emilian Peev7e25e5e2017-04-07 15:48:49 +01005734 continue;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07005735 }
5736
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005737 camera_metadata_entry entry = metadata.find(tag);
5738
5739 if (entry.count > 0) {
5740 /**
5741 * Already has an entry for this trigger in the request.
5742 * Rewrite it with our requested trigger value.
5743 */
5744 RequestTrigger oldTrigger = trigger;
5745
5746 oldTrigger.entryValue = entry.data.u8[0];
5747
5748 mTriggerReplacedMap.add(tag, oldTrigger);
5749 } else {
5750 /**
5751 * More typical, no trigger entry, so we just add it
5752 */
5753 mTriggerRemovedMap.add(tag, trigger);
5754 }
5755
5756 status_t res;
5757
5758 switch (trigger.getTagType()) {
5759 case TYPE_BYTE: {
5760 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
5761 res = metadata.update(tag,
5762 &entryValue,
5763 /*count*/1);
5764 break;
5765 }
5766 case TYPE_INT32:
5767 res = metadata.update(tag,
5768 &trigger.entryValue,
5769 /*count*/1);
5770 break;
5771 default:
5772 ALOGE("%s: Type not supported: 0x%x",
5773 __FUNCTION__,
5774 trigger.getTagType());
5775 return INVALID_OPERATION;
5776 }
5777
5778 if (res != OK) {
5779 ALOGE("%s: Failed to update request metadata with trigger tag %s"
5780 ", value %d", __FUNCTION__, trigger.getTagName(),
5781 trigger.entryValue);
5782 return res;
5783 }
5784
5785 ALOGV("%s: Mixed in trigger %s, value %d", __FUNCTION__,
5786 trigger.getTagName(),
5787 trigger.entryValue);
5788 }
5789
5790 mTriggerMap.clear();
5791
5792 return count;
5793}
5794
5795status_t Camera3Device::RequestThread::removeTriggers(
5796 const sp<CaptureRequest> &request) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005797 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005798 Mutex::Autolock al(mTriggerMutex);
5799
Emilian Peevaebbe412018-01-15 13:53:24 +00005800 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005801
5802 /**
5803 * Replace all old entries with their old values.
5804 */
5805 for (size_t i = 0; i < mTriggerReplacedMap.size(); ++i) {
5806 RequestTrigger trigger = mTriggerReplacedMap.valueAt(i);
5807
5808 status_t res;
5809
5810 uint32_t tag = trigger.metadataTag;
5811 switch (trigger.getTagType()) {
5812 case TYPE_BYTE: {
5813 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
5814 res = metadata.update(tag,
5815 &entryValue,
5816 /*count*/1);
5817 break;
5818 }
5819 case TYPE_INT32:
5820 res = metadata.update(tag,
5821 &trigger.entryValue,
5822 /*count*/1);
5823 break;
5824 default:
5825 ALOGE("%s: Type not supported: 0x%x",
5826 __FUNCTION__,
5827 trigger.getTagType());
5828 return INVALID_OPERATION;
5829 }
5830
5831 if (res != OK) {
5832 ALOGE("%s: Failed to restore request metadata with trigger tag %s"
5833 ", trigger value %d", __FUNCTION__,
5834 trigger.getTagName(), trigger.entryValue);
5835 return res;
5836 }
5837 }
5838 mTriggerReplacedMap.clear();
5839
5840 /**
5841 * Remove all new entries.
5842 */
5843 for (size_t i = 0; i < mTriggerRemovedMap.size(); ++i) {
5844 RequestTrigger trigger = mTriggerRemovedMap.valueAt(i);
5845 status_t res = metadata.erase(trigger.metadataTag);
5846
5847 if (res != OK) {
5848 ALOGE("%s: Failed to erase metadata with trigger tag %s"
5849 ", trigger value %d", __FUNCTION__,
5850 trigger.getTagName(), trigger.entryValue);
5851 return res;
5852 }
5853 }
5854 mTriggerRemovedMap.clear();
5855
5856 return OK;
5857}
5858
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04005859status_t Camera3Device::RequestThread::addFakeTriggerIds(
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005860 const sp<CaptureRequest> &request) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08005861 // Trigger ID 0 had special meaning in the HAL2 spec, so avoid it here
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04005862 static const int32_t fakeTriggerId = 1;
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005863 status_t res;
5864
Emilian Peevaebbe412018-01-15 13:53:24 +00005865 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005866
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04005867 // If AF trigger is active, insert a fake AF trigger ID if none already
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005868 // exists
5869 camera_metadata_entry afTrigger = metadata.find(ANDROID_CONTROL_AF_TRIGGER);
5870 camera_metadata_entry afId = metadata.find(ANDROID_CONTROL_AF_TRIGGER_ID);
5871 if (afTrigger.count > 0 &&
5872 afTrigger.data.u8[0] != ANDROID_CONTROL_AF_TRIGGER_IDLE &&
5873 afId.count == 0) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04005874 res = metadata.update(ANDROID_CONTROL_AF_TRIGGER_ID, &fakeTriggerId, 1);
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005875 if (res != OK) return res;
5876 }
5877
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04005878 // If AE precapture trigger is active, insert a fake precapture trigger ID
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005879 // if none already exists
5880 camera_metadata_entry pcTrigger =
5881 metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER);
5882 camera_metadata_entry pcId = metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_ID);
5883 if (pcTrigger.count > 0 &&
5884 pcTrigger.data.u8[0] != ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_IDLE &&
5885 pcId.count == 0) {
5886 res = metadata.update(ANDROID_CONTROL_AE_PRECAPTURE_ID,
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04005887 &fakeTriggerId, 1);
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005888 if (res != OK) return res;
5889 }
5890
5891 return OK;
5892}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005893
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005894bool Camera3Device::RequestThread::overrideAutoRotateAndCrop(
5895 const sp<CaptureRequest> &request) {
5896 ATRACE_CALL();
5897
5898 if (request->mRotateAndCropAuto) {
5899 Mutex::Autolock l(mTriggerMutex);
5900 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
5901
5902 auto rotateAndCropEntry = metadata.find(ANDROID_SCALER_ROTATE_AND_CROP);
5903 if (rotateAndCropEntry.count > 0) {
5904 if (rotateAndCropEntry.data.u8[0] == mRotateAndCropOverride) {
5905 return false;
5906 } else {
5907 rotateAndCropEntry.data.u8[0] = mRotateAndCropOverride;
5908 return true;
5909 }
5910 } else {
5911 uint8_t rotateAndCrop_u8 = mRotateAndCropOverride;
5912 metadata.update(ANDROID_SCALER_ROTATE_AND_CROP,
5913 &rotateAndCrop_u8, 1);
5914 return true;
5915 }
5916 }
5917 return false;
5918}
5919
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005920bool Camera3Device::RequestThread::overrideTestPattern(
5921 const sp<CaptureRequest> &request) {
5922 ATRACE_CALL();
5923
Eino-Ville Talvala1646c3c2021-07-29 13:48:40 -07005924 if (!mSupportCameraMute) return false;
Eino-Ville Talvalac2459842021-07-22 16:36:36 -07005925
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005926 Mutex::Autolock l(mTriggerMutex);
5927
5928 bool changed = false;
5929
5930 int32_t testPatternMode = request->mOriginalTestPatternMode;
5931 int32_t testPatternData[4] = {
5932 request->mOriginalTestPatternData[0],
5933 request->mOriginalTestPatternData[1],
5934 request->mOriginalTestPatternData[2],
5935 request->mOriginalTestPatternData[3]
5936 };
5937
Eino-Ville Talvala11afe4f2021-05-27 14:45:31 -07005938 if (mCameraMute != ANDROID_SENSOR_TEST_PATTERN_MODE_OFF) {
5939 testPatternMode = mCameraMute;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005940 testPatternData[0] = 0;
5941 testPatternData[1] = 0;
5942 testPatternData[2] = 0;
5943 testPatternData[3] = 0;
5944 }
5945
5946 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
5947
5948 auto testPatternEntry = metadata.find(ANDROID_SENSOR_TEST_PATTERN_MODE);
5949 if (testPatternEntry.count > 0) {
5950 if (testPatternEntry.data.i32[0] != testPatternMode) {
5951 testPatternEntry.data.i32[0] = testPatternMode;
5952 changed = true;
5953 }
5954 } else {
5955 metadata.update(ANDROID_SENSOR_TEST_PATTERN_MODE,
5956 &testPatternMode, 1);
5957 changed = true;
5958 }
5959
5960 auto testPatternColor = metadata.find(ANDROID_SENSOR_TEST_PATTERN_DATA);
Eino-Ville Talvalac2459842021-07-22 16:36:36 -07005961 if (testPatternColor.count >= 4) {
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005962 for (size_t i = 0; i < 4; i++) {
Eino-Ville Talvalac2459842021-07-22 16:36:36 -07005963 if (testPatternColor.data.i32[i] != testPatternData[i]) {
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005964 testPatternColor.data.i32[i] = testPatternData[i];
5965 changed = true;
5966 }
5967 }
5968 } else {
5969 metadata.update(ANDROID_SENSOR_TEST_PATTERN_DATA,
Eino-Ville Talvalac2459842021-07-22 16:36:36 -07005970 testPatternData, 4);
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005971 changed = true;
5972 }
5973
5974 return changed;
5975}
5976
Cliff Wuc2ad9c82021-04-21 00:58:58 +08005977status_t Camera3Device::RequestThread::setHalInterface(
5978 sp<HalInterface> newHalInterface) {
5979 if (newHalInterface.get() == nullptr) {
5980 ALOGE("%s: The newHalInterface does not exist!", __FUNCTION__);
5981 return DEAD_OBJECT;
5982 }
5983
5984 mInterface = newHalInterface;
5985
5986 return OK;
5987}
5988
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005989/**
5990 * PreparerThread inner class methods
5991 */
5992
5993Camera3Device::PreparerThread::PreparerThread() :
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07005994 Thread(/*canCallJava*/false), mListener(nullptr),
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005995 mActive(false), mCancelNow(false), mCurrentMaxCount(0), mCurrentPrepareComplete(false) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005996}
5997
5998Camera3Device::PreparerThread::~PreparerThread() {
5999 Thread::requestExitAndWait();
6000 if (mCurrentStream != nullptr) {
6001 mCurrentStream->cancelPrepare();
6002 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
6003 mCurrentStream.clear();
6004 }
6005 clear();
6006}
6007
Ruben Brunkc78ac262015-08-13 17:58:46 -07006008status_t Camera3Device::PreparerThread::prepare(int maxCount, sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07006009 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006010 status_t res;
6011
6012 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006013 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006014
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07006015 res = stream->startPrepare(maxCount, true /*blockRequest*/);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006016 if (res == OK) {
6017 // No preparation needed, fire listener right off
6018 ALOGV("%s: Stream %d already prepared", __FUNCTION__, stream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006019 if (listener != NULL) {
6020 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006021 }
6022 return OK;
6023 } else if (res != NOT_ENOUGH_DATA) {
6024 return res;
6025 }
6026
6027 // Need to prepare, start up thread if necessary
6028 if (!mActive) {
6029 // mRunning will change to false before the thread fully shuts down, so wait to be sure it
6030 // isn't running
6031 Thread::requestExitAndWait();
6032 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
6033 if (res != OK) {
6034 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__, res, strerror(-res));
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006035 if (listener != NULL) {
6036 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006037 }
6038 return res;
6039 }
6040 mCancelNow = false;
6041 mActive = true;
6042 ALOGV("%s: Preparer stream started", __FUNCTION__);
6043 }
6044
6045 // queue up the work
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006046 mPendingStreams.emplace(maxCount, stream);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006047 ALOGV("%s: Stream %d queued for preparing", __FUNCTION__, stream->getId());
6048
6049 return OK;
6050}
6051
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006052void Camera3Device::PreparerThread::pause() {
6053 ATRACE_CALL();
6054
6055 Mutex::Autolock l(mLock);
6056
6057 std::unordered_map<int, sp<camera3::Camera3StreamInterface> > pendingStreams;
6058 pendingStreams.insert(mPendingStreams.begin(), mPendingStreams.end());
6059 sp<camera3::Camera3StreamInterface> currentStream = mCurrentStream;
6060 int currentMaxCount = mCurrentMaxCount;
6061 mPendingStreams.clear();
6062 mCancelNow = true;
6063 while (mActive) {
6064 auto res = mThreadActiveSignal.waitRelative(mLock, kActiveTimeout);
6065 if (res == TIMED_OUT) {
6066 ALOGE("%s: Timed out waiting on prepare thread!", __FUNCTION__);
6067 return;
6068 } else if (res != OK) {
6069 ALOGE("%s: Encountered an error: %d waiting on prepare thread!", __FUNCTION__, res);
6070 return;
6071 }
6072 }
6073
6074 //Check whether the prepare thread was able to complete the current
6075 //stream. In case work is still pending emplace it along with the rest
6076 //of the streams in the pending list.
6077 if (currentStream != nullptr) {
6078 if (!mCurrentPrepareComplete) {
6079 pendingStreams.emplace(currentMaxCount, currentStream);
6080 }
6081 }
6082
6083 mPendingStreams.insert(pendingStreams.begin(), pendingStreams.end());
6084 for (const auto& it : mPendingStreams) {
6085 it.second->cancelPrepare();
6086 }
6087}
6088
6089status_t Camera3Device::PreparerThread::resume() {
6090 ATRACE_CALL();
6091 status_t res;
6092
6093 Mutex::Autolock l(mLock);
6094 sp<NotificationListener> listener = mListener.promote();
6095
6096 if (mActive) {
6097 ALOGE("%s: Trying to resume an already active prepare thread!", __FUNCTION__);
6098 return NO_INIT;
6099 }
6100
6101 auto it = mPendingStreams.begin();
6102 for (; it != mPendingStreams.end();) {
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07006103 res = it->second->startPrepare(it->first, true /*blockRequest*/);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006104 if (res == OK) {
6105 if (listener != NULL) {
6106 listener->notifyPrepared(it->second->getId());
6107 }
6108 it = mPendingStreams.erase(it);
6109 } else if (res != NOT_ENOUGH_DATA) {
6110 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__,
6111 res, strerror(-res));
6112 it = mPendingStreams.erase(it);
6113 } else {
6114 it++;
6115 }
6116 }
6117
6118 if (mPendingStreams.empty()) {
6119 return OK;
6120 }
6121
6122 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
6123 if (res != OK) {
6124 ALOGE("%s: Unable to start preparer stream: %d (%s)",
6125 __FUNCTION__, res, strerror(-res));
6126 return res;
6127 }
6128 mCancelNow = false;
6129 mActive = true;
6130 ALOGV("%s: Preparer stream started", __FUNCTION__);
6131
6132 return OK;
6133}
6134
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006135status_t Camera3Device::PreparerThread::clear() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07006136 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006137 Mutex::Autolock l(mLock);
6138
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006139 for (const auto& it : mPendingStreams) {
6140 it.second->cancelPrepare();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006141 }
6142 mPendingStreams.clear();
6143 mCancelNow = true;
6144
6145 return OK;
6146}
6147
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006148void Camera3Device::PreparerThread::setNotificationListener(wp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07006149 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006150 Mutex::Autolock l(mLock);
6151 mListener = listener;
6152}
6153
6154bool Camera3Device::PreparerThread::threadLoop() {
6155 status_t res;
6156 {
6157 Mutex::Autolock l(mLock);
6158 if (mCurrentStream == nullptr) {
6159 // End thread if done with work
6160 if (mPendingStreams.empty()) {
6161 ALOGV("%s: Preparer stream out of work", __FUNCTION__);
6162 // threadLoop _must not_ re-acquire mLock after it sets mActive to false; would
6163 // cause deadlock with prepare()'s requestExitAndWait triggered by !mActive.
6164 mActive = false;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006165 mThreadActiveSignal.signal();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006166 return false;
6167 }
6168
6169 // Get next stream to prepare
6170 auto it = mPendingStreams.begin();
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006171 mCurrentStream = it->second;
6172 mCurrentMaxCount = it->first;
6173 mCurrentPrepareComplete = false;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006174 mPendingStreams.erase(it);
6175 ATRACE_ASYNC_BEGIN("stream prepare", mCurrentStream->getId());
6176 ALOGV("%s: Preparing stream %d", __FUNCTION__, mCurrentStream->getId());
6177 } else if (mCancelNow) {
6178 mCurrentStream->cancelPrepare();
6179 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
6180 ALOGV("%s: Cancelling stream %d prepare", __FUNCTION__, mCurrentStream->getId());
6181 mCurrentStream.clear();
6182 mCancelNow = false;
6183 return true;
6184 }
6185 }
6186
6187 res = mCurrentStream->prepareNextBuffer();
6188 if (res == NOT_ENOUGH_DATA) return true;
6189 if (res != OK) {
6190 // Something bad happened; try to recover by cancelling prepare and
6191 // signalling listener anyway
6192 ALOGE("%s: Stream %d returned error %d (%s) during prepare", __FUNCTION__,
6193 mCurrentStream->getId(), res, strerror(-res));
6194 mCurrentStream->cancelPrepare();
6195 }
6196
6197 // This stream has finished, notify listener
6198 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006199 sp<NotificationListener> listener = mListener.promote();
6200 if (listener != NULL) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006201 ALOGV("%s: Stream %d prepare done, signaling listener", __FUNCTION__,
6202 mCurrentStream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006203 listener->notifyPrepared(mCurrentStream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006204 }
6205
6206 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
6207 mCurrentStream.clear();
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006208 mCurrentPrepareComplete = true;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006209
6210 return true;
6211}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07006212
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006213status_t Camera3Device::RequestBufferStateMachine::initialize(
6214 sp<camera3::StatusTracker> statusTracker) {
6215 if (statusTracker == nullptr) {
6216 ALOGE("%s: statusTracker is null", __FUNCTION__);
6217 return BAD_VALUE;
6218 }
6219
6220 std::lock_guard<std::mutex> lock(mLock);
6221 mStatusTracker = statusTracker;
Yin-Chia Yeh87b3ec02019-06-03 10:44:39 -07006222 mRequestBufferStatusId = statusTracker->addComponent("BufferRequestSM");
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006223 return OK;
6224}
6225
6226bool Camera3Device::RequestBufferStateMachine::startRequestBuffer() {
6227 std::lock_guard<std::mutex> lock(mLock);
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08006228 if (mStatus == RB_STATUS_READY || mStatus == RB_STATUS_PENDING_STOP) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006229 mRequestBufferOngoing = true;
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08006230 notifyTrackerLocked(/*active*/true);
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006231 return true;
6232 }
6233 return false;
6234}
6235
6236void Camera3Device::RequestBufferStateMachine::endRequestBuffer() {
6237 std::lock_guard<std::mutex> lock(mLock);
6238 if (!mRequestBufferOngoing) {
6239 ALOGE("%s called without a successful startRequestBuffer call first!", __FUNCTION__);
6240 return;
6241 }
6242 mRequestBufferOngoing = false;
6243 if (mStatus == RB_STATUS_PENDING_STOP) {
6244 checkSwitchToStopLocked();
6245 }
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08006246 notifyTrackerLocked(/*active*/false);
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006247}
6248
6249void Camera3Device::RequestBufferStateMachine::onStreamsConfigured() {
6250 std::lock_guard<std::mutex> lock(mLock);
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006251 mSwitchedToOffline = false;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006252 mStatus = RB_STATUS_READY;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006253 return;
6254}
6255
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08006256void Camera3Device::RequestBufferStateMachine::onSubmittingRequest() {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006257 std::lock_guard<std::mutex> lock(mLock);
6258 mRequestThreadPaused = false;
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08006259 // inflight map register actually happens in prepareHalRequest now, but it is close enough
6260 // approximation.
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006261 mInflightMapEmpty = false;
6262 if (mStatus == RB_STATUS_STOPPED) {
6263 mStatus = RB_STATUS_READY;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006264 }
6265 return;
6266}
6267
6268void Camera3Device::RequestBufferStateMachine::onRequestThreadPaused() {
6269 std::lock_guard<std::mutex> lock(mLock);
6270 mRequestThreadPaused = true;
6271 if (mStatus == RB_STATUS_PENDING_STOP) {
6272 checkSwitchToStopLocked();
6273 }
6274 return;
6275}
6276
6277void Camera3Device::RequestBufferStateMachine::onInflightMapEmpty() {
6278 std::lock_guard<std::mutex> lock(mLock);
6279 mInflightMapEmpty = true;
6280 if (mStatus == RB_STATUS_PENDING_STOP) {
6281 checkSwitchToStopLocked();
6282 }
6283 return;
6284}
6285
6286void Camera3Device::RequestBufferStateMachine::onWaitUntilIdle() {
6287 std::lock_guard<std::mutex> lock(mLock);
6288 if (!checkSwitchToStopLocked()) {
6289 mStatus = RB_STATUS_PENDING_STOP;
6290 }
6291 return;
6292}
6293
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006294bool Camera3Device::RequestBufferStateMachine::onSwitchToOfflineSuccess() {
6295 std::lock_guard<std::mutex> lock(mLock);
6296 if (mRequestBufferOngoing) {
6297 ALOGE("%s: HAL must not be requesting buffer after HAL returns switchToOffline!",
6298 __FUNCTION__);
6299 return false;
6300 }
6301 mSwitchedToOffline = true;
6302 mInflightMapEmpty = true;
6303 mRequestThreadPaused = true;
6304 mStatus = RB_STATUS_STOPPED;
6305 return true;
6306}
6307
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006308void Camera3Device::RequestBufferStateMachine::notifyTrackerLocked(bool active) {
6309 sp<StatusTracker> statusTracker = mStatusTracker.promote();
6310 if (statusTracker != nullptr) {
6311 if (active) {
6312 statusTracker->markComponentActive(mRequestBufferStatusId);
6313 } else {
6314 statusTracker->markComponentIdle(mRequestBufferStatusId, Fence::NO_FENCE);
6315 }
6316 }
6317}
6318
6319bool Camera3Device::RequestBufferStateMachine::checkSwitchToStopLocked() {
6320 if (mInflightMapEmpty && mRequestThreadPaused && !mRequestBufferOngoing) {
6321 mStatus = RB_STATUS_STOPPED;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006322 return true;
6323 }
6324 return false;
6325}
6326
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006327bool Camera3Device::startRequestBuffer() {
6328 return mRequestBufferSM.startRequestBuffer();
6329}
Shuzhen Wang268a1362018-10-16 16:32:59 -07006330
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006331void Camera3Device::endRequestBuffer() {
6332 mRequestBufferSM.endRequestBuffer();
6333}
Shuzhen Wang268a1362018-10-16 16:32:59 -07006334
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006335nsecs_t Camera3Device::getWaitDuration() {
6336 return kBaseGetBufferWait + getExpectedInFlightDuration();
6337}
Shuzhen Wang268a1362018-10-16 16:32:59 -07006338
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006339void Camera3Device::getInflightBufferKeys(std::vector<std::pair<int32_t, int32_t>>* out) {
6340 mInterface->getInflightBufferKeys(out);
6341}
Shuzhen Wang268a1362018-10-16 16:32:59 -07006342
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006343void Camera3Device::getInflightRequestBufferKeys(std::vector<uint64_t>* out) {
6344 mInterface->getInflightRequestBufferKeys(out);
6345}
Shuzhen Wang268a1362018-10-16 16:32:59 -07006346
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006347std::vector<sp<Camera3StreamInterface>> Camera3Device::getAllStreams() {
6348 std::vector<sp<Camera3StreamInterface>> ret;
6349 bool hasInputStream = mInputStream != nullptr;
6350 ret.reserve(mOutputStreams.size() + mDeletedStreams.size() + ((hasInputStream) ? 1 : 0));
6351 if (hasInputStream) {
6352 ret.push_back(mInputStream);
Shuzhen Wang268a1362018-10-16 16:32:59 -07006353 }
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006354 for (size_t i = 0; i < mOutputStreams.size(); i++) {
6355 ret.push_back(mOutputStreams[i]);
6356 }
6357 for (size_t i = 0; i < mDeletedStreams.size(); i++) {
6358 ret.push_back(mDeletedStreams[i]);
6359 }
6360 return ret;
Shuzhen Wang268a1362018-10-16 16:32:59 -07006361}
6362
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006363status_t Camera3Device::switchToOffline(
6364 const std::vector<int32_t>& streamsToKeep,
6365 /*out*/ sp<CameraOfflineSessionBase>* session) {
6366 ATRACE_CALL();
6367 if (session == nullptr) {
6368 ALOGE("%s: session must not be null", __FUNCTION__);
6369 return BAD_VALUE;
6370 }
6371
6372 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006373
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006374 bool hasInputStream = mInputStream != nullptr;
6375 int32_t inputStreamId = hasInputStream ? mInputStream->getId() : -1;
6376 bool inputStreamSupportsOffline = hasInputStream ?
6377 mInputStream->getOfflineProcessingSupport() : false;
6378 auto outputStreamIds = mOutputStreams.getStreamIds();
6379 auto streamIds = outputStreamIds;
6380 if (hasInputStream) {
6381 streamIds.push_back(mInputStream->getId());
6382 }
6383
6384 // Check all streams in streamsToKeep supports offline mode
6385 for (auto id : streamsToKeep) {
6386 if (std::find(streamIds.begin(), streamIds.end(), id) == streamIds.end()) {
6387 ALOGE("%s: Unknown stream ID %d", __FUNCTION__, id);
6388 return BAD_VALUE;
6389 } else if (id == inputStreamId) {
6390 if (!inputStreamSupportsOffline) {
6391 ALOGE("%s: input stream %d cannot be switched to offline",
6392 __FUNCTION__, id);
6393 return BAD_VALUE;
6394 }
6395 } else {
6396 sp<camera3::Camera3OutputStreamInterface> stream = mOutputStreams.get(id);
6397 if (!stream->getOfflineProcessingSupport()) {
6398 ALOGE("%s: output stream %d cannot be switched to offline",
6399 __FUNCTION__, id);
6400 return BAD_VALUE;
6401 }
6402 }
6403 }
6404
6405 // TODO: block surface sharing and surface group streams until we can support them
6406
6407 // Stop repeating request, wait until all remaining requests are submitted, then call into
6408 // HAL switchToOffline
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006409 hardware::camera::device::V3_6::CameraOfflineSessionInfo offlineSessionInfo;
6410 sp<hardware::camera::device::V3_6::ICameraOfflineSession> offlineSession;
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006411 camera3::BufferRecords bufferRecords;
6412 status_t ret = mRequestThread->switchToOffline(
6413 streamsToKeep, &offlineSessionInfo, &offlineSession, &bufferRecords);
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006414
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006415 if (ret != OK) {
6416 SET_ERR("Switch to offline failed: %s (%d)", strerror(-ret), ret);
6417 return ret;
6418 }
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006419
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006420 bool succ = mRequestBufferSM.onSwitchToOfflineSuccess();
6421 if (!succ) {
6422 SET_ERR("HAL must not be calling requestStreamBuffers call");
6423 // TODO: block ALL callbacks from HAL till app configured new streams?
6424 return UNKNOWN_ERROR;
6425 }
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006426
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006427 // Verify offlineSessionInfo
6428 std::vector<int32_t> offlineStreamIds;
6429 offlineStreamIds.reserve(offlineSessionInfo.offlineStreams.size());
6430 for (auto offlineStream : offlineSessionInfo.offlineStreams) {
6431 // verify stream IDs
6432 int32_t id = offlineStream.id;
6433 if (std::find(streamIds.begin(), streamIds.end(), id) == streamIds.end()) {
6434 SET_ERR("stream ID %d not found!", id);
6435 return UNKNOWN_ERROR;
6436 }
6437
6438 // When not using HAL buf manager, only allow streams requested by app to be preserved
6439 if (!mUseHalBufManager) {
6440 if (std::find(streamsToKeep.begin(), streamsToKeep.end(), id) == streamsToKeep.end()) {
6441 SET_ERR("stream ID %d must not be switched to offline!", id);
6442 return UNKNOWN_ERROR;
6443 }
6444 }
6445
6446 offlineStreamIds.push_back(id);
6447 sp<Camera3StreamInterface> stream = (id == inputStreamId) ?
6448 static_cast<sp<Camera3StreamInterface>>(mInputStream) :
6449 static_cast<sp<Camera3StreamInterface>>(mOutputStreams.get(id));
6450 // Verify number of outstanding buffers
6451 if (stream->getOutstandingBuffersCount() != offlineStream.numOutstandingBuffers) {
6452 SET_ERR("Offline stream %d # of remaining buffer mismatch: (%zu,%d) (service/HAL)",
6453 id, stream->getOutstandingBuffersCount(), offlineStream.numOutstandingBuffers);
6454 return UNKNOWN_ERROR;
6455 }
6456 }
6457
6458 // Verify all streams to be deleted don't have any outstanding buffers
6459 if (hasInputStream && std::find(offlineStreamIds.begin(), offlineStreamIds.end(),
6460 inputStreamId) == offlineStreamIds.end()) {
6461 if (mInputStream->hasOutstandingBuffers()) {
6462 SET_ERR("Input stream %d still has %zu outstanding buffer!",
6463 inputStreamId, mInputStream->getOutstandingBuffersCount());
6464 return UNKNOWN_ERROR;
6465 }
6466 }
6467
6468 for (const auto& outStreamId : outputStreamIds) {
6469 if (std::find(offlineStreamIds.begin(), offlineStreamIds.end(),
6470 outStreamId) == offlineStreamIds.end()) {
6471 auto outStream = mOutputStreams.get(outStreamId);
6472 if (outStream->hasOutstandingBuffers()) {
6473 SET_ERR("Output stream %d still has %zu outstanding buffer!",
6474 outStreamId, outStream->getOutstandingBuffersCount());
6475 return UNKNOWN_ERROR;
6476 }
6477 }
6478 }
6479
6480 InFlightRequestMap offlineReqs;
6481 // Verify inflight requests and their pending buffers
6482 {
6483 std::lock_guard<std::mutex> l(mInFlightLock);
6484 for (auto offlineReq : offlineSessionInfo.offlineRequests) {
6485 int idx = mInFlightMap.indexOfKey(offlineReq.frameNumber);
6486 if (idx == NAME_NOT_FOUND) {
6487 SET_ERR("Offline request frame number %d not found!", offlineReq.frameNumber);
6488 return UNKNOWN_ERROR;
6489 }
6490
6491 const auto& inflightReq = mInFlightMap.valueAt(idx);
6492 // TODO: check specific stream IDs
6493 size_t numBuffersLeft = static_cast<size_t>(inflightReq.numBuffersLeft);
6494 if (numBuffersLeft != offlineReq.pendingStreams.size()) {
6495 SET_ERR("Offline request # of remaining buffer mismatch: (%d,%d) (service/HAL)",
6496 inflightReq.numBuffersLeft, offlineReq.pendingStreams.size());
6497 return UNKNOWN_ERROR;
6498 }
6499 offlineReqs.add(offlineReq.frameNumber, inflightReq);
6500 }
6501 }
6502
6503 // Create Camera3OfflineSession and transfer object ownership
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006504 // (streams, inflight requests, buffer caches)
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006505 camera3::StreamSet offlineStreamSet;
6506 sp<camera3::Camera3Stream> inputStream;
6507 for (auto offlineStream : offlineSessionInfo.offlineStreams) {
6508 int32_t id = offlineStream.id;
6509 if (mInputStream != nullptr && id == mInputStream->getId()) {
6510 inputStream = mInputStream;
6511 } else {
6512 offlineStreamSet.add(id, mOutputStreams.get(id));
6513 }
6514 }
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006515
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006516 // TODO: check if we need to lock before copying states
6517 // though technically no other thread should be talking to Camera3Device at this point
6518 Camera3OfflineStates offlineStates(
6519 mTagMonitor, mVendorTagId, mUseHalBufManager, mNeedFixupMonochromeTags,
Shuzhen Wangb7b42652020-05-07 11:59:02 -07006520 mUsePartialResult, mNumPartialResults, mLastCompletedRegularFrameNumber,
6521 mLastCompletedReprocessFrameNumber, mLastCompletedZslFrameNumber,
6522 mNextResultFrameNumber, mNextReprocessResultFrameNumber,
6523 mNextZslStillResultFrameNumber, mNextShutterFrameNumber,
6524 mNextReprocessShutterFrameNumber, mNextZslStillShutterFrameNumber,
6525 mDeviceInfo, mPhysicalDeviceInfoMap, mDistortionMappers,
6526 mZoomRatioMappers, mRotateAndCropMappers);
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006527
6528 *session = new Camera3OfflineSession(mId, inputStream, offlineStreamSet,
6529 std::move(bufferRecords), offlineReqs, offlineStates, offlineSession);
6530
6531 // Delete all streams that has been transferred to offline session
6532 Mutex::Autolock l(mLock);
6533 for (auto offlineStream : offlineSessionInfo.offlineStreams) {
6534 int32_t id = offlineStream.id;
6535 if (mInputStream != nullptr && id == mInputStream->getId()) {
6536 mInputStream.clear();
6537 } else {
6538 mOutputStreams.remove(id);
6539 }
6540 }
6541
6542 // disconnect all other streams and switch to UNCONFIGURED state
6543 if (mInputStream != nullptr) {
6544 ret = mInputStream->disconnect();
6545 if (ret != OK) {
6546 SET_ERR_L("disconnect input stream failed!");
6547 return UNKNOWN_ERROR;
6548 }
6549 }
6550
6551 for (auto streamId : mOutputStreams.getStreamIds()) {
6552 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
6553 ret = stream->disconnect();
6554 if (ret != OK) {
6555 SET_ERR_L("disconnect output stream %d failed!", streamId);
6556 return UNKNOWN_ERROR;
6557 }
6558 }
6559
6560 mInputStream.clear();
6561 mOutputStreams.clear();
6562 mNeedConfig = true;
6563 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
6564 mOperatingMode = NO_MODE;
6565 mIsConstrainedHighSpeedConfiguration = false;
Emilian Peevc0fe54c2020-03-11 14:05:07 -07006566 mRequestThread->clearPreviousRequest();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006567
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006568 return OK;
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006569 // TO be done by CameraDeviceClient/Camera3OfflineSession
6570 // register the offline client to camera service
6571 // Setup result passthing threads etc
6572 // Initialize offline session so HAL can start sending callback to it (result Fmq)
6573 // TODO: check how many onIdle callback will be sent
6574 // Java side to make sure the CameraCaptureSession is properly closed
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006575}
6576
Emilian Peevcc0b7952020-01-07 13:54:47 -08006577void Camera3Device::getOfflineStreamIds(std::vector<int> *offlineStreamIds) {
6578 ATRACE_CALL();
6579
6580 if (offlineStreamIds == nullptr) {
6581 return;
6582 }
6583
6584 Mutex::Autolock il(mInterfaceLock);
6585
6586 auto streamIds = mOutputStreams.getStreamIds();
6587 bool hasInputStream = mInputStream != nullptr;
6588 if (hasInputStream && mInputStream->getOfflineProcessingSupport()) {
6589 offlineStreamIds->push_back(mInputStream->getId());
6590 }
6591
6592 for (const auto & streamId : streamIds) {
6593 sp<camera3::Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
6594 // Streams that use the camera buffer manager are currently not supported in
6595 // offline mode
6596 if (stream->getOfflineProcessingSupport() &&
6597 (stream->getStreamSetId() == CAMERA3_STREAM_SET_ID_INVALID)) {
6598 offlineStreamIds->push_back(streamId);
6599 }
6600 }
6601}
6602
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08006603status_t Camera3Device::setRotateAndCropAutoBehavior(
6604 camera_metadata_enum_android_scaler_rotate_and_crop_t rotateAndCropValue) {
6605 ATRACE_CALL();
6606 Mutex::Autolock il(mInterfaceLock);
6607 Mutex::Autolock l(mLock);
6608 if (mRequestThread == nullptr) {
6609 return INVALID_OPERATION;
6610 }
6611 return mRequestThread->setRotateAndCropAutoBehavior(rotateAndCropValue);
6612}
6613
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08006614bool Camera3Device::supportsCameraMute() {
6615 Mutex::Autolock il(mInterfaceLock);
6616 Mutex::Autolock l(mLock);
6617
6618 return mSupportCameraMute;
6619}
6620
6621status_t Camera3Device::setCameraMute(bool enabled) {
6622 ATRACE_CALL();
6623 Mutex::Autolock il(mInterfaceLock);
6624 Mutex::Autolock l(mLock);
6625
6626 if (mRequestThread == nullptr || !mSupportCameraMute) {
6627 return INVALID_OPERATION;
6628 }
Eino-Ville Talvala11afe4f2021-05-27 14:45:31 -07006629 int32_t muteMode =
6630 !enabled ? ANDROID_SENSOR_TEST_PATTERN_MODE_OFF :
6631 mSupportTestPatternSolidColor ? ANDROID_SENSOR_TEST_PATTERN_MODE_SOLID_COLOR :
6632 ANDROID_SENSOR_TEST_PATTERN_MODE_BLACK;
6633 return mRequestThread->setCameraMute(muteMode);
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08006634}
6635
Cliff Wuc2ad9c82021-04-21 00:58:58 +08006636status_t Camera3Device::injectCamera(const String8& injectedCamId,
6637 sp<CameraProviderManager> manager) {
6638 ALOGI("%s Injection camera: injectedCamId = %s", __FUNCTION__, injectedCamId.string());
6639 ATRACE_CALL();
6640 Mutex::Autolock il(mInterfaceLock);
6641
6642 status_t res = NO_ERROR;
6643 if (mInjectionMethods->isInjecting()) {
6644 if (injectedCamId == mInjectionMethods->getInjectedCamId()) {
6645 return OK;
6646 } else {
6647 res = mInjectionMethods->stopInjection();
6648 if (res != OK) {
6649 ALOGE("%s: Failed to stop the injection camera! ret != NO_ERROR: %d",
6650 __FUNCTION__, res);
6651 return res;
6652 }
6653 }
6654 }
6655
6656 res = mInjectionMethods->injectionInitialize(injectedCamId, manager, this);
6657 if (res != OK) {
6658 ALOGE("%s: Failed to initialize the injection camera! ret != NO_ERROR: %d",
6659 __FUNCTION__, res);
6660 return res;
6661 }
6662
6663 camera3::camera_stream_configuration injectionConfig;
6664 std::vector<uint32_t> injectionBufferSizes;
6665 mInjectionMethods->getInjectionConfig(&injectionConfig, &injectionBufferSizes);
6666 // When the second display of android is cast to the remote device, and the opened camera is
6667 // also cast to the second display, in this case, because the camera has configured the streams
6668 // at this time, we can directly call injectCamera() to replace the internal camera with
6669 // injection camera.
6670 if (mOperatingMode >= 0 && injectionConfig.num_streams > 0
6671 && injectionBufferSizes.size() > 0) {
6672 ALOGV("%s: The opened camera is directly cast to the remote device.", __FUNCTION__);
6673 res = mInjectionMethods->injectCamera(
6674 injectionConfig, injectionBufferSizes);
6675 if (res != OK) {
6676 ALOGE("Can't finish inject camera process!");
6677 return res;
6678 }
6679 }
6680
6681 return OK;
6682}
6683
6684status_t Camera3Device::stopInjection() {
6685 ALOGI("%s: Injection camera: stopInjection", __FUNCTION__);
6686 Mutex::Autolock il(mInterfaceLock);
6687 return mInjectionMethods->stopInjection();
6688}
6689
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08006690}; // namespace android