blob: fc17f4f48d3b22ea350d429787f82c7228260ba5 [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,
3086 const std::unordered_map<std::string, CameraMetadata>& physicalMetadata) {
3087
3088 mTagMonitor.monitorMetadata(source, frameNumber, timestamp, metadata,
3089 physicalMetadata);
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07003090}
3091
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003092/**
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003093 * HalInterface inner class methods
3094 */
3095
Yifan Hongf79b5542017-04-11 14:44:25 -07003096Camera3Device::HalInterface::HalInterface(
3097 sp<ICameraDeviceSession> &session,
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003098 std::shared_ptr<RequestMetadataQueue> queue,
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003099 bool useHalBufManager, bool supportOfflineProcessing) :
Yifan Hongf79b5542017-04-11 14:44:25 -07003100 mHidlSession(session),
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003101 mRequestMetadataQueue(queue),
Emilian Peev4ec17882019-01-24 17:16:58 -08003102 mUseHalBufManager(useHalBufManager),
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003103 mIsReconfigurationQuerySupported(true),
3104 mSupportOfflineProcessing(supportOfflineProcessing) {
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003105 // Check with hardware service manager if we can downcast these interfaces
3106 // Somewhat expensive, so cache the results at startup
Shuzhen Wang83bff122020-11-20 15:51:39 -08003107 auto castResult_3_7 = device::V3_7::ICameraDeviceSession::castFrom(mHidlSession);
3108 if (castResult_3_7.isOk()) {
3109 mHidlSession_3_7 = castResult_3_7;
3110 }
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003111 auto castResult_3_6 = device::V3_6::ICameraDeviceSession::castFrom(mHidlSession);
3112 if (castResult_3_6.isOk()) {
3113 mHidlSession_3_6 = castResult_3_6;
3114 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003115 auto castResult_3_5 = device::V3_5::ICameraDeviceSession::castFrom(mHidlSession);
3116 if (castResult_3_5.isOk()) {
3117 mHidlSession_3_5 = castResult_3_5;
3118 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003119 auto castResult_3_4 = device::V3_4::ICameraDeviceSession::castFrom(mHidlSession);
3120 if (castResult_3_4.isOk()) {
3121 mHidlSession_3_4 = castResult_3_4;
3122 }
3123 auto castResult_3_3 = device::V3_3::ICameraDeviceSession::castFrom(mHidlSession);
3124 if (castResult_3_3.isOk()) {
3125 mHidlSession_3_3 = castResult_3_3;
3126 }
3127}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003128
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003129Camera3Device::HalInterface::HalInterface() :
3130 mUseHalBufManager(false),
3131 mSupportOfflineProcessing(false) {}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003132
3133Camera3Device::HalInterface::HalInterface(const HalInterface& other) :
Yifan Hongf79b5542017-04-11 14:44:25 -07003134 mHidlSession(other.mHidlSession),
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003135 mRequestMetadataQueue(other.mRequestMetadataQueue),
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003136 mUseHalBufManager(other.mUseHalBufManager),
3137 mSupportOfflineProcessing(other.mSupportOfflineProcessing) {}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003138
3139bool Camera3Device::HalInterface::valid() {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003140 return (mHidlSession != nullptr);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003141}
3142
3143void Camera3Device::HalInterface::clear() {
Shuzhen Wang83bff122020-11-20 15:51:39 -08003144 mHidlSession_3_7.clear();
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003145 mHidlSession_3_6.clear();
Emilian Peev644a3e12018-11-23 13:52:39 +00003146 mHidlSession_3_5.clear();
Emilian Peev9e740b02018-01-30 18:28:03 +00003147 mHidlSession_3_4.clear();
3148 mHidlSession_3_3.clear();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003149 mHidlSession.clear();
3150}
3151
3152status_t Camera3Device::HalInterface::constructDefaultRequestSettings(
Emilian Peevf4816702020-04-03 15:44:51 -07003153 camera_request_template_t templateId,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003154 /*out*/ camera_metadata_t **requestTemplate) {
3155 ATRACE_NAME("CameraHal::constructDefaultRequestSettings");
3156 if (!valid()) return INVALID_OPERATION;
3157 status_t res = OK;
3158
Emilian Peev31abd0a2017-05-11 18:37:46 +01003159 common::V1_0::Status status;
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003160
3161 auto requestCallback = [&status, &requestTemplate]
Emilian Peev31abd0a2017-05-11 18:37:46 +01003162 (common::V1_0::Status s, const device::V3_2::CameraMetadata& request) {
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003163 status = s;
3164 if (status == common::V1_0::Status::OK) {
3165 const camera_metadata *r =
3166 reinterpret_cast<const camera_metadata_t*>(request.data());
3167 size_t expectedSize = request.size();
3168 int ret = validate_camera_metadata_structure(r, &expectedSize);
3169 if (ret == OK || ret == CAMERA_METADATA_VALIDATION_SHIFTED) {
3170 *requestTemplate = clone_camera_metadata(r);
3171 if (*requestTemplate == nullptr) {
3172 ALOGE("%s: Unable to clone camera metadata received from HAL",
3173 __FUNCTION__);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003174 status = common::V1_0::Status::INTERNAL_ERROR;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003175 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003176 } else {
3177 ALOGE("%s: Malformed camera metadata received from HAL", __FUNCTION__);
3178 status = common::V1_0::Status::INTERNAL_ERROR;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003179 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003180 }
3181 };
3182 hardware::Return<void> err;
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003183 RequestTemplate id;
3184 switch (templateId) {
Emilian Peevf4816702020-04-03 15:44:51 -07003185 case CAMERA_TEMPLATE_PREVIEW:
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003186 id = RequestTemplate::PREVIEW;
3187 break;
Emilian Peevf4816702020-04-03 15:44:51 -07003188 case CAMERA_TEMPLATE_STILL_CAPTURE:
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003189 id = RequestTemplate::STILL_CAPTURE;
3190 break;
Emilian Peevf4816702020-04-03 15:44:51 -07003191 case CAMERA_TEMPLATE_VIDEO_RECORD:
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003192 id = RequestTemplate::VIDEO_RECORD;
3193 break;
Emilian Peevf4816702020-04-03 15:44:51 -07003194 case CAMERA_TEMPLATE_VIDEO_SNAPSHOT:
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003195 id = RequestTemplate::VIDEO_SNAPSHOT;
3196 break;
Emilian Peevf4816702020-04-03 15:44:51 -07003197 case CAMERA_TEMPLATE_ZERO_SHUTTER_LAG:
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003198 id = RequestTemplate::ZERO_SHUTTER_LAG;
3199 break;
Emilian Peevf4816702020-04-03 15:44:51 -07003200 case CAMERA_TEMPLATE_MANUAL:
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003201 id = RequestTemplate::MANUAL;
3202 break;
3203 default:
3204 // Unknown template ID, or this HAL is too old to support it
3205 return BAD_VALUE;
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003206 }
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003207 err = mHidlSession->constructDefaultRequestSettings(id, requestCallback);
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003208
Emilian Peev31abd0a2017-05-11 18:37:46 +01003209 if (!err.isOk()) {
3210 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3211 res = DEAD_OBJECT;
3212 } else {
3213 res = CameraProviderManager::mapToStatusT(status);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003214 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003215
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003216 return res;
3217}
3218
Emilian Peev4ec17882019-01-24 17:16:58 -08003219bool Camera3Device::HalInterface::isReconfigurationRequired(CameraMetadata& oldSessionParams,
3220 CameraMetadata& newSessionParams) {
3221 // We do reconfiguration by default;
3222 bool ret = true;
3223 if ((mHidlSession_3_5 != nullptr) && mIsReconfigurationQuerySupported) {
3224 android::hardware::hidl_vec<uint8_t> oldParams, newParams;
3225 camera_metadata_t* oldSessioMeta = const_cast<camera_metadata_t*>(
3226 oldSessionParams.getAndLock());
3227 camera_metadata_t* newSessioMeta = const_cast<camera_metadata_t*>(
3228 newSessionParams.getAndLock());
3229 oldParams.setToExternal(reinterpret_cast<uint8_t*>(oldSessioMeta),
3230 get_camera_metadata_size(oldSessioMeta));
3231 newParams.setToExternal(reinterpret_cast<uint8_t*>(newSessioMeta),
3232 get_camera_metadata_size(newSessioMeta));
3233 hardware::camera::common::V1_0::Status callStatus;
3234 bool required;
3235 auto hidlCb = [&callStatus, &required] (hardware::camera::common::V1_0::Status s,
3236 bool requiredFlag) {
3237 callStatus = s;
3238 required = requiredFlag;
3239 };
3240 auto err = mHidlSession_3_5->isReconfigurationRequired(oldParams, newParams, hidlCb);
3241 oldSessionParams.unlock(oldSessioMeta);
3242 newSessionParams.unlock(newSessioMeta);
3243 if (err.isOk()) {
3244 switch (callStatus) {
3245 case hardware::camera::common::V1_0::Status::OK:
3246 ret = required;
3247 break;
3248 case hardware::camera::common::V1_0::Status::METHOD_NOT_SUPPORTED:
3249 mIsReconfigurationQuerySupported = false;
3250 ret = true;
3251 break;
3252 default:
3253 ALOGV("%s: Reconfiguration query failed: %d", __FUNCTION__, callStatus);
3254 ret = true;
3255 }
3256 } else {
3257 ALOGE("%s: Unexpected binder error: %s", __FUNCTION__, err.description().c_str());
3258 ret = true;
3259 }
3260 }
3261
3262 return ret;
3263}
3264
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003265status_t Camera3Device::HalInterface::configureStreams(const camera_metadata_t *sessionParams,
Emilian Peevf4816702020-04-03 15:44:51 -07003266 camera_stream_configuration *config, const std::vector<uint32_t>& bufferSizes) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003267 ATRACE_NAME("CameraHal::configureStreams");
3268 if (!valid()) return INVALID_OPERATION;
3269 status_t res = OK;
3270
Shuzhen Wang83bff122020-11-20 15:51:39 -08003271 if (config->input_is_multi_resolution && mHidlSession_3_7 == nullptr) {
3272 ALOGE("%s: Camera device doesn't support multi-resolution input stream", __FUNCTION__);
3273 return BAD_VALUE;
3274 }
3275
Emilian Peev31abd0a2017-05-11 18:37:46 +01003276 // Convert stream config to HIDL
3277 std::set<int> activeStreams;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003278 device::V3_2::StreamConfiguration requestedConfiguration3_2;
3279 device::V3_4::StreamConfiguration requestedConfiguration3_4;
Shuzhen Wang83bff122020-11-20 15:51:39 -08003280 device::V3_7::StreamConfiguration requestedConfiguration3_7;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003281 requestedConfiguration3_2.streams.resize(config->num_streams);
3282 requestedConfiguration3_4.streams.resize(config->num_streams);
Shuzhen Wang83bff122020-11-20 15:51:39 -08003283 requestedConfiguration3_7.streams.resize(config->num_streams);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003284 for (size_t i = 0; i < config->num_streams; i++) {
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003285 device::V3_2::Stream &dst3_2 = requestedConfiguration3_2.streams[i];
3286 device::V3_4::Stream &dst3_4 = requestedConfiguration3_4.streams[i];
Shuzhen Wang83bff122020-11-20 15:51:39 -08003287 device::V3_7::Stream &dst3_7 = requestedConfiguration3_7.streams[i];
Emilian Peevf4816702020-04-03 15:44:51 -07003288 camera3::camera_stream_t *src = config->streams[i];
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003289
Emilian Peev31abd0a2017-05-11 18:37:46 +01003290 Camera3Stream* cam3stream = Camera3Stream::cast(src);
3291 cam3stream->setBufferFreedListener(this);
3292 int streamId = cam3stream->getId();
3293 StreamType streamType;
3294 switch (src->stream_type) {
Emilian Peevf4816702020-04-03 15:44:51 -07003295 case CAMERA_STREAM_OUTPUT:
Emilian Peev31abd0a2017-05-11 18:37:46 +01003296 streamType = StreamType::OUTPUT;
3297 break;
Emilian Peevf4816702020-04-03 15:44:51 -07003298 case CAMERA_STREAM_INPUT:
Emilian Peev31abd0a2017-05-11 18:37:46 +01003299 streamType = StreamType::INPUT;
3300 break;
3301 default:
3302 ALOGE("%s: Stream %d: Unsupported stream type %d",
3303 __FUNCTION__, streamId, config->streams[i]->stream_type);
3304 return BAD_VALUE;
3305 }
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003306 dst3_2.id = streamId;
3307 dst3_2.streamType = streamType;
3308 dst3_2.width = src->width;
3309 dst3_2.height = src->height;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003310 dst3_2.usage = mapToConsumerUsage(cam3stream->getUsage());
Emilian Peevf4816702020-04-03 15:44:51 -07003311 dst3_2.rotation = mapToStreamRotation((camera_stream_rotation_t) src->rotation);
Shuzhen Wang92653952019-05-07 15:11:43 -07003312 // For HidlSession version 3.5 or newer, the format and dataSpace sent
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08003313 // to HAL are original, not the overridden ones.
Shuzhen Wang92653952019-05-07 15:11:43 -07003314 if (mHidlSession_3_5 != nullptr) {
3315 dst3_2.format = mapToPixelFormat(cam3stream->isFormatOverridden() ?
3316 cam3stream->getOriginalFormat() : src->format);
3317 dst3_2.dataSpace = mapToHidlDataspace(cam3stream->isDataSpaceOverridden() ?
3318 cam3stream->getOriginalDataSpace() : src->data_space);
3319 } else {
3320 dst3_2.format = mapToPixelFormat(src->format);
3321 dst3_2.dataSpace = mapToHidlDataspace(src->data_space);
3322 }
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003323 dst3_4.v3_2 = dst3_2;
Emilian Peev192ee832018-01-31 14:46:47 +00003324 dst3_4.bufferSize = bufferSizes[i];
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003325 if (src->physical_camera_id != nullptr) {
3326 dst3_4.physicalCameraId = src->physical_camera_id;
3327 }
Shuzhen Wang83bff122020-11-20 15:51:39 -08003328 dst3_7.v3_4 = dst3_4;
3329 dst3_7.groupId = cam3stream->getHalStreamGroupId();
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08003330 dst3_7.sensorPixelModesUsed.resize(src->sensor_pixel_modes_used.size());
3331 size_t j = 0;
3332 for (int mode : src->sensor_pixel_modes_used) {
3333 dst3_7.sensorPixelModesUsed[j++] =
3334 static_cast<CameraMetadataEnumAndroidSensorPixelMode>(mode);
3335 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003336 activeStreams.insert(streamId);
3337 // Create Buffer ID map if necessary
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003338 mBufferRecords.tryCreateBufferCache(streamId);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003339 }
3340 // remove BufferIdMap for deleted streams
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003341 mBufferRecords.removeInactiveBufferCaches(activeStreams);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003342
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003343 StreamConfigurationMode operationMode;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003344 res = mapToStreamConfigurationMode(
Emilian Peevf4816702020-04-03 15:44:51 -07003345 (camera_stream_configuration_mode_t) config->operation_mode,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003346 /*out*/ &operationMode);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003347 if (res != OK) {
3348 return res;
3349 }
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003350 requestedConfiguration3_2.operationMode = operationMode;
3351 requestedConfiguration3_4.operationMode = operationMode;
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08003352 requestedConfiguration3_7.operationMode = operationMode;
3353 size_t sessionParamSize = get_camera_metadata_size(sessionParams);
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003354 requestedConfiguration3_4.sessionParams.setToExternal(
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003355 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(sessionParams)),
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08003356 sessionParamSize);
Shuzhen Wang83bff122020-11-20 15:51:39 -08003357 requestedConfiguration3_7.operationMode = operationMode;
3358 requestedConfiguration3_7.sessionParams.setToExternal(
3359 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(sessionParams)),
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08003360 sessionParamSize);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003361
Emilian Peev31abd0a2017-05-11 18:37:46 +01003362 // Invoke configureStreams
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003363 device::V3_3::HalStreamConfiguration finalConfiguration;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003364 device::V3_4::HalStreamConfiguration finalConfiguration3_4;
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003365 device::V3_6::HalStreamConfiguration finalConfiguration3_6;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003366 common::V1_0::Status status;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003367
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003368 auto configStream34Cb = [&status, &finalConfiguration3_4]
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003369 (common::V1_0::Status s, const device::V3_4::HalStreamConfiguration& halConfiguration) {
3370 finalConfiguration3_4 = halConfiguration;
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003371 status = s;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003372 };
3373
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003374 auto configStream36Cb = [&status, &finalConfiguration3_6]
3375 (common::V1_0::Status s, const device::V3_6::HalStreamConfiguration& halConfiguration) {
3376 finalConfiguration3_6 = halConfiguration;
3377 status = s;
3378 };
3379
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003380 auto postprocConfigStream34 = [&finalConfiguration, &finalConfiguration3_4]
3381 (hardware::Return<void>& err) -> status_t {
3382 if (!err.isOk()) {
3383 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3384 return DEAD_OBJECT;
3385 }
3386 finalConfiguration.streams.resize(finalConfiguration3_4.streams.size());
3387 for (size_t i = 0; i < finalConfiguration3_4.streams.size(); i++) {
3388 finalConfiguration.streams[i] = finalConfiguration3_4.streams[i].v3_3;
3389 }
3390 return OK;
3391 };
3392
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003393 auto postprocConfigStream36 = [&finalConfiguration, &finalConfiguration3_6]
3394 (hardware::Return<void>& err) -> status_t {
3395 if (!err.isOk()) {
3396 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3397 return DEAD_OBJECT;
3398 }
3399 finalConfiguration.streams.resize(finalConfiguration3_6.streams.size());
3400 for (size_t i = 0; i < finalConfiguration3_6.streams.size(); i++) {
3401 finalConfiguration.streams[i] = finalConfiguration3_6.streams[i].v3_4.v3_3;
3402 }
3403 return OK;
3404 };
3405
Shuzhen Wang92653952019-05-07 15:11:43 -07003406 // See which version of HAL we have
Shuzhen Wang83bff122020-11-20 15:51:39 -08003407 if (mHidlSession_3_7 != nullptr) {
3408 ALOGV("%s: v3.7 device found", __FUNCTION__);
3409 requestedConfiguration3_7.streamConfigCounter = mNextStreamConfigCounter++;
3410 requestedConfiguration3_7.multiResolutionInputImage = config->input_is_multi_resolution;
3411 auto err = mHidlSession_3_7->configureStreams_3_7(
3412 requestedConfiguration3_7, configStream36Cb);
3413 res = postprocConfigStream36(err);
3414 if (res != OK) {
3415 return res;
3416 }
3417 } else if (mHidlSession_3_6 != nullptr) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003418 ALOGV("%s: v3.6 device found", __FUNCTION__);
3419 device::V3_5::StreamConfiguration requestedConfiguration3_5;
3420 requestedConfiguration3_5.v3_4 = requestedConfiguration3_4;
3421 requestedConfiguration3_5.streamConfigCounter = mNextStreamConfigCounter++;
3422 auto err = mHidlSession_3_6->configureStreams_3_6(
3423 requestedConfiguration3_5, configStream36Cb);
3424 res = postprocConfigStream36(err);
3425 if (res != OK) {
3426 return res;
3427 }
3428 } else if (mHidlSession_3_5 != nullptr) {
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003429 ALOGV("%s: v3.5 device found", __FUNCTION__);
3430 device::V3_5::StreamConfiguration requestedConfiguration3_5;
3431 requestedConfiguration3_5.v3_4 = requestedConfiguration3_4;
3432 requestedConfiguration3_5.streamConfigCounter = mNextStreamConfigCounter++;
3433 auto err = mHidlSession_3_5->configureStreams_3_5(
3434 requestedConfiguration3_5, configStream34Cb);
3435 res = postprocConfigStream34(err);
3436 if (res != OK) {
3437 return res;
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003438 }
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003439 } else if (mHidlSession_3_4 != nullptr) {
3440 // We do; use v3.4 for the call
3441 ALOGV("%s: v3.4 device found", __FUNCTION__);
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003442 auto err = mHidlSession_3_4->configureStreams_3_4(
3443 requestedConfiguration3_4, configStream34Cb);
3444 res = postprocConfigStream34(err);
3445 if (res != OK) {
3446 return res;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003447 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003448 } else if (mHidlSession_3_3 != nullptr) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003449 // We do; use v3.3 for the call
3450 ALOGV("%s: v3.3 device found", __FUNCTION__);
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003451 auto err = mHidlSession_3_3->configureStreams_3_3(requestedConfiguration3_2,
Emilian Peev31abd0a2017-05-11 18:37:46 +01003452 [&status, &finalConfiguration]
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003453 (common::V1_0::Status s, const device::V3_3::HalStreamConfiguration& halConfiguration) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003454 finalConfiguration = halConfiguration;
3455 status = s;
3456 });
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003457 if (!err.isOk()) {
3458 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3459 return DEAD_OBJECT;
3460 }
3461 } else {
3462 // We don't; use v3.2 call and construct a v3.3 HalStreamConfiguration
3463 ALOGV("%s: v3.2 device found", __FUNCTION__);
3464 HalStreamConfiguration finalConfiguration_3_2;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003465 auto err = mHidlSession->configureStreams(requestedConfiguration3_2,
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003466 [&status, &finalConfiguration_3_2]
3467 (common::V1_0::Status s, const HalStreamConfiguration& halConfiguration) {
3468 finalConfiguration_3_2 = halConfiguration;
3469 status = s;
3470 });
3471 if (!err.isOk()) {
3472 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3473 return DEAD_OBJECT;
3474 }
3475 finalConfiguration.streams.resize(finalConfiguration_3_2.streams.size());
3476 for (size_t i = 0; i < finalConfiguration_3_2.streams.size(); i++) {
3477 finalConfiguration.streams[i].v3_2 = finalConfiguration_3_2.streams[i];
3478 finalConfiguration.streams[i].overrideDataSpace =
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003479 requestedConfiguration3_2.streams[i].dataSpace;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003480 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003481 }
3482
3483 if (status != common::V1_0::Status::OK ) {
3484 return CameraProviderManager::mapToStatusT(status);
3485 }
3486
3487 // And convert output stream configuration from HIDL
3488
3489 for (size_t i = 0; i < config->num_streams; i++) {
Emilian Peevf4816702020-04-03 15:44:51 -07003490 camera3::camera_stream_t *dst = config->streams[i];
Emilian Peev31abd0a2017-05-11 18:37:46 +01003491 int streamId = Camera3Stream::cast(dst)->getId();
3492
3493 // Start scan at i, with the assumption that the stream order matches
3494 size_t realIdx = i;
3495 bool found = false;
Eino-Ville Talvala370875f2019-04-12 12:40:27 -07003496 size_t halStreamCount = finalConfiguration.streams.size();
3497 for (size_t idx = 0; idx < halStreamCount; idx++) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003498 if (finalConfiguration.streams[realIdx].v3_2.id == streamId) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003499 found = true;
3500 break;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003501 }
Eino-Ville Talvala370875f2019-04-12 12:40:27 -07003502 realIdx = (realIdx >= halStreamCount - 1) ? 0 : realIdx + 1;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003503 }
3504 if (!found) {
3505 ALOGE("%s: Stream %d not found in stream configuration response from HAL",
3506 __FUNCTION__, streamId);
3507 return INVALID_OPERATION;
3508 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003509 device::V3_3::HalStream &src = finalConfiguration.streams[realIdx];
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003510 device::V3_6::HalStream &src_36 = finalConfiguration3_6.streams[realIdx];
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003511
Emilian Peev710c1422017-08-30 11:19:38 +01003512 Camera3Stream* dstStream = Camera3Stream::cast(dst);
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003513 int overrideFormat = mapToFrameworkFormat(src.v3_2.overrideFormat);
3514 android_dataspace overrideDataSpace = mapToFrameworkDataspace(src.overrideDataSpace);
3515
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003516 if (mHidlSession_3_6 != nullptr) {
3517 dstStream->setOfflineProcessingSupport(src_36.supportOffline);
3518 }
3519
Yin-Chia Yeh90667662019-07-01 15:45:00 -07003520 if (dstStream->getOriginalFormat() != HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
Shuzhen Wang92653952019-05-07 15:11:43 -07003521 dstStream->setFormatOverride(false);
3522 dstStream->setDataSpaceOverride(false);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003523 if (dst->format != overrideFormat) {
3524 ALOGE("%s: Stream %d: Format override not allowed for format 0x%x", __FUNCTION__,
3525 streamId, dst->format);
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003526 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003527 if (dst->data_space != overrideDataSpace) {
3528 ALOGE("%s: Stream %d: DataSpace override not allowed for format 0x%x", __FUNCTION__,
3529 streamId, dst->format);
3530 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003531 } else {
Shuzhen Wang92653952019-05-07 15:11:43 -07003532 bool needFormatOverride =
3533 requestedConfiguration3_2.streams[i].format != src.v3_2.overrideFormat;
3534 bool needDataspaceOverride =
3535 requestedConfiguration3_2.streams[i].dataSpace != src.overrideDataSpace;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003536 // Override allowed with IMPLEMENTATION_DEFINED
Shuzhen Wang92653952019-05-07 15:11:43 -07003537 dstStream->setFormatOverride(needFormatOverride);
3538 dstStream->setDataSpaceOverride(needDataspaceOverride);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003539 dst->format = overrideFormat;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003540 dst->data_space = overrideDataSpace;
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003541 }
3542
Emilian Peevf4816702020-04-03 15:44:51 -07003543 if (dst->stream_type == CAMERA_STREAM_INPUT) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003544 if (src.v3_2.producerUsage != 0) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003545 ALOGE("%s: Stream %d: INPUT streams must have 0 for producer usage",
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003546 __FUNCTION__, streamId);
3547 return INVALID_OPERATION;
3548 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003549 dstStream->setUsage(
3550 mapConsumerToFrameworkUsage(src.v3_2.consumerUsage));
Emilian Peev31abd0a2017-05-11 18:37:46 +01003551 } else {
3552 // OUTPUT
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003553 if (src.v3_2.consumerUsage != 0) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003554 ALOGE("%s: Stream %d: OUTPUT streams must have 0 for consumer usage",
3555 __FUNCTION__, streamId);
3556 return INVALID_OPERATION;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003557 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003558 dstStream->setUsage(
3559 mapProducerToFrameworkUsage(src.v3_2.producerUsage));
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003560 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003561 dst->max_buffers = src.v3_2.maxBuffers;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003562 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003563
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003564 return res;
3565}
3566
Cliff Wuc2ad9c82021-04-21 00:58:58 +08003567status_t Camera3Device::HalInterface::configureInjectedStreams(
3568 const camera_metadata_t* sessionParams, camera_stream_configuration* config,
3569 const std::vector<uint32_t>& bufferSizes,
3570 const CameraMetadata& cameraCharacteristics) {
3571 ATRACE_NAME("InjectionCameraHal::configureStreams");
3572 if (!valid()) return INVALID_OPERATION;
3573 status_t res = OK;
3574
3575 if (config->input_is_multi_resolution) {
3576 ALOGE("%s: Injection camera device doesn't support multi-resolution input "
3577 "stream", __FUNCTION__);
3578 return BAD_VALUE;
3579 }
3580
3581 // Convert stream config to HIDL
3582 std::set<int> activeStreams;
3583 device::V3_2::StreamConfiguration requestedConfiguration3_2;
3584 device::V3_4::StreamConfiguration requestedConfiguration3_4;
3585 device::V3_7::StreamConfiguration requestedConfiguration3_7;
3586 requestedConfiguration3_2.streams.resize(config->num_streams);
3587 requestedConfiguration3_4.streams.resize(config->num_streams);
3588 requestedConfiguration3_7.streams.resize(config->num_streams);
3589 for (size_t i = 0; i < config->num_streams; i++) {
3590 device::V3_2::Stream& dst3_2 = requestedConfiguration3_2.streams[i];
3591 device::V3_4::Stream& dst3_4 = requestedConfiguration3_4.streams[i];
3592 device::V3_7::Stream& dst3_7 = requestedConfiguration3_7.streams[i];
3593 camera3::camera_stream_t* src = config->streams[i];
3594
3595 Camera3Stream* cam3stream = Camera3Stream::cast(src);
3596 cam3stream->setBufferFreedListener(this);
3597 int streamId = cam3stream->getId();
3598 StreamType streamType;
3599 switch (src->stream_type) {
3600 case CAMERA_STREAM_OUTPUT:
3601 streamType = StreamType::OUTPUT;
3602 break;
3603 case CAMERA_STREAM_INPUT:
3604 streamType = StreamType::INPUT;
3605 break;
3606 default:
3607 ALOGE("%s: Stream %d: Unsupported stream type %d", __FUNCTION__,
3608 streamId, config->streams[i]->stream_type);
3609 return BAD_VALUE;
3610 }
3611 dst3_2.id = streamId;
3612 dst3_2.streamType = streamType;
3613 dst3_2.width = src->width;
3614 dst3_2.height = src->height;
3615 dst3_2.usage = mapToConsumerUsage(cam3stream->getUsage());
3616 dst3_2.rotation =
3617 mapToStreamRotation((camera_stream_rotation_t)src->rotation);
3618 // For HidlSession version 3.5 or newer, the format and dataSpace sent
3619 // to HAL are original, not the overridden ones.
3620 if (mHidlSession_3_5 != nullptr) {
3621 dst3_2.format = mapToPixelFormat(cam3stream->isFormatOverridden()
3622 ? cam3stream->getOriginalFormat()
3623 : src->format);
3624 dst3_2.dataSpace =
3625 mapToHidlDataspace(cam3stream->isDataSpaceOverridden()
3626 ? cam3stream->getOriginalDataSpace()
3627 : src->data_space);
3628 } else {
3629 dst3_2.format = mapToPixelFormat(src->format);
3630 dst3_2.dataSpace = mapToHidlDataspace(src->data_space);
3631 }
3632 dst3_4.v3_2 = dst3_2;
3633 dst3_4.bufferSize = bufferSizes[i];
3634 if (src->physical_camera_id != nullptr) {
3635 dst3_4.physicalCameraId = src->physical_camera_id;
3636 }
3637 dst3_7.v3_4 = dst3_4;
3638 dst3_7.groupId = cam3stream->getHalStreamGroupId();
3639 dst3_7.sensorPixelModesUsed.resize(src->sensor_pixel_modes_used.size());
3640 size_t j = 0;
3641 for (int mode : src->sensor_pixel_modes_used) {
3642 dst3_7.sensorPixelModesUsed[j++] =
3643 static_cast<CameraMetadataEnumAndroidSensorPixelMode>(mode);
3644 }
3645 activeStreams.insert(streamId);
3646 // Create Buffer ID map if necessary
3647 mBufferRecords.tryCreateBufferCache(streamId);
3648 }
3649 // remove BufferIdMap for deleted streams
3650 mBufferRecords.removeInactiveBufferCaches(activeStreams);
3651
3652 StreamConfigurationMode operationMode;
3653 res = mapToStreamConfigurationMode(
3654 (camera_stream_configuration_mode_t)config->operation_mode,
3655 /*out*/ &operationMode);
3656 if (res != OK) {
3657 return res;
3658 }
3659 requestedConfiguration3_7.operationMode = operationMode;
3660 size_t sessionParamSize = get_camera_metadata_size(sessionParams);
3661 requestedConfiguration3_7.operationMode = operationMode;
3662 requestedConfiguration3_7.sessionParams.setToExternal(
3663 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(sessionParams)),
3664 sessionParamSize);
3665
3666 // See which version of HAL we have
3667 if (mHidlSession_3_7 != nullptr) {
3668 requestedConfiguration3_7.streamConfigCounter = mNextStreamConfigCounter++;
3669 requestedConfiguration3_7.multiResolutionInputImage =
3670 config->input_is_multi_resolution;
3671
3672 const camera_metadata_t* rawMetadata = cameraCharacteristics.getAndLock();
3673 ::android::hardware::camera::device::V3_2::CameraMetadata hidlChars = {};
3674 hidlChars.setToExternal(
3675 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(rawMetadata)),
3676 get_camera_metadata_size(rawMetadata));
3677 cameraCharacteristics.unlock(rawMetadata);
3678
3679 sp<hardware::camera::device::V3_7::ICameraInjectionSession>
3680 hidlInjectionSession_3_7;
3681 auto castInjectionResult_3_7 =
3682 device::V3_7::ICameraInjectionSession::castFrom(mHidlSession_3_7);
3683 if (castInjectionResult_3_7.isOk()) {
3684 hidlInjectionSession_3_7 = castInjectionResult_3_7;
3685 } else {
3686 ALOGE("%s: Transaction error: %s", __FUNCTION__,
3687 castInjectionResult_3_7.description().c_str());
3688 return DEAD_OBJECT;
3689 }
3690
3691 auto err = hidlInjectionSession_3_7->configureInjectionStreams(
3692 requestedConfiguration3_7, hidlChars);
3693 if (!err.isOk()) {
3694 ALOGE("%s: Transaction error: %s", __FUNCTION__,
3695 err.description().c_str());
3696 return DEAD_OBJECT;
3697 }
3698 } else {
3699 ALOGE("%s: mHidlSession_3_7 does not exist, the lowest version of injection "
3700 "session is 3.7", __FUNCTION__);
3701 return DEAD_OBJECT;
3702 }
3703
3704 return res;
3705}
3706
Emilian Peevf4816702020-04-03 15:44:51 -07003707status_t Camera3Device::HalInterface::wrapAsHidlRequest(camera_capture_request_t* request,
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003708 /*out*/device::V3_2::CaptureRequest* captureRequest,
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003709 /*out*/std::vector<native_handle_t*>* handlesCreated,
3710 /*out*/std::vector<std::pair<int32_t, int32_t>>* inflightBuffers) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003711 ATRACE_CALL();
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003712 if (captureRequest == nullptr || handlesCreated == nullptr || inflightBuffers == nullptr) {
3713 ALOGE("%s: captureRequest (%p), handlesCreated (%p), and inflightBuffers(%p) "
3714 "must not be null", __FUNCTION__, captureRequest, handlesCreated, inflightBuffers);
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003715 return BAD_VALUE;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003716 }
3717
3718 captureRequest->frameNumber = request->frame_number;
Yifan Hongf79b5542017-04-11 14:44:25 -07003719
3720 captureRequest->fmqSettingsSize = 0;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003721
3722 {
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003723 if (request->input_buffer != nullptr) {
3724 int32_t streamId = Camera3Stream::cast(request->input_buffer->stream)->getId();
3725 buffer_handle_t buf = *(request->input_buffer->buffer);
3726 auto pair = getBufferId(buf, streamId);
3727 bool isNewBuffer = pair.first;
3728 uint64_t bufferId = pair.second;
3729 captureRequest->inputBuffer.streamId = streamId;
3730 captureRequest->inputBuffer.bufferId = bufferId;
3731 captureRequest->inputBuffer.buffer = (isNewBuffer) ? buf : nullptr;
3732 captureRequest->inputBuffer.status = BufferStatus::OK;
3733 native_handle_t *acquireFence = nullptr;
3734 if (request->input_buffer->acquire_fence != -1) {
3735 acquireFence = native_handle_create(1,0);
3736 acquireFence->data[0] = request->input_buffer->acquire_fence;
3737 handlesCreated->push_back(acquireFence);
3738 }
3739 captureRequest->inputBuffer.acquireFence = acquireFence;
3740 captureRequest->inputBuffer.releaseFence = nullptr;
3741
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003742 mBufferRecords.pushInflightBuffer(captureRequest->frameNumber, streamId,
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003743 request->input_buffer->buffer);
3744 inflightBuffers->push_back(std::make_pair(captureRequest->frameNumber, streamId));
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003745 } else {
3746 captureRequest->inputBuffer.streamId = -1;
3747 captureRequest->inputBuffer.bufferId = BUFFER_ID_NO_BUFFER;
3748 }
3749
3750 captureRequest->outputBuffers.resize(request->num_output_buffers);
3751 for (size_t i = 0; i < request->num_output_buffers; i++) {
Emilian Peevf4816702020-04-03 15:44:51 -07003752 const camera_stream_buffer_t *src = request->output_buffers + i;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003753 StreamBuffer &dst = captureRequest->outputBuffers[i];
3754 int32_t streamId = Camera3Stream::cast(src->stream)->getId();
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003755 if (src->buffer != nullptr) {
3756 buffer_handle_t buf = *(src->buffer);
3757 auto pair = getBufferId(buf, streamId);
3758 bool isNewBuffer = pair.first;
3759 dst.bufferId = pair.second;
3760 dst.buffer = isNewBuffer ? buf : nullptr;
3761 native_handle_t *acquireFence = nullptr;
3762 if (src->acquire_fence != -1) {
3763 acquireFence = native_handle_create(1,0);
3764 acquireFence->data[0] = src->acquire_fence;
3765 handlesCreated->push_back(acquireFence);
3766 }
3767 dst.acquireFence = acquireFence;
3768 } else if (mUseHalBufManager) {
3769 // HAL buffer management path
3770 dst.bufferId = BUFFER_ID_NO_BUFFER;
3771 dst.buffer = nullptr;
3772 dst.acquireFence = nullptr;
3773 } else {
3774 ALOGE("%s: cannot send a null buffer in capture request!", __FUNCTION__);
3775 return BAD_VALUE;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003776 }
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003777 dst.streamId = streamId;
3778 dst.status = BufferStatus::OK;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003779 dst.releaseFence = nullptr;
3780
Yin-Chia Yeh5f840f82019-03-05 11:59:04 -08003781 // Output buffers are empty when using HAL buffer manager
3782 if (!mUseHalBufManager) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003783 mBufferRecords.pushInflightBuffer(
3784 captureRequest->frameNumber, streamId, src->buffer);
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003785 inflightBuffers->push_back(std::make_pair(captureRequest->frameNumber, streamId));
Yin-Chia Yeh5f840f82019-03-05 11:59:04 -08003786 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003787 }
3788 }
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003789 return OK;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003790}
3791
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003792void Camera3Device::HalInterface::cleanupNativeHandles(
3793 std::vector<native_handle_t*> *handles, bool closeFd) {
3794 if (handles == nullptr) {
3795 return;
3796 }
3797 if (closeFd) {
3798 for (auto& handle : *handles) {
3799 native_handle_close(handle);
3800 }
3801 }
3802 for (auto& handle : *handles) {
3803 native_handle_delete(handle);
3804 }
3805 handles->clear();
3806 return;
3807}
3808
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003809status_t Camera3Device::HalInterface::processBatchCaptureRequests(
Emilian Peevf4816702020-04-03 15:44:51 -07003810 std::vector<camera_capture_request_t*>& requests,/*out*/uint32_t* numRequestProcessed) {
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003811 ATRACE_NAME("CameraHal::processBatchCaptureRequests");
3812 if (!valid()) return INVALID_OPERATION;
3813
Emilian Peevaebbe412018-01-15 13:53:24 +00003814 sp<device::V3_4::ICameraDeviceSession> hidlSession_3_4;
Shuzhen Wang83bff122020-11-20 15:51:39 -08003815 sp<device::V3_7::ICameraDeviceSession> hidlSession_3_7;
3816 auto castResult_3_7 = device::V3_7::ICameraDeviceSession::castFrom(mHidlSession);
3817 if (castResult_3_7.isOk()) {
3818 hidlSession_3_7 = castResult_3_7;
3819 }
Emilian Peevaebbe412018-01-15 13:53:24 +00003820 auto castResult_3_4 = device::V3_4::ICameraDeviceSession::castFrom(mHidlSession);
3821 if (castResult_3_4.isOk()) {
3822 hidlSession_3_4 = castResult_3_4;
3823 }
3824
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003825 hardware::hidl_vec<device::V3_2::CaptureRequest> captureRequests;
Emilian Peevaebbe412018-01-15 13:53:24 +00003826 hardware::hidl_vec<device::V3_4::CaptureRequest> captureRequests_3_4;
Shuzhen Wang83bff122020-11-20 15:51:39 -08003827 hardware::hidl_vec<device::V3_7::CaptureRequest> captureRequests_3_7;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003828 size_t batchSize = requests.size();
Shuzhen Wang83bff122020-11-20 15:51:39 -08003829 if (hidlSession_3_7 != nullptr) {
3830 captureRequests_3_7.resize(batchSize);
3831 } else if (hidlSession_3_4 != nullptr) {
Emilian Peevaebbe412018-01-15 13:53:24 +00003832 captureRequests_3_4.resize(batchSize);
3833 } else {
3834 captureRequests.resize(batchSize);
3835 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003836 std::vector<native_handle_t*> handlesCreated;
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003837 std::vector<std::pair<int32_t, int32_t>> inflightBuffers;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003838
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003839 status_t res = OK;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003840 for (size_t i = 0; i < batchSize; i++) {
Shuzhen Wang83bff122020-11-20 15:51:39 -08003841 if (hidlSession_3_7 != nullptr) {
3842 res = wrapAsHidlRequest(requests[i], /*out*/&captureRequests_3_7[i].v3_4.v3_2,
3843 /*out*/&handlesCreated, /*out*/&inflightBuffers);
3844 } else if (hidlSession_3_4 != nullptr) {
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003845 res = wrapAsHidlRequest(requests[i], /*out*/&captureRequests_3_4[i].v3_2,
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003846 /*out*/&handlesCreated, /*out*/&inflightBuffers);
Emilian Peevaebbe412018-01-15 13:53:24 +00003847 } else {
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003848 res = wrapAsHidlRequest(requests[i], /*out*/&captureRequests[i],
3849 /*out*/&handlesCreated, /*out*/&inflightBuffers);
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003850 }
3851 if (res != OK) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003852 mBufferRecords.popInflightBuffers(inflightBuffers);
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003853 cleanupNativeHandles(&handlesCreated);
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003854 return res;
Emilian Peevaebbe412018-01-15 13:53:24 +00003855 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003856 }
3857
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003858 std::vector<device::V3_2::BufferCache> cachesToRemove;
3859 {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003860 std::lock_guard<std::mutex> lock(mFreedBuffersLock);
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003861 for (auto& pair : mFreedBuffers) {
3862 // The stream might have been removed since onBufferFreed
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003863 if (mBufferRecords.isStreamCached(pair.first)) {
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003864 cachesToRemove.push_back({pair.first, pair.second});
3865 }
3866 }
3867 mFreedBuffers.clear();
3868 }
3869
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003870 common::V1_0::Status status = common::V1_0::Status::INTERNAL_ERROR;
3871 *numRequestProcessed = 0;
Yifan Hongf79b5542017-04-11 14:44:25 -07003872
3873 // Write metadata to FMQ.
3874 for (size_t i = 0; i < batchSize; i++) {
Emilian Peevf4816702020-04-03 15:44:51 -07003875 camera_capture_request_t* request = requests[i];
Emilian Peevaebbe412018-01-15 13:53:24 +00003876 device::V3_2::CaptureRequest* captureRequest;
Shuzhen Wang83bff122020-11-20 15:51:39 -08003877 if (hidlSession_3_7 != nullptr) {
3878 captureRequest = &captureRequests_3_7[i].v3_4.v3_2;
3879 } else if (hidlSession_3_4 != nullptr) {
Emilian Peevaebbe412018-01-15 13:53:24 +00003880 captureRequest = &captureRequests_3_4[i].v3_2;
3881 } else {
3882 captureRequest = &captureRequests[i];
3883 }
Yifan Hongf79b5542017-04-11 14:44:25 -07003884
3885 if (request->settings != nullptr) {
3886 size_t settingsSize = get_camera_metadata_size(request->settings);
3887 if (mRequestMetadataQueue != nullptr && mRequestMetadataQueue->write(
3888 reinterpret_cast<const uint8_t*>(request->settings), settingsSize)) {
3889 captureRequest->settings.resize(0);
3890 captureRequest->fmqSettingsSize = settingsSize;
3891 } else {
3892 if (mRequestMetadataQueue != nullptr) {
3893 ALOGW("%s: couldn't utilize fmq, fallback to hwbinder", __FUNCTION__);
3894 }
3895 captureRequest->settings.setToExternal(
3896 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(request->settings)),
3897 get_camera_metadata_size(request->settings));
3898 captureRequest->fmqSettingsSize = 0u;
3899 }
3900 } else {
3901 // A null request settings maps to a size-0 CameraMetadata
3902 captureRequest->settings.resize(0);
3903 captureRequest->fmqSettingsSize = 0u;
3904 }
Emilian Peevaebbe412018-01-15 13:53:24 +00003905
Shuzhen Wang83bff122020-11-20 15:51:39 -08003906 // hidl session 3.7 specific handling.
3907 if (hidlSession_3_7 != nullptr) {
3908 captureRequests_3_7[i].inputWidth = request->input_width;
3909 captureRequests_3_7[i].inputHeight = request->input_height;
3910 }
3911
3912 // hidl session 3.7 and 3.4 specific handling.
3913 if (hidlSession_3_7 != nullptr || hidlSession_3_4 != nullptr) {
3914 hardware::hidl_vec<device::V3_4::PhysicalCameraSetting>& physicalCameraSettings =
3915 (hidlSession_3_7 != nullptr) ?
3916 captureRequests_3_7[i].v3_4.physicalCameraSettings :
3917 captureRequests_3_4[i].physicalCameraSettings;
3918 physicalCameraSettings.resize(request->num_physcam_settings);
Emilian Peevaebbe412018-01-15 13:53:24 +00003919 for (size_t j = 0; j < request->num_physcam_settings; j++) {
Emilian Peev00420d22018-02-05 21:33:13 +00003920 if (request->physcam_settings != nullptr) {
3921 size_t settingsSize = get_camera_metadata_size(request->physcam_settings[j]);
3922 if (mRequestMetadataQueue != nullptr && mRequestMetadataQueue->write(
3923 reinterpret_cast<const uint8_t*>(request->physcam_settings[j]),
3924 settingsSize)) {
Shuzhen Wang83bff122020-11-20 15:51:39 -08003925 physicalCameraSettings[j].settings.resize(0);
3926 physicalCameraSettings[j].fmqSettingsSize = settingsSize;
Emilian Peev00420d22018-02-05 21:33:13 +00003927 } else {
3928 if (mRequestMetadataQueue != nullptr) {
3929 ALOGW("%s: couldn't utilize fmq, fallback to hwbinder", __FUNCTION__);
3930 }
Shuzhen Wang83bff122020-11-20 15:51:39 -08003931 physicalCameraSettings[j].settings.setToExternal(
Emilian Peev00420d22018-02-05 21:33:13 +00003932 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(
3933 request->physcam_settings[j])),
3934 get_camera_metadata_size(request->physcam_settings[j]));
Shuzhen Wang83bff122020-11-20 15:51:39 -08003935 physicalCameraSettings[j].fmqSettingsSize = 0u;
Emilian Peevaebbe412018-01-15 13:53:24 +00003936 }
Emilian Peev00420d22018-02-05 21:33:13 +00003937 } else {
Yin-Chia Yeha2849702021-03-10 10:11:33 -08003938 physicalCameraSettings[j].fmqSettingsSize = 0u;
3939 physicalCameraSettings[j].settings.resize(0);
Emilian Peevaebbe412018-01-15 13:53:24 +00003940 }
Shuzhen Wang83bff122020-11-20 15:51:39 -08003941 physicalCameraSettings[j].physicalCameraId = request->physcam_id[j];
Emilian Peevaebbe412018-01-15 13:53:24 +00003942 }
3943 }
Yifan Hongf79b5542017-04-11 14:44:25 -07003944 }
Emilian Peevaebbe412018-01-15 13:53:24 +00003945
3946 hardware::details::return_status err;
Jayant Chowdharyc8d581e2018-07-16 14:46:23 -07003947 auto resultCallback =
3948 [&status, &numRequestProcessed] (auto s, uint32_t n) {
3949 status = s;
3950 *numRequestProcessed = n;
3951 };
Shuzhen Wang83bff122020-11-20 15:51:39 -08003952 if (hidlSession_3_7 != nullptr) {
3953 err = hidlSession_3_7->processCaptureRequest_3_7(captureRequests_3_7, cachesToRemove,
3954 resultCallback);
3955 } else if (hidlSession_3_4 != nullptr) {
Emilian Peevaebbe412018-01-15 13:53:24 +00003956 err = hidlSession_3_4->processCaptureRequest_3_4(captureRequests_3_4, cachesToRemove,
Jayant Chowdharyc8d581e2018-07-16 14:46:23 -07003957 resultCallback);
Emilian Peevaebbe412018-01-15 13:53:24 +00003958 } else {
3959 err = mHidlSession->processCaptureRequest(captureRequests, cachesToRemove,
Jayant Chowdharyc8d581e2018-07-16 14:46:23 -07003960 resultCallback);
Emilian Peevaebbe412018-01-15 13:53:24 +00003961 }
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -07003962 if (!err.isOk()) {
3963 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003964 status = common::V1_0::Status::CAMERA_DISCONNECTED;
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -07003965 }
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003966
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003967 if (status == common::V1_0::Status::OK && *numRequestProcessed != batchSize) {
3968 ALOGE("%s: processCaptureRequest returns OK but processed %d/%zu requests",
3969 __FUNCTION__, *numRequestProcessed, batchSize);
3970 status = common::V1_0::Status::INTERNAL_ERROR;
3971 }
3972
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003973 res = CameraProviderManager::mapToStatusT(status);
3974 if (res == OK) {
3975 if (mHidlSession->isRemote()) {
3976 // Only close acquire fence FDs when the HIDL transaction succeeds (so the FDs have been
3977 // sent to camera HAL processes)
3978 cleanupNativeHandles(&handlesCreated, /*closeFd*/true);
3979 } else {
3980 // In passthrough mode the FDs are now owned by HAL
3981 cleanupNativeHandles(&handlesCreated);
3982 }
3983 } else {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003984 mBufferRecords.popInflightBuffers(inflightBuffers);
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003985 cleanupNativeHandles(&handlesCreated);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003986 }
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003987 return res;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003988}
3989
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003990status_t Camera3Device::HalInterface::flush() {
3991 ATRACE_NAME("CameraHal::flush");
3992 if (!valid()) return INVALID_OPERATION;
3993 status_t res = OK;
3994
Emilian Peev31abd0a2017-05-11 18:37:46 +01003995 auto err = mHidlSession->flush();
3996 if (!err.isOk()) {
3997 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3998 res = DEAD_OBJECT;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003999 } else {
Emilian Peev31abd0a2017-05-11 18:37:46 +01004000 res = CameraProviderManager::mapToStatusT(err);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004001 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01004002
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004003 return res;
4004}
4005
Emilian Peev31abd0a2017-05-11 18:37:46 +01004006status_t Camera3Device::HalInterface::dump(int /*fd*/) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004007 ATRACE_NAME("CameraHal::dump");
4008 if (!valid()) return INVALID_OPERATION;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004009
Emilian Peev31abd0a2017-05-11 18:37:46 +01004010 // Handled by CameraProviderManager::dump
4011
4012 return OK;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004013}
4014
4015status_t Camera3Device::HalInterface::close() {
4016 ATRACE_NAME("CameraHal::close()");
4017 if (!valid()) return INVALID_OPERATION;
4018 status_t res = OK;
4019
Emilian Peev31abd0a2017-05-11 18:37:46 +01004020 auto err = mHidlSession->close();
4021 // Interface will be dead shortly anyway, so don't log errors
4022 if (!err.isOk()) {
4023 res = DEAD_OBJECT;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004024 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01004025
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004026 return res;
4027}
4028
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004029void Camera3Device::HalInterface::signalPipelineDrain(const std::vector<int>& streamIds) {
4030 ATRACE_NAME("CameraHal::signalPipelineDrain");
4031 if (!valid() || mHidlSession_3_5 == nullptr) {
4032 ALOGE("%s called on invalid camera!", __FUNCTION__);
4033 return;
4034 }
4035
Yin-Chia Yehc300a072019-02-13 14:56:57 -08004036 auto err = mHidlSession_3_5->signalStreamFlush(streamIds, mNextStreamConfigCounter - 1);
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004037 if (!err.isOk()) {
4038 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
4039 return;
4040 }
4041}
4042
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004043status_t Camera3Device::HalInterface::switchToOffline(
4044 const std::vector<int32_t>& streamsToKeep,
4045 /*out*/hardware::camera::device::V3_6::CameraOfflineSessionInfo* offlineSessionInfo,
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004046 /*out*/sp<hardware::camera::device::V3_6::ICameraOfflineSession>* offlineSession,
4047 /*out*/camera3::BufferRecords* bufferRecords) {
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004048 ATRACE_NAME("CameraHal::switchToOffline");
4049 if (!valid() || mHidlSession_3_6 == nullptr) {
4050 ALOGE("%s called on invalid camera!", __FUNCTION__);
4051 return INVALID_OPERATION;
4052 }
4053
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004054 if (offlineSessionInfo == nullptr || offlineSession == nullptr || bufferRecords == nullptr) {
4055 ALOGE("%s: output arguments must not be null!", __FUNCTION__);
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004056 return INVALID_OPERATION;
4057 }
4058
4059 common::V1_0::Status status = common::V1_0::Status::INTERNAL_ERROR;
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004060 auto resultCallback =
4061 [&status, &offlineSessionInfo, &offlineSession] (auto s, auto info, auto session) {
4062 status = s;
4063 *offlineSessionInfo = info;
4064 *offlineSession = session;
4065 };
4066 auto err = mHidlSession_3_6->switchToOffline(streamsToKeep, resultCallback);
4067
4068 if (!err.isOk()) {
4069 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
4070 return DEAD_OBJECT;
4071 }
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004072
4073 status_t ret = CameraProviderManager::mapToStatusT(status);
4074 if (ret != OK) {
4075 return ret;
4076 }
4077
4078 // TODO: assert no ongoing requestBuffer/returnBuffer call here
4079 // TODO: update RequestBufferStateMachine to block requestBuffer/returnBuffer once HAL
4080 // returns from switchToOffline.
4081
4082
4083 // Validate buffer caches
4084 std::vector<int32_t> streams;
4085 streams.reserve(offlineSessionInfo->offlineStreams.size());
4086 for (auto offlineStream : offlineSessionInfo->offlineStreams) {
4087 int32_t id = offlineStream.id;
4088 streams.push_back(id);
4089 // Verify buffer caches
4090 std::vector<uint64_t> bufIds(offlineStream.circulatingBufferIds.begin(),
4091 offlineStream.circulatingBufferIds.end());
4092 if (!verifyBufferIds(id, bufIds)) {
4093 ALOGE("%s: stream ID %d buffer cache records mismatch!", __FUNCTION__, id);
4094 return UNKNOWN_ERROR;
4095 }
4096 }
4097
4098 // Move buffer records
4099 bufferRecords->takeBufferCaches(mBufferRecords, streams);
4100 bufferRecords->takeInflightBufferMap(mBufferRecords);
4101 bufferRecords->takeRequestedBufferMap(mBufferRecords);
4102 return ret;
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004103}
4104
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07004105void Camera3Device::HalInterface::getInflightBufferKeys(
4106 std::vector<std::pair<int32_t, int32_t>>* out) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004107 mBufferRecords.getInflightBufferKeys(out);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07004108 return;
4109}
4110
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08004111void Camera3Device::HalInterface::getInflightRequestBufferKeys(
4112 std::vector<uint64_t>* out) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004113 mBufferRecords.getInflightRequestBufferKeys(out);
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08004114 return;
4115}
4116
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004117bool Camera3Device::HalInterface::verifyBufferIds(
4118 int32_t streamId, std::vector<uint64_t>& bufIds) {
4119 return mBufferRecords.verifyBufferIds(streamId, bufIds);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004120}
4121
4122status_t Camera3Device::HalInterface::popInflightBuffer(
Yin-Chia Yehf4650602017-01-10 13:13:39 -08004123 int32_t frameNumber, int32_t streamId,
4124 /*out*/ buffer_handle_t **buffer) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004125 return mBufferRecords.popInflightBuffer(frameNumber, streamId, buffer);
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07004126}
4127
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004128status_t Camera3Device::HalInterface::pushInflightRequestBuffer(
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08004129 uint64_t bufferId, buffer_handle_t* buf, int32_t streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004130 return mBufferRecords.pushInflightRequestBuffer(bufferId, buf, streamId);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004131}
4132
4133// Find and pop a buffer_handle_t based on bufferId
4134status_t Camera3Device::HalInterface::popInflightRequestBuffer(
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08004135 uint64_t bufferId,
4136 /*out*/ buffer_handle_t** buffer,
4137 /*optional out*/ int32_t* streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004138 return mBufferRecords.popInflightRequestBuffer(bufferId, buffer, streamId);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004139}
4140
Yin-Chia Yeh77327052017-01-09 18:23:07 -08004141std::pair<bool, uint64_t> Camera3Device::HalInterface::getBufferId(
4142 const buffer_handle_t& buf, int streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004143 return mBufferRecords.getBufferId(buf, streamId);
Yin-Chia Yeh77327052017-01-09 18:23:07 -08004144}
4145
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07004146void Camera3Device::HalInterface::onBufferFreed(
4147 int streamId, const native_handle_t* handle) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004148 uint32_t bufferId = mBufferRecords.removeOneBufferCache(streamId, handle);
4149 std::lock_guard<std::mutex> lock(mFreedBuffersLock);
4150 if (bufferId != BUFFER_ID_NO_BUFFER) {
4151 mFreedBuffers.push_back(std::make_pair(streamId, bufferId));
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07004152 }
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07004153}
4154
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07004155void Camera3Device::HalInterface::onStreamReConfigured(int streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004156 std::vector<uint64_t> bufIds = mBufferRecords.clearBufferCaches(streamId);
4157 std::lock_guard<std::mutex> lock(mFreedBuffersLock);
4158 for (auto bufferId : bufIds) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07004159 mFreedBuffers.push_back(std::make_pair(streamId, bufferId));
4160 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07004161}
4162
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004163/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004164 * RequestThread inner class methods
4165 */
4166
4167Camera3Device::RequestThread::RequestThread(wp<Camera3Device> parent,
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004168 sp<StatusTracker> statusTracker,
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004169 sp<HalInterface> interface, const Vector<int32_t>& sessionParamKeys,
Eino-Ville Talvala1646c3c2021-07-29 13:48:40 -07004170 bool useHalBufManager,
4171 bool supportCameraMute) :
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004172 Thread(/*canCallJava*/false),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004173 mParent(parent),
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004174 mStatusTracker(statusTracker),
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004175 mInterface(interface),
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07004176 mListener(nullptr),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004177 mId(getId(parent)),
Shuzhen Wang316781a2020-08-18 18:11:01 -07004178 mFirstRepeating(false),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004179 mReconfigured(false),
4180 mDoPause(false),
4181 mPaused(true),
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004182 mNotifyPipelineDrain(false),
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004183 mFrameNumber(0),
Jianing Weicb0652e2014-03-12 18:29:36 -07004184 mLatestRequestId(NAME_NOT_FOUND),
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07004185 mCurrentAfTriggerId(0),
4186 mCurrentPreCaptureTriggerId(0),
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004187 mRotateAndCropOverride(ANDROID_SCALER_ROTATE_AND_CROP_NONE),
Eino-Ville Talvala11afe4f2021-05-27 14:45:31 -07004188 mCameraMute(ANDROID_SENSOR_TEST_PATTERN_MODE_OFF),
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004189 mCameraMuteChanged(false),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004190 mRepeatingLastFrameNumber(
4191 hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES),
Shuzhen Wang686f6442017-06-20 16:16:04 -07004192 mPrepareVideoStream(false),
Emilian Peeva14b4dd2018-05-15 11:00:31 +01004193 mConstrainedMode(false),
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004194 mRequestLatency(kRequestLatencyBinSize),
4195 mSessionParamKeys(sessionParamKeys),
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004196 mLatestSessionParams(sessionParamKeys.size()),
Eino-Ville Talvala1646c3c2021-07-29 13:48:40 -07004197 mUseHalBufManager(useHalBufManager),
4198 mSupportCameraMute(supportCameraMute){
Yin-Chia Yeh87b3ec02019-06-03 10:44:39 -07004199 mStatusId = statusTracker->addComponent("RequestThread");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004200}
4201
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004202Camera3Device::RequestThread::~RequestThread() {}
4203
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004204void Camera3Device::RequestThread::setNotificationListener(
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004205 wp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004206 ATRACE_CALL();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004207 Mutex::Autolock l(mRequestLock);
4208 mListener = listener;
4209}
4210
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004211void Camera3Device::RequestThread::configurationComplete(bool isConstrainedHighSpeed,
Shuzhen Wang99080502021-03-07 21:08:20 -08004212 const CameraMetadata& sessionParams,
4213 const std::map<int32_t, std::set<String8>>& groupIdPhysicalCameraMap) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004214 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004215 Mutex::Autolock l(mRequestLock);
4216 mReconfigured = true;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004217 mLatestSessionParams = sessionParams;
Shuzhen Wang99080502021-03-07 21:08:20 -08004218 mGroupIdPhysicalCameraMap = groupIdPhysicalCameraMap;
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07004219 // Prepare video stream for high speed recording.
4220 mPrepareVideoStream = isConstrainedHighSpeed;
Emilian Peeva14b4dd2018-05-15 11:00:31 +01004221 mConstrainedMode = isConstrainedHighSpeed;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004222}
4223
Jianing Wei90e59c92014-03-12 18:29:36 -07004224status_t Camera3Device::RequestThread::queueRequestList(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004225 List<sp<CaptureRequest> > &requests,
4226 /*out*/
4227 int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004228 ATRACE_CALL();
Jianing Wei90e59c92014-03-12 18:29:36 -07004229 Mutex::Autolock l(mRequestLock);
4230 for (List<sp<CaptureRequest> >::iterator it = requests.begin(); it != requests.end();
4231 ++it) {
4232 mRequestQueue.push_back(*it);
4233 }
4234
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004235 if (lastFrameNumber != NULL) {
4236 *lastFrameNumber = mFrameNumber + mRequestQueue.size() - 1;
4237 ALOGV("%s: requestId %d, mFrameNumber %" PRId32 ", lastFrameNumber %" PRId64 ".",
4238 __FUNCTION__, (*(requests.begin()))->mResultExtras.requestId, mFrameNumber,
4239 *lastFrameNumber);
4240 }
Jianing Weicb0652e2014-03-12 18:29:36 -07004241
Jianing Wei90e59c92014-03-12 18:29:36 -07004242 unpauseForNewRequests();
4243
4244 return OK;
4245}
4246
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004247
4248status_t Camera3Device::RequestThread::queueTrigger(
4249 RequestTrigger trigger[],
4250 size_t count) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004251 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004252 Mutex::Autolock l(mTriggerMutex);
4253 status_t ret;
4254
4255 for (size_t i = 0; i < count; ++i) {
4256 ret = queueTriggerLocked(trigger[i]);
4257
4258 if (ret != OK) {
4259 return ret;
4260 }
4261 }
4262
4263 return OK;
4264}
4265
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004266const String8& Camera3Device::RequestThread::getId(const wp<Camera3Device> &device) {
4267 static String8 deadId("<DeadDevice>");
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004268 sp<Camera3Device> d = device.promote();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004269 if (d != nullptr) return d->mId;
4270 return deadId;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004271}
4272
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004273status_t Camera3Device::RequestThread::queueTriggerLocked(
4274 RequestTrigger trigger) {
4275
4276 uint32_t tag = trigger.metadataTag;
4277 ssize_t index = mTriggerMap.indexOfKey(tag);
4278
4279 switch (trigger.getTagType()) {
4280 case TYPE_BYTE:
4281 // fall-through
4282 case TYPE_INT32:
4283 break;
4284 default:
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004285 ALOGE("%s: Type not supported: 0x%x", __FUNCTION__,
4286 trigger.getTagType());
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004287 return INVALID_OPERATION;
4288 }
4289
4290 /**
4291 * Collect only the latest trigger, since we only have 1 field
4292 * in the request settings per trigger tag, and can't send more than 1
4293 * trigger per request.
4294 */
4295 if (index != NAME_NOT_FOUND) {
4296 mTriggerMap.editValueAt(index) = trigger;
4297 } else {
4298 mTriggerMap.add(tag, trigger);
4299 }
4300
4301 return OK;
4302}
4303
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004304status_t Camera3Device::RequestThread::setRepeatingRequests(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004305 const RequestList &requests,
4306 /*out*/
4307 int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004308 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004309 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004310 if (lastFrameNumber != NULL) {
4311 *lastFrameNumber = mRepeatingLastFrameNumber;
4312 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004313 mRepeatingRequests.clear();
Shuzhen Wang316781a2020-08-18 18:11:01 -07004314 mFirstRepeating = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004315 mRepeatingRequests.insert(mRepeatingRequests.begin(),
4316 requests.begin(), requests.end());
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004317
4318 unpauseForNewRequests();
4319
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004320 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004321 return OK;
4322}
4323
Chih-Hung Hsieh8b0b9712016-08-09 14:25:53 -07004324bool Camera3Device::RequestThread::isRepeatingRequestLocked(const sp<CaptureRequest>& requestIn) {
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07004325 if (mRepeatingRequests.empty()) {
4326 return false;
4327 }
4328 int32_t requestId = requestIn->mResultExtras.requestId;
4329 const RequestList &repeatRequests = mRepeatingRequests;
4330 // All repeating requests are guaranteed to have same id so only check first quest
4331 const sp<CaptureRequest> firstRequest = *repeatRequests.begin();
4332 return (firstRequest->mResultExtras.requestId == requestId);
4333}
4334
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004335status_t Camera3Device::RequestThread::clearRepeatingRequests(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004336 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004337 Mutex::Autolock l(mRequestLock);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004338 return clearRepeatingRequestsLocked(lastFrameNumber);
4339
4340}
4341
4342status_t Camera3Device::RequestThread::clearRepeatingRequestsLocked(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004343 mRepeatingRequests.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004344 if (lastFrameNumber != NULL) {
4345 *lastFrameNumber = mRepeatingLastFrameNumber;
4346 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004347 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004348 return OK;
4349}
4350
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004351status_t Camera3Device::RequestThread::clear(
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004352 /*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004353 ATRACE_CALL();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004354 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004355 ALOGV("RequestThread::%s:", __FUNCTION__);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004356
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004357 mRepeatingRequests.clear();
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07004358
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004359 // Send errors for all requests pending in the request queue, including
4360 // pending repeating requests
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004361 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004362 if (listener != NULL) {
4363 for (RequestList::iterator it = mRequestQueue.begin();
4364 it != mRequestQueue.end(); ++it) {
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004365 // Abort the input buffers for reprocess requests.
4366 if ((*it)->mInputStream != NULL) {
Emilian Peevf4816702020-04-03 15:44:51 -07004367 camera_stream_buffer_t inputBuffer;
Shuzhen Wang83bff122020-11-20 15:51:39 -08004368 camera3::Size inputBufferSize;
Eino-Ville Talvalaba435252017-06-21 16:07:25 -07004369 status_t res = (*it)->mInputStream->getInputBuffer(&inputBuffer,
Shuzhen Wang83bff122020-11-20 15:51:39 -08004370 &inputBufferSize, /*respectHalLimit*/ false);
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004371 if (res != OK) {
4372 ALOGW("%s: %d: couldn't get input buffer while clearing the request "
4373 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
4374 } else {
Emilian Peevf4816702020-04-03 15:44:51 -07004375 inputBuffer.status = CAMERA_BUFFER_STATUS_ERROR;
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004376 res = (*it)->mInputStream->returnInputBuffer(inputBuffer);
4377 if (res != OK) {
4378 ALOGE("%s: %d: couldn't return input buffer while clearing the request "
4379 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
4380 }
4381 }
4382 }
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004383 // Set the frame number this request would have had, if it
4384 // had been submitted; this frame number will not be reused.
4385 // The requestId and burstId fields were set when the request was
4386 // submitted originally (in convertMetadataListToRequestListLocked)
4387 (*it)->mResultExtras.frameNumber = mFrameNumber++;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004388 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004389 (*it)->mResultExtras);
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07004390 }
4391 }
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004392 mRequestQueue.clear();
Jinguang Dongb26e7a02016-11-14 16:04:02 +08004393
4394 Mutex::Autolock al(mTriggerMutex);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004395 mTriggerMap.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004396 if (lastFrameNumber != NULL) {
4397 *lastFrameNumber = mRepeatingLastFrameNumber;
4398 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004399 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Emilian Peev8dae54c2019-12-02 15:17:17 -08004400 mRequestSignal.signal();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004401 return OK;
4402}
4403
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004404status_t Camera3Device::RequestThread::flush() {
4405 ATRACE_CALL();
4406 Mutex::Autolock l(mFlushLock);
4407
Emilian Peev08dd2452017-04-06 16:55:14 +01004408 return mInterface->flush();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004409}
4410
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004411void Camera3Device::RequestThread::setPaused(bool paused) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004412 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004413 Mutex::Autolock l(mPauseLock);
4414 mDoPause = paused;
4415 mDoPauseSignal.signal();
4416}
4417
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004418status_t Camera3Device::RequestThread::waitUntilRequestProcessed(
4419 int32_t requestId, nsecs_t timeout) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004420 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004421 Mutex::Autolock l(mLatestRequestMutex);
4422 status_t res;
4423 while (mLatestRequestId != requestId) {
4424 nsecs_t startTime = systemTime();
4425
4426 res = mLatestRequestSignal.waitRelative(mLatestRequestMutex, timeout);
4427 if (res != OK) return res;
4428
4429 timeout -= (systemTime() - startTime);
4430 }
4431
4432 return OK;
4433}
4434
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004435void Camera3Device::RequestThread::requestExit() {
4436 // Call parent to set up shutdown
4437 Thread::requestExit();
4438 // The exit from any possible waits
4439 mDoPauseSignal.signal();
4440 mRequestSignal.signal();
Shuzhen Wang686f6442017-06-20 16:16:04 -07004441
4442 mRequestLatency.log("ProcessCaptureRequest latency histogram");
4443 mRequestLatency.reset();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004444}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004445
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004446void Camera3Device::RequestThread::checkAndStopRepeatingRequest() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004447 ATRACE_CALL();
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07004448 bool surfaceAbandoned = false;
4449 int64_t lastFrameNumber = 0;
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004450 sp<NotificationListener> listener;
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07004451 {
4452 Mutex::Autolock l(mRequestLock);
4453 // Check all streams needed by repeating requests are still valid. Otherwise, stop
4454 // repeating requests.
4455 for (const auto& request : mRepeatingRequests) {
4456 for (const auto& s : request->mOutputStreams) {
4457 if (s->isAbandoned()) {
4458 surfaceAbandoned = true;
4459 clearRepeatingRequestsLocked(&lastFrameNumber);
4460 break;
4461 }
4462 }
4463 if (surfaceAbandoned) {
4464 break;
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004465 }
4466 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004467 listener = mListener.promote();
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004468 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004469
4470 if (listener != NULL && surfaceAbandoned) {
4471 listener->notifyRepeatingRequestError(lastFrameNumber);
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07004472 }
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004473}
4474
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004475bool Camera3Device::RequestThread::sendRequestsBatch() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004476 ATRACE_CALL();
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004477 status_t res;
4478 size_t batchSize = mNextRequests.size();
Emilian Peevf4816702020-04-03 15:44:51 -07004479 std::vector<camera_capture_request_t*> requests(batchSize);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004480 uint32_t numRequestProcessed = 0;
4481 for (size_t i = 0; i < batchSize; i++) {
4482 requests[i] = &mNextRequests.editItemAt(i).halRequest;
Yin-Chia Yeh885691c2018-05-01 15:54:24 -07004483 ATRACE_ASYNC_BEGIN("frame capture", mNextRequests[i].halRequest.frame_number);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004484 }
4485
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004486 res = mInterface->processBatchCaptureRequests(requests, &numRequestProcessed);
4487
4488 bool triggerRemoveFailed = false;
4489 NextRequest& triggerFailedRequest = mNextRequests.editItemAt(0);
4490 for (size_t i = 0; i < numRequestProcessed; i++) {
4491 NextRequest& nextRequest = mNextRequests.editItemAt(i);
4492 nextRequest.submitted = true;
4493
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004494 updateNextRequest(nextRequest);
Emilian Peevaebbe412018-01-15 13:53:24 +00004495
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004496 if (!triggerRemoveFailed) {
4497 // Remove any previously queued triggers (after unlock)
4498 status_t removeTriggerRes = removeTriggers(mPrevRequest);
4499 if (removeTriggerRes != OK) {
4500 triggerRemoveFailed = true;
4501 triggerFailedRequest = nextRequest;
4502 }
4503 }
4504 }
4505
4506 if (triggerRemoveFailed) {
4507 SET_ERR("RequestThread: Unable to remove triggers "
4508 "(capture request %d, HAL device: %s (%d)",
4509 triggerFailedRequest.halRequest.frame_number, strerror(-res), res);
4510 cleanUpFailedRequests(/*sendRequestError*/ false);
4511 return false;
4512 }
4513
4514 if (res != OK) {
4515 // Should only get a failure here for malformed requests or device-level
4516 // errors, so consider all errors fatal. Bad metadata failures should
4517 // come through notify.
4518 SET_ERR("RequestThread: Unable to submit capture request %d to HAL device: %s (%d)",
4519 mNextRequests[numRequestProcessed].halRequest.frame_number,
4520 strerror(-res), res);
4521 cleanUpFailedRequests(/*sendRequestError*/ false);
4522 return false;
4523 }
4524 return true;
4525}
4526
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07004527nsecs_t Camera3Device::RequestThread::calculateMaxExpectedDuration(const camera_metadata_t *request) {
4528 nsecs_t maxExpectedDuration = kDefaultExpectedDuration;
4529 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
4530 find_camera_metadata_ro_entry(request,
4531 ANDROID_CONTROL_AE_MODE,
4532 &e);
4533 if (e.count == 0) return maxExpectedDuration;
4534
4535 switch (e.data.u8[0]) {
4536 case ANDROID_CONTROL_AE_MODE_OFF:
4537 find_camera_metadata_ro_entry(request,
4538 ANDROID_SENSOR_EXPOSURE_TIME,
4539 &e);
4540 if (e.count > 0) {
4541 maxExpectedDuration = e.data.i64[0];
4542 }
4543 find_camera_metadata_ro_entry(request,
4544 ANDROID_SENSOR_FRAME_DURATION,
4545 &e);
4546 if (e.count > 0) {
4547 maxExpectedDuration = std::max(e.data.i64[0], maxExpectedDuration);
4548 }
4549 break;
4550 default:
4551 find_camera_metadata_ro_entry(request,
4552 ANDROID_CONTROL_AE_TARGET_FPS_RANGE,
4553 &e);
4554 if (e.count > 1) {
4555 maxExpectedDuration = 1e9 / e.data.u8[0];
4556 }
4557 break;
4558 }
4559
4560 return maxExpectedDuration;
4561}
4562
Emilian Peeva14b4dd2018-05-15 11:00:31 +01004563bool Camera3Device::RequestThread::skipHFRTargetFPSUpdate(int32_t tag,
4564 const camera_metadata_ro_entry_t& newEntry, const camera_metadata_entry_t& currentEntry) {
4565 if (mConstrainedMode && (ANDROID_CONTROL_AE_TARGET_FPS_RANGE == tag) &&
4566 (newEntry.count == currentEntry.count) && (currentEntry.count == 2) &&
4567 (currentEntry.data.i32[1] == newEntry.data.i32[1])) {
4568 return true;
4569 }
4570
4571 return false;
4572}
4573
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004574void Camera3Device::RequestThread::updateNextRequest(NextRequest& nextRequest) {
4575 // Update the latest request sent to HAL
Shuzhen Wang83bff122020-11-20 15:51:39 -08004576 camera_capture_request_t& halRequest = nextRequest.halRequest;
4577 if (halRequest.settings != NULL) { // Don't update if they were unchanged
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004578 Mutex::Autolock al(mLatestRequestMutex);
4579
Shuzhen Wang83bff122020-11-20 15:51:39 -08004580 camera_metadata_t* cloned = clone_camera_metadata(halRequest.settings);
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004581 mLatestRequest.acquire(cloned);
4582
4583 mLatestPhysicalRequest.clear();
Shuzhen Wang83bff122020-11-20 15:51:39 -08004584 for (uint32_t i = 0; i < halRequest.num_physcam_settings; i++) {
4585 cloned = clone_camera_metadata(halRequest.physcam_settings[i]);
4586 mLatestPhysicalRequest.emplace(halRequest.physcam_id[i],
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004587 CameraMetadata(cloned));
4588 }
4589
4590 sp<Camera3Device> parent = mParent.promote();
4591 if (parent != NULL) {
4592 parent->monitorMetadata(TagMonitor::REQUEST,
Shuzhen Wang83bff122020-11-20 15:51:39 -08004593 halRequest.frame_number,
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004594 0, mLatestRequest, mLatestPhysicalRequest);
4595 }
4596 }
4597
Shuzhen Wang83bff122020-11-20 15:51:39 -08004598 if (halRequest.settings != NULL) {
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004599 nextRequest.captureRequest->mSettingsList.begin()->metadata.unlock(
Shuzhen Wang83bff122020-11-20 15:51:39 -08004600 halRequest.settings);
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004601 }
4602
Shuzhen Wang83bff122020-11-20 15:51:39 -08004603 cleanupPhysicalSettings(nextRequest.captureRequest, &halRequest);
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004604}
4605
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004606bool Camera3Device::RequestThread::updateSessionParameters(const CameraMetadata& settings) {
4607 ATRACE_CALL();
4608 bool updatesDetected = false;
4609
Emilian Peev4ec17882019-01-24 17:16:58 -08004610 CameraMetadata updatedParams(mLatestSessionParams);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004611 for (auto tag : mSessionParamKeys) {
4612 camera_metadata_ro_entry entry = settings.find(tag);
Emilian Peev4ec17882019-01-24 17:16:58 -08004613 camera_metadata_entry lastEntry = updatedParams.find(tag);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004614
4615 if (entry.count > 0) {
4616 bool isDifferent = false;
4617 if (lastEntry.count > 0) {
4618 // Have a last value, compare to see if changed
4619 if (lastEntry.type == entry.type &&
4620 lastEntry.count == entry.count) {
4621 // Same type and count, compare values
4622 size_t bytesPerValue = camera_metadata_type_size[lastEntry.type];
4623 size_t entryBytes = bytesPerValue * lastEntry.count;
4624 int cmp = memcmp(entry.data.u8, lastEntry.data.u8, entryBytes);
4625 if (cmp != 0) {
4626 isDifferent = true;
4627 }
4628 } else {
4629 // Count or type has changed
4630 isDifferent = true;
4631 }
4632 } else {
4633 // No last entry, so always consider to be different
4634 isDifferent = true;
4635 }
4636
4637 if (isDifferent) {
4638 ALOGV("%s: Session parameter tag id %d changed", __FUNCTION__, tag);
Emilian Peeva14b4dd2018-05-15 11:00:31 +01004639 if (!skipHFRTargetFPSUpdate(tag, entry, lastEntry)) {
4640 updatesDetected = true;
4641 }
Emilian Peev4ec17882019-01-24 17:16:58 -08004642 updatedParams.update(entry);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004643 }
4644 } else if (lastEntry.count > 0) {
4645 // Value has been removed
4646 ALOGV("%s: Session parameter tag id %d removed", __FUNCTION__, tag);
Emilian Peev4ec17882019-01-24 17:16:58 -08004647 updatedParams.erase(tag);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004648 updatesDetected = true;
4649 }
4650 }
4651
Emilian Peev4ec17882019-01-24 17:16:58 -08004652 bool reconfigureRequired;
4653 if (updatesDetected) {
4654 reconfigureRequired = mInterface->isReconfigurationRequired(mLatestSessionParams,
4655 updatedParams);
4656 mLatestSessionParams = updatedParams;
4657 } else {
4658 reconfigureRequired = false;
4659 }
4660
4661 return reconfigureRequired;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004662}
4663
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004664bool Camera3Device::RequestThread::threadLoop() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004665 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004666 status_t res;
Jayant Chowdhary37eca242019-11-18 08:55:56 -08004667 // Any function called from threadLoop() must not hold mInterfaceLock since
4668 // it could lead to deadlocks (disconnect() -> hold mInterfaceMutex -> wait for request thread
4669 // to finish -> request thread waits on mInterfaceMutex) http://b/143513518
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004670
4671 // Handle paused state.
4672 if (waitIfPaused()) {
4673 return true;
4674 }
4675
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004676 // Wait for the next batch of requests.
4677 waitForNextRequestBatch();
4678 if (mNextRequests.size() == 0) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004679 return true;
4680 }
4681
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004682 // Get the latest request ID, if any
4683 int latestRequestId;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004684 camera_metadata_entry_t requestIdEntry = mNextRequests[mNextRequests.size() - 1].
Emilian Peevaebbe412018-01-15 13:53:24 +00004685 captureRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_ID);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004686 if (requestIdEntry.count > 0) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004687 latestRequestId = requestIdEntry.data.i32[0];
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004688 } else {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004689 ALOGW("%s: Did not have android.request.id set in the request.", __FUNCTION__);
4690 latestRequestId = NAME_NOT_FOUND;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004691 }
4692
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004693 // 'mNextRequests' will at this point contain either a set of HFR batched requests
4694 // or a single request from streaming or burst. In either case the first element
4695 // should contain the latest camera settings that we need to check for any session
4696 // parameter updates.
Emilian Peevaebbe412018-01-15 13:53:24 +00004697 if (updateSessionParameters(mNextRequests[0].captureRequest->mSettingsList.begin()->metadata)) {
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004698 res = OK;
4699
4700 //Input stream buffers are already acquired at this point so an input stream
4701 //will not be able to move to idle state unless we force it.
4702 if (mNextRequests[0].captureRequest->mInputStream != nullptr) {
4703 res = mNextRequests[0].captureRequest->mInputStream->forceToIdle();
4704 if (res != OK) {
4705 ALOGE("%s: Failed to force idle input stream: %d", __FUNCTION__, res);
4706 cleanUpFailedRequests(/*sendRequestError*/ false);
4707 return false;
4708 }
4709 }
4710
4711 if (res == OK) {
Emilian Peev3bead5f2020-05-28 17:29:08 -07004712 sp<Camera3Device> parent = mParent.promote();
4713 if (parent != nullptr) {
4714 mReconfigured |= parent->reconfigureCamera(mLatestSessionParams, mStatusId);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004715 }
Emilian Peev3bead5f2020-05-28 17:29:08 -07004716 setPaused(false);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004717
4718 if (mNextRequests[0].captureRequest->mInputStream != nullptr) {
4719 mNextRequests[0].captureRequest->mInputStream->restoreConfiguredState();
4720 if (res != OK) {
4721 ALOGE("%s: Failed to restore configured input stream: %d", __FUNCTION__, res);
4722 cleanUpFailedRequests(/*sendRequestError*/ false);
4723 return false;
4724 }
4725 }
4726 }
4727 }
4728
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004729 // Prepare a batch of HAL requests and output buffers.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004730 res = prepareHalRequests();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004731 if (res == TIMED_OUT) {
4732 // Not a fatal error if getting output buffers time out.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004733 cleanUpFailedRequests(/*sendRequestError*/ true);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004734 // Check if any stream is abandoned.
4735 checkAndStopRepeatingRequest();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004736 return true;
4737 } else if (res != OK) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004738 cleanUpFailedRequests(/*sendRequestError*/ false);
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004739 return false;
4740 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004741
Zhijun Hecc27e112013-10-03 16:12:43 -07004742 // Inform waitUntilRequestProcessed thread of a new request ID
4743 {
4744 Mutex::Autolock al(mLatestRequestMutex);
4745
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004746 mLatestRequestId = latestRequestId;
Zhijun Hecc27e112013-10-03 16:12:43 -07004747 mLatestRequestSignal.signal();
4748 }
4749
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004750 // Submit a batch of requests to HAL.
4751 // Use flush lock only when submitting multilple requests in a batch.
4752 // TODO: The problem with flush lock is flush() will be blocked by process_capture_request()
4753 // which may take a long time to finish so synchronizing flush() and
4754 // process_capture_request() defeats the purpose of cancelling requests ASAP with flush().
4755 // For now, only synchronize for high speed recording and we should figure something out for
4756 // removing the synchronization.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004757 bool useFlushLock = mNextRequests.size() > 1;
Eino-Ville Talvala17a61ad2013-06-03 16:53:32 -07004758
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004759 if (useFlushLock) {
4760 mFlushLock.lock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004761 }
4762
Zhijun Hef0645c12016-08-02 00:58:11 -07004763 ALOGVV("%s: %d: submitting %zu requests in a batch.", __FUNCTION__, __LINE__,
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004764 mNextRequests.size());
Igor Murashkin1e479c02013-09-06 16:55:14 -07004765
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08004766 sp<Camera3Device> parent = mParent.promote();
4767 if (parent != nullptr) {
4768 parent->mRequestBufferSM.onSubmittingRequest();
4769 }
4770
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004771 bool submitRequestSuccess = false;
Shuzhen Wang686f6442017-06-20 16:16:04 -07004772 nsecs_t tRequestStart = systemTime(SYSTEM_TIME_MONOTONIC);
Yin-Chia Yeh11648852019-05-16 10:42:54 -07004773 submitRequestSuccess = sendRequestsBatch();
4774
Shuzhen Wang686f6442017-06-20 16:16:04 -07004775 nsecs_t tRequestEnd = systemTime(SYSTEM_TIME_MONOTONIC);
4776 mRequestLatency.add(tRequestStart, tRequestEnd);
Igor Murashkin1e479c02013-09-06 16:55:14 -07004777
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004778 if (useFlushLock) {
4779 mFlushLock.unlock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004780 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004781
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004782 // Unset as current request
4783 {
4784 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004785 mNextRequests.clear();
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004786 }
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004787 mRequestSubmittedSignal.signal();
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004788
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004789 return submitRequestSuccess;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004790}
4791
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004792status_t Camera3Device::RequestThread::prepareHalRequests() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004793 ATRACE_CALL();
4794
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07004795 bool batchedRequest = mNextRequests[0].captureRequest->mBatchSize > 1;
Shuzhen Wang4a472662017-02-26 23:29:04 -08004796 for (size_t i = 0; i < mNextRequests.size(); i++) {
4797 auto& nextRequest = mNextRequests.editItemAt(i);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004798 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
Emilian Peevf4816702020-04-03 15:44:51 -07004799 camera_capture_request_t* halRequest = &nextRequest.halRequest;
4800 Vector<camera_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004801
4802 // Prepare a request to HAL
4803 halRequest->frame_number = captureRequest->mResultExtras.frameNumber;
4804
4805 // Insert any queued triggers (before metadata is locked)
4806 status_t res = insertTriggers(captureRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004807 if (res < 0) {
4808 SET_ERR("RequestThread: Unable to insert triggers "
4809 "(capture request %d, HAL device: %s (%d)",
4810 halRequest->frame_number, strerror(-res), res);
4811 return INVALID_OPERATION;
4812 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07004813
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004814 int triggerCount = res;
4815 bool triggersMixedIn = (triggerCount > 0 || mPrevTriggers > 0);
4816 mPrevTriggers = triggerCount;
4817
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004818 bool rotateAndCropChanged = overrideAutoRotateAndCrop(captureRequest);
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004819 bool testPatternChanged = overrideTestPattern(captureRequest);
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004820
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004821 // If the request is the same as last, or we had triggers now or last time or
4822 // changing overrides this time
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004823 bool newRequest =
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004824 (mPrevRequest != captureRequest || triggersMixedIn ||
4825 rotateAndCropChanged || testPatternChanged) &&
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07004826 // Request settings are all the same within one batch, so only treat the first
4827 // request in a batch as new
Zhijun He54c36822018-07-18 09:33:39 -07004828 !(batchedRequest && i > 0);
Emilian Peev00420d22018-02-05 21:33:13 +00004829 if (newRequest) {
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08004830 std::set<std::string> cameraIdsWithZoom;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004831 /**
4832 * HAL workaround:
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004833 * Insert a fake trigger ID if a trigger is set but no trigger ID is
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004834 */
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004835 res = addFakeTriggerIds(captureRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004836 if (res != OK) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004837 SET_ERR("RequestThread: Unable to insert fake trigger IDs "
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004838 "(capture request %d, HAL device: %s (%d)",
4839 halRequest->frame_number, strerror(-res), res);
4840 return INVALID_OPERATION;
4841 }
4842
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07004843 {
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07004844 sp<Camera3Device> parent = mParent.promote();
4845 if (parent != nullptr) {
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -07004846 List<PhysicalCameraSettings>::iterator it;
4847 for (it = captureRequest->mSettingsList.begin();
4848 it != captureRequest->mSettingsList.end(); it++) {
Jayant Chowdhary9255ce02021-07-15 11:18:17 -07004849 if (parent->mUHRCropAndMeteringRegionMappers.find(it->cameraId) ==
4850 parent->mUHRCropAndMeteringRegionMappers.end()) {
4851 continue;
4852 }
4853
4854 if (!captureRequest->mUHRCropAndMeteringRegionsUpdated) {
4855 res = parent->mUHRCropAndMeteringRegionMappers[it->cameraId].
4856 updateCaptureRequest(&(it->metadata));
4857 if (res != OK) {
4858 SET_ERR("RequestThread: Unable to correct capture requests "
4859 "for scaler crop region and metering regions for request "
4860 "%d: %s (%d)", halRequest->frame_number, strerror(-res),
4861 res);
4862 return INVALID_OPERATION;
4863 }
4864 captureRequest->mUHRCropAndMeteringRegionsUpdated = true;
4865 }
4866 }
4867
4868 // Correct metadata regions for distortion correction if enabled
4869 for (it = captureRequest->mSettingsList.begin();
4870 it != captureRequest->mSettingsList.end(); it++) {
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -07004871 if (parent->mDistortionMappers.find(it->cameraId) ==
4872 parent->mDistortionMappers.end()) {
4873 continue;
4874 }
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07004875
4876 if (!captureRequest->mDistortionCorrectionUpdated) {
4877 res = parent->mDistortionMappers[it->cameraId].correctCaptureRequest(
4878 &(it->metadata));
4879 if (res != OK) {
4880 SET_ERR("RequestThread: Unable to correct capture requests "
4881 "for lens distortion for request %d: %s (%d)",
4882 halRequest->frame_number, strerror(-res), res);
4883 return INVALID_OPERATION;
4884 }
4885 captureRequest->mDistortionCorrectionUpdated = true;
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -07004886 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07004887 }
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08004888
4889 for (it = captureRequest->mSettingsList.begin();
4890 it != captureRequest->mSettingsList.end(); it++) {
4891 if (parent->mZoomRatioMappers.find(it->cameraId) ==
4892 parent->mZoomRatioMappers.end()) {
4893 continue;
4894 }
4895
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07004896 if (!captureRequest->mZoomRatioIs1x) {
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08004897 cameraIdsWithZoom.insert(it->cameraId);
4898 }
4899
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07004900 if (!captureRequest->mZoomRatioUpdated) {
4901 res = parent->mZoomRatioMappers[it->cameraId].updateCaptureRequest(
4902 &(it->metadata));
4903 if (res != OK) {
4904 SET_ERR("RequestThread: Unable to correct capture requests "
4905 "for zoom ratio for request %d: %s (%d)",
4906 halRequest->frame_number, strerror(-res), res);
4907 return INVALID_OPERATION;
4908 }
4909 captureRequest->mZoomRatioUpdated = true;
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08004910 }
4911 }
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07004912 if (captureRequest->mRotateAndCropAuto &&
4913 !captureRequest->mRotationAndCropUpdated) {
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004914 for (it = captureRequest->mSettingsList.begin();
4915 it != captureRequest->mSettingsList.end(); it++) {
4916 auto mapper = parent->mRotateAndCropMappers.find(it->cameraId);
4917 if (mapper != parent->mRotateAndCropMappers.end()) {
4918 res = mapper->second.updateCaptureRequest(&(it->metadata));
4919 if (res != OK) {
4920 SET_ERR("RequestThread: Unable to correct capture requests "
4921 "for rotate-and-crop for request %d: %s (%d)",
4922 halRequest->frame_number, strerror(-res), res);
4923 return INVALID_OPERATION;
4924 }
4925 }
4926 }
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07004927 captureRequest->mRotationAndCropUpdated = true;
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004928 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07004929 }
4930 }
4931
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004932 /**
4933 * The request should be presorted so accesses in HAL
4934 * are O(logn). Sidenote, sorting a sorted metadata is nop.
4935 */
Emilian Peevaebbe412018-01-15 13:53:24 +00004936 captureRequest->mSettingsList.begin()->metadata.sort();
4937 halRequest->settings = captureRequest->mSettingsList.begin()->metadata.getAndLock();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004938 mPrevRequest = captureRequest;
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08004939 mPrevCameraIdsWithZoom = cameraIdsWithZoom;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004940 ALOGVV("%s: Request settings are NEW", __FUNCTION__);
4941
4942 IF_ALOGV() {
4943 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
4944 find_camera_metadata_ro_entry(
4945 halRequest->settings,
4946 ANDROID_CONTROL_AF_TRIGGER,
4947 &e
4948 );
4949 if (e.count > 0) {
4950 ALOGV("%s: Request (frame num %d) had AF trigger 0x%x",
4951 __FUNCTION__,
4952 halRequest->frame_number,
4953 e.data.u8[0]);
4954 }
4955 }
4956 } else {
4957 // leave request.settings NULL to indicate 'reuse latest given'
4958 ALOGVV("%s: Request settings are REUSED",
4959 __FUNCTION__);
4960 }
4961
Emilian Peevaebbe412018-01-15 13:53:24 +00004962 if (captureRequest->mSettingsList.size() > 1) {
4963 halRequest->num_physcam_settings = captureRequest->mSettingsList.size() - 1;
4964 halRequest->physcam_id = new const char* [halRequest->num_physcam_settings];
Emilian Peev00420d22018-02-05 21:33:13 +00004965 if (newRequest) {
4966 halRequest->physcam_settings =
4967 new const camera_metadata* [halRequest->num_physcam_settings];
4968 } else {
4969 halRequest->physcam_settings = nullptr;
4970 }
Emilian Peevaebbe412018-01-15 13:53:24 +00004971 auto it = ++captureRequest->mSettingsList.begin();
4972 size_t i = 0;
4973 for (; it != captureRequest->mSettingsList.end(); it++, i++) {
4974 halRequest->physcam_id[i] = it->cameraId.c_str();
Emilian Peev00420d22018-02-05 21:33:13 +00004975 if (newRequest) {
4976 it->metadata.sort();
4977 halRequest->physcam_settings[i] = it->metadata.getAndLock();
4978 }
Emilian Peevaebbe412018-01-15 13:53:24 +00004979 }
4980 }
4981
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004982 uint32_t totalNumBuffers = 0;
4983
4984 // Fill in buffers
4985 if (captureRequest->mInputStream != NULL) {
4986 halRequest->input_buffer = &captureRequest->mInputBuffer;
Shuzhen Wang83bff122020-11-20 15:51:39 -08004987
4988 halRequest->input_width = captureRequest->mInputBufferSize.width;
4989 halRequest->input_height = captureRequest->mInputBufferSize.height;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004990 totalNumBuffers += 1;
4991 } else {
4992 halRequest->input_buffer = NULL;
4993 }
4994
Emilian Peevf4816702020-04-03 15:44:51 -07004995 outputBuffers->insertAt(camera_stream_buffer_t(), 0,
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004996 captureRequest->mOutputStreams.size());
4997 halRequest->output_buffers = outputBuffers->array();
Shuzhen Wang99080502021-03-07 21:08:20 -08004998 std::set<std::set<String8>> requestedPhysicalCameras;
Yin-Chia Yehb3a80b12018-09-04 12:13:05 -07004999
5000 sp<Camera3Device> parent = mParent.promote();
5001 if (parent == NULL) {
5002 // Should not happen, and nowhere to send errors to, so just log it
5003 CLOGE("RequestThread: Parent is gone");
5004 return INVALID_OPERATION;
5005 }
5006 nsecs_t waitDuration = kBaseGetBufferWait + parent->getExpectedInFlightDuration();
5007
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005008 SurfaceMap uniqueSurfaceIdMap;
Shuzhen Wang4a472662017-02-26 23:29:04 -08005009 for (size_t j = 0; j < captureRequest->mOutputStreams.size(); j++) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005010 sp<Camera3OutputStreamInterface> outputStream =
5011 captureRequest->mOutputStreams.editItemAt(j);
5012 int streamId = outputStream->getId();
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07005013
5014 // Prepare video buffers for high speed recording on the first video request.
5015 if (mPrepareVideoStream && outputStream->isVideoStream()) {
5016 // Only try to prepare video stream on the first video request.
5017 mPrepareVideoStream = false;
5018
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07005019 res = outputStream->startPrepare(Camera3StreamInterface::ALLOCATE_PIPELINE_MAX,
5020 false /*blockRequest*/);
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07005021 while (res == NOT_ENOUGH_DATA) {
5022 res = outputStream->prepareNextBuffer();
5023 }
5024 if (res != OK) {
5025 ALOGW("%s: Preparing video buffers for high speed failed: %s (%d)",
5026 __FUNCTION__, strerror(-res), res);
5027 outputStream->cancelPrepare();
5028 }
5029 }
5030
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005031 std::vector<size_t> uniqueSurfaceIds;
5032 res = outputStream->getUniqueSurfaceIds(
5033 captureRequest->mOutputSurfaces[streamId],
5034 &uniqueSurfaceIds);
5035 // INVALID_OPERATION is normal output for streams not supporting surfaceIds
5036 if (res != OK && res != INVALID_OPERATION) {
5037 ALOGE("%s: failed to query stream %d unique surface IDs",
5038 __FUNCTION__, streamId);
5039 return res;
5040 }
5041 if (res == OK) {
5042 uniqueSurfaceIdMap.insert({streamId, std::move(uniqueSurfaceIds)});
5043 }
5044
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07005045 if (mUseHalBufManager) {
Yin-Chia Yeh110342b2018-11-19 11:47:46 -08005046 if (outputStream->isAbandoned()) {
Yin-Chia Yeha1b56c82019-03-27 15:50:39 -07005047 ALOGV("%s: stream %d is abandoned, skipping request", __FUNCTION__, streamId);
Yin-Chia Yeh110342b2018-11-19 11:47:46 -08005048 return TIMED_OUT;
5049 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07005050 // HAL will request buffer through requestStreamBuffer API
Emilian Peevf4816702020-04-03 15:44:51 -07005051 camera_stream_buffer_t& buffer = outputBuffers->editItemAt(j);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07005052 buffer.stream = outputStream->asHalStream();
5053 buffer.buffer = nullptr;
Emilian Peevf4816702020-04-03 15:44:51 -07005054 buffer.status = CAMERA_BUFFER_STATUS_OK;
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07005055 buffer.acquire_fence = -1;
5056 buffer.release_fence = -1;
Emilian Peevf0348ae2021-01-13 13:39:45 -08005057 // Mark the output stream as unpreparable to block clients from calling
5058 // 'prepare' after this request reaches CameraHal and before the respective
5059 // buffers are requested.
5060 outputStream->markUnpreparable();
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07005061 } else {
5062 res = outputStream->getBuffer(&outputBuffers->editItemAt(j),
5063 waitDuration,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005064 captureRequest->mOutputSurfaces[streamId]);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07005065 if (res != OK) {
5066 // Can't get output buffer from gralloc queue - this could be due to
5067 // abandoned queue or other consumer misbehavior, so not a fatal
5068 // error
Yin-Chia Yeha1b56c82019-03-27 15:50:39 -07005069 ALOGV("RequestThread: Can't get output buffer, skipping request:"
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07005070 " %s (%d)", strerror(-res), res);
5071
5072 return TIMED_OUT;
5073 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005074 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08005075
5076 {
5077 sp<Camera3Device> parent = mParent.promote();
5078 if (parent != nullptr) {
5079 const String8& streamCameraId = outputStream->getPhysicalCameraId();
5080 for (const auto& settings : captureRequest->mSettingsList) {
5081 if ((streamCameraId.isEmpty() &&
5082 parent->getId() == settings.cameraId.c_str()) ||
5083 streamCameraId == settings.cameraId.c_str()) {
5084 outputStream->fireBufferRequestForFrameNumber(
5085 captureRequest->mResultExtras.frameNumber,
5086 settings.metadata);
5087 }
5088 }
5089 }
5090 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07005091
Shuzhen Wang5c22c152017-12-31 17:12:25 -08005092 String8 physicalCameraId = outputStream->getPhysicalCameraId();
Shuzhen Wang99080502021-03-07 21:08:20 -08005093 int32_t streamGroupId = outputStream->getHalStreamGroupId();
5094 if (streamGroupId != -1 && mGroupIdPhysicalCameraMap.count(streamGroupId) == 1) {
5095 requestedPhysicalCameras.insert(mGroupIdPhysicalCameraMap[streamGroupId]);
5096 } else if (!physicalCameraId.isEmpty()) {
5097 requestedPhysicalCameras.insert(std::set<String8>({physicalCameraId}));
Shuzhen Wang5c22c152017-12-31 17:12:25 -08005098 }
5099 halRequest->num_output_buffers++;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005100 }
5101 totalNumBuffers += halRequest->num_output_buffers;
5102
5103 // Log request in the in-flight queue
Shuzhen Wang4a472662017-02-26 23:29:04 -08005104 // If this request list is for constrained high speed recording (not
5105 // preview), and the current request is not the last one in the batch,
5106 // do not send callback to the app.
5107 bool hasCallback = true;
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07005108 if (batchedRequest && i != mNextRequests.size()-1) {
Shuzhen Wang4a472662017-02-26 23:29:04 -08005109 hasCallback = false;
5110 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01005111 bool isStillCapture = false;
Shuzhen Wang26abaf42018-08-28 15:41:20 -07005112 bool isZslCapture = false;
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08005113 const camera_metadata_t* settings = halRequest->settings;
5114 bool shouldUnlockSettings = false;
5115 if (settings == nullptr) {
5116 shouldUnlockSettings = true;
5117 settings = captureRequest->mSettingsList.begin()->metadata.getAndLock();
5118 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01005119 if (!mNextRequests[0].captureRequest->mSettingsList.begin()->metadata.isEmpty()) {
5120 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08005121 find_camera_metadata_ro_entry(settings, ANDROID_CONTROL_CAPTURE_INTENT, &e);
Emilian Peev9dd21f42018-08-03 13:39:29 +01005122 if ((e.count > 0) && (e.data.u8[0] == ANDROID_CONTROL_CAPTURE_INTENT_STILL_CAPTURE)) {
5123 isStillCapture = true;
5124 ATRACE_ASYNC_BEGIN("still capture", mNextRequests[i].halRequest.frame_number);
5125 }
Shuzhen Wang26abaf42018-08-28 15:41:20 -07005126
Emilian Peevaf8416e2021-02-04 17:52:43 -08005127 e = camera_metadata_ro_entry_t();
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08005128 find_camera_metadata_ro_entry(settings, ANDROID_CONTROL_ENABLE_ZSL, &e);
Shuzhen Wang26abaf42018-08-28 15:41:20 -07005129 if ((e.count > 0) && (e.data.u8[0] == ANDROID_CONTROL_ENABLE_ZSL_TRUE)) {
5130 isZslCapture = true;
5131 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01005132 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005133 res = parent->registerInFlight(halRequest->frame_number,
5134 totalNumBuffers, captureRequest->mResultExtras,
5135 /*hasInput*/halRequest->input_buffer != NULL,
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07005136 hasCallback,
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08005137 calculateMaxExpectedDuration(settings),
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005138 requestedPhysicalCameras, isStillCapture, isZslCapture,
5139 captureRequest->mRotateAndCropAuto, mPrevCameraIdsWithZoom,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005140 (mUseHalBufManager) ? uniqueSurfaceIdMap :
Shuzhen Wang316781a2020-08-18 18:11:01 -07005141 SurfaceMap{}, captureRequest->mRequestTimeNs);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005142 ALOGVV("%s: registered in flight requestId = %" PRId32 ", frameNumber = %" PRId64
5143 ", burstId = %" PRId32 ".",
5144 __FUNCTION__,
5145 captureRequest->mResultExtras.requestId, captureRequest->mResultExtras.frameNumber,
5146 captureRequest->mResultExtras.burstId);
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08005147
5148 if (shouldUnlockSettings) {
5149 captureRequest->mSettingsList.begin()->metadata.unlock(settings);
5150 }
5151
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005152 if (res != OK) {
5153 SET_ERR("RequestThread: Unable to register new in-flight request:"
5154 " %s (%d)", strerror(-res), res);
5155 return INVALID_OPERATION;
5156 }
5157 }
5158
5159 return OK;
5160}
5161
Igor Murashkin1e479c02013-09-06 16:55:14 -07005162CameraMetadata Camera3Device::RequestThread::getLatestRequest() const {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005163 ATRACE_CALL();
Igor Murashkin1e479c02013-09-06 16:55:14 -07005164 Mutex::Autolock al(mLatestRequestMutex);
5165
5166 ALOGV("RequestThread::%s", __FUNCTION__);
5167
5168 return mLatestRequest;
5169}
5170
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005171bool Camera3Device::RequestThread::isStreamPending(
5172 sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005173 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005174 Mutex::Autolock l(mRequestLock);
5175
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005176 for (const auto& nextRequest : mNextRequests) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005177 if (!nextRequest.submitted) {
5178 for (const auto& s : nextRequest.captureRequest->mOutputStreams) {
5179 if (stream == s) return true;
5180 }
5181 if (stream == nextRequest.captureRequest->mInputStream) return true;
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07005182 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07005183 }
5184
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005185 for (const auto& request : mRequestQueue) {
5186 for (const auto& s : request->mOutputStreams) {
5187 if (stream == s) return true;
5188 }
5189 if (stream == request->mInputStream) return true;
5190 }
5191
5192 for (const auto& request : mRepeatingRequests) {
5193 for (const auto& s : request->mOutputStreams) {
5194 if (stream == s) return true;
5195 }
5196 if (stream == request->mInputStream) return true;
5197 }
5198
5199 return false;
5200}
Jianing Weicb0652e2014-03-12 18:29:36 -07005201
Emilian Peev40ead602017-09-26 15:46:36 +01005202bool Camera3Device::RequestThread::isOutputSurfacePending(int streamId, size_t surfaceId) {
5203 ATRACE_CALL();
5204 Mutex::Autolock l(mRequestLock);
5205
5206 for (const auto& nextRequest : mNextRequests) {
5207 for (const auto& s : nextRequest.captureRequest->mOutputSurfaces) {
5208 if (s.first == streamId) {
5209 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
5210 if (it != s.second.end()) {
5211 return true;
5212 }
5213 }
5214 }
5215 }
5216
5217 for (const auto& request : mRequestQueue) {
5218 for (const auto& s : request->mOutputSurfaces) {
5219 if (s.first == streamId) {
5220 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
5221 if (it != s.second.end()) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005222 return true;
Emilian Peev40ead602017-09-26 15:46:36 +01005223 }
5224 }
5225 }
5226 }
5227
5228 for (const auto& request : mRepeatingRequests) {
5229 for (const auto& s : request->mOutputSurfaces) {
5230 if (s.first == streamId) {
5231 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
5232 if (it != s.second.end()) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005233 return true;
Emilian Peev40ead602017-09-26 15:46:36 +01005234 }
5235 }
5236 }
5237 }
5238
5239 return false;
5240}
5241
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07005242void Camera3Device::RequestThread::signalPipelineDrain(const std::vector<int>& streamIds) {
5243 if (!mUseHalBufManager) {
5244 ALOGE("%s called for camera device not supporting HAL buffer management", __FUNCTION__);
5245 return;
5246 }
5247
5248 Mutex::Autolock pl(mPauseLock);
5249 if (mPaused) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005250 mInterface->signalPipelineDrain(streamIds);
5251 return;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07005252 }
5253 // If request thread is still busy, wait until paused then notify HAL
5254 mNotifyPipelineDrain = true;
5255 mStreamIdsToBeDrained = streamIds;
5256}
5257
Yin-Chia Yehe52b8fa2020-07-28 00:17:58 -07005258void Camera3Device::RequestThread::resetPipelineDrain() {
5259 Mutex::Autolock pl(mPauseLock);
5260 mNotifyPipelineDrain = false;
5261 mStreamIdsToBeDrained.clear();
5262}
5263
Emilian Peevc0fe54c2020-03-11 14:05:07 -07005264void Camera3Device::RequestThread::clearPreviousRequest() {
5265 Mutex::Autolock l(mRequestLock);
5266 mPrevRequest.clear();
5267}
5268
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005269status_t Camera3Device::RequestThread::switchToOffline(
5270 const std::vector<int32_t>& streamsToKeep,
5271 /*out*/hardware::camera::device::V3_6::CameraOfflineSessionInfo* offlineSessionInfo,
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005272 /*out*/sp<hardware::camera::device::V3_6::ICameraOfflineSession>* offlineSession,
5273 /*out*/camera3::BufferRecords* bufferRecords) {
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005274 Mutex::Autolock l(mRequestLock);
5275 clearRepeatingRequestsLocked(/*lastFrameNumber*/nullptr);
5276
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005277 // Wait until request thread is fully stopped
5278 // TBD: check if request thread is being paused by other APIs (shouldn't be)
5279
5280 // We could also check for mRepeatingRequests.empty(), but the API interface
5281 // is serialized by Camera3Device::mInterfaceLock so no one should be able to submit any
5282 // new requests during the call; hence skip that check.
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005283 bool queueEmpty = mNextRequests.empty() && mRequestQueue.empty();
5284 while (!queueEmpty) {
5285 status_t res = mRequestSubmittedSignal.waitRelative(mRequestLock, kRequestSubmitTimeout);
5286 if (res == TIMED_OUT) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005287 ALOGE("%s: request thread failed to submit one request within timeout!", __FUNCTION__);
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005288 return res;
5289 } else if (res != OK) {
5290 ALOGE("%s: request thread failed to submit a request: %s (%d)!",
5291 __FUNCTION__, strerror(-res), res);
5292 return res;
5293 }
5294 queueEmpty = mNextRequests.empty() && mRequestQueue.empty();
5295 }
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005296
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005297 return mInterface->switchToOffline(
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005298 streamsToKeep, offlineSessionInfo, offlineSession, bufferRecords);
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005299}
5300
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005301status_t Camera3Device::RequestThread::setRotateAndCropAutoBehavior(
5302 camera_metadata_enum_android_scaler_rotate_and_crop_t rotateAndCropValue) {
5303 ATRACE_CALL();
5304 Mutex::Autolock l(mTriggerMutex);
5305 if (rotateAndCropValue == ANDROID_SCALER_ROTATE_AND_CROP_AUTO) {
5306 return BAD_VALUE;
5307 }
5308 mRotateAndCropOverride = rotateAndCropValue;
5309 return OK;
5310}
5311
Eino-Ville Talvala11afe4f2021-05-27 14:45:31 -07005312status_t Camera3Device::RequestThread::setCameraMute(int32_t muteMode) {
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005313 ATRACE_CALL();
5314 Mutex::Autolock l(mTriggerMutex);
Eino-Ville Talvala11afe4f2021-05-27 14:45:31 -07005315 if (muteMode != mCameraMute) {
5316 mCameraMute = muteMode;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005317 mCameraMuteChanged = true;
5318 }
5319 return OK;
5320}
5321
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07005322nsecs_t Camera3Device::getExpectedInFlightDuration() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005323 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005324 std::lock_guard<std::mutex> l(mInFlightLock);
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07005325 return mExpectedInflightDuration > kMinInflightDuration ?
5326 mExpectedInflightDuration : kMinInflightDuration;
5327}
5328
Emilian Peevaebbe412018-01-15 13:53:24 +00005329void Camera3Device::RequestThread::cleanupPhysicalSettings(sp<CaptureRequest> request,
Emilian Peevf4816702020-04-03 15:44:51 -07005330 camera_capture_request_t *halRequest) {
Emilian Peevaebbe412018-01-15 13:53:24 +00005331 if ((request == nullptr) || (halRequest == nullptr)) {
5332 ALOGE("%s: Invalid request!", __FUNCTION__);
5333 return;
5334 }
5335
5336 if (halRequest->num_physcam_settings > 0) {
5337 if (halRequest->physcam_id != nullptr) {
5338 delete [] halRequest->physcam_id;
5339 halRequest->physcam_id = nullptr;
5340 }
5341 if (halRequest->physcam_settings != nullptr) {
5342 auto it = ++(request->mSettingsList.begin());
5343 size_t i = 0;
5344 for (; it != request->mSettingsList.end(); it++, i++) {
5345 it->metadata.unlock(halRequest->physcam_settings[i]);
5346 }
5347 delete [] halRequest->physcam_settings;
5348 halRequest->physcam_settings = nullptr;
5349 }
5350 }
5351}
5352
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005353void Camera3Device::RequestThread::cleanUpFailedRequests(bool sendRequestError) {
5354 if (mNextRequests.empty()) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005355 return;
5356 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005357
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005358 for (auto& nextRequest : mNextRequests) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005359 // Skip the ones that have been submitted successfully.
5360 if (nextRequest.submitted) {
5361 continue;
5362 }
5363
5364 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
Emilian Peevf4816702020-04-03 15:44:51 -07005365 camera_capture_request_t* halRequest = &nextRequest.halRequest;
5366 Vector<camera_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005367
5368 if (halRequest->settings != NULL) {
Emilian Peevaebbe412018-01-15 13:53:24 +00005369 captureRequest->mSettingsList.begin()->metadata.unlock(halRequest->settings);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005370 }
5371
Emilian Peevaebbe412018-01-15 13:53:24 +00005372 cleanupPhysicalSettings(captureRequest, halRequest);
5373
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005374 if (captureRequest->mInputStream != NULL) {
Emilian Peevf4816702020-04-03 15:44:51 -07005375 captureRequest->mInputBuffer.status = CAMERA_BUFFER_STATUS_ERROR;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005376 captureRequest->mInputStream->returnInputBuffer(captureRequest->mInputBuffer);
5377 }
5378
Yin-Chia Yeh21cb47b2019-01-18 15:08:17 -08005379 // No output buffer can be returned when using HAL buffer manager
5380 if (!mUseHalBufManager) {
5381 for (size_t i = 0; i < halRequest->num_output_buffers; i++) {
5382 //Buffers that failed processing could still have
5383 //valid acquire fence.
5384 int acquireFence = (*outputBuffers)[i].acquire_fence;
5385 if (0 <= acquireFence) {
5386 close(acquireFence);
5387 outputBuffers->editItemAt(i).acquire_fence = -1;
5388 }
Emilian Peevf4816702020-04-03 15:44:51 -07005389 outputBuffers->editItemAt(i).status = CAMERA_BUFFER_STATUS_ERROR;
Yin-Chia Yeh21cb47b2019-01-18 15:08:17 -08005390 captureRequest->mOutputStreams.editItemAt(i)->returnBuffer((*outputBuffers)[i], 0,
5391 /*timestampIncreasing*/true, std::vector<size_t> (),
5392 captureRequest->mResultExtras.frameNumber);
Emilian Peevc58cf4c2017-05-11 17:23:41 +01005393 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005394 }
5395
5396 if (sendRequestError) {
5397 Mutex::Autolock l(mRequestLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005398 sp<NotificationListener> listener = mListener.promote();
5399 if (listener != NULL) {
5400 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08005401 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005402 captureRequest->mResultExtras);
5403 }
5404 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07005405
5406 // Remove yet-to-be submitted inflight request from inflightMap
5407 {
5408 sp<Camera3Device> parent = mParent.promote();
5409 if (parent != NULL) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005410 std::lock_guard<std::mutex> l(parent->mInFlightLock);
Shuzhen Wangcadb3302016-11-04 14:17:56 -07005411 ssize_t idx = parent->mInFlightMap.indexOfKey(captureRequest->mResultExtras.frameNumber);
5412 if (idx >= 0) {
5413 ALOGV("%s: Remove inflight request from queue: frameNumber %" PRId64,
5414 __FUNCTION__, captureRequest->mResultExtras.frameNumber);
5415 parent->removeInFlightMapEntryLocked(idx);
5416 }
5417 }
5418 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005419 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07005420
5421 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005422 mNextRequests.clear();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005423}
5424
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005425void Camera3Device::RequestThread::waitForNextRequestBatch() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005426 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005427 // Optimized a bit for the simple steady-state case (single repeating
5428 // request), to avoid putting that request in the queue temporarily.
5429 Mutex::Autolock l(mRequestLock);
5430
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005431 assert(mNextRequests.empty());
5432
5433 NextRequest nextRequest;
5434 nextRequest.captureRequest = waitForNextRequestLocked();
5435 if (nextRequest.captureRequest == nullptr) {
5436 return;
5437 }
5438
Emilian Peevf4816702020-04-03 15:44:51 -07005439 nextRequest.halRequest = camera_capture_request_t();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005440 nextRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005441 mNextRequests.add(nextRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005442
5443 // Wait for additional requests
5444 const size_t batchSize = nextRequest.captureRequest->mBatchSize;
5445
5446 for (size_t i = 1; i < batchSize; i++) {
5447 NextRequest additionalRequest;
5448 additionalRequest.captureRequest = waitForNextRequestLocked();
5449 if (additionalRequest.captureRequest == nullptr) {
5450 break;
5451 }
5452
Emilian Peevf4816702020-04-03 15:44:51 -07005453 additionalRequest.halRequest = camera_capture_request_t();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005454 additionalRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005455 mNextRequests.add(additionalRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005456 }
5457
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005458 if (mNextRequests.size() < batchSize) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08005459 ALOGE("RequestThread: only get %zu out of %zu requests. Skipping requests.",
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005460 mNextRequests.size(), batchSize);
5461 cleanUpFailedRequests(/*sendRequestError*/true);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005462 }
5463
5464 return;
5465}
5466
5467sp<Camera3Device::CaptureRequest>
5468 Camera3Device::RequestThread::waitForNextRequestLocked() {
5469 status_t res;
5470 sp<CaptureRequest> nextRequest;
5471
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005472 while (mRequestQueue.empty()) {
5473 if (!mRepeatingRequests.empty()) {
5474 // Always atomically enqueue all requests in a repeating request
5475 // list. Guarantees a complete in-sequence set of captures to
5476 // application.
5477 const RequestList &requests = mRepeatingRequests;
Shuzhen Wang316781a2020-08-18 18:11:01 -07005478 if (mFirstRepeating) {
5479 mFirstRepeating = false;
5480 } else {
5481 for (auto& request : requests) {
5482 // For repeating requests, override timestamp request using
5483 // the time a request is inserted into the request queue,
5484 // because the original repeating request will have an old
5485 // fixed timestamp.
5486 request->mRequestTimeNs = systemTime();
5487 }
5488 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005489 RequestList::const_iterator firstRequest =
5490 requests.begin();
5491 nextRequest = *firstRequest;
5492 mRequestQueue.insert(mRequestQueue.end(),
5493 ++firstRequest,
5494 requests.end());
5495 // No need to wait any longer
Jianing Weicb0652e2014-03-12 18:29:36 -07005496
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005497 mRepeatingLastFrameNumber = mFrameNumber + requests.size() - 1;
Jianing Weicb0652e2014-03-12 18:29:36 -07005498
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005499 break;
5500 }
5501
5502 res = mRequestSignal.waitRelative(mRequestLock, kRequestTimeout);
5503
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005504 if ((mRequestQueue.empty() && mRepeatingRequests.empty()) ||
5505 exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005506 Mutex::Autolock pl(mPauseLock);
5507 if (mPaused == false) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005508 ALOGV("%s: RequestThread: Going idle", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005509 mPaused = true;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07005510 if (mNotifyPipelineDrain) {
5511 mInterface->signalPipelineDrain(mStreamIdsToBeDrained);
5512 mNotifyPipelineDrain = false;
5513 mStreamIdsToBeDrained.clear();
5514 }
Yin-Chia Yehc300a072019-02-13 14:56:57 -08005515 // Let the tracker know
5516 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5517 if (statusTracker != 0) {
5518 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
5519 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005520 sp<Camera3Device> parent = mParent.promote();
5521 if (parent != nullptr) {
5522 parent->mRequestBufferSM.onRequestThreadPaused();
5523 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005524 }
5525 // Stop waiting for now and let thread management happen
5526 return NULL;
5527 }
5528 }
5529
5530 if (nextRequest == NULL) {
5531 // Don't have a repeating request already in hand, so queue
5532 // must have an entry now.
5533 RequestList::iterator firstRequest =
5534 mRequestQueue.begin();
5535 nextRequest = *firstRequest;
5536 mRequestQueue.erase(firstRequest);
Shuzhen Wang9d066012016-09-30 11:30:20 -07005537 if (mRequestQueue.empty() && !nextRequest->mRepeating) {
5538 sp<NotificationListener> listener = mListener.promote();
5539 if (listener != NULL) {
5540 listener->notifyRequestQueueEmpty();
5541 }
5542 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005543 }
5544
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005545 // In case we've been unpaused by setPaused clearing mDoPause, need to
5546 // update internal pause state (capture/setRepeatingRequest unpause
5547 // directly).
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005548 Mutex::Autolock pl(mPauseLock);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005549 if (mPaused) {
5550 ALOGV("%s: RequestThread: Unpaused", __FUNCTION__);
5551 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5552 if (statusTracker != 0) {
5553 statusTracker->markComponentActive(mStatusId);
5554 }
5555 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005556 mPaused = false;
5557
5558 // Check if we've reconfigured since last time, and reset the preview
5559 // request if so. Can't use 'NULL request == repeat' across configure calls.
5560 if (mReconfigured) {
5561 mPrevRequest.clear();
5562 mReconfigured = false;
5563 }
5564
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005565 if (nextRequest != NULL) {
5566 nextRequest->mResultExtras.frameNumber = mFrameNumber++;
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07005567 nextRequest->mResultExtras.afTriggerId = mCurrentAfTriggerId;
5568 nextRequest->mResultExtras.precaptureTriggerId = mCurrentPreCaptureTriggerId;
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07005569
5570 // Since RequestThread::clear() removes buffers from the input stream,
5571 // get the right buffer here before unlocking mRequestLock
5572 if (nextRequest->mInputStream != NULL) {
Shuzhen Wang83bff122020-11-20 15:51:39 -08005573 res = nextRequest->mInputStream->getInputBuffer(&nextRequest->mInputBuffer,
5574 &nextRequest->mInputBufferSize);
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07005575 if (res != OK) {
5576 // Can't get input buffer from gralloc queue - this could be due to
5577 // disconnected queue or other producer misbehavior, so not a fatal
5578 // error
5579 ALOGE("%s: Can't get input buffer, skipping request:"
5580 " %s (%d)", __FUNCTION__, strerror(-res), res);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005581
5582 sp<NotificationListener> listener = mListener.promote();
5583 if (listener != NULL) {
5584 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08005585 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07005586 nextRequest->mResultExtras);
5587 }
5588 return NULL;
5589 }
5590 }
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005591 }
Chien-Yu Chend196d612015-06-22 19:49:01 -07005592
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005593 return nextRequest;
5594}
5595
5596bool Camera3Device::RequestThread::waitIfPaused() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005597 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005598 status_t res;
5599 Mutex::Autolock l(mPauseLock);
5600 while (mDoPause) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005601 if (mPaused == false) {
5602 mPaused = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005603 ALOGV("%s: RequestThread: Paused", __FUNCTION__);
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07005604 if (mNotifyPipelineDrain) {
5605 mInterface->signalPipelineDrain(mStreamIdsToBeDrained);
5606 mNotifyPipelineDrain = false;
5607 mStreamIdsToBeDrained.clear();
5608 }
Yin-Chia Yehc300a072019-02-13 14:56:57 -08005609 // Let the tracker know
5610 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5611 if (statusTracker != 0) {
5612 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
5613 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005614 sp<Camera3Device> parent = mParent.promote();
5615 if (parent != nullptr) {
5616 parent->mRequestBufferSM.onRequestThreadPaused();
5617 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005618 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005619
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005620 res = mDoPauseSignal.waitRelative(mPauseLock, kRequestTimeout);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005621 if (res == TIMED_OUT || exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005622 return true;
5623 }
5624 }
5625 // We don't set mPaused to false here, because waitForNextRequest needs
5626 // to further manage the paused state in case of starvation.
5627 return false;
5628}
5629
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005630void Camera3Device::RequestThread::unpauseForNewRequests() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005631 ATRACE_CALL();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005632 // With work to do, mark thread as unpaused.
5633 // If paused by request (setPaused), don't resume, to avoid
5634 // extra signaling/waiting overhead to waitUntilPaused
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005635 mRequestSignal.signal();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005636 Mutex::Autolock p(mPauseLock);
5637 if (!mDoPause) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005638 ALOGV("%s: RequestThread: Going active", __FUNCTION__);
5639 if (mPaused) {
5640 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5641 if (statusTracker != 0) {
5642 statusTracker->markComponentActive(mStatusId);
5643 }
5644 }
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005645 mPaused = false;
5646 }
5647}
5648
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07005649void Camera3Device::RequestThread::setErrorState(const char *fmt, ...) {
5650 sp<Camera3Device> parent = mParent.promote();
5651 if (parent != NULL) {
5652 va_list args;
5653 va_start(args, fmt);
5654
5655 parent->setErrorStateV(fmt, args);
5656
5657 va_end(args);
5658 }
5659}
5660
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005661status_t Camera3Device::RequestThread::insertTriggers(
5662 const sp<CaptureRequest> &request) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005663 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005664 Mutex::Autolock al(mTriggerMutex);
5665
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07005666 sp<Camera3Device> parent = mParent.promote();
5667 if (parent == NULL) {
5668 CLOGE("RequestThread: Parent is gone");
5669 return DEAD_OBJECT;
5670 }
5671
Emilian Peevaebbe412018-01-15 13:53:24 +00005672 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005673 size_t count = mTriggerMap.size();
5674
5675 for (size_t i = 0; i < count; ++i) {
5676 RequestTrigger trigger = mTriggerMap.valueAt(i);
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005677 uint32_t tag = trigger.metadataTag;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07005678
5679 if (tag == ANDROID_CONTROL_AF_TRIGGER_ID || tag == ANDROID_CONTROL_AE_PRECAPTURE_ID) {
5680 bool isAeTrigger = (trigger.metadataTag == ANDROID_CONTROL_AE_PRECAPTURE_ID);
5681 uint32_t triggerId = static_cast<uint32_t>(trigger.entryValue);
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07005682 if (isAeTrigger) {
5683 request->mResultExtras.precaptureTriggerId = triggerId;
5684 mCurrentPreCaptureTriggerId = triggerId;
5685 } else {
5686 request->mResultExtras.afTriggerId = triggerId;
5687 mCurrentAfTriggerId = triggerId;
5688 }
Emilian Peev7e25e5e2017-04-07 15:48:49 +01005689 continue;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07005690 }
5691
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005692 camera_metadata_entry entry = metadata.find(tag);
5693
5694 if (entry.count > 0) {
5695 /**
5696 * Already has an entry for this trigger in the request.
5697 * Rewrite it with our requested trigger value.
5698 */
5699 RequestTrigger oldTrigger = trigger;
5700
5701 oldTrigger.entryValue = entry.data.u8[0];
5702
5703 mTriggerReplacedMap.add(tag, oldTrigger);
5704 } else {
5705 /**
5706 * More typical, no trigger entry, so we just add it
5707 */
5708 mTriggerRemovedMap.add(tag, trigger);
5709 }
5710
5711 status_t res;
5712
5713 switch (trigger.getTagType()) {
5714 case TYPE_BYTE: {
5715 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
5716 res = metadata.update(tag,
5717 &entryValue,
5718 /*count*/1);
5719 break;
5720 }
5721 case TYPE_INT32:
5722 res = metadata.update(tag,
5723 &trigger.entryValue,
5724 /*count*/1);
5725 break;
5726 default:
5727 ALOGE("%s: Type not supported: 0x%x",
5728 __FUNCTION__,
5729 trigger.getTagType());
5730 return INVALID_OPERATION;
5731 }
5732
5733 if (res != OK) {
5734 ALOGE("%s: Failed to update request metadata with trigger tag %s"
5735 ", value %d", __FUNCTION__, trigger.getTagName(),
5736 trigger.entryValue);
5737 return res;
5738 }
5739
5740 ALOGV("%s: Mixed in trigger %s, value %d", __FUNCTION__,
5741 trigger.getTagName(),
5742 trigger.entryValue);
5743 }
5744
5745 mTriggerMap.clear();
5746
5747 return count;
5748}
5749
5750status_t Camera3Device::RequestThread::removeTriggers(
5751 const sp<CaptureRequest> &request) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005752 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005753 Mutex::Autolock al(mTriggerMutex);
5754
Emilian Peevaebbe412018-01-15 13:53:24 +00005755 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005756
5757 /**
5758 * Replace all old entries with their old values.
5759 */
5760 for (size_t i = 0; i < mTriggerReplacedMap.size(); ++i) {
5761 RequestTrigger trigger = mTriggerReplacedMap.valueAt(i);
5762
5763 status_t res;
5764
5765 uint32_t tag = trigger.metadataTag;
5766 switch (trigger.getTagType()) {
5767 case TYPE_BYTE: {
5768 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
5769 res = metadata.update(tag,
5770 &entryValue,
5771 /*count*/1);
5772 break;
5773 }
5774 case TYPE_INT32:
5775 res = metadata.update(tag,
5776 &trigger.entryValue,
5777 /*count*/1);
5778 break;
5779 default:
5780 ALOGE("%s: Type not supported: 0x%x",
5781 __FUNCTION__,
5782 trigger.getTagType());
5783 return INVALID_OPERATION;
5784 }
5785
5786 if (res != OK) {
5787 ALOGE("%s: Failed to restore request metadata with trigger tag %s"
5788 ", trigger value %d", __FUNCTION__,
5789 trigger.getTagName(), trigger.entryValue);
5790 return res;
5791 }
5792 }
5793 mTriggerReplacedMap.clear();
5794
5795 /**
5796 * Remove all new entries.
5797 */
5798 for (size_t i = 0; i < mTriggerRemovedMap.size(); ++i) {
5799 RequestTrigger trigger = mTriggerRemovedMap.valueAt(i);
5800 status_t res = metadata.erase(trigger.metadataTag);
5801
5802 if (res != OK) {
5803 ALOGE("%s: Failed to erase metadata with trigger tag %s"
5804 ", trigger value %d", __FUNCTION__,
5805 trigger.getTagName(), trigger.entryValue);
5806 return res;
5807 }
5808 }
5809 mTriggerRemovedMap.clear();
5810
5811 return OK;
5812}
5813
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04005814status_t Camera3Device::RequestThread::addFakeTriggerIds(
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005815 const sp<CaptureRequest> &request) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08005816 // Trigger ID 0 had special meaning in the HAL2 spec, so avoid it here
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04005817 static const int32_t fakeTriggerId = 1;
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005818 status_t res;
5819
Emilian Peevaebbe412018-01-15 13:53:24 +00005820 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005821
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04005822 // If AF trigger is active, insert a fake AF trigger ID if none already
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005823 // exists
5824 camera_metadata_entry afTrigger = metadata.find(ANDROID_CONTROL_AF_TRIGGER);
5825 camera_metadata_entry afId = metadata.find(ANDROID_CONTROL_AF_TRIGGER_ID);
5826 if (afTrigger.count > 0 &&
5827 afTrigger.data.u8[0] != ANDROID_CONTROL_AF_TRIGGER_IDLE &&
5828 afId.count == 0) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04005829 res = metadata.update(ANDROID_CONTROL_AF_TRIGGER_ID, &fakeTriggerId, 1);
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005830 if (res != OK) return res;
5831 }
5832
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04005833 // If AE precapture trigger is active, insert a fake precapture trigger ID
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005834 // if none already exists
5835 camera_metadata_entry pcTrigger =
5836 metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER);
5837 camera_metadata_entry pcId = metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_ID);
5838 if (pcTrigger.count > 0 &&
5839 pcTrigger.data.u8[0] != ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_IDLE &&
5840 pcId.count == 0) {
5841 res = metadata.update(ANDROID_CONTROL_AE_PRECAPTURE_ID,
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04005842 &fakeTriggerId, 1);
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005843 if (res != OK) return res;
5844 }
5845
5846 return OK;
5847}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005848
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005849bool Camera3Device::RequestThread::overrideAutoRotateAndCrop(
5850 const sp<CaptureRequest> &request) {
5851 ATRACE_CALL();
5852
5853 if (request->mRotateAndCropAuto) {
5854 Mutex::Autolock l(mTriggerMutex);
5855 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
5856
5857 auto rotateAndCropEntry = metadata.find(ANDROID_SCALER_ROTATE_AND_CROP);
5858 if (rotateAndCropEntry.count > 0) {
5859 if (rotateAndCropEntry.data.u8[0] == mRotateAndCropOverride) {
5860 return false;
5861 } else {
5862 rotateAndCropEntry.data.u8[0] = mRotateAndCropOverride;
5863 return true;
5864 }
5865 } else {
5866 uint8_t rotateAndCrop_u8 = mRotateAndCropOverride;
5867 metadata.update(ANDROID_SCALER_ROTATE_AND_CROP,
5868 &rotateAndCrop_u8, 1);
5869 return true;
5870 }
5871 }
5872 return false;
5873}
5874
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005875bool Camera3Device::RequestThread::overrideTestPattern(
5876 const sp<CaptureRequest> &request) {
5877 ATRACE_CALL();
5878
Eino-Ville Talvala1646c3c2021-07-29 13:48:40 -07005879 if (!mSupportCameraMute) return false;
Eino-Ville Talvalac2459842021-07-22 16:36:36 -07005880
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005881 Mutex::Autolock l(mTriggerMutex);
5882
5883 bool changed = false;
5884
5885 int32_t testPatternMode = request->mOriginalTestPatternMode;
5886 int32_t testPatternData[4] = {
5887 request->mOriginalTestPatternData[0],
5888 request->mOriginalTestPatternData[1],
5889 request->mOriginalTestPatternData[2],
5890 request->mOriginalTestPatternData[3]
5891 };
5892
Eino-Ville Talvala11afe4f2021-05-27 14:45:31 -07005893 if (mCameraMute != ANDROID_SENSOR_TEST_PATTERN_MODE_OFF) {
5894 testPatternMode = mCameraMute;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005895 testPatternData[0] = 0;
5896 testPatternData[1] = 0;
5897 testPatternData[2] = 0;
5898 testPatternData[3] = 0;
5899 }
5900
5901 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
5902
5903 auto testPatternEntry = metadata.find(ANDROID_SENSOR_TEST_PATTERN_MODE);
5904 if (testPatternEntry.count > 0) {
5905 if (testPatternEntry.data.i32[0] != testPatternMode) {
5906 testPatternEntry.data.i32[0] = testPatternMode;
5907 changed = true;
5908 }
5909 } else {
5910 metadata.update(ANDROID_SENSOR_TEST_PATTERN_MODE,
5911 &testPatternMode, 1);
5912 changed = true;
5913 }
5914
5915 auto testPatternColor = metadata.find(ANDROID_SENSOR_TEST_PATTERN_DATA);
Eino-Ville Talvalac2459842021-07-22 16:36:36 -07005916 if (testPatternColor.count >= 4) {
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005917 for (size_t i = 0; i < 4; i++) {
Eino-Ville Talvalac2459842021-07-22 16:36:36 -07005918 if (testPatternColor.data.i32[i] != testPatternData[i]) {
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005919 testPatternColor.data.i32[i] = testPatternData[i];
5920 changed = true;
5921 }
5922 }
5923 } else {
5924 metadata.update(ANDROID_SENSOR_TEST_PATTERN_DATA,
Eino-Ville Talvalac2459842021-07-22 16:36:36 -07005925 testPatternData, 4);
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005926 changed = true;
5927 }
5928
5929 return changed;
5930}
5931
Cliff Wuc2ad9c82021-04-21 00:58:58 +08005932status_t Camera3Device::RequestThread::setHalInterface(
5933 sp<HalInterface> newHalInterface) {
5934 if (newHalInterface.get() == nullptr) {
5935 ALOGE("%s: The newHalInterface does not exist!", __FUNCTION__);
5936 return DEAD_OBJECT;
5937 }
5938
5939 mInterface = newHalInterface;
5940
5941 return OK;
5942}
5943
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005944/**
5945 * PreparerThread inner class methods
5946 */
5947
5948Camera3Device::PreparerThread::PreparerThread() :
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07005949 Thread(/*canCallJava*/false), mListener(nullptr),
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005950 mActive(false), mCancelNow(false), mCurrentMaxCount(0), mCurrentPrepareComplete(false) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005951}
5952
5953Camera3Device::PreparerThread::~PreparerThread() {
5954 Thread::requestExitAndWait();
5955 if (mCurrentStream != nullptr) {
5956 mCurrentStream->cancelPrepare();
5957 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
5958 mCurrentStream.clear();
5959 }
5960 clear();
5961}
5962
Ruben Brunkc78ac262015-08-13 17:58:46 -07005963status_t Camera3Device::PreparerThread::prepare(int maxCount, sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005964 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005965 status_t res;
5966
5967 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005968 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005969
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07005970 res = stream->startPrepare(maxCount, true /*blockRequest*/);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005971 if (res == OK) {
5972 // No preparation needed, fire listener right off
5973 ALOGV("%s: Stream %d already prepared", __FUNCTION__, stream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005974 if (listener != NULL) {
5975 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005976 }
5977 return OK;
5978 } else if (res != NOT_ENOUGH_DATA) {
5979 return res;
5980 }
5981
5982 // Need to prepare, start up thread if necessary
5983 if (!mActive) {
5984 // mRunning will change to false before the thread fully shuts down, so wait to be sure it
5985 // isn't running
5986 Thread::requestExitAndWait();
5987 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
5988 if (res != OK) {
5989 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__, res, strerror(-res));
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005990 if (listener != NULL) {
5991 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005992 }
5993 return res;
5994 }
5995 mCancelNow = false;
5996 mActive = true;
5997 ALOGV("%s: Preparer stream started", __FUNCTION__);
5998 }
5999
6000 // queue up the work
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006001 mPendingStreams.emplace(maxCount, stream);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006002 ALOGV("%s: Stream %d queued for preparing", __FUNCTION__, stream->getId());
6003
6004 return OK;
6005}
6006
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006007void Camera3Device::PreparerThread::pause() {
6008 ATRACE_CALL();
6009
6010 Mutex::Autolock l(mLock);
6011
6012 std::unordered_map<int, sp<camera3::Camera3StreamInterface> > pendingStreams;
6013 pendingStreams.insert(mPendingStreams.begin(), mPendingStreams.end());
6014 sp<camera3::Camera3StreamInterface> currentStream = mCurrentStream;
6015 int currentMaxCount = mCurrentMaxCount;
6016 mPendingStreams.clear();
6017 mCancelNow = true;
6018 while (mActive) {
6019 auto res = mThreadActiveSignal.waitRelative(mLock, kActiveTimeout);
6020 if (res == TIMED_OUT) {
6021 ALOGE("%s: Timed out waiting on prepare thread!", __FUNCTION__);
6022 return;
6023 } else if (res != OK) {
6024 ALOGE("%s: Encountered an error: %d waiting on prepare thread!", __FUNCTION__, res);
6025 return;
6026 }
6027 }
6028
6029 //Check whether the prepare thread was able to complete the current
6030 //stream. In case work is still pending emplace it along with the rest
6031 //of the streams in the pending list.
6032 if (currentStream != nullptr) {
6033 if (!mCurrentPrepareComplete) {
6034 pendingStreams.emplace(currentMaxCount, currentStream);
6035 }
6036 }
6037
6038 mPendingStreams.insert(pendingStreams.begin(), pendingStreams.end());
6039 for (const auto& it : mPendingStreams) {
6040 it.second->cancelPrepare();
6041 }
6042}
6043
6044status_t Camera3Device::PreparerThread::resume() {
6045 ATRACE_CALL();
6046 status_t res;
6047
6048 Mutex::Autolock l(mLock);
6049 sp<NotificationListener> listener = mListener.promote();
6050
6051 if (mActive) {
6052 ALOGE("%s: Trying to resume an already active prepare thread!", __FUNCTION__);
6053 return NO_INIT;
6054 }
6055
6056 auto it = mPendingStreams.begin();
6057 for (; it != mPendingStreams.end();) {
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07006058 res = it->second->startPrepare(it->first, true /*blockRequest*/);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006059 if (res == OK) {
6060 if (listener != NULL) {
6061 listener->notifyPrepared(it->second->getId());
6062 }
6063 it = mPendingStreams.erase(it);
6064 } else if (res != NOT_ENOUGH_DATA) {
6065 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__,
6066 res, strerror(-res));
6067 it = mPendingStreams.erase(it);
6068 } else {
6069 it++;
6070 }
6071 }
6072
6073 if (mPendingStreams.empty()) {
6074 return OK;
6075 }
6076
6077 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
6078 if (res != OK) {
6079 ALOGE("%s: Unable to start preparer stream: %d (%s)",
6080 __FUNCTION__, res, strerror(-res));
6081 return res;
6082 }
6083 mCancelNow = false;
6084 mActive = true;
6085 ALOGV("%s: Preparer stream started", __FUNCTION__);
6086
6087 return OK;
6088}
6089
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006090status_t Camera3Device::PreparerThread::clear() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07006091 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006092 Mutex::Autolock l(mLock);
6093
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006094 for (const auto& it : mPendingStreams) {
6095 it.second->cancelPrepare();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006096 }
6097 mPendingStreams.clear();
6098 mCancelNow = true;
6099
6100 return OK;
6101}
6102
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006103void Camera3Device::PreparerThread::setNotificationListener(wp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07006104 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006105 Mutex::Autolock l(mLock);
6106 mListener = listener;
6107}
6108
6109bool Camera3Device::PreparerThread::threadLoop() {
6110 status_t res;
6111 {
6112 Mutex::Autolock l(mLock);
6113 if (mCurrentStream == nullptr) {
6114 // End thread if done with work
6115 if (mPendingStreams.empty()) {
6116 ALOGV("%s: Preparer stream out of work", __FUNCTION__);
6117 // threadLoop _must not_ re-acquire mLock after it sets mActive to false; would
6118 // cause deadlock with prepare()'s requestExitAndWait triggered by !mActive.
6119 mActive = false;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006120 mThreadActiveSignal.signal();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006121 return false;
6122 }
6123
6124 // Get next stream to prepare
6125 auto it = mPendingStreams.begin();
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006126 mCurrentStream = it->second;
6127 mCurrentMaxCount = it->first;
6128 mCurrentPrepareComplete = false;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006129 mPendingStreams.erase(it);
6130 ATRACE_ASYNC_BEGIN("stream prepare", mCurrentStream->getId());
6131 ALOGV("%s: Preparing stream %d", __FUNCTION__, mCurrentStream->getId());
6132 } else if (mCancelNow) {
6133 mCurrentStream->cancelPrepare();
6134 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
6135 ALOGV("%s: Cancelling stream %d prepare", __FUNCTION__, mCurrentStream->getId());
6136 mCurrentStream.clear();
6137 mCancelNow = false;
6138 return true;
6139 }
6140 }
6141
6142 res = mCurrentStream->prepareNextBuffer();
6143 if (res == NOT_ENOUGH_DATA) return true;
6144 if (res != OK) {
6145 // Something bad happened; try to recover by cancelling prepare and
6146 // signalling listener anyway
6147 ALOGE("%s: Stream %d returned error %d (%s) during prepare", __FUNCTION__,
6148 mCurrentStream->getId(), res, strerror(-res));
6149 mCurrentStream->cancelPrepare();
6150 }
6151
6152 // This stream has finished, notify listener
6153 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006154 sp<NotificationListener> listener = mListener.promote();
6155 if (listener != NULL) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006156 ALOGV("%s: Stream %d prepare done, signaling listener", __FUNCTION__,
6157 mCurrentStream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006158 listener->notifyPrepared(mCurrentStream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006159 }
6160
6161 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
6162 mCurrentStream.clear();
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006163 mCurrentPrepareComplete = true;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006164
6165 return true;
6166}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07006167
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006168status_t Camera3Device::RequestBufferStateMachine::initialize(
6169 sp<camera3::StatusTracker> statusTracker) {
6170 if (statusTracker == nullptr) {
6171 ALOGE("%s: statusTracker is null", __FUNCTION__);
6172 return BAD_VALUE;
6173 }
6174
6175 std::lock_guard<std::mutex> lock(mLock);
6176 mStatusTracker = statusTracker;
Yin-Chia Yeh87b3ec02019-06-03 10:44:39 -07006177 mRequestBufferStatusId = statusTracker->addComponent("BufferRequestSM");
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006178 return OK;
6179}
6180
6181bool Camera3Device::RequestBufferStateMachine::startRequestBuffer() {
6182 std::lock_guard<std::mutex> lock(mLock);
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08006183 if (mStatus == RB_STATUS_READY || mStatus == RB_STATUS_PENDING_STOP) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006184 mRequestBufferOngoing = true;
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08006185 notifyTrackerLocked(/*active*/true);
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006186 return true;
6187 }
6188 return false;
6189}
6190
6191void Camera3Device::RequestBufferStateMachine::endRequestBuffer() {
6192 std::lock_guard<std::mutex> lock(mLock);
6193 if (!mRequestBufferOngoing) {
6194 ALOGE("%s called without a successful startRequestBuffer call first!", __FUNCTION__);
6195 return;
6196 }
6197 mRequestBufferOngoing = false;
6198 if (mStatus == RB_STATUS_PENDING_STOP) {
6199 checkSwitchToStopLocked();
6200 }
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08006201 notifyTrackerLocked(/*active*/false);
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006202}
6203
6204void Camera3Device::RequestBufferStateMachine::onStreamsConfigured() {
6205 std::lock_guard<std::mutex> lock(mLock);
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006206 mSwitchedToOffline = false;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006207 mStatus = RB_STATUS_READY;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006208 return;
6209}
6210
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08006211void Camera3Device::RequestBufferStateMachine::onSubmittingRequest() {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006212 std::lock_guard<std::mutex> lock(mLock);
6213 mRequestThreadPaused = false;
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08006214 // inflight map register actually happens in prepareHalRequest now, but it is close enough
6215 // approximation.
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006216 mInflightMapEmpty = false;
6217 if (mStatus == RB_STATUS_STOPPED) {
6218 mStatus = RB_STATUS_READY;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006219 }
6220 return;
6221}
6222
6223void Camera3Device::RequestBufferStateMachine::onRequestThreadPaused() {
6224 std::lock_guard<std::mutex> lock(mLock);
6225 mRequestThreadPaused = true;
6226 if (mStatus == RB_STATUS_PENDING_STOP) {
6227 checkSwitchToStopLocked();
6228 }
6229 return;
6230}
6231
6232void Camera3Device::RequestBufferStateMachine::onInflightMapEmpty() {
6233 std::lock_guard<std::mutex> lock(mLock);
6234 mInflightMapEmpty = true;
6235 if (mStatus == RB_STATUS_PENDING_STOP) {
6236 checkSwitchToStopLocked();
6237 }
6238 return;
6239}
6240
6241void Camera3Device::RequestBufferStateMachine::onWaitUntilIdle() {
6242 std::lock_guard<std::mutex> lock(mLock);
6243 if (!checkSwitchToStopLocked()) {
6244 mStatus = RB_STATUS_PENDING_STOP;
6245 }
6246 return;
6247}
6248
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006249bool Camera3Device::RequestBufferStateMachine::onSwitchToOfflineSuccess() {
6250 std::lock_guard<std::mutex> lock(mLock);
6251 if (mRequestBufferOngoing) {
6252 ALOGE("%s: HAL must not be requesting buffer after HAL returns switchToOffline!",
6253 __FUNCTION__);
6254 return false;
6255 }
6256 mSwitchedToOffline = true;
6257 mInflightMapEmpty = true;
6258 mRequestThreadPaused = true;
6259 mStatus = RB_STATUS_STOPPED;
6260 return true;
6261}
6262
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006263void Camera3Device::RequestBufferStateMachine::notifyTrackerLocked(bool active) {
6264 sp<StatusTracker> statusTracker = mStatusTracker.promote();
6265 if (statusTracker != nullptr) {
6266 if (active) {
6267 statusTracker->markComponentActive(mRequestBufferStatusId);
6268 } else {
6269 statusTracker->markComponentIdle(mRequestBufferStatusId, Fence::NO_FENCE);
6270 }
6271 }
6272}
6273
6274bool Camera3Device::RequestBufferStateMachine::checkSwitchToStopLocked() {
6275 if (mInflightMapEmpty && mRequestThreadPaused && !mRequestBufferOngoing) {
6276 mStatus = RB_STATUS_STOPPED;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006277 return true;
6278 }
6279 return false;
6280}
6281
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006282bool Camera3Device::startRequestBuffer() {
6283 return mRequestBufferSM.startRequestBuffer();
6284}
Shuzhen Wang268a1362018-10-16 16:32:59 -07006285
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006286void Camera3Device::endRequestBuffer() {
6287 mRequestBufferSM.endRequestBuffer();
6288}
Shuzhen Wang268a1362018-10-16 16:32:59 -07006289
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006290nsecs_t Camera3Device::getWaitDuration() {
6291 return kBaseGetBufferWait + getExpectedInFlightDuration();
6292}
Shuzhen Wang268a1362018-10-16 16:32:59 -07006293
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006294void Camera3Device::getInflightBufferKeys(std::vector<std::pair<int32_t, int32_t>>* out) {
6295 mInterface->getInflightBufferKeys(out);
6296}
Shuzhen Wang268a1362018-10-16 16:32:59 -07006297
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006298void Camera3Device::getInflightRequestBufferKeys(std::vector<uint64_t>* out) {
6299 mInterface->getInflightRequestBufferKeys(out);
6300}
Shuzhen Wang268a1362018-10-16 16:32:59 -07006301
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006302std::vector<sp<Camera3StreamInterface>> Camera3Device::getAllStreams() {
6303 std::vector<sp<Camera3StreamInterface>> ret;
6304 bool hasInputStream = mInputStream != nullptr;
6305 ret.reserve(mOutputStreams.size() + mDeletedStreams.size() + ((hasInputStream) ? 1 : 0));
6306 if (hasInputStream) {
6307 ret.push_back(mInputStream);
Shuzhen Wang268a1362018-10-16 16:32:59 -07006308 }
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006309 for (size_t i = 0; i < mOutputStreams.size(); i++) {
6310 ret.push_back(mOutputStreams[i]);
6311 }
6312 for (size_t i = 0; i < mDeletedStreams.size(); i++) {
6313 ret.push_back(mDeletedStreams[i]);
6314 }
6315 return ret;
Shuzhen Wang268a1362018-10-16 16:32:59 -07006316}
6317
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006318status_t Camera3Device::switchToOffline(
6319 const std::vector<int32_t>& streamsToKeep,
6320 /*out*/ sp<CameraOfflineSessionBase>* session) {
6321 ATRACE_CALL();
6322 if (session == nullptr) {
6323 ALOGE("%s: session must not be null", __FUNCTION__);
6324 return BAD_VALUE;
6325 }
6326
6327 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006328
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006329 bool hasInputStream = mInputStream != nullptr;
6330 int32_t inputStreamId = hasInputStream ? mInputStream->getId() : -1;
6331 bool inputStreamSupportsOffline = hasInputStream ?
6332 mInputStream->getOfflineProcessingSupport() : false;
6333 auto outputStreamIds = mOutputStreams.getStreamIds();
6334 auto streamIds = outputStreamIds;
6335 if (hasInputStream) {
6336 streamIds.push_back(mInputStream->getId());
6337 }
6338
6339 // Check all streams in streamsToKeep supports offline mode
6340 for (auto id : streamsToKeep) {
6341 if (std::find(streamIds.begin(), streamIds.end(), id) == streamIds.end()) {
6342 ALOGE("%s: Unknown stream ID %d", __FUNCTION__, id);
6343 return BAD_VALUE;
6344 } else if (id == inputStreamId) {
6345 if (!inputStreamSupportsOffline) {
6346 ALOGE("%s: input stream %d cannot be switched to offline",
6347 __FUNCTION__, id);
6348 return BAD_VALUE;
6349 }
6350 } else {
6351 sp<camera3::Camera3OutputStreamInterface> stream = mOutputStreams.get(id);
6352 if (!stream->getOfflineProcessingSupport()) {
6353 ALOGE("%s: output stream %d cannot be switched to offline",
6354 __FUNCTION__, id);
6355 return BAD_VALUE;
6356 }
6357 }
6358 }
6359
6360 // TODO: block surface sharing and surface group streams until we can support them
6361
6362 // Stop repeating request, wait until all remaining requests are submitted, then call into
6363 // HAL switchToOffline
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006364 hardware::camera::device::V3_6::CameraOfflineSessionInfo offlineSessionInfo;
6365 sp<hardware::camera::device::V3_6::ICameraOfflineSession> offlineSession;
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006366 camera3::BufferRecords bufferRecords;
6367 status_t ret = mRequestThread->switchToOffline(
6368 streamsToKeep, &offlineSessionInfo, &offlineSession, &bufferRecords);
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006369
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006370 if (ret != OK) {
6371 SET_ERR("Switch to offline failed: %s (%d)", strerror(-ret), ret);
6372 return ret;
6373 }
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006374
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006375 bool succ = mRequestBufferSM.onSwitchToOfflineSuccess();
6376 if (!succ) {
6377 SET_ERR("HAL must not be calling requestStreamBuffers call");
6378 // TODO: block ALL callbacks from HAL till app configured new streams?
6379 return UNKNOWN_ERROR;
6380 }
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006381
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006382 // Verify offlineSessionInfo
6383 std::vector<int32_t> offlineStreamIds;
6384 offlineStreamIds.reserve(offlineSessionInfo.offlineStreams.size());
6385 for (auto offlineStream : offlineSessionInfo.offlineStreams) {
6386 // verify stream IDs
6387 int32_t id = offlineStream.id;
6388 if (std::find(streamIds.begin(), streamIds.end(), id) == streamIds.end()) {
6389 SET_ERR("stream ID %d not found!", id);
6390 return UNKNOWN_ERROR;
6391 }
6392
6393 // When not using HAL buf manager, only allow streams requested by app to be preserved
6394 if (!mUseHalBufManager) {
6395 if (std::find(streamsToKeep.begin(), streamsToKeep.end(), id) == streamsToKeep.end()) {
6396 SET_ERR("stream ID %d must not be switched to offline!", id);
6397 return UNKNOWN_ERROR;
6398 }
6399 }
6400
6401 offlineStreamIds.push_back(id);
6402 sp<Camera3StreamInterface> stream = (id == inputStreamId) ?
6403 static_cast<sp<Camera3StreamInterface>>(mInputStream) :
6404 static_cast<sp<Camera3StreamInterface>>(mOutputStreams.get(id));
6405 // Verify number of outstanding buffers
6406 if (stream->getOutstandingBuffersCount() != offlineStream.numOutstandingBuffers) {
6407 SET_ERR("Offline stream %d # of remaining buffer mismatch: (%zu,%d) (service/HAL)",
6408 id, stream->getOutstandingBuffersCount(), offlineStream.numOutstandingBuffers);
6409 return UNKNOWN_ERROR;
6410 }
6411 }
6412
6413 // Verify all streams to be deleted don't have any outstanding buffers
6414 if (hasInputStream && std::find(offlineStreamIds.begin(), offlineStreamIds.end(),
6415 inputStreamId) == offlineStreamIds.end()) {
6416 if (mInputStream->hasOutstandingBuffers()) {
6417 SET_ERR("Input stream %d still has %zu outstanding buffer!",
6418 inputStreamId, mInputStream->getOutstandingBuffersCount());
6419 return UNKNOWN_ERROR;
6420 }
6421 }
6422
6423 for (const auto& outStreamId : outputStreamIds) {
6424 if (std::find(offlineStreamIds.begin(), offlineStreamIds.end(),
6425 outStreamId) == offlineStreamIds.end()) {
6426 auto outStream = mOutputStreams.get(outStreamId);
6427 if (outStream->hasOutstandingBuffers()) {
6428 SET_ERR("Output stream %d still has %zu outstanding buffer!",
6429 outStreamId, outStream->getOutstandingBuffersCount());
6430 return UNKNOWN_ERROR;
6431 }
6432 }
6433 }
6434
6435 InFlightRequestMap offlineReqs;
6436 // Verify inflight requests and their pending buffers
6437 {
6438 std::lock_guard<std::mutex> l(mInFlightLock);
6439 for (auto offlineReq : offlineSessionInfo.offlineRequests) {
6440 int idx = mInFlightMap.indexOfKey(offlineReq.frameNumber);
6441 if (idx == NAME_NOT_FOUND) {
6442 SET_ERR("Offline request frame number %d not found!", offlineReq.frameNumber);
6443 return UNKNOWN_ERROR;
6444 }
6445
6446 const auto& inflightReq = mInFlightMap.valueAt(idx);
6447 // TODO: check specific stream IDs
6448 size_t numBuffersLeft = static_cast<size_t>(inflightReq.numBuffersLeft);
6449 if (numBuffersLeft != offlineReq.pendingStreams.size()) {
6450 SET_ERR("Offline request # of remaining buffer mismatch: (%d,%d) (service/HAL)",
6451 inflightReq.numBuffersLeft, offlineReq.pendingStreams.size());
6452 return UNKNOWN_ERROR;
6453 }
6454 offlineReqs.add(offlineReq.frameNumber, inflightReq);
6455 }
6456 }
6457
6458 // Create Camera3OfflineSession and transfer object ownership
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006459 // (streams, inflight requests, buffer caches)
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006460 camera3::StreamSet offlineStreamSet;
6461 sp<camera3::Camera3Stream> inputStream;
6462 for (auto offlineStream : offlineSessionInfo.offlineStreams) {
6463 int32_t id = offlineStream.id;
6464 if (mInputStream != nullptr && id == mInputStream->getId()) {
6465 inputStream = mInputStream;
6466 } else {
6467 offlineStreamSet.add(id, mOutputStreams.get(id));
6468 }
6469 }
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006470
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006471 // TODO: check if we need to lock before copying states
6472 // though technically no other thread should be talking to Camera3Device at this point
6473 Camera3OfflineStates offlineStates(
6474 mTagMonitor, mVendorTagId, mUseHalBufManager, mNeedFixupMonochromeTags,
Shuzhen Wangb7b42652020-05-07 11:59:02 -07006475 mUsePartialResult, mNumPartialResults, mLastCompletedRegularFrameNumber,
6476 mLastCompletedReprocessFrameNumber, mLastCompletedZslFrameNumber,
6477 mNextResultFrameNumber, mNextReprocessResultFrameNumber,
6478 mNextZslStillResultFrameNumber, mNextShutterFrameNumber,
6479 mNextReprocessShutterFrameNumber, mNextZslStillShutterFrameNumber,
6480 mDeviceInfo, mPhysicalDeviceInfoMap, mDistortionMappers,
6481 mZoomRatioMappers, mRotateAndCropMappers);
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006482
6483 *session = new Camera3OfflineSession(mId, inputStream, offlineStreamSet,
6484 std::move(bufferRecords), offlineReqs, offlineStates, offlineSession);
6485
6486 // Delete all streams that has been transferred to offline session
6487 Mutex::Autolock l(mLock);
6488 for (auto offlineStream : offlineSessionInfo.offlineStreams) {
6489 int32_t id = offlineStream.id;
6490 if (mInputStream != nullptr && id == mInputStream->getId()) {
6491 mInputStream.clear();
6492 } else {
6493 mOutputStreams.remove(id);
6494 }
6495 }
6496
6497 // disconnect all other streams and switch to UNCONFIGURED state
6498 if (mInputStream != nullptr) {
6499 ret = mInputStream->disconnect();
6500 if (ret != OK) {
6501 SET_ERR_L("disconnect input stream failed!");
6502 return UNKNOWN_ERROR;
6503 }
6504 }
6505
6506 for (auto streamId : mOutputStreams.getStreamIds()) {
6507 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
6508 ret = stream->disconnect();
6509 if (ret != OK) {
6510 SET_ERR_L("disconnect output stream %d failed!", streamId);
6511 return UNKNOWN_ERROR;
6512 }
6513 }
6514
6515 mInputStream.clear();
6516 mOutputStreams.clear();
6517 mNeedConfig = true;
6518 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
6519 mOperatingMode = NO_MODE;
6520 mIsConstrainedHighSpeedConfiguration = false;
Emilian Peevc0fe54c2020-03-11 14:05:07 -07006521 mRequestThread->clearPreviousRequest();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006522
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006523 return OK;
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006524 // TO be done by CameraDeviceClient/Camera3OfflineSession
6525 // register the offline client to camera service
6526 // Setup result passthing threads etc
6527 // Initialize offline session so HAL can start sending callback to it (result Fmq)
6528 // TODO: check how many onIdle callback will be sent
6529 // Java side to make sure the CameraCaptureSession is properly closed
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006530}
6531
Emilian Peevcc0b7952020-01-07 13:54:47 -08006532void Camera3Device::getOfflineStreamIds(std::vector<int> *offlineStreamIds) {
6533 ATRACE_CALL();
6534
6535 if (offlineStreamIds == nullptr) {
6536 return;
6537 }
6538
6539 Mutex::Autolock il(mInterfaceLock);
6540
6541 auto streamIds = mOutputStreams.getStreamIds();
6542 bool hasInputStream = mInputStream != nullptr;
6543 if (hasInputStream && mInputStream->getOfflineProcessingSupport()) {
6544 offlineStreamIds->push_back(mInputStream->getId());
6545 }
6546
6547 for (const auto & streamId : streamIds) {
6548 sp<camera3::Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
6549 // Streams that use the camera buffer manager are currently not supported in
6550 // offline mode
6551 if (stream->getOfflineProcessingSupport() &&
6552 (stream->getStreamSetId() == CAMERA3_STREAM_SET_ID_INVALID)) {
6553 offlineStreamIds->push_back(streamId);
6554 }
6555 }
6556}
6557
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08006558status_t Camera3Device::setRotateAndCropAutoBehavior(
6559 camera_metadata_enum_android_scaler_rotate_and_crop_t rotateAndCropValue) {
6560 ATRACE_CALL();
6561 Mutex::Autolock il(mInterfaceLock);
6562 Mutex::Autolock l(mLock);
6563 if (mRequestThread == nullptr) {
6564 return INVALID_OPERATION;
6565 }
6566 return mRequestThread->setRotateAndCropAutoBehavior(rotateAndCropValue);
6567}
6568
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08006569bool Camera3Device::supportsCameraMute() {
6570 Mutex::Autolock il(mInterfaceLock);
6571 Mutex::Autolock l(mLock);
6572
6573 return mSupportCameraMute;
6574}
6575
6576status_t Camera3Device::setCameraMute(bool enabled) {
6577 ATRACE_CALL();
6578 Mutex::Autolock il(mInterfaceLock);
6579 Mutex::Autolock l(mLock);
6580
6581 if (mRequestThread == nullptr || !mSupportCameraMute) {
6582 return INVALID_OPERATION;
6583 }
Eino-Ville Talvala11afe4f2021-05-27 14:45:31 -07006584 int32_t muteMode =
6585 !enabled ? ANDROID_SENSOR_TEST_PATTERN_MODE_OFF :
6586 mSupportTestPatternSolidColor ? ANDROID_SENSOR_TEST_PATTERN_MODE_SOLID_COLOR :
6587 ANDROID_SENSOR_TEST_PATTERN_MODE_BLACK;
6588 return mRequestThread->setCameraMute(muteMode);
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08006589}
6590
Cliff Wuc2ad9c82021-04-21 00:58:58 +08006591status_t Camera3Device::injectCamera(const String8& injectedCamId,
6592 sp<CameraProviderManager> manager) {
6593 ALOGI("%s Injection camera: injectedCamId = %s", __FUNCTION__, injectedCamId.string());
6594 ATRACE_CALL();
6595 Mutex::Autolock il(mInterfaceLock);
Cliff Wu3b268182021-07-06 15:44:43 +08006596 // When the camera device is active, injectCamera() and stopInjection() will call
6597 // internalPauseAndWaitLocked() and internalResumeLocked(), and then they will call
6598 // mStatusChanged.waitRelative(mLock, timeout) of waitUntilStateThenRelock(). But
6599 // mStatusChanged.waitRelative(mLock, timeout)'s parameter: mutex "mLock" must be in the locked
6600 // state, so we need to add "Mutex::Autolock l(mLock)" to lock the "mLock" before calling
6601 // waitUntilStateThenRelock().
6602 Mutex::Autolock l(mLock);
Cliff Wuc2ad9c82021-04-21 00:58:58 +08006603
6604 status_t res = NO_ERROR;
6605 if (mInjectionMethods->isInjecting()) {
6606 if (injectedCamId == mInjectionMethods->getInjectedCamId()) {
6607 return OK;
6608 } else {
6609 res = mInjectionMethods->stopInjection();
6610 if (res != OK) {
6611 ALOGE("%s: Failed to stop the injection camera! ret != NO_ERROR: %d",
6612 __FUNCTION__, res);
6613 return res;
6614 }
6615 }
6616 }
6617
6618 res = mInjectionMethods->injectionInitialize(injectedCamId, manager, this);
6619 if (res != OK) {
6620 ALOGE("%s: Failed to initialize the injection camera! ret != NO_ERROR: %d",
6621 __FUNCTION__, res);
6622 return res;
6623 }
6624
Cliff Wuc2ad9c82021-04-21 00:58:58 +08006625 // When the second display of android is cast to the remote device, and the opened camera is
6626 // also cast to the second display, in this case, because the camera has configured the streams
6627 // at this time, we can directly call injectCamera() to replace the internal camera with
6628 // injection camera.
Cliff Wu3b268182021-07-06 15:44:43 +08006629 if (mInjectionMethods->isStreamConfigCompleteButNotInjected()) {
6630 ALOGD("%s: The opened camera is directly cast to the remote device.", __FUNCTION__);
6631
6632 camera3::camera_stream_configuration injectionConfig;
6633 std::vector<uint32_t> injectionBufferSizes;
6634 mInjectionMethods->getInjectionConfig(&injectionConfig, &injectionBufferSizes);
6635 if (mOperatingMode < 0 || injectionConfig.num_streams <= 0
6636 || injectionBufferSizes.size() <= 0) {
6637 ALOGE("Failed to inject camera due to abandoned configuration! "
6638 "mOperatingMode: %d injectionConfig.num_streams: %d "
6639 "injectionBufferSizes.size(): %zu", mOperatingMode,
6640 injectionConfig.num_streams, injectionBufferSizes.size());
6641 return DEAD_OBJECT;
6642 }
6643
Cliff Wuc2ad9c82021-04-21 00:58:58 +08006644 res = mInjectionMethods->injectCamera(
6645 injectionConfig, injectionBufferSizes);
6646 if (res != OK) {
6647 ALOGE("Can't finish inject camera process!");
6648 return res;
6649 }
6650 }
6651
6652 return OK;
6653}
6654
6655status_t Camera3Device::stopInjection() {
6656 ALOGI("%s: Injection camera: stopInjection", __FUNCTION__);
6657 Mutex::Autolock il(mInterfaceLock);
Cliff Wu3b268182021-07-06 15:44:43 +08006658 Mutex::Autolock l(mLock);
Cliff Wuc2ad9c82021-04-21 00:58:58 +08006659 return mInjectionMethods->stopInjection();
6660}
6661
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08006662}; // namespace android