blob: a195fb1755b8d9a5969849a1817e82365e3df90f [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 Wuc2ad9c82021-04-21 00:58:58 +08002839 // Since the streams configuration of the injection camera is based on the internal camera, we
2840 // must wait until the internal camera configure streams before calling injectCamera() to
2841 // configure the injection streams.
2842 if (mInjectionMethods->isInjecting()) {
2843 ALOGV("%s: Injection camera %s: Start to configure streams.",
2844 __FUNCTION__, mInjectionMethods->getInjectedCamId().string());
2845 res = mInjectionMethods->injectCamera(config, bufferSizes);
2846 if (res != OK) {
2847 ALOGE("Can't finish inject camera process!");
2848 return res;
2849 }
2850 }
2851
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002852 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002853}
2854
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002855status_t Camera3Device::addFakeStreamLocked() {
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002856 ATRACE_CALL();
2857 status_t res;
2858
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002859 if (mFakeStreamId != NO_STREAM) {
2860 // Should never be adding a second fake stream when one is already
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002861 // active
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002862 SET_ERR_L("%s: Camera %s: A fake stream already exists!",
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002863 __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002864 return INVALID_OPERATION;
2865 }
2866
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002867 ALOGV("%s: Camera %s: Adding a fake stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002868
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002869 sp<Camera3OutputStreamInterface> fakeStream =
2870 new Camera3FakeStream(mNextStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002871
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002872 res = mOutputStreams.add(mNextStreamId, fakeStream);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002873 if (res < 0) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002874 SET_ERR_L("Can't add fake stream to set: %s (%d)", strerror(-res), res);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002875 return res;
2876 }
2877
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002878 mFakeStreamId = mNextStreamId;
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002879 mNextStreamId++;
2880
2881 return OK;
2882}
2883
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002884status_t Camera3Device::tryRemoveFakeStreamLocked() {
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002885 ATRACE_CALL();
2886 status_t res;
2887
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002888 if (mFakeStreamId == NO_STREAM) return OK;
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002889 if (mOutputStreams.size() == 1) return OK;
2890
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002891 ALOGV("%s: Camera %s: Removing the fake stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002892
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002893 // Ok, have a fake stream and there's at least one other output stream,
2894 // so remove the fake
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002895
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002896 sp<Camera3StreamInterface> deletedStream = mOutputStreams.get(mFakeStreamId);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002897 if (deletedStream == nullptr) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002898 SET_ERR_L("Fake stream %d does not appear to exist", mFakeStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002899 return INVALID_OPERATION;
2900 }
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002901 mOutputStreams.remove(mFakeStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002902
2903 // Free up the stream endpoint so that it can be used by some other stream
2904 res = deletedStream->disconnect();
2905 if (res != OK) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002906 SET_ERR_L("Can't disconnect deleted fake stream %d", mFakeStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002907 // fall through since we want to still list the stream as deleted.
2908 }
2909 mDeletedStreams.add(deletedStream);
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002910 mFakeStreamId = NO_STREAM;
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002911
2912 return res;
2913}
2914
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002915void Camera3Device::setErrorState(const char *fmt, ...) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002916 ATRACE_CALL();
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002917 Mutex::Autolock l(mLock);
2918 va_list args;
2919 va_start(args, fmt);
2920
2921 setErrorStateLockedV(fmt, args);
2922
2923 va_end(args);
2924}
2925
2926void Camera3Device::setErrorStateV(const char *fmt, va_list args) {
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 setErrorStateLockedV(fmt, args);
2930}
2931
2932void Camera3Device::setErrorStateLocked(const char *fmt, ...) {
2933 va_list args;
2934 va_start(args, fmt);
2935
2936 setErrorStateLockedV(fmt, args);
2937
2938 va_end(args);
2939}
2940
2941void Camera3Device::setErrorStateLockedV(const char *fmt, va_list args) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002942 // Print out all error messages to log
2943 String8 errorCause = String8::formatV(fmt, args);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002944 ALOGE("Camera %s: %s", mId.string(), errorCause.string());
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002945
2946 // But only do error state transition steps for the first error
Zhijun Heb05eeae2013-06-06 13:51:22 -07002947 if (mStatus == STATUS_ERROR || mStatus == STATUS_UNINITIALIZED) return;
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002948
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002949 mErrorCause = errorCause;
2950
Yin-Chia Yeh3d145ae2017-07-27 12:47:03 -07002951 if (mRequestThread != nullptr) {
2952 mRequestThread->setPaused(true);
2953 }
Ruben Brunk183f0562015-08-12 12:55:02 -07002954 internalUpdateStatusLocked(STATUS_ERROR);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002955
2956 // Notify upstream about a device error
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002957 sp<NotificationListener> listener = mListener.promote();
2958 if (listener != NULL) {
2959 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002960 CaptureResultExtras());
Shuzhen Wang316781a2020-08-18 18:11:01 -07002961 mSessionStatsBuilder.onDeviceError();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002962 }
2963
2964 // Save stack trace. View by dumping it later.
2965 CameraTraces::saveTrace();
2966 // TODO: consider adding errorCause and client pid/procname
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002967}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002968
2969/**
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002970 * In-flight request management
2971 */
2972
Jianing Weicb0652e2014-03-12 18:29:36 -07002973status_t Camera3Device::registerInFlight(uint32_t frameNumber,
Chien-Yu Chend196d612015-06-22 19:49:01 -07002974 int32_t numBuffers, CaptureResultExtras resultExtras, bool hasInput,
Shuzhen Wang5c22c152017-12-31 17:12:25 -08002975 bool hasAppCallback, nsecs_t maxExpectedDuration,
Shuzhen Wang99080502021-03-07 21:08:20 -08002976 const std::set<std::set<String8>>& physicalCameraIds,
2977 bool isStillCapture, bool isZslCapture, bool rotateAndCropAuto,
2978 const std::set<std::string>& cameraIdsWithZoom,
Shuzhen Wang316781a2020-08-18 18:11:01 -07002979 const SurfaceMap& outputSurfaces, nsecs_t requestTimeNs) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002980 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002981 std::lock_guard<std::mutex> l(mInFlightLock);
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002982
2983 ssize_t res;
Chien-Yu Chend196d612015-06-22 19:49:01 -07002984 res = mInFlightMap.add(frameNumber, InFlightRequest(numBuffers, resultExtras, hasInput,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07002985 hasAppCallback, maxExpectedDuration, physicalCameraIds, isStillCapture, isZslCapture,
Shuzhen Wang316781a2020-08-18 18:11:01 -07002986 rotateAndCropAuto, cameraIdsWithZoom, requestTimeNs, outputSurfaces));
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002987 if (res < 0) return res;
2988
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07002989 if (mInFlightMap.size() == 1) {
Emilian Peev26d975d2018-07-05 14:52:57 +01002990 // Hold a separate dedicated tracker lock to prevent race with disconnect and also
2991 // avoid a deadlock during reprocess requests.
2992 Mutex::Autolock l(mTrackerLock);
Yin-Chia Yeh38dfde52017-06-27 17:13:33 -07002993 if (mStatusTracker != nullptr) {
2994 mStatusTracker->markComponentActive(mInFlightStatusId);
2995 }
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07002996 }
2997
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07002998 mExpectedInflightDuration += maxExpectedDuration;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002999 return OK;
3000}
3001
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003002void Camera3Device::onInflightEntryRemovedLocked(nsecs_t duration) {
Shuzhen Wangcadb3302016-11-04 14:17:56 -07003003 // Indicate idle inFlightMap to the status tracker
3004 if (mInFlightMap.size() == 0) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07003005 mRequestBufferSM.onInflightMapEmpty();
Emilian Peev26d975d2018-07-05 14:52:57 +01003006 // Hold a separate dedicated tracker lock to prevent race with disconnect and also
3007 // avoid a deadlock during reprocess requests.
3008 Mutex::Autolock l(mTrackerLock);
Yin-Chia Yeh38dfde52017-06-27 17:13:33 -07003009 if (mStatusTracker != nullptr) {
3010 mStatusTracker->markComponentIdle(mInFlightStatusId, Fence::NO_FENCE);
3011 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07003012 }
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003013 mExpectedInflightDuration -= duration;
Shuzhen Wangcadb3302016-11-04 14:17:56 -07003014}
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003015
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003016void Camera3Device::checkInflightMapLengthLocked() {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04003017 // Validation check - if we have too many in-flight frames with long total inflight duration,
Yin-Chia Yeh99fd0972019-06-27 14:22:44 -07003018 // something has likely gone wrong. This might still be legit only if application send in
3019 // a long burst of long exposure requests.
3020 if (mExpectedInflightDuration > kMinWarnInflightDuration) {
3021 if (!mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() > kInFlightWarnLimit) {
3022 CLOGW("In-flight list too large: %zu, total inflight duration %" PRIu64,
3023 mInFlightMap.size(), mExpectedInflightDuration);
3024 } else if (mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() >
3025 kInFlightWarnLimitHighSpeed) {
3026 CLOGW("In-flight list too large for high speed configuration: %zu,"
3027 "total inflight duration %" PRIu64,
3028 mInFlightMap.size(), mExpectedInflightDuration);
3029 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003030 }
3031}
3032
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003033void Camera3Device::onInflightMapFlushedLocked() {
3034 mExpectedInflightDuration = 0;
3035}
3036
3037void Camera3Device::removeInFlightMapEntryLocked(int idx) {
Jayant Chowdharyd4776262020-06-23 23:45:57 -07003038 ATRACE_HFR_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003039 nsecs_t duration = mInFlightMap.valueAt(idx).maxExpectedDuration;
3040 mInFlightMap.removeItemsAt(idx, 1);
3041
3042 onInflightEntryRemovedLocked(duration);
3043}
3044
3045
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003046void Camera3Device::flushInflightRequests() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003047 ATRACE_CALL();
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003048 sp<NotificationListener> listener;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003049 {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003050 std::lock_guard<std::mutex> l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003051 listener = mListener.promote();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003052 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003053
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003054 FlushInflightReqStates states {
3055 mId, mInFlightLock, mInFlightMap, mUseHalBufManager,
Shuzhen Wang316781a2020-08-18 18:11:01 -07003056 listener, *this, *mInterface, *this, mSessionStatsBuilder};
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003057
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003058 camera3::flushInflightRequests(states);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003059}
3060
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003061CameraMetadata Camera3Device::getLatestRequestLocked() {
Igor Murashkin1e479c02013-09-06 16:55:14 -07003062 ALOGV("%s", __FUNCTION__);
3063
Igor Murashkin1e479c02013-09-06 16:55:14 -07003064 CameraMetadata retVal;
3065
3066 if (mRequestThread != NULL) {
3067 retVal = mRequestThread->getLatestRequest();
3068 }
3069
Igor Murashkin1e479c02013-09-06 16:55:14 -07003070 return retVal;
3071}
3072
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07003073void Camera3Device::monitorMetadata(TagMonitor::eventSource source,
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003074 int64_t frameNumber, nsecs_t timestamp, const CameraMetadata& metadata,
3075 const std::unordered_map<std::string, CameraMetadata>& physicalMetadata) {
3076
3077 mTagMonitor.monitorMetadata(source, frameNumber, timestamp, metadata,
3078 physicalMetadata);
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07003079}
3080
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003081/**
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003082 * HalInterface inner class methods
3083 */
3084
Yifan Hongf79b5542017-04-11 14:44:25 -07003085Camera3Device::HalInterface::HalInterface(
3086 sp<ICameraDeviceSession> &session,
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003087 std::shared_ptr<RequestMetadataQueue> queue,
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003088 bool useHalBufManager, bool supportOfflineProcessing) :
Yifan Hongf79b5542017-04-11 14:44:25 -07003089 mHidlSession(session),
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003090 mRequestMetadataQueue(queue),
Emilian Peev4ec17882019-01-24 17:16:58 -08003091 mUseHalBufManager(useHalBufManager),
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003092 mIsReconfigurationQuerySupported(true),
3093 mSupportOfflineProcessing(supportOfflineProcessing) {
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003094 // Check with hardware service manager if we can downcast these interfaces
3095 // Somewhat expensive, so cache the results at startup
Shuzhen Wang83bff122020-11-20 15:51:39 -08003096 auto castResult_3_7 = device::V3_7::ICameraDeviceSession::castFrom(mHidlSession);
3097 if (castResult_3_7.isOk()) {
3098 mHidlSession_3_7 = castResult_3_7;
3099 }
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003100 auto castResult_3_6 = device::V3_6::ICameraDeviceSession::castFrom(mHidlSession);
3101 if (castResult_3_6.isOk()) {
3102 mHidlSession_3_6 = castResult_3_6;
3103 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003104 auto castResult_3_5 = device::V3_5::ICameraDeviceSession::castFrom(mHidlSession);
3105 if (castResult_3_5.isOk()) {
3106 mHidlSession_3_5 = castResult_3_5;
3107 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003108 auto castResult_3_4 = device::V3_4::ICameraDeviceSession::castFrom(mHidlSession);
3109 if (castResult_3_4.isOk()) {
3110 mHidlSession_3_4 = castResult_3_4;
3111 }
3112 auto castResult_3_3 = device::V3_3::ICameraDeviceSession::castFrom(mHidlSession);
3113 if (castResult_3_3.isOk()) {
3114 mHidlSession_3_3 = castResult_3_3;
3115 }
3116}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003117
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003118Camera3Device::HalInterface::HalInterface() :
3119 mUseHalBufManager(false),
3120 mSupportOfflineProcessing(false) {}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003121
3122Camera3Device::HalInterface::HalInterface(const HalInterface& other) :
Yifan Hongf79b5542017-04-11 14:44:25 -07003123 mHidlSession(other.mHidlSession),
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003124 mRequestMetadataQueue(other.mRequestMetadataQueue),
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003125 mUseHalBufManager(other.mUseHalBufManager),
3126 mSupportOfflineProcessing(other.mSupportOfflineProcessing) {}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003127
3128bool Camera3Device::HalInterface::valid() {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003129 return (mHidlSession != nullptr);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003130}
3131
3132void Camera3Device::HalInterface::clear() {
Shuzhen Wang83bff122020-11-20 15:51:39 -08003133 mHidlSession_3_7.clear();
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003134 mHidlSession_3_6.clear();
Emilian Peev644a3e12018-11-23 13:52:39 +00003135 mHidlSession_3_5.clear();
Emilian Peev9e740b02018-01-30 18:28:03 +00003136 mHidlSession_3_4.clear();
3137 mHidlSession_3_3.clear();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003138 mHidlSession.clear();
3139}
3140
3141status_t Camera3Device::HalInterface::constructDefaultRequestSettings(
Emilian Peevf4816702020-04-03 15:44:51 -07003142 camera_request_template_t templateId,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003143 /*out*/ camera_metadata_t **requestTemplate) {
3144 ATRACE_NAME("CameraHal::constructDefaultRequestSettings");
3145 if (!valid()) return INVALID_OPERATION;
3146 status_t res = OK;
3147
Emilian Peev31abd0a2017-05-11 18:37:46 +01003148 common::V1_0::Status status;
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003149
3150 auto requestCallback = [&status, &requestTemplate]
Emilian Peev31abd0a2017-05-11 18:37:46 +01003151 (common::V1_0::Status s, const device::V3_2::CameraMetadata& request) {
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003152 status = s;
3153 if (status == common::V1_0::Status::OK) {
3154 const camera_metadata *r =
3155 reinterpret_cast<const camera_metadata_t*>(request.data());
3156 size_t expectedSize = request.size();
3157 int ret = validate_camera_metadata_structure(r, &expectedSize);
3158 if (ret == OK || ret == CAMERA_METADATA_VALIDATION_SHIFTED) {
3159 *requestTemplate = clone_camera_metadata(r);
3160 if (*requestTemplate == nullptr) {
3161 ALOGE("%s: Unable to clone camera metadata received from HAL",
3162 __FUNCTION__);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003163 status = common::V1_0::Status::INTERNAL_ERROR;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003164 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003165 } else {
3166 ALOGE("%s: Malformed camera metadata received from HAL", __FUNCTION__);
3167 status = common::V1_0::Status::INTERNAL_ERROR;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003168 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003169 }
3170 };
3171 hardware::Return<void> err;
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003172 RequestTemplate id;
3173 switch (templateId) {
Emilian Peevf4816702020-04-03 15:44:51 -07003174 case CAMERA_TEMPLATE_PREVIEW:
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003175 id = RequestTemplate::PREVIEW;
3176 break;
Emilian Peevf4816702020-04-03 15:44:51 -07003177 case CAMERA_TEMPLATE_STILL_CAPTURE:
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003178 id = RequestTemplate::STILL_CAPTURE;
3179 break;
Emilian Peevf4816702020-04-03 15:44:51 -07003180 case CAMERA_TEMPLATE_VIDEO_RECORD:
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003181 id = RequestTemplate::VIDEO_RECORD;
3182 break;
Emilian Peevf4816702020-04-03 15:44:51 -07003183 case CAMERA_TEMPLATE_VIDEO_SNAPSHOT:
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003184 id = RequestTemplate::VIDEO_SNAPSHOT;
3185 break;
Emilian Peevf4816702020-04-03 15:44:51 -07003186 case CAMERA_TEMPLATE_ZERO_SHUTTER_LAG:
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003187 id = RequestTemplate::ZERO_SHUTTER_LAG;
3188 break;
Emilian Peevf4816702020-04-03 15:44:51 -07003189 case CAMERA_TEMPLATE_MANUAL:
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003190 id = RequestTemplate::MANUAL;
3191 break;
3192 default:
3193 // Unknown template ID, or this HAL is too old to support it
3194 return BAD_VALUE;
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003195 }
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003196 err = mHidlSession->constructDefaultRequestSettings(id, requestCallback);
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003197
Emilian Peev31abd0a2017-05-11 18:37:46 +01003198 if (!err.isOk()) {
3199 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3200 res = DEAD_OBJECT;
3201 } else {
3202 res = CameraProviderManager::mapToStatusT(status);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003203 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003204
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003205 return res;
3206}
3207
Emilian Peev4ec17882019-01-24 17:16:58 -08003208bool Camera3Device::HalInterface::isReconfigurationRequired(CameraMetadata& oldSessionParams,
3209 CameraMetadata& newSessionParams) {
3210 // We do reconfiguration by default;
3211 bool ret = true;
3212 if ((mHidlSession_3_5 != nullptr) && mIsReconfigurationQuerySupported) {
3213 android::hardware::hidl_vec<uint8_t> oldParams, newParams;
3214 camera_metadata_t* oldSessioMeta = const_cast<camera_metadata_t*>(
3215 oldSessionParams.getAndLock());
3216 camera_metadata_t* newSessioMeta = const_cast<camera_metadata_t*>(
3217 newSessionParams.getAndLock());
3218 oldParams.setToExternal(reinterpret_cast<uint8_t*>(oldSessioMeta),
3219 get_camera_metadata_size(oldSessioMeta));
3220 newParams.setToExternal(reinterpret_cast<uint8_t*>(newSessioMeta),
3221 get_camera_metadata_size(newSessioMeta));
3222 hardware::camera::common::V1_0::Status callStatus;
3223 bool required;
3224 auto hidlCb = [&callStatus, &required] (hardware::camera::common::V1_0::Status s,
3225 bool requiredFlag) {
3226 callStatus = s;
3227 required = requiredFlag;
3228 };
3229 auto err = mHidlSession_3_5->isReconfigurationRequired(oldParams, newParams, hidlCb);
3230 oldSessionParams.unlock(oldSessioMeta);
3231 newSessionParams.unlock(newSessioMeta);
3232 if (err.isOk()) {
3233 switch (callStatus) {
3234 case hardware::camera::common::V1_0::Status::OK:
3235 ret = required;
3236 break;
3237 case hardware::camera::common::V1_0::Status::METHOD_NOT_SUPPORTED:
3238 mIsReconfigurationQuerySupported = false;
3239 ret = true;
3240 break;
3241 default:
3242 ALOGV("%s: Reconfiguration query failed: %d", __FUNCTION__, callStatus);
3243 ret = true;
3244 }
3245 } else {
3246 ALOGE("%s: Unexpected binder error: %s", __FUNCTION__, err.description().c_str());
3247 ret = true;
3248 }
3249 }
3250
3251 return ret;
3252}
3253
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003254status_t Camera3Device::HalInterface::configureStreams(const camera_metadata_t *sessionParams,
Emilian Peevf4816702020-04-03 15:44:51 -07003255 camera_stream_configuration *config, const std::vector<uint32_t>& bufferSizes) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003256 ATRACE_NAME("CameraHal::configureStreams");
3257 if (!valid()) return INVALID_OPERATION;
3258 status_t res = OK;
3259
Shuzhen Wang83bff122020-11-20 15:51:39 -08003260 if (config->input_is_multi_resolution && mHidlSession_3_7 == nullptr) {
3261 ALOGE("%s: Camera device doesn't support multi-resolution input stream", __FUNCTION__);
3262 return BAD_VALUE;
3263 }
3264
Emilian Peev31abd0a2017-05-11 18:37:46 +01003265 // Convert stream config to HIDL
3266 std::set<int> activeStreams;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003267 device::V3_2::StreamConfiguration requestedConfiguration3_2;
3268 device::V3_4::StreamConfiguration requestedConfiguration3_4;
Shuzhen Wang83bff122020-11-20 15:51:39 -08003269 device::V3_7::StreamConfiguration requestedConfiguration3_7;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003270 requestedConfiguration3_2.streams.resize(config->num_streams);
3271 requestedConfiguration3_4.streams.resize(config->num_streams);
Shuzhen Wang83bff122020-11-20 15:51:39 -08003272 requestedConfiguration3_7.streams.resize(config->num_streams);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003273 for (size_t i = 0; i < config->num_streams; i++) {
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003274 device::V3_2::Stream &dst3_2 = requestedConfiguration3_2.streams[i];
3275 device::V3_4::Stream &dst3_4 = requestedConfiguration3_4.streams[i];
Shuzhen Wang83bff122020-11-20 15:51:39 -08003276 device::V3_7::Stream &dst3_7 = requestedConfiguration3_7.streams[i];
Emilian Peevf4816702020-04-03 15:44:51 -07003277 camera3::camera_stream_t *src = config->streams[i];
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003278
Emilian Peev31abd0a2017-05-11 18:37:46 +01003279 Camera3Stream* cam3stream = Camera3Stream::cast(src);
3280 cam3stream->setBufferFreedListener(this);
3281 int streamId = cam3stream->getId();
3282 StreamType streamType;
3283 switch (src->stream_type) {
Emilian Peevf4816702020-04-03 15:44:51 -07003284 case CAMERA_STREAM_OUTPUT:
Emilian Peev31abd0a2017-05-11 18:37:46 +01003285 streamType = StreamType::OUTPUT;
3286 break;
Emilian Peevf4816702020-04-03 15:44:51 -07003287 case CAMERA_STREAM_INPUT:
Emilian Peev31abd0a2017-05-11 18:37:46 +01003288 streamType = StreamType::INPUT;
3289 break;
3290 default:
3291 ALOGE("%s: Stream %d: Unsupported stream type %d",
3292 __FUNCTION__, streamId, config->streams[i]->stream_type);
3293 return BAD_VALUE;
3294 }
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003295 dst3_2.id = streamId;
3296 dst3_2.streamType = streamType;
3297 dst3_2.width = src->width;
3298 dst3_2.height = src->height;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003299 dst3_2.usage = mapToConsumerUsage(cam3stream->getUsage());
Emilian Peevf4816702020-04-03 15:44:51 -07003300 dst3_2.rotation = mapToStreamRotation((camera_stream_rotation_t) src->rotation);
Shuzhen Wang92653952019-05-07 15:11:43 -07003301 // For HidlSession version 3.5 or newer, the format and dataSpace sent
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08003302 // to HAL are original, not the overridden ones.
Shuzhen Wang92653952019-05-07 15:11:43 -07003303 if (mHidlSession_3_5 != nullptr) {
3304 dst3_2.format = mapToPixelFormat(cam3stream->isFormatOverridden() ?
3305 cam3stream->getOriginalFormat() : src->format);
3306 dst3_2.dataSpace = mapToHidlDataspace(cam3stream->isDataSpaceOverridden() ?
3307 cam3stream->getOriginalDataSpace() : src->data_space);
3308 } else {
3309 dst3_2.format = mapToPixelFormat(src->format);
3310 dst3_2.dataSpace = mapToHidlDataspace(src->data_space);
3311 }
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003312 dst3_4.v3_2 = dst3_2;
Emilian Peev192ee832018-01-31 14:46:47 +00003313 dst3_4.bufferSize = bufferSizes[i];
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003314 if (src->physical_camera_id != nullptr) {
3315 dst3_4.physicalCameraId = src->physical_camera_id;
3316 }
Shuzhen Wang83bff122020-11-20 15:51:39 -08003317 dst3_7.v3_4 = dst3_4;
3318 dst3_7.groupId = cam3stream->getHalStreamGroupId();
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08003319 dst3_7.sensorPixelModesUsed.resize(src->sensor_pixel_modes_used.size());
3320 size_t j = 0;
3321 for (int mode : src->sensor_pixel_modes_used) {
3322 dst3_7.sensorPixelModesUsed[j++] =
3323 static_cast<CameraMetadataEnumAndroidSensorPixelMode>(mode);
3324 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003325 activeStreams.insert(streamId);
3326 // Create Buffer ID map if necessary
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003327 mBufferRecords.tryCreateBufferCache(streamId);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003328 }
3329 // remove BufferIdMap for deleted streams
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003330 mBufferRecords.removeInactiveBufferCaches(activeStreams);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003331
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003332 StreamConfigurationMode operationMode;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003333 res = mapToStreamConfigurationMode(
Emilian Peevf4816702020-04-03 15:44:51 -07003334 (camera_stream_configuration_mode_t) config->operation_mode,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003335 /*out*/ &operationMode);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003336 if (res != OK) {
3337 return res;
3338 }
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003339 requestedConfiguration3_2.operationMode = operationMode;
3340 requestedConfiguration3_4.operationMode = operationMode;
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08003341 requestedConfiguration3_7.operationMode = operationMode;
3342 size_t sessionParamSize = get_camera_metadata_size(sessionParams);
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003343 requestedConfiguration3_4.sessionParams.setToExternal(
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003344 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(sessionParams)),
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08003345 sessionParamSize);
Shuzhen Wang83bff122020-11-20 15:51:39 -08003346 requestedConfiguration3_7.operationMode = operationMode;
3347 requestedConfiguration3_7.sessionParams.setToExternal(
3348 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(sessionParams)),
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08003349 sessionParamSize);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003350
Emilian Peev31abd0a2017-05-11 18:37:46 +01003351 // Invoke configureStreams
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003352 device::V3_3::HalStreamConfiguration finalConfiguration;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003353 device::V3_4::HalStreamConfiguration finalConfiguration3_4;
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003354 device::V3_6::HalStreamConfiguration finalConfiguration3_6;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003355 common::V1_0::Status status;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003356
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003357 auto configStream34Cb = [&status, &finalConfiguration3_4]
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003358 (common::V1_0::Status s, const device::V3_4::HalStreamConfiguration& halConfiguration) {
3359 finalConfiguration3_4 = halConfiguration;
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003360 status = s;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003361 };
3362
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003363 auto configStream36Cb = [&status, &finalConfiguration3_6]
3364 (common::V1_0::Status s, const device::V3_6::HalStreamConfiguration& halConfiguration) {
3365 finalConfiguration3_6 = halConfiguration;
3366 status = s;
3367 };
3368
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003369 auto postprocConfigStream34 = [&finalConfiguration, &finalConfiguration3_4]
3370 (hardware::Return<void>& err) -> status_t {
3371 if (!err.isOk()) {
3372 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3373 return DEAD_OBJECT;
3374 }
3375 finalConfiguration.streams.resize(finalConfiguration3_4.streams.size());
3376 for (size_t i = 0; i < finalConfiguration3_4.streams.size(); i++) {
3377 finalConfiguration.streams[i] = finalConfiguration3_4.streams[i].v3_3;
3378 }
3379 return OK;
3380 };
3381
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003382 auto postprocConfigStream36 = [&finalConfiguration, &finalConfiguration3_6]
3383 (hardware::Return<void>& err) -> status_t {
3384 if (!err.isOk()) {
3385 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3386 return DEAD_OBJECT;
3387 }
3388 finalConfiguration.streams.resize(finalConfiguration3_6.streams.size());
3389 for (size_t i = 0; i < finalConfiguration3_6.streams.size(); i++) {
3390 finalConfiguration.streams[i] = finalConfiguration3_6.streams[i].v3_4.v3_3;
3391 }
3392 return OK;
3393 };
3394
Shuzhen Wang92653952019-05-07 15:11:43 -07003395 // See which version of HAL we have
Shuzhen Wang83bff122020-11-20 15:51:39 -08003396 if (mHidlSession_3_7 != nullptr) {
3397 ALOGV("%s: v3.7 device found", __FUNCTION__);
3398 requestedConfiguration3_7.streamConfigCounter = mNextStreamConfigCounter++;
3399 requestedConfiguration3_7.multiResolutionInputImage = config->input_is_multi_resolution;
3400 auto err = mHidlSession_3_7->configureStreams_3_7(
3401 requestedConfiguration3_7, configStream36Cb);
3402 res = postprocConfigStream36(err);
3403 if (res != OK) {
3404 return res;
3405 }
3406 } else if (mHidlSession_3_6 != nullptr) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003407 ALOGV("%s: v3.6 device found", __FUNCTION__);
3408 device::V3_5::StreamConfiguration requestedConfiguration3_5;
3409 requestedConfiguration3_5.v3_4 = requestedConfiguration3_4;
3410 requestedConfiguration3_5.streamConfigCounter = mNextStreamConfigCounter++;
3411 auto err = mHidlSession_3_6->configureStreams_3_6(
3412 requestedConfiguration3_5, configStream36Cb);
3413 res = postprocConfigStream36(err);
3414 if (res != OK) {
3415 return res;
3416 }
3417 } else if (mHidlSession_3_5 != nullptr) {
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003418 ALOGV("%s: v3.5 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_5->configureStreams_3_5(
3423 requestedConfiguration3_5, configStream34Cb);
3424 res = postprocConfigStream34(err);
3425 if (res != OK) {
3426 return res;
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003427 }
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003428 } else if (mHidlSession_3_4 != nullptr) {
3429 // We do; use v3.4 for the call
3430 ALOGV("%s: v3.4 device found", __FUNCTION__);
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003431 auto err = mHidlSession_3_4->configureStreams_3_4(
3432 requestedConfiguration3_4, configStream34Cb);
3433 res = postprocConfigStream34(err);
3434 if (res != OK) {
3435 return res;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003436 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003437 } else if (mHidlSession_3_3 != nullptr) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003438 // We do; use v3.3 for the call
3439 ALOGV("%s: v3.3 device found", __FUNCTION__);
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003440 auto err = mHidlSession_3_3->configureStreams_3_3(requestedConfiguration3_2,
Emilian Peev31abd0a2017-05-11 18:37:46 +01003441 [&status, &finalConfiguration]
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003442 (common::V1_0::Status s, const device::V3_3::HalStreamConfiguration& halConfiguration) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003443 finalConfiguration = halConfiguration;
3444 status = s;
3445 });
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003446 if (!err.isOk()) {
3447 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3448 return DEAD_OBJECT;
3449 }
3450 } else {
3451 // We don't; use v3.2 call and construct a v3.3 HalStreamConfiguration
3452 ALOGV("%s: v3.2 device found", __FUNCTION__);
3453 HalStreamConfiguration finalConfiguration_3_2;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003454 auto err = mHidlSession->configureStreams(requestedConfiguration3_2,
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003455 [&status, &finalConfiguration_3_2]
3456 (common::V1_0::Status s, const HalStreamConfiguration& halConfiguration) {
3457 finalConfiguration_3_2 = halConfiguration;
3458 status = s;
3459 });
3460 if (!err.isOk()) {
3461 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3462 return DEAD_OBJECT;
3463 }
3464 finalConfiguration.streams.resize(finalConfiguration_3_2.streams.size());
3465 for (size_t i = 0; i < finalConfiguration_3_2.streams.size(); i++) {
3466 finalConfiguration.streams[i].v3_2 = finalConfiguration_3_2.streams[i];
3467 finalConfiguration.streams[i].overrideDataSpace =
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003468 requestedConfiguration3_2.streams[i].dataSpace;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003469 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003470 }
3471
3472 if (status != common::V1_0::Status::OK ) {
3473 return CameraProviderManager::mapToStatusT(status);
3474 }
3475
3476 // And convert output stream configuration from HIDL
3477
3478 for (size_t i = 0; i < config->num_streams; i++) {
Emilian Peevf4816702020-04-03 15:44:51 -07003479 camera3::camera_stream_t *dst = config->streams[i];
Emilian Peev31abd0a2017-05-11 18:37:46 +01003480 int streamId = Camera3Stream::cast(dst)->getId();
3481
3482 // Start scan at i, with the assumption that the stream order matches
3483 size_t realIdx = i;
3484 bool found = false;
Eino-Ville Talvala370875f2019-04-12 12:40:27 -07003485 size_t halStreamCount = finalConfiguration.streams.size();
3486 for (size_t idx = 0; idx < halStreamCount; idx++) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003487 if (finalConfiguration.streams[realIdx].v3_2.id == streamId) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003488 found = true;
3489 break;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003490 }
Eino-Ville Talvala370875f2019-04-12 12:40:27 -07003491 realIdx = (realIdx >= halStreamCount - 1) ? 0 : realIdx + 1;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003492 }
3493 if (!found) {
3494 ALOGE("%s: Stream %d not found in stream configuration response from HAL",
3495 __FUNCTION__, streamId);
3496 return INVALID_OPERATION;
3497 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003498 device::V3_3::HalStream &src = finalConfiguration.streams[realIdx];
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003499 device::V3_6::HalStream &src_36 = finalConfiguration3_6.streams[realIdx];
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003500
Emilian Peev710c1422017-08-30 11:19:38 +01003501 Camera3Stream* dstStream = Camera3Stream::cast(dst);
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003502 int overrideFormat = mapToFrameworkFormat(src.v3_2.overrideFormat);
3503 android_dataspace overrideDataSpace = mapToFrameworkDataspace(src.overrideDataSpace);
3504
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003505 if (mHidlSession_3_6 != nullptr) {
3506 dstStream->setOfflineProcessingSupport(src_36.supportOffline);
3507 }
3508
Yin-Chia Yeh90667662019-07-01 15:45:00 -07003509 if (dstStream->getOriginalFormat() != HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
Shuzhen Wang92653952019-05-07 15:11:43 -07003510 dstStream->setFormatOverride(false);
3511 dstStream->setDataSpaceOverride(false);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003512 if (dst->format != overrideFormat) {
3513 ALOGE("%s: Stream %d: Format override not allowed for format 0x%x", __FUNCTION__,
3514 streamId, dst->format);
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003515 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003516 if (dst->data_space != overrideDataSpace) {
3517 ALOGE("%s: Stream %d: DataSpace override not allowed for format 0x%x", __FUNCTION__,
3518 streamId, dst->format);
3519 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003520 } else {
Shuzhen Wang92653952019-05-07 15:11:43 -07003521 bool needFormatOverride =
3522 requestedConfiguration3_2.streams[i].format != src.v3_2.overrideFormat;
3523 bool needDataspaceOverride =
3524 requestedConfiguration3_2.streams[i].dataSpace != src.overrideDataSpace;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003525 // Override allowed with IMPLEMENTATION_DEFINED
Shuzhen Wang92653952019-05-07 15:11:43 -07003526 dstStream->setFormatOverride(needFormatOverride);
3527 dstStream->setDataSpaceOverride(needDataspaceOverride);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003528 dst->format = overrideFormat;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003529 dst->data_space = overrideDataSpace;
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003530 }
3531
Emilian Peevf4816702020-04-03 15:44:51 -07003532 if (dst->stream_type == CAMERA_STREAM_INPUT) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003533 if (src.v3_2.producerUsage != 0) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003534 ALOGE("%s: Stream %d: INPUT streams must have 0 for producer usage",
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003535 __FUNCTION__, streamId);
3536 return INVALID_OPERATION;
3537 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003538 dstStream->setUsage(
3539 mapConsumerToFrameworkUsage(src.v3_2.consumerUsage));
Emilian Peev31abd0a2017-05-11 18:37:46 +01003540 } else {
3541 // OUTPUT
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003542 if (src.v3_2.consumerUsage != 0) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003543 ALOGE("%s: Stream %d: OUTPUT streams must have 0 for consumer usage",
3544 __FUNCTION__, streamId);
3545 return INVALID_OPERATION;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003546 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003547 dstStream->setUsage(
3548 mapProducerToFrameworkUsage(src.v3_2.producerUsage));
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003549 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003550 dst->max_buffers = src.v3_2.maxBuffers;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003551 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003552
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003553 return res;
3554}
3555
Cliff Wuc2ad9c82021-04-21 00:58:58 +08003556status_t Camera3Device::HalInterface::configureInjectedStreams(
3557 const camera_metadata_t* sessionParams, camera_stream_configuration* config,
3558 const std::vector<uint32_t>& bufferSizes,
3559 const CameraMetadata& cameraCharacteristics) {
3560 ATRACE_NAME("InjectionCameraHal::configureStreams");
3561 if (!valid()) return INVALID_OPERATION;
3562 status_t res = OK;
3563
3564 if (config->input_is_multi_resolution) {
3565 ALOGE("%s: Injection camera device doesn't support multi-resolution input "
3566 "stream", __FUNCTION__);
3567 return BAD_VALUE;
3568 }
3569
3570 // Convert stream config to HIDL
3571 std::set<int> activeStreams;
3572 device::V3_2::StreamConfiguration requestedConfiguration3_2;
3573 device::V3_4::StreamConfiguration requestedConfiguration3_4;
3574 device::V3_7::StreamConfiguration requestedConfiguration3_7;
3575 requestedConfiguration3_2.streams.resize(config->num_streams);
3576 requestedConfiguration3_4.streams.resize(config->num_streams);
3577 requestedConfiguration3_7.streams.resize(config->num_streams);
3578 for (size_t i = 0; i < config->num_streams; i++) {
3579 device::V3_2::Stream& dst3_2 = requestedConfiguration3_2.streams[i];
3580 device::V3_4::Stream& dst3_4 = requestedConfiguration3_4.streams[i];
3581 device::V3_7::Stream& dst3_7 = requestedConfiguration3_7.streams[i];
3582 camera3::camera_stream_t* src = config->streams[i];
3583
3584 Camera3Stream* cam3stream = Camera3Stream::cast(src);
3585 cam3stream->setBufferFreedListener(this);
3586 int streamId = cam3stream->getId();
3587 StreamType streamType;
3588 switch (src->stream_type) {
3589 case CAMERA_STREAM_OUTPUT:
3590 streamType = StreamType::OUTPUT;
3591 break;
3592 case CAMERA_STREAM_INPUT:
3593 streamType = StreamType::INPUT;
3594 break;
3595 default:
3596 ALOGE("%s: Stream %d: Unsupported stream type %d", __FUNCTION__,
3597 streamId, config->streams[i]->stream_type);
3598 return BAD_VALUE;
3599 }
3600 dst3_2.id = streamId;
3601 dst3_2.streamType = streamType;
3602 dst3_2.width = src->width;
3603 dst3_2.height = src->height;
3604 dst3_2.usage = mapToConsumerUsage(cam3stream->getUsage());
3605 dst3_2.rotation =
3606 mapToStreamRotation((camera_stream_rotation_t)src->rotation);
3607 // For HidlSession version 3.5 or newer, the format and dataSpace sent
3608 // to HAL are original, not the overridden ones.
3609 if (mHidlSession_3_5 != nullptr) {
3610 dst3_2.format = mapToPixelFormat(cam3stream->isFormatOverridden()
3611 ? cam3stream->getOriginalFormat()
3612 : src->format);
3613 dst3_2.dataSpace =
3614 mapToHidlDataspace(cam3stream->isDataSpaceOverridden()
3615 ? cam3stream->getOriginalDataSpace()
3616 : src->data_space);
3617 } else {
3618 dst3_2.format = mapToPixelFormat(src->format);
3619 dst3_2.dataSpace = mapToHidlDataspace(src->data_space);
3620 }
3621 dst3_4.v3_2 = dst3_2;
3622 dst3_4.bufferSize = bufferSizes[i];
3623 if (src->physical_camera_id != nullptr) {
3624 dst3_4.physicalCameraId = src->physical_camera_id;
3625 }
3626 dst3_7.v3_4 = dst3_4;
3627 dst3_7.groupId = cam3stream->getHalStreamGroupId();
3628 dst3_7.sensorPixelModesUsed.resize(src->sensor_pixel_modes_used.size());
3629 size_t j = 0;
3630 for (int mode : src->sensor_pixel_modes_used) {
3631 dst3_7.sensorPixelModesUsed[j++] =
3632 static_cast<CameraMetadataEnumAndroidSensorPixelMode>(mode);
3633 }
3634 activeStreams.insert(streamId);
3635 // Create Buffer ID map if necessary
3636 mBufferRecords.tryCreateBufferCache(streamId);
3637 }
3638 // remove BufferIdMap for deleted streams
3639 mBufferRecords.removeInactiveBufferCaches(activeStreams);
3640
3641 StreamConfigurationMode operationMode;
3642 res = mapToStreamConfigurationMode(
3643 (camera_stream_configuration_mode_t)config->operation_mode,
3644 /*out*/ &operationMode);
3645 if (res != OK) {
3646 return res;
3647 }
3648 requestedConfiguration3_7.operationMode = operationMode;
3649 size_t sessionParamSize = get_camera_metadata_size(sessionParams);
3650 requestedConfiguration3_7.operationMode = operationMode;
3651 requestedConfiguration3_7.sessionParams.setToExternal(
3652 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(sessionParams)),
3653 sessionParamSize);
3654
3655 // See which version of HAL we have
3656 if (mHidlSession_3_7 != nullptr) {
3657 requestedConfiguration3_7.streamConfigCounter = mNextStreamConfigCounter++;
3658 requestedConfiguration3_7.multiResolutionInputImage =
3659 config->input_is_multi_resolution;
3660
3661 const camera_metadata_t* rawMetadata = cameraCharacteristics.getAndLock();
3662 ::android::hardware::camera::device::V3_2::CameraMetadata hidlChars = {};
3663 hidlChars.setToExternal(
3664 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(rawMetadata)),
3665 get_camera_metadata_size(rawMetadata));
3666 cameraCharacteristics.unlock(rawMetadata);
3667
3668 sp<hardware::camera::device::V3_7::ICameraInjectionSession>
3669 hidlInjectionSession_3_7;
3670 auto castInjectionResult_3_7 =
3671 device::V3_7::ICameraInjectionSession::castFrom(mHidlSession_3_7);
3672 if (castInjectionResult_3_7.isOk()) {
3673 hidlInjectionSession_3_7 = castInjectionResult_3_7;
3674 } else {
3675 ALOGE("%s: Transaction error: %s", __FUNCTION__,
3676 castInjectionResult_3_7.description().c_str());
3677 return DEAD_OBJECT;
3678 }
3679
3680 auto err = hidlInjectionSession_3_7->configureInjectionStreams(
3681 requestedConfiguration3_7, hidlChars);
3682 if (!err.isOk()) {
3683 ALOGE("%s: Transaction error: %s", __FUNCTION__,
3684 err.description().c_str());
3685 return DEAD_OBJECT;
3686 }
3687 } else {
3688 ALOGE("%s: mHidlSession_3_7 does not exist, the lowest version of injection "
3689 "session is 3.7", __FUNCTION__);
3690 return DEAD_OBJECT;
3691 }
3692
3693 return res;
3694}
3695
Emilian Peevf4816702020-04-03 15:44:51 -07003696status_t Camera3Device::HalInterface::wrapAsHidlRequest(camera_capture_request_t* request,
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003697 /*out*/device::V3_2::CaptureRequest* captureRequest,
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003698 /*out*/std::vector<native_handle_t*>* handlesCreated,
3699 /*out*/std::vector<std::pair<int32_t, int32_t>>* inflightBuffers) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003700 ATRACE_CALL();
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003701 if (captureRequest == nullptr || handlesCreated == nullptr || inflightBuffers == nullptr) {
3702 ALOGE("%s: captureRequest (%p), handlesCreated (%p), and inflightBuffers(%p) "
3703 "must not be null", __FUNCTION__, captureRequest, handlesCreated, inflightBuffers);
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003704 return BAD_VALUE;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003705 }
3706
3707 captureRequest->frameNumber = request->frame_number;
Yifan Hongf79b5542017-04-11 14:44:25 -07003708
3709 captureRequest->fmqSettingsSize = 0;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003710
3711 {
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003712 if (request->input_buffer != nullptr) {
3713 int32_t streamId = Camera3Stream::cast(request->input_buffer->stream)->getId();
3714 buffer_handle_t buf = *(request->input_buffer->buffer);
3715 auto pair = getBufferId(buf, streamId);
3716 bool isNewBuffer = pair.first;
3717 uint64_t bufferId = pair.second;
3718 captureRequest->inputBuffer.streamId = streamId;
3719 captureRequest->inputBuffer.bufferId = bufferId;
3720 captureRequest->inputBuffer.buffer = (isNewBuffer) ? buf : nullptr;
3721 captureRequest->inputBuffer.status = BufferStatus::OK;
3722 native_handle_t *acquireFence = nullptr;
3723 if (request->input_buffer->acquire_fence != -1) {
3724 acquireFence = native_handle_create(1,0);
3725 acquireFence->data[0] = request->input_buffer->acquire_fence;
3726 handlesCreated->push_back(acquireFence);
3727 }
3728 captureRequest->inputBuffer.acquireFence = acquireFence;
3729 captureRequest->inputBuffer.releaseFence = nullptr;
3730
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003731 mBufferRecords.pushInflightBuffer(captureRequest->frameNumber, streamId,
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003732 request->input_buffer->buffer);
3733 inflightBuffers->push_back(std::make_pair(captureRequest->frameNumber, streamId));
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003734 } else {
3735 captureRequest->inputBuffer.streamId = -1;
3736 captureRequest->inputBuffer.bufferId = BUFFER_ID_NO_BUFFER;
3737 }
3738
3739 captureRequest->outputBuffers.resize(request->num_output_buffers);
3740 for (size_t i = 0; i < request->num_output_buffers; i++) {
Emilian Peevf4816702020-04-03 15:44:51 -07003741 const camera_stream_buffer_t *src = request->output_buffers + i;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003742 StreamBuffer &dst = captureRequest->outputBuffers[i];
3743 int32_t streamId = Camera3Stream::cast(src->stream)->getId();
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003744 if (src->buffer != nullptr) {
3745 buffer_handle_t buf = *(src->buffer);
3746 auto pair = getBufferId(buf, streamId);
3747 bool isNewBuffer = pair.first;
3748 dst.bufferId = pair.second;
3749 dst.buffer = isNewBuffer ? buf : nullptr;
3750 native_handle_t *acquireFence = nullptr;
3751 if (src->acquire_fence != -1) {
3752 acquireFence = native_handle_create(1,0);
3753 acquireFence->data[0] = src->acquire_fence;
3754 handlesCreated->push_back(acquireFence);
3755 }
3756 dst.acquireFence = acquireFence;
3757 } else if (mUseHalBufManager) {
3758 // HAL buffer management path
3759 dst.bufferId = BUFFER_ID_NO_BUFFER;
3760 dst.buffer = nullptr;
3761 dst.acquireFence = nullptr;
3762 } else {
3763 ALOGE("%s: cannot send a null buffer in capture request!", __FUNCTION__);
3764 return BAD_VALUE;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003765 }
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003766 dst.streamId = streamId;
3767 dst.status = BufferStatus::OK;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003768 dst.releaseFence = nullptr;
3769
Yin-Chia Yeh5f840f82019-03-05 11:59:04 -08003770 // Output buffers are empty when using HAL buffer manager
3771 if (!mUseHalBufManager) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003772 mBufferRecords.pushInflightBuffer(
3773 captureRequest->frameNumber, streamId, src->buffer);
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003774 inflightBuffers->push_back(std::make_pair(captureRequest->frameNumber, streamId));
Yin-Chia Yeh5f840f82019-03-05 11:59:04 -08003775 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003776 }
3777 }
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003778 return OK;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003779}
3780
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003781void Camera3Device::HalInterface::cleanupNativeHandles(
3782 std::vector<native_handle_t*> *handles, bool closeFd) {
3783 if (handles == nullptr) {
3784 return;
3785 }
3786 if (closeFd) {
3787 for (auto& handle : *handles) {
3788 native_handle_close(handle);
3789 }
3790 }
3791 for (auto& handle : *handles) {
3792 native_handle_delete(handle);
3793 }
3794 handles->clear();
3795 return;
3796}
3797
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003798status_t Camera3Device::HalInterface::processBatchCaptureRequests(
Emilian Peevf4816702020-04-03 15:44:51 -07003799 std::vector<camera_capture_request_t*>& requests,/*out*/uint32_t* numRequestProcessed) {
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003800 ATRACE_NAME("CameraHal::processBatchCaptureRequests");
3801 if (!valid()) return INVALID_OPERATION;
3802
Emilian Peevaebbe412018-01-15 13:53:24 +00003803 sp<device::V3_4::ICameraDeviceSession> hidlSession_3_4;
Shuzhen Wang83bff122020-11-20 15:51:39 -08003804 sp<device::V3_7::ICameraDeviceSession> hidlSession_3_7;
3805 auto castResult_3_7 = device::V3_7::ICameraDeviceSession::castFrom(mHidlSession);
3806 if (castResult_3_7.isOk()) {
3807 hidlSession_3_7 = castResult_3_7;
3808 }
Emilian Peevaebbe412018-01-15 13:53:24 +00003809 auto castResult_3_4 = device::V3_4::ICameraDeviceSession::castFrom(mHidlSession);
3810 if (castResult_3_4.isOk()) {
3811 hidlSession_3_4 = castResult_3_4;
3812 }
3813
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003814 hardware::hidl_vec<device::V3_2::CaptureRequest> captureRequests;
Emilian Peevaebbe412018-01-15 13:53:24 +00003815 hardware::hidl_vec<device::V3_4::CaptureRequest> captureRequests_3_4;
Shuzhen Wang83bff122020-11-20 15:51:39 -08003816 hardware::hidl_vec<device::V3_7::CaptureRequest> captureRequests_3_7;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003817 size_t batchSize = requests.size();
Shuzhen Wang83bff122020-11-20 15:51:39 -08003818 if (hidlSession_3_7 != nullptr) {
3819 captureRequests_3_7.resize(batchSize);
3820 } else if (hidlSession_3_4 != nullptr) {
Emilian Peevaebbe412018-01-15 13:53:24 +00003821 captureRequests_3_4.resize(batchSize);
3822 } else {
3823 captureRequests.resize(batchSize);
3824 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003825 std::vector<native_handle_t*> handlesCreated;
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003826 std::vector<std::pair<int32_t, int32_t>> inflightBuffers;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003827
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003828 status_t res = OK;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003829 for (size_t i = 0; i < batchSize; i++) {
Shuzhen Wang83bff122020-11-20 15:51:39 -08003830 if (hidlSession_3_7 != nullptr) {
3831 res = wrapAsHidlRequest(requests[i], /*out*/&captureRequests_3_7[i].v3_4.v3_2,
3832 /*out*/&handlesCreated, /*out*/&inflightBuffers);
3833 } else if (hidlSession_3_4 != nullptr) {
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003834 res = wrapAsHidlRequest(requests[i], /*out*/&captureRequests_3_4[i].v3_2,
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003835 /*out*/&handlesCreated, /*out*/&inflightBuffers);
Emilian Peevaebbe412018-01-15 13:53:24 +00003836 } else {
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003837 res = wrapAsHidlRequest(requests[i], /*out*/&captureRequests[i],
3838 /*out*/&handlesCreated, /*out*/&inflightBuffers);
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003839 }
3840 if (res != OK) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003841 mBufferRecords.popInflightBuffers(inflightBuffers);
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003842 cleanupNativeHandles(&handlesCreated);
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003843 return res;
Emilian Peevaebbe412018-01-15 13:53:24 +00003844 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003845 }
3846
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003847 std::vector<device::V3_2::BufferCache> cachesToRemove;
3848 {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003849 std::lock_guard<std::mutex> lock(mFreedBuffersLock);
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003850 for (auto& pair : mFreedBuffers) {
3851 // The stream might have been removed since onBufferFreed
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003852 if (mBufferRecords.isStreamCached(pair.first)) {
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003853 cachesToRemove.push_back({pair.first, pair.second});
3854 }
3855 }
3856 mFreedBuffers.clear();
3857 }
3858
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003859 common::V1_0::Status status = common::V1_0::Status::INTERNAL_ERROR;
3860 *numRequestProcessed = 0;
Yifan Hongf79b5542017-04-11 14:44:25 -07003861
3862 // Write metadata to FMQ.
3863 for (size_t i = 0; i < batchSize; i++) {
Emilian Peevf4816702020-04-03 15:44:51 -07003864 camera_capture_request_t* request = requests[i];
Emilian Peevaebbe412018-01-15 13:53:24 +00003865 device::V3_2::CaptureRequest* captureRequest;
Shuzhen Wang83bff122020-11-20 15:51:39 -08003866 if (hidlSession_3_7 != nullptr) {
3867 captureRequest = &captureRequests_3_7[i].v3_4.v3_2;
3868 } else if (hidlSession_3_4 != nullptr) {
Emilian Peevaebbe412018-01-15 13:53:24 +00003869 captureRequest = &captureRequests_3_4[i].v3_2;
3870 } else {
3871 captureRequest = &captureRequests[i];
3872 }
Yifan Hongf79b5542017-04-11 14:44:25 -07003873
3874 if (request->settings != nullptr) {
3875 size_t settingsSize = get_camera_metadata_size(request->settings);
3876 if (mRequestMetadataQueue != nullptr && mRequestMetadataQueue->write(
3877 reinterpret_cast<const uint8_t*>(request->settings), settingsSize)) {
3878 captureRequest->settings.resize(0);
3879 captureRequest->fmqSettingsSize = settingsSize;
3880 } else {
3881 if (mRequestMetadataQueue != nullptr) {
3882 ALOGW("%s: couldn't utilize fmq, fallback to hwbinder", __FUNCTION__);
3883 }
3884 captureRequest->settings.setToExternal(
3885 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(request->settings)),
3886 get_camera_metadata_size(request->settings));
3887 captureRequest->fmqSettingsSize = 0u;
3888 }
3889 } else {
3890 // A null request settings maps to a size-0 CameraMetadata
3891 captureRequest->settings.resize(0);
3892 captureRequest->fmqSettingsSize = 0u;
3893 }
Emilian Peevaebbe412018-01-15 13:53:24 +00003894
Shuzhen Wang83bff122020-11-20 15:51:39 -08003895 // hidl session 3.7 specific handling.
3896 if (hidlSession_3_7 != nullptr) {
3897 captureRequests_3_7[i].inputWidth = request->input_width;
3898 captureRequests_3_7[i].inputHeight = request->input_height;
3899 }
3900
3901 // hidl session 3.7 and 3.4 specific handling.
3902 if (hidlSession_3_7 != nullptr || hidlSession_3_4 != nullptr) {
3903 hardware::hidl_vec<device::V3_4::PhysicalCameraSetting>& physicalCameraSettings =
3904 (hidlSession_3_7 != nullptr) ?
3905 captureRequests_3_7[i].v3_4.physicalCameraSettings :
3906 captureRequests_3_4[i].physicalCameraSettings;
3907 physicalCameraSettings.resize(request->num_physcam_settings);
Emilian Peevaebbe412018-01-15 13:53:24 +00003908 for (size_t j = 0; j < request->num_physcam_settings; j++) {
Emilian Peev00420d22018-02-05 21:33:13 +00003909 if (request->physcam_settings != nullptr) {
3910 size_t settingsSize = get_camera_metadata_size(request->physcam_settings[j]);
3911 if (mRequestMetadataQueue != nullptr && mRequestMetadataQueue->write(
3912 reinterpret_cast<const uint8_t*>(request->physcam_settings[j]),
3913 settingsSize)) {
Shuzhen Wang83bff122020-11-20 15:51:39 -08003914 physicalCameraSettings[j].settings.resize(0);
3915 physicalCameraSettings[j].fmqSettingsSize = settingsSize;
Emilian Peev00420d22018-02-05 21:33:13 +00003916 } else {
3917 if (mRequestMetadataQueue != nullptr) {
3918 ALOGW("%s: couldn't utilize fmq, fallback to hwbinder", __FUNCTION__);
3919 }
Shuzhen Wang83bff122020-11-20 15:51:39 -08003920 physicalCameraSettings[j].settings.setToExternal(
Emilian Peev00420d22018-02-05 21:33:13 +00003921 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(
3922 request->physcam_settings[j])),
3923 get_camera_metadata_size(request->physcam_settings[j]));
Shuzhen Wang83bff122020-11-20 15:51:39 -08003924 physicalCameraSettings[j].fmqSettingsSize = 0u;
Emilian Peevaebbe412018-01-15 13:53:24 +00003925 }
Emilian Peev00420d22018-02-05 21:33:13 +00003926 } else {
Yin-Chia Yeha2849702021-03-10 10:11:33 -08003927 physicalCameraSettings[j].fmqSettingsSize = 0u;
3928 physicalCameraSettings[j].settings.resize(0);
Emilian Peevaebbe412018-01-15 13:53:24 +00003929 }
Shuzhen Wang83bff122020-11-20 15:51:39 -08003930 physicalCameraSettings[j].physicalCameraId = request->physcam_id[j];
Emilian Peevaebbe412018-01-15 13:53:24 +00003931 }
3932 }
Yifan Hongf79b5542017-04-11 14:44:25 -07003933 }
Emilian Peevaebbe412018-01-15 13:53:24 +00003934
3935 hardware::details::return_status err;
Jayant Chowdharyc8d581e2018-07-16 14:46:23 -07003936 auto resultCallback =
3937 [&status, &numRequestProcessed] (auto s, uint32_t n) {
3938 status = s;
3939 *numRequestProcessed = n;
3940 };
Shuzhen Wang83bff122020-11-20 15:51:39 -08003941 if (hidlSession_3_7 != nullptr) {
3942 err = hidlSession_3_7->processCaptureRequest_3_7(captureRequests_3_7, cachesToRemove,
3943 resultCallback);
3944 } else if (hidlSession_3_4 != nullptr) {
Emilian Peevaebbe412018-01-15 13:53:24 +00003945 err = hidlSession_3_4->processCaptureRequest_3_4(captureRequests_3_4, cachesToRemove,
Jayant Chowdharyc8d581e2018-07-16 14:46:23 -07003946 resultCallback);
Emilian Peevaebbe412018-01-15 13:53:24 +00003947 } else {
3948 err = mHidlSession->processCaptureRequest(captureRequests, cachesToRemove,
Jayant Chowdharyc8d581e2018-07-16 14:46:23 -07003949 resultCallback);
Emilian Peevaebbe412018-01-15 13:53:24 +00003950 }
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -07003951 if (!err.isOk()) {
3952 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003953 status = common::V1_0::Status::CAMERA_DISCONNECTED;
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -07003954 }
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003955
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003956 if (status == common::V1_0::Status::OK && *numRequestProcessed != batchSize) {
3957 ALOGE("%s: processCaptureRequest returns OK but processed %d/%zu requests",
3958 __FUNCTION__, *numRequestProcessed, batchSize);
3959 status = common::V1_0::Status::INTERNAL_ERROR;
3960 }
3961
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003962 res = CameraProviderManager::mapToStatusT(status);
3963 if (res == OK) {
3964 if (mHidlSession->isRemote()) {
3965 // Only close acquire fence FDs when the HIDL transaction succeeds (so the FDs have been
3966 // sent to camera HAL processes)
3967 cleanupNativeHandles(&handlesCreated, /*closeFd*/true);
3968 } else {
3969 // In passthrough mode the FDs are now owned by HAL
3970 cleanupNativeHandles(&handlesCreated);
3971 }
3972 } else {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003973 mBufferRecords.popInflightBuffers(inflightBuffers);
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003974 cleanupNativeHandles(&handlesCreated);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003975 }
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003976 return res;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003977}
3978
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003979status_t Camera3Device::HalInterface::flush() {
3980 ATRACE_NAME("CameraHal::flush");
3981 if (!valid()) return INVALID_OPERATION;
3982 status_t res = OK;
3983
Emilian Peev31abd0a2017-05-11 18:37:46 +01003984 auto err = mHidlSession->flush();
3985 if (!err.isOk()) {
3986 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3987 res = DEAD_OBJECT;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003988 } else {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003989 res = CameraProviderManager::mapToStatusT(err);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003990 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003991
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003992 return res;
3993}
3994
Emilian Peev31abd0a2017-05-11 18:37:46 +01003995status_t Camera3Device::HalInterface::dump(int /*fd*/) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003996 ATRACE_NAME("CameraHal::dump");
3997 if (!valid()) return INVALID_OPERATION;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003998
Emilian Peev31abd0a2017-05-11 18:37:46 +01003999 // Handled by CameraProviderManager::dump
4000
4001 return OK;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004002}
4003
4004status_t Camera3Device::HalInterface::close() {
4005 ATRACE_NAME("CameraHal::close()");
4006 if (!valid()) return INVALID_OPERATION;
4007 status_t res = OK;
4008
Emilian Peev31abd0a2017-05-11 18:37:46 +01004009 auto err = mHidlSession->close();
4010 // Interface will be dead shortly anyway, so don't log errors
4011 if (!err.isOk()) {
4012 res = DEAD_OBJECT;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004013 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01004014
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004015 return res;
4016}
4017
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004018void Camera3Device::HalInterface::signalPipelineDrain(const std::vector<int>& streamIds) {
4019 ATRACE_NAME("CameraHal::signalPipelineDrain");
4020 if (!valid() || mHidlSession_3_5 == nullptr) {
4021 ALOGE("%s called on invalid camera!", __FUNCTION__);
4022 return;
4023 }
4024
Yin-Chia Yehc300a072019-02-13 14:56:57 -08004025 auto err = mHidlSession_3_5->signalStreamFlush(streamIds, mNextStreamConfigCounter - 1);
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004026 if (!err.isOk()) {
4027 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
4028 return;
4029 }
4030}
4031
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004032status_t Camera3Device::HalInterface::switchToOffline(
4033 const std::vector<int32_t>& streamsToKeep,
4034 /*out*/hardware::camera::device::V3_6::CameraOfflineSessionInfo* offlineSessionInfo,
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004035 /*out*/sp<hardware::camera::device::V3_6::ICameraOfflineSession>* offlineSession,
4036 /*out*/camera3::BufferRecords* bufferRecords) {
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004037 ATRACE_NAME("CameraHal::switchToOffline");
4038 if (!valid() || mHidlSession_3_6 == nullptr) {
4039 ALOGE("%s called on invalid camera!", __FUNCTION__);
4040 return INVALID_OPERATION;
4041 }
4042
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004043 if (offlineSessionInfo == nullptr || offlineSession == nullptr || bufferRecords == nullptr) {
4044 ALOGE("%s: output arguments must not be null!", __FUNCTION__);
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004045 return INVALID_OPERATION;
4046 }
4047
4048 common::V1_0::Status status = common::V1_0::Status::INTERNAL_ERROR;
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004049 auto resultCallback =
4050 [&status, &offlineSessionInfo, &offlineSession] (auto s, auto info, auto session) {
4051 status = s;
4052 *offlineSessionInfo = info;
4053 *offlineSession = session;
4054 };
4055 auto err = mHidlSession_3_6->switchToOffline(streamsToKeep, resultCallback);
4056
4057 if (!err.isOk()) {
4058 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
4059 return DEAD_OBJECT;
4060 }
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004061
4062 status_t ret = CameraProviderManager::mapToStatusT(status);
4063 if (ret != OK) {
4064 return ret;
4065 }
4066
4067 // TODO: assert no ongoing requestBuffer/returnBuffer call here
4068 // TODO: update RequestBufferStateMachine to block requestBuffer/returnBuffer once HAL
4069 // returns from switchToOffline.
4070
4071
4072 // Validate buffer caches
4073 std::vector<int32_t> streams;
4074 streams.reserve(offlineSessionInfo->offlineStreams.size());
4075 for (auto offlineStream : offlineSessionInfo->offlineStreams) {
4076 int32_t id = offlineStream.id;
4077 streams.push_back(id);
4078 // Verify buffer caches
4079 std::vector<uint64_t> bufIds(offlineStream.circulatingBufferIds.begin(),
4080 offlineStream.circulatingBufferIds.end());
4081 if (!verifyBufferIds(id, bufIds)) {
4082 ALOGE("%s: stream ID %d buffer cache records mismatch!", __FUNCTION__, id);
4083 return UNKNOWN_ERROR;
4084 }
4085 }
4086
4087 // Move buffer records
4088 bufferRecords->takeBufferCaches(mBufferRecords, streams);
4089 bufferRecords->takeInflightBufferMap(mBufferRecords);
4090 bufferRecords->takeRequestedBufferMap(mBufferRecords);
4091 return ret;
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004092}
4093
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07004094void Camera3Device::HalInterface::getInflightBufferKeys(
4095 std::vector<std::pair<int32_t, int32_t>>* out) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004096 mBufferRecords.getInflightBufferKeys(out);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07004097 return;
4098}
4099
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08004100void Camera3Device::HalInterface::getInflightRequestBufferKeys(
4101 std::vector<uint64_t>* out) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004102 mBufferRecords.getInflightRequestBufferKeys(out);
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08004103 return;
4104}
4105
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004106bool Camera3Device::HalInterface::verifyBufferIds(
4107 int32_t streamId, std::vector<uint64_t>& bufIds) {
4108 return mBufferRecords.verifyBufferIds(streamId, bufIds);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004109}
4110
4111status_t Camera3Device::HalInterface::popInflightBuffer(
Yin-Chia Yehf4650602017-01-10 13:13:39 -08004112 int32_t frameNumber, int32_t streamId,
4113 /*out*/ buffer_handle_t **buffer) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004114 return mBufferRecords.popInflightBuffer(frameNumber, streamId, buffer);
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07004115}
4116
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004117status_t Camera3Device::HalInterface::pushInflightRequestBuffer(
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08004118 uint64_t bufferId, buffer_handle_t* buf, int32_t streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004119 return mBufferRecords.pushInflightRequestBuffer(bufferId, buf, streamId);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004120}
4121
4122// Find and pop a buffer_handle_t based on bufferId
4123status_t Camera3Device::HalInterface::popInflightRequestBuffer(
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08004124 uint64_t bufferId,
4125 /*out*/ buffer_handle_t** buffer,
4126 /*optional out*/ int32_t* streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004127 return mBufferRecords.popInflightRequestBuffer(bufferId, buffer, streamId);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004128}
4129
Yin-Chia Yeh77327052017-01-09 18:23:07 -08004130std::pair<bool, uint64_t> Camera3Device::HalInterface::getBufferId(
4131 const buffer_handle_t& buf, int streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004132 return mBufferRecords.getBufferId(buf, streamId);
Yin-Chia Yeh77327052017-01-09 18:23:07 -08004133}
4134
Shuzhen Wangcd5b1822021-09-07 11:52:48 -07004135uint64_t Camera3Device::HalInterface::removeOneBufferCache(int streamId,
4136 const native_handle_t* handle) {
4137 return mBufferRecords.removeOneBufferCache(streamId, handle);
4138}
4139
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07004140void Camera3Device::HalInterface::onBufferFreed(
4141 int streamId, const native_handle_t* handle) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004142 uint32_t bufferId = mBufferRecords.removeOneBufferCache(streamId, handle);
4143 std::lock_guard<std::mutex> lock(mFreedBuffersLock);
4144 if (bufferId != BUFFER_ID_NO_BUFFER) {
4145 mFreedBuffers.push_back(std::make_pair(streamId, bufferId));
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07004146 }
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07004147}
4148
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07004149void Camera3Device::HalInterface::onStreamReConfigured(int streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004150 std::vector<uint64_t> bufIds = mBufferRecords.clearBufferCaches(streamId);
4151 std::lock_guard<std::mutex> lock(mFreedBuffersLock);
4152 for (auto bufferId : bufIds) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07004153 mFreedBuffers.push_back(std::make_pair(streamId, bufferId));
4154 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07004155}
4156
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004157/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004158 * RequestThread inner class methods
4159 */
4160
4161Camera3Device::RequestThread::RequestThread(wp<Camera3Device> parent,
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004162 sp<StatusTracker> statusTracker,
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004163 sp<HalInterface> interface, const Vector<int32_t>& sessionParamKeys,
Eino-Ville Talvala1646c3c2021-07-29 13:48:40 -07004164 bool useHalBufManager,
4165 bool supportCameraMute) :
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004166 Thread(/*canCallJava*/false),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004167 mParent(parent),
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004168 mStatusTracker(statusTracker),
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004169 mInterface(interface),
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07004170 mListener(nullptr),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004171 mId(getId(parent)),
Shuzhen Wang316781a2020-08-18 18:11:01 -07004172 mFirstRepeating(false),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004173 mReconfigured(false),
4174 mDoPause(false),
4175 mPaused(true),
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004176 mNotifyPipelineDrain(false),
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004177 mFrameNumber(0),
Jianing Weicb0652e2014-03-12 18:29:36 -07004178 mLatestRequestId(NAME_NOT_FOUND),
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07004179 mCurrentAfTriggerId(0),
4180 mCurrentPreCaptureTriggerId(0),
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004181 mRotateAndCropOverride(ANDROID_SCALER_ROTATE_AND_CROP_NONE),
Eino-Ville Talvala11afe4f2021-05-27 14:45:31 -07004182 mCameraMute(ANDROID_SENSOR_TEST_PATTERN_MODE_OFF),
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004183 mCameraMuteChanged(false),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004184 mRepeatingLastFrameNumber(
4185 hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES),
Shuzhen Wang686f6442017-06-20 16:16:04 -07004186 mPrepareVideoStream(false),
Emilian Peeva14b4dd2018-05-15 11:00:31 +01004187 mConstrainedMode(false),
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004188 mRequestLatency(kRequestLatencyBinSize),
4189 mSessionParamKeys(sessionParamKeys),
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004190 mLatestSessionParams(sessionParamKeys.size()),
Eino-Ville Talvala1646c3c2021-07-29 13:48:40 -07004191 mUseHalBufManager(useHalBufManager),
4192 mSupportCameraMute(supportCameraMute){
Yin-Chia Yeh87b3ec02019-06-03 10:44:39 -07004193 mStatusId = statusTracker->addComponent("RequestThread");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004194}
4195
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004196Camera3Device::RequestThread::~RequestThread() {}
4197
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004198void Camera3Device::RequestThread::setNotificationListener(
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004199 wp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004200 ATRACE_CALL();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004201 Mutex::Autolock l(mRequestLock);
4202 mListener = listener;
4203}
4204
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004205void Camera3Device::RequestThread::configurationComplete(bool isConstrainedHighSpeed,
Shuzhen Wang99080502021-03-07 21:08:20 -08004206 const CameraMetadata& sessionParams,
4207 const std::map<int32_t, std::set<String8>>& groupIdPhysicalCameraMap) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004208 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004209 Mutex::Autolock l(mRequestLock);
4210 mReconfigured = true;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004211 mLatestSessionParams = sessionParams;
Shuzhen Wang99080502021-03-07 21:08:20 -08004212 mGroupIdPhysicalCameraMap = groupIdPhysicalCameraMap;
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07004213 // Prepare video stream for high speed recording.
4214 mPrepareVideoStream = isConstrainedHighSpeed;
Emilian Peeva14b4dd2018-05-15 11:00:31 +01004215 mConstrainedMode = isConstrainedHighSpeed;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004216}
4217
Jianing Wei90e59c92014-03-12 18:29:36 -07004218status_t Camera3Device::RequestThread::queueRequestList(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004219 List<sp<CaptureRequest> > &requests,
4220 /*out*/
4221 int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004222 ATRACE_CALL();
Jianing Wei90e59c92014-03-12 18:29:36 -07004223 Mutex::Autolock l(mRequestLock);
4224 for (List<sp<CaptureRequest> >::iterator it = requests.begin(); it != requests.end();
4225 ++it) {
4226 mRequestQueue.push_back(*it);
4227 }
4228
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004229 if (lastFrameNumber != NULL) {
4230 *lastFrameNumber = mFrameNumber + mRequestQueue.size() - 1;
4231 ALOGV("%s: requestId %d, mFrameNumber %" PRId32 ", lastFrameNumber %" PRId64 ".",
4232 __FUNCTION__, (*(requests.begin()))->mResultExtras.requestId, mFrameNumber,
4233 *lastFrameNumber);
4234 }
Jianing Weicb0652e2014-03-12 18:29:36 -07004235
Jianing Wei90e59c92014-03-12 18:29:36 -07004236 unpauseForNewRequests();
4237
4238 return OK;
4239}
4240
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004241
4242status_t Camera3Device::RequestThread::queueTrigger(
4243 RequestTrigger trigger[],
4244 size_t count) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004245 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004246 Mutex::Autolock l(mTriggerMutex);
4247 status_t ret;
4248
4249 for (size_t i = 0; i < count; ++i) {
4250 ret = queueTriggerLocked(trigger[i]);
4251
4252 if (ret != OK) {
4253 return ret;
4254 }
4255 }
4256
4257 return OK;
4258}
4259
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004260const String8& Camera3Device::RequestThread::getId(const wp<Camera3Device> &device) {
4261 static String8 deadId("<DeadDevice>");
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004262 sp<Camera3Device> d = device.promote();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004263 if (d != nullptr) return d->mId;
4264 return deadId;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004265}
4266
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004267status_t Camera3Device::RequestThread::queueTriggerLocked(
4268 RequestTrigger trigger) {
4269
4270 uint32_t tag = trigger.metadataTag;
4271 ssize_t index = mTriggerMap.indexOfKey(tag);
4272
4273 switch (trigger.getTagType()) {
4274 case TYPE_BYTE:
4275 // fall-through
4276 case TYPE_INT32:
4277 break;
4278 default:
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004279 ALOGE("%s: Type not supported: 0x%x", __FUNCTION__,
4280 trigger.getTagType());
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004281 return INVALID_OPERATION;
4282 }
4283
4284 /**
4285 * Collect only the latest trigger, since we only have 1 field
4286 * in the request settings per trigger tag, and can't send more than 1
4287 * trigger per request.
4288 */
4289 if (index != NAME_NOT_FOUND) {
4290 mTriggerMap.editValueAt(index) = trigger;
4291 } else {
4292 mTriggerMap.add(tag, trigger);
4293 }
4294
4295 return OK;
4296}
4297
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004298status_t Camera3Device::RequestThread::setRepeatingRequests(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004299 const RequestList &requests,
4300 /*out*/
4301 int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004302 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004303 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004304 if (lastFrameNumber != NULL) {
4305 *lastFrameNumber = mRepeatingLastFrameNumber;
4306 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004307 mRepeatingRequests.clear();
Shuzhen Wang316781a2020-08-18 18:11:01 -07004308 mFirstRepeating = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004309 mRepeatingRequests.insert(mRepeatingRequests.begin(),
4310 requests.begin(), requests.end());
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004311
4312 unpauseForNewRequests();
4313
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004314 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004315 return OK;
4316}
4317
Chih-Hung Hsieh8b0b9712016-08-09 14:25:53 -07004318bool Camera3Device::RequestThread::isRepeatingRequestLocked(const sp<CaptureRequest>& requestIn) {
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07004319 if (mRepeatingRequests.empty()) {
4320 return false;
4321 }
4322 int32_t requestId = requestIn->mResultExtras.requestId;
4323 const RequestList &repeatRequests = mRepeatingRequests;
4324 // All repeating requests are guaranteed to have same id so only check first quest
4325 const sp<CaptureRequest> firstRequest = *repeatRequests.begin();
4326 return (firstRequest->mResultExtras.requestId == requestId);
4327}
4328
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004329status_t Camera3Device::RequestThread::clearRepeatingRequests(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004330 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004331 Mutex::Autolock l(mRequestLock);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004332 return clearRepeatingRequestsLocked(lastFrameNumber);
4333
4334}
4335
4336status_t Camera3Device::RequestThread::clearRepeatingRequestsLocked(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004337 mRepeatingRequests.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004338 if (lastFrameNumber != NULL) {
4339 *lastFrameNumber = mRepeatingLastFrameNumber;
4340 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004341 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004342 return OK;
4343}
4344
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004345status_t Camera3Device::RequestThread::clear(
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004346 /*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004347 ATRACE_CALL();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004348 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004349 ALOGV("RequestThread::%s:", __FUNCTION__);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004350
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004351 mRepeatingRequests.clear();
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07004352
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004353 // Send errors for all requests pending in the request queue, including
4354 // pending repeating requests
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004355 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004356 if (listener != NULL) {
4357 for (RequestList::iterator it = mRequestQueue.begin();
4358 it != mRequestQueue.end(); ++it) {
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004359 // Abort the input buffers for reprocess requests.
4360 if ((*it)->mInputStream != NULL) {
Emilian Peevf4816702020-04-03 15:44:51 -07004361 camera_stream_buffer_t inputBuffer;
Shuzhen Wang83bff122020-11-20 15:51:39 -08004362 camera3::Size inputBufferSize;
Eino-Ville Talvalaba435252017-06-21 16:07:25 -07004363 status_t res = (*it)->mInputStream->getInputBuffer(&inputBuffer,
Shuzhen Wang83bff122020-11-20 15:51:39 -08004364 &inputBufferSize, /*respectHalLimit*/ false);
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004365 if (res != OK) {
4366 ALOGW("%s: %d: couldn't get input buffer while clearing the request "
4367 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
4368 } else {
Emilian Peevf4816702020-04-03 15:44:51 -07004369 inputBuffer.status = CAMERA_BUFFER_STATUS_ERROR;
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004370 res = (*it)->mInputStream->returnInputBuffer(inputBuffer);
4371 if (res != OK) {
4372 ALOGE("%s: %d: couldn't return input buffer while clearing the request "
4373 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
4374 }
4375 }
4376 }
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004377 // Set the frame number this request would have had, if it
4378 // had been submitted; this frame number will not be reused.
4379 // The requestId and burstId fields were set when the request was
4380 // submitted originally (in convertMetadataListToRequestListLocked)
4381 (*it)->mResultExtras.frameNumber = mFrameNumber++;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004382 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004383 (*it)->mResultExtras);
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07004384 }
4385 }
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004386 mRequestQueue.clear();
Jinguang Dongb26e7a02016-11-14 16:04:02 +08004387
4388 Mutex::Autolock al(mTriggerMutex);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004389 mTriggerMap.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004390 if (lastFrameNumber != NULL) {
4391 *lastFrameNumber = mRepeatingLastFrameNumber;
4392 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004393 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Emilian Peev8dae54c2019-12-02 15:17:17 -08004394 mRequestSignal.signal();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004395 return OK;
4396}
4397
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004398status_t Camera3Device::RequestThread::flush() {
4399 ATRACE_CALL();
4400 Mutex::Autolock l(mFlushLock);
4401
Emilian Peev08dd2452017-04-06 16:55:14 +01004402 return mInterface->flush();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004403}
4404
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004405void Camera3Device::RequestThread::setPaused(bool paused) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004406 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004407 Mutex::Autolock l(mPauseLock);
4408 mDoPause = paused;
4409 mDoPauseSignal.signal();
4410}
4411
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004412status_t Camera3Device::RequestThread::waitUntilRequestProcessed(
4413 int32_t requestId, nsecs_t timeout) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004414 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004415 Mutex::Autolock l(mLatestRequestMutex);
4416 status_t res;
4417 while (mLatestRequestId != requestId) {
4418 nsecs_t startTime = systemTime();
4419
4420 res = mLatestRequestSignal.waitRelative(mLatestRequestMutex, timeout);
4421 if (res != OK) return res;
4422
4423 timeout -= (systemTime() - startTime);
4424 }
4425
4426 return OK;
4427}
4428
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004429void Camera3Device::RequestThread::requestExit() {
4430 // Call parent to set up shutdown
4431 Thread::requestExit();
4432 // The exit from any possible waits
4433 mDoPauseSignal.signal();
4434 mRequestSignal.signal();
Shuzhen Wang686f6442017-06-20 16:16:04 -07004435
4436 mRequestLatency.log("ProcessCaptureRequest latency histogram");
4437 mRequestLatency.reset();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004438}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004439
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004440void Camera3Device::RequestThread::checkAndStopRepeatingRequest() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004441 ATRACE_CALL();
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07004442 bool surfaceAbandoned = false;
4443 int64_t lastFrameNumber = 0;
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004444 sp<NotificationListener> listener;
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07004445 {
4446 Mutex::Autolock l(mRequestLock);
4447 // Check all streams needed by repeating requests are still valid. Otherwise, stop
4448 // repeating requests.
4449 for (const auto& request : mRepeatingRequests) {
4450 for (const auto& s : request->mOutputStreams) {
4451 if (s->isAbandoned()) {
4452 surfaceAbandoned = true;
4453 clearRepeatingRequestsLocked(&lastFrameNumber);
4454 break;
4455 }
4456 }
4457 if (surfaceAbandoned) {
4458 break;
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004459 }
4460 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004461 listener = mListener.promote();
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004462 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004463
4464 if (listener != NULL && surfaceAbandoned) {
4465 listener->notifyRepeatingRequestError(lastFrameNumber);
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07004466 }
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004467}
4468
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004469bool Camera3Device::RequestThread::sendRequestsBatch() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004470 ATRACE_CALL();
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004471 status_t res;
4472 size_t batchSize = mNextRequests.size();
Emilian Peevf4816702020-04-03 15:44:51 -07004473 std::vector<camera_capture_request_t*> requests(batchSize);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004474 uint32_t numRequestProcessed = 0;
4475 for (size_t i = 0; i < batchSize; i++) {
4476 requests[i] = &mNextRequests.editItemAt(i).halRequest;
Yin-Chia Yeh885691c2018-05-01 15:54:24 -07004477 ATRACE_ASYNC_BEGIN("frame capture", mNextRequests[i].halRequest.frame_number);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004478 }
4479
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004480 res = mInterface->processBatchCaptureRequests(requests, &numRequestProcessed);
4481
4482 bool triggerRemoveFailed = false;
4483 NextRequest& triggerFailedRequest = mNextRequests.editItemAt(0);
4484 for (size_t i = 0; i < numRequestProcessed; i++) {
4485 NextRequest& nextRequest = mNextRequests.editItemAt(i);
4486 nextRequest.submitted = true;
4487
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004488 updateNextRequest(nextRequest);
Emilian Peevaebbe412018-01-15 13:53:24 +00004489
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004490 if (!triggerRemoveFailed) {
4491 // Remove any previously queued triggers (after unlock)
4492 status_t removeTriggerRes = removeTriggers(mPrevRequest);
4493 if (removeTriggerRes != OK) {
4494 triggerRemoveFailed = true;
4495 triggerFailedRequest = nextRequest;
4496 }
4497 }
4498 }
4499
4500 if (triggerRemoveFailed) {
4501 SET_ERR("RequestThread: Unable to remove triggers "
4502 "(capture request %d, HAL device: %s (%d)",
4503 triggerFailedRequest.halRequest.frame_number, strerror(-res), res);
4504 cleanUpFailedRequests(/*sendRequestError*/ false);
4505 return false;
4506 }
4507
4508 if (res != OK) {
4509 // Should only get a failure here for malformed requests or device-level
4510 // errors, so consider all errors fatal. Bad metadata failures should
4511 // come through notify.
4512 SET_ERR("RequestThread: Unable to submit capture request %d to HAL device: %s (%d)",
4513 mNextRequests[numRequestProcessed].halRequest.frame_number,
4514 strerror(-res), res);
4515 cleanUpFailedRequests(/*sendRequestError*/ false);
4516 return false;
4517 }
4518 return true;
4519}
4520
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07004521nsecs_t Camera3Device::RequestThread::calculateMaxExpectedDuration(const camera_metadata_t *request) {
4522 nsecs_t maxExpectedDuration = kDefaultExpectedDuration;
4523 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
4524 find_camera_metadata_ro_entry(request,
4525 ANDROID_CONTROL_AE_MODE,
4526 &e);
4527 if (e.count == 0) return maxExpectedDuration;
4528
4529 switch (e.data.u8[0]) {
4530 case ANDROID_CONTROL_AE_MODE_OFF:
4531 find_camera_metadata_ro_entry(request,
4532 ANDROID_SENSOR_EXPOSURE_TIME,
4533 &e);
4534 if (e.count > 0) {
4535 maxExpectedDuration = e.data.i64[0];
4536 }
4537 find_camera_metadata_ro_entry(request,
4538 ANDROID_SENSOR_FRAME_DURATION,
4539 &e);
4540 if (e.count > 0) {
4541 maxExpectedDuration = std::max(e.data.i64[0], maxExpectedDuration);
4542 }
4543 break;
4544 default:
4545 find_camera_metadata_ro_entry(request,
4546 ANDROID_CONTROL_AE_TARGET_FPS_RANGE,
4547 &e);
4548 if (e.count > 1) {
4549 maxExpectedDuration = 1e9 / e.data.u8[0];
4550 }
4551 break;
4552 }
4553
4554 return maxExpectedDuration;
4555}
4556
Emilian Peeva14b4dd2018-05-15 11:00:31 +01004557bool Camera3Device::RequestThread::skipHFRTargetFPSUpdate(int32_t tag,
4558 const camera_metadata_ro_entry_t& newEntry, const camera_metadata_entry_t& currentEntry) {
4559 if (mConstrainedMode && (ANDROID_CONTROL_AE_TARGET_FPS_RANGE == tag) &&
4560 (newEntry.count == currentEntry.count) && (currentEntry.count == 2) &&
4561 (currentEntry.data.i32[1] == newEntry.data.i32[1])) {
4562 return true;
4563 }
4564
4565 return false;
4566}
4567
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004568void Camera3Device::RequestThread::updateNextRequest(NextRequest& nextRequest) {
4569 // Update the latest request sent to HAL
Shuzhen Wang83bff122020-11-20 15:51:39 -08004570 camera_capture_request_t& halRequest = nextRequest.halRequest;
4571 if (halRequest.settings != NULL) { // Don't update if they were unchanged
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004572 Mutex::Autolock al(mLatestRequestMutex);
4573
Shuzhen Wang83bff122020-11-20 15:51:39 -08004574 camera_metadata_t* cloned = clone_camera_metadata(halRequest.settings);
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004575 mLatestRequest.acquire(cloned);
4576
4577 mLatestPhysicalRequest.clear();
Shuzhen Wang83bff122020-11-20 15:51:39 -08004578 for (uint32_t i = 0; i < halRequest.num_physcam_settings; i++) {
4579 cloned = clone_camera_metadata(halRequest.physcam_settings[i]);
4580 mLatestPhysicalRequest.emplace(halRequest.physcam_id[i],
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004581 CameraMetadata(cloned));
4582 }
4583
4584 sp<Camera3Device> parent = mParent.promote();
4585 if (parent != NULL) {
4586 parent->monitorMetadata(TagMonitor::REQUEST,
Shuzhen Wang83bff122020-11-20 15:51:39 -08004587 halRequest.frame_number,
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004588 0, mLatestRequest, mLatestPhysicalRequest);
4589 }
4590 }
4591
Shuzhen Wang83bff122020-11-20 15:51:39 -08004592 if (halRequest.settings != NULL) {
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004593 nextRequest.captureRequest->mSettingsList.begin()->metadata.unlock(
Shuzhen Wang83bff122020-11-20 15:51:39 -08004594 halRequest.settings);
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004595 }
4596
Shuzhen Wang83bff122020-11-20 15:51:39 -08004597 cleanupPhysicalSettings(nextRequest.captureRequest, &halRequest);
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004598}
4599
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004600bool Camera3Device::RequestThread::updateSessionParameters(const CameraMetadata& settings) {
4601 ATRACE_CALL();
4602 bool updatesDetected = false;
4603
Emilian Peev4ec17882019-01-24 17:16:58 -08004604 CameraMetadata updatedParams(mLatestSessionParams);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004605 for (auto tag : mSessionParamKeys) {
4606 camera_metadata_ro_entry entry = settings.find(tag);
Emilian Peev4ec17882019-01-24 17:16:58 -08004607 camera_metadata_entry lastEntry = updatedParams.find(tag);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004608
4609 if (entry.count > 0) {
4610 bool isDifferent = false;
4611 if (lastEntry.count > 0) {
4612 // Have a last value, compare to see if changed
4613 if (lastEntry.type == entry.type &&
4614 lastEntry.count == entry.count) {
4615 // Same type and count, compare values
4616 size_t bytesPerValue = camera_metadata_type_size[lastEntry.type];
4617 size_t entryBytes = bytesPerValue * lastEntry.count;
4618 int cmp = memcmp(entry.data.u8, lastEntry.data.u8, entryBytes);
4619 if (cmp != 0) {
4620 isDifferent = true;
4621 }
4622 } else {
4623 // Count or type has changed
4624 isDifferent = true;
4625 }
4626 } else {
4627 // No last entry, so always consider to be different
4628 isDifferent = true;
4629 }
4630
4631 if (isDifferent) {
4632 ALOGV("%s: Session parameter tag id %d changed", __FUNCTION__, tag);
Emilian Peeva14b4dd2018-05-15 11:00:31 +01004633 if (!skipHFRTargetFPSUpdate(tag, entry, lastEntry)) {
4634 updatesDetected = true;
4635 }
Emilian Peev4ec17882019-01-24 17:16:58 -08004636 updatedParams.update(entry);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004637 }
4638 } else if (lastEntry.count > 0) {
4639 // Value has been removed
4640 ALOGV("%s: Session parameter tag id %d removed", __FUNCTION__, tag);
Emilian Peev4ec17882019-01-24 17:16:58 -08004641 updatedParams.erase(tag);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004642 updatesDetected = true;
4643 }
4644 }
4645
Emilian Peev4ec17882019-01-24 17:16:58 -08004646 bool reconfigureRequired;
4647 if (updatesDetected) {
4648 reconfigureRequired = mInterface->isReconfigurationRequired(mLatestSessionParams,
4649 updatedParams);
4650 mLatestSessionParams = updatedParams;
4651 } else {
4652 reconfigureRequired = false;
4653 }
4654
4655 return reconfigureRequired;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004656}
4657
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004658bool Camera3Device::RequestThread::threadLoop() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004659 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004660 status_t res;
Jayant Chowdhary37eca242019-11-18 08:55:56 -08004661 // Any function called from threadLoop() must not hold mInterfaceLock since
4662 // it could lead to deadlocks (disconnect() -> hold mInterfaceMutex -> wait for request thread
4663 // to finish -> request thread waits on mInterfaceMutex) http://b/143513518
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004664
4665 // Handle paused state.
4666 if (waitIfPaused()) {
4667 return true;
4668 }
4669
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004670 // Wait for the next batch of requests.
4671 waitForNextRequestBatch();
4672 if (mNextRequests.size() == 0) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004673 return true;
4674 }
4675
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004676 // Get the latest request ID, if any
4677 int latestRequestId;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004678 camera_metadata_entry_t requestIdEntry = mNextRequests[mNextRequests.size() - 1].
Emilian Peevaebbe412018-01-15 13:53:24 +00004679 captureRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_ID);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004680 if (requestIdEntry.count > 0) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004681 latestRequestId = requestIdEntry.data.i32[0];
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004682 } else {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004683 ALOGW("%s: Did not have android.request.id set in the request.", __FUNCTION__);
4684 latestRequestId = NAME_NOT_FOUND;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004685 }
4686
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004687 // 'mNextRequests' will at this point contain either a set of HFR batched requests
4688 // or a single request from streaming or burst. In either case the first element
4689 // should contain the latest camera settings that we need to check for any session
4690 // parameter updates.
Emilian Peevaebbe412018-01-15 13:53:24 +00004691 if (updateSessionParameters(mNextRequests[0].captureRequest->mSettingsList.begin()->metadata)) {
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004692 res = OK;
4693
4694 //Input stream buffers are already acquired at this point so an input stream
4695 //will not be able to move to idle state unless we force it.
4696 if (mNextRequests[0].captureRequest->mInputStream != nullptr) {
4697 res = mNextRequests[0].captureRequest->mInputStream->forceToIdle();
4698 if (res != OK) {
4699 ALOGE("%s: Failed to force idle input stream: %d", __FUNCTION__, res);
4700 cleanUpFailedRequests(/*sendRequestError*/ false);
4701 return false;
4702 }
4703 }
4704
4705 if (res == OK) {
Emilian Peev3bead5f2020-05-28 17:29:08 -07004706 sp<Camera3Device> parent = mParent.promote();
4707 if (parent != nullptr) {
4708 mReconfigured |= parent->reconfigureCamera(mLatestSessionParams, mStatusId);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004709 }
Emilian Peev3bead5f2020-05-28 17:29:08 -07004710 setPaused(false);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004711
4712 if (mNextRequests[0].captureRequest->mInputStream != nullptr) {
4713 mNextRequests[0].captureRequest->mInputStream->restoreConfiguredState();
4714 if (res != OK) {
4715 ALOGE("%s: Failed to restore configured input stream: %d", __FUNCTION__, res);
4716 cleanUpFailedRequests(/*sendRequestError*/ false);
4717 return false;
4718 }
4719 }
4720 }
4721 }
4722
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004723 // Prepare a batch of HAL requests and output buffers.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004724 res = prepareHalRequests();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004725 if (res == TIMED_OUT) {
4726 // Not a fatal error if getting output buffers time out.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004727 cleanUpFailedRequests(/*sendRequestError*/ true);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004728 // Check if any stream is abandoned.
4729 checkAndStopRepeatingRequest();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004730 return true;
4731 } else if (res != OK) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004732 cleanUpFailedRequests(/*sendRequestError*/ false);
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004733 return false;
4734 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004735
Zhijun Hecc27e112013-10-03 16:12:43 -07004736 // Inform waitUntilRequestProcessed thread of a new request ID
4737 {
4738 Mutex::Autolock al(mLatestRequestMutex);
4739
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004740 mLatestRequestId = latestRequestId;
Zhijun Hecc27e112013-10-03 16:12:43 -07004741 mLatestRequestSignal.signal();
4742 }
4743
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004744 // Submit a batch of requests to HAL.
4745 // Use flush lock only when submitting multilple requests in a batch.
4746 // TODO: The problem with flush lock is flush() will be blocked by process_capture_request()
4747 // which may take a long time to finish so synchronizing flush() and
4748 // process_capture_request() defeats the purpose of cancelling requests ASAP with flush().
4749 // For now, only synchronize for high speed recording and we should figure something out for
4750 // removing the synchronization.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004751 bool useFlushLock = mNextRequests.size() > 1;
Eino-Ville Talvala17a61ad2013-06-03 16:53:32 -07004752
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004753 if (useFlushLock) {
4754 mFlushLock.lock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004755 }
4756
Zhijun Hef0645c12016-08-02 00:58:11 -07004757 ALOGVV("%s: %d: submitting %zu requests in a batch.", __FUNCTION__, __LINE__,
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004758 mNextRequests.size());
Igor Murashkin1e479c02013-09-06 16:55:14 -07004759
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08004760 sp<Camera3Device> parent = mParent.promote();
4761 if (parent != nullptr) {
4762 parent->mRequestBufferSM.onSubmittingRequest();
4763 }
4764
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004765 bool submitRequestSuccess = false;
Shuzhen Wang686f6442017-06-20 16:16:04 -07004766 nsecs_t tRequestStart = systemTime(SYSTEM_TIME_MONOTONIC);
Yin-Chia Yeh11648852019-05-16 10:42:54 -07004767 submitRequestSuccess = sendRequestsBatch();
4768
Shuzhen Wang686f6442017-06-20 16:16:04 -07004769 nsecs_t tRequestEnd = systemTime(SYSTEM_TIME_MONOTONIC);
4770 mRequestLatency.add(tRequestStart, tRequestEnd);
Igor Murashkin1e479c02013-09-06 16:55:14 -07004771
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004772 if (useFlushLock) {
4773 mFlushLock.unlock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004774 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004775
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004776 // Unset as current request
4777 {
4778 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004779 mNextRequests.clear();
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004780 }
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004781 mRequestSubmittedSignal.signal();
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004782
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004783 return submitRequestSuccess;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004784}
4785
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004786status_t Camera3Device::RequestThread::prepareHalRequests() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004787 ATRACE_CALL();
4788
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07004789 bool batchedRequest = mNextRequests[0].captureRequest->mBatchSize > 1;
Shuzhen Wang4a472662017-02-26 23:29:04 -08004790 for (size_t i = 0; i < mNextRequests.size(); i++) {
4791 auto& nextRequest = mNextRequests.editItemAt(i);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004792 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
Emilian Peevf4816702020-04-03 15:44:51 -07004793 camera_capture_request_t* halRequest = &nextRequest.halRequest;
4794 Vector<camera_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004795
4796 // Prepare a request to HAL
4797 halRequest->frame_number = captureRequest->mResultExtras.frameNumber;
4798
4799 // Insert any queued triggers (before metadata is locked)
4800 status_t res = insertTriggers(captureRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004801 if (res < 0) {
4802 SET_ERR("RequestThread: Unable to insert triggers "
4803 "(capture request %d, HAL device: %s (%d)",
4804 halRequest->frame_number, strerror(-res), res);
4805 return INVALID_OPERATION;
4806 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07004807
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004808 int triggerCount = res;
4809 bool triggersMixedIn = (triggerCount > 0 || mPrevTriggers > 0);
4810 mPrevTriggers = triggerCount;
4811
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004812 bool rotateAndCropChanged = overrideAutoRotateAndCrop(captureRequest);
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004813 bool testPatternChanged = overrideTestPattern(captureRequest);
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004814
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004815 // If the request is the same as last, or we had triggers now or last time or
4816 // changing overrides this time
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004817 bool newRequest =
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004818 (mPrevRequest != captureRequest || triggersMixedIn ||
4819 rotateAndCropChanged || testPatternChanged) &&
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07004820 // Request settings are all the same within one batch, so only treat the first
4821 // request in a batch as new
Zhijun He54c36822018-07-18 09:33:39 -07004822 !(batchedRequest && i > 0);
Emilian Peev00420d22018-02-05 21:33:13 +00004823 if (newRequest) {
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08004824 std::set<std::string> cameraIdsWithZoom;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004825 /**
4826 * HAL workaround:
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004827 * Insert a fake trigger ID if a trigger is set but no trigger ID is
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004828 */
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004829 res = addFakeTriggerIds(captureRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004830 if (res != OK) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004831 SET_ERR("RequestThread: Unable to insert fake trigger IDs "
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004832 "(capture request %d, HAL device: %s (%d)",
4833 halRequest->frame_number, strerror(-res), res);
4834 return INVALID_OPERATION;
4835 }
4836
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07004837 {
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07004838 sp<Camera3Device> parent = mParent.promote();
4839 if (parent != nullptr) {
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -07004840 List<PhysicalCameraSettings>::iterator it;
4841 for (it = captureRequest->mSettingsList.begin();
4842 it != captureRequest->mSettingsList.end(); it++) {
Jayant Chowdhary9255ce02021-07-15 11:18:17 -07004843 if (parent->mUHRCropAndMeteringRegionMappers.find(it->cameraId) ==
4844 parent->mUHRCropAndMeteringRegionMappers.end()) {
4845 continue;
4846 }
4847
4848 if (!captureRequest->mUHRCropAndMeteringRegionsUpdated) {
4849 res = parent->mUHRCropAndMeteringRegionMappers[it->cameraId].
4850 updateCaptureRequest(&(it->metadata));
4851 if (res != OK) {
4852 SET_ERR("RequestThread: Unable to correct capture requests "
4853 "for scaler crop region and metering regions for request "
4854 "%d: %s (%d)", halRequest->frame_number, strerror(-res),
4855 res);
4856 return INVALID_OPERATION;
4857 }
4858 captureRequest->mUHRCropAndMeteringRegionsUpdated = true;
4859 }
4860 }
4861
4862 // Correct metadata regions for distortion correction if enabled
4863 for (it = captureRequest->mSettingsList.begin();
4864 it != captureRequest->mSettingsList.end(); it++) {
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -07004865 if (parent->mDistortionMappers.find(it->cameraId) ==
4866 parent->mDistortionMappers.end()) {
4867 continue;
4868 }
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07004869
4870 if (!captureRequest->mDistortionCorrectionUpdated) {
4871 res = parent->mDistortionMappers[it->cameraId].correctCaptureRequest(
4872 &(it->metadata));
4873 if (res != OK) {
4874 SET_ERR("RequestThread: Unable to correct capture requests "
4875 "for lens distortion for request %d: %s (%d)",
4876 halRequest->frame_number, strerror(-res), res);
4877 return INVALID_OPERATION;
4878 }
4879 captureRequest->mDistortionCorrectionUpdated = true;
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -07004880 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07004881 }
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08004882
4883 for (it = captureRequest->mSettingsList.begin();
4884 it != captureRequest->mSettingsList.end(); it++) {
4885 if (parent->mZoomRatioMappers.find(it->cameraId) ==
4886 parent->mZoomRatioMappers.end()) {
4887 continue;
4888 }
4889
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07004890 if (!captureRequest->mZoomRatioIs1x) {
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08004891 cameraIdsWithZoom.insert(it->cameraId);
4892 }
4893
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07004894 if (!captureRequest->mZoomRatioUpdated) {
4895 res = parent->mZoomRatioMappers[it->cameraId].updateCaptureRequest(
4896 &(it->metadata));
4897 if (res != OK) {
4898 SET_ERR("RequestThread: Unable to correct capture requests "
4899 "for zoom ratio for request %d: %s (%d)",
4900 halRequest->frame_number, strerror(-res), res);
4901 return INVALID_OPERATION;
4902 }
4903 captureRequest->mZoomRatioUpdated = true;
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08004904 }
4905 }
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07004906 if (captureRequest->mRotateAndCropAuto &&
4907 !captureRequest->mRotationAndCropUpdated) {
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004908 for (it = captureRequest->mSettingsList.begin();
4909 it != captureRequest->mSettingsList.end(); it++) {
4910 auto mapper = parent->mRotateAndCropMappers.find(it->cameraId);
4911 if (mapper != parent->mRotateAndCropMappers.end()) {
4912 res = mapper->second.updateCaptureRequest(&(it->metadata));
4913 if (res != OK) {
4914 SET_ERR("RequestThread: Unable to correct capture requests "
4915 "for rotate-and-crop for request %d: %s (%d)",
4916 halRequest->frame_number, strerror(-res), res);
4917 return INVALID_OPERATION;
4918 }
4919 }
4920 }
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07004921 captureRequest->mRotationAndCropUpdated = true;
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004922 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07004923 }
4924 }
4925
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004926 /**
4927 * The request should be presorted so accesses in HAL
4928 * are O(logn). Sidenote, sorting a sorted metadata is nop.
4929 */
Emilian Peevaebbe412018-01-15 13:53:24 +00004930 captureRequest->mSettingsList.begin()->metadata.sort();
4931 halRequest->settings = captureRequest->mSettingsList.begin()->metadata.getAndLock();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004932 mPrevRequest = captureRequest;
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08004933 mPrevCameraIdsWithZoom = cameraIdsWithZoom;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004934 ALOGVV("%s: Request settings are NEW", __FUNCTION__);
4935
4936 IF_ALOGV() {
4937 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
4938 find_camera_metadata_ro_entry(
4939 halRequest->settings,
4940 ANDROID_CONTROL_AF_TRIGGER,
4941 &e
4942 );
4943 if (e.count > 0) {
4944 ALOGV("%s: Request (frame num %d) had AF trigger 0x%x",
4945 __FUNCTION__,
4946 halRequest->frame_number,
4947 e.data.u8[0]);
4948 }
4949 }
4950 } else {
4951 // leave request.settings NULL to indicate 'reuse latest given'
4952 ALOGVV("%s: Request settings are REUSED",
4953 __FUNCTION__);
4954 }
4955
Emilian Peevaebbe412018-01-15 13:53:24 +00004956 if (captureRequest->mSettingsList.size() > 1) {
4957 halRequest->num_physcam_settings = captureRequest->mSettingsList.size() - 1;
4958 halRequest->physcam_id = new const char* [halRequest->num_physcam_settings];
Emilian Peev00420d22018-02-05 21:33:13 +00004959 if (newRequest) {
4960 halRequest->physcam_settings =
4961 new const camera_metadata* [halRequest->num_physcam_settings];
4962 } else {
4963 halRequest->physcam_settings = nullptr;
4964 }
Emilian Peevaebbe412018-01-15 13:53:24 +00004965 auto it = ++captureRequest->mSettingsList.begin();
4966 size_t i = 0;
4967 for (; it != captureRequest->mSettingsList.end(); it++, i++) {
4968 halRequest->physcam_id[i] = it->cameraId.c_str();
Emilian Peev00420d22018-02-05 21:33:13 +00004969 if (newRequest) {
4970 it->metadata.sort();
4971 halRequest->physcam_settings[i] = it->metadata.getAndLock();
4972 }
Emilian Peevaebbe412018-01-15 13:53:24 +00004973 }
4974 }
4975
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004976 uint32_t totalNumBuffers = 0;
4977
4978 // Fill in buffers
4979 if (captureRequest->mInputStream != NULL) {
4980 halRequest->input_buffer = &captureRequest->mInputBuffer;
Shuzhen Wang83bff122020-11-20 15:51:39 -08004981
4982 halRequest->input_width = captureRequest->mInputBufferSize.width;
4983 halRequest->input_height = captureRequest->mInputBufferSize.height;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004984 totalNumBuffers += 1;
4985 } else {
4986 halRequest->input_buffer = NULL;
4987 }
4988
Emilian Peevf4816702020-04-03 15:44:51 -07004989 outputBuffers->insertAt(camera_stream_buffer_t(), 0,
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004990 captureRequest->mOutputStreams.size());
4991 halRequest->output_buffers = outputBuffers->array();
Shuzhen Wang99080502021-03-07 21:08:20 -08004992 std::set<std::set<String8>> requestedPhysicalCameras;
Yin-Chia Yehb3a80b12018-09-04 12:13:05 -07004993
4994 sp<Camera3Device> parent = mParent.promote();
4995 if (parent == NULL) {
4996 // Should not happen, and nowhere to send errors to, so just log it
4997 CLOGE("RequestThread: Parent is gone");
4998 return INVALID_OPERATION;
4999 }
5000 nsecs_t waitDuration = kBaseGetBufferWait + parent->getExpectedInFlightDuration();
5001
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005002 SurfaceMap uniqueSurfaceIdMap;
Shuzhen Wang4a472662017-02-26 23:29:04 -08005003 for (size_t j = 0; j < captureRequest->mOutputStreams.size(); j++) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005004 sp<Camera3OutputStreamInterface> outputStream =
5005 captureRequest->mOutputStreams.editItemAt(j);
5006 int streamId = outputStream->getId();
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07005007
5008 // Prepare video buffers for high speed recording on the first video request.
5009 if (mPrepareVideoStream && outputStream->isVideoStream()) {
5010 // Only try to prepare video stream on the first video request.
5011 mPrepareVideoStream = false;
5012
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07005013 res = outputStream->startPrepare(Camera3StreamInterface::ALLOCATE_PIPELINE_MAX,
5014 false /*blockRequest*/);
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07005015 while (res == NOT_ENOUGH_DATA) {
5016 res = outputStream->prepareNextBuffer();
5017 }
5018 if (res != OK) {
5019 ALOGW("%s: Preparing video buffers for high speed failed: %s (%d)",
5020 __FUNCTION__, strerror(-res), res);
5021 outputStream->cancelPrepare();
5022 }
5023 }
5024
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005025 std::vector<size_t> uniqueSurfaceIds;
5026 res = outputStream->getUniqueSurfaceIds(
5027 captureRequest->mOutputSurfaces[streamId],
5028 &uniqueSurfaceIds);
5029 // INVALID_OPERATION is normal output for streams not supporting surfaceIds
5030 if (res != OK && res != INVALID_OPERATION) {
5031 ALOGE("%s: failed to query stream %d unique surface IDs",
5032 __FUNCTION__, streamId);
5033 return res;
5034 }
5035 if (res == OK) {
5036 uniqueSurfaceIdMap.insert({streamId, std::move(uniqueSurfaceIds)});
5037 }
5038
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07005039 if (mUseHalBufManager) {
Yin-Chia Yeh110342b2018-11-19 11:47:46 -08005040 if (outputStream->isAbandoned()) {
Yin-Chia Yeha1b56c82019-03-27 15:50:39 -07005041 ALOGV("%s: stream %d is abandoned, skipping request", __FUNCTION__, streamId);
Yin-Chia Yeh110342b2018-11-19 11:47:46 -08005042 return TIMED_OUT;
5043 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07005044 // HAL will request buffer through requestStreamBuffer API
Emilian Peevf4816702020-04-03 15:44:51 -07005045 camera_stream_buffer_t& buffer = outputBuffers->editItemAt(j);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07005046 buffer.stream = outputStream->asHalStream();
5047 buffer.buffer = nullptr;
Emilian Peevf4816702020-04-03 15:44:51 -07005048 buffer.status = CAMERA_BUFFER_STATUS_OK;
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07005049 buffer.acquire_fence = -1;
5050 buffer.release_fence = -1;
Emilian Peevf0348ae2021-01-13 13:39:45 -08005051 // Mark the output stream as unpreparable to block clients from calling
5052 // 'prepare' after this request reaches CameraHal and before the respective
5053 // buffers are requested.
5054 outputStream->markUnpreparable();
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07005055 } else {
5056 res = outputStream->getBuffer(&outputBuffers->editItemAt(j),
5057 waitDuration,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005058 captureRequest->mOutputSurfaces[streamId]);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07005059 if (res != OK) {
5060 // Can't get output buffer from gralloc queue - this could be due to
5061 // abandoned queue or other consumer misbehavior, so not a fatal
5062 // error
Yin-Chia Yeha1b56c82019-03-27 15:50:39 -07005063 ALOGV("RequestThread: Can't get output buffer, skipping request:"
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07005064 " %s (%d)", strerror(-res), res);
5065
5066 return TIMED_OUT;
5067 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005068 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08005069
5070 {
5071 sp<Camera3Device> parent = mParent.promote();
5072 if (parent != nullptr) {
5073 const String8& streamCameraId = outputStream->getPhysicalCameraId();
5074 for (const auto& settings : captureRequest->mSettingsList) {
5075 if ((streamCameraId.isEmpty() &&
5076 parent->getId() == settings.cameraId.c_str()) ||
5077 streamCameraId == settings.cameraId.c_str()) {
5078 outputStream->fireBufferRequestForFrameNumber(
5079 captureRequest->mResultExtras.frameNumber,
5080 settings.metadata);
5081 }
5082 }
5083 }
5084 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07005085
Shuzhen Wang5c22c152017-12-31 17:12:25 -08005086 String8 physicalCameraId = outputStream->getPhysicalCameraId();
Shuzhen Wang99080502021-03-07 21:08:20 -08005087 int32_t streamGroupId = outputStream->getHalStreamGroupId();
5088 if (streamGroupId != -1 && mGroupIdPhysicalCameraMap.count(streamGroupId) == 1) {
5089 requestedPhysicalCameras.insert(mGroupIdPhysicalCameraMap[streamGroupId]);
5090 } else if (!physicalCameraId.isEmpty()) {
5091 requestedPhysicalCameras.insert(std::set<String8>({physicalCameraId}));
Shuzhen Wang5c22c152017-12-31 17:12:25 -08005092 }
5093 halRequest->num_output_buffers++;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005094 }
5095 totalNumBuffers += halRequest->num_output_buffers;
5096
5097 // Log request in the in-flight queue
Shuzhen Wang4a472662017-02-26 23:29:04 -08005098 // If this request list is for constrained high speed recording (not
5099 // preview), and the current request is not the last one in the batch,
5100 // do not send callback to the app.
5101 bool hasCallback = true;
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07005102 if (batchedRequest && i != mNextRequests.size()-1) {
Shuzhen Wang4a472662017-02-26 23:29:04 -08005103 hasCallback = false;
5104 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01005105 bool isStillCapture = false;
Shuzhen Wang26abaf42018-08-28 15:41:20 -07005106 bool isZslCapture = false;
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08005107 const camera_metadata_t* settings = halRequest->settings;
5108 bool shouldUnlockSettings = false;
5109 if (settings == nullptr) {
5110 shouldUnlockSettings = true;
5111 settings = captureRequest->mSettingsList.begin()->metadata.getAndLock();
5112 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01005113 if (!mNextRequests[0].captureRequest->mSettingsList.begin()->metadata.isEmpty()) {
5114 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08005115 find_camera_metadata_ro_entry(settings, ANDROID_CONTROL_CAPTURE_INTENT, &e);
Emilian Peev9dd21f42018-08-03 13:39:29 +01005116 if ((e.count > 0) && (e.data.u8[0] == ANDROID_CONTROL_CAPTURE_INTENT_STILL_CAPTURE)) {
5117 isStillCapture = true;
5118 ATRACE_ASYNC_BEGIN("still capture", mNextRequests[i].halRequest.frame_number);
5119 }
Shuzhen Wang26abaf42018-08-28 15:41:20 -07005120
Emilian Peevaf8416e2021-02-04 17:52:43 -08005121 e = camera_metadata_ro_entry_t();
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08005122 find_camera_metadata_ro_entry(settings, ANDROID_CONTROL_ENABLE_ZSL, &e);
Shuzhen Wang26abaf42018-08-28 15:41:20 -07005123 if ((e.count > 0) && (e.data.u8[0] == ANDROID_CONTROL_ENABLE_ZSL_TRUE)) {
5124 isZslCapture = true;
5125 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01005126 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005127 res = parent->registerInFlight(halRequest->frame_number,
5128 totalNumBuffers, captureRequest->mResultExtras,
5129 /*hasInput*/halRequest->input_buffer != NULL,
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07005130 hasCallback,
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08005131 calculateMaxExpectedDuration(settings),
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005132 requestedPhysicalCameras, isStillCapture, isZslCapture,
5133 captureRequest->mRotateAndCropAuto, mPrevCameraIdsWithZoom,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005134 (mUseHalBufManager) ? uniqueSurfaceIdMap :
Shuzhen Wang316781a2020-08-18 18:11:01 -07005135 SurfaceMap{}, captureRequest->mRequestTimeNs);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005136 ALOGVV("%s: registered in flight requestId = %" PRId32 ", frameNumber = %" PRId64
5137 ", burstId = %" PRId32 ".",
5138 __FUNCTION__,
5139 captureRequest->mResultExtras.requestId, captureRequest->mResultExtras.frameNumber,
5140 captureRequest->mResultExtras.burstId);
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08005141
5142 if (shouldUnlockSettings) {
5143 captureRequest->mSettingsList.begin()->metadata.unlock(settings);
5144 }
5145
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005146 if (res != OK) {
5147 SET_ERR("RequestThread: Unable to register new in-flight request:"
5148 " %s (%d)", strerror(-res), res);
5149 return INVALID_OPERATION;
5150 }
5151 }
5152
5153 return OK;
5154}
5155
Igor Murashkin1e479c02013-09-06 16:55:14 -07005156CameraMetadata Camera3Device::RequestThread::getLatestRequest() const {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005157 ATRACE_CALL();
Igor Murashkin1e479c02013-09-06 16:55:14 -07005158 Mutex::Autolock al(mLatestRequestMutex);
5159
5160 ALOGV("RequestThread::%s", __FUNCTION__);
5161
5162 return mLatestRequest;
5163}
5164
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005165bool Camera3Device::RequestThread::isStreamPending(
5166 sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005167 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005168 Mutex::Autolock l(mRequestLock);
5169
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005170 for (const auto& nextRequest : mNextRequests) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005171 if (!nextRequest.submitted) {
5172 for (const auto& s : nextRequest.captureRequest->mOutputStreams) {
5173 if (stream == s) return true;
5174 }
5175 if (stream == nextRequest.captureRequest->mInputStream) return true;
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07005176 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07005177 }
5178
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005179 for (const auto& request : mRequestQueue) {
5180 for (const auto& s : request->mOutputStreams) {
5181 if (stream == s) return true;
5182 }
5183 if (stream == request->mInputStream) return true;
5184 }
5185
5186 for (const auto& request : mRepeatingRequests) {
5187 for (const auto& s : request->mOutputStreams) {
5188 if (stream == s) return true;
5189 }
5190 if (stream == request->mInputStream) return true;
5191 }
5192
5193 return false;
5194}
Jianing Weicb0652e2014-03-12 18:29:36 -07005195
Emilian Peev40ead602017-09-26 15:46:36 +01005196bool Camera3Device::RequestThread::isOutputSurfacePending(int streamId, size_t surfaceId) {
5197 ATRACE_CALL();
5198 Mutex::Autolock l(mRequestLock);
5199
5200 for (const auto& nextRequest : mNextRequests) {
5201 for (const auto& s : nextRequest.captureRequest->mOutputSurfaces) {
5202 if (s.first == streamId) {
5203 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
5204 if (it != s.second.end()) {
5205 return true;
5206 }
5207 }
5208 }
5209 }
5210
5211 for (const auto& request : mRequestQueue) {
5212 for (const auto& s : request->mOutputSurfaces) {
5213 if (s.first == streamId) {
5214 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
5215 if (it != s.second.end()) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005216 return true;
Emilian Peev40ead602017-09-26 15:46:36 +01005217 }
5218 }
5219 }
5220 }
5221
5222 for (const auto& request : mRepeatingRequests) {
5223 for (const auto& s : request->mOutputSurfaces) {
5224 if (s.first == streamId) {
5225 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
5226 if (it != s.second.end()) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005227 return true;
Emilian Peev40ead602017-09-26 15:46:36 +01005228 }
5229 }
5230 }
5231 }
5232
5233 return false;
5234}
5235
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07005236void Camera3Device::RequestThread::signalPipelineDrain(const std::vector<int>& streamIds) {
5237 if (!mUseHalBufManager) {
5238 ALOGE("%s called for camera device not supporting HAL buffer management", __FUNCTION__);
5239 return;
5240 }
5241
5242 Mutex::Autolock pl(mPauseLock);
5243 if (mPaused) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005244 mInterface->signalPipelineDrain(streamIds);
5245 return;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07005246 }
5247 // If request thread is still busy, wait until paused then notify HAL
5248 mNotifyPipelineDrain = true;
5249 mStreamIdsToBeDrained = streamIds;
5250}
5251
Yin-Chia Yehe52b8fa2020-07-28 00:17:58 -07005252void Camera3Device::RequestThread::resetPipelineDrain() {
5253 Mutex::Autolock pl(mPauseLock);
5254 mNotifyPipelineDrain = false;
5255 mStreamIdsToBeDrained.clear();
5256}
5257
Emilian Peevc0fe54c2020-03-11 14:05:07 -07005258void Camera3Device::RequestThread::clearPreviousRequest() {
5259 Mutex::Autolock l(mRequestLock);
5260 mPrevRequest.clear();
5261}
5262
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005263status_t Camera3Device::RequestThread::switchToOffline(
5264 const std::vector<int32_t>& streamsToKeep,
5265 /*out*/hardware::camera::device::V3_6::CameraOfflineSessionInfo* offlineSessionInfo,
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005266 /*out*/sp<hardware::camera::device::V3_6::ICameraOfflineSession>* offlineSession,
5267 /*out*/camera3::BufferRecords* bufferRecords) {
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005268 Mutex::Autolock l(mRequestLock);
5269 clearRepeatingRequestsLocked(/*lastFrameNumber*/nullptr);
5270
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005271 // Wait until request thread is fully stopped
5272 // TBD: check if request thread is being paused by other APIs (shouldn't be)
5273
5274 // We could also check for mRepeatingRequests.empty(), but the API interface
5275 // is serialized by Camera3Device::mInterfaceLock so no one should be able to submit any
5276 // new requests during the call; hence skip that check.
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005277 bool queueEmpty = mNextRequests.empty() && mRequestQueue.empty();
5278 while (!queueEmpty) {
5279 status_t res = mRequestSubmittedSignal.waitRelative(mRequestLock, kRequestSubmitTimeout);
5280 if (res == TIMED_OUT) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005281 ALOGE("%s: request thread failed to submit one request within timeout!", __FUNCTION__);
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005282 return res;
5283 } else if (res != OK) {
5284 ALOGE("%s: request thread failed to submit a request: %s (%d)!",
5285 __FUNCTION__, strerror(-res), res);
5286 return res;
5287 }
5288 queueEmpty = mNextRequests.empty() && mRequestQueue.empty();
5289 }
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005290
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005291 return mInterface->switchToOffline(
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005292 streamsToKeep, offlineSessionInfo, offlineSession, bufferRecords);
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005293}
5294
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005295status_t Camera3Device::RequestThread::setRotateAndCropAutoBehavior(
5296 camera_metadata_enum_android_scaler_rotate_and_crop_t rotateAndCropValue) {
5297 ATRACE_CALL();
5298 Mutex::Autolock l(mTriggerMutex);
5299 if (rotateAndCropValue == ANDROID_SCALER_ROTATE_AND_CROP_AUTO) {
5300 return BAD_VALUE;
5301 }
5302 mRotateAndCropOverride = rotateAndCropValue;
5303 return OK;
5304}
5305
Eino-Ville Talvala11afe4f2021-05-27 14:45:31 -07005306status_t Camera3Device::RequestThread::setCameraMute(int32_t muteMode) {
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005307 ATRACE_CALL();
5308 Mutex::Autolock l(mTriggerMutex);
Eino-Ville Talvala11afe4f2021-05-27 14:45:31 -07005309 if (muteMode != mCameraMute) {
5310 mCameraMute = muteMode;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005311 mCameraMuteChanged = true;
5312 }
5313 return OK;
5314}
5315
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07005316nsecs_t Camera3Device::getExpectedInFlightDuration() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005317 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005318 std::lock_guard<std::mutex> l(mInFlightLock);
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07005319 return mExpectedInflightDuration > kMinInflightDuration ?
5320 mExpectedInflightDuration : kMinInflightDuration;
5321}
5322
Emilian Peevaebbe412018-01-15 13:53:24 +00005323void Camera3Device::RequestThread::cleanupPhysicalSettings(sp<CaptureRequest> request,
Emilian Peevf4816702020-04-03 15:44:51 -07005324 camera_capture_request_t *halRequest) {
Emilian Peevaebbe412018-01-15 13:53:24 +00005325 if ((request == nullptr) || (halRequest == nullptr)) {
5326 ALOGE("%s: Invalid request!", __FUNCTION__);
5327 return;
5328 }
5329
5330 if (halRequest->num_physcam_settings > 0) {
5331 if (halRequest->physcam_id != nullptr) {
5332 delete [] halRequest->physcam_id;
5333 halRequest->physcam_id = nullptr;
5334 }
5335 if (halRequest->physcam_settings != nullptr) {
5336 auto it = ++(request->mSettingsList.begin());
5337 size_t i = 0;
5338 for (; it != request->mSettingsList.end(); it++, i++) {
5339 it->metadata.unlock(halRequest->physcam_settings[i]);
5340 }
5341 delete [] halRequest->physcam_settings;
5342 halRequest->physcam_settings = nullptr;
5343 }
5344 }
5345}
5346
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005347void Camera3Device::RequestThread::cleanUpFailedRequests(bool sendRequestError) {
5348 if (mNextRequests.empty()) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005349 return;
5350 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005351
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005352 for (auto& nextRequest : mNextRequests) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005353 // Skip the ones that have been submitted successfully.
5354 if (nextRequest.submitted) {
5355 continue;
5356 }
5357
5358 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
Emilian Peevf4816702020-04-03 15:44:51 -07005359 camera_capture_request_t* halRequest = &nextRequest.halRequest;
5360 Vector<camera_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005361
5362 if (halRequest->settings != NULL) {
Emilian Peevaebbe412018-01-15 13:53:24 +00005363 captureRequest->mSettingsList.begin()->metadata.unlock(halRequest->settings);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005364 }
5365
Emilian Peevaebbe412018-01-15 13:53:24 +00005366 cleanupPhysicalSettings(captureRequest, halRequest);
5367
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005368 if (captureRequest->mInputStream != NULL) {
Emilian Peevf4816702020-04-03 15:44:51 -07005369 captureRequest->mInputBuffer.status = CAMERA_BUFFER_STATUS_ERROR;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005370 captureRequest->mInputStream->returnInputBuffer(captureRequest->mInputBuffer);
5371 }
5372
Yin-Chia Yeh21cb47b2019-01-18 15:08:17 -08005373 // No output buffer can be returned when using HAL buffer manager
5374 if (!mUseHalBufManager) {
5375 for (size_t i = 0; i < halRequest->num_output_buffers; i++) {
5376 //Buffers that failed processing could still have
5377 //valid acquire fence.
5378 int acquireFence = (*outputBuffers)[i].acquire_fence;
5379 if (0 <= acquireFence) {
5380 close(acquireFence);
5381 outputBuffers->editItemAt(i).acquire_fence = -1;
5382 }
Emilian Peevf4816702020-04-03 15:44:51 -07005383 outputBuffers->editItemAt(i).status = CAMERA_BUFFER_STATUS_ERROR;
Yin-Chia Yeh21cb47b2019-01-18 15:08:17 -08005384 captureRequest->mOutputStreams.editItemAt(i)->returnBuffer((*outputBuffers)[i], 0,
5385 /*timestampIncreasing*/true, std::vector<size_t> (),
5386 captureRequest->mResultExtras.frameNumber);
Emilian Peevc58cf4c2017-05-11 17:23:41 +01005387 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005388 }
5389
5390 if (sendRequestError) {
5391 Mutex::Autolock l(mRequestLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005392 sp<NotificationListener> listener = mListener.promote();
5393 if (listener != NULL) {
5394 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08005395 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005396 captureRequest->mResultExtras);
5397 }
5398 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07005399
5400 // Remove yet-to-be submitted inflight request from inflightMap
5401 {
5402 sp<Camera3Device> parent = mParent.promote();
5403 if (parent != NULL) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005404 std::lock_guard<std::mutex> l(parent->mInFlightLock);
Shuzhen Wangcadb3302016-11-04 14:17:56 -07005405 ssize_t idx = parent->mInFlightMap.indexOfKey(captureRequest->mResultExtras.frameNumber);
5406 if (idx >= 0) {
5407 ALOGV("%s: Remove inflight request from queue: frameNumber %" PRId64,
5408 __FUNCTION__, captureRequest->mResultExtras.frameNumber);
5409 parent->removeInFlightMapEntryLocked(idx);
5410 }
5411 }
5412 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005413 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07005414
5415 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005416 mNextRequests.clear();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005417}
5418
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005419void Camera3Device::RequestThread::waitForNextRequestBatch() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005420 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005421 // Optimized a bit for the simple steady-state case (single repeating
5422 // request), to avoid putting that request in the queue temporarily.
5423 Mutex::Autolock l(mRequestLock);
5424
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005425 assert(mNextRequests.empty());
5426
5427 NextRequest nextRequest;
5428 nextRequest.captureRequest = waitForNextRequestLocked();
5429 if (nextRequest.captureRequest == nullptr) {
5430 return;
5431 }
5432
Emilian Peevf4816702020-04-03 15:44:51 -07005433 nextRequest.halRequest = camera_capture_request_t();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005434 nextRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005435 mNextRequests.add(nextRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005436
5437 // Wait for additional requests
5438 const size_t batchSize = nextRequest.captureRequest->mBatchSize;
5439
5440 for (size_t i = 1; i < batchSize; i++) {
5441 NextRequest additionalRequest;
5442 additionalRequest.captureRequest = waitForNextRequestLocked();
5443 if (additionalRequest.captureRequest == nullptr) {
5444 break;
5445 }
5446
Emilian Peevf4816702020-04-03 15:44:51 -07005447 additionalRequest.halRequest = camera_capture_request_t();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005448 additionalRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005449 mNextRequests.add(additionalRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005450 }
5451
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005452 if (mNextRequests.size() < batchSize) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08005453 ALOGE("RequestThread: only get %zu out of %zu requests. Skipping requests.",
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005454 mNextRequests.size(), batchSize);
5455 cleanUpFailedRequests(/*sendRequestError*/true);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005456 }
5457
5458 return;
5459}
5460
5461sp<Camera3Device::CaptureRequest>
5462 Camera3Device::RequestThread::waitForNextRequestLocked() {
5463 status_t res;
5464 sp<CaptureRequest> nextRequest;
5465
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005466 while (mRequestQueue.empty()) {
5467 if (!mRepeatingRequests.empty()) {
5468 // Always atomically enqueue all requests in a repeating request
5469 // list. Guarantees a complete in-sequence set of captures to
5470 // application.
5471 const RequestList &requests = mRepeatingRequests;
Shuzhen Wang316781a2020-08-18 18:11:01 -07005472 if (mFirstRepeating) {
5473 mFirstRepeating = false;
5474 } else {
5475 for (auto& request : requests) {
5476 // For repeating requests, override timestamp request using
5477 // the time a request is inserted into the request queue,
5478 // because the original repeating request will have an old
5479 // fixed timestamp.
5480 request->mRequestTimeNs = systemTime();
5481 }
5482 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005483 RequestList::const_iterator firstRequest =
5484 requests.begin();
5485 nextRequest = *firstRequest;
5486 mRequestQueue.insert(mRequestQueue.end(),
5487 ++firstRequest,
5488 requests.end());
5489 // No need to wait any longer
Jianing Weicb0652e2014-03-12 18:29:36 -07005490
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005491 mRepeatingLastFrameNumber = mFrameNumber + requests.size() - 1;
Jianing Weicb0652e2014-03-12 18:29:36 -07005492
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005493 break;
5494 }
5495
5496 res = mRequestSignal.waitRelative(mRequestLock, kRequestTimeout);
5497
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005498 if ((mRequestQueue.empty() && mRepeatingRequests.empty()) ||
5499 exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005500 Mutex::Autolock pl(mPauseLock);
5501 if (mPaused == false) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005502 ALOGV("%s: RequestThread: Going idle", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005503 mPaused = true;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07005504 if (mNotifyPipelineDrain) {
5505 mInterface->signalPipelineDrain(mStreamIdsToBeDrained);
5506 mNotifyPipelineDrain = false;
5507 mStreamIdsToBeDrained.clear();
5508 }
Yin-Chia Yehc300a072019-02-13 14:56:57 -08005509 // Let the tracker know
5510 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5511 if (statusTracker != 0) {
5512 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
5513 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005514 sp<Camera3Device> parent = mParent.promote();
5515 if (parent != nullptr) {
5516 parent->mRequestBufferSM.onRequestThreadPaused();
5517 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005518 }
5519 // Stop waiting for now and let thread management happen
5520 return NULL;
5521 }
5522 }
5523
5524 if (nextRequest == NULL) {
5525 // Don't have a repeating request already in hand, so queue
5526 // must have an entry now.
5527 RequestList::iterator firstRequest =
5528 mRequestQueue.begin();
5529 nextRequest = *firstRequest;
5530 mRequestQueue.erase(firstRequest);
Shuzhen Wang9d066012016-09-30 11:30:20 -07005531 if (mRequestQueue.empty() && !nextRequest->mRepeating) {
5532 sp<NotificationListener> listener = mListener.promote();
5533 if (listener != NULL) {
5534 listener->notifyRequestQueueEmpty();
5535 }
5536 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005537 }
5538
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005539 // In case we've been unpaused by setPaused clearing mDoPause, need to
5540 // update internal pause state (capture/setRepeatingRequest unpause
5541 // directly).
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005542 Mutex::Autolock pl(mPauseLock);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005543 if (mPaused) {
5544 ALOGV("%s: RequestThread: Unpaused", __FUNCTION__);
5545 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5546 if (statusTracker != 0) {
5547 statusTracker->markComponentActive(mStatusId);
5548 }
5549 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005550 mPaused = false;
5551
5552 // Check if we've reconfigured since last time, and reset the preview
5553 // request if so. Can't use 'NULL request == repeat' across configure calls.
5554 if (mReconfigured) {
5555 mPrevRequest.clear();
5556 mReconfigured = false;
5557 }
5558
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005559 if (nextRequest != NULL) {
5560 nextRequest->mResultExtras.frameNumber = mFrameNumber++;
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07005561 nextRequest->mResultExtras.afTriggerId = mCurrentAfTriggerId;
5562 nextRequest->mResultExtras.precaptureTriggerId = mCurrentPreCaptureTriggerId;
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07005563
5564 // Since RequestThread::clear() removes buffers from the input stream,
5565 // get the right buffer here before unlocking mRequestLock
5566 if (nextRequest->mInputStream != NULL) {
Shuzhen Wang83bff122020-11-20 15:51:39 -08005567 res = nextRequest->mInputStream->getInputBuffer(&nextRequest->mInputBuffer,
5568 &nextRequest->mInputBufferSize);
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07005569 if (res != OK) {
5570 // Can't get input buffer from gralloc queue - this could be due to
5571 // disconnected queue or other producer misbehavior, so not a fatal
5572 // error
5573 ALOGE("%s: Can't get input buffer, skipping request:"
5574 " %s (%d)", __FUNCTION__, strerror(-res), res);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005575
5576 sp<NotificationListener> listener = mListener.promote();
5577 if (listener != NULL) {
5578 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08005579 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07005580 nextRequest->mResultExtras);
5581 }
5582 return NULL;
5583 }
5584 }
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005585 }
Chien-Yu Chend196d612015-06-22 19:49:01 -07005586
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005587 return nextRequest;
5588}
5589
5590bool Camera3Device::RequestThread::waitIfPaused() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005591 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005592 status_t res;
5593 Mutex::Autolock l(mPauseLock);
5594 while (mDoPause) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005595 if (mPaused == false) {
5596 mPaused = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005597 ALOGV("%s: RequestThread: Paused", __FUNCTION__);
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07005598 if (mNotifyPipelineDrain) {
5599 mInterface->signalPipelineDrain(mStreamIdsToBeDrained);
5600 mNotifyPipelineDrain = false;
5601 mStreamIdsToBeDrained.clear();
5602 }
Yin-Chia Yehc300a072019-02-13 14:56:57 -08005603 // Let the tracker know
5604 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5605 if (statusTracker != 0) {
5606 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
5607 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005608 sp<Camera3Device> parent = mParent.promote();
5609 if (parent != nullptr) {
5610 parent->mRequestBufferSM.onRequestThreadPaused();
5611 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005612 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005613
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005614 res = mDoPauseSignal.waitRelative(mPauseLock, kRequestTimeout);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005615 if (res == TIMED_OUT || exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005616 return true;
5617 }
5618 }
5619 // We don't set mPaused to false here, because waitForNextRequest needs
5620 // to further manage the paused state in case of starvation.
5621 return false;
5622}
5623
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005624void Camera3Device::RequestThread::unpauseForNewRequests() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005625 ATRACE_CALL();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005626 // With work to do, mark thread as unpaused.
5627 // If paused by request (setPaused), don't resume, to avoid
5628 // extra signaling/waiting overhead to waitUntilPaused
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005629 mRequestSignal.signal();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005630 Mutex::Autolock p(mPauseLock);
5631 if (!mDoPause) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005632 ALOGV("%s: RequestThread: Going active", __FUNCTION__);
5633 if (mPaused) {
5634 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5635 if (statusTracker != 0) {
5636 statusTracker->markComponentActive(mStatusId);
5637 }
5638 }
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005639 mPaused = false;
5640 }
5641}
5642
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07005643void Camera3Device::RequestThread::setErrorState(const char *fmt, ...) {
5644 sp<Camera3Device> parent = mParent.promote();
5645 if (parent != NULL) {
5646 va_list args;
5647 va_start(args, fmt);
5648
5649 parent->setErrorStateV(fmt, args);
5650
5651 va_end(args);
5652 }
5653}
5654
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005655status_t Camera3Device::RequestThread::insertTriggers(
5656 const sp<CaptureRequest> &request) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005657 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005658 Mutex::Autolock al(mTriggerMutex);
5659
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07005660 sp<Camera3Device> parent = mParent.promote();
5661 if (parent == NULL) {
5662 CLOGE("RequestThread: Parent is gone");
5663 return DEAD_OBJECT;
5664 }
5665
Emilian Peevaebbe412018-01-15 13:53:24 +00005666 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005667 size_t count = mTriggerMap.size();
5668
5669 for (size_t i = 0; i < count; ++i) {
5670 RequestTrigger trigger = mTriggerMap.valueAt(i);
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005671 uint32_t tag = trigger.metadataTag;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07005672
5673 if (tag == ANDROID_CONTROL_AF_TRIGGER_ID || tag == ANDROID_CONTROL_AE_PRECAPTURE_ID) {
5674 bool isAeTrigger = (trigger.metadataTag == ANDROID_CONTROL_AE_PRECAPTURE_ID);
5675 uint32_t triggerId = static_cast<uint32_t>(trigger.entryValue);
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07005676 if (isAeTrigger) {
5677 request->mResultExtras.precaptureTriggerId = triggerId;
5678 mCurrentPreCaptureTriggerId = triggerId;
5679 } else {
5680 request->mResultExtras.afTriggerId = triggerId;
5681 mCurrentAfTriggerId = triggerId;
5682 }
Emilian Peev7e25e5e2017-04-07 15:48:49 +01005683 continue;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07005684 }
5685
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005686 camera_metadata_entry entry = metadata.find(tag);
5687
5688 if (entry.count > 0) {
5689 /**
5690 * Already has an entry for this trigger in the request.
5691 * Rewrite it with our requested trigger value.
5692 */
5693 RequestTrigger oldTrigger = trigger;
5694
5695 oldTrigger.entryValue = entry.data.u8[0];
5696
5697 mTriggerReplacedMap.add(tag, oldTrigger);
5698 } else {
5699 /**
5700 * More typical, no trigger entry, so we just add it
5701 */
5702 mTriggerRemovedMap.add(tag, trigger);
5703 }
5704
5705 status_t res;
5706
5707 switch (trigger.getTagType()) {
5708 case TYPE_BYTE: {
5709 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
5710 res = metadata.update(tag,
5711 &entryValue,
5712 /*count*/1);
5713 break;
5714 }
5715 case TYPE_INT32:
5716 res = metadata.update(tag,
5717 &trigger.entryValue,
5718 /*count*/1);
5719 break;
5720 default:
5721 ALOGE("%s: Type not supported: 0x%x",
5722 __FUNCTION__,
5723 trigger.getTagType());
5724 return INVALID_OPERATION;
5725 }
5726
5727 if (res != OK) {
5728 ALOGE("%s: Failed to update request metadata with trigger tag %s"
5729 ", value %d", __FUNCTION__, trigger.getTagName(),
5730 trigger.entryValue);
5731 return res;
5732 }
5733
5734 ALOGV("%s: Mixed in trigger %s, value %d", __FUNCTION__,
5735 trigger.getTagName(),
5736 trigger.entryValue);
5737 }
5738
5739 mTriggerMap.clear();
5740
5741 return count;
5742}
5743
5744status_t Camera3Device::RequestThread::removeTriggers(
5745 const sp<CaptureRequest> &request) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005746 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005747 Mutex::Autolock al(mTriggerMutex);
5748
Emilian Peevaebbe412018-01-15 13:53:24 +00005749 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005750
5751 /**
5752 * Replace all old entries with their old values.
5753 */
5754 for (size_t i = 0; i < mTriggerReplacedMap.size(); ++i) {
5755 RequestTrigger trigger = mTriggerReplacedMap.valueAt(i);
5756
5757 status_t res;
5758
5759 uint32_t tag = trigger.metadataTag;
5760 switch (trigger.getTagType()) {
5761 case TYPE_BYTE: {
5762 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
5763 res = metadata.update(tag,
5764 &entryValue,
5765 /*count*/1);
5766 break;
5767 }
5768 case TYPE_INT32:
5769 res = metadata.update(tag,
5770 &trigger.entryValue,
5771 /*count*/1);
5772 break;
5773 default:
5774 ALOGE("%s: Type not supported: 0x%x",
5775 __FUNCTION__,
5776 trigger.getTagType());
5777 return INVALID_OPERATION;
5778 }
5779
5780 if (res != OK) {
5781 ALOGE("%s: Failed to restore request metadata with trigger tag %s"
5782 ", trigger value %d", __FUNCTION__,
5783 trigger.getTagName(), trigger.entryValue);
5784 return res;
5785 }
5786 }
5787 mTriggerReplacedMap.clear();
5788
5789 /**
5790 * Remove all new entries.
5791 */
5792 for (size_t i = 0; i < mTriggerRemovedMap.size(); ++i) {
5793 RequestTrigger trigger = mTriggerRemovedMap.valueAt(i);
5794 status_t res = metadata.erase(trigger.metadataTag);
5795
5796 if (res != OK) {
5797 ALOGE("%s: Failed to erase metadata with trigger tag %s"
5798 ", trigger value %d", __FUNCTION__,
5799 trigger.getTagName(), trigger.entryValue);
5800 return res;
5801 }
5802 }
5803 mTriggerRemovedMap.clear();
5804
5805 return OK;
5806}
5807
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04005808status_t Camera3Device::RequestThread::addFakeTriggerIds(
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005809 const sp<CaptureRequest> &request) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08005810 // Trigger ID 0 had special meaning in the HAL2 spec, so avoid it here
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04005811 static const int32_t fakeTriggerId = 1;
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005812 status_t res;
5813
Emilian Peevaebbe412018-01-15 13:53:24 +00005814 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005815
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04005816 // If AF trigger is active, insert a fake AF trigger ID if none already
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005817 // exists
5818 camera_metadata_entry afTrigger = metadata.find(ANDROID_CONTROL_AF_TRIGGER);
5819 camera_metadata_entry afId = metadata.find(ANDROID_CONTROL_AF_TRIGGER_ID);
5820 if (afTrigger.count > 0 &&
5821 afTrigger.data.u8[0] != ANDROID_CONTROL_AF_TRIGGER_IDLE &&
5822 afId.count == 0) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04005823 res = metadata.update(ANDROID_CONTROL_AF_TRIGGER_ID, &fakeTriggerId, 1);
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005824 if (res != OK) return res;
5825 }
5826
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04005827 // If AE precapture trigger is active, insert a fake precapture trigger ID
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005828 // if none already exists
5829 camera_metadata_entry pcTrigger =
5830 metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER);
5831 camera_metadata_entry pcId = metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_ID);
5832 if (pcTrigger.count > 0 &&
5833 pcTrigger.data.u8[0] != ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_IDLE &&
5834 pcId.count == 0) {
5835 res = metadata.update(ANDROID_CONTROL_AE_PRECAPTURE_ID,
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04005836 &fakeTriggerId, 1);
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005837 if (res != OK) return res;
5838 }
5839
5840 return OK;
5841}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005842
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005843bool Camera3Device::RequestThread::overrideAutoRotateAndCrop(
5844 const sp<CaptureRequest> &request) {
5845 ATRACE_CALL();
5846
5847 if (request->mRotateAndCropAuto) {
5848 Mutex::Autolock l(mTriggerMutex);
5849 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
5850
5851 auto rotateAndCropEntry = metadata.find(ANDROID_SCALER_ROTATE_AND_CROP);
5852 if (rotateAndCropEntry.count > 0) {
5853 if (rotateAndCropEntry.data.u8[0] == mRotateAndCropOverride) {
5854 return false;
5855 } else {
5856 rotateAndCropEntry.data.u8[0] = mRotateAndCropOverride;
5857 return true;
5858 }
5859 } else {
5860 uint8_t rotateAndCrop_u8 = mRotateAndCropOverride;
5861 metadata.update(ANDROID_SCALER_ROTATE_AND_CROP,
5862 &rotateAndCrop_u8, 1);
5863 return true;
5864 }
5865 }
5866 return false;
5867}
5868
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005869bool Camera3Device::RequestThread::overrideTestPattern(
5870 const sp<CaptureRequest> &request) {
5871 ATRACE_CALL();
5872
Eino-Ville Talvala1646c3c2021-07-29 13:48:40 -07005873 if (!mSupportCameraMute) return false;
Eino-Ville Talvalac2459842021-07-22 16:36:36 -07005874
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005875 Mutex::Autolock l(mTriggerMutex);
5876
5877 bool changed = false;
5878
5879 int32_t testPatternMode = request->mOriginalTestPatternMode;
5880 int32_t testPatternData[4] = {
5881 request->mOriginalTestPatternData[0],
5882 request->mOriginalTestPatternData[1],
5883 request->mOriginalTestPatternData[2],
5884 request->mOriginalTestPatternData[3]
5885 };
5886
Eino-Ville Talvala11afe4f2021-05-27 14:45:31 -07005887 if (mCameraMute != ANDROID_SENSOR_TEST_PATTERN_MODE_OFF) {
5888 testPatternMode = mCameraMute;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005889 testPatternData[0] = 0;
5890 testPatternData[1] = 0;
5891 testPatternData[2] = 0;
5892 testPatternData[3] = 0;
5893 }
5894
5895 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
5896
5897 auto testPatternEntry = metadata.find(ANDROID_SENSOR_TEST_PATTERN_MODE);
5898 if (testPatternEntry.count > 0) {
5899 if (testPatternEntry.data.i32[0] != testPatternMode) {
5900 testPatternEntry.data.i32[0] = testPatternMode;
5901 changed = true;
5902 }
5903 } else {
5904 metadata.update(ANDROID_SENSOR_TEST_PATTERN_MODE,
5905 &testPatternMode, 1);
5906 changed = true;
5907 }
5908
5909 auto testPatternColor = metadata.find(ANDROID_SENSOR_TEST_PATTERN_DATA);
Eino-Ville Talvalac2459842021-07-22 16:36:36 -07005910 if (testPatternColor.count >= 4) {
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005911 for (size_t i = 0; i < 4; i++) {
Eino-Ville Talvalac2459842021-07-22 16:36:36 -07005912 if (testPatternColor.data.i32[i] != testPatternData[i]) {
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005913 testPatternColor.data.i32[i] = testPatternData[i];
5914 changed = true;
5915 }
5916 }
5917 } else {
5918 metadata.update(ANDROID_SENSOR_TEST_PATTERN_DATA,
Eino-Ville Talvalac2459842021-07-22 16:36:36 -07005919 testPatternData, 4);
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005920 changed = true;
5921 }
5922
5923 return changed;
5924}
5925
Cliff Wuc2ad9c82021-04-21 00:58:58 +08005926status_t Camera3Device::RequestThread::setHalInterface(
5927 sp<HalInterface> newHalInterface) {
5928 if (newHalInterface.get() == nullptr) {
5929 ALOGE("%s: The newHalInterface does not exist!", __FUNCTION__);
5930 return DEAD_OBJECT;
5931 }
5932
5933 mInterface = newHalInterface;
5934
5935 return OK;
5936}
5937
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005938/**
5939 * PreparerThread inner class methods
5940 */
5941
5942Camera3Device::PreparerThread::PreparerThread() :
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07005943 Thread(/*canCallJava*/false), mListener(nullptr),
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005944 mActive(false), mCancelNow(false), mCurrentMaxCount(0), mCurrentPrepareComplete(false) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005945}
5946
5947Camera3Device::PreparerThread::~PreparerThread() {
5948 Thread::requestExitAndWait();
5949 if (mCurrentStream != nullptr) {
5950 mCurrentStream->cancelPrepare();
5951 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
5952 mCurrentStream.clear();
5953 }
5954 clear();
5955}
5956
Ruben Brunkc78ac262015-08-13 17:58:46 -07005957status_t Camera3Device::PreparerThread::prepare(int maxCount, sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005958 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005959 status_t res;
5960
5961 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005962 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005963
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07005964 res = stream->startPrepare(maxCount, true /*blockRequest*/);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005965 if (res == OK) {
5966 // No preparation needed, fire listener right off
5967 ALOGV("%s: Stream %d already prepared", __FUNCTION__, stream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005968 if (listener != NULL) {
5969 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005970 }
5971 return OK;
5972 } else if (res != NOT_ENOUGH_DATA) {
5973 return res;
5974 }
5975
5976 // Need to prepare, start up thread if necessary
5977 if (!mActive) {
5978 // mRunning will change to false before the thread fully shuts down, so wait to be sure it
5979 // isn't running
5980 Thread::requestExitAndWait();
5981 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
5982 if (res != OK) {
5983 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__, res, strerror(-res));
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005984 if (listener != NULL) {
5985 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005986 }
5987 return res;
5988 }
5989 mCancelNow = false;
5990 mActive = true;
5991 ALOGV("%s: Preparer stream started", __FUNCTION__);
5992 }
5993
5994 // queue up the work
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005995 mPendingStreams.emplace(maxCount, stream);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005996 ALOGV("%s: Stream %d queued for preparing", __FUNCTION__, stream->getId());
5997
5998 return OK;
5999}
6000
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006001void Camera3Device::PreparerThread::pause() {
6002 ATRACE_CALL();
6003
6004 Mutex::Autolock l(mLock);
6005
6006 std::unordered_map<int, sp<camera3::Camera3StreamInterface> > pendingStreams;
6007 pendingStreams.insert(mPendingStreams.begin(), mPendingStreams.end());
6008 sp<camera3::Camera3StreamInterface> currentStream = mCurrentStream;
6009 int currentMaxCount = mCurrentMaxCount;
6010 mPendingStreams.clear();
6011 mCancelNow = true;
6012 while (mActive) {
6013 auto res = mThreadActiveSignal.waitRelative(mLock, kActiveTimeout);
6014 if (res == TIMED_OUT) {
6015 ALOGE("%s: Timed out waiting on prepare thread!", __FUNCTION__);
6016 return;
6017 } else if (res != OK) {
6018 ALOGE("%s: Encountered an error: %d waiting on prepare thread!", __FUNCTION__, res);
6019 return;
6020 }
6021 }
6022
6023 //Check whether the prepare thread was able to complete the current
6024 //stream. In case work is still pending emplace it along with the rest
6025 //of the streams in the pending list.
6026 if (currentStream != nullptr) {
6027 if (!mCurrentPrepareComplete) {
6028 pendingStreams.emplace(currentMaxCount, currentStream);
6029 }
6030 }
6031
6032 mPendingStreams.insert(pendingStreams.begin(), pendingStreams.end());
6033 for (const auto& it : mPendingStreams) {
6034 it.second->cancelPrepare();
6035 }
6036}
6037
6038status_t Camera3Device::PreparerThread::resume() {
6039 ATRACE_CALL();
6040 status_t res;
6041
6042 Mutex::Autolock l(mLock);
6043 sp<NotificationListener> listener = mListener.promote();
6044
6045 if (mActive) {
6046 ALOGE("%s: Trying to resume an already active prepare thread!", __FUNCTION__);
6047 return NO_INIT;
6048 }
6049
6050 auto it = mPendingStreams.begin();
6051 for (; it != mPendingStreams.end();) {
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07006052 res = it->second->startPrepare(it->first, true /*blockRequest*/);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006053 if (res == OK) {
6054 if (listener != NULL) {
6055 listener->notifyPrepared(it->second->getId());
6056 }
6057 it = mPendingStreams.erase(it);
6058 } else if (res != NOT_ENOUGH_DATA) {
6059 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__,
6060 res, strerror(-res));
6061 it = mPendingStreams.erase(it);
6062 } else {
6063 it++;
6064 }
6065 }
6066
6067 if (mPendingStreams.empty()) {
6068 return OK;
6069 }
6070
6071 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
6072 if (res != OK) {
6073 ALOGE("%s: Unable to start preparer stream: %d (%s)",
6074 __FUNCTION__, res, strerror(-res));
6075 return res;
6076 }
6077 mCancelNow = false;
6078 mActive = true;
6079 ALOGV("%s: Preparer stream started", __FUNCTION__);
6080
6081 return OK;
6082}
6083
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006084status_t Camera3Device::PreparerThread::clear() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07006085 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006086 Mutex::Autolock l(mLock);
6087
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006088 for (const auto& it : mPendingStreams) {
6089 it.second->cancelPrepare();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006090 }
6091 mPendingStreams.clear();
6092 mCancelNow = true;
6093
6094 return OK;
6095}
6096
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006097void Camera3Device::PreparerThread::setNotificationListener(wp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07006098 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006099 Mutex::Autolock l(mLock);
6100 mListener = listener;
6101}
6102
6103bool Camera3Device::PreparerThread::threadLoop() {
6104 status_t res;
6105 {
6106 Mutex::Autolock l(mLock);
6107 if (mCurrentStream == nullptr) {
6108 // End thread if done with work
6109 if (mPendingStreams.empty()) {
6110 ALOGV("%s: Preparer stream out of work", __FUNCTION__);
6111 // threadLoop _must not_ re-acquire mLock after it sets mActive to false; would
6112 // cause deadlock with prepare()'s requestExitAndWait triggered by !mActive.
6113 mActive = false;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006114 mThreadActiveSignal.signal();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006115 return false;
6116 }
6117
6118 // Get next stream to prepare
6119 auto it = mPendingStreams.begin();
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006120 mCurrentStream = it->second;
6121 mCurrentMaxCount = it->first;
6122 mCurrentPrepareComplete = false;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006123 mPendingStreams.erase(it);
6124 ATRACE_ASYNC_BEGIN("stream prepare", mCurrentStream->getId());
6125 ALOGV("%s: Preparing stream %d", __FUNCTION__, mCurrentStream->getId());
6126 } else if (mCancelNow) {
6127 mCurrentStream->cancelPrepare();
6128 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
6129 ALOGV("%s: Cancelling stream %d prepare", __FUNCTION__, mCurrentStream->getId());
6130 mCurrentStream.clear();
6131 mCancelNow = false;
6132 return true;
6133 }
6134 }
6135
6136 res = mCurrentStream->prepareNextBuffer();
6137 if (res == NOT_ENOUGH_DATA) return true;
6138 if (res != OK) {
6139 // Something bad happened; try to recover by cancelling prepare and
6140 // signalling listener anyway
6141 ALOGE("%s: Stream %d returned error %d (%s) during prepare", __FUNCTION__,
6142 mCurrentStream->getId(), res, strerror(-res));
6143 mCurrentStream->cancelPrepare();
6144 }
6145
6146 // This stream has finished, notify listener
6147 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006148 sp<NotificationListener> listener = mListener.promote();
6149 if (listener != NULL) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006150 ALOGV("%s: Stream %d prepare done, signaling listener", __FUNCTION__,
6151 mCurrentStream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006152 listener->notifyPrepared(mCurrentStream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006153 }
6154
6155 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
6156 mCurrentStream.clear();
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006157 mCurrentPrepareComplete = true;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006158
6159 return true;
6160}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07006161
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006162status_t Camera3Device::RequestBufferStateMachine::initialize(
6163 sp<camera3::StatusTracker> statusTracker) {
6164 if (statusTracker == nullptr) {
6165 ALOGE("%s: statusTracker is null", __FUNCTION__);
6166 return BAD_VALUE;
6167 }
6168
6169 std::lock_guard<std::mutex> lock(mLock);
6170 mStatusTracker = statusTracker;
Yin-Chia Yeh87b3ec02019-06-03 10:44:39 -07006171 mRequestBufferStatusId = statusTracker->addComponent("BufferRequestSM");
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006172 return OK;
6173}
6174
6175bool Camera3Device::RequestBufferStateMachine::startRequestBuffer() {
6176 std::lock_guard<std::mutex> lock(mLock);
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08006177 if (mStatus == RB_STATUS_READY || mStatus == RB_STATUS_PENDING_STOP) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006178 mRequestBufferOngoing = true;
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08006179 notifyTrackerLocked(/*active*/true);
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006180 return true;
6181 }
6182 return false;
6183}
6184
6185void Camera3Device::RequestBufferStateMachine::endRequestBuffer() {
6186 std::lock_guard<std::mutex> lock(mLock);
6187 if (!mRequestBufferOngoing) {
6188 ALOGE("%s called without a successful startRequestBuffer call first!", __FUNCTION__);
6189 return;
6190 }
6191 mRequestBufferOngoing = false;
6192 if (mStatus == RB_STATUS_PENDING_STOP) {
6193 checkSwitchToStopLocked();
6194 }
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08006195 notifyTrackerLocked(/*active*/false);
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006196}
6197
6198void Camera3Device::RequestBufferStateMachine::onStreamsConfigured() {
6199 std::lock_guard<std::mutex> lock(mLock);
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006200 mSwitchedToOffline = false;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006201 mStatus = RB_STATUS_READY;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006202 return;
6203}
6204
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08006205void Camera3Device::RequestBufferStateMachine::onSubmittingRequest() {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006206 std::lock_guard<std::mutex> lock(mLock);
6207 mRequestThreadPaused = false;
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08006208 // inflight map register actually happens in prepareHalRequest now, but it is close enough
6209 // approximation.
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006210 mInflightMapEmpty = false;
6211 if (mStatus == RB_STATUS_STOPPED) {
6212 mStatus = RB_STATUS_READY;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006213 }
6214 return;
6215}
6216
6217void Camera3Device::RequestBufferStateMachine::onRequestThreadPaused() {
6218 std::lock_guard<std::mutex> lock(mLock);
6219 mRequestThreadPaused = true;
6220 if (mStatus == RB_STATUS_PENDING_STOP) {
6221 checkSwitchToStopLocked();
6222 }
6223 return;
6224}
6225
6226void Camera3Device::RequestBufferStateMachine::onInflightMapEmpty() {
6227 std::lock_guard<std::mutex> lock(mLock);
6228 mInflightMapEmpty = true;
6229 if (mStatus == RB_STATUS_PENDING_STOP) {
6230 checkSwitchToStopLocked();
6231 }
6232 return;
6233}
6234
6235void Camera3Device::RequestBufferStateMachine::onWaitUntilIdle() {
6236 std::lock_guard<std::mutex> lock(mLock);
6237 if (!checkSwitchToStopLocked()) {
6238 mStatus = RB_STATUS_PENDING_STOP;
6239 }
6240 return;
6241}
6242
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006243bool Camera3Device::RequestBufferStateMachine::onSwitchToOfflineSuccess() {
6244 std::lock_guard<std::mutex> lock(mLock);
6245 if (mRequestBufferOngoing) {
6246 ALOGE("%s: HAL must not be requesting buffer after HAL returns switchToOffline!",
6247 __FUNCTION__);
6248 return false;
6249 }
6250 mSwitchedToOffline = true;
6251 mInflightMapEmpty = true;
6252 mRequestThreadPaused = true;
6253 mStatus = RB_STATUS_STOPPED;
6254 return true;
6255}
6256
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006257void Camera3Device::RequestBufferStateMachine::notifyTrackerLocked(bool active) {
6258 sp<StatusTracker> statusTracker = mStatusTracker.promote();
6259 if (statusTracker != nullptr) {
6260 if (active) {
6261 statusTracker->markComponentActive(mRequestBufferStatusId);
6262 } else {
6263 statusTracker->markComponentIdle(mRequestBufferStatusId, Fence::NO_FENCE);
6264 }
6265 }
6266}
6267
6268bool Camera3Device::RequestBufferStateMachine::checkSwitchToStopLocked() {
6269 if (mInflightMapEmpty && mRequestThreadPaused && !mRequestBufferOngoing) {
6270 mStatus = RB_STATUS_STOPPED;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006271 return true;
6272 }
6273 return false;
6274}
6275
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006276bool Camera3Device::startRequestBuffer() {
6277 return mRequestBufferSM.startRequestBuffer();
6278}
Shuzhen Wang268a1362018-10-16 16:32:59 -07006279
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006280void Camera3Device::endRequestBuffer() {
6281 mRequestBufferSM.endRequestBuffer();
6282}
Shuzhen Wang268a1362018-10-16 16:32:59 -07006283
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006284nsecs_t Camera3Device::getWaitDuration() {
6285 return kBaseGetBufferWait + getExpectedInFlightDuration();
6286}
Shuzhen Wang268a1362018-10-16 16:32:59 -07006287
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006288void Camera3Device::getInflightBufferKeys(std::vector<std::pair<int32_t, int32_t>>* out) {
6289 mInterface->getInflightBufferKeys(out);
6290}
Shuzhen Wang268a1362018-10-16 16:32:59 -07006291
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006292void Camera3Device::getInflightRequestBufferKeys(std::vector<uint64_t>* out) {
6293 mInterface->getInflightRequestBufferKeys(out);
6294}
Shuzhen Wang268a1362018-10-16 16:32:59 -07006295
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006296std::vector<sp<Camera3StreamInterface>> Camera3Device::getAllStreams() {
6297 std::vector<sp<Camera3StreamInterface>> ret;
6298 bool hasInputStream = mInputStream != nullptr;
6299 ret.reserve(mOutputStreams.size() + mDeletedStreams.size() + ((hasInputStream) ? 1 : 0));
6300 if (hasInputStream) {
6301 ret.push_back(mInputStream);
Shuzhen Wang268a1362018-10-16 16:32:59 -07006302 }
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006303 for (size_t i = 0; i < mOutputStreams.size(); i++) {
6304 ret.push_back(mOutputStreams[i]);
6305 }
6306 for (size_t i = 0; i < mDeletedStreams.size(); i++) {
6307 ret.push_back(mDeletedStreams[i]);
6308 }
6309 return ret;
Shuzhen Wang268a1362018-10-16 16:32:59 -07006310}
6311
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006312status_t Camera3Device::switchToOffline(
6313 const std::vector<int32_t>& streamsToKeep,
6314 /*out*/ sp<CameraOfflineSessionBase>* session) {
6315 ATRACE_CALL();
6316 if (session == nullptr) {
6317 ALOGE("%s: session must not be null", __FUNCTION__);
6318 return BAD_VALUE;
6319 }
6320
6321 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006322
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006323 bool hasInputStream = mInputStream != nullptr;
6324 int32_t inputStreamId = hasInputStream ? mInputStream->getId() : -1;
6325 bool inputStreamSupportsOffline = hasInputStream ?
6326 mInputStream->getOfflineProcessingSupport() : false;
6327 auto outputStreamIds = mOutputStreams.getStreamIds();
6328 auto streamIds = outputStreamIds;
6329 if (hasInputStream) {
6330 streamIds.push_back(mInputStream->getId());
6331 }
6332
6333 // Check all streams in streamsToKeep supports offline mode
6334 for (auto id : streamsToKeep) {
6335 if (std::find(streamIds.begin(), streamIds.end(), id) == streamIds.end()) {
6336 ALOGE("%s: Unknown stream ID %d", __FUNCTION__, id);
6337 return BAD_VALUE;
6338 } else if (id == inputStreamId) {
6339 if (!inputStreamSupportsOffline) {
6340 ALOGE("%s: input stream %d cannot be switched to offline",
6341 __FUNCTION__, id);
6342 return BAD_VALUE;
6343 }
6344 } else {
6345 sp<camera3::Camera3OutputStreamInterface> stream = mOutputStreams.get(id);
6346 if (!stream->getOfflineProcessingSupport()) {
6347 ALOGE("%s: output stream %d cannot be switched to offline",
6348 __FUNCTION__, id);
6349 return BAD_VALUE;
6350 }
6351 }
6352 }
6353
6354 // TODO: block surface sharing and surface group streams until we can support them
6355
6356 // Stop repeating request, wait until all remaining requests are submitted, then call into
6357 // HAL switchToOffline
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006358 hardware::camera::device::V3_6::CameraOfflineSessionInfo offlineSessionInfo;
6359 sp<hardware::camera::device::V3_6::ICameraOfflineSession> offlineSession;
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006360 camera3::BufferRecords bufferRecords;
6361 status_t ret = mRequestThread->switchToOffline(
6362 streamsToKeep, &offlineSessionInfo, &offlineSession, &bufferRecords);
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006363
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006364 if (ret != OK) {
6365 SET_ERR("Switch to offline failed: %s (%d)", strerror(-ret), ret);
6366 return ret;
6367 }
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006368
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006369 bool succ = mRequestBufferSM.onSwitchToOfflineSuccess();
6370 if (!succ) {
6371 SET_ERR("HAL must not be calling requestStreamBuffers call");
6372 // TODO: block ALL callbacks from HAL till app configured new streams?
6373 return UNKNOWN_ERROR;
6374 }
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006375
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006376 // Verify offlineSessionInfo
6377 std::vector<int32_t> offlineStreamIds;
6378 offlineStreamIds.reserve(offlineSessionInfo.offlineStreams.size());
6379 for (auto offlineStream : offlineSessionInfo.offlineStreams) {
6380 // verify stream IDs
6381 int32_t id = offlineStream.id;
6382 if (std::find(streamIds.begin(), streamIds.end(), id) == streamIds.end()) {
6383 SET_ERR("stream ID %d not found!", id);
6384 return UNKNOWN_ERROR;
6385 }
6386
6387 // When not using HAL buf manager, only allow streams requested by app to be preserved
6388 if (!mUseHalBufManager) {
6389 if (std::find(streamsToKeep.begin(), streamsToKeep.end(), id) == streamsToKeep.end()) {
6390 SET_ERR("stream ID %d must not be switched to offline!", id);
6391 return UNKNOWN_ERROR;
6392 }
6393 }
6394
6395 offlineStreamIds.push_back(id);
6396 sp<Camera3StreamInterface> stream = (id == inputStreamId) ?
6397 static_cast<sp<Camera3StreamInterface>>(mInputStream) :
6398 static_cast<sp<Camera3StreamInterface>>(mOutputStreams.get(id));
6399 // Verify number of outstanding buffers
6400 if (stream->getOutstandingBuffersCount() != offlineStream.numOutstandingBuffers) {
6401 SET_ERR("Offline stream %d # of remaining buffer mismatch: (%zu,%d) (service/HAL)",
6402 id, stream->getOutstandingBuffersCount(), offlineStream.numOutstandingBuffers);
6403 return UNKNOWN_ERROR;
6404 }
6405 }
6406
6407 // Verify all streams to be deleted don't have any outstanding buffers
6408 if (hasInputStream && std::find(offlineStreamIds.begin(), offlineStreamIds.end(),
6409 inputStreamId) == offlineStreamIds.end()) {
6410 if (mInputStream->hasOutstandingBuffers()) {
6411 SET_ERR("Input stream %d still has %zu outstanding buffer!",
6412 inputStreamId, mInputStream->getOutstandingBuffersCount());
6413 return UNKNOWN_ERROR;
6414 }
6415 }
6416
6417 for (const auto& outStreamId : outputStreamIds) {
6418 if (std::find(offlineStreamIds.begin(), offlineStreamIds.end(),
6419 outStreamId) == offlineStreamIds.end()) {
6420 auto outStream = mOutputStreams.get(outStreamId);
6421 if (outStream->hasOutstandingBuffers()) {
6422 SET_ERR("Output stream %d still has %zu outstanding buffer!",
6423 outStreamId, outStream->getOutstandingBuffersCount());
6424 return UNKNOWN_ERROR;
6425 }
6426 }
6427 }
6428
6429 InFlightRequestMap offlineReqs;
6430 // Verify inflight requests and their pending buffers
6431 {
6432 std::lock_guard<std::mutex> l(mInFlightLock);
6433 for (auto offlineReq : offlineSessionInfo.offlineRequests) {
6434 int idx = mInFlightMap.indexOfKey(offlineReq.frameNumber);
6435 if (idx == NAME_NOT_FOUND) {
6436 SET_ERR("Offline request frame number %d not found!", offlineReq.frameNumber);
6437 return UNKNOWN_ERROR;
6438 }
6439
6440 const auto& inflightReq = mInFlightMap.valueAt(idx);
6441 // TODO: check specific stream IDs
6442 size_t numBuffersLeft = static_cast<size_t>(inflightReq.numBuffersLeft);
6443 if (numBuffersLeft != offlineReq.pendingStreams.size()) {
6444 SET_ERR("Offline request # of remaining buffer mismatch: (%d,%d) (service/HAL)",
6445 inflightReq.numBuffersLeft, offlineReq.pendingStreams.size());
6446 return UNKNOWN_ERROR;
6447 }
6448 offlineReqs.add(offlineReq.frameNumber, inflightReq);
6449 }
6450 }
6451
6452 // Create Camera3OfflineSession and transfer object ownership
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006453 // (streams, inflight requests, buffer caches)
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006454 camera3::StreamSet offlineStreamSet;
6455 sp<camera3::Camera3Stream> inputStream;
6456 for (auto offlineStream : offlineSessionInfo.offlineStreams) {
6457 int32_t id = offlineStream.id;
6458 if (mInputStream != nullptr && id == mInputStream->getId()) {
6459 inputStream = mInputStream;
6460 } else {
6461 offlineStreamSet.add(id, mOutputStreams.get(id));
6462 }
6463 }
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006464
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006465 // TODO: check if we need to lock before copying states
6466 // though technically no other thread should be talking to Camera3Device at this point
6467 Camera3OfflineStates offlineStates(
6468 mTagMonitor, mVendorTagId, mUseHalBufManager, mNeedFixupMonochromeTags,
Shuzhen Wangb7b42652020-05-07 11:59:02 -07006469 mUsePartialResult, mNumPartialResults, mLastCompletedRegularFrameNumber,
6470 mLastCompletedReprocessFrameNumber, mLastCompletedZslFrameNumber,
6471 mNextResultFrameNumber, mNextReprocessResultFrameNumber,
6472 mNextZslStillResultFrameNumber, mNextShutterFrameNumber,
6473 mNextReprocessShutterFrameNumber, mNextZslStillShutterFrameNumber,
6474 mDeviceInfo, mPhysicalDeviceInfoMap, mDistortionMappers,
6475 mZoomRatioMappers, mRotateAndCropMappers);
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006476
6477 *session = new Camera3OfflineSession(mId, inputStream, offlineStreamSet,
6478 std::move(bufferRecords), offlineReqs, offlineStates, offlineSession);
6479
6480 // Delete all streams that has been transferred to offline session
6481 Mutex::Autolock l(mLock);
6482 for (auto offlineStream : offlineSessionInfo.offlineStreams) {
6483 int32_t id = offlineStream.id;
6484 if (mInputStream != nullptr && id == mInputStream->getId()) {
6485 mInputStream.clear();
6486 } else {
6487 mOutputStreams.remove(id);
6488 }
6489 }
6490
6491 // disconnect all other streams and switch to UNCONFIGURED state
6492 if (mInputStream != nullptr) {
6493 ret = mInputStream->disconnect();
6494 if (ret != OK) {
6495 SET_ERR_L("disconnect input stream failed!");
6496 return UNKNOWN_ERROR;
6497 }
6498 }
6499
6500 for (auto streamId : mOutputStreams.getStreamIds()) {
6501 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
6502 ret = stream->disconnect();
6503 if (ret != OK) {
6504 SET_ERR_L("disconnect output stream %d failed!", streamId);
6505 return UNKNOWN_ERROR;
6506 }
6507 }
6508
6509 mInputStream.clear();
6510 mOutputStreams.clear();
6511 mNeedConfig = true;
6512 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
6513 mOperatingMode = NO_MODE;
6514 mIsConstrainedHighSpeedConfiguration = false;
Emilian Peevc0fe54c2020-03-11 14:05:07 -07006515 mRequestThread->clearPreviousRequest();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006516
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006517 return OK;
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006518 // TO be done by CameraDeviceClient/Camera3OfflineSession
6519 // register the offline client to camera service
6520 // Setup result passthing threads etc
6521 // Initialize offline session so HAL can start sending callback to it (result Fmq)
6522 // TODO: check how many onIdle callback will be sent
6523 // Java side to make sure the CameraCaptureSession is properly closed
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006524}
6525
Emilian Peevcc0b7952020-01-07 13:54:47 -08006526void Camera3Device::getOfflineStreamIds(std::vector<int> *offlineStreamIds) {
6527 ATRACE_CALL();
6528
6529 if (offlineStreamIds == nullptr) {
6530 return;
6531 }
6532
6533 Mutex::Autolock il(mInterfaceLock);
6534
6535 auto streamIds = mOutputStreams.getStreamIds();
6536 bool hasInputStream = mInputStream != nullptr;
6537 if (hasInputStream && mInputStream->getOfflineProcessingSupport()) {
6538 offlineStreamIds->push_back(mInputStream->getId());
6539 }
6540
6541 for (const auto & streamId : streamIds) {
6542 sp<camera3::Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
6543 // Streams that use the camera buffer manager are currently not supported in
6544 // offline mode
6545 if (stream->getOfflineProcessingSupport() &&
6546 (stream->getStreamSetId() == CAMERA3_STREAM_SET_ID_INVALID)) {
6547 offlineStreamIds->push_back(streamId);
6548 }
6549 }
6550}
6551
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08006552status_t Camera3Device::setRotateAndCropAutoBehavior(
6553 camera_metadata_enum_android_scaler_rotate_and_crop_t rotateAndCropValue) {
6554 ATRACE_CALL();
6555 Mutex::Autolock il(mInterfaceLock);
6556 Mutex::Autolock l(mLock);
6557 if (mRequestThread == nullptr) {
6558 return INVALID_OPERATION;
6559 }
6560 return mRequestThread->setRotateAndCropAutoBehavior(rotateAndCropValue);
6561}
6562
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08006563bool Camera3Device::supportsCameraMute() {
6564 Mutex::Autolock il(mInterfaceLock);
6565 Mutex::Autolock l(mLock);
6566
6567 return mSupportCameraMute;
6568}
6569
6570status_t Camera3Device::setCameraMute(bool enabled) {
6571 ATRACE_CALL();
6572 Mutex::Autolock il(mInterfaceLock);
6573 Mutex::Autolock l(mLock);
6574
6575 if (mRequestThread == nullptr || !mSupportCameraMute) {
6576 return INVALID_OPERATION;
6577 }
Eino-Ville Talvala11afe4f2021-05-27 14:45:31 -07006578 int32_t muteMode =
6579 !enabled ? ANDROID_SENSOR_TEST_PATTERN_MODE_OFF :
6580 mSupportTestPatternSolidColor ? ANDROID_SENSOR_TEST_PATTERN_MODE_SOLID_COLOR :
6581 ANDROID_SENSOR_TEST_PATTERN_MODE_BLACK;
6582 return mRequestThread->setCameraMute(muteMode);
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08006583}
6584
Cliff Wuc2ad9c82021-04-21 00:58:58 +08006585status_t Camera3Device::injectCamera(const String8& injectedCamId,
6586 sp<CameraProviderManager> manager) {
6587 ALOGI("%s Injection camera: injectedCamId = %s", __FUNCTION__, injectedCamId.string());
6588 ATRACE_CALL();
6589 Mutex::Autolock il(mInterfaceLock);
6590
6591 status_t res = NO_ERROR;
6592 if (mInjectionMethods->isInjecting()) {
6593 if (injectedCamId == mInjectionMethods->getInjectedCamId()) {
6594 return OK;
6595 } else {
6596 res = mInjectionMethods->stopInjection();
6597 if (res != OK) {
6598 ALOGE("%s: Failed to stop the injection camera! ret != NO_ERROR: %d",
6599 __FUNCTION__, res);
6600 return res;
6601 }
6602 }
6603 }
6604
6605 res = mInjectionMethods->injectionInitialize(injectedCamId, manager, this);
6606 if (res != OK) {
6607 ALOGE("%s: Failed to initialize the injection camera! ret != NO_ERROR: %d",
6608 __FUNCTION__, res);
6609 return res;
6610 }
6611
6612 camera3::camera_stream_configuration injectionConfig;
6613 std::vector<uint32_t> injectionBufferSizes;
6614 mInjectionMethods->getInjectionConfig(&injectionConfig, &injectionBufferSizes);
6615 // When the second display of android is cast to the remote device, and the opened camera is
6616 // also cast to the second display, in this case, because the camera has configured the streams
6617 // at this time, we can directly call injectCamera() to replace the internal camera with
6618 // injection camera.
6619 if (mOperatingMode >= 0 && injectionConfig.num_streams > 0
6620 && injectionBufferSizes.size() > 0) {
6621 ALOGV("%s: The opened camera is directly cast to the remote device.", __FUNCTION__);
6622 res = mInjectionMethods->injectCamera(
6623 injectionConfig, injectionBufferSizes);
6624 if (res != OK) {
6625 ALOGE("Can't finish inject camera process!");
6626 return res;
6627 }
6628 }
6629
6630 return OK;
6631}
6632
6633status_t Camera3Device::stopInjection() {
6634 ALOGI("%s: Injection camera: stopInjection", __FUNCTION__);
6635 Mutex::Autolock il(mInterfaceLock);
6636 return mInjectionMethods->stopInjection();
6637}
6638
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08006639}; // namespace android