blob: 368c39c26016f2889e6c23b74e327195f9f10736 [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();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002680 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Igor Murashkin2fba5842013-04-22 14:03:54 -07002681
2682 // Don't configure bidi streams twice, nor add them twice to the list
2683 if (mOutputStreams[i].get() ==
2684 static_cast<Camera3StreamInterface*>(mInputStream.get())) {
2685
2686 config.num_streams--;
2687 continue;
2688 }
2689
Emilian Peevf4816702020-04-03 15:44:51 -07002690 camera3::camera_stream_t *outputStream;
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002691 outputStream = mOutputStreams[i]->startConfiguration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002692 if (outputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002693 CLOGE("Can't start output stream configuration");
2694 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002695 return INVALID_OPERATION;
2696 }
2697 streams.add(outputStream);
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002698
Shuzhen Wangb7ab1e42019-02-20 15:42:23 -08002699 if (outputStream->format == HAL_PIXEL_FORMAT_BLOB) {
Emilian Peev192ee832018-01-31 14:46:47 +00002700 size_t k = i + ((mInputStream != nullptr) ? 1 : 0); // Input stream if present should
2701 // always occupy the initial entry.
Shuzhen Wangb7ab1e42019-02-20 15:42:23 -08002702 if (outputStream->data_space == HAL_DATASPACE_V0_JFIF) {
2703 bufferSizes[k] = static_cast<uint32_t>(
2704 getJpegBufferSize(outputStream->width, outputStream->height));
2705 } else if (outputStream->data_space ==
2706 static_cast<android_dataspace>(HAL_DATASPACE_JPEG_APP_SEGMENTS)) {
2707 bufferSizes[k] = outputStream->width * outputStream->height;
2708 } else {
2709 ALOGW("%s: Blob dataSpace %d not supported",
2710 __FUNCTION__, outputStream->data_space);
2711 }
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002712 }
Shuzhen Wang99080502021-03-07 21:08:20 -08002713
2714 if (mOutputStreams[i]->isMultiResolution()) {
2715 int32_t streamGroupId = mOutputStreams[i]->getHalStreamGroupId();
2716 const String8& physicalCameraId = mOutputStreams[i]->getPhysicalCameraId();
2717 mGroupIdPhysicalCameraMap[streamGroupId].insert(physicalCameraId);
2718 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002719 }
2720
2721 config.streams = streams.editArray();
2722
2723 // Do the HAL configuration; will potentially touch stream
Shuzhen Wang92653952019-05-07 15:11:43 -07002724 // max_buffers, usage, and priv fields, as well as data_space and format
2725 // fields for IMPLEMENTATION_DEFINED formats.
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002726
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002727 const camera_metadata_t *sessionBuffer = sessionParams.getAndLock();
Emilian Peev192ee832018-01-31 14:46:47 +00002728 res = mInterface->configureStreams(sessionBuffer, &config, bufferSizes);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002729 sessionParams.unlock(sessionBuffer);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002730
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002731 if (res == BAD_VALUE) {
2732 // HAL rejected this set of streams as unsupported, clean up config
2733 // attempt and return to unconfigured state
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002734 CLOGE("Set of requested inputs/outputs not supported by HAL");
2735 cancelStreamsConfigurationLocked();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002736 return BAD_VALUE;
2737 } else if (res != OK) {
2738 // Some other kind of error from configure_streams - this is not
2739 // expected
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002740 SET_ERR_L("Unable to configure streams with HAL: %s (%d)",
2741 strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002742 return res;
2743 }
2744
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002745 // Finish all stream configuration immediately.
2746 // TODO: Try to relax this later back to lazy completion, which should be
2747 // faster
2748
Igor Murashkin073f8572013-05-02 14:59:28 -07002749 if (mInputStream != NULL && mInputStream->isConfiguring()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002750 bool streamReConfigured = false;
2751 res = mInputStream->finishConfiguration(&streamReConfigured);
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002752 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002753 CLOGE("Can't finish configuring input stream %d: %s (%d)",
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002754 mInputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002755 cancelStreamsConfigurationLocked();
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002756 if ((res == NO_INIT || res == DEAD_OBJECT) && mInputStream->isAbandoned()) {
2757 return DEAD_OBJECT;
2758 }
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002759 return BAD_VALUE;
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002760 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002761 if (streamReConfigured) {
2762 mInterface->onStreamReConfigured(mInputStream->getId());
2763 }
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002764 }
2765
2766 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002767 sp<Camera3OutputStreamInterface> outputStream = mOutputStreams[i];
Zhijun He5d677d12016-05-29 16:52:39 -07002768 if (outputStream->isConfiguring() && !outputStream->isConsumerConfigurationDeferred()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002769 bool streamReConfigured = false;
2770 res = outputStream->finishConfiguration(&streamReConfigured);
Igor Murashkin073f8572013-05-02 14:59:28 -07002771 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002772 CLOGE("Can't finish configuring output stream %d: %s (%d)",
Igor Murashkin073f8572013-05-02 14:59:28 -07002773 outputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002774 cancelStreamsConfigurationLocked();
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002775 if ((res == NO_INIT || res == DEAD_OBJECT) && outputStream->isAbandoned()) {
2776 return DEAD_OBJECT;
2777 }
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002778 return BAD_VALUE;
Igor Murashkin073f8572013-05-02 14:59:28 -07002779 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002780 if (streamReConfigured) {
2781 mInterface->onStreamReConfigured(outputStream->getId());
2782 }
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002783 }
2784 }
2785
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002786 // Request thread needs to know to avoid using repeat-last-settings protocol
2787 // across configure_streams() calls
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002788 if (notifyRequestThread) {
Shuzhen Wang99080502021-03-07 21:08:20 -08002789 mRequestThread->configurationComplete(mIsConstrainedHighSpeedConfiguration,
2790 sessionParams, mGroupIdPhysicalCameraMap);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002791 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002792
Zhijun He90f7c372016-08-16 16:19:43 -07002793 char value[PROPERTY_VALUE_MAX];
2794 property_get("camera.fifo.disable", value, "0");
2795 int32_t disableFifo = atoi(value);
2796 if (disableFifo != 1) {
2797 // Boost priority of request thread to SCHED_FIFO.
2798 pid_t requestThreadTid = mRequestThread->getTid();
2799 res = requestPriority(getpid(), requestThreadTid,
Mikhail Naganov83f04272017-02-07 10:45:09 -08002800 kRequestThreadPriority, /*isForApp*/ false, /*asynchronous*/ false);
Zhijun He90f7c372016-08-16 16:19:43 -07002801 if (res != OK) {
2802 ALOGW("Can't set realtime priority for request processing thread: %s (%d)",
2803 strerror(-res), res);
2804 } else {
2805 ALOGD("Set real time priority for request queue thread (tid %d)", requestThreadTid);
2806 }
Eino-Ville Talvalaf99498e2015-09-25 16:52:55 -07002807 }
2808
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002809 // Update device state
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002810 const camera_metadata_t *newSessionParams = sessionParams.getAndLock();
2811 const camera_metadata_t *currentSessionParams = mSessionParams.getAndLock();
2812 bool updateSessionParams = (newSessionParams != currentSessionParams) ? true : false;
2813 sessionParams.unlock(newSessionParams);
2814 mSessionParams.unlock(currentSessionParams);
2815 if (updateSessionParams) {
2816 mSessionParams = sessionParams;
2817 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002818
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002819 mNeedConfig = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002820
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002821 internalUpdateStatusLocked((mFakeStreamId == NO_STREAM) ?
Ruben Brunk183f0562015-08-12 12:55:02 -07002822 STATUS_CONFIGURED : STATUS_UNCONFIGURED);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002823
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002824 ALOGV("%s: Camera %s: Stream configuration complete", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002825
Zhijun He0a210512014-07-24 13:45:15 -07002826 // tear down the deleted streams after configure streams.
2827 mDeletedStreams.clear();
2828
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002829 auto rc = mPreparerThread->resume();
2830 if (rc != OK) {
2831 SET_ERR_L("%s: Camera %s: Preparer thread failed to resume!", __FUNCTION__, mId.string());
2832 return rc;
2833 }
2834
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002835 if (mFakeStreamId == NO_STREAM) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07002836 mRequestBufferSM.onStreamsConfigured();
2837 }
2838
Cliff Wu3b268182021-07-06 15:44:43 +08002839 // First call injectCamera() and then run configureStreamsLocked() case:
Cliff Wuc2ad9c82021-04-21 00:58:58 +08002840 // Since the streams configuration of the injection camera is based on the internal camera, we
Cliff Wu3b268182021-07-06 15:44:43 +08002841 // must wait until the internal camera configure streams before running the injection job to
Cliff Wuc2ad9c82021-04-21 00:58:58 +08002842 // configure the injection streams.
2843 if (mInjectionMethods->isInjecting()) {
Cliff Wu3b268182021-07-06 15:44:43 +08002844 ALOGD("%s: Injection camera %s: Start to configure streams.",
Cliff Wuc2ad9c82021-04-21 00:58:58 +08002845 __FUNCTION__, mInjectionMethods->getInjectedCamId().string());
2846 res = mInjectionMethods->injectCamera(config, bufferSizes);
2847 if (res != OK) {
2848 ALOGE("Can't finish inject camera process!");
2849 return res;
2850 }
Cliff Wu3b268182021-07-06 15:44:43 +08002851 } else {
2852 // First run configureStreamsLocked() and then call injectCamera() case:
2853 // If the stream configuration has been completed and camera deive is active, but the
2854 // injection camera has not been injected yet, we need to store the stream configuration of
2855 // the internal camera (because the stream configuration of the injection camera is based
2856 // on the internal camera). When injecting occurs later, this configuration can be used by
2857 // the injection camera.
2858 ALOGV("%s: The stream configuration is complete and the camera device is active, but the"
2859 " injection camera has not been injected yet.", __FUNCTION__);
2860 mInjectionMethods->storeInjectionConfig(config, bufferSizes);
Cliff Wuc2ad9c82021-04-21 00:58:58 +08002861 }
2862
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002863 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002864}
2865
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002866status_t Camera3Device::addFakeStreamLocked() {
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002867 ATRACE_CALL();
2868 status_t res;
2869
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002870 if (mFakeStreamId != NO_STREAM) {
2871 // Should never be adding a second fake stream when one is already
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002872 // active
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002873 SET_ERR_L("%s: Camera %s: A fake stream already exists!",
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002874 __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002875 return INVALID_OPERATION;
2876 }
2877
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002878 ALOGV("%s: Camera %s: Adding a fake stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002879
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002880 sp<Camera3OutputStreamInterface> fakeStream =
2881 new Camera3FakeStream(mNextStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002882
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002883 res = mOutputStreams.add(mNextStreamId, fakeStream);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002884 if (res < 0) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002885 SET_ERR_L("Can't add fake stream to set: %s (%d)", strerror(-res), res);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002886 return res;
2887 }
2888
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002889 mFakeStreamId = mNextStreamId;
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002890 mNextStreamId++;
2891
2892 return OK;
2893}
2894
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002895status_t Camera3Device::tryRemoveFakeStreamLocked() {
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002896 ATRACE_CALL();
2897 status_t res;
2898
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002899 if (mFakeStreamId == NO_STREAM) return OK;
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002900 if (mOutputStreams.size() == 1) return OK;
2901
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002902 ALOGV("%s: Camera %s: Removing the fake stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002903
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002904 // Ok, have a fake stream and there's at least one other output stream,
2905 // so remove the fake
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002906
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002907 sp<Camera3StreamInterface> deletedStream = mOutputStreams.get(mFakeStreamId);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002908 if (deletedStream == nullptr) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002909 SET_ERR_L("Fake stream %d does not appear to exist", mFakeStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002910 return INVALID_OPERATION;
2911 }
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002912 mOutputStreams.remove(mFakeStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002913
2914 // Free up the stream endpoint so that it can be used by some other stream
2915 res = deletedStream->disconnect();
2916 if (res != OK) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002917 SET_ERR_L("Can't disconnect deleted fake stream %d", mFakeStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002918 // fall through since we want to still list the stream as deleted.
2919 }
2920 mDeletedStreams.add(deletedStream);
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002921 mFakeStreamId = NO_STREAM;
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002922
2923 return res;
2924}
2925
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002926void Camera3Device::setErrorState(const char *fmt, ...) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002927 ATRACE_CALL();
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002928 Mutex::Autolock l(mLock);
2929 va_list args;
2930 va_start(args, fmt);
2931
2932 setErrorStateLockedV(fmt, args);
2933
2934 va_end(args);
2935}
2936
2937void Camera3Device::setErrorStateV(const char *fmt, va_list args) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002938 ATRACE_CALL();
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002939 Mutex::Autolock l(mLock);
2940 setErrorStateLockedV(fmt, args);
2941}
2942
2943void Camera3Device::setErrorStateLocked(const char *fmt, ...) {
2944 va_list args;
2945 va_start(args, fmt);
2946
2947 setErrorStateLockedV(fmt, args);
2948
2949 va_end(args);
2950}
2951
2952void Camera3Device::setErrorStateLockedV(const char *fmt, va_list args) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002953 // Print out all error messages to log
2954 String8 errorCause = String8::formatV(fmt, args);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002955 ALOGE("Camera %s: %s", mId.string(), errorCause.string());
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002956
2957 // But only do error state transition steps for the first error
Zhijun Heb05eeae2013-06-06 13:51:22 -07002958 if (mStatus == STATUS_ERROR || mStatus == STATUS_UNINITIALIZED) return;
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002959
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002960 mErrorCause = errorCause;
2961
Yin-Chia Yeh3d145ae2017-07-27 12:47:03 -07002962 if (mRequestThread != nullptr) {
2963 mRequestThread->setPaused(true);
2964 }
Ruben Brunk183f0562015-08-12 12:55:02 -07002965 internalUpdateStatusLocked(STATUS_ERROR);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002966
2967 // Notify upstream about a device error
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002968 sp<NotificationListener> listener = mListener.promote();
2969 if (listener != NULL) {
2970 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002971 CaptureResultExtras());
Shuzhen Wang316781a2020-08-18 18:11:01 -07002972 mSessionStatsBuilder.onDeviceError();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002973 }
2974
2975 // Save stack trace. View by dumping it later.
2976 CameraTraces::saveTrace();
2977 // TODO: consider adding errorCause and client pid/procname
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002978}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002979
2980/**
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002981 * In-flight request management
2982 */
2983
Jianing Weicb0652e2014-03-12 18:29:36 -07002984status_t Camera3Device::registerInFlight(uint32_t frameNumber,
Chien-Yu Chend196d612015-06-22 19:49:01 -07002985 int32_t numBuffers, CaptureResultExtras resultExtras, bool hasInput,
Shuzhen Wang5c22c152017-12-31 17:12:25 -08002986 bool hasAppCallback, nsecs_t maxExpectedDuration,
Shuzhen Wang99080502021-03-07 21:08:20 -08002987 const std::set<std::set<String8>>& physicalCameraIds,
2988 bool isStillCapture, bool isZslCapture, bool rotateAndCropAuto,
2989 const std::set<std::string>& cameraIdsWithZoom,
Shuzhen Wang316781a2020-08-18 18:11:01 -07002990 const SurfaceMap& outputSurfaces, nsecs_t requestTimeNs) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002991 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002992 std::lock_guard<std::mutex> l(mInFlightLock);
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002993
2994 ssize_t res;
Chien-Yu Chend196d612015-06-22 19:49:01 -07002995 res = mInFlightMap.add(frameNumber, InFlightRequest(numBuffers, resultExtras, hasInput,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07002996 hasAppCallback, maxExpectedDuration, physicalCameraIds, isStillCapture, isZslCapture,
Shuzhen Wang316781a2020-08-18 18:11:01 -07002997 rotateAndCropAuto, cameraIdsWithZoom, requestTimeNs, outputSurfaces));
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002998 if (res < 0) return res;
2999
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07003000 if (mInFlightMap.size() == 1) {
Emilian Peev26d975d2018-07-05 14:52:57 +01003001 // Hold a separate dedicated tracker lock to prevent race with disconnect and also
3002 // avoid a deadlock during reprocess requests.
3003 Mutex::Autolock l(mTrackerLock);
Yin-Chia Yeh38dfde52017-06-27 17:13:33 -07003004 if (mStatusTracker != nullptr) {
3005 mStatusTracker->markComponentActive(mInFlightStatusId);
3006 }
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07003007 }
3008
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003009 mExpectedInflightDuration += maxExpectedDuration;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003010 return OK;
3011}
3012
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003013void Camera3Device::onInflightEntryRemovedLocked(nsecs_t duration) {
Shuzhen Wangcadb3302016-11-04 14:17:56 -07003014 // Indicate idle inFlightMap to the status tracker
3015 if (mInFlightMap.size() == 0) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07003016 mRequestBufferSM.onInflightMapEmpty();
Emilian Peev26d975d2018-07-05 14:52:57 +01003017 // Hold a separate dedicated tracker lock to prevent race with disconnect and also
3018 // avoid a deadlock during reprocess requests.
3019 Mutex::Autolock l(mTrackerLock);
Yin-Chia Yeh38dfde52017-06-27 17:13:33 -07003020 if (mStatusTracker != nullptr) {
3021 mStatusTracker->markComponentIdle(mInFlightStatusId, Fence::NO_FENCE);
3022 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07003023 }
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003024 mExpectedInflightDuration -= duration;
Shuzhen Wangcadb3302016-11-04 14:17:56 -07003025}
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003026
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003027void Camera3Device::checkInflightMapLengthLocked() {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04003028 // Validation check - if we have too many in-flight frames with long total inflight duration,
Yin-Chia Yeh99fd0972019-06-27 14:22:44 -07003029 // something has likely gone wrong. This might still be legit only if application send in
3030 // a long burst of long exposure requests.
3031 if (mExpectedInflightDuration > kMinWarnInflightDuration) {
3032 if (!mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() > kInFlightWarnLimit) {
3033 CLOGW("In-flight list too large: %zu, total inflight duration %" PRIu64,
3034 mInFlightMap.size(), mExpectedInflightDuration);
3035 } else if (mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() >
3036 kInFlightWarnLimitHighSpeed) {
3037 CLOGW("In-flight list too large for high speed configuration: %zu,"
3038 "total inflight duration %" PRIu64,
3039 mInFlightMap.size(), mExpectedInflightDuration);
3040 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003041 }
3042}
3043
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003044void Camera3Device::onInflightMapFlushedLocked() {
3045 mExpectedInflightDuration = 0;
3046}
3047
3048void Camera3Device::removeInFlightMapEntryLocked(int idx) {
Jayant Chowdharyd4776262020-06-23 23:45:57 -07003049 ATRACE_HFR_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003050 nsecs_t duration = mInFlightMap.valueAt(idx).maxExpectedDuration;
3051 mInFlightMap.removeItemsAt(idx, 1);
3052
3053 onInflightEntryRemovedLocked(duration);
3054}
3055
3056
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003057void Camera3Device::flushInflightRequests() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003058 ATRACE_CALL();
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003059 sp<NotificationListener> listener;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003060 {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003061 std::lock_guard<std::mutex> l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003062 listener = mListener.promote();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003063 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003064
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003065 FlushInflightReqStates states {
3066 mId, mInFlightLock, mInFlightMap, mUseHalBufManager,
Shuzhen Wang316781a2020-08-18 18:11:01 -07003067 listener, *this, *mInterface, *this, mSessionStatsBuilder};
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003068
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003069 camera3::flushInflightRequests(states);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003070}
3071
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003072CameraMetadata Camera3Device::getLatestRequestLocked() {
Igor Murashkin1e479c02013-09-06 16:55:14 -07003073 ALOGV("%s", __FUNCTION__);
3074
Igor Murashkin1e479c02013-09-06 16:55:14 -07003075 CameraMetadata retVal;
3076
3077 if (mRequestThread != NULL) {
3078 retVal = mRequestThread->getLatestRequest();
3079 }
3080
Igor Murashkin1e479c02013-09-06 16:55:14 -07003081 return retVal;
3082}
3083
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07003084void Camera3Device::monitorMetadata(TagMonitor::eventSource source,
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003085 int64_t frameNumber, nsecs_t timestamp, const CameraMetadata& metadata,
Jayant Chowdharycd277cd2021-08-11 15:48:40 -07003086 const std::unordered_map<std::string, CameraMetadata>& physicalMetadata,
Jayant Chowdharyc30b4c32021-08-18 11:43:16 -07003087 const camera_stream_buffer_t *outputBuffers, uint32_t numOutputBuffers,
3088 int32_t inputStreamId) {
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003089
3090 mTagMonitor.monitorMetadata(source, frameNumber, timestamp, metadata,
Jayant Chowdharyc30b4c32021-08-18 11:43:16 -07003091 physicalMetadata, outputBuffers, numOutputBuffers, inputStreamId);
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07003092}
3093
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003094/**
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003095 * HalInterface inner class methods
3096 */
3097
Yifan Hongf79b5542017-04-11 14:44:25 -07003098Camera3Device::HalInterface::HalInterface(
3099 sp<ICameraDeviceSession> &session,
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003100 std::shared_ptr<RequestMetadataQueue> queue,
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003101 bool useHalBufManager, bool supportOfflineProcessing) :
Yifan Hongf79b5542017-04-11 14:44:25 -07003102 mHidlSession(session),
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003103 mRequestMetadataQueue(queue),
Emilian Peev4ec17882019-01-24 17:16:58 -08003104 mUseHalBufManager(useHalBufManager),
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003105 mIsReconfigurationQuerySupported(true),
3106 mSupportOfflineProcessing(supportOfflineProcessing) {
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003107 // Check with hardware service manager if we can downcast these interfaces
3108 // Somewhat expensive, so cache the results at startup
Shuzhen Wang83bff122020-11-20 15:51:39 -08003109 auto castResult_3_7 = device::V3_7::ICameraDeviceSession::castFrom(mHidlSession);
3110 if (castResult_3_7.isOk()) {
3111 mHidlSession_3_7 = castResult_3_7;
3112 }
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003113 auto castResult_3_6 = device::V3_6::ICameraDeviceSession::castFrom(mHidlSession);
3114 if (castResult_3_6.isOk()) {
3115 mHidlSession_3_6 = castResult_3_6;
3116 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003117 auto castResult_3_5 = device::V3_5::ICameraDeviceSession::castFrom(mHidlSession);
3118 if (castResult_3_5.isOk()) {
3119 mHidlSession_3_5 = castResult_3_5;
3120 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003121 auto castResult_3_4 = device::V3_4::ICameraDeviceSession::castFrom(mHidlSession);
3122 if (castResult_3_4.isOk()) {
3123 mHidlSession_3_4 = castResult_3_4;
3124 }
3125 auto castResult_3_3 = device::V3_3::ICameraDeviceSession::castFrom(mHidlSession);
3126 if (castResult_3_3.isOk()) {
3127 mHidlSession_3_3 = castResult_3_3;
3128 }
3129}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003130
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003131Camera3Device::HalInterface::HalInterface() :
3132 mUseHalBufManager(false),
3133 mSupportOfflineProcessing(false) {}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003134
3135Camera3Device::HalInterface::HalInterface(const HalInterface& other) :
Yifan Hongf79b5542017-04-11 14:44:25 -07003136 mHidlSession(other.mHidlSession),
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003137 mRequestMetadataQueue(other.mRequestMetadataQueue),
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003138 mUseHalBufManager(other.mUseHalBufManager),
3139 mSupportOfflineProcessing(other.mSupportOfflineProcessing) {}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003140
3141bool Camera3Device::HalInterface::valid() {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003142 return (mHidlSession != nullptr);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003143}
3144
3145void Camera3Device::HalInterface::clear() {
Shuzhen Wang83bff122020-11-20 15:51:39 -08003146 mHidlSession_3_7.clear();
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003147 mHidlSession_3_6.clear();
Emilian Peev644a3e12018-11-23 13:52:39 +00003148 mHidlSession_3_5.clear();
Emilian Peev9e740b02018-01-30 18:28:03 +00003149 mHidlSession_3_4.clear();
3150 mHidlSession_3_3.clear();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003151 mHidlSession.clear();
3152}
3153
3154status_t Camera3Device::HalInterface::constructDefaultRequestSettings(
Emilian Peevf4816702020-04-03 15:44:51 -07003155 camera_request_template_t templateId,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003156 /*out*/ camera_metadata_t **requestTemplate) {
3157 ATRACE_NAME("CameraHal::constructDefaultRequestSettings");
3158 if (!valid()) return INVALID_OPERATION;
3159 status_t res = OK;
3160
Emilian Peev31abd0a2017-05-11 18:37:46 +01003161 common::V1_0::Status status;
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003162
3163 auto requestCallback = [&status, &requestTemplate]
Emilian Peev31abd0a2017-05-11 18:37:46 +01003164 (common::V1_0::Status s, const device::V3_2::CameraMetadata& request) {
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003165 status = s;
3166 if (status == common::V1_0::Status::OK) {
3167 const camera_metadata *r =
3168 reinterpret_cast<const camera_metadata_t*>(request.data());
3169 size_t expectedSize = request.size();
3170 int ret = validate_camera_metadata_structure(r, &expectedSize);
3171 if (ret == OK || ret == CAMERA_METADATA_VALIDATION_SHIFTED) {
3172 *requestTemplate = clone_camera_metadata(r);
3173 if (*requestTemplate == nullptr) {
3174 ALOGE("%s: Unable to clone camera metadata received from HAL",
3175 __FUNCTION__);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003176 status = common::V1_0::Status::INTERNAL_ERROR;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003177 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003178 } else {
3179 ALOGE("%s: Malformed camera metadata received from HAL", __FUNCTION__);
3180 status = common::V1_0::Status::INTERNAL_ERROR;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003181 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003182 }
3183 };
3184 hardware::Return<void> err;
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003185 RequestTemplate id;
3186 switch (templateId) {
Emilian Peevf4816702020-04-03 15:44:51 -07003187 case CAMERA_TEMPLATE_PREVIEW:
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003188 id = RequestTemplate::PREVIEW;
3189 break;
Emilian Peevf4816702020-04-03 15:44:51 -07003190 case CAMERA_TEMPLATE_STILL_CAPTURE:
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003191 id = RequestTemplate::STILL_CAPTURE;
3192 break;
Emilian Peevf4816702020-04-03 15:44:51 -07003193 case CAMERA_TEMPLATE_VIDEO_RECORD:
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003194 id = RequestTemplate::VIDEO_RECORD;
3195 break;
Emilian Peevf4816702020-04-03 15:44:51 -07003196 case CAMERA_TEMPLATE_VIDEO_SNAPSHOT:
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003197 id = RequestTemplate::VIDEO_SNAPSHOT;
3198 break;
Emilian Peevf4816702020-04-03 15:44:51 -07003199 case CAMERA_TEMPLATE_ZERO_SHUTTER_LAG:
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003200 id = RequestTemplate::ZERO_SHUTTER_LAG;
3201 break;
Emilian Peevf4816702020-04-03 15:44:51 -07003202 case CAMERA_TEMPLATE_MANUAL:
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003203 id = RequestTemplate::MANUAL;
3204 break;
3205 default:
3206 // Unknown template ID, or this HAL is too old to support it
3207 return BAD_VALUE;
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003208 }
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003209 err = mHidlSession->constructDefaultRequestSettings(id, requestCallback);
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003210
Emilian Peev31abd0a2017-05-11 18:37:46 +01003211 if (!err.isOk()) {
3212 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3213 res = DEAD_OBJECT;
3214 } else {
3215 res = CameraProviderManager::mapToStatusT(status);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003216 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003217
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003218 return res;
3219}
3220
Emilian Peev4ec17882019-01-24 17:16:58 -08003221bool Camera3Device::HalInterface::isReconfigurationRequired(CameraMetadata& oldSessionParams,
3222 CameraMetadata& newSessionParams) {
3223 // We do reconfiguration by default;
3224 bool ret = true;
3225 if ((mHidlSession_3_5 != nullptr) && mIsReconfigurationQuerySupported) {
3226 android::hardware::hidl_vec<uint8_t> oldParams, newParams;
3227 camera_metadata_t* oldSessioMeta = const_cast<camera_metadata_t*>(
3228 oldSessionParams.getAndLock());
3229 camera_metadata_t* newSessioMeta = const_cast<camera_metadata_t*>(
3230 newSessionParams.getAndLock());
3231 oldParams.setToExternal(reinterpret_cast<uint8_t*>(oldSessioMeta),
3232 get_camera_metadata_size(oldSessioMeta));
3233 newParams.setToExternal(reinterpret_cast<uint8_t*>(newSessioMeta),
3234 get_camera_metadata_size(newSessioMeta));
3235 hardware::camera::common::V1_0::Status callStatus;
3236 bool required;
3237 auto hidlCb = [&callStatus, &required] (hardware::camera::common::V1_0::Status s,
3238 bool requiredFlag) {
3239 callStatus = s;
3240 required = requiredFlag;
3241 };
3242 auto err = mHidlSession_3_5->isReconfigurationRequired(oldParams, newParams, hidlCb);
3243 oldSessionParams.unlock(oldSessioMeta);
3244 newSessionParams.unlock(newSessioMeta);
3245 if (err.isOk()) {
3246 switch (callStatus) {
3247 case hardware::camera::common::V1_0::Status::OK:
3248 ret = required;
3249 break;
3250 case hardware::camera::common::V1_0::Status::METHOD_NOT_SUPPORTED:
3251 mIsReconfigurationQuerySupported = false;
3252 ret = true;
3253 break;
3254 default:
3255 ALOGV("%s: Reconfiguration query failed: %d", __FUNCTION__, callStatus);
3256 ret = true;
3257 }
3258 } else {
3259 ALOGE("%s: Unexpected binder error: %s", __FUNCTION__, err.description().c_str());
3260 ret = true;
3261 }
3262 }
3263
3264 return ret;
3265}
3266
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003267status_t Camera3Device::HalInterface::configureStreams(const camera_metadata_t *sessionParams,
Emilian Peevf4816702020-04-03 15:44:51 -07003268 camera_stream_configuration *config, const std::vector<uint32_t>& bufferSizes) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003269 ATRACE_NAME("CameraHal::configureStreams");
3270 if (!valid()) return INVALID_OPERATION;
3271 status_t res = OK;
3272
Shuzhen Wang83bff122020-11-20 15:51:39 -08003273 if (config->input_is_multi_resolution && mHidlSession_3_7 == nullptr) {
3274 ALOGE("%s: Camera device doesn't support multi-resolution input stream", __FUNCTION__);
3275 return BAD_VALUE;
3276 }
3277
Emilian Peev31abd0a2017-05-11 18:37:46 +01003278 // Convert stream config to HIDL
3279 std::set<int> activeStreams;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003280 device::V3_2::StreamConfiguration requestedConfiguration3_2;
3281 device::V3_4::StreamConfiguration requestedConfiguration3_4;
Shuzhen Wang83bff122020-11-20 15:51:39 -08003282 device::V3_7::StreamConfiguration requestedConfiguration3_7;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003283 requestedConfiguration3_2.streams.resize(config->num_streams);
3284 requestedConfiguration3_4.streams.resize(config->num_streams);
Shuzhen Wang83bff122020-11-20 15:51:39 -08003285 requestedConfiguration3_7.streams.resize(config->num_streams);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003286 for (size_t i = 0; i < config->num_streams; i++) {
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003287 device::V3_2::Stream &dst3_2 = requestedConfiguration3_2.streams[i];
3288 device::V3_4::Stream &dst3_4 = requestedConfiguration3_4.streams[i];
Shuzhen Wang83bff122020-11-20 15:51:39 -08003289 device::V3_7::Stream &dst3_7 = requestedConfiguration3_7.streams[i];
Emilian Peevf4816702020-04-03 15:44:51 -07003290 camera3::camera_stream_t *src = config->streams[i];
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003291
Emilian Peev31abd0a2017-05-11 18:37:46 +01003292 Camera3Stream* cam3stream = Camera3Stream::cast(src);
3293 cam3stream->setBufferFreedListener(this);
3294 int streamId = cam3stream->getId();
3295 StreamType streamType;
3296 switch (src->stream_type) {
Emilian Peevf4816702020-04-03 15:44:51 -07003297 case CAMERA_STREAM_OUTPUT:
Emilian Peev31abd0a2017-05-11 18:37:46 +01003298 streamType = StreamType::OUTPUT;
3299 break;
Emilian Peevf4816702020-04-03 15:44:51 -07003300 case CAMERA_STREAM_INPUT:
Emilian Peev31abd0a2017-05-11 18:37:46 +01003301 streamType = StreamType::INPUT;
3302 break;
3303 default:
3304 ALOGE("%s: Stream %d: Unsupported stream type %d",
3305 __FUNCTION__, streamId, config->streams[i]->stream_type);
3306 return BAD_VALUE;
3307 }
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003308 dst3_2.id = streamId;
3309 dst3_2.streamType = streamType;
3310 dst3_2.width = src->width;
3311 dst3_2.height = src->height;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003312 dst3_2.usage = mapToConsumerUsage(cam3stream->getUsage());
Emilian Peevf4816702020-04-03 15:44:51 -07003313 dst3_2.rotation = mapToStreamRotation((camera_stream_rotation_t) src->rotation);
Shuzhen Wang92653952019-05-07 15:11:43 -07003314 // For HidlSession version 3.5 or newer, the format and dataSpace sent
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08003315 // to HAL are original, not the overridden ones.
Shuzhen Wang92653952019-05-07 15:11:43 -07003316 if (mHidlSession_3_5 != nullptr) {
3317 dst3_2.format = mapToPixelFormat(cam3stream->isFormatOverridden() ?
3318 cam3stream->getOriginalFormat() : src->format);
3319 dst3_2.dataSpace = mapToHidlDataspace(cam3stream->isDataSpaceOverridden() ?
3320 cam3stream->getOriginalDataSpace() : src->data_space);
3321 } else {
3322 dst3_2.format = mapToPixelFormat(src->format);
3323 dst3_2.dataSpace = mapToHidlDataspace(src->data_space);
3324 }
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003325 dst3_4.v3_2 = dst3_2;
Emilian Peev192ee832018-01-31 14:46:47 +00003326 dst3_4.bufferSize = bufferSizes[i];
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003327 if (src->physical_camera_id != nullptr) {
3328 dst3_4.physicalCameraId = src->physical_camera_id;
3329 }
Shuzhen Wang83bff122020-11-20 15:51:39 -08003330 dst3_7.v3_4 = dst3_4;
3331 dst3_7.groupId = cam3stream->getHalStreamGroupId();
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08003332 dst3_7.sensorPixelModesUsed.resize(src->sensor_pixel_modes_used.size());
3333 size_t j = 0;
3334 for (int mode : src->sensor_pixel_modes_used) {
3335 dst3_7.sensorPixelModesUsed[j++] =
3336 static_cast<CameraMetadataEnumAndroidSensorPixelMode>(mode);
3337 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003338 activeStreams.insert(streamId);
3339 // Create Buffer ID map if necessary
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003340 mBufferRecords.tryCreateBufferCache(streamId);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003341 }
3342 // remove BufferIdMap for deleted streams
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003343 mBufferRecords.removeInactiveBufferCaches(activeStreams);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003344
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003345 StreamConfigurationMode operationMode;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003346 res = mapToStreamConfigurationMode(
Emilian Peevf4816702020-04-03 15:44:51 -07003347 (camera_stream_configuration_mode_t) config->operation_mode,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003348 /*out*/ &operationMode);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003349 if (res != OK) {
3350 return res;
3351 }
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003352 requestedConfiguration3_2.operationMode = operationMode;
3353 requestedConfiguration3_4.operationMode = operationMode;
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08003354 requestedConfiguration3_7.operationMode = operationMode;
3355 size_t sessionParamSize = get_camera_metadata_size(sessionParams);
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003356 requestedConfiguration3_4.sessionParams.setToExternal(
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003357 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(sessionParams)),
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08003358 sessionParamSize);
Shuzhen Wang83bff122020-11-20 15:51:39 -08003359 requestedConfiguration3_7.operationMode = operationMode;
3360 requestedConfiguration3_7.sessionParams.setToExternal(
3361 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(sessionParams)),
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08003362 sessionParamSize);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003363
Emilian Peev31abd0a2017-05-11 18:37:46 +01003364 // Invoke configureStreams
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003365 device::V3_3::HalStreamConfiguration finalConfiguration;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003366 device::V3_4::HalStreamConfiguration finalConfiguration3_4;
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003367 device::V3_6::HalStreamConfiguration finalConfiguration3_6;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003368 common::V1_0::Status status;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003369
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003370 auto configStream34Cb = [&status, &finalConfiguration3_4]
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003371 (common::V1_0::Status s, const device::V3_4::HalStreamConfiguration& halConfiguration) {
3372 finalConfiguration3_4 = halConfiguration;
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003373 status = s;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003374 };
3375
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003376 auto configStream36Cb = [&status, &finalConfiguration3_6]
3377 (common::V1_0::Status s, const device::V3_6::HalStreamConfiguration& halConfiguration) {
3378 finalConfiguration3_6 = halConfiguration;
3379 status = s;
3380 };
3381
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003382 auto postprocConfigStream34 = [&finalConfiguration, &finalConfiguration3_4]
3383 (hardware::Return<void>& err) -> status_t {
3384 if (!err.isOk()) {
3385 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3386 return DEAD_OBJECT;
3387 }
3388 finalConfiguration.streams.resize(finalConfiguration3_4.streams.size());
3389 for (size_t i = 0; i < finalConfiguration3_4.streams.size(); i++) {
3390 finalConfiguration.streams[i] = finalConfiguration3_4.streams[i].v3_3;
3391 }
3392 return OK;
3393 };
3394
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003395 auto postprocConfigStream36 = [&finalConfiguration, &finalConfiguration3_6]
3396 (hardware::Return<void>& err) -> status_t {
3397 if (!err.isOk()) {
3398 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3399 return DEAD_OBJECT;
3400 }
3401 finalConfiguration.streams.resize(finalConfiguration3_6.streams.size());
3402 for (size_t i = 0; i < finalConfiguration3_6.streams.size(); i++) {
3403 finalConfiguration.streams[i] = finalConfiguration3_6.streams[i].v3_4.v3_3;
3404 }
3405 return OK;
3406 };
3407
Shuzhen Wang92653952019-05-07 15:11:43 -07003408 // See which version of HAL we have
Shuzhen Wang83bff122020-11-20 15:51:39 -08003409 if (mHidlSession_3_7 != nullptr) {
3410 ALOGV("%s: v3.7 device found", __FUNCTION__);
3411 requestedConfiguration3_7.streamConfigCounter = mNextStreamConfigCounter++;
3412 requestedConfiguration3_7.multiResolutionInputImage = config->input_is_multi_resolution;
3413 auto err = mHidlSession_3_7->configureStreams_3_7(
3414 requestedConfiguration3_7, configStream36Cb);
3415 res = postprocConfigStream36(err);
3416 if (res != OK) {
3417 return res;
3418 }
3419 } else if (mHidlSession_3_6 != nullptr) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003420 ALOGV("%s: v3.6 device found", __FUNCTION__);
3421 device::V3_5::StreamConfiguration requestedConfiguration3_5;
3422 requestedConfiguration3_5.v3_4 = requestedConfiguration3_4;
3423 requestedConfiguration3_5.streamConfigCounter = mNextStreamConfigCounter++;
3424 auto err = mHidlSession_3_6->configureStreams_3_6(
3425 requestedConfiguration3_5, configStream36Cb);
3426 res = postprocConfigStream36(err);
3427 if (res != OK) {
3428 return res;
3429 }
3430 } else if (mHidlSession_3_5 != nullptr) {
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003431 ALOGV("%s: v3.5 device found", __FUNCTION__);
3432 device::V3_5::StreamConfiguration requestedConfiguration3_5;
3433 requestedConfiguration3_5.v3_4 = requestedConfiguration3_4;
3434 requestedConfiguration3_5.streamConfigCounter = mNextStreamConfigCounter++;
3435 auto err = mHidlSession_3_5->configureStreams_3_5(
3436 requestedConfiguration3_5, configStream34Cb);
3437 res = postprocConfigStream34(err);
3438 if (res != OK) {
3439 return res;
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003440 }
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003441 } else if (mHidlSession_3_4 != nullptr) {
3442 // We do; use v3.4 for the call
3443 ALOGV("%s: v3.4 device found", __FUNCTION__);
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003444 auto err = mHidlSession_3_4->configureStreams_3_4(
3445 requestedConfiguration3_4, configStream34Cb);
3446 res = postprocConfigStream34(err);
3447 if (res != OK) {
3448 return res;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003449 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003450 } else if (mHidlSession_3_3 != nullptr) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003451 // We do; use v3.3 for the call
3452 ALOGV("%s: v3.3 device found", __FUNCTION__);
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003453 auto err = mHidlSession_3_3->configureStreams_3_3(requestedConfiguration3_2,
Emilian Peev31abd0a2017-05-11 18:37:46 +01003454 [&status, &finalConfiguration]
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003455 (common::V1_0::Status s, const device::V3_3::HalStreamConfiguration& halConfiguration) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003456 finalConfiguration = halConfiguration;
3457 status = s;
3458 });
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003459 if (!err.isOk()) {
3460 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3461 return DEAD_OBJECT;
3462 }
3463 } else {
3464 // We don't; use v3.2 call and construct a v3.3 HalStreamConfiguration
3465 ALOGV("%s: v3.2 device found", __FUNCTION__);
3466 HalStreamConfiguration finalConfiguration_3_2;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003467 auto err = mHidlSession->configureStreams(requestedConfiguration3_2,
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003468 [&status, &finalConfiguration_3_2]
3469 (common::V1_0::Status s, const HalStreamConfiguration& halConfiguration) {
3470 finalConfiguration_3_2 = halConfiguration;
3471 status = s;
3472 });
3473 if (!err.isOk()) {
3474 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3475 return DEAD_OBJECT;
3476 }
3477 finalConfiguration.streams.resize(finalConfiguration_3_2.streams.size());
3478 for (size_t i = 0; i < finalConfiguration_3_2.streams.size(); i++) {
3479 finalConfiguration.streams[i].v3_2 = finalConfiguration_3_2.streams[i];
3480 finalConfiguration.streams[i].overrideDataSpace =
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003481 requestedConfiguration3_2.streams[i].dataSpace;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003482 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003483 }
3484
3485 if (status != common::V1_0::Status::OK ) {
3486 return CameraProviderManager::mapToStatusT(status);
3487 }
3488
3489 // And convert output stream configuration from HIDL
3490
3491 for (size_t i = 0; i < config->num_streams; i++) {
Emilian Peevf4816702020-04-03 15:44:51 -07003492 camera3::camera_stream_t *dst = config->streams[i];
Emilian Peev31abd0a2017-05-11 18:37:46 +01003493 int streamId = Camera3Stream::cast(dst)->getId();
3494
3495 // Start scan at i, with the assumption that the stream order matches
3496 size_t realIdx = i;
3497 bool found = false;
Eino-Ville Talvala370875f2019-04-12 12:40:27 -07003498 size_t halStreamCount = finalConfiguration.streams.size();
3499 for (size_t idx = 0; idx < halStreamCount; idx++) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003500 if (finalConfiguration.streams[realIdx].v3_2.id == streamId) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003501 found = true;
3502 break;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003503 }
Eino-Ville Talvala370875f2019-04-12 12:40:27 -07003504 realIdx = (realIdx >= halStreamCount - 1) ? 0 : realIdx + 1;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003505 }
3506 if (!found) {
3507 ALOGE("%s: Stream %d not found in stream configuration response from HAL",
3508 __FUNCTION__, streamId);
3509 return INVALID_OPERATION;
3510 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003511 device::V3_3::HalStream &src = finalConfiguration.streams[realIdx];
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003512 device::V3_6::HalStream &src_36 = finalConfiguration3_6.streams[realIdx];
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003513
Emilian Peev710c1422017-08-30 11:19:38 +01003514 Camera3Stream* dstStream = Camera3Stream::cast(dst);
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003515 int overrideFormat = mapToFrameworkFormat(src.v3_2.overrideFormat);
3516 android_dataspace overrideDataSpace = mapToFrameworkDataspace(src.overrideDataSpace);
3517
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003518 if (mHidlSession_3_6 != nullptr) {
3519 dstStream->setOfflineProcessingSupport(src_36.supportOffline);
3520 }
3521
Yin-Chia Yeh90667662019-07-01 15:45:00 -07003522 if (dstStream->getOriginalFormat() != HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
Shuzhen Wang92653952019-05-07 15:11:43 -07003523 dstStream->setFormatOverride(false);
3524 dstStream->setDataSpaceOverride(false);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003525 if (dst->format != overrideFormat) {
3526 ALOGE("%s: Stream %d: Format override not allowed for format 0x%x", __FUNCTION__,
3527 streamId, dst->format);
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003528 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003529 if (dst->data_space != overrideDataSpace) {
3530 ALOGE("%s: Stream %d: DataSpace override not allowed for format 0x%x", __FUNCTION__,
3531 streamId, dst->format);
3532 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003533 } else {
Shuzhen Wang92653952019-05-07 15:11:43 -07003534 bool needFormatOverride =
3535 requestedConfiguration3_2.streams[i].format != src.v3_2.overrideFormat;
3536 bool needDataspaceOverride =
3537 requestedConfiguration3_2.streams[i].dataSpace != src.overrideDataSpace;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003538 // Override allowed with IMPLEMENTATION_DEFINED
Shuzhen Wang92653952019-05-07 15:11:43 -07003539 dstStream->setFormatOverride(needFormatOverride);
3540 dstStream->setDataSpaceOverride(needDataspaceOverride);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003541 dst->format = overrideFormat;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003542 dst->data_space = overrideDataSpace;
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003543 }
3544
Emilian Peevf4816702020-04-03 15:44:51 -07003545 if (dst->stream_type == CAMERA_STREAM_INPUT) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003546 if (src.v3_2.producerUsage != 0) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003547 ALOGE("%s: Stream %d: INPUT streams must have 0 for producer usage",
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003548 __FUNCTION__, streamId);
3549 return INVALID_OPERATION;
3550 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003551 dstStream->setUsage(
3552 mapConsumerToFrameworkUsage(src.v3_2.consumerUsage));
Emilian Peev31abd0a2017-05-11 18:37:46 +01003553 } else {
3554 // OUTPUT
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003555 if (src.v3_2.consumerUsage != 0) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003556 ALOGE("%s: Stream %d: OUTPUT streams must have 0 for consumer usage",
3557 __FUNCTION__, streamId);
3558 return INVALID_OPERATION;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003559 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003560 dstStream->setUsage(
3561 mapProducerToFrameworkUsage(src.v3_2.producerUsage));
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003562 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003563 dst->max_buffers = src.v3_2.maxBuffers;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003564 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003565
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003566 return res;
3567}
3568
Cliff Wuc2ad9c82021-04-21 00:58:58 +08003569status_t Camera3Device::HalInterface::configureInjectedStreams(
3570 const camera_metadata_t* sessionParams, camera_stream_configuration* config,
3571 const std::vector<uint32_t>& bufferSizes,
3572 const CameraMetadata& cameraCharacteristics) {
3573 ATRACE_NAME("InjectionCameraHal::configureStreams");
3574 if (!valid()) return INVALID_OPERATION;
3575 status_t res = OK;
3576
3577 if (config->input_is_multi_resolution) {
3578 ALOGE("%s: Injection camera device doesn't support multi-resolution input "
3579 "stream", __FUNCTION__);
3580 return BAD_VALUE;
3581 }
3582
3583 // Convert stream config to HIDL
3584 std::set<int> activeStreams;
3585 device::V3_2::StreamConfiguration requestedConfiguration3_2;
3586 device::V3_4::StreamConfiguration requestedConfiguration3_4;
3587 device::V3_7::StreamConfiguration requestedConfiguration3_7;
3588 requestedConfiguration3_2.streams.resize(config->num_streams);
3589 requestedConfiguration3_4.streams.resize(config->num_streams);
3590 requestedConfiguration3_7.streams.resize(config->num_streams);
3591 for (size_t i = 0; i < config->num_streams; i++) {
3592 device::V3_2::Stream& dst3_2 = requestedConfiguration3_2.streams[i];
3593 device::V3_4::Stream& dst3_4 = requestedConfiguration3_4.streams[i];
3594 device::V3_7::Stream& dst3_7 = requestedConfiguration3_7.streams[i];
3595 camera3::camera_stream_t* src = config->streams[i];
3596
3597 Camera3Stream* cam3stream = Camera3Stream::cast(src);
3598 cam3stream->setBufferFreedListener(this);
3599 int streamId = cam3stream->getId();
3600 StreamType streamType;
3601 switch (src->stream_type) {
3602 case CAMERA_STREAM_OUTPUT:
3603 streamType = StreamType::OUTPUT;
3604 break;
3605 case CAMERA_STREAM_INPUT:
3606 streamType = StreamType::INPUT;
3607 break;
3608 default:
3609 ALOGE("%s: Stream %d: Unsupported stream type %d", __FUNCTION__,
3610 streamId, config->streams[i]->stream_type);
3611 return BAD_VALUE;
3612 }
3613 dst3_2.id = streamId;
3614 dst3_2.streamType = streamType;
3615 dst3_2.width = src->width;
3616 dst3_2.height = src->height;
3617 dst3_2.usage = mapToConsumerUsage(cam3stream->getUsage());
3618 dst3_2.rotation =
3619 mapToStreamRotation((camera_stream_rotation_t)src->rotation);
3620 // For HidlSession version 3.5 or newer, the format and dataSpace sent
3621 // to HAL are original, not the overridden ones.
3622 if (mHidlSession_3_5 != nullptr) {
3623 dst3_2.format = mapToPixelFormat(cam3stream->isFormatOverridden()
3624 ? cam3stream->getOriginalFormat()
3625 : src->format);
3626 dst3_2.dataSpace =
3627 mapToHidlDataspace(cam3stream->isDataSpaceOverridden()
3628 ? cam3stream->getOriginalDataSpace()
3629 : src->data_space);
3630 } else {
3631 dst3_2.format = mapToPixelFormat(src->format);
3632 dst3_2.dataSpace = mapToHidlDataspace(src->data_space);
3633 }
3634 dst3_4.v3_2 = dst3_2;
3635 dst3_4.bufferSize = bufferSizes[i];
3636 if (src->physical_camera_id != nullptr) {
3637 dst3_4.physicalCameraId = src->physical_camera_id;
3638 }
3639 dst3_7.v3_4 = dst3_4;
3640 dst3_7.groupId = cam3stream->getHalStreamGroupId();
3641 dst3_7.sensorPixelModesUsed.resize(src->sensor_pixel_modes_used.size());
3642 size_t j = 0;
3643 for (int mode : src->sensor_pixel_modes_used) {
3644 dst3_7.sensorPixelModesUsed[j++] =
3645 static_cast<CameraMetadataEnumAndroidSensorPixelMode>(mode);
3646 }
3647 activeStreams.insert(streamId);
3648 // Create Buffer ID map if necessary
3649 mBufferRecords.tryCreateBufferCache(streamId);
3650 }
3651 // remove BufferIdMap for deleted streams
3652 mBufferRecords.removeInactiveBufferCaches(activeStreams);
3653
3654 StreamConfigurationMode operationMode;
3655 res = mapToStreamConfigurationMode(
3656 (camera_stream_configuration_mode_t)config->operation_mode,
3657 /*out*/ &operationMode);
3658 if (res != OK) {
3659 return res;
3660 }
3661 requestedConfiguration3_7.operationMode = operationMode;
3662 size_t sessionParamSize = get_camera_metadata_size(sessionParams);
3663 requestedConfiguration3_7.operationMode = operationMode;
3664 requestedConfiguration3_7.sessionParams.setToExternal(
3665 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(sessionParams)),
3666 sessionParamSize);
3667
3668 // See which version of HAL we have
3669 if (mHidlSession_3_7 != nullptr) {
3670 requestedConfiguration3_7.streamConfigCounter = mNextStreamConfigCounter++;
3671 requestedConfiguration3_7.multiResolutionInputImage =
3672 config->input_is_multi_resolution;
3673
3674 const camera_metadata_t* rawMetadata = cameraCharacteristics.getAndLock();
3675 ::android::hardware::camera::device::V3_2::CameraMetadata hidlChars = {};
3676 hidlChars.setToExternal(
3677 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(rawMetadata)),
3678 get_camera_metadata_size(rawMetadata));
3679 cameraCharacteristics.unlock(rawMetadata);
3680
3681 sp<hardware::camera::device::V3_7::ICameraInjectionSession>
3682 hidlInjectionSession_3_7;
3683 auto castInjectionResult_3_7 =
3684 device::V3_7::ICameraInjectionSession::castFrom(mHidlSession_3_7);
3685 if (castInjectionResult_3_7.isOk()) {
3686 hidlInjectionSession_3_7 = castInjectionResult_3_7;
3687 } else {
3688 ALOGE("%s: Transaction error: %s", __FUNCTION__,
3689 castInjectionResult_3_7.description().c_str());
3690 return DEAD_OBJECT;
3691 }
3692
3693 auto err = hidlInjectionSession_3_7->configureInjectionStreams(
3694 requestedConfiguration3_7, hidlChars);
3695 if (!err.isOk()) {
3696 ALOGE("%s: Transaction error: %s", __FUNCTION__,
3697 err.description().c_str());
3698 return DEAD_OBJECT;
3699 }
3700 } else {
3701 ALOGE("%s: mHidlSession_3_7 does not exist, the lowest version of injection "
3702 "session is 3.7", __FUNCTION__);
3703 return DEAD_OBJECT;
3704 }
3705
3706 return res;
3707}
3708
Emilian Peevf4816702020-04-03 15:44:51 -07003709status_t Camera3Device::HalInterface::wrapAsHidlRequest(camera_capture_request_t* request,
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003710 /*out*/device::V3_2::CaptureRequest* captureRequest,
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003711 /*out*/std::vector<native_handle_t*>* handlesCreated,
3712 /*out*/std::vector<std::pair<int32_t, int32_t>>* inflightBuffers) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003713 ATRACE_CALL();
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003714 if (captureRequest == nullptr || handlesCreated == nullptr || inflightBuffers == nullptr) {
3715 ALOGE("%s: captureRequest (%p), handlesCreated (%p), and inflightBuffers(%p) "
3716 "must not be null", __FUNCTION__, captureRequest, handlesCreated, inflightBuffers);
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003717 return BAD_VALUE;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003718 }
3719
3720 captureRequest->frameNumber = request->frame_number;
Yifan Hongf79b5542017-04-11 14:44:25 -07003721
3722 captureRequest->fmqSettingsSize = 0;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003723
3724 {
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003725 if (request->input_buffer != nullptr) {
3726 int32_t streamId = Camera3Stream::cast(request->input_buffer->stream)->getId();
3727 buffer_handle_t buf = *(request->input_buffer->buffer);
3728 auto pair = getBufferId(buf, streamId);
3729 bool isNewBuffer = pair.first;
3730 uint64_t bufferId = pair.second;
3731 captureRequest->inputBuffer.streamId = streamId;
3732 captureRequest->inputBuffer.bufferId = bufferId;
3733 captureRequest->inputBuffer.buffer = (isNewBuffer) ? buf : nullptr;
3734 captureRequest->inputBuffer.status = BufferStatus::OK;
3735 native_handle_t *acquireFence = nullptr;
3736 if (request->input_buffer->acquire_fence != -1) {
3737 acquireFence = native_handle_create(1,0);
3738 acquireFence->data[0] = request->input_buffer->acquire_fence;
3739 handlesCreated->push_back(acquireFence);
3740 }
3741 captureRequest->inputBuffer.acquireFence = acquireFence;
3742 captureRequest->inputBuffer.releaseFence = nullptr;
3743
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003744 mBufferRecords.pushInflightBuffer(captureRequest->frameNumber, streamId,
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003745 request->input_buffer->buffer);
3746 inflightBuffers->push_back(std::make_pair(captureRequest->frameNumber, streamId));
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003747 } else {
3748 captureRequest->inputBuffer.streamId = -1;
3749 captureRequest->inputBuffer.bufferId = BUFFER_ID_NO_BUFFER;
3750 }
3751
3752 captureRequest->outputBuffers.resize(request->num_output_buffers);
3753 for (size_t i = 0; i < request->num_output_buffers; i++) {
Emilian Peevf4816702020-04-03 15:44:51 -07003754 const camera_stream_buffer_t *src = request->output_buffers + i;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003755 StreamBuffer &dst = captureRequest->outputBuffers[i];
3756 int32_t streamId = Camera3Stream::cast(src->stream)->getId();
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003757 if (src->buffer != nullptr) {
3758 buffer_handle_t buf = *(src->buffer);
3759 auto pair = getBufferId(buf, streamId);
3760 bool isNewBuffer = pair.first;
3761 dst.bufferId = pair.second;
3762 dst.buffer = isNewBuffer ? buf : nullptr;
3763 native_handle_t *acquireFence = nullptr;
3764 if (src->acquire_fence != -1) {
3765 acquireFence = native_handle_create(1,0);
3766 acquireFence->data[0] = src->acquire_fence;
3767 handlesCreated->push_back(acquireFence);
3768 }
3769 dst.acquireFence = acquireFence;
3770 } else if (mUseHalBufManager) {
3771 // HAL buffer management path
3772 dst.bufferId = BUFFER_ID_NO_BUFFER;
3773 dst.buffer = nullptr;
3774 dst.acquireFence = nullptr;
3775 } else {
3776 ALOGE("%s: cannot send a null buffer in capture request!", __FUNCTION__);
3777 return BAD_VALUE;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003778 }
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003779 dst.streamId = streamId;
3780 dst.status = BufferStatus::OK;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003781 dst.releaseFence = nullptr;
3782
Yin-Chia Yeh5f840f82019-03-05 11:59:04 -08003783 // Output buffers are empty when using HAL buffer manager
3784 if (!mUseHalBufManager) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003785 mBufferRecords.pushInflightBuffer(
3786 captureRequest->frameNumber, streamId, src->buffer);
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003787 inflightBuffers->push_back(std::make_pair(captureRequest->frameNumber, streamId));
Yin-Chia Yeh5f840f82019-03-05 11:59:04 -08003788 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003789 }
3790 }
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003791 return OK;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003792}
3793
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003794void Camera3Device::HalInterface::cleanupNativeHandles(
3795 std::vector<native_handle_t*> *handles, bool closeFd) {
3796 if (handles == nullptr) {
3797 return;
3798 }
3799 if (closeFd) {
3800 for (auto& handle : *handles) {
3801 native_handle_close(handle);
3802 }
3803 }
3804 for (auto& handle : *handles) {
3805 native_handle_delete(handle);
3806 }
3807 handles->clear();
3808 return;
3809}
3810
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003811status_t Camera3Device::HalInterface::processBatchCaptureRequests(
Emilian Peevf4816702020-04-03 15:44:51 -07003812 std::vector<camera_capture_request_t*>& requests,/*out*/uint32_t* numRequestProcessed) {
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003813 ATRACE_NAME("CameraHal::processBatchCaptureRequests");
3814 if (!valid()) return INVALID_OPERATION;
3815
Emilian Peevaebbe412018-01-15 13:53:24 +00003816 sp<device::V3_4::ICameraDeviceSession> hidlSession_3_4;
Shuzhen Wang83bff122020-11-20 15:51:39 -08003817 sp<device::V3_7::ICameraDeviceSession> hidlSession_3_7;
3818 auto castResult_3_7 = device::V3_7::ICameraDeviceSession::castFrom(mHidlSession);
3819 if (castResult_3_7.isOk()) {
3820 hidlSession_3_7 = castResult_3_7;
3821 }
Emilian Peevaebbe412018-01-15 13:53:24 +00003822 auto castResult_3_4 = device::V3_4::ICameraDeviceSession::castFrom(mHidlSession);
3823 if (castResult_3_4.isOk()) {
3824 hidlSession_3_4 = castResult_3_4;
3825 }
3826
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003827 hardware::hidl_vec<device::V3_2::CaptureRequest> captureRequests;
Emilian Peevaebbe412018-01-15 13:53:24 +00003828 hardware::hidl_vec<device::V3_4::CaptureRequest> captureRequests_3_4;
Shuzhen Wang83bff122020-11-20 15:51:39 -08003829 hardware::hidl_vec<device::V3_7::CaptureRequest> captureRequests_3_7;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003830 size_t batchSize = requests.size();
Shuzhen Wang83bff122020-11-20 15:51:39 -08003831 if (hidlSession_3_7 != nullptr) {
3832 captureRequests_3_7.resize(batchSize);
3833 } else if (hidlSession_3_4 != nullptr) {
Emilian Peevaebbe412018-01-15 13:53:24 +00003834 captureRequests_3_4.resize(batchSize);
3835 } else {
3836 captureRequests.resize(batchSize);
3837 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003838 std::vector<native_handle_t*> handlesCreated;
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003839 std::vector<std::pair<int32_t, int32_t>> inflightBuffers;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003840
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003841 status_t res = OK;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003842 for (size_t i = 0; i < batchSize; i++) {
Shuzhen Wang83bff122020-11-20 15:51:39 -08003843 if (hidlSession_3_7 != nullptr) {
3844 res = wrapAsHidlRequest(requests[i], /*out*/&captureRequests_3_7[i].v3_4.v3_2,
3845 /*out*/&handlesCreated, /*out*/&inflightBuffers);
3846 } else if (hidlSession_3_4 != nullptr) {
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003847 res = wrapAsHidlRequest(requests[i], /*out*/&captureRequests_3_4[i].v3_2,
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003848 /*out*/&handlesCreated, /*out*/&inflightBuffers);
Emilian Peevaebbe412018-01-15 13:53:24 +00003849 } else {
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003850 res = wrapAsHidlRequest(requests[i], /*out*/&captureRequests[i],
3851 /*out*/&handlesCreated, /*out*/&inflightBuffers);
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003852 }
3853 if (res != OK) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003854 mBufferRecords.popInflightBuffers(inflightBuffers);
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003855 cleanupNativeHandles(&handlesCreated);
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003856 return res;
Emilian Peevaebbe412018-01-15 13:53:24 +00003857 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003858 }
3859
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003860 std::vector<device::V3_2::BufferCache> cachesToRemove;
3861 {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003862 std::lock_guard<std::mutex> lock(mFreedBuffersLock);
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003863 for (auto& pair : mFreedBuffers) {
3864 // The stream might have been removed since onBufferFreed
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003865 if (mBufferRecords.isStreamCached(pair.first)) {
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003866 cachesToRemove.push_back({pair.first, pair.second});
3867 }
3868 }
3869 mFreedBuffers.clear();
3870 }
3871
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003872 common::V1_0::Status status = common::V1_0::Status::INTERNAL_ERROR;
3873 *numRequestProcessed = 0;
Yifan Hongf79b5542017-04-11 14:44:25 -07003874
3875 // Write metadata to FMQ.
3876 for (size_t i = 0; i < batchSize; i++) {
Emilian Peevf4816702020-04-03 15:44:51 -07003877 camera_capture_request_t* request = requests[i];
Emilian Peevaebbe412018-01-15 13:53:24 +00003878 device::V3_2::CaptureRequest* captureRequest;
Shuzhen Wang83bff122020-11-20 15:51:39 -08003879 if (hidlSession_3_7 != nullptr) {
3880 captureRequest = &captureRequests_3_7[i].v3_4.v3_2;
3881 } else if (hidlSession_3_4 != nullptr) {
Emilian Peevaebbe412018-01-15 13:53:24 +00003882 captureRequest = &captureRequests_3_4[i].v3_2;
3883 } else {
3884 captureRequest = &captureRequests[i];
3885 }
Yifan Hongf79b5542017-04-11 14:44:25 -07003886
3887 if (request->settings != nullptr) {
3888 size_t settingsSize = get_camera_metadata_size(request->settings);
3889 if (mRequestMetadataQueue != nullptr && mRequestMetadataQueue->write(
3890 reinterpret_cast<const uint8_t*>(request->settings), settingsSize)) {
3891 captureRequest->settings.resize(0);
3892 captureRequest->fmqSettingsSize = settingsSize;
3893 } else {
3894 if (mRequestMetadataQueue != nullptr) {
3895 ALOGW("%s: couldn't utilize fmq, fallback to hwbinder", __FUNCTION__);
3896 }
3897 captureRequest->settings.setToExternal(
3898 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(request->settings)),
3899 get_camera_metadata_size(request->settings));
3900 captureRequest->fmqSettingsSize = 0u;
3901 }
3902 } else {
3903 // A null request settings maps to a size-0 CameraMetadata
3904 captureRequest->settings.resize(0);
3905 captureRequest->fmqSettingsSize = 0u;
3906 }
Emilian Peevaebbe412018-01-15 13:53:24 +00003907
Shuzhen Wang83bff122020-11-20 15:51:39 -08003908 // hidl session 3.7 specific handling.
3909 if (hidlSession_3_7 != nullptr) {
3910 captureRequests_3_7[i].inputWidth = request->input_width;
3911 captureRequests_3_7[i].inputHeight = request->input_height;
3912 }
3913
3914 // hidl session 3.7 and 3.4 specific handling.
3915 if (hidlSession_3_7 != nullptr || hidlSession_3_4 != nullptr) {
3916 hardware::hidl_vec<device::V3_4::PhysicalCameraSetting>& physicalCameraSettings =
3917 (hidlSession_3_7 != nullptr) ?
3918 captureRequests_3_7[i].v3_4.physicalCameraSettings :
3919 captureRequests_3_4[i].physicalCameraSettings;
3920 physicalCameraSettings.resize(request->num_physcam_settings);
Emilian Peevaebbe412018-01-15 13:53:24 +00003921 for (size_t j = 0; j < request->num_physcam_settings; j++) {
Emilian Peev00420d22018-02-05 21:33:13 +00003922 if (request->physcam_settings != nullptr) {
3923 size_t settingsSize = get_camera_metadata_size(request->physcam_settings[j]);
3924 if (mRequestMetadataQueue != nullptr && mRequestMetadataQueue->write(
3925 reinterpret_cast<const uint8_t*>(request->physcam_settings[j]),
3926 settingsSize)) {
Shuzhen Wang83bff122020-11-20 15:51:39 -08003927 physicalCameraSettings[j].settings.resize(0);
3928 physicalCameraSettings[j].fmqSettingsSize = settingsSize;
Emilian Peev00420d22018-02-05 21:33:13 +00003929 } else {
3930 if (mRequestMetadataQueue != nullptr) {
3931 ALOGW("%s: couldn't utilize fmq, fallback to hwbinder", __FUNCTION__);
3932 }
Shuzhen Wang83bff122020-11-20 15:51:39 -08003933 physicalCameraSettings[j].settings.setToExternal(
Emilian Peev00420d22018-02-05 21:33:13 +00003934 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(
3935 request->physcam_settings[j])),
3936 get_camera_metadata_size(request->physcam_settings[j]));
Shuzhen Wang83bff122020-11-20 15:51:39 -08003937 physicalCameraSettings[j].fmqSettingsSize = 0u;
Emilian Peevaebbe412018-01-15 13:53:24 +00003938 }
Emilian Peev00420d22018-02-05 21:33:13 +00003939 } else {
Yin-Chia Yeha2849702021-03-10 10:11:33 -08003940 physicalCameraSettings[j].fmqSettingsSize = 0u;
3941 physicalCameraSettings[j].settings.resize(0);
Emilian Peevaebbe412018-01-15 13:53:24 +00003942 }
Shuzhen Wang83bff122020-11-20 15:51:39 -08003943 physicalCameraSettings[j].physicalCameraId = request->physcam_id[j];
Emilian Peevaebbe412018-01-15 13:53:24 +00003944 }
3945 }
Yifan Hongf79b5542017-04-11 14:44:25 -07003946 }
Emilian Peevaebbe412018-01-15 13:53:24 +00003947
3948 hardware::details::return_status err;
Jayant Chowdharyc8d581e2018-07-16 14:46:23 -07003949 auto resultCallback =
3950 [&status, &numRequestProcessed] (auto s, uint32_t n) {
3951 status = s;
3952 *numRequestProcessed = n;
3953 };
Shuzhen Wang83bff122020-11-20 15:51:39 -08003954 if (hidlSession_3_7 != nullptr) {
3955 err = hidlSession_3_7->processCaptureRequest_3_7(captureRequests_3_7, cachesToRemove,
3956 resultCallback);
3957 } else if (hidlSession_3_4 != nullptr) {
Emilian Peevaebbe412018-01-15 13:53:24 +00003958 err = hidlSession_3_4->processCaptureRequest_3_4(captureRequests_3_4, cachesToRemove,
Jayant Chowdharyc8d581e2018-07-16 14:46:23 -07003959 resultCallback);
Emilian Peevaebbe412018-01-15 13:53:24 +00003960 } else {
3961 err = mHidlSession->processCaptureRequest(captureRequests, cachesToRemove,
Jayant Chowdharyc8d581e2018-07-16 14:46:23 -07003962 resultCallback);
Emilian Peevaebbe412018-01-15 13:53:24 +00003963 }
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -07003964 if (!err.isOk()) {
3965 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003966 status = common::V1_0::Status::CAMERA_DISCONNECTED;
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -07003967 }
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003968
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003969 if (status == common::V1_0::Status::OK && *numRequestProcessed != batchSize) {
3970 ALOGE("%s: processCaptureRequest returns OK but processed %d/%zu requests",
3971 __FUNCTION__, *numRequestProcessed, batchSize);
3972 status = common::V1_0::Status::INTERNAL_ERROR;
3973 }
3974
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003975 res = CameraProviderManager::mapToStatusT(status);
3976 if (res == OK) {
3977 if (mHidlSession->isRemote()) {
3978 // Only close acquire fence FDs when the HIDL transaction succeeds (so the FDs have been
3979 // sent to camera HAL processes)
3980 cleanupNativeHandles(&handlesCreated, /*closeFd*/true);
3981 } else {
3982 // In passthrough mode the FDs are now owned by HAL
3983 cleanupNativeHandles(&handlesCreated);
3984 }
3985 } else {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003986 mBufferRecords.popInflightBuffers(inflightBuffers);
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003987 cleanupNativeHandles(&handlesCreated);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003988 }
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003989 return res;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003990}
3991
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003992status_t Camera3Device::HalInterface::flush() {
3993 ATRACE_NAME("CameraHal::flush");
3994 if (!valid()) return INVALID_OPERATION;
3995 status_t res = OK;
3996
Emilian Peev31abd0a2017-05-11 18:37:46 +01003997 auto err = mHidlSession->flush();
3998 if (!err.isOk()) {
3999 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
4000 res = DEAD_OBJECT;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004001 } else {
Emilian Peev31abd0a2017-05-11 18:37:46 +01004002 res = CameraProviderManager::mapToStatusT(err);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004003 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01004004
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004005 return res;
4006}
4007
Emilian Peev31abd0a2017-05-11 18:37:46 +01004008status_t Camera3Device::HalInterface::dump(int /*fd*/) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004009 ATRACE_NAME("CameraHal::dump");
4010 if (!valid()) return INVALID_OPERATION;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004011
Emilian Peev31abd0a2017-05-11 18:37:46 +01004012 // Handled by CameraProviderManager::dump
4013
4014 return OK;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004015}
4016
4017status_t Camera3Device::HalInterface::close() {
4018 ATRACE_NAME("CameraHal::close()");
4019 if (!valid()) return INVALID_OPERATION;
4020 status_t res = OK;
4021
Emilian Peev31abd0a2017-05-11 18:37:46 +01004022 auto err = mHidlSession->close();
4023 // Interface will be dead shortly anyway, so don't log errors
4024 if (!err.isOk()) {
4025 res = DEAD_OBJECT;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004026 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01004027
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004028 return res;
4029}
4030
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004031void Camera3Device::HalInterface::signalPipelineDrain(const std::vector<int>& streamIds) {
4032 ATRACE_NAME("CameraHal::signalPipelineDrain");
4033 if (!valid() || mHidlSession_3_5 == nullptr) {
4034 ALOGE("%s called on invalid camera!", __FUNCTION__);
4035 return;
4036 }
4037
Yin-Chia Yehc300a072019-02-13 14:56:57 -08004038 auto err = mHidlSession_3_5->signalStreamFlush(streamIds, mNextStreamConfigCounter - 1);
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004039 if (!err.isOk()) {
4040 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
4041 return;
4042 }
4043}
4044
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004045status_t Camera3Device::HalInterface::switchToOffline(
4046 const std::vector<int32_t>& streamsToKeep,
4047 /*out*/hardware::camera::device::V3_6::CameraOfflineSessionInfo* offlineSessionInfo,
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004048 /*out*/sp<hardware::camera::device::V3_6::ICameraOfflineSession>* offlineSession,
4049 /*out*/camera3::BufferRecords* bufferRecords) {
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004050 ATRACE_NAME("CameraHal::switchToOffline");
4051 if (!valid() || mHidlSession_3_6 == nullptr) {
4052 ALOGE("%s called on invalid camera!", __FUNCTION__);
4053 return INVALID_OPERATION;
4054 }
4055
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004056 if (offlineSessionInfo == nullptr || offlineSession == nullptr || bufferRecords == nullptr) {
4057 ALOGE("%s: output arguments must not be null!", __FUNCTION__);
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004058 return INVALID_OPERATION;
4059 }
4060
4061 common::V1_0::Status status = common::V1_0::Status::INTERNAL_ERROR;
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004062 auto resultCallback =
4063 [&status, &offlineSessionInfo, &offlineSession] (auto s, auto info, auto session) {
4064 status = s;
4065 *offlineSessionInfo = info;
4066 *offlineSession = session;
4067 };
4068 auto err = mHidlSession_3_6->switchToOffline(streamsToKeep, resultCallback);
4069
4070 if (!err.isOk()) {
4071 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
4072 return DEAD_OBJECT;
4073 }
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004074
4075 status_t ret = CameraProviderManager::mapToStatusT(status);
4076 if (ret != OK) {
4077 return ret;
4078 }
4079
4080 // TODO: assert no ongoing requestBuffer/returnBuffer call here
4081 // TODO: update RequestBufferStateMachine to block requestBuffer/returnBuffer once HAL
4082 // returns from switchToOffline.
4083
4084
4085 // Validate buffer caches
4086 std::vector<int32_t> streams;
4087 streams.reserve(offlineSessionInfo->offlineStreams.size());
4088 for (auto offlineStream : offlineSessionInfo->offlineStreams) {
4089 int32_t id = offlineStream.id;
4090 streams.push_back(id);
4091 // Verify buffer caches
4092 std::vector<uint64_t> bufIds(offlineStream.circulatingBufferIds.begin(),
4093 offlineStream.circulatingBufferIds.end());
4094 if (!verifyBufferIds(id, bufIds)) {
4095 ALOGE("%s: stream ID %d buffer cache records mismatch!", __FUNCTION__, id);
4096 return UNKNOWN_ERROR;
4097 }
4098 }
4099
4100 // Move buffer records
4101 bufferRecords->takeBufferCaches(mBufferRecords, streams);
4102 bufferRecords->takeInflightBufferMap(mBufferRecords);
4103 bufferRecords->takeRequestedBufferMap(mBufferRecords);
4104 return ret;
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004105}
4106
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07004107void Camera3Device::HalInterface::getInflightBufferKeys(
4108 std::vector<std::pair<int32_t, int32_t>>* out) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004109 mBufferRecords.getInflightBufferKeys(out);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07004110 return;
4111}
4112
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08004113void Camera3Device::HalInterface::getInflightRequestBufferKeys(
4114 std::vector<uint64_t>* out) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004115 mBufferRecords.getInflightRequestBufferKeys(out);
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08004116 return;
4117}
4118
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004119bool Camera3Device::HalInterface::verifyBufferIds(
4120 int32_t streamId, std::vector<uint64_t>& bufIds) {
4121 return mBufferRecords.verifyBufferIds(streamId, bufIds);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004122}
4123
4124status_t Camera3Device::HalInterface::popInflightBuffer(
Yin-Chia Yehf4650602017-01-10 13:13:39 -08004125 int32_t frameNumber, int32_t streamId,
4126 /*out*/ buffer_handle_t **buffer) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004127 return mBufferRecords.popInflightBuffer(frameNumber, streamId, buffer);
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07004128}
4129
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004130status_t Camera3Device::HalInterface::pushInflightRequestBuffer(
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08004131 uint64_t bufferId, buffer_handle_t* buf, int32_t streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004132 return mBufferRecords.pushInflightRequestBuffer(bufferId, buf, streamId);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004133}
4134
4135// Find and pop a buffer_handle_t based on bufferId
4136status_t Camera3Device::HalInterface::popInflightRequestBuffer(
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08004137 uint64_t bufferId,
4138 /*out*/ buffer_handle_t** buffer,
4139 /*optional out*/ int32_t* streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004140 return mBufferRecords.popInflightRequestBuffer(bufferId, buffer, streamId);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004141}
4142
Yin-Chia Yeh77327052017-01-09 18:23:07 -08004143std::pair<bool, uint64_t> Camera3Device::HalInterface::getBufferId(
4144 const buffer_handle_t& buf, int streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004145 return mBufferRecords.getBufferId(buf, streamId);
Yin-Chia Yeh77327052017-01-09 18:23:07 -08004146}
4147
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07004148void Camera3Device::HalInterface::onBufferFreed(
4149 int streamId, const native_handle_t* handle) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004150 uint32_t bufferId = mBufferRecords.removeOneBufferCache(streamId, handle);
4151 std::lock_guard<std::mutex> lock(mFreedBuffersLock);
4152 if (bufferId != BUFFER_ID_NO_BUFFER) {
4153 mFreedBuffers.push_back(std::make_pair(streamId, bufferId));
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07004154 }
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07004155}
4156
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07004157void Camera3Device::HalInterface::onStreamReConfigured(int streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004158 std::vector<uint64_t> bufIds = mBufferRecords.clearBufferCaches(streamId);
4159 std::lock_guard<std::mutex> lock(mFreedBuffersLock);
4160 for (auto bufferId : bufIds) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07004161 mFreedBuffers.push_back(std::make_pair(streamId, bufferId));
4162 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07004163}
4164
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004165/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004166 * RequestThread inner class methods
4167 */
4168
4169Camera3Device::RequestThread::RequestThread(wp<Camera3Device> parent,
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004170 sp<StatusTracker> statusTracker,
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004171 sp<HalInterface> interface, const Vector<int32_t>& sessionParamKeys,
Eino-Ville Talvala1646c3c2021-07-29 13:48:40 -07004172 bool useHalBufManager,
4173 bool supportCameraMute) :
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004174 Thread(/*canCallJava*/false),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004175 mParent(parent),
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004176 mStatusTracker(statusTracker),
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004177 mInterface(interface),
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07004178 mListener(nullptr),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004179 mId(getId(parent)),
Shuzhen Wang316781a2020-08-18 18:11:01 -07004180 mFirstRepeating(false),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004181 mReconfigured(false),
4182 mDoPause(false),
4183 mPaused(true),
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004184 mNotifyPipelineDrain(false),
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004185 mFrameNumber(0),
Jianing Weicb0652e2014-03-12 18:29:36 -07004186 mLatestRequestId(NAME_NOT_FOUND),
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07004187 mCurrentAfTriggerId(0),
4188 mCurrentPreCaptureTriggerId(0),
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004189 mRotateAndCropOverride(ANDROID_SCALER_ROTATE_AND_CROP_NONE),
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) {
Jayant Chowdharycd277cd2021-08-11 15:48:40 -07004594 int32_t inputStreamId = -1;
4595 if (halRequest.input_buffer != nullptr) {
4596 inputStreamId = Camera3Stream::cast(halRequest.input_buffer->stream)->getId();
4597 }
4598
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004599 parent->monitorMetadata(TagMonitor::REQUEST,
Shuzhen Wang83bff122020-11-20 15:51:39 -08004600 halRequest.frame_number,
Jayant Chowdharyc30b4c32021-08-18 11:43:16 -07004601 0, mLatestRequest, mLatestPhysicalRequest, halRequest.output_buffers,
4602 halRequest.num_output_buffers, inputStreamId);
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004603 }
4604 }
4605
Shuzhen Wang83bff122020-11-20 15:51:39 -08004606 if (halRequest.settings != NULL) {
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004607 nextRequest.captureRequest->mSettingsList.begin()->metadata.unlock(
Shuzhen Wang83bff122020-11-20 15:51:39 -08004608 halRequest.settings);
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004609 }
4610
Shuzhen Wang83bff122020-11-20 15:51:39 -08004611 cleanupPhysicalSettings(nextRequest.captureRequest, &halRequest);
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004612}
4613
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004614bool Camera3Device::RequestThread::updateSessionParameters(const CameraMetadata& settings) {
4615 ATRACE_CALL();
4616 bool updatesDetected = false;
4617
Emilian Peev4ec17882019-01-24 17:16:58 -08004618 CameraMetadata updatedParams(mLatestSessionParams);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004619 for (auto tag : mSessionParamKeys) {
4620 camera_metadata_ro_entry entry = settings.find(tag);
Emilian Peev4ec17882019-01-24 17:16:58 -08004621 camera_metadata_entry lastEntry = updatedParams.find(tag);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004622
4623 if (entry.count > 0) {
4624 bool isDifferent = false;
4625 if (lastEntry.count > 0) {
4626 // Have a last value, compare to see if changed
4627 if (lastEntry.type == entry.type &&
4628 lastEntry.count == entry.count) {
4629 // Same type and count, compare values
4630 size_t bytesPerValue = camera_metadata_type_size[lastEntry.type];
4631 size_t entryBytes = bytesPerValue * lastEntry.count;
4632 int cmp = memcmp(entry.data.u8, lastEntry.data.u8, entryBytes);
4633 if (cmp != 0) {
4634 isDifferent = true;
4635 }
4636 } else {
4637 // Count or type has changed
4638 isDifferent = true;
4639 }
4640 } else {
4641 // No last entry, so always consider to be different
4642 isDifferent = true;
4643 }
4644
4645 if (isDifferent) {
4646 ALOGV("%s: Session parameter tag id %d changed", __FUNCTION__, tag);
Emilian Peeva14b4dd2018-05-15 11:00:31 +01004647 if (!skipHFRTargetFPSUpdate(tag, entry, lastEntry)) {
4648 updatesDetected = true;
4649 }
Emilian Peev4ec17882019-01-24 17:16:58 -08004650 updatedParams.update(entry);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004651 }
4652 } else if (lastEntry.count > 0) {
4653 // Value has been removed
4654 ALOGV("%s: Session parameter tag id %d removed", __FUNCTION__, tag);
Emilian Peev4ec17882019-01-24 17:16:58 -08004655 updatedParams.erase(tag);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004656 updatesDetected = true;
4657 }
4658 }
4659
Emilian Peev4ec17882019-01-24 17:16:58 -08004660 bool reconfigureRequired;
4661 if (updatesDetected) {
4662 reconfigureRequired = mInterface->isReconfigurationRequired(mLatestSessionParams,
4663 updatedParams);
4664 mLatestSessionParams = updatedParams;
4665 } else {
4666 reconfigureRequired = false;
4667 }
4668
4669 return reconfigureRequired;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004670}
4671
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004672bool Camera3Device::RequestThread::threadLoop() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004673 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004674 status_t res;
Jayant Chowdhary37eca242019-11-18 08:55:56 -08004675 // Any function called from threadLoop() must not hold mInterfaceLock since
4676 // it could lead to deadlocks (disconnect() -> hold mInterfaceMutex -> wait for request thread
4677 // to finish -> request thread waits on mInterfaceMutex) http://b/143513518
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004678
4679 // Handle paused state.
4680 if (waitIfPaused()) {
4681 return true;
4682 }
4683
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004684 // Wait for the next batch of requests.
4685 waitForNextRequestBatch();
4686 if (mNextRequests.size() == 0) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004687 return true;
4688 }
4689
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004690 // Get the latest request ID, if any
4691 int latestRequestId;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004692 camera_metadata_entry_t requestIdEntry = mNextRequests[mNextRequests.size() - 1].
Emilian Peevaebbe412018-01-15 13:53:24 +00004693 captureRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_ID);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004694 if (requestIdEntry.count > 0) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004695 latestRequestId = requestIdEntry.data.i32[0];
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004696 } else {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004697 ALOGW("%s: Did not have android.request.id set in the request.", __FUNCTION__);
4698 latestRequestId = NAME_NOT_FOUND;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004699 }
4700
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004701 // 'mNextRequests' will at this point contain either a set of HFR batched requests
4702 // or a single request from streaming or burst. In either case the first element
4703 // should contain the latest camera settings that we need to check for any session
4704 // parameter updates.
Emilian Peevaebbe412018-01-15 13:53:24 +00004705 if (updateSessionParameters(mNextRequests[0].captureRequest->mSettingsList.begin()->metadata)) {
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004706 res = OK;
4707
4708 //Input stream buffers are already acquired at this point so an input stream
4709 //will not be able to move to idle state unless we force it.
4710 if (mNextRequests[0].captureRequest->mInputStream != nullptr) {
4711 res = mNextRequests[0].captureRequest->mInputStream->forceToIdle();
4712 if (res != OK) {
4713 ALOGE("%s: Failed to force idle input stream: %d", __FUNCTION__, res);
4714 cleanUpFailedRequests(/*sendRequestError*/ false);
4715 return false;
4716 }
4717 }
4718
4719 if (res == OK) {
Emilian Peev3bead5f2020-05-28 17:29:08 -07004720 sp<Camera3Device> parent = mParent.promote();
4721 if (parent != nullptr) {
4722 mReconfigured |= parent->reconfigureCamera(mLatestSessionParams, mStatusId);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004723 }
Emilian Peev3bead5f2020-05-28 17:29:08 -07004724 setPaused(false);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004725
4726 if (mNextRequests[0].captureRequest->mInputStream != nullptr) {
4727 mNextRequests[0].captureRequest->mInputStream->restoreConfiguredState();
4728 if (res != OK) {
4729 ALOGE("%s: Failed to restore configured input stream: %d", __FUNCTION__, res);
4730 cleanUpFailedRequests(/*sendRequestError*/ false);
4731 return false;
4732 }
4733 }
4734 }
4735 }
4736
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004737 // Prepare a batch of HAL requests and output buffers.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004738 res = prepareHalRequests();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004739 if (res == TIMED_OUT) {
4740 // Not a fatal error if getting output buffers time out.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004741 cleanUpFailedRequests(/*sendRequestError*/ true);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004742 // Check if any stream is abandoned.
4743 checkAndStopRepeatingRequest();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004744 return true;
4745 } else if (res != OK) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004746 cleanUpFailedRequests(/*sendRequestError*/ false);
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004747 return false;
4748 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004749
Zhijun Hecc27e112013-10-03 16:12:43 -07004750 // Inform waitUntilRequestProcessed thread of a new request ID
4751 {
4752 Mutex::Autolock al(mLatestRequestMutex);
4753
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004754 mLatestRequestId = latestRequestId;
Zhijun Hecc27e112013-10-03 16:12:43 -07004755 mLatestRequestSignal.signal();
4756 }
4757
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004758 // Submit a batch of requests to HAL.
4759 // Use flush lock only when submitting multilple requests in a batch.
4760 // TODO: The problem with flush lock is flush() will be blocked by process_capture_request()
4761 // which may take a long time to finish so synchronizing flush() and
4762 // process_capture_request() defeats the purpose of cancelling requests ASAP with flush().
4763 // For now, only synchronize for high speed recording and we should figure something out for
4764 // removing the synchronization.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004765 bool useFlushLock = mNextRequests.size() > 1;
Eino-Ville Talvala17a61ad2013-06-03 16:53:32 -07004766
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004767 if (useFlushLock) {
4768 mFlushLock.lock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004769 }
4770
Zhijun Hef0645c12016-08-02 00:58:11 -07004771 ALOGVV("%s: %d: submitting %zu requests in a batch.", __FUNCTION__, __LINE__,
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004772 mNextRequests.size());
Igor Murashkin1e479c02013-09-06 16:55:14 -07004773
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08004774 sp<Camera3Device> parent = mParent.promote();
4775 if (parent != nullptr) {
4776 parent->mRequestBufferSM.onSubmittingRequest();
4777 }
4778
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004779 bool submitRequestSuccess = false;
Shuzhen Wang686f6442017-06-20 16:16:04 -07004780 nsecs_t tRequestStart = systemTime(SYSTEM_TIME_MONOTONIC);
Yin-Chia Yeh11648852019-05-16 10:42:54 -07004781 submitRequestSuccess = sendRequestsBatch();
4782
Shuzhen Wang686f6442017-06-20 16:16:04 -07004783 nsecs_t tRequestEnd = systemTime(SYSTEM_TIME_MONOTONIC);
4784 mRequestLatency.add(tRequestStart, tRequestEnd);
Igor Murashkin1e479c02013-09-06 16:55:14 -07004785
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004786 if (useFlushLock) {
4787 mFlushLock.unlock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004788 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004789
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004790 // Unset as current request
4791 {
4792 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004793 mNextRequests.clear();
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004794 }
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004795 mRequestSubmittedSignal.signal();
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004796
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004797 return submitRequestSuccess;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004798}
4799
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004800status_t Camera3Device::RequestThread::prepareHalRequests() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004801 ATRACE_CALL();
4802
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07004803 bool batchedRequest = mNextRequests[0].captureRequest->mBatchSize > 1;
Shuzhen Wang4a472662017-02-26 23:29:04 -08004804 for (size_t i = 0; i < mNextRequests.size(); i++) {
4805 auto& nextRequest = mNextRequests.editItemAt(i);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004806 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
Emilian Peevf4816702020-04-03 15:44:51 -07004807 camera_capture_request_t* halRequest = &nextRequest.halRequest;
4808 Vector<camera_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004809
4810 // Prepare a request to HAL
4811 halRequest->frame_number = captureRequest->mResultExtras.frameNumber;
4812
4813 // Insert any queued triggers (before metadata is locked)
4814 status_t res = insertTriggers(captureRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004815 if (res < 0) {
4816 SET_ERR("RequestThread: Unable to insert triggers "
4817 "(capture request %d, HAL device: %s (%d)",
4818 halRequest->frame_number, strerror(-res), res);
4819 return INVALID_OPERATION;
4820 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07004821
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004822 int triggerCount = res;
4823 bool triggersMixedIn = (triggerCount > 0 || mPrevTriggers > 0);
4824 mPrevTriggers = triggerCount;
4825
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004826 bool rotateAndCropChanged = overrideAutoRotateAndCrop(captureRequest);
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004827 bool testPatternChanged = overrideTestPattern(captureRequest);
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004828
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004829 // If the request is the same as last, or we had triggers now or last time or
4830 // changing overrides this time
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004831 bool newRequest =
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004832 (mPrevRequest != captureRequest || triggersMixedIn ||
4833 rotateAndCropChanged || testPatternChanged) &&
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07004834 // Request settings are all the same within one batch, so only treat the first
4835 // request in a batch as new
Zhijun He54c36822018-07-18 09:33:39 -07004836 !(batchedRequest && i > 0);
Emilian Peev00420d22018-02-05 21:33:13 +00004837 if (newRequest) {
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08004838 std::set<std::string> cameraIdsWithZoom;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004839 /**
4840 * HAL workaround:
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004841 * Insert a fake trigger ID if a trigger is set but no trigger ID is
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004842 */
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004843 res = addFakeTriggerIds(captureRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004844 if (res != OK) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004845 SET_ERR("RequestThread: Unable to insert fake trigger IDs "
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004846 "(capture request %d, HAL device: %s (%d)",
4847 halRequest->frame_number, strerror(-res), res);
4848 return INVALID_OPERATION;
4849 }
4850
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07004851 {
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07004852 sp<Camera3Device> parent = mParent.promote();
4853 if (parent != nullptr) {
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -07004854 List<PhysicalCameraSettings>::iterator it;
4855 for (it = captureRequest->mSettingsList.begin();
4856 it != captureRequest->mSettingsList.end(); it++) {
Jayant Chowdhary9255ce02021-07-15 11:18:17 -07004857 if (parent->mUHRCropAndMeteringRegionMappers.find(it->cameraId) ==
4858 parent->mUHRCropAndMeteringRegionMappers.end()) {
4859 continue;
4860 }
4861
4862 if (!captureRequest->mUHRCropAndMeteringRegionsUpdated) {
4863 res = parent->mUHRCropAndMeteringRegionMappers[it->cameraId].
4864 updateCaptureRequest(&(it->metadata));
4865 if (res != OK) {
4866 SET_ERR("RequestThread: Unable to correct capture requests "
4867 "for scaler crop region and metering regions for request "
4868 "%d: %s (%d)", halRequest->frame_number, strerror(-res),
4869 res);
4870 return INVALID_OPERATION;
4871 }
4872 captureRequest->mUHRCropAndMeteringRegionsUpdated = true;
4873 }
4874 }
4875
4876 // Correct metadata regions for distortion correction if enabled
4877 for (it = captureRequest->mSettingsList.begin();
4878 it != captureRequest->mSettingsList.end(); it++) {
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -07004879 if (parent->mDistortionMappers.find(it->cameraId) ==
4880 parent->mDistortionMappers.end()) {
4881 continue;
4882 }
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07004883
4884 if (!captureRequest->mDistortionCorrectionUpdated) {
4885 res = parent->mDistortionMappers[it->cameraId].correctCaptureRequest(
4886 &(it->metadata));
4887 if (res != OK) {
4888 SET_ERR("RequestThread: Unable to correct capture requests "
4889 "for lens distortion for request %d: %s (%d)",
4890 halRequest->frame_number, strerror(-res), res);
4891 return INVALID_OPERATION;
4892 }
4893 captureRequest->mDistortionCorrectionUpdated = true;
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -07004894 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07004895 }
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08004896
4897 for (it = captureRequest->mSettingsList.begin();
4898 it != captureRequest->mSettingsList.end(); it++) {
4899 if (parent->mZoomRatioMappers.find(it->cameraId) ==
4900 parent->mZoomRatioMappers.end()) {
4901 continue;
4902 }
4903
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07004904 if (!captureRequest->mZoomRatioIs1x) {
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08004905 cameraIdsWithZoom.insert(it->cameraId);
4906 }
4907
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07004908 if (!captureRequest->mZoomRatioUpdated) {
4909 res = parent->mZoomRatioMappers[it->cameraId].updateCaptureRequest(
4910 &(it->metadata));
4911 if (res != OK) {
4912 SET_ERR("RequestThread: Unable to correct capture requests "
4913 "for zoom ratio for request %d: %s (%d)",
4914 halRequest->frame_number, strerror(-res), res);
4915 return INVALID_OPERATION;
4916 }
4917 captureRequest->mZoomRatioUpdated = true;
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08004918 }
4919 }
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07004920 if (captureRequest->mRotateAndCropAuto &&
4921 !captureRequest->mRotationAndCropUpdated) {
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004922 for (it = captureRequest->mSettingsList.begin();
4923 it != captureRequest->mSettingsList.end(); it++) {
4924 auto mapper = parent->mRotateAndCropMappers.find(it->cameraId);
4925 if (mapper != parent->mRotateAndCropMappers.end()) {
4926 res = mapper->second.updateCaptureRequest(&(it->metadata));
4927 if (res != OK) {
4928 SET_ERR("RequestThread: Unable to correct capture requests "
4929 "for rotate-and-crop for request %d: %s (%d)",
4930 halRequest->frame_number, strerror(-res), res);
4931 return INVALID_OPERATION;
4932 }
4933 }
4934 }
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07004935 captureRequest->mRotationAndCropUpdated = true;
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004936 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07004937 }
4938 }
4939
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004940 /**
4941 * The request should be presorted so accesses in HAL
4942 * are O(logn). Sidenote, sorting a sorted metadata is nop.
4943 */
Emilian Peevaebbe412018-01-15 13:53:24 +00004944 captureRequest->mSettingsList.begin()->metadata.sort();
4945 halRequest->settings = captureRequest->mSettingsList.begin()->metadata.getAndLock();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004946 mPrevRequest = captureRequest;
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08004947 mPrevCameraIdsWithZoom = cameraIdsWithZoom;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004948 ALOGVV("%s: Request settings are NEW", __FUNCTION__);
4949
4950 IF_ALOGV() {
4951 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
4952 find_camera_metadata_ro_entry(
4953 halRequest->settings,
4954 ANDROID_CONTROL_AF_TRIGGER,
4955 &e
4956 );
4957 if (e.count > 0) {
4958 ALOGV("%s: Request (frame num %d) had AF trigger 0x%x",
4959 __FUNCTION__,
4960 halRequest->frame_number,
4961 e.data.u8[0]);
4962 }
4963 }
4964 } else {
4965 // leave request.settings NULL to indicate 'reuse latest given'
4966 ALOGVV("%s: Request settings are REUSED",
4967 __FUNCTION__);
4968 }
4969
Emilian Peevaebbe412018-01-15 13:53:24 +00004970 if (captureRequest->mSettingsList.size() > 1) {
4971 halRequest->num_physcam_settings = captureRequest->mSettingsList.size() - 1;
4972 halRequest->physcam_id = new const char* [halRequest->num_physcam_settings];
Emilian Peev00420d22018-02-05 21:33:13 +00004973 if (newRequest) {
4974 halRequest->physcam_settings =
4975 new const camera_metadata* [halRequest->num_physcam_settings];
4976 } else {
4977 halRequest->physcam_settings = nullptr;
4978 }
Emilian Peevaebbe412018-01-15 13:53:24 +00004979 auto it = ++captureRequest->mSettingsList.begin();
4980 size_t i = 0;
4981 for (; it != captureRequest->mSettingsList.end(); it++, i++) {
4982 halRequest->physcam_id[i] = it->cameraId.c_str();
Emilian Peev00420d22018-02-05 21:33:13 +00004983 if (newRequest) {
4984 it->metadata.sort();
4985 halRequest->physcam_settings[i] = it->metadata.getAndLock();
4986 }
Emilian Peevaebbe412018-01-15 13:53:24 +00004987 }
4988 }
4989
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004990 uint32_t totalNumBuffers = 0;
4991
4992 // Fill in buffers
4993 if (captureRequest->mInputStream != NULL) {
4994 halRequest->input_buffer = &captureRequest->mInputBuffer;
Shuzhen Wang83bff122020-11-20 15:51:39 -08004995
4996 halRequest->input_width = captureRequest->mInputBufferSize.width;
4997 halRequest->input_height = captureRequest->mInputBufferSize.height;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004998 totalNumBuffers += 1;
4999 } else {
5000 halRequest->input_buffer = NULL;
5001 }
5002
Emilian Peevf4816702020-04-03 15:44:51 -07005003 outputBuffers->insertAt(camera_stream_buffer_t(), 0,
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005004 captureRequest->mOutputStreams.size());
5005 halRequest->output_buffers = outputBuffers->array();
Shuzhen Wang99080502021-03-07 21:08:20 -08005006 std::set<std::set<String8>> requestedPhysicalCameras;
Yin-Chia Yehb3a80b12018-09-04 12:13:05 -07005007
5008 sp<Camera3Device> parent = mParent.promote();
5009 if (parent == NULL) {
5010 // Should not happen, and nowhere to send errors to, so just log it
5011 CLOGE("RequestThread: Parent is gone");
5012 return INVALID_OPERATION;
5013 }
5014 nsecs_t waitDuration = kBaseGetBufferWait + parent->getExpectedInFlightDuration();
5015
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005016 SurfaceMap uniqueSurfaceIdMap;
Shuzhen Wang4a472662017-02-26 23:29:04 -08005017 for (size_t j = 0; j < captureRequest->mOutputStreams.size(); j++) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005018 sp<Camera3OutputStreamInterface> outputStream =
5019 captureRequest->mOutputStreams.editItemAt(j);
5020 int streamId = outputStream->getId();
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07005021
5022 // Prepare video buffers for high speed recording on the first video request.
5023 if (mPrepareVideoStream && outputStream->isVideoStream()) {
5024 // Only try to prepare video stream on the first video request.
5025 mPrepareVideoStream = false;
5026
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07005027 res = outputStream->startPrepare(Camera3StreamInterface::ALLOCATE_PIPELINE_MAX,
5028 false /*blockRequest*/);
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07005029 while (res == NOT_ENOUGH_DATA) {
5030 res = outputStream->prepareNextBuffer();
5031 }
5032 if (res != OK) {
5033 ALOGW("%s: Preparing video buffers for high speed failed: %s (%d)",
5034 __FUNCTION__, strerror(-res), res);
5035 outputStream->cancelPrepare();
5036 }
5037 }
5038
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005039 std::vector<size_t> uniqueSurfaceIds;
5040 res = outputStream->getUniqueSurfaceIds(
5041 captureRequest->mOutputSurfaces[streamId],
5042 &uniqueSurfaceIds);
5043 // INVALID_OPERATION is normal output for streams not supporting surfaceIds
5044 if (res != OK && res != INVALID_OPERATION) {
5045 ALOGE("%s: failed to query stream %d unique surface IDs",
5046 __FUNCTION__, streamId);
5047 return res;
5048 }
5049 if (res == OK) {
5050 uniqueSurfaceIdMap.insert({streamId, std::move(uniqueSurfaceIds)});
5051 }
5052
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07005053 if (mUseHalBufManager) {
Yin-Chia Yeh110342b2018-11-19 11:47:46 -08005054 if (outputStream->isAbandoned()) {
Yin-Chia Yeha1b56c82019-03-27 15:50:39 -07005055 ALOGV("%s: stream %d is abandoned, skipping request", __FUNCTION__, streamId);
Yin-Chia Yeh110342b2018-11-19 11:47:46 -08005056 return TIMED_OUT;
5057 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07005058 // HAL will request buffer through requestStreamBuffer API
Emilian Peevf4816702020-04-03 15:44:51 -07005059 camera_stream_buffer_t& buffer = outputBuffers->editItemAt(j);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07005060 buffer.stream = outputStream->asHalStream();
5061 buffer.buffer = nullptr;
Emilian Peevf4816702020-04-03 15:44:51 -07005062 buffer.status = CAMERA_BUFFER_STATUS_OK;
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07005063 buffer.acquire_fence = -1;
5064 buffer.release_fence = -1;
Emilian Peevf0348ae2021-01-13 13:39:45 -08005065 // Mark the output stream as unpreparable to block clients from calling
5066 // 'prepare' after this request reaches CameraHal and before the respective
5067 // buffers are requested.
5068 outputStream->markUnpreparable();
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07005069 } else {
5070 res = outputStream->getBuffer(&outputBuffers->editItemAt(j),
5071 waitDuration,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005072 captureRequest->mOutputSurfaces[streamId]);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07005073 if (res != OK) {
5074 // Can't get output buffer from gralloc queue - this could be due to
5075 // abandoned queue or other consumer misbehavior, so not a fatal
5076 // error
Yin-Chia Yeha1b56c82019-03-27 15:50:39 -07005077 ALOGV("RequestThread: Can't get output buffer, skipping request:"
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07005078 " %s (%d)", strerror(-res), res);
5079
5080 return TIMED_OUT;
5081 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005082 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08005083
5084 {
5085 sp<Camera3Device> parent = mParent.promote();
5086 if (parent != nullptr) {
5087 const String8& streamCameraId = outputStream->getPhysicalCameraId();
5088 for (const auto& settings : captureRequest->mSettingsList) {
5089 if ((streamCameraId.isEmpty() &&
5090 parent->getId() == settings.cameraId.c_str()) ||
5091 streamCameraId == settings.cameraId.c_str()) {
5092 outputStream->fireBufferRequestForFrameNumber(
5093 captureRequest->mResultExtras.frameNumber,
5094 settings.metadata);
5095 }
5096 }
5097 }
5098 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07005099
Shuzhen Wang5c22c152017-12-31 17:12:25 -08005100 String8 physicalCameraId = outputStream->getPhysicalCameraId();
Shuzhen Wang99080502021-03-07 21:08:20 -08005101 int32_t streamGroupId = outputStream->getHalStreamGroupId();
5102 if (streamGroupId != -1 && mGroupIdPhysicalCameraMap.count(streamGroupId) == 1) {
5103 requestedPhysicalCameras.insert(mGroupIdPhysicalCameraMap[streamGroupId]);
5104 } else if (!physicalCameraId.isEmpty()) {
5105 requestedPhysicalCameras.insert(std::set<String8>({physicalCameraId}));
Shuzhen Wang5c22c152017-12-31 17:12:25 -08005106 }
5107 halRequest->num_output_buffers++;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005108 }
5109 totalNumBuffers += halRequest->num_output_buffers;
5110
5111 // Log request in the in-flight queue
Shuzhen Wang4a472662017-02-26 23:29:04 -08005112 // If this request list is for constrained high speed recording (not
5113 // preview), and the current request is not the last one in the batch,
5114 // do not send callback to the app.
5115 bool hasCallback = true;
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07005116 if (batchedRequest && i != mNextRequests.size()-1) {
Shuzhen Wang4a472662017-02-26 23:29:04 -08005117 hasCallback = false;
5118 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01005119 bool isStillCapture = false;
Shuzhen Wang26abaf42018-08-28 15:41:20 -07005120 bool isZslCapture = false;
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08005121 const camera_metadata_t* settings = halRequest->settings;
5122 bool shouldUnlockSettings = false;
5123 if (settings == nullptr) {
5124 shouldUnlockSettings = true;
5125 settings = captureRequest->mSettingsList.begin()->metadata.getAndLock();
5126 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01005127 if (!mNextRequests[0].captureRequest->mSettingsList.begin()->metadata.isEmpty()) {
5128 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08005129 find_camera_metadata_ro_entry(settings, ANDROID_CONTROL_CAPTURE_INTENT, &e);
Emilian Peev9dd21f42018-08-03 13:39:29 +01005130 if ((e.count > 0) && (e.data.u8[0] == ANDROID_CONTROL_CAPTURE_INTENT_STILL_CAPTURE)) {
5131 isStillCapture = true;
5132 ATRACE_ASYNC_BEGIN("still capture", mNextRequests[i].halRequest.frame_number);
5133 }
Shuzhen Wang26abaf42018-08-28 15:41:20 -07005134
Emilian Peevaf8416e2021-02-04 17:52:43 -08005135 e = camera_metadata_ro_entry_t();
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08005136 find_camera_metadata_ro_entry(settings, ANDROID_CONTROL_ENABLE_ZSL, &e);
Shuzhen Wang26abaf42018-08-28 15:41:20 -07005137 if ((e.count > 0) && (e.data.u8[0] == ANDROID_CONTROL_ENABLE_ZSL_TRUE)) {
5138 isZslCapture = true;
5139 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01005140 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005141 res = parent->registerInFlight(halRequest->frame_number,
5142 totalNumBuffers, captureRequest->mResultExtras,
5143 /*hasInput*/halRequest->input_buffer != NULL,
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07005144 hasCallback,
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08005145 calculateMaxExpectedDuration(settings),
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005146 requestedPhysicalCameras, isStillCapture, isZslCapture,
5147 captureRequest->mRotateAndCropAuto, mPrevCameraIdsWithZoom,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005148 (mUseHalBufManager) ? uniqueSurfaceIdMap :
Shuzhen Wang316781a2020-08-18 18:11:01 -07005149 SurfaceMap{}, captureRequest->mRequestTimeNs);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005150 ALOGVV("%s: registered in flight requestId = %" PRId32 ", frameNumber = %" PRId64
5151 ", burstId = %" PRId32 ".",
5152 __FUNCTION__,
5153 captureRequest->mResultExtras.requestId, captureRequest->mResultExtras.frameNumber,
5154 captureRequest->mResultExtras.burstId);
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08005155
5156 if (shouldUnlockSettings) {
5157 captureRequest->mSettingsList.begin()->metadata.unlock(settings);
5158 }
5159
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005160 if (res != OK) {
5161 SET_ERR("RequestThread: Unable to register new in-flight request:"
5162 " %s (%d)", strerror(-res), res);
5163 return INVALID_OPERATION;
5164 }
5165 }
5166
5167 return OK;
5168}
5169
Igor Murashkin1e479c02013-09-06 16:55:14 -07005170CameraMetadata Camera3Device::RequestThread::getLatestRequest() const {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005171 ATRACE_CALL();
Igor Murashkin1e479c02013-09-06 16:55:14 -07005172 Mutex::Autolock al(mLatestRequestMutex);
5173
5174 ALOGV("RequestThread::%s", __FUNCTION__);
5175
5176 return mLatestRequest;
5177}
5178
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005179bool Camera3Device::RequestThread::isStreamPending(
5180 sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005181 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005182 Mutex::Autolock l(mRequestLock);
5183
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005184 for (const auto& nextRequest : mNextRequests) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005185 if (!nextRequest.submitted) {
5186 for (const auto& s : nextRequest.captureRequest->mOutputStreams) {
5187 if (stream == s) return true;
5188 }
5189 if (stream == nextRequest.captureRequest->mInputStream) return true;
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07005190 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07005191 }
5192
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005193 for (const auto& request : mRequestQueue) {
5194 for (const auto& s : request->mOutputStreams) {
5195 if (stream == s) return true;
5196 }
5197 if (stream == request->mInputStream) return true;
5198 }
5199
5200 for (const auto& request : mRepeatingRequests) {
5201 for (const auto& s : request->mOutputStreams) {
5202 if (stream == s) return true;
5203 }
5204 if (stream == request->mInputStream) return true;
5205 }
5206
5207 return false;
5208}
Jianing Weicb0652e2014-03-12 18:29:36 -07005209
Emilian Peev40ead602017-09-26 15:46:36 +01005210bool Camera3Device::RequestThread::isOutputSurfacePending(int streamId, size_t surfaceId) {
5211 ATRACE_CALL();
5212 Mutex::Autolock l(mRequestLock);
5213
5214 for (const auto& nextRequest : mNextRequests) {
5215 for (const auto& s : nextRequest.captureRequest->mOutputSurfaces) {
5216 if (s.first == streamId) {
5217 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
5218 if (it != s.second.end()) {
5219 return true;
5220 }
5221 }
5222 }
5223 }
5224
5225 for (const auto& request : mRequestQueue) {
5226 for (const auto& s : request->mOutputSurfaces) {
5227 if (s.first == streamId) {
5228 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
5229 if (it != s.second.end()) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005230 return true;
Emilian Peev40ead602017-09-26 15:46:36 +01005231 }
5232 }
5233 }
5234 }
5235
5236 for (const auto& request : mRepeatingRequests) {
5237 for (const auto& s : request->mOutputSurfaces) {
5238 if (s.first == streamId) {
5239 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
5240 if (it != s.second.end()) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005241 return true;
Emilian Peev40ead602017-09-26 15:46:36 +01005242 }
5243 }
5244 }
5245 }
5246
5247 return false;
5248}
5249
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07005250void Camera3Device::RequestThread::signalPipelineDrain(const std::vector<int>& streamIds) {
5251 if (!mUseHalBufManager) {
5252 ALOGE("%s called for camera device not supporting HAL buffer management", __FUNCTION__);
5253 return;
5254 }
5255
5256 Mutex::Autolock pl(mPauseLock);
5257 if (mPaused) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005258 mInterface->signalPipelineDrain(streamIds);
5259 return;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07005260 }
5261 // If request thread is still busy, wait until paused then notify HAL
5262 mNotifyPipelineDrain = true;
5263 mStreamIdsToBeDrained = streamIds;
5264}
5265
Yin-Chia Yehe52b8fa2020-07-28 00:17:58 -07005266void Camera3Device::RequestThread::resetPipelineDrain() {
5267 Mutex::Autolock pl(mPauseLock);
5268 mNotifyPipelineDrain = false;
5269 mStreamIdsToBeDrained.clear();
5270}
5271
Emilian Peevc0fe54c2020-03-11 14:05:07 -07005272void Camera3Device::RequestThread::clearPreviousRequest() {
5273 Mutex::Autolock l(mRequestLock);
5274 mPrevRequest.clear();
5275}
5276
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005277status_t Camera3Device::RequestThread::switchToOffline(
5278 const std::vector<int32_t>& streamsToKeep,
5279 /*out*/hardware::camera::device::V3_6::CameraOfflineSessionInfo* offlineSessionInfo,
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005280 /*out*/sp<hardware::camera::device::V3_6::ICameraOfflineSession>* offlineSession,
5281 /*out*/camera3::BufferRecords* bufferRecords) {
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005282 Mutex::Autolock l(mRequestLock);
5283 clearRepeatingRequestsLocked(/*lastFrameNumber*/nullptr);
5284
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005285 // Wait until request thread is fully stopped
5286 // TBD: check if request thread is being paused by other APIs (shouldn't be)
5287
5288 // We could also check for mRepeatingRequests.empty(), but the API interface
5289 // is serialized by Camera3Device::mInterfaceLock so no one should be able to submit any
5290 // new requests during the call; hence skip that check.
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005291 bool queueEmpty = mNextRequests.empty() && mRequestQueue.empty();
5292 while (!queueEmpty) {
5293 status_t res = mRequestSubmittedSignal.waitRelative(mRequestLock, kRequestSubmitTimeout);
5294 if (res == TIMED_OUT) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005295 ALOGE("%s: request thread failed to submit one request within timeout!", __FUNCTION__);
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005296 return res;
5297 } else if (res != OK) {
5298 ALOGE("%s: request thread failed to submit a request: %s (%d)!",
5299 __FUNCTION__, strerror(-res), res);
5300 return res;
5301 }
5302 queueEmpty = mNextRequests.empty() && mRequestQueue.empty();
5303 }
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005304
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005305 return mInterface->switchToOffline(
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005306 streamsToKeep, offlineSessionInfo, offlineSession, bufferRecords);
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005307}
5308
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005309status_t Camera3Device::RequestThread::setRotateAndCropAutoBehavior(
5310 camera_metadata_enum_android_scaler_rotate_and_crop_t rotateAndCropValue) {
5311 ATRACE_CALL();
5312 Mutex::Autolock l(mTriggerMutex);
5313 if (rotateAndCropValue == ANDROID_SCALER_ROTATE_AND_CROP_AUTO) {
5314 return BAD_VALUE;
5315 }
5316 mRotateAndCropOverride = rotateAndCropValue;
5317 return OK;
5318}
5319
Eino-Ville Talvala11afe4f2021-05-27 14:45:31 -07005320status_t Camera3Device::RequestThread::setCameraMute(int32_t muteMode) {
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005321 ATRACE_CALL();
5322 Mutex::Autolock l(mTriggerMutex);
Eino-Ville Talvala11afe4f2021-05-27 14:45:31 -07005323 if (muteMode != mCameraMute) {
5324 mCameraMute = muteMode;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005325 mCameraMuteChanged = true;
5326 }
5327 return OK;
5328}
5329
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07005330nsecs_t Camera3Device::getExpectedInFlightDuration() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005331 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005332 std::lock_guard<std::mutex> l(mInFlightLock);
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07005333 return mExpectedInflightDuration > kMinInflightDuration ?
5334 mExpectedInflightDuration : kMinInflightDuration;
5335}
5336
Emilian Peevaebbe412018-01-15 13:53:24 +00005337void Camera3Device::RequestThread::cleanupPhysicalSettings(sp<CaptureRequest> request,
Emilian Peevf4816702020-04-03 15:44:51 -07005338 camera_capture_request_t *halRequest) {
Emilian Peevaebbe412018-01-15 13:53:24 +00005339 if ((request == nullptr) || (halRequest == nullptr)) {
5340 ALOGE("%s: Invalid request!", __FUNCTION__);
5341 return;
5342 }
5343
5344 if (halRequest->num_physcam_settings > 0) {
5345 if (halRequest->physcam_id != nullptr) {
5346 delete [] halRequest->physcam_id;
5347 halRequest->physcam_id = nullptr;
5348 }
5349 if (halRequest->physcam_settings != nullptr) {
5350 auto it = ++(request->mSettingsList.begin());
5351 size_t i = 0;
5352 for (; it != request->mSettingsList.end(); it++, i++) {
5353 it->metadata.unlock(halRequest->physcam_settings[i]);
5354 }
5355 delete [] halRequest->physcam_settings;
5356 halRequest->physcam_settings = nullptr;
5357 }
5358 }
5359}
5360
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005361void Camera3Device::RequestThread::cleanUpFailedRequests(bool sendRequestError) {
5362 if (mNextRequests.empty()) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005363 return;
5364 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005365
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005366 for (auto& nextRequest : mNextRequests) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005367 // Skip the ones that have been submitted successfully.
5368 if (nextRequest.submitted) {
5369 continue;
5370 }
5371
5372 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
Emilian Peevf4816702020-04-03 15:44:51 -07005373 camera_capture_request_t* halRequest = &nextRequest.halRequest;
5374 Vector<camera_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005375
5376 if (halRequest->settings != NULL) {
Emilian Peevaebbe412018-01-15 13:53:24 +00005377 captureRequest->mSettingsList.begin()->metadata.unlock(halRequest->settings);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005378 }
5379
Emilian Peevaebbe412018-01-15 13:53:24 +00005380 cleanupPhysicalSettings(captureRequest, halRequest);
5381
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005382 if (captureRequest->mInputStream != NULL) {
Emilian Peevf4816702020-04-03 15:44:51 -07005383 captureRequest->mInputBuffer.status = CAMERA_BUFFER_STATUS_ERROR;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005384 captureRequest->mInputStream->returnInputBuffer(captureRequest->mInputBuffer);
5385 }
5386
Yin-Chia Yeh21cb47b2019-01-18 15:08:17 -08005387 // No output buffer can be returned when using HAL buffer manager
5388 if (!mUseHalBufManager) {
5389 for (size_t i = 0; i < halRequest->num_output_buffers; i++) {
5390 //Buffers that failed processing could still have
5391 //valid acquire fence.
5392 int acquireFence = (*outputBuffers)[i].acquire_fence;
5393 if (0 <= acquireFence) {
5394 close(acquireFence);
5395 outputBuffers->editItemAt(i).acquire_fence = -1;
5396 }
Emilian Peevf4816702020-04-03 15:44:51 -07005397 outputBuffers->editItemAt(i).status = CAMERA_BUFFER_STATUS_ERROR;
Yin-Chia Yeh21cb47b2019-01-18 15:08:17 -08005398 captureRequest->mOutputStreams.editItemAt(i)->returnBuffer((*outputBuffers)[i], 0,
5399 /*timestampIncreasing*/true, std::vector<size_t> (),
5400 captureRequest->mResultExtras.frameNumber);
Emilian Peevc58cf4c2017-05-11 17:23:41 +01005401 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005402 }
5403
5404 if (sendRequestError) {
5405 Mutex::Autolock l(mRequestLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005406 sp<NotificationListener> listener = mListener.promote();
5407 if (listener != NULL) {
5408 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08005409 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005410 captureRequest->mResultExtras);
5411 }
5412 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07005413
5414 // Remove yet-to-be submitted inflight request from inflightMap
5415 {
5416 sp<Camera3Device> parent = mParent.promote();
5417 if (parent != NULL) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005418 std::lock_guard<std::mutex> l(parent->mInFlightLock);
Shuzhen Wangcadb3302016-11-04 14:17:56 -07005419 ssize_t idx = parent->mInFlightMap.indexOfKey(captureRequest->mResultExtras.frameNumber);
5420 if (idx >= 0) {
5421 ALOGV("%s: Remove inflight request from queue: frameNumber %" PRId64,
5422 __FUNCTION__, captureRequest->mResultExtras.frameNumber);
5423 parent->removeInFlightMapEntryLocked(idx);
5424 }
5425 }
5426 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005427 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07005428
5429 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005430 mNextRequests.clear();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005431}
5432
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005433void Camera3Device::RequestThread::waitForNextRequestBatch() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005434 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005435 // Optimized a bit for the simple steady-state case (single repeating
5436 // request), to avoid putting that request in the queue temporarily.
5437 Mutex::Autolock l(mRequestLock);
5438
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005439 assert(mNextRequests.empty());
5440
5441 NextRequest nextRequest;
5442 nextRequest.captureRequest = waitForNextRequestLocked();
5443 if (nextRequest.captureRequest == nullptr) {
5444 return;
5445 }
5446
Emilian Peevf4816702020-04-03 15:44:51 -07005447 nextRequest.halRequest = camera_capture_request_t();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005448 nextRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005449 mNextRequests.add(nextRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005450
5451 // Wait for additional requests
5452 const size_t batchSize = nextRequest.captureRequest->mBatchSize;
5453
5454 for (size_t i = 1; i < batchSize; i++) {
5455 NextRequest additionalRequest;
5456 additionalRequest.captureRequest = waitForNextRequestLocked();
5457 if (additionalRequest.captureRequest == nullptr) {
5458 break;
5459 }
5460
Emilian Peevf4816702020-04-03 15:44:51 -07005461 additionalRequest.halRequest = camera_capture_request_t();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005462 additionalRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005463 mNextRequests.add(additionalRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005464 }
5465
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005466 if (mNextRequests.size() < batchSize) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08005467 ALOGE("RequestThread: only get %zu out of %zu requests. Skipping requests.",
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005468 mNextRequests.size(), batchSize);
5469 cleanUpFailedRequests(/*sendRequestError*/true);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005470 }
5471
5472 return;
5473}
5474
5475sp<Camera3Device::CaptureRequest>
5476 Camera3Device::RequestThread::waitForNextRequestLocked() {
5477 status_t res;
5478 sp<CaptureRequest> nextRequest;
5479
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005480 while (mRequestQueue.empty()) {
5481 if (!mRepeatingRequests.empty()) {
5482 // Always atomically enqueue all requests in a repeating request
5483 // list. Guarantees a complete in-sequence set of captures to
5484 // application.
5485 const RequestList &requests = mRepeatingRequests;
Shuzhen Wang316781a2020-08-18 18:11:01 -07005486 if (mFirstRepeating) {
5487 mFirstRepeating = false;
5488 } else {
5489 for (auto& request : requests) {
5490 // For repeating requests, override timestamp request using
5491 // the time a request is inserted into the request queue,
5492 // because the original repeating request will have an old
5493 // fixed timestamp.
5494 request->mRequestTimeNs = systemTime();
5495 }
5496 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005497 RequestList::const_iterator firstRequest =
5498 requests.begin();
5499 nextRequest = *firstRequest;
5500 mRequestQueue.insert(mRequestQueue.end(),
5501 ++firstRequest,
5502 requests.end());
5503 // No need to wait any longer
Jianing Weicb0652e2014-03-12 18:29:36 -07005504
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005505 mRepeatingLastFrameNumber = mFrameNumber + requests.size() - 1;
Jianing Weicb0652e2014-03-12 18:29:36 -07005506
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005507 break;
5508 }
5509
5510 res = mRequestSignal.waitRelative(mRequestLock, kRequestTimeout);
5511
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005512 if ((mRequestQueue.empty() && mRepeatingRequests.empty()) ||
5513 exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005514 Mutex::Autolock pl(mPauseLock);
5515 if (mPaused == false) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005516 ALOGV("%s: RequestThread: Going idle", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005517 mPaused = true;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07005518 if (mNotifyPipelineDrain) {
5519 mInterface->signalPipelineDrain(mStreamIdsToBeDrained);
5520 mNotifyPipelineDrain = false;
5521 mStreamIdsToBeDrained.clear();
5522 }
Yin-Chia Yehc300a072019-02-13 14:56:57 -08005523 // Let the tracker know
5524 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5525 if (statusTracker != 0) {
5526 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
5527 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005528 sp<Camera3Device> parent = mParent.promote();
5529 if (parent != nullptr) {
5530 parent->mRequestBufferSM.onRequestThreadPaused();
5531 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005532 }
5533 // Stop waiting for now and let thread management happen
5534 return NULL;
5535 }
5536 }
5537
5538 if (nextRequest == NULL) {
5539 // Don't have a repeating request already in hand, so queue
5540 // must have an entry now.
5541 RequestList::iterator firstRequest =
5542 mRequestQueue.begin();
5543 nextRequest = *firstRequest;
5544 mRequestQueue.erase(firstRequest);
Shuzhen Wang9d066012016-09-30 11:30:20 -07005545 if (mRequestQueue.empty() && !nextRequest->mRepeating) {
5546 sp<NotificationListener> listener = mListener.promote();
5547 if (listener != NULL) {
5548 listener->notifyRequestQueueEmpty();
5549 }
5550 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005551 }
5552
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005553 // In case we've been unpaused by setPaused clearing mDoPause, need to
5554 // update internal pause state (capture/setRepeatingRequest unpause
5555 // directly).
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005556 Mutex::Autolock pl(mPauseLock);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005557 if (mPaused) {
5558 ALOGV("%s: RequestThread: Unpaused", __FUNCTION__);
5559 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5560 if (statusTracker != 0) {
5561 statusTracker->markComponentActive(mStatusId);
5562 }
5563 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005564 mPaused = false;
5565
5566 // Check if we've reconfigured since last time, and reset the preview
5567 // request if so. Can't use 'NULL request == repeat' across configure calls.
5568 if (mReconfigured) {
5569 mPrevRequest.clear();
5570 mReconfigured = false;
5571 }
5572
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005573 if (nextRequest != NULL) {
5574 nextRequest->mResultExtras.frameNumber = mFrameNumber++;
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07005575 nextRequest->mResultExtras.afTriggerId = mCurrentAfTriggerId;
5576 nextRequest->mResultExtras.precaptureTriggerId = mCurrentPreCaptureTriggerId;
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07005577
5578 // Since RequestThread::clear() removes buffers from the input stream,
5579 // get the right buffer here before unlocking mRequestLock
5580 if (nextRequest->mInputStream != NULL) {
Shuzhen Wang83bff122020-11-20 15:51:39 -08005581 res = nextRequest->mInputStream->getInputBuffer(&nextRequest->mInputBuffer,
5582 &nextRequest->mInputBufferSize);
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07005583 if (res != OK) {
5584 // Can't get input buffer from gralloc queue - this could be due to
5585 // disconnected queue or other producer misbehavior, so not a fatal
5586 // error
5587 ALOGE("%s: Can't get input buffer, skipping request:"
5588 " %s (%d)", __FUNCTION__, strerror(-res), res);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005589
5590 sp<NotificationListener> listener = mListener.promote();
5591 if (listener != NULL) {
5592 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08005593 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07005594 nextRequest->mResultExtras);
5595 }
5596 return NULL;
5597 }
5598 }
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005599 }
Chien-Yu Chend196d612015-06-22 19:49:01 -07005600
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005601 return nextRequest;
5602}
5603
5604bool Camera3Device::RequestThread::waitIfPaused() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005605 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005606 status_t res;
5607 Mutex::Autolock l(mPauseLock);
5608 while (mDoPause) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005609 if (mPaused == false) {
5610 mPaused = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005611 ALOGV("%s: RequestThread: Paused", __FUNCTION__);
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07005612 if (mNotifyPipelineDrain) {
5613 mInterface->signalPipelineDrain(mStreamIdsToBeDrained);
5614 mNotifyPipelineDrain = false;
5615 mStreamIdsToBeDrained.clear();
5616 }
Yin-Chia Yehc300a072019-02-13 14:56:57 -08005617 // Let the tracker know
5618 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5619 if (statusTracker != 0) {
5620 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
5621 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005622 sp<Camera3Device> parent = mParent.promote();
5623 if (parent != nullptr) {
5624 parent->mRequestBufferSM.onRequestThreadPaused();
5625 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005626 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005627
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005628 res = mDoPauseSignal.waitRelative(mPauseLock, kRequestTimeout);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005629 if (res == TIMED_OUT || exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005630 return true;
5631 }
5632 }
5633 // We don't set mPaused to false here, because waitForNextRequest needs
5634 // to further manage the paused state in case of starvation.
5635 return false;
5636}
5637
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005638void Camera3Device::RequestThread::unpauseForNewRequests() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005639 ATRACE_CALL();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005640 // With work to do, mark thread as unpaused.
5641 // If paused by request (setPaused), don't resume, to avoid
5642 // extra signaling/waiting overhead to waitUntilPaused
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005643 mRequestSignal.signal();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005644 Mutex::Autolock p(mPauseLock);
5645 if (!mDoPause) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005646 ALOGV("%s: RequestThread: Going active", __FUNCTION__);
5647 if (mPaused) {
5648 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5649 if (statusTracker != 0) {
5650 statusTracker->markComponentActive(mStatusId);
5651 }
5652 }
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005653 mPaused = false;
5654 }
5655}
5656
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07005657void Camera3Device::RequestThread::setErrorState(const char *fmt, ...) {
5658 sp<Camera3Device> parent = mParent.promote();
5659 if (parent != NULL) {
5660 va_list args;
5661 va_start(args, fmt);
5662
5663 parent->setErrorStateV(fmt, args);
5664
5665 va_end(args);
5666 }
5667}
5668
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005669status_t Camera3Device::RequestThread::insertTriggers(
5670 const sp<CaptureRequest> &request) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005671 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005672 Mutex::Autolock al(mTriggerMutex);
5673
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07005674 sp<Camera3Device> parent = mParent.promote();
5675 if (parent == NULL) {
5676 CLOGE("RequestThread: Parent is gone");
5677 return DEAD_OBJECT;
5678 }
5679
Emilian Peevaebbe412018-01-15 13:53:24 +00005680 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005681 size_t count = mTriggerMap.size();
5682
5683 for (size_t i = 0; i < count; ++i) {
5684 RequestTrigger trigger = mTriggerMap.valueAt(i);
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005685 uint32_t tag = trigger.metadataTag;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07005686
5687 if (tag == ANDROID_CONTROL_AF_TRIGGER_ID || tag == ANDROID_CONTROL_AE_PRECAPTURE_ID) {
5688 bool isAeTrigger = (trigger.metadataTag == ANDROID_CONTROL_AE_PRECAPTURE_ID);
5689 uint32_t triggerId = static_cast<uint32_t>(trigger.entryValue);
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07005690 if (isAeTrigger) {
5691 request->mResultExtras.precaptureTriggerId = triggerId;
5692 mCurrentPreCaptureTriggerId = triggerId;
5693 } else {
5694 request->mResultExtras.afTriggerId = triggerId;
5695 mCurrentAfTriggerId = triggerId;
5696 }
Emilian Peev7e25e5e2017-04-07 15:48:49 +01005697 continue;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07005698 }
5699
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005700 camera_metadata_entry entry = metadata.find(tag);
5701
5702 if (entry.count > 0) {
5703 /**
5704 * Already has an entry for this trigger in the request.
5705 * Rewrite it with our requested trigger value.
5706 */
5707 RequestTrigger oldTrigger = trigger;
5708
5709 oldTrigger.entryValue = entry.data.u8[0];
5710
5711 mTriggerReplacedMap.add(tag, oldTrigger);
5712 } else {
5713 /**
5714 * More typical, no trigger entry, so we just add it
5715 */
5716 mTriggerRemovedMap.add(tag, trigger);
5717 }
5718
5719 status_t res;
5720
5721 switch (trigger.getTagType()) {
5722 case TYPE_BYTE: {
5723 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
5724 res = metadata.update(tag,
5725 &entryValue,
5726 /*count*/1);
5727 break;
5728 }
5729 case TYPE_INT32:
5730 res = metadata.update(tag,
5731 &trigger.entryValue,
5732 /*count*/1);
5733 break;
5734 default:
5735 ALOGE("%s: Type not supported: 0x%x",
5736 __FUNCTION__,
5737 trigger.getTagType());
5738 return INVALID_OPERATION;
5739 }
5740
5741 if (res != OK) {
5742 ALOGE("%s: Failed to update request metadata with trigger tag %s"
5743 ", value %d", __FUNCTION__, trigger.getTagName(),
5744 trigger.entryValue);
5745 return res;
5746 }
5747
5748 ALOGV("%s: Mixed in trigger %s, value %d", __FUNCTION__,
5749 trigger.getTagName(),
5750 trigger.entryValue);
5751 }
5752
5753 mTriggerMap.clear();
5754
5755 return count;
5756}
5757
5758status_t Camera3Device::RequestThread::removeTriggers(
5759 const sp<CaptureRequest> &request) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005760 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005761 Mutex::Autolock al(mTriggerMutex);
5762
Emilian Peevaebbe412018-01-15 13:53:24 +00005763 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005764
5765 /**
5766 * Replace all old entries with their old values.
5767 */
5768 for (size_t i = 0; i < mTriggerReplacedMap.size(); ++i) {
5769 RequestTrigger trigger = mTriggerReplacedMap.valueAt(i);
5770
5771 status_t res;
5772
5773 uint32_t tag = trigger.metadataTag;
5774 switch (trigger.getTagType()) {
5775 case TYPE_BYTE: {
5776 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
5777 res = metadata.update(tag,
5778 &entryValue,
5779 /*count*/1);
5780 break;
5781 }
5782 case TYPE_INT32:
5783 res = metadata.update(tag,
5784 &trigger.entryValue,
5785 /*count*/1);
5786 break;
5787 default:
5788 ALOGE("%s: Type not supported: 0x%x",
5789 __FUNCTION__,
5790 trigger.getTagType());
5791 return INVALID_OPERATION;
5792 }
5793
5794 if (res != OK) {
5795 ALOGE("%s: Failed to restore request metadata with trigger tag %s"
5796 ", trigger value %d", __FUNCTION__,
5797 trigger.getTagName(), trigger.entryValue);
5798 return res;
5799 }
5800 }
5801 mTriggerReplacedMap.clear();
5802
5803 /**
5804 * Remove all new entries.
5805 */
5806 for (size_t i = 0; i < mTriggerRemovedMap.size(); ++i) {
5807 RequestTrigger trigger = mTriggerRemovedMap.valueAt(i);
5808 status_t res = metadata.erase(trigger.metadataTag);
5809
5810 if (res != OK) {
5811 ALOGE("%s: Failed to erase metadata with trigger tag %s"
5812 ", trigger value %d", __FUNCTION__,
5813 trigger.getTagName(), trigger.entryValue);
5814 return res;
5815 }
5816 }
5817 mTriggerRemovedMap.clear();
5818
5819 return OK;
5820}
5821
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04005822status_t Camera3Device::RequestThread::addFakeTriggerIds(
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005823 const sp<CaptureRequest> &request) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08005824 // Trigger ID 0 had special meaning in the HAL2 spec, so avoid it here
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04005825 static const int32_t fakeTriggerId = 1;
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005826 status_t res;
5827
Emilian Peevaebbe412018-01-15 13:53:24 +00005828 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005829
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04005830 // If AF trigger is active, insert a fake AF trigger ID if none already
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005831 // exists
5832 camera_metadata_entry afTrigger = metadata.find(ANDROID_CONTROL_AF_TRIGGER);
5833 camera_metadata_entry afId = metadata.find(ANDROID_CONTROL_AF_TRIGGER_ID);
5834 if (afTrigger.count > 0 &&
5835 afTrigger.data.u8[0] != ANDROID_CONTROL_AF_TRIGGER_IDLE &&
5836 afId.count == 0) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04005837 res = metadata.update(ANDROID_CONTROL_AF_TRIGGER_ID, &fakeTriggerId, 1);
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005838 if (res != OK) return res;
5839 }
5840
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04005841 // If AE precapture trigger is active, insert a fake precapture trigger ID
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005842 // if none already exists
5843 camera_metadata_entry pcTrigger =
5844 metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER);
5845 camera_metadata_entry pcId = metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_ID);
5846 if (pcTrigger.count > 0 &&
5847 pcTrigger.data.u8[0] != ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_IDLE &&
5848 pcId.count == 0) {
5849 res = metadata.update(ANDROID_CONTROL_AE_PRECAPTURE_ID,
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04005850 &fakeTriggerId, 1);
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005851 if (res != OK) return res;
5852 }
5853
5854 return OK;
5855}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005856
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005857bool Camera3Device::RequestThread::overrideAutoRotateAndCrop(
5858 const sp<CaptureRequest> &request) {
5859 ATRACE_CALL();
5860
5861 if (request->mRotateAndCropAuto) {
5862 Mutex::Autolock l(mTriggerMutex);
5863 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
5864
5865 auto rotateAndCropEntry = metadata.find(ANDROID_SCALER_ROTATE_AND_CROP);
5866 if (rotateAndCropEntry.count > 0) {
5867 if (rotateAndCropEntry.data.u8[0] == mRotateAndCropOverride) {
5868 return false;
5869 } else {
5870 rotateAndCropEntry.data.u8[0] = mRotateAndCropOverride;
5871 return true;
5872 }
5873 } else {
5874 uint8_t rotateAndCrop_u8 = mRotateAndCropOverride;
5875 metadata.update(ANDROID_SCALER_ROTATE_AND_CROP,
5876 &rotateAndCrop_u8, 1);
5877 return true;
5878 }
5879 }
5880 return false;
5881}
5882
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005883bool Camera3Device::RequestThread::overrideTestPattern(
5884 const sp<CaptureRequest> &request) {
5885 ATRACE_CALL();
5886
Eino-Ville Talvala1646c3c2021-07-29 13:48:40 -07005887 if (!mSupportCameraMute) return false;
Eino-Ville Talvalac2459842021-07-22 16:36:36 -07005888
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005889 Mutex::Autolock l(mTriggerMutex);
5890
5891 bool changed = false;
5892
5893 int32_t testPatternMode = request->mOriginalTestPatternMode;
5894 int32_t testPatternData[4] = {
5895 request->mOriginalTestPatternData[0],
5896 request->mOriginalTestPatternData[1],
5897 request->mOriginalTestPatternData[2],
5898 request->mOriginalTestPatternData[3]
5899 };
5900
Eino-Ville Talvala11afe4f2021-05-27 14:45:31 -07005901 if (mCameraMute != ANDROID_SENSOR_TEST_PATTERN_MODE_OFF) {
5902 testPatternMode = mCameraMute;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005903 testPatternData[0] = 0;
5904 testPatternData[1] = 0;
5905 testPatternData[2] = 0;
5906 testPatternData[3] = 0;
5907 }
5908
5909 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
5910
5911 auto testPatternEntry = metadata.find(ANDROID_SENSOR_TEST_PATTERN_MODE);
5912 if (testPatternEntry.count > 0) {
5913 if (testPatternEntry.data.i32[0] != testPatternMode) {
5914 testPatternEntry.data.i32[0] = testPatternMode;
5915 changed = true;
5916 }
5917 } else {
5918 metadata.update(ANDROID_SENSOR_TEST_PATTERN_MODE,
5919 &testPatternMode, 1);
5920 changed = true;
5921 }
5922
5923 auto testPatternColor = metadata.find(ANDROID_SENSOR_TEST_PATTERN_DATA);
Eino-Ville Talvalac2459842021-07-22 16:36:36 -07005924 if (testPatternColor.count >= 4) {
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005925 for (size_t i = 0; i < 4; i++) {
Eino-Ville Talvalac2459842021-07-22 16:36:36 -07005926 if (testPatternColor.data.i32[i] != testPatternData[i]) {
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005927 testPatternColor.data.i32[i] = testPatternData[i];
5928 changed = true;
5929 }
5930 }
5931 } else {
5932 metadata.update(ANDROID_SENSOR_TEST_PATTERN_DATA,
Eino-Ville Talvalac2459842021-07-22 16:36:36 -07005933 testPatternData, 4);
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005934 changed = true;
5935 }
5936
5937 return changed;
5938}
5939
Cliff Wuc2ad9c82021-04-21 00:58:58 +08005940status_t Camera3Device::RequestThread::setHalInterface(
5941 sp<HalInterface> newHalInterface) {
5942 if (newHalInterface.get() == nullptr) {
5943 ALOGE("%s: The newHalInterface does not exist!", __FUNCTION__);
5944 return DEAD_OBJECT;
5945 }
5946
5947 mInterface = newHalInterface;
5948
5949 return OK;
5950}
5951
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005952/**
5953 * PreparerThread inner class methods
5954 */
5955
5956Camera3Device::PreparerThread::PreparerThread() :
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07005957 Thread(/*canCallJava*/false), mListener(nullptr),
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005958 mActive(false), mCancelNow(false), mCurrentMaxCount(0), mCurrentPrepareComplete(false) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005959}
5960
5961Camera3Device::PreparerThread::~PreparerThread() {
5962 Thread::requestExitAndWait();
5963 if (mCurrentStream != nullptr) {
5964 mCurrentStream->cancelPrepare();
5965 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
5966 mCurrentStream.clear();
5967 }
5968 clear();
5969}
5970
Ruben Brunkc78ac262015-08-13 17:58:46 -07005971status_t Camera3Device::PreparerThread::prepare(int maxCount, sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005972 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005973 status_t res;
5974
5975 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005976 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005977
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07005978 res = stream->startPrepare(maxCount, true /*blockRequest*/);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005979 if (res == OK) {
5980 // No preparation needed, fire listener right off
5981 ALOGV("%s: Stream %d already prepared", __FUNCTION__, stream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005982 if (listener != NULL) {
5983 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005984 }
5985 return OK;
5986 } else if (res != NOT_ENOUGH_DATA) {
5987 return res;
5988 }
5989
5990 // Need to prepare, start up thread if necessary
5991 if (!mActive) {
5992 // mRunning will change to false before the thread fully shuts down, so wait to be sure it
5993 // isn't running
5994 Thread::requestExitAndWait();
5995 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
5996 if (res != OK) {
5997 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__, res, strerror(-res));
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005998 if (listener != NULL) {
5999 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006000 }
6001 return res;
6002 }
6003 mCancelNow = false;
6004 mActive = true;
6005 ALOGV("%s: Preparer stream started", __FUNCTION__);
6006 }
6007
6008 // queue up the work
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006009 mPendingStreams.emplace(maxCount, stream);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006010 ALOGV("%s: Stream %d queued for preparing", __FUNCTION__, stream->getId());
6011
6012 return OK;
6013}
6014
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006015void Camera3Device::PreparerThread::pause() {
6016 ATRACE_CALL();
6017
6018 Mutex::Autolock l(mLock);
6019
6020 std::unordered_map<int, sp<camera3::Camera3StreamInterface> > pendingStreams;
6021 pendingStreams.insert(mPendingStreams.begin(), mPendingStreams.end());
6022 sp<camera3::Camera3StreamInterface> currentStream = mCurrentStream;
6023 int currentMaxCount = mCurrentMaxCount;
6024 mPendingStreams.clear();
6025 mCancelNow = true;
6026 while (mActive) {
6027 auto res = mThreadActiveSignal.waitRelative(mLock, kActiveTimeout);
6028 if (res == TIMED_OUT) {
6029 ALOGE("%s: Timed out waiting on prepare thread!", __FUNCTION__);
6030 return;
6031 } else if (res != OK) {
6032 ALOGE("%s: Encountered an error: %d waiting on prepare thread!", __FUNCTION__, res);
6033 return;
6034 }
6035 }
6036
6037 //Check whether the prepare thread was able to complete the current
6038 //stream. In case work is still pending emplace it along with the rest
6039 //of the streams in the pending list.
6040 if (currentStream != nullptr) {
6041 if (!mCurrentPrepareComplete) {
6042 pendingStreams.emplace(currentMaxCount, currentStream);
6043 }
6044 }
6045
6046 mPendingStreams.insert(pendingStreams.begin(), pendingStreams.end());
6047 for (const auto& it : mPendingStreams) {
6048 it.second->cancelPrepare();
6049 }
6050}
6051
6052status_t Camera3Device::PreparerThread::resume() {
6053 ATRACE_CALL();
6054 status_t res;
6055
6056 Mutex::Autolock l(mLock);
6057 sp<NotificationListener> listener = mListener.promote();
6058
6059 if (mActive) {
6060 ALOGE("%s: Trying to resume an already active prepare thread!", __FUNCTION__);
6061 return NO_INIT;
6062 }
6063
6064 auto it = mPendingStreams.begin();
6065 for (; it != mPendingStreams.end();) {
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07006066 res = it->second->startPrepare(it->first, true /*blockRequest*/);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006067 if (res == OK) {
6068 if (listener != NULL) {
6069 listener->notifyPrepared(it->second->getId());
6070 }
6071 it = mPendingStreams.erase(it);
6072 } else if (res != NOT_ENOUGH_DATA) {
6073 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__,
6074 res, strerror(-res));
6075 it = mPendingStreams.erase(it);
6076 } else {
6077 it++;
6078 }
6079 }
6080
6081 if (mPendingStreams.empty()) {
6082 return OK;
6083 }
6084
6085 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
6086 if (res != OK) {
6087 ALOGE("%s: Unable to start preparer stream: %d (%s)",
6088 __FUNCTION__, res, strerror(-res));
6089 return res;
6090 }
6091 mCancelNow = false;
6092 mActive = true;
6093 ALOGV("%s: Preparer stream started", __FUNCTION__);
6094
6095 return OK;
6096}
6097
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006098status_t Camera3Device::PreparerThread::clear() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07006099 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006100 Mutex::Autolock l(mLock);
6101
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006102 for (const auto& it : mPendingStreams) {
6103 it.second->cancelPrepare();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006104 }
6105 mPendingStreams.clear();
6106 mCancelNow = true;
6107
6108 return OK;
6109}
6110
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006111void Camera3Device::PreparerThread::setNotificationListener(wp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07006112 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006113 Mutex::Autolock l(mLock);
6114 mListener = listener;
6115}
6116
6117bool Camera3Device::PreparerThread::threadLoop() {
6118 status_t res;
6119 {
6120 Mutex::Autolock l(mLock);
6121 if (mCurrentStream == nullptr) {
6122 // End thread if done with work
6123 if (mPendingStreams.empty()) {
6124 ALOGV("%s: Preparer stream out of work", __FUNCTION__);
6125 // threadLoop _must not_ re-acquire mLock after it sets mActive to false; would
6126 // cause deadlock with prepare()'s requestExitAndWait triggered by !mActive.
6127 mActive = false;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006128 mThreadActiveSignal.signal();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006129 return false;
6130 }
6131
6132 // Get next stream to prepare
6133 auto it = mPendingStreams.begin();
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006134 mCurrentStream = it->second;
6135 mCurrentMaxCount = it->first;
6136 mCurrentPrepareComplete = false;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006137 mPendingStreams.erase(it);
6138 ATRACE_ASYNC_BEGIN("stream prepare", mCurrentStream->getId());
6139 ALOGV("%s: Preparing stream %d", __FUNCTION__, mCurrentStream->getId());
6140 } else if (mCancelNow) {
6141 mCurrentStream->cancelPrepare();
6142 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
6143 ALOGV("%s: Cancelling stream %d prepare", __FUNCTION__, mCurrentStream->getId());
6144 mCurrentStream.clear();
6145 mCancelNow = false;
6146 return true;
6147 }
6148 }
6149
6150 res = mCurrentStream->prepareNextBuffer();
6151 if (res == NOT_ENOUGH_DATA) return true;
6152 if (res != OK) {
6153 // Something bad happened; try to recover by cancelling prepare and
6154 // signalling listener anyway
6155 ALOGE("%s: Stream %d returned error %d (%s) during prepare", __FUNCTION__,
6156 mCurrentStream->getId(), res, strerror(-res));
6157 mCurrentStream->cancelPrepare();
6158 }
6159
6160 // This stream has finished, notify listener
6161 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006162 sp<NotificationListener> listener = mListener.promote();
6163 if (listener != NULL) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006164 ALOGV("%s: Stream %d prepare done, signaling listener", __FUNCTION__,
6165 mCurrentStream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006166 listener->notifyPrepared(mCurrentStream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006167 }
6168
6169 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
6170 mCurrentStream.clear();
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006171 mCurrentPrepareComplete = true;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006172
6173 return true;
6174}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07006175
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006176status_t Camera3Device::RequestBufferStateMachine::initialize(
6177 sp<camera3::StatusTracker> statusTracker) {
6178 if (statusTracker == nullptr) {
6179 ALOGE("%s: statusTracker is null", __FUNCTION__);
6180 return BAD_VALUE;
6181 }
6182
6183 std::lock_guard<std::mutex> lock(mLock);
6184 mStatusTracker = statusTracker;
Yin-Chia Yeh87b3ec02019-06-03 10:44:39 -07006185 mRequestBufferStatusId = statusTracker->addComponent("BufferRequestSM");
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006186 return OK;
6187}
6188
6189bool Camera3Device::RequestBufferStateMachine::startRequestBuffer() {
6190 std::lock_guard<std::mutex> lock(mLock);
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08006191 if (mStatus == RB_STATUS_READY || mStatus == RB_STATUS_PENDING_STOP) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006192 mRequestBufferOngoing = true;
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08006193 notifyTrackerLocked(/*active*/true);
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006194 return true;
6195 }
6196 return false;
6197}
6198
6199void Camera3Device::RequestBufferStateMachine::endRequestBuffer() {
6200 std::lock_guard<std::mutex> lock(mLock);
6201 if (!mRequestBufferOngoing) {
6202 ALOGE("%s called without a successful startRequestBuffer call first!", __FUNCTION__);
6203 return;
6204 }
6205 mRequestBufferOngoing = false;
6206 if (mStatus == RB_STATUS_PENDING_STOP) {
6207 checkSwitchToStopLocked();
6208 }
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08006209 notifyTrackerLocked(/*active*/false);
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006210}
6211
6212void Camera3Device::RequestBufferStateMachine::onStreamsConfigured() {
6213 std::lock_guard<std::mutex> lock(mLock);
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006214 mSwitchedToOffline = false;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006215 mStatus = RB_STATUS_READY;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006216 return;
6217}
6218
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08006219void Camera3Device::RequestBufferStateMachine::onSubmittingRequest() {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006220 std::lock_guard<std::mutex> lock(mLock);
6221 mRequestThreadPaused = false;
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08006222 // inflight map register actually happens in prepareHalRequest now, but it is close enough
6223 // approximation.
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006224 mInflightMapEmpty = false;
6225 if (mStatus == RB_STATUS_STOPPED) {
6226 mStatus = RB_STATUS_READY;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006227 }
6228 return;
6229}
6230
6231void Camera3Device::RequestBufferStateMachine::onRequestThreadPaused() {
6232 std::lock_guard<std::mutex> lock(mLock);
6233 mRequestThreadPaused = true;
6234 if (mStatus == RB_STATUS_PENDING_STOP) {
6235 checkSwitchToStopLocked();
6236 }
6237 return;
6238}
6239
6240void Camera3Device::RequestBufferStateMachine::onInflightMapEmpty() {
6241 std::lock_guard<std::mutex> lock(mLock);
6242 mInflightMapEmpty = true;
6243 if (mStatus == RB_STATUS_PENDING_STOP) {
6244 checkSwitchToStopLocked();
6245 }
6246 return;
6247}
6248
6249void Camera3Device::RequestBufferStateMachine::onWaitUntilIdle() {
6250 std::lock_guard<std::mutex> lock(mLock);
6251 if (!checkSwitchToStopLocked()) {
6252 mStatus = RB_STATUS_PENDING_STOP;
6253 }
6254 return;
6255}
6256
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006257bool Camera3Device::RequestBufferStateMachine::onSwitchToOfflineSuccess() {
6258 std::lock_guard<std::mutex> lock(mLock);
6259 if (mRequestBufferOngoing) {
6260 ALOGE("%s: HAL must not be requesting buffer after HAL returns switchToOffline!",
6261 __FUNCTION__);
6262 return false;
6263 }
6264 mSwitchedToOffline = true;
6265 mInflightMapEmpty = true;
6266 mRequestThreadPaused = true;
6267 mStatus = RB_STATUS_STOPPED;
6268 return true;
6269}
6270
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006271void Camera3Device::RequestBufferStateMachine::notifyTrackerLocked(bool active) {
6272 sp<StatusTracker> statusTracker = mStatusTracker.promote();
6273 if (statusTracker != nullptr) {
6274 if (active) {
6275 statusTracker->markComponentActive(mRequestBufferStatusId);
6276 } else {
6277 statusTracker->markComponentIdle(mRequestBufferStatusId, Fence::NO_FENCE);
6278 }
6279 }
6280}
6281
6282bool Camera3Device::RequestBufferStateMachine::checkSwitchToStopLocked() {
6283 if (mInflightMapEmpty && mRequestThreadPaused && !mRequestBufferOngoing) {
6284 mStatus = RB_STATUS_STOPPED;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006285 return true;
6286 }
6287 return false;
6288}
6289
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006290bool Camera3Device::startRequestBuffer() {
6291 return mRequestBufferSM.startRequestBuffer();
6292}
Shuzhen Wang268a1362018-10-16 16:32:59 -07006293
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006294void Camera3Device::endRequestBuffer() {
6295 mRequestBufferSM.endRequestBuffer();
6296}
Shuzhen Wang268a1362018-10-16 16:32:59 -07006297
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006298nsecs_t Camera3Device::getWaitDuration() {
6299 return kBaseGetBufferWait + getExpectedInFlightDuration();
6300}
Shuzhen Wang268a1362018-10-16 16:32:59 -07006301
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006302void Camera3Device::getInflightBufferKeys(std::vector<std::pair<int32_t, int32_t>>* out) {
6303 mInterface->getInflightBufferKeys(out);
6304}
Shuzhen Wang268a1362018-10-16 16:32:59 -07006305
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006306void Camera3Device::getInflightRequestBufferKeys(std::vector<uint64_t>* out) {
6307 mInterface->getInflightRequestBufferKeys(out);
6308}
Shuzhen Wang268a1362018-10-16 16:32:59 -07006309
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006310std::vector<sp<Camera3StreamInterface>> Camera3Device::getAllStreams() {
6311 std::vector<sp<Camera3StreamInterface>> ret;
6312 bool hasInputStream = mInputStream != nullptr;
6313 ret.reserve(mOutputStreams.size() + mDeletedStreams.size() + ((hasInputStream) ? 1 : 0));
6314 if (hasInputStream) {
6315 ret.push_back(mInputStream);
Shuzhen Wang268a1362018-10-16 16:32:59 -07006316 }
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006317 for (size_t i = 0; i < mOutputStreams.size(); i++) {
6318 ret.push_back(mOutputStreams[i]);
6319 }
6320 for (size_t i = 0; i < mDeletedStreams.size(); i++) {
6321 ret.push_back(mDeletedStreams[i]);
6322 }
6323 return ret;
Shuzhen Wang268a1362018-10-16 16:32:59 -07006324}
6325
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006326status_t Camera3Device::switchToOffline(
6327 const std::vector<int32_t>& streamsToKeep,
6328 /*out*/ sp<CameraOfflineSessionBase>* session) {
6329 ATRACE_CALL();
6330 if (session == nullptr) {
6331 ALOGE("%s: session must not be null", __FUNCTION__);
6332 return BAD_VALUE;
6333 }
6334
6335 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006336
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006337 bool hasInputStream = mInputStream != nullptr;
6338 int32_t inputStreamId = hasInputStream ? mInputStream->getId() : -1;
6339 bool inputStreamSupportsOffline = hasInputStream ?
6340 mInputStream->getOfflineProcessingSupport() : false;
6341 auto outputStreamIds = mOutputStreams.getStreamIds();
6342 auto streamIds = outputStreamIds;
6343 if (hasInputStream) {
6344 streamIds.push_back(mInputStream->getId());
6345 }
6346
6347 // Check all streams in streamsToKeep supports offline mode
6348 for (auto id : streamsToKeep) {
6349 if (std::find(streamIds.begin(), streamIds.end(), id) == streamIds.end()) {
6350 ALOGE("%s: Unknown stream ID %d", __FUNCTION__, id);
6351 return BAD_VALUE;
6352 } else if (id == inputStreamId) {
6353 if (!inputStreamSupportsOffline) {
6354 ALOGE("%s: input stream %d cannot be switched to offline",
6355 __FUNCTION__, id);
6356 return BAD_VALUE;
6357 }
6358 } else {
6359 sp<camera3::Camera3OutputStreamInterface> stream = mOutputStreams.get(id);
6360 if (!stream->getOfflineProcessingSupport()) {
6361 ALOGE("%s: output stream %d cannot be switched to offline",
6362 __FUNCTION__, id);
6363 return BAD_VALUE;
6364 }
6365 }
6366 }
6367
6368 // TODO: block surface sharing and surface group streams until we can support them
6369
6370 // Stop repeating request, wait until all remaining requests are submitted, then call into
6371 // HAL switchToOffline
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006372 hardware::camera::device::V3_6::CameraOfflineSessionInfo offlineSessionInfo;
6373 sp<hardware::camera::device::V3_6::ICameraOfflineSession> offlineSession;
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006374 camera3::BufferRecords bufferRecords;
6375 status_t ret = mRequestThread->switchToOffline(
6376 streamsToKeep, &offlineSessionInfo, &offlineSession, &bufferRecords);
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006377
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006378 if (ret != OK) {
6379 SET_ERR("Switch to offline failed: %s (%d)", strerror(-ret), ret);
6380 return ret;
6381 }
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006382
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006383 bool succ = mRequestBufferSM.onSwitchToOfflineSuccess();
6384 if (!succ) {
6385 SET_ERR("HAL must not be calling requestStreamBuffers call");
6386 // TODO: block ALL callbacks from HAL till app configured new streams?
6387 return UNKNOWN_ERROR;
6388 }
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006389
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006390 // Verify offlineSessionInfo
6391 std::vector<int32_t> offlineStreamIds;
6392 offlineStreamIds.reserve(offlineSessionInfo.offlineStreams.size());
6393 for (auto offlineStream : offlineSessionInfo.offlineStreams) {
6394 // verify stream IDs
6395 int32_t id = offlineStream.id;
6396 if (std::find(streamIds.begin(), streamIds.end(), id) == streamIds.end()) {
6397 SET_ERR("stream ID %d not found!", id);
6398 return UNKNOWN_ERROR;
6399 }
6400
6401 // When not using HAL buf manager, only allow streams requested by app to be preserved
6402 if (!mUseHalBufManager) {
6403 if (std::find(streamsToKeep.begin(), streamsToKeep.end(), id) == streamsToKeep.end()) {
6404 SET_ERR("stream ID %d must not be switched to offline!", id);
6405 return UNKNOWN_ERROR;
6406 }
6407 }
6408
6409 offlineStreamIds.push_back(id);
6410 sp<Camera3StreamInterface> stream = (id == inputStreamId) ?
6411 static_cast<sp<Camera3StreamInterface>>(mInputStream) :
6412 static_cast<sp<Camera3StreamInterface>>(mOutputStreams.get(id));
6413 // Verify number of outstanding buffers
6414 if (stream->getOutstandingBuffersCount() != offlineStream.numOutstandingBuffers) {
6415 SET_ERR("Offline stream %d # of remaining buffer mismatch: (%zu,%d) (service/HAL)",
6416 id, stream->getOutstandingBuffersCount(), offlineStream.numOutstandingBuffers);
6417 return UNKNOWN_ERROR;
6418 }
6419 }
6420
6421 // Verify all streams to be deleted don't have any outstanding buffers
6422 if (hasInputStream && std::find(offlineStreamIds.begin(), offlineStreamIds.end(),
6423 inputStreamId) == offlineStreamIds.end()) {
6424 if (mInputStream->hasOutstandingBuffers()) {
6425 SET_ERR("Input stream %d still has %zu outstanding buffer!",
6426 inputStreamId, mInputStream->getOutstandingBuffersCount());
6427 return UNKNOWN_ERROR;
6428 }
6429 }
6430
6431 for (const auto& outStreamId : outputStreamIds) {
6432 if (std::find(offlineStreamIds.begin(), offlineStreamIds.end(),
6433 outStreamId) == offlineStreamIds.end()) {
6434 auto outStream = mOutputStreams.get(outStreamId);
6435 if (outStream->hasOutstandingBuffers()) {
6436 SET_ERR("Output stream %d still has %zu outstanding buffer!",
6437 outStreamId, outStream->getOutstandingBuffersCount());
6438 return UNKNOWN_ERROR;
6439 }
6440 }
6441 }
6442
6443 InFlightRequestMap offlineReqs;
6444 // Verify inflight requests and their pending buffers
6445 {
6446 std::lock_guard<std::mutex> l(mInFlightLock);
6447 for (auto offlineReq : offlineSessionInfo.offlineRequests) {
6448 int idx = mInFlightMap.indexOfKey(offlineReq.frameNumber);
6449 if (idx == NAME_NOT_FOUND) {
6450 SET_ERR("Offline request frame number %d not found!", offlineReq.frameNumber);
6451 return UNKNOWN_ERROR;
6452 }
6453
6454 const auto& inflightReq = mInFlightMap.valueAt(idx);
6455 // TODO: check specific stream IDs
6456 size_t numBuffersLeft = static_cast<size_t>(inflightReq.numBuffersLeft);
6457 if (numBuffersLeft != offlineReq.pendingStreams.size()) {
6458 SET_ERR("Offline request # of remaining buffer mismatch: (%d,%d) (service/HAL)",
6459 inflightReq.numBuffersLeft, offlineReq.pendingStreams.size());
6460 return UNKNOWN_ERROR;
6461 }
6462 offlineReqs.add(offlineReq.frameNumber, inflightReq);
6463 }
6464 }
6465
6466 // Create Camera3OfflineSession and transfer object ownership
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006467 // (streams, inflight requests, buffer caches)
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006468 camera3::StreamSet offlineStreamSet;
6469 sp<camera3::Camera3Stream> inputStream;
6470 for (auto offlineStream : offlineSessionInfo.offlineStreams) {
6471 int32_t id = offlineStream.id;
6472 if (mInputStream != nullptr && id == mInputStream->getId()) {
6473 inputStream = mInputStream;
6474 } else {
6475 offlineStreamSet.add(id, mOutputStreams.get(id));
6476 }
6477 }
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006478
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006479 // TODO: check if we need to lock before copying states
6480 // though technically no other thread should be talking to Camera3Device at this point
6481 Camera3OfflineStates offlineStates(
6482 mTagMonitor, mVendorTagId, mUseHalBufManager, mNeedFixupMonochromeTags,
Shuzhen Wangb7b42652020-05-07 11:59:02 -07006483 mUsePartialResult, mNumPartialResults, mLastCompletedRegularFrameNumber,
6484 mLastCompletedReprocessFrameNumber, mLastCompletedZslFrameNumber,
6485 mNextResultFrameNumber, mNextReprocessResultFrameNumber,
6486 mNextZslStillResultFrameNumber, mNextShutterFrameNumber,
6487 mNextReprocessShutterFrameNumber, mNextZslStillShutterFrameNumber,
6488 mDeviceInfo, mPhysicalDeviceInfoMap, mDistortionMappers,
6489 mZoomRatioMappers, mRotateAndCropMappers);
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006490
6491 *session = new Camera3OfflineSession(mId, inputStream, offlineStreamSet,
6492 std::move(bufferRecords), offlineReqs, offlineStates, offlineSession);
6493
6494 // Delete all streams that has been transferred to offline session
6495 Mutex::Autolock l(mLock);
6496 for (auto offlineStream : offlineSessionInfo.offlineStreams) {
6497 int32_t id = offlineStream.id;
6498 if (mInputStream != nullptr && id == mInputStream->getId()) {
6499 mInputStream.clear();
6500 } else {
6501 mOutputStreams.remove(id);
6502 }
6503 }
6504
6505 // disconnect all other streams and switch to UNCONFIGURED state
6506 if (mInputStream != nullptr) {
6507 ret = mInputStream->disconnect();
6508 if (ret != OK) {
6509 SET_ERR_L("disconnect input stream failed!");
6510 return UNKNOWN_ERROR;
6511 }
6512 }
6513
6514 for (auto streamId : mOutputStreams.getStreamIds()) {
6515 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
6516 ret = stream->disconnect();
6517 if (ret != OK) {
6518 SET_ERR_L("disconnect output stream %d failed!", streamId);
6519 return UNKNOWN_ERROR;
6520 }
6521 }
6522
6523 mInputStream.clear();
6524 mOutputStreams.clear();
6525 mNeedConfig = true;
6526 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
6527 mOperatingMode = NO_MODE;
6528 mIsConstrainedHighSpeedConfiguration = false;
Emilian Peevc0fe54c2020-03-11 14:05:07 -07006529 mRequestThread->clearPreviousRequest();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006530
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006531 return OK;
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006532 // TO be done by CameraDeviceClient/Camera3OfflineSession
6533 // register the offline client to camera service
6534 // Setup result passthing threads etc
6535 // Initialize offline session so HAL can start sending callback to it (result Fmq)
6536 // TODO: check how many onIdle callback will be sent
6537 // Java side to make sure the CameraCaptureSession is properly closed
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006538}
6539
Emilian Peevcc0b7952020-01-07 13:54:47 -08006540void Camera3Device::getOfflineStreamIds(std::vector<int> *offlineStreamIds) {
6541 ATRACE_CALL();
6542
6543 if (offlineStreamIds == nullptr) {
6544 return;
6545 }
6546
6547 Mutex::Autolock il(mInterfaceLock);
6548
6549 auto streamIds = mOutputStreams.getStreamIds();
6550 bool hasInputStream = mInputStream != nullptr;
6551 if (hasInputStream && mInputStream->getOfflineProcessingSupport()) {
6552 offlineStreamIds->push_back(mInputStream->getId());
6553 }
6554
6555 for (const auto & streamId : streamIds) {
6556 sp<camera3::Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
6557 // Streams that use the camera buffer manager are currently not supported in
6558 // offline mode
6559 if (stream->getOfflineProcessingSupport() &&
6560 (stream->getStreamSetId() == CAMERA3_STREAM_SET_ID_INVALID)) {
6561 offlineStreamIds->push_back(streamId);
6562 }
6563 }
6564}
6565
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08006566status_t Camera3Device::setRotateAndCropAutoBehavior(
6567 camera_metadata_enum_android_scaler_rotate_and_crop_t rotateAndCropValue) {
6568 ATRACE_CALL();
6569 Mutex::Autolock il(mInterfaceLock);
6570 Mutex::Autolock l(mLock);
6571 if (mRequestThread == nullptr) {
6572 return INVALID_OPERATION;
6573 }
6574 return mRequestThread->setRotateAndCropAutoBehavior(rotateAndCropValue);
6575}
6576
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08006577bool Camera3Device::supportsCameraMute() {
6578 Mutex::Autolock il(mInterfaceLock);
6579 Mutex::Autolock l(mLock);
6580
6581 return mSupportCameraMute;
6582}
6583
6584status_t Camera3Device::setCameraMute(bool enabled) {
6585 ATRACE_CALL();
6586 Mutex::Autolock il(mInterfaceLock);
6587 Mutex::Autolock l(mLock);
6588
6589 if (mRequestThread == nullptr || !mSupportCameraMute) {
6590 return INVALID_OPERATION;
6591 }
Eino-Ville Talvala11afe4f2021-05-27 14:45:31 -07006592 int32_t muteMode =
6593 !enabled ? ANDROID_SENSOR_TEST_PATTERN_MODE_OFF :
6594 mSupportTestPatternSolidColor ? ANDROID_SENSOR_TEST_PATTERN_MODE_SOLID_COLOR :
6595 ANDROID_SENSOR_TEST_PATTERN_MODE_BLACK;
6596 return mRequestThread->setCameraMute(muteMode);
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08006597}
6598
Cliff Wuc2ad9c82021-04-21 00:58:58 +08006599status_t Camera3Device::injectCamera(const String8& injectedCamId,
6600 sp<CameraProviderManager> manager) {
6601 ALOGI("%s Injection camera: injectedCamId = %s", __FUNCTION__, injectedCamId.string());
6602 ATRACE_CALL();
6603 Mutex::Autolock il(mInterfaceLock);
Cliff Wu3b268182021-07-06 15:44:43 +08006604 // When the camera device is active, injectCamera() and stopInjection() will call
6605 // internalPauseAndWaitLocked() and internalResumeLocked(), and then they will call
6606 // mStatusChanged.waitRelative(mLock, timeout) of waitUntilStateThenRelock(). But
6607 // mStatusChanged.waitRelative(mLock, timeout)'s parameter: mutex "mLock" must be in the locked
6608 // state, so we need to add "Mutex::Autolock l(mLock)" to lock the "mLock" before calling
6609 // waitUntilStateThenRelock().
6610 Mutex::Autolock l(mLock);
Cliff Wuc2ad9c82021-04-21 00:58:58 +08006611
6612 status_t res = NO_ERROR;
6613 if (mInjectionMethods->isInjecting()) {
6614 if (injectedCamId == mInjectionMethods->getInjectedCamId()) {
6615 return OK;
6616 } else {
6617 res = mInjectionMethods->stopInjection();
6618 if (res != OK) {
6619 ALOGE("%s: Failed to stop the injection camera! ret != NO_ERROR: %d",
6620 __FUNCTION__, res);
6621 return res;
6622 }
6623 }
6624 }
6625
6626 res = mInjectionMethods->injectionInitialize(injectedCamId, manager, this);
6627 if (res != OK) {
6628 ALOGE("%s: Failed to initialize the injection camera! ret != NO_ERROR: %d",
6629 __FUNCTION__, res);
6630 return res;
6631 }
6632
Cliff Wuc2ad9c82021-04-21 00:58:58 +08006633 // When the second display of android is cast to the remote device, and the opened camera is
6634 // also cast to the second display, in this case, because the camera has configured the streams
6635 // at this time, we can directly call injectCamera() to replace the internal camera with
6636 // injection camera.
Cliff Wu3b268182021-07-06 15:44:43 +08006637 if (mInjectionMethods->isStreamConfigCompleteButNotInjected()) {
6638 ALOGD("%s: The opened camera is directly cast to the remote device.", __FUNCTION__);
6639
6640 camera3::camera_stream_configuration injectionConfig;
6641 std::vector<uint32_t> injectionBufferSizes;
6642 mInjectionMethods->getInjectionConfig(&injectionConfig, &injectionBufferSizes);
6643 if (mOperatingMode < 0 || injectionConfig.num_streams <= 0
6644 || injectionBufferSizes.size() <= 0) {
6645 ALOGE("Failed to inject camera due to abandoned configuration! "
6646 "mOperatingMode: %d injectionConfig.num_streams: %d "
6647 "injectionBufferSizes.size(): %zu", mOperatingMode,
6648 injectionConfig.num_streams, injectionBufferSizes.size());
6649 return DEAD_OBJECT;
6650 }
6651
Cliff Wuc2ad9c82021-04-21 00:58:58 +08006652 res = mInjectionMethods->injectCamera(
6653 injectionConfig, injectionBufferSizes);
6654 if (res != OK) {
6655 ALOGE("Can't finish inject camera process!");
6656 return res;
6657 }
6658 }
6659
6660 return OK;
6661}
6662
6663status_t Camera3Device::stopInjection() {
6664 ALOGI("%s: Injection camera: stopInjection", __FUNCTION__);
6665 Mutex::Autolock il(mInterfaceLock);
Cliff Wu3b268182021-07-06 15:44:43 +08006666 Mutex::Autolock l(mLock);
Cliff Wuc2ad9c82021-04-21 00:58:58 +08006667 return mInjectionMethods->stopInjection();
6668}
6669
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08006670}; // namespace android