blob: 578a32fd9ae734459ed835373d1780f883f715fc [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);
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700174 }
175 }
176
Yifan Hongf79b5542017-04-11 14:44:25 -0700177 std::shared_ptr<RequestMetadataQueue> queue;
Yifan Honga640c5a2017-04-12 16:30:31 -0700178 auto requestQueueRet = session->getCaptureRequestMetadataQueue(
179 [&queue](const auto& descriptor) {
180 queue = std::make_shared<RequestMetadataQueue>(descriptor);
181 if (!queue->isValid() || queue->availableToWrite() <= 0) {
182 ALOGE("HAL returns empty request metadata fmq, not use it");
183 queue = nullptr;
184 // don't use the queue onwards.
185 }
186 });
187 if (!requestQueueRet.isOk()) {
188 ALOGE("Transaction error when getting request metadata fmq: %s, not use it",
189 requestQueueRet.description().c_str());
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -0700190 return DEAD_OBJECT;
Yifan Hongf79b5542017-04-11 14:44:25 -0700191 }
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700192
193 std::unique_ptr<ResultMetadataQueue>& resQueue = mResultMetadataQueue;
Yifan Honga640c5a2017-04-12 16:30:31 -0700194 auto resultQueueRet = session->getCaptureResultMetadataQueue(
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700195 [&resQueue](const auto& descriptor) {
196 resQueue = std::make_unique<ResultMetadataQueue>(descriptor);
197 if (!resQueue->isValid() || resQueue->availableToWrite() <= 0) {
Yifan Honga640c5a2017-04-12 16:30:31 -0700198 ALOGE("HAL returns empty result metadata fmq, not use it");
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700199 resQueue = nullptr;
200 // Don't use the resQueue onwards.
Yifan Honga640c5a2017-04-12 16:30:31 -0700201 }
202 });
203 if (!resultQueueRet.isOk()) {
204 ALOGE("Transaction error when getting result metadata queue from camera session: %s",
205 resultQueueRet.description().c_str());
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -0700206 return DEAD_OBJECT;
Yifan Honga640c5a2017-04-12 16:30:31 -0700207 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -0700208 IF_ALOGV() {
209 session->interfaceChain([](
210 ::android::hardware::hidl_vec<::android::hardware::hidl_string> interfaceChain) {
211 ALOGV("Session interface chain:");
Chih-Hung Hsieh3ef324d2018-12-11 11:48:12 -0800212 for (const auto& iface : interfaceChain) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -0700213 ALOGV(" %s", iface.c_str());
214 }
215 });
216 }
Yifan Hongf79b5542017-04-11 14:44:25 -0700217
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -0800218 camera_metadata_entry bufMgrMode =
219 mDeviceInfo.find(ANDROID_INFO_SUPPORTED_BUFFER_MANAGEMENT_VERSION);
220 if (bufMgrMode.count > 0) {
221 mUseHalBufManager = (bufMgrMode.data.u8[0] ==
222 ANDROID_INFO_SUPPORTED_BUFFER_MANAGEMENT_VERSION_HIDL_DEVICE_3_5);
223 }
224
Yin-Chia Yehb978c382019-10-30 00:22:37 -0700225 camera_metadata_entry_t capabilities = mDeviceInfo.find(ANDROID_REQUEST_AVAILABLE_CAPABILITIES);
226 for (size_t i = 0; i < capabilities.count; i++) {
227 uint8_t capability = capabilities.data.u8[i];
228 if (capability == ANDROID_REQUEST_AVAILABLE_CAPABILITIES_OFFLINE_PROCESSING) {
229 mSupportOfflineProcessing = true;
230 }
231 }
232
233 mInterface = new HalInterface(session, queue, mUseHalBufManager, mSupportOfflineProcessing);
Emilian Peev71c73a22017-03-21 16:35:51 +0000234 std::string providerType;
235 mVendorTagId = manager->getProviderTagIdLocked(mId.string());
Emilian Peevbd8c5032018-02-14 23:05:40 +0000236 mTagMonitor.initialize(mVendorTagId);
237 if (!monitorTags.isEmpty()) {
238 mTagMonitor.parseTagsToMonitor(String8(monitorTags));
239 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800240
Shuzhen Wang268a1362018-10-16 16:32:59 -0700241 // Metadata tags needs fixup for monochrome camera device version less
242 // than 3.5.
243 hardware::hidl_version maxVersion{0,0};
244 res = manager->getHighestSupportedVersion(mId.string(), &maxVersion);
245 if (res != OK) {
246 ALOGE("%s: Error in getting camera device version id: %s (%d)",
247 __FUNCTION__, strerror(-res), res);
248 return res;
249 }
250 int deviceVersion = HARDWARE_DEVICE_API_VERSION(
251 maxVersion.get_major(), maxVersion.get_minor());
252
253 bool isMonochrome = false;
Yin-Chia Yehb978c382019-10-30 00:22:37 -0700254 for (size_t i = 0; i < capabilities.count; i++) {
255 uint8_t capability = capabilities.data.u8[i];
Shuzhen Wang268a1362018-10-16 16:32:59 -0700256 if (capability == ANDROID_REQUEST_AVAILABLE_CAPABILITIES_MONOCHROME) {
257 isMonochrome = true;
258 }
259 }
260 mNeedFixupMonochromeTags = (isMonochrome && deviceVersion < CAMERA_DEVICE_API_VERSION_3_5);
261
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800262 return initializeCommonLocked();
263}
264
265status_t Camera3Device::initializeCommonLocked() {
266
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700267 /** Start up status tracker thread */
268 mStatusTracker = new StatusTracker(this);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800269 status_t res = mStatusTracker->run(String8::format("C3Dev-%s-Status", mId.string()).string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700270 if (res != OK) {
271 SET_ERR_L("Unable to start status tracking thread: %s (%d)",
272 strerror(-res), res);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800273 mInterface->close();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700274 mStatusTracker.clear();
275 return res;
276 }
277
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -0700278 /** Register in-flight map to the status tracker */
Yin-Chia Yeh87b3ec02019-06-03 10:44:39 -0700279 mInFlightStatusId = mStatusTracker->addComponent("InflightRequests");
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -0700280
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -0700281 if (mUseHalBufManager) {
282 res = mRequestBufferSM.initialize(mStatusTracker);
283 if (res != OK) {
284 SET_ERR_L("Unable to start request buffer state machine: %s (%d)",
285 strerror(-res), res);
286 mInterface->close();
287 mStatusTracker.clear();
288 return res;
289 }
290 }
291
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -0800292 /** Create buffer manager */
293 mBufferManager = new Camera3BufferManager();
294
295 Vector<int32_t> sessionParamKeys;
296 camera_metadata_entry_t sessionKeysEntry = mDeviceInfo.find(
297 ANDROID_REQUEST_AVAILABLE_SESSION_KEYS);
298 if (sessionKeysEntry.count > 0) {
299 sessionParamKeys.insertArrayAt(sessionKeysEntry.data.i32, 0, sessionKeysEntry.count);
300 }
301
Chien-Yu Chenab5135b2015-06-30 11:20:58 -0700302 /** Start up request queue thread */
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -0700303 mRequestThread = new RequestThread(
304 this, mStatusTracker, mInterface, sessionParamKeys, mUseHalBufManager);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800305 res = mRequestThread->run(String8::format("C3Dev-%s-ReqQueue", mId.string()).string());
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800306 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700307 SET_ERR_L("Unable to start request queue thread: %s (%d)",
308 strerror(-res), res);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800309 mInterface->close();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800310 mRequestThread.clear();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800311 return res;
312 }
313
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -0700314 mPreparerThread = new PreparerThread();
315
Ruben Brunk183f0562015-08-12 12:55:02 -0700316 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800317 mNextStreamId = 0;
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -0400318 mFakeStreamId = NO_STREAM;
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -0700319 mNeedConfig = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700320 mPauseStateNotify = false;
Shuzhen Wang83bff122020-11-20 15:51:39 -0800321 mIsInputStreamMultiResolution = false;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800322
Shuzhen Wangc28dccc2016-02-11 23:48:46 -0800323 // Measure the clock domain offset between camera and video/hw_composer
324 camera_metadata_entry timestampSource =
325 mDeviceInfo.find(ANDROID_SENSOR_INFO_TIMESTAMP_SOURCE);
326 if (timestampSource.count > 0 && timestampSource.data.u8[0] ==
327 ANDROID_SENSOR_INFO_TIMESTAMP_SOURCE_REALTIME) {
328 mTimestampOffset = getMonoToBoottimeOffset();
329 }
330
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -0700331 // Will the HAL be sending in early partial result metadata?
Emilian Peev08dd2452017-04-06 16:55:14 +0100332 camera_metadata_entry partialResultsCount =
333 mDeviceInfo.find(ANDROID_REQUEST_PARTIAL_RESULT_COUNT);
334 if (partialResultsCount.count > 0) {
335 mNumPartialResults = partialResultsCount.data.i32[0];
336 mUsePartialResult = (mNumPartialResults > 1);
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -0700337 }
338
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800339 bool usePrecorrectArray = DistortionMapper::isDistortionSupported(mDeviceInfo);
340 if (usePrecorrectArray) {
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -0700341 res = mDistortionMappers[mId.c_str()].setupStaticInfo(mDeviceInfo);
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -0700342 if (res != OK) {
343 SET_ERR_L("Unable to read necessary calibration fields for distortion correction");
344 return res;
345 }
346 }
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800347
Shuzhen Wang1c834da2019-12-18 11:17:03 -0800348 mZoomRatioMappers[mId.c_str()] = ZoomRatioMapper(&mDeviceInfo,
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800349 mSupportNativeZoomRatio, usePrecorrectArray);
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800350
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -0800351 if (RotateAndCropMapper::isNeeded(&mDeviceInfo)) {
352 mRotateAndCropMappers.emplace(mId.c_str(), &mDeviceInfo);
353 }
354
Eino-Ville Talvala305cec62020-11-12 14:18:17 -0800355 camera_metadata_entry_t availableTestPatternModes = mDeviceInfo.find(
356 ANDROID_SENSOR_AVAILABLE_TEST_PATTERN_MODES);
357 for (size_t i = 0; i < availableTestPatternModes.count; i++) {
Eino-Ville Talvala11afe4f2021-05-27 14:45:31 -0700358 if (availableTestPatternModes.data.i32[i] ==
359 ANDROID_SENSOR_TEST_PATTERN_MODE_SOLID_COLOR) {
Eino-Ville Talvala305cec62020-11-12 14:18:17 -0800360 mSupportCameraMute = true;
Eino-Ville Talvala11afe4f2021-05-27 14:45:31 -0700361 mSupportTestPatternSolidColor = true;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -0800362 break;
Eino-Ville Talvala11afe4f2021-05-27 14:45:31 -0700363 } else if (availableTestPatternModes.data.i32[i] ==
364 ANDROID_SENSOR_TEST_PATTERN_MODE_BLACK) {
365 mSupportCameraMute = true;
366 mSupportTestPatternSolidColor = false;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -0800367 }
368 }
369
Cliff Wuc2ad9c82021-04-21 00:58:58 +0800370 mInjectionMethods = new Camera3DeviceInjectionMethods(this);
371
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800372 return OK;
373}
374
375status_t Camera3Device::disconnect() {
Yin-Chia Yehc5248132018-08-15 12:19:20 -0700376 return disconnectImpl();
377}
378
379status_t Camera3Device::disconnectImpl() {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800380 ATRACE_CALL();
Yin-Chia Yehe1c80632016-08-08 14:48:05 -0700381 ALOGI("%s: E", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800382
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700383 status_t res = OK;
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700384 std::vector<wp<Camera3StreamInterface>> streams;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700385 {
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800386 Mutex::Autolock il(mInterfaceLock);
387 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
388 {
389 Mutex::Autolock l(mLock);
390 if (mStatus == STATUS_UNINITIALIZED) return res;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700391
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800392 if (mStatus == STATUS_ACTIVE ||
393 (mStatus == STATUS_ERROR && mRequestThread != NULL)) {
394 res = mRequestThread->clearRepeatingRequests();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700395 if (res != OK) {
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800396 SET_ERR_L("Can't stop streaming");
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700397 // Continue to close device even in case of error
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800398 } else {
399 res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
400 if (res != OK) {
401 SET_ERR_L("Timeout waiting for HAL to drain (% " PRIi64 " ns)",
402 maxExpectedDuration);
403 // Continue to close device even in case of error
404 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700405 }
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700406 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800407
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800408 if (mStatus == STATUS_ERROR) {
409 CLOGE("Shutting down in an error state");
410 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700411
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800412 if (mStatusTracker != NULL) {
413 mStatusTracker->requestExit();
414 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700415
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800416 if (mRequestThread != NULL) {
417 mRequestThread->requestExit();
418 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700419
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800420 streams.reserve(mOutputStreams.size() + (mInputStream != nullptr ? 1 : 0));
421 for (size_t i = 0; i < mOutputStreams.size(); i++) {
422 streams.push_back(mOutputStreams[i]);
423 }
424 if (mInputStream != nullptr) {
425 streams.push_back(mInputStream);
426 }
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700427 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700428 }
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800429 // Joining done without holding mLock and mInterfaceLock, otherwise deadlocks may ensue
430 // as the threads try to access parent state (b/143513518)
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700431 if (mRequestThread != NULL && mStatus != STATUS_ERROR) {
432 // HAL may be in a bad state, so waiting for request thread
433 // (which may be stuck in the HAL processCaptureRequest call)
434 // could be dangerous.
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800435 // give up mInterfaceLock here and then lock it again. Could this lead
436 // to other deadlocks
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700437 mRequestThread->join();
438 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700439 {
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800440 Mutex::Autolock il(mInterfaceLock);
441 if (mStatusTracker != NULL) {
442 mStatusTracker->join();
443 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800444
Cliff Wuc2ad9c82021-04-21 00:58:58 +0800445 if (mInjectionMethods->isInjecting()) {
446 mInjectionMethods->stopInjection();
447 }
448
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800449 HalInterface* interface;
450 {
451 Mutex::Autolock l(mLock);
452 mRequestThread.clear();
453 Mutex::Autolock stLock(mTrackerLock);
454 mStatusTracker.clear();
455 interface = mInterface.get();
456 }
Eino-Ville Talvalaefff1c42015-08-28 16:27:27 -0700457
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800458 // Call close without internal mutex held, as the HAL close may need to
459 // wait on assorted callbacks,etc, to complete before it can return.
460 interface->close();
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700461
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800462 flushInflightRequests();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800463
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800464 {
465 Mutex::Autolock l(mLock);
466 mInterface->clear();
467 mOutputStreams.clear();
468 mInputStream.clear();
469 mDeletedStreams.clear();
470 mBufferManager.clear();
471 internalUpdateStatusLocked(STATUS_UNINITIALIZED);
472 }
473
474 for (auto& weakStream : streams) {
475 sp<Camera3StreamInterface> stream = weakStream.promote();
476 if (stream != nullptr) {
477 ALOGE("%s: Stream %d leaked! strong reference (%d)!",
478 __FUNCTION__, stream->getId(), stream->getStrongCount() - 1);
479 }
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700480 }
481 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -0700482 ALOGI("%s: X", __FUNCTION__);
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700483 return res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800484}
485
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700486// For dumping/debugging only -
487// try to acquire a lock a few times, eventually give up to proceed with
488// debug/dump operations
489bool Camera3Device::tryLockSpinRightRound(Mutex& lock) {
490 bool gotLock = false;
491 for (size_t i = 0; i < kDumpLockAttempts; ++i) {
492 if (lock.tryLock() == NO_ERROR) {
493 gotLock = true;
494 break;
495 } else {
496 usleep(kDumpSleepDuration);
497 }
498 }
499 return gotLock;
500}
501
Shuzhen Wang83bff122020-11-20 15:51:39 -0800502camera3::Size Camera3Device::getMaxJpegResolution() const {
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700503 int32_t maxJpegWidth = 0, maxJpegHeight = 0;
Emilian Peev08dd2452017-04-06 16:55:14 +0100504 const int STREAM_CONFIGURATION_SIZE = 4;
505 const int STREAM_FORMAT_OFFSET = 0;
506 const int STREAM_WIDTH_OFFSET = 1;
507 const int STREAM_HEIGHT_OFFSET = 2;
508 const int STREAM_IS_INPUT_OFFSET = 3;
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -0800509 bool isHighResolutionSensor =
510 camera3::SessionConfigurationUtils::isUltraHighResolutionSensor(mDeviceInfo);
511 int32_t scalerSizesTag = isHighResolutionSensor ?
512 ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS_MAXIMUM_RESOLUTION :
513 ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS;
Emilian Peev08dd2452017-04-06 16:55:14 +0100514 camera_metadata_ro_entry_t availableStreamConfigs =
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -0800515 mDeviceInfo.find(scalerSizesTag);
Emilian Peev08dd2452017-04-06 16:55:14 +0100516 if (availableStreamConfigs.count == 0 ||
517 availableStreamConfigs.count % STREAM_CONFIGURATION_SIZE != 0) {
Shuzhen Wang83bff122020-11-20 15:51:39 -0800518 return camera3::Size(0, 0);
Emilian Peev08dd2452017-04-06 16:55:14 +0100519 }
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700520
Emilian Peev08dd2452017-04-06 16:55:14 +0100521 // Get max jpeg size (area-wise).
522 for (size_t i=0; i < availableStreamConfigs.count; i+= STREAM_CONFIGURATION_SIZE) {
523 int32_t format = availableStreamConfigs.data.i32[i + STREAM_FORMAT_OFFSET];
524 int32_t width = availableStreamConfigs.data.i32[i + STREAM_WIDTH_OFFSET];
525 int32_t height = availableStreamConfigs.data.i32[i + STREAM_HEIGHT_OFFSET];
526 int32_t isInput = availableStreamConfigs.data.i32[i + STREAM_IS_INPUT_OFFSET];
527 if (isInput == ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS_OUTPUT
528 && format == HAL_PIXEL_FORMAT_BLOB &&
529 (width * height > maxJpegWidth * maxJpegHeight)) {
530 maxJpegWidth = width;
531 maxJpegHeight = height;
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700532 }
533 }
Emilian Peev08dd2452017-04-06 16:55:14 +0100534
Shuzhen Wang83bff122020-11-20 15:51:39 -0800535 return camera3::Size(maxJpegWidth, maxJpegHeight);
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700536}
537
Shuzhen Wangc28dccc2016-02-11 23:48:46 -0800538nsecs_t Camera3Device::getMonoToBoottimeOffset() {
539 // try three times to get the clock offset, choose the one
540 // with the minimum gap in measurements.
541 const int tries = 3;
542 nsecs_t bestGap, measured;
543 for (int i = 0; i < tries; ++i) {
544 const nsecs_t tmono = systemTime(SYSTEM_TIME_MONOTONIC);
545 const nsecs_t tbase = systemTime(SYSTEM_TIME_BOOTTIME);
546 const nsecs_t tmono2 = systemTime(SYSTEM_TIME_MONOTONIC);
547 const nsecs_t gap = tmono2 - tmono;
548 if (i == 0 || gap < bestGap) {
549 bestGap = gap;
550 measured = tbase - ((tmono + tmono2) >> 1);
551 }
552 }
553 return measured;
554}
555
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800556hardware::graphics::common::V1_0::PixelFormat Camera3Device::mapToPixelFormat(
557 int frameworkFormat) {
558 return (hardware::graphics::common::V1_0::PixelFormat) frameworkFormat;
559}
560
561DataspaceFlags Camera3Device::mapToHidlDataspace(
562 android_dataspace dataSpace) {
563 return dataSpace;
564}
565
Chia-I Wu67a0c0e2017-04-06 13:37:01 -0700566BufferUsageFlags Camera3Device::mapToConsumerUsage(
Emilian Peev050f5dc2017-05-18 14:43:56 +0100567 uint64_t usage) {
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -0700568 return usage;
569}
570
Emilian Peevf4816702020-04-03 15:44:51 -0700571StreamRotation Camera3Device::mapToStreamRotation(camera_stream_rotation_t rotation) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800572 switch (rotation) {
Emilian Peevf4816702020-04-03 15:44:51 -0700573 case CAMERA_STREAM_ROTATION_0:
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800574 return StreamRotation::ROTATION_0;
Emilian Peevf4816702020-04-03 15:44:51 -0700575 case CAMERA_STREAM_ROTATION_90:
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800576 return StreamRotation::ROTATION_90;
Emilian Peevf4816702020-04-03 15:44:51 -0700577 case CAMERA_STREAM_ROTATION_180:
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800578 return StreamRotation::ROTATION_180;
Emilian Peevf4816702020-04-03 15:44:51 -0700579 case CAMERA_STREAM_ROTATION_270:
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800580 return StreamRotation::ROTATION_270;
581 }
582 ALOGE("%s: Unknown stream rotation %d", __FUNCTION__, rotation);
583 return StreamRotation::ROTATION_0;
584}
585
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800586status_t Camera3Device::mapToStreamConfigurationMode(
Emilian Peevf4816702020-04-03 15:44:51 -0700587 camera_stream_configuration_mode_t operationMode, StreamConfigurationMode *mode) {
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800588 if (mode == nullptr) return BAD_VALUE;
Emilian Peevf4816702020-04-03 15:44:51 -0700589 if (operationMode < CAMERA_VENDOR_STREAM_CONFIGURATION_MODE_START) {
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800590 switch(operationMode) {
Emilian Peevf4816702020-04-03 15:44:51 -0700591 case CAMERA_STREAM_CONFIGURATION_NORMAL_MODE:
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800592 *mode = StreamConfigurationMode::NORMAL_MODE;
593 break;
Emilian Peevf4816702020-04-03 15:44:51 -0700594 case CAMERA_STREAM_CONFIGURATION_CONSTRAINED_HIGH_SPEED_MODE:
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800595 *mode = StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE;
596 break;
597 default:
598 ALOGE("%s: Unknown stream configuration mode %d", __FUNCTION__, operationMode);
599 return BAD_VALUE;
600 }
601 } else {
602 *mode = static_cast<StreamConfigurationMode>(operationMode);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800603 }
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800604 return OK;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800605}
606
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800607int Camera3Device::mapToFrameworkFormat(
608 hardware::graphics::common::V1_0::PixelFormat pixelFormat) {
609 return static_cast<uint32_t>(pixelFormat);
610}
611
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -0700612android_dataspace Camera3Device::mapToFrameworkDataspace(
613 DataspaceFlags dataSpace) {
614 return static_cast<android_dataspace>(dataSpace);
615}
616
Emilian Peev050f5dc2017-05-18 14:43:56 +0100617uint64_t Camera3Device::mapConsumerToFrameworkUsage(
Chia-I Wu67a0c0e2017-04-06 13:37:01 -0700618 BufferUsageFlags usage) {
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -0700619 return usage;
620}
621
Emilian Peev050f5dc2017-05-18 14:43:56 +0100622uint64_t Camera3Device::mapProducerToFrameworkUsage(
Chia-I Wu67a0c0e2017-04-06 13:37:01 -0700623 BufferUsageFlags usage) {
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -0700624 return usage;
625}
626
Zhijun Hef7da0962014-04-24 13:27:56 -0700627ssize_t Camera3Device::getJpegBufferSize(uint32_t width, uint32_t height) const {
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700628 // Get max jpeg size (area-wise).
Shuzhen Wang83bff122020-11-20 15:51:39 -0800629 camera3::Size maxJpegResolution = getMaxJpegResolution();
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700630 if (maxJpegResolution.width == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800631 ALOGE("%s: Camera %s: Can't find valid available jpeg sizes in static metadata!",
632 __FUNCTION__, mId.string());
Zhijun Hef7da0962014-04-24 13:27:56 -0700633 return BAD_VALUE;
634 }
635
Zhijun Hef7da0962014-04-24 13:27:56 -0700636 // Get max jpeg buffer size
637 ssize_t maxJpegBufferSize = 0;
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700638 camera_metadata_ro_entry jpegBufMaxSize = mDeviceInfo.find(ANDROID_JPEG_MAX_SIZE);
639 if (jpegBufMaxSize.count == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800640 ALOGE("%s: Camera %s: Can't find maximum JPEG size in static metadata!", __FUNCTION__,
641 mId.string());
Zhijun Hef7da0962014-04-24 13:27:56 -0700642 return BAD_VALUE;
643 }
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700644 maxJpegBufferSize = jpegBufMaxSize.data.i32[0];
Yin-Chia Yeh0c4e56d2015-01-09 15:21:27 -0800645 assert(kMinJpegBufferSize < maxJpegBufferSize);
Zhijun Hef7da0962014-04-24 13:27:56 -0700646
647 // Calculate final jpeg buffer size for the given resolution.
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700648 float scaleFactor = ((float) (width * height)) /
649 (maxJpegResolution.width * maxJpegResolution.height);
Yin-Chia Yeh0c4e56d2015-01-09 15:21:27 -0800650 ssize_t jpegBufferSize = scaleFactor * (maxJpegBufferSize - kMinJpegBufferSize) +
651 kMinJpegBufferSize;
Zhijun Hef7da0962014-04-24 13:27:56 -0700652 if (jpegBufferSize > maxJpegBufferSize) {
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -0800653 ALOGI("%s: jpeg buffer size calculated is > maxJpeg bufferSize(%zd), clamping",
654 __FUNCTION__, maxJpegBufferSize);
Zhijun Hef7da0962014-04-24 13:27:56 -0700655 jpegBufferSize = maxJpegBufferSize;
Zhijun Hef7da0962014-04-24 13:27:56 -0700656 }
657
658 return jpegBufferSize;
659}
660
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700661ssize_t Camera3Device::getPointCloudBufferSize() const {
662 const int FLOATS_PER_POINT=4;
663 camera_metadata_ro_entry maxPointCount = mDeviceInfo.find(ANDROID_DEPTH_MAX_DEPTH_SAMPLES);
664 if (maxPointCount.count == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800665 ALOGE("%s: Camera %s: Can't find maximum depth point cloud size in static metadata!",
666 __FUNCTION__, mId.string());
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700667 return BAD_VALUE;
668 }
669 ssize_t maxBytesForPointCloud = sizeof(android_depth_points) +
670 maxPointCount.data.i32[0] * sizeof(float) * FLOATS_PER_POINT;
671 return maxBytesForPointCloud;
672}
673
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -0800674ssize_t Camera3Device::getRawOpaqueBufferSize(int32_t width, int32_t height,
675 bool maxResolution) const {
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800676 const int PER_CONFIGURATION_SIZE = 3;
677 const int WIDTH_OFFSET = 0;
678 const int HEIGHT_OFFSET = 1;
679 const int SIZE_OFFSET = 2;
680 camera_metadata_ro_entry rawOpaqueSizes =
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -0800681 mDeviceInfo.find(
682 camera3::SessionConfigurationUtils::getAppropriateModeTag(
683 ANDROID_SENSOR_OPAQUE_RAW_SIZE,
684 maxResolution));
Aurimas Liutikasbc57b122016-02-16 09:59:16 -0800685 size_t count = rawOpaqueSizes.count;
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800686 if (count == 0 || (count % PER_CONFIGURATION_SIZE)) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800687 ALOGE("%s: Camera %s: bad opaque RAW size static metadata length(%zu)!",
688 __FUNCTION__, mId.string(), count);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800689 return BAD_VALUE;
690 }
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700691
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800692 for (size_t i = 0; i < count; i += PER_CONFIGURATION_SIZE) {
693 if (width == rawOpaqueSizes.data.i32[i + WIDTH_OFFSET] &&
694 height == rawOpaqueSizes.data.i32[i + HEIGHT_OFFSET]) {
695 return rawOpaqueSizes.data.i32[i + SIZE_OFFSET];
696 }
697 }
698
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800699 ALOGE("%s: Camera %s: cannot find size for %dx%d opaque RAW image!",
700 __FUNCTION__, mId.string(), width, height);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800701 return BAD_VALUE;
702}
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700703
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800704status_t Camera3Device::dump(int fd, const Vector<String16> &args) {
705 ATRACE_CALL();
706 (void)args;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700707
708 // Try to lock, but continue in case of failure (to avoid blocking in
709 // deadlocks)
710 bool gotInterfaceLock = tryLockSpinRightRound(mInterfaceLock);
711 bool gotLock = tryLockSpinRightRound(mLock);
712
713 ALOGW_IF(!gotInterfaceLock,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800714 "Camera %s: %s: Unable to lock interface lock, proceeding anyway",
715 mId.string(), __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700716 ALOGW_IF(!gotLock,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800717 "Camera %s: %s: Unable to lock main lock, proceeding anyway",
718 mId.string(), __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700719
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800720 bool dumpTemplates = false;
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700721
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800722 String16 templatesOption("-t");
723 int n = args.size();
724 for (int i = 0; i < n; i++) {
725 if (args[i] == templatesOption) {
726 dumpTemplates = true;
727 }
Emilian Peevbd8c5032018-02-14 23:05:40 +0000728 if (args[i] == TagMonitor::kMonitorOption) {
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700729 if (i + 1 < n) {
730 String8 monitorTags = String8(args[i + 1]);
731 if (monitorTags == "off") {
732 mTagMonitor.disableMonitoring();
733 } else {
734 mTagMonitor.parseTagsToMonitor(monitorTags);
735 }
736 } else {
737 mTagMonitor.disableMonitoring();
738 }
739 }
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800740 }
741
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800742 String8 lines;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800743
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800744 const char *status =
745 mStatus == STATUS_ERROR ? "ERROR" :
746 mStatus == STATUS_UNINITIALIZED ? "UNINITIALIZED" :
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700747 mStatus == STATUS_UNCONFIGURED ? "UNCONFIGURED" :
748 mStatus == STATUS_CONFIGURED ? "CONFIGURED" :
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800749 mStatus == STATUS_ACTIVE ? "ACTIVE" :
750 "Unknown";
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700751
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800752 lines.appendFormat(" Device status: %s\n", status);
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700753 if (mStatus == STATUS_ERROR) {
754 lines.appendFormat(" Error cause: %s\n", mErrorCause.string());
755 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800756 lines.appendFormat(" Stream configuration:\n");
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800757 const char *mode =
758 mOperatingMode == static_cast<int>(StreamConfigurationMode::NORMAL_MODE) ? "NORMAL" :
759 mOperatingMode == static_cast<int>(
760 StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE) ? "CONSTRAINED_HIGH_SPEED" :
761 "CUSTOM";
762 lines.appendFormat(" Operation mode: %s (%d) \n", mode, mOperatingMode);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800763
764 if (mInputStream != NULL) {
765 write(fd, lines.string(), lines.size());
766 mInputStream->dump(fd, args);
767 } else {
768 lines.appendFormat(" No input stream.\n");
769 write(fd, lines.string(), lines.size());
770 }
771 for (size_t i = 0; i < mOutputStreams.size(); i++) {
772 mOutputStreams[i]->dump(fd,args);
773 }
774
Zhijun He431503c2016-03-07 17:30:16 -0800775 if (mBufferManager != NULL) {
776 lines = String8(" Camera3 Buffer Manager:\n");
777 write(fd, lines.string(), lines.size());
778 mBufferManager->dump(fd, args);
779 }
Zhijun He125684a2015-12-26 15:07:30 -0800780
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700781 lines = String8(" In-flight requests:\n");
782 if (mInFlightMap.size() == 0) {
783 lines.append(" None\n");
784 } else {
785 for (size_t i = 0; i < mInFlightMap.size(); i++) {
786 InFlightRequest r = mInFlightMap.valueAt(i);
Colin Crosse5729fa2014-03-21 15:04:25 -0700787 lines.appendFormat(" Frame %d | Timestamp: %" PRId64 ", metadata"
Greg Kaiser51b882c2020-06-10 05:41:44 +0000788 " arrived: %s, buffers left: %d\n", mInFlightMap.keyAt(i),
Chien-Yu Chen43e69a62014-11-25 16:38:33 -0800789 r.shutterTimestamp, r.haveResultMetadata ? "true" : "false",
Greg Kaiser51b882c2020-06-10 05:41:44 +0000790 r.numBuffersLeft);
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700791 }
792 }
793 write(fd, lines.string(), lines.size());
794
Shuzhen Wang686f6442017-06-20 16:16:04 -0700795 if (mRequestThread != NULL) {
796 mRequestThread->dumpCaptureRequestLatency(fd,
797 " ProcessCaptureRequest latency histogram:");
798 }
799
Igor Murashkin1e479c02013-09-06 16:55:14 -0700800 {
801 lines = String8(" Last request sent:\n");
802 write(fd, lines.string(), lines.size());
803
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700804 CameraMetadata lastRequest = getLatestRequestLocked();
Igor Murashkin1e479c02013-09-06 16:55:14 -0700805 lastRequest.dump(fd, /*verbosity*/2, /*indentation*/6);
806 }
807
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800808 if (dumpTemplates) {
Emilian Peevf4816702020-04-03 15:44:51 -0700809 const char *templateNames[CAMERA_TEMPLATE_COUNT] = {
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800810 "TEMPLATE_PREVIEW",
811 "TEMPLATE_STILL_CAPTURE",
812 "TEMPLATE_VIDEO_RECORD",
813 "TEMPLATE_VIDEO_SNAPSHOT",
814 "TEMPLATE_ZERO_SHUTTER_LAG",
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -0800815 "TEMPLATE_MANUAL",
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800816 };
817
Emilian Peevf4816702020-04-03 15:44:51 -0700818 for (int i = 1; i < CAMERA_TEMPLATE_COUNT; i++) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800819 camera_metadata_t *templateRequest = nullptr;
820 mInterface->constructDefaultRequestSettings(
Emilian Peevf4816702020-04-03 15:44:51 -0700821 (camera_request_template_t) i, &templateRequest);
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800822 lines = String8::format(" HAL Request %s:\n", templateNames[i-1]);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800823 if (templateRequest == nullptr) {
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800824 lines.append(" Not supported\n");
825 write(fd, lines.string(), lines.size());
826 } else {
827 write(fd, lines.string(), lines.size());
828 dump_indented_camera_metadata(templateRequest,
829 fd, /*verbosity*/2, /*indentation*/8);
830 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800831 free_camera_metadata(templateRequest);
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800832 }
833 }
834
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700835 mTagMonitor.dumpMonitoredMetadata(fd);
836
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800837 if (mInterface->valid()) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -0800838 lines = String8(" HAL device dump:\n");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800839 write(fd, lines.string(), lines.size());
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800840 mInterface->dump(fd);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800841 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800842
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700843 if (gotLock) mLock.unlock();
844 if (gotInterfaceLock) mInterfaceLock.unlock();
845
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800846 return OK;
847}
848
Emilian Peevfaa4bde2020-01-23 12:19:37 -0800849const CameraMetadata& Camera3Device::infoPhysical(const String8& physicalId) const {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800850 ALOGVV("%s: E", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800851 if (CC_UNLIKELY(mStatus == STATUS_UNINITIALIZED ||
852 mStatus == STATUS_ERROR)) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700853 ALOGW("%s: Access to static info %s!", __FUNCTION__,
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800854 mStatus == STATUS_ERROR ?
855 "when in error state" : "before init");
856 }
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700857 if (physicalId.isEmpty()) {
858 return mDeviceInfo;
859 } else {
860 std::string id(physicalId.c_str());
861 if (mPhysicalDeviceInfoMap.find(id) != mPhysicalDeviceInfoMap.end()) {
862 return mPhysicalDeviceInfoMap.at(id);
863 } else {
864 ALOGE("%s: Invalid physical camera id %s", __FUNCTION__, physicalId.c_str());
865 return mDeviceInfo;
866 }
867 }
868}
869
870const CameraMetadata& Camera3Device::info() const {
871 String8 emptyId;
Emilian Peevfaa4bde2020-01-23 12:19:37 -0800872 return infoPhysical(emptyId);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800873}
874
Jianing Wei90e59c92014-03-12 18:29:36 -0700875status_t Camera3Device::checkStatusOkToCaptureLocked() {
876 switch (mStatus) {
877 case STATUS_ERROR:
878 CLOGE("Device has encountered a serious error");
879 return INVALID_OPERATION;
880 case STATUS_UNINITIALIZED:
881 CLOGE("Device not initialized");
882 return INVALID_OPERATION;
883 case STATUS_UNCONFIGURED:
884 case STATUS_CONFIGURED:
885 case STATUS_ACTIVE:
886 // OK
887 break;
888 default:
889 SET_ERR_L("Unexpected status: %d", mStatus);
890 return INVALID_OPERATION;
891 }
892 return OK;
893}
894
895status_t Camera3Device::convertMetadataListToRequestListLocked(
Emilian Peevaebbe412018-01-15 13:53:24 +0000896 const List<const PhysicalCameraSettingsList> &metadataList,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700897 const std::list<const SurfaceMap> &surfaceMaps,
Shuzhen Wang316781a2020-08-18 18:11:01 -0700898 bool repeating, nsecs_t requestTimeNs,
Shuzhen Wang9d066012016-09-30 11:30:20 -0700899 RequestList *requestList) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700900 if (requestList == NULL) {
901 CLOGE("requestList cannot be NULL.");
902 return BAD_VALUE;
903 }
904
Jianing Weicb0652e2014-03-12 18:29:36 -0700905 int32_t burstId = 0;
Emilian Peevaebbe412018-01-15 13:53:24 +0000906 List<const PhysicalCameraSettingsList>::const_iterator metadataIt = metadataList.begin();
Shuzhen Wang0129d522016-10-30 22:43:41 -0700907 std::list<const SurfaceMap>::const_iterator surfaceMapIt = surfaceMaps.begin();
908 for (; metadataIt != metadataList.end() && surfaceMapIt != surfaceMaps.end();
909 ++metadataIt, ++surfaceMapIt) {
910 sp<CaptureRequest> newRequest = setUpRequestLocked(*metadataIt, *surfaceMapIt);
Jianing Wei90e59c92014-03-12 18:29:36 -0700911 if (newRequest == 0) {
912 CLOGE("Can't create capture request");
913 return BAD_VALUE;
914 }
Jianing Weicb0652e2014-03-12 18:29:36 -0700915
Shuzhen Wang9d066012016-09-30 11:30:20 -0700916 newRequest->mRepeating = repeating;
Shuzhen Wang316781a2020-08-18 18:11:01 -0700917 newRequest->mRequestTimeNs = requestTimeNs;
Shuzhen Wang9d066012016-09-30 11:30:20 -0700918
Jianing Weicb0652e2014-03-12 18:29:36 -0700919 // Setup burst Id and request Id
920 newRequest->mResultExtras.burstId = burstId++;
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -0800921 auto requestIdEntry = metadataIt->begin()->metadata.find(ANDROID_REQUEST_ID);
922 if (requestIdEntry.count == 0) {
Jianing Weicb0652e2014-03-12 18:29:36 -0700923 CLOGE("RequestID does not exist in metadata");
924 return BAD_VALUE;
925 }
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -0800926 newRequest->mResultExtras.requestId = requestIdEntry.data.i32[0];
Jianing Weicb0652e2014-03-12 18:29:36 -0700927
Jianing Wei90e59c92014-03-12 18:29:36 -0700928 requestList->push_back(newRequest);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700929
930 ALOGV("%s: requestId = %" PRId32, __FUNCTION__, newRequest->mResultExtras.requestId);
Jianing Wei90e59c92014-03-12 18:29:36 -0700931 }
Shuzhen Wang0129d522016-10-30 22:43:41 -0700932 if (metadataIt != metadataList.end() || surfaceMapIt != surfaceMaps.end()) {
933 ALOGE("%s: metadataList and surfaceMaps are not the same size!", __FUNCTION__);
934 return BAD_VALUE;
935 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -0700936
937 // Setup batch size if this is a high speed video recording request.
938 if (mIsConstrainedHighSpeedConfiguration && requestList->size() > 0) {
939 auto firstRequest = requestList->begin();
940 for (auto& outputStream : (*firstRequest)->mOutputStreams) {
941 if (outputStream->isVideoStream()) {
942 (*firstRequest)->mBatchSize = requestList->size();
Yin-Chia Yeh14ef48d2020-02-10 15:06:37 -0800943 outputStream->setBatchSize(requestList->size());
Chien-Yu Chen85a64552015-08-28 15:46:12 -0700944 break;
945 }
946 }
947 }
948
Jianing Wei90e59c92014-03-12 18:29:36 -0700949 return OK;
950}
951
Yin-Chia Yeh7e5a2042019-02-06 16:01:06 -0800952status_t Camera3Device::capture(CameraMetadata &request, int64_t* lastFrameNumber) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800953 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800954
Emilian Peevaebbe412018-01-15 13:53:24 +0000955 List<const PhysicalCameraSettingsList> requestsList;
Shuzhen Wang0129d522016-10-30 22:43:41 -0700956 std::list<const SurfaceMap> surfaceMaps;
Emilian Peevaebbe412018-01-15 13:53:24 +0000957 convertToRequestList(requestsList, surfaceMaps, request);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700958
Yin-Chia Yeh7e5a2042019-02-06 16:01:06 -0800959 return captureList(requestsList, surfaceMaps, lastFrameNumber);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700960}
961
Emilian Peevaebbe412018-01-15 13:53:24 +0000962void Camera3Device::convertToRequestList(List<const PhysicalCameraSettingsList>& requestsList,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700963 std::list<const SurfaceMap>& surfaceMaps,
964 const CameraMetadata& request) {
Emilian Peevaebbe412018-01-15 13:53:24 +0000965 PhysicalCameraSettingsList requestList;
966 requestList.push_back({std::string(getId().string()), request});
967 requestsList.push_back(requestList);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700968
969 SurfaceMap surfaceMap;
970 camera_metadata_ro_entry streams = request.find(ANDROID_REQUEST_OUTPUT_STREAMS);
971 // With no surface list passed in, stream and surface will have 1-to-1
972 // mapping. So the surface index is 0 for each stream in the surfaceMap.
973 for (size_t i = 0; i < streams.count; i++) {
974 surfaceMap[streams.data.i32[i]].push_back(0);
975 }
976 surfaceMaps.push_back(surfaceMap);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800977}
978
Jianing Wei90e59c92014-03-12 18:29:36 -0700979status_t Camera3Device::submitRequestsHelper(
Emilian Peevaebbe412018-01-15 13:53:24 +0000980 const List<const PhysicalCameraSettingsList> &requests,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700981 const std::list<const SurfaceMap> &surfaceMaps,
982 bool repeating,
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700983 /*out*/
984 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700985 ATRACE_CALL();
Shuzhen Wang316781a2020-08-18 18:11:01 -0700986 nsecs_t requestTimeNs = systemTime();
987
Jianing Wei90e59c92014-03-12 18:29:36 -0700988 Mutex::Autolock il(mInterfaceLock);
989 Mutex::Autolock l(mLock);
990
991 status_t res = checkStatusOkToCaptureLocked();
992 if (res != OK) {
993 // error logged by previous call
994 return res;
995 }
996
997 RequestList requestList;
998
Shuzhen Wang0129d522016-10-30 22:43:41 -0700999 res = convertMetadataListToRequestListLocked(requests, surfaceMaps,
Shuzhen Wang316781a2020-08-18 18:11:01 -07001000 repeating, requestTimeNs, /*out*/&requestList);
Jianing Wei90e59c92014-03-12 18:29:36 -07001001 if (res != OK) {
1002 // error logged by previous call
1003 return res;
1004 }
1005
1006 if (repeating) {
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07001007 res = mRequestThread->setRepeatingRequests(requestList, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -07001008 } else {
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07001009 res = mRequestThread->queueRequestList(requestList, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -07001010 }
1011
1012 if (res == OK) {
1013 waitUntilStateThenRelock(/*active*/true, kActiveTimeout);
1014 if (res != OK) {
1015 SET_ERR_L("Can't transition to active in %f seconds!",
1016 kActiveTimeout/1e9);
1017 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001018 ALOGV("Camera %s: Capture request %" PRId32 " enqueued", mId.string(),
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07001019 (*(requestList.begin()))->mResultExtras.requestId);
Jianing Wei90e59c92014-03-12 18:29:36 -07001020 } else {
1021 CLOGE("Cannot queue request. Impossible.");
1022 return BAD_VALUE;
1023 }
1024
1025 return res;
1026}
1027
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001028hardware::Return<void> Camera3Device::requestStreamBuffers(
1029 const hardware::hidl_vec<hardware::camera::device::V3_5::BufferRequest>& bufReqs,
1030 requestStreamBuffers_cb _hidl_cb) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001031 RequestBufferStates states {
Shuzhen Wang316781a2020-08-18 18:11:01 -07001032 mId, mRequestBufferInterfaceLock, mUseHalBufManager, mOutputStreams, mSessionStatsBuilder,
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001033 *this, *mInterface, *this};
1034 camera3::requestStreamBuffers(states, bufReqs, _hidl_cb);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001035 return hardware::Void();
1036}
1037
1038hardware::Return<void> Camera3Device::returnStreamBuffers(
1039 const hardware::hidl_vec<hardware::camera::device::V3_2::StreamBuffer>& buffers) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001040 ReturnBufferStates states {
Shuzhen Wang316781a2020-08-18 18:11:01 -07001041 mId, mUseHalBufManager, mOutputStreams, mSessionStatsBuilder, *mInterface};
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001042 camera3::returnStreamBuffers(states, buffers);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001043 return hardware::Void();
1044}
1045
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001046hardware::Return<void> Camera3Device::processCaptureResult_3_4(
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001047 const hardware::hidl_vec<
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001048 hardware::camera::device::V3_4::CaptureResult>& results) {
Yin-Chia Yeh657c1872017-07-18 18:09:57 -07001049 // Ideally we should grab mLock, but that can lead to deadlock, and
1050 // it's not super important to get up to date value of mStatus for this
1051 // warning print, hence skipping the lock here
1052 if (mStatus == STATUS_ERROR) {
1053 // Per API contract, HAL should act as closed after device error
1054 // But mStatus can be set to error by framework as well, so just log
1055 // a warning here.
1056 ALOGW("%s: received capture result in error state.", __FUNCTION__);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07001057 }
Yifan Honga640c5a2017-04-12 16:30:31 -07001058
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001059 sp<NotificationListener> listener;
1060 {
1061 std::lock_guard<std::mutex> l(mOutputLock);
1062 listener = mListener.promote();
1063 }
1064
Yifan Honga640c5a2017-04-12 16:30:31 -07001065 if (mProcessCaptureResultLock.tryLock() != OK) {
1066 // This should never happen; it indicates a wrong client implementation
1067 // that doesn't follow the contract. But, we can be tolerant here.
1068 ALOGE("%s: callback overlapped! waiting 1s...",
1069 __FUNCTION__);
1070 if (mProcessCaptureResultLock.timedLock(1000000000 /* 1s */) != OK) {
1071 ALOGE("%s: cannot acquire lock in 1s, dropping results",
1072 __FUNCTION__);
1073 // really don't know what to do, so bail out.
1074 return hardware::Void();
1075 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001076 }
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001077 CaptureOutputStates states {
1078 mId,
Shuzhen Wangb7b42652020-05-07 11:59:02 -07001079 mInFlightLock, mLastCompletedRegularFrameNumber,
1080 mLastCompletedReprocessFrameNumber, mLastCompletedZslFrameNumber,
1081 mInFlightMap, mOutputLock, mResultQueue, mResultSignal,
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001082 mNextShutterFrameNumber,
1083 mNextReprocessShutterFrameNumber, mNextZslStillShutterFrameNumber,
1084 mNextResultFrameNumber,
1085 mNextReprocessResultFrameNumber, mNextZslStillResultFrameNumber,
1086 mUseHalBufManager, mUsePartialResult, mNeedFixupMonochromeTags,
1087 mNumPartialResults, mVendorTagId, mDeviceInfo, mPhysicalDeviceInfoMap,
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08001088 mResultMetadataQueue, mDistortionMappers, mZoomRatioMappers, mRotateAndCropMappers,
Shuzhen Wang316781a2020-08-18 18:11:01 -07001089 mTagMonitor, mInputStream, mOutputStreams, mSessionStatsBuilder, listener, *this, *this,
1090 *mInterface
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001091 };
1092
Yifan Honga640c5a2017-04-12 16:30:31 -07001093 for (const auto& result : results) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001094 processOneCaptureResultLocked(states, result.v3_2, result.physicalCameraMetadata);
Yifan Honga640c5a2017-04-12 16:30:31 -07001095 }
1096 mProcessCaptureResultLock.unlock();
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001097 return hardware::Void();
1098}
1099
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001100// Only one processCaptureResult should be called at a time, so
1101// the locks won't block. The locks are present here simply to enforce this.
1102hardware::Return<void> Camera3Device::processCaptureResult(
1103 const hardware::hidl_vec<
1104 hardware::camera::device::V3_2::CaptureResult>& results) {
1105 hardware::hidl_vec<hardware::camera::device::V3_4::PhysicalCameraMetadata> noPhysMetadata;
1106
1107 // Ideally we should grab mLock, but that can lead to deadlock, and
1108 // it's not super important to get up to date value of mStatus for this
1109 // warning print, hence skipping the lock here
1110 if (mStatus == STATUS_ERROR) {
1111 // Per API contract, HAL should act as closed after device error
1112 // But mStatus can be set to error by framework as well, so just log
1113 // a warning here.
1114 ALOGW("%s: received capture result in error state.", __FUNCTION__);
1115 }
1116
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001117 sp<NotificationListener> listener;
1118 {
1119 std::lock_guard<std::mutex> l(mOutputLock);
1120 listener = mListener.promote();
1121 }
1122
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001123 if (mProcessCaptureResultLock.tryLock() != OK) {
1124 // This should never happen; it indicates a wrong client implementation
1125 // that doesn't follow the contract. But, we can be tolerant here.
1126 ALOGE("%s: callback overlapped! waiting 1s...",
1127 __FUNCTION__);
1128 if (mProcessCaptureResultLock.timedLock(1000000000 /* 1s */) != OK) {
1129 ALOGE("%s: cannot acquire lock in 1s, dropping results",
1130 __FUNCTION__);
1131 // really don't know what to do, so bail out.
1132 return hardware::Void();
1133 }
1134 }
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001135
1136 CaptureOutputStates states {
1137 mId,
Shuzhen Wangb7b42652020-05-07 11:59:02 -07001138 mInFlightLock, mLastCompletedRegularFrameNumber,
1139 mLastCompletedReprocessFrameNumber, mLastCompletedZslFrameNumber,
1140 mInFlightMap, mOutputLock, mResultQueue, mResultSignal,
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001141 mNextShutterFrameNumber,
1142 mNextReprocessShutterFrameNumber, mNextZslStillShutterFrameNumber,
1143 mNextResultFrameNumber,
1144 mNextReprocessResultFrameNumber, mNextZslStillResultFrameNumber,
1145 mUseHalBufManager, mUsePartialResult, mNeedFixupMonochromeTags,
1146 mNumPartialResults, mVendorTagId, mDeviceInfo, mPhysicalDeviceInfoMap,
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08001147 mResultMetadataQueue, mDistortionMappers, mZoomRatioMappers, mRotateAndCropMappers,
Shuzhen Wang316781a2020-08-18 18:11:01 -07001148 mTagMonitor, mInputStream, mOutputStreams, mSessionStatsBuilder, listener, *this, *this,
1149 *mInterface
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001150 };
1151
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001152 for (const auto& result : results) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001153 processOneCaptureResultLocked(states, result, noPhysMetadata);
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001154 }
1155 mProcessCaptureResultLock.unlock();
1156 return hardware::Void();
1157}
1158
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001159hardware::Return<void> Camera3Device::notify(
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001160 const hardware::hidl_vec<hardware::camera::device::V3_2::NotifyMsg>& msgs) {
Yin-Chia Yeh657c1872017-07-18 18:09:57 -07001161 // Ideally we should grab mLock, but that can lead to deadlock, and
1162 // it's not super important to get up to date value of mStatus for this
1163 // warning print, hence skipping the lock here
1164 if (mStatus == STATUS_ERROR) {
1165 // Per API contract, HAL should act as closed after device error
1166 // But mStatus can be set to error by framework as well, so just log
1167 // a warning here.
1168 ALOGW("%s: received notify message in error state.", __FUNCTION__);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07001169 }
Yin-Chia Yeh657c1872017-07-18 18:09:57 -07001170
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001171 sp<NotificationListener> listener;
1172 {
1173 std::lock_guard<std::mutex> l(mOutputLock);
1174 listener = mListener.promote();
1175 }
1176
1177 CaptureOutputStates states {
1178 mId,
Shuzhen Wangb7b42652020-05-07 11:59:02 -07001179 mInFlightLock, mLastCompletedRegularFrameNumber,
1180 mLastCompletedReprocessFrameNumber, mLastCompletedZslFrameNumber,
1181 mInFlightMap, mOutputLock, mResultQueue, mResultSignal,
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001182 mNextShutterFrameNumber,
1183 mNextReprocessShutterFrameNumber, mNextZslStillShutterFrameNumber,
1184 mNextResultFrameNumber,
1185 mNextReprocessResultFrameNumber, mNextZslStillResultFrameNumber,
1186 mUseHalBufManager, mUsePartialResult, mNeedFixupMonochromeTags,
1187 mNumPartialResults, mVendorTagId, mDeviceInfo, mPhysicalDeviceInfoMap,
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08001188 mResultMetadataQueue, mDistortionMappers, mZoomRatioMappers, mRotateAndCropMappers,
Shuzhen Wang316781a2020-08-18 18:11:01 -07001189 mTagMonitor, mInputStream, mOutputStreams, mSessionStatsBuilder, listener, *this, *this,
1190 *mInterface
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001191 };
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001192 for (const auto& msg : msgs) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001193 camera3::notify(states, msg);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001194 }
1195 return hardware::Void();
1196}
1197
Emilian Peevaebbe412018-01-15 13:53:24 +00001198status_t Camera3Device::captureList(const List<const PhysicalCameraSettingsList> &requestsList,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001199 const std::list<const SurfaceMap> &surfaceMaps,
Jianing Weicb0652e2014-03-12 18:29:36 -07001200 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -07001201 ATRACE_CALL();
1202
Emilian Peevaebbe412018-01-15 13:53:24 +00001203 return submitRequestsHelper(requestsList, surfaceMaps, /*repeating*/false, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -07001204}
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001205
Jianing Weicb0652e2014-03-12 18:29:36 -07001206status_t Camera3Device::setStreamingRequest(const CameraMetadata &request,
1207 int64_t* /*lastFrameNumber*/) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001208 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001209
Emilian Peevaebbe412018-01-15 13:53:24 +00001210 List<const PhysicalCameraSettingsList> requestsList;
Shuzhen Wang0129d522016-10-30 22:43:41 -07001211 std::list<const SurfaceMap> surfaceMaps;
Emilian Peevaebbe412018-01-15 13:53:24 +00001212 convertToRequestList(requestsList, surfaceMaps, request);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001213
Emilian Peevaebbe412018-01-15 13:53:24 +00001214 return setStreamingRequestList(requestsList, /*surfaceMap*/surfaceMaps,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001215 /*lastFrameNumber*/NULL);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001216}
1217
Emilian Peevaebbe412018-01-15 13:53:24 +00001218status_t Camera3Device::setStreamingRequestList(
1219 const List<const PhysicalCameraSettingsList> &requestsList,
1220 const std::list<const SurfaceMap> &surfaceMaps, int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -07001221 ATRACE_CALL();
1222
Emilian Peevaebbe412018-01-15 13:53:24 +00001223 return submitRequestsHelper(requestsList, surfaceMaps, /*repeating*/true, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -07001224}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001225
1226sp<Camera3Device::CaptureRequest> Camera3Device::setUpRequestLocked(
Emilian Peevaebbe412018-01-15 13:53:24 +00001227 const PhysicalCameraSettingsList &request, const SurfaceMap &surfaceMap) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001228 status_t res;
1229
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001230 if (mStatus == STATUS_UNCONFIGURED || mNeedConfig) {
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08001231 // This point should only be reached via API1 (API2 must explicitly call configureStreams)
1232 // so unilaterally select normal operating mode.
Emilian Peevaebbe412018-01-15 13:53:24 +00001233 res = filterParamsAndConfigureLocked(request.begin()->metadata,
Emilian Peevf4816702020-04-03 15:44:51 -07001234 CAMERA_STREAM_CONFIGURATION_NORMAL_MODE);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001235 // Stream configuration failed. Client might try other configuraitons.
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001236 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001237 CLOGE("Can't set up streams: %s (%d)", strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001238 return NULL;
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001239 } else if (mStatus == STATUS_UNCONFIGURED) {
1240 // Stream configuration successfully configure to empty stream configuration.
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001241 CLOGE("No streams configured");
1242 return NULL;
1243 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001244 }
1245
Shuzhen Wang0129d522016-10-30 22:43:41 -07001246 sp<CaptureRequest> newRequest = createCaptureRequest(request, surfaceMap);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001247 return newRequest;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001248}
1249
Jianing Weicb0652e2014-03-12 18:29:36 -07001250status_t Camera3Device::clearStreamingRequest(int64_t *lastFrameNumber) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001251 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001252 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001253 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001254
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001255 switch (mStatus) {
1256 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001257 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001258 return INVALID_OPERATION;
1259 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001260 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001261 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001262 case STATUS_UNCONFIGURED:
1263 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001264 case STATUS_ACTIVE:
1265 // OK
1266 break;
1267 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001268 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001269 return INVALID_OPERATION;
1270 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001271 ALOGV("Camera %s: Clearing repeating request", mId.string());
Jianing Weicb0652e2014-03-12 18:29:36 -07001272
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07001273 return mRequestThread->clearRepeatingRequests(lastFrameNumber);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001274}
1275
1276status_t Camera3Device::waitUntilRequestReceived(int32_t requestId, nsecs_t timeout) {
1277 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001278 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001279
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001280 return mRequestThread->waitUntilRequestProcessed(requestId, timeout);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001281}
1282
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001283status_t Camera3Device::createInputStream(
Shuzhen Wang83bff122020-11-20 15:51:39 -08001284 uint32_t width, uint32_t height, int format, bool isMultiResolution, int *id) {
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001285 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001286 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001287 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001288 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001289 ALOGV("Camera %s: Creating new input stream %d: %d x %d, format %d",
1290 mId.string(), mNextStreamId, width, height, format);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001291
1292 status_t res;
1293 bool wasActive = false;
1294
1295 switch (mStatus) {
1296 case STATUS_ERROR:
1297 ALOGE("%s: Device has encountered a serious error", __FUNCTION__);
1298 return INVALID_OPERATION;
1299 case STATUS_UNINITIALIZED:
1300 ALOGE("%s: Device not initialized", __FUNCTION__);
1301 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001302 case STATUS_UNCONFIGURED:
1303 case STATUS_CONFIGURED:
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001304 // OK
1305 break;
1306 case STATUS_ACTIVE:
1307 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001308 res = internalPauseAndWaitLocked(maxExpectedDuration);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001309 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001310 SET_ERR_L("Can't pause captures to reconfigure streams!");
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001311 return res;
1312 }
1313 wasActive = true;
1314 break;
1315 default:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001316 SET_ERR_L("%s: Unexpected status: %d", mStatus);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001317 return INVALID_OPERATION;
1318 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001319 assert(mStatus != STATUS_ACTIVE);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001320
1321 if (mInputStream != 0) {
1322 ALOGE("%s: Cannot create more than 1 input stream", __FUNCTION__);
1323 return INVALID_OPERATION;
1324 }
1325
1326 sp<Camera3InputStream> newStream = new Camera3InputStream(mNextStreamId,
1327 width, height, format);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001328 newStream->setStatusTracker(mStatusTracker);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001329
1330 mInputStream = newStream;
Shuzhen Wang83bff122020-11-20 15:51:39 -08001331 mIsInputStreamMultiResolution = isMultiResolution;
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001332
1333 *id = mNextStreamId++;
1334
1335 // Continue captures if active at start
1336 if (wasActive) {
1337 ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001338 // Reuse current operating mode and session parameters for new stream config
1339 res = configureStreamsLocked(mOperatingMode, mSessionParams);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001340 if (res != OK) {
1341 ALOGE("%s: Can't reconfigure device for new stream %d: %s (%d)",
1342 __FUNCTION__, mNextStreamId, strerror(-res), res);
1343 return res;
1344 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001345 internalResumeLocked();
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001346 }
1347
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001348 ALOGV("Camera %s: Created input stream", mId.string());
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001349 return OK;
1350}
1351
Eino-Ville Talvala727d1722015-06-09 13:44:19 -07001352status_t Camera3Device::createStream(sp<Surface> consumer,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001353 uint32_t width, uint32_t height, int format,
Emilian Peevf4816702020-04-03 15:44:51 -07001354 android_dataspace dataSpace, camera_stream_rotation_t rotation, int *id,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001355 const String8& physicalCameraId,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001356 const std::unordered_set<int32_t> &sensorPixelModesUsed,
1357 std::vector<int> *surfaceIds, int streamSetId, bool isShared, bool isMultiResolution,
1358 uint64_t consumerUsage) {
Shuzhen Wang0129d522016-10-30 22:43:41 -07001359 ATRACE_CALL();
1360
1361 if (consumer == nullptr) {
1362 ALOGE("%s: consumer must not be null", __FUNCTION__);
1363 return BAD_VALUE;
1364 }
1365
1366 std::vector<sp<Surface>> consumers;
1367 consumers.push_back(consumer);
1368
1369 return createStream(consumers, /*hasDeferredConsumer*/ false, width, height,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001370 format, dataSpace, rotation, id, physicalCameraId, sensorPixelModesUsed, surfaceIds,
1371 streamSetId, isShared, isMultiResolution, consumerUsage);
1372}
1373
1374static bool isRawFormat(int format) {
1375 switch (format) {
1376 case HAL_PIXEL_FORMAT_RAW16:
1377 case HAL_PIXEL_FORMAT_RAW12:
1378 case HAL_PIXEL_FORMAT_RAW10:
1379 case HAL_PIXEL_FORMAT_RAW_OPAQUE:
1380 return true;
1381 default:
1382 return false;
1383 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001384}
1385
1386status_t Camera3Device::createStream(const std::vector<sp<Surface>>& consumers,
1387 bool hasDeferredConsumer, uint32_t width, uint32_t height, int format,
Emilian Peevf4816702020-04-03 15:44:51 -07001388 android_dataspace dataSpace, camera_stream_rotation_t rotation, int *id,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001389 const String8& physicalCameraId, const std::unordered_set<int32_t> &sensorPixelModesUsed,
Shuzhen Wang83bff122020-11-20 15:51:39 -08001390 std::vector<int> *surfaceIds, int streamSetId, bool isShared, bool isMultiResolution,
1391 uint64_t consumerUsage) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001392 ATRACE_CALL();
Emilian Peev40ead602017-09-26 15:46:36 +01001393
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001394 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001395 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001396 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001397 ALOGV("Camera %s: Creating new stream %d: %d x %d, format %d, dataspace %d rotation %d"
Shuzhen Wang83bff122020-11-20 15:51:39 -08001398 " consumer usage %" PRIu64 ", isShared %d, physicalCameraId %s, isMultiResolution %d",
1399 mId.string(), mNextStreamId, width, height, format, dataSpace, rotation,
1400 consumerUsage, isShared, physicalCameraId.string(), isMultiResolution);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001401
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001402 status_t res;
1403 bool wasActive = false;
1404
1405 switch (mStatus) {
1406 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001407 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001408 return INVALID_OPERATION;
1409 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001410 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001411 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001412 case STATUS_UNCONFIGURED:
1413 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001414 // OK
1415 break;
1416 case STATUS_ACTIVE:
1417 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001418 res = internalPauseAndWaitLocked(maxExpectedDuration);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001419 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001420 SET_ERR_L("Can't pause captures to reconfigure streams!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001421 return res;
1422 }
1423 wasActive = true;
1424 break;
1425 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001426 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001427 return INVALID_OPERATION;
1428 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001429 assert(mStatus != STATUS_ACTIVE);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001430
1431 sp<Camera3OutputStream> newStream;
Zhijun He5d677d12016-05-29 16:52:39 -07001432
Shuzhen Wang0129d522016-10-30 22:43:41 -07001433 if (consumers.size() == 0 && !hasDeferredConsumer) {
1434 ALOGE("%s: Number of consumers cannot be smaller than 1", __FUNCTION__);
1435 return BAD_VALUE;
1436 }
Zhijun He5d677d12016-05-29 16:52:39 -07001437
Shuzhen Wang0129d522016-10-30 22:43:41 -07001438 if (hasDeferredConsumer && format != HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
Zhijun He5d677d12016-05-29 16:52:39 -07001439 ALOGE("Deferred consumer stream creation only support IMPLEMENTATION_DEFINED format");
1440 return BAD_VALUE;
1441 }
1442
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001443 if (isRawFormat(format) && sensorPixelModesUsed.size() > 1) {
1444 // We can't use one stream with a raw format in both sensor pixel modes since its going to
1445 // be found in only one sensor pixel mode.
1446 ALOGE("%s: RAW opaque stream cannot be used with > 1 sensor pixel modes", __FUNCTION__);
1447 return BAD_VALUE;
1448 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001449 if (format == HAL_PIXEL_FORMAT_BLOB) {
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -07001450 ssize_t blobBufferSize;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001451 if (dataSpace == HAL_DATASPACE_DEPTH) {
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -07001452 blobBufferSize = getPointCloudBufferSize();
1453 if (blobBufferSize <= 0) {
1454 SET_ERR_L("Invalid point cloud buffer size %zd", blobBufferSize);
1455 return BAD_VALUE;
1456 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001457 } else if (dataSpace == static_cast<android_dataspace>(HAL_DATASPACE_JPEG_APP_SEGMENTS)) {
1458 blobBufferSize = width * height;
1459 } else {
1460 blobBufferSize = getJpegBufferSize(width, height);
1461 if (blobBufferSize <= 0) {
1462 SET_ERR_L("Invalid jpeg buffer size %zd", blobBufferSize);
1463 return BAD_VALUE;
1464 }
Zhijun Hef7da0962014-04-24 13:27:56 -07001465 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001466 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001467 width, height, blobBufferSize, format, dataSpace, rotation,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001468 mTimestampOffset, physicalCameraId, sensorPixelModesUsed, streamSetId,
1469 isMultiResolution);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -08001470 } else if (format == HAL_PIXEL_FORMAT_RAW_OPAQUE) {
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001471 bool maxResolution =
1472 sensorPixelModesUsed.find(ANDROID_SENSOR_PIXEL_MODE_MAXIMUM_RESOLUTION) !=
1473 sensorPixelModesUsed.end();
1474 ssize_t rawOpaqueBufferSize = getRawOpaqueBufferSize(width, height, maxResolution);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -08001475 if (rawOpaqueBufferSize <= 0) {
1476 SET_ERR_L("Invalid RAW opaque buffer size %zd", rawOpaqueBufferSize);
1477 return BAD_VALUE;
1478 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001479 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001480 width, height, rawOpaqueBufferSize, format, dataSpace, rotation,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001481 mTimestampOffset, physicalCameraId, sensorPixelModesUsed, streamSetId,
1482 isMultiResolution);
Shuzhen Wang758c2152017-01-10 18:26:18 -08001483 } else if (isShared) {
1484 newStream = new Camera3SharedOutputStream(mNextStreamId, consumers,
1485 width, height, format, consumerUsage, dataSpace, rotation,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001486 mTimestampOffset, physicalCameraId, sensorPixelModesUsed, streamSetId,
1487 mUseHalBufManager);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001488 } else if (consumers.size() == 0 && hasDeferredConsumer) {
Zhijun He5d677d12016-05-29 16:52:39 -07001489 newStream = new Camera3OutputStream(mNextStreamId,
1490 width, height, format, consumerUsage, dataSpace, rotation,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001491 mTimestampOffset, physicalCameraId, sensorPixelModesUsed, streamSetId,
1492 isMultiResolution);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001493 } else {
Shuzhen Wang0129d522016-10-30 22:43:41 -07001494 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001495 width, height, format, dataSpace, rotation,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001496 mTimestampOffset, physicalCameraId, sensorPixelModesUsed, streamSetId,
1497 isMultiResolution);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001498 }
Emilian Peev40ead602017-09-26 15:46:36 +01001499
1500 size_t consumerCount = consumers.size();
1501 for (size_t i = 0; i < consumerCount; i++) {
1502 int id = newStream->getSurfaceId(consumers[i]);
1503 if (id < 0) {
1504 SET_ERR_L("Invalid surface id");
1505 return BAD_VALUE;
1506 }
1507 if (surfaceIds != nullptr) {
1508 surfaceIds->push_back(id);
1509 }
1510 }
1511
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001512 newStream->setStatusTracker(mStatusTracker);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001513
Emilian Peev08dd2452017-04-06 16:55:14 +01001514 newStream->setBufferManager(mBufferManager);
Zhijun He125684a2015-12-26 15:07:30 -08001515
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08001516 newStream->setImageDumpMask(mImageDumpMask);
1517
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001518 res = mOutputStreams.add(mNextStreamId, newStream);
1519 if (res < 0) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001520 SET_ERR_L("Can't add new stream to set: %s (%d)", strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001521 return res;
1522 }
1523
Shuzhen Wang316781a2020-08-18 18:11:01 -07001524 mSessionStatsBuilder.addStream(mNextStreamId);
1525
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001526 *id = mNextStreamId++;
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07001527 mNeedConfig = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001528
1529 // Continue captures if active at start
1530 if (wasActive) {
1531 ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001532 // Reuse current operating mode and session parameters for new stream config
1533 res = configureStreamsLocked(mOperatingMode, mSessionParams);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001534 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001535 CLOGE("Can't reconfigure device for new stream %d: %s (%d)",
1536 mNextStreamId, strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001537 return res;
1538 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001539 internalResumeLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001540 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001541 ALOGV("Camera %s: Created new stream", mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001542 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001543}
1544
Emilian Peev710c1422017-08-30 11:19:38 +01001545status_t Camera3Device::getStreamInfo(int id, StreamInfo *streamInfo) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001546 ATRACE_CALL();
Emilian Peev710c1422017-08-30 11:19:38 +01001547 if (nullptr == streamInfo) {
1548 return BAD_VALUE;
1549 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001550 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001551 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001552
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001553 switch (mStatus) {
1554 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001555 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001556 return INVALID_OPERATION;
1557 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001558 CLOGE("Device not initialized!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001559 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001560 case STATUS_UNCONFIGURED:
1561 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001562 case STATUS_ACTIVE:
1563 // OK
1564 break;
1565 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001566 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001567 return INVALID_OPERATION;
1568 }
1569
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001570 sp<Camera3StreamInterface> stream = mOutputStreams.get(id);
1571 if (stream == nullptr) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001572 CLOGE("Stream %d is unknown", id);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001573 return BAD_VALUE;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001574 }
1575
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001576 streamInfo->width = stream->getWidth();
1577 streamInfo->height = stream->getHeight();
1578 streamInfo->format = stream->getFormat();
1579 streamInfo->dataSpace = stream->getDataSpace();
1580 streamInfo->formatOverridden = stream->isFormatOverridden();
1581 streamInfo->originalFormat = stream->getOriginalFormat();
1582 streamInfo->dataSpaceOverridden = stream->isDataSpaceOverridden();
1583 streamInfo->originalDataSpace = stream->getOriginalDataSpace();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001584 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001585}
1586
1587status_t Camera3Device::setStreamTransform(int id,
1588 int transform) {
1589 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001590 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001591 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001592
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001593 switch (mStatus) {
1594 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001595 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001596 return INVALID_OPERATION;
1597 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001598 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001599 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001600 case STATUS_UNCONFIGURED:
1601 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001602 case STATUS_ACTIVE:
1603 // OK
1604 break;
1605 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001606 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001607 return INVALID_OPERATION;
1608 }
1609
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001610 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(id);
1611 if (stream == nullptr) {
1612 CLOGE("Stream %d does not exist", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001613 return BAD_VALUE;
1614 }
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001615 return stream->setTransform(transform);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001616}
1617
1618status_t Camera3Device::deleteStream(int id) {
1619 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001620 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001621 Mutex::Autolock l(mLock);
1622 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001623
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001624 ALOGV("%s: Camera %s: Deleting stream %d", __FUNCTION__, mId.string(), id);
Igor Murashkine2172be2013-05-28 15:31:39 -07001625
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001626 // CameraDevice semantics require device to already be idle before
1627 // deleteStream is called, unlike for createStream.
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001628 if (mStatus == STATUS_ACTIVE) {
Yin-Chia Yeh693047d2018-03-08 12:14:19 -08001629 ALOGW("%s: Camera %s: Device not idle", __FUNCTION__, mId.string());
Igor Murashkin52827132013-05-13 14:53:44 -07001630 return -EBUSY;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001631 }
1632
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07001633 if (mStatus == STATUS_ERROR) {
1634 ALOGW("%s: Camera %s: deleteStream not allowed in ERROR state",
1635 __FUNCTION__, mId.string());
1636 return -EBUSY;
1637 }
1638
Igor Murashkin2fba5842013-04-22 14:03:54 -07001639 sp<Camera3StreamInterface> deletedStream;
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001640 sp<Camera3StreamInterface> stream = mOutputStreams.get(id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001641 if (mInputStream != NULL && id == mInputStream->getId()) {
1642 deletedStream = mInputStream;
1643 mInputStream.clear();
1644 } else {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001645 if (stream == nullptr) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001646 CLOGE("Stream %d does not exist", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001647 return BAD_VALUE;
1648 }
Shuzhen Wang316781a2020-08-18 18:11:01 -07001649 mSessionStatsBuilder.removeStream(id);
Zhijun He5f446352014-01-22 09:49:33 -08001650 }
1651
1652 // Delete output stream or the output part of a bi-directional stream.
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001653 if (stream != nullptr) {
1654 deletedStream = stream;
1655 mOutputStreams.remove(id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001656 }
1657
1658 // Free up the stream endpoint so that it can be used by some other stream
1659 res = deletedStream->disconnect();
1660 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001661 SET_ERR_L("Can't disconnect deleted stream %d", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001662 // fall through since we want to still list the stream as deleted.
1663 }
1664 mDeletedStreams.add(deletedStream);
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07001665 mNeedConfig = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001666
1667 return res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001668}
1669
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001670status_t Camera3Device::configureStreams(const CameraMetadata& sessionParams, int operatingMode) {
Igor Murashkine2d167e2014-08-19 16:19:59 -07001671 ATRACE_CALL();
1672 ALOGV("%s: E", __FUNCTION__);
1673
1674 Mutex::Autolock il(mInterfaceLock);
1675 Mutex::Autolock l(mLock);
Chien-Yu Chen17338fc2015-06-18 16:30:12 -07001676
Emilian Peev811d2952018-05-25 11:08:40 +01001677 // In case the client doesn't include any session parameter, try a
1678 // speculative configuration using the values from the last cached
1679 // default request.
1680 if (sessionParams.isEmpty() &&
Emilian Peevf4816702020-04-03 15:44:51 -07001681 ((mLastTemplateId > 0) && (mLastTemplateId < CAMERA_TEMPLATE_COUNT)) &&
Emilian Peev811d2952018-05-25 11:08:40 +01001682 (!mRequestTemplateCache[mLastTemplateId].isEmpty())) {
1683 ALOGV("%s: Speculative session param configuration with template id: %d", __func__,
1684 mLastTemplateId);
1685 return filterParamsAndConfigureLocked(mRequestTemplateCache[mLastTemplateId],
1686 operatingMode);
1687 }
1688
Emilian Peevac3ce6c2017-12-12 15:27:02 +00001689 return filterParamsAndConfigureLocked(sessionParams, operatingMode);
1690}
1691
1692status_t Camera3Device::filterParamsAndConfigureLocked(const CameraMetadata& sessionParams,
1693 int operatingMode) {
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001694 //Filter out any incoming session parameters
1695 const CameraMetadata params(sessionParams);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001696 camera_metadata_entry_t availableSessionKeys = mDeviceInfo.find(
1697 ANDROID_REQUEST_AVAILABLE_SESSION_KEYS);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00001698 CameraMetadata filteredParams(availableSessionKeys.count);
1699 camera_metadata_t *meta = const_cast<camera_metadata_t *>(
1700 filteredParams.getAndLock());
1701 set_camera_metadata_vendor_id(meta, mVendorTagId);
1702 filteredParams.unlock(meta);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001703 if (availableSessionKeys.count > 0) {
1704 for (size_t i = 0; i < availableSessionKeys.count; i++) {
1705 camera_metadata_ro_entry entry = params.find(
1706 availableSessionKeys.data.i32[i]);
1707 if (entry.count > 0) {
1708 filteredParams.update(entry);
1709 }
1710 }
1711 }
1712
1713 return configureStreamsLocked(operatingMode, filteredParams);
Igor Murashkine2d167e2014-08-19 16:19:59 -07001714}
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001715
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07001716status_t Camera3Device::getInputBufferProducer(
1717 sp<IGraphicBufferProducer> *producer) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07001718 ATRACE_CALL();
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07001719 Mutex::Autolock il(mInterfaceLock);
1720 Mutex::Autolock l(mLock);
1721
1722 if (producer == NULL) {
1723 return BAD_VALUE;
1724 } else if (mInputStream == NULL) {
1725 return INVALID_OPERATION;
1726 }
1727
1728 return mInputStream->getInputBufferProducer(producer);
1729}
1730
Emilian Peevf4816702020-04-03 15:44:51 -07001731status_t Camera3Device::createDefaultRequest(camera_request_template_t templateId,
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001732 CameraMetadata *request) {
1733 ATRACE_CALL();
Alex Rayfe7e0c62013-05-30 00:12:13 -07001734 ALOGV("%s: for template %d", __FUNCTION__, templateId);
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08001735
Emilian Peevf4816702020-04-03 15:44:51 -07001736 if (templateId <= 0 || templateId >= CAMERA_TEMPLATE_COUNT) {
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08001737 android_errorWriteWithInfoLog(CameraService::SN_EVENT_LOG_ID, "26866110",
Jayant Chowdhary12361932018-08-27 14:46:13 -07001738 CameraThreadState::getCallingUid(), nullptr, 0);
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08001739 return BAD_VALUE;
1740 }
1741
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001742 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001743
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001744 {
1745 Mutex::Autolock l(mLock);
1746 switch (mStatus) {
1747 case STATUS_ERROR:
1748 CLOGE("Device has encountered a serious error");
1749 return INVALID_OPERATION;
1750 case STATUS_UNINITIALIZED:
1751 CLOGE("Device is not initialized!");
1752 return INVALID_OPERATION;
1753 case STATUS_UNCONFIGURED:
1754 case STATUS_CONFIGURED:
1755 case STATUS_ACTIVE:
1756 // OK
1757 break;
1758 default:
1759 SET_ERR_L("Unexpected status: %d", mStatus);
1760 return INVALID_OPERATION;
1761 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001762
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001763 if (!mRequestTemplateCache[templateId].isEmpty()) {
1764 *request = mRequestTemplateCache[templateId];
Emilian Peev811d2952018-05-25 11:08:40 +01001765 mLastTemplateId = templateId;
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001766 return OK;
1767 }
Zhijun Hea1530f12014-09-14 12:44:20 -07001768 }
1769
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001770 camera_metadata_t *rawRequest;
1771 status_t res = mInterface->constructDefaultRequestSettings(
Emilian Peevf4816702020-04-03 15:44:51 -07001772 (camera_request_template_t) templateId, &rawRequest);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001773
1774 {
1775 Mutex::Autolock l(mLock);
1776 if (res == BAD_VALUE) {
1777 ALOGI("%s: template %d is not supported on this camera device",
1778 __FUNCTION__, templateId);
1779 return res;
1780 } else if (res != OK) {
1781 CLOGE("Unable to construct request template %d: %s (%d)",
1782 templateId, strerror(-res), res);
1783 return res;
1784 }
1785
1786 set_camera_metadata_vendor_id(rawRequest, mVendorTagId);
1787 mRequestTemplateCache[templateId].acquire(rawRequest);
1788
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08001789 // Override the template request with zoomRatioMapper
1790 res = mZoomRatioMappers[mId.c_str()].initZoomRatioInTemplate(
1791 &mRequestTemplateCache[templateId]);
1792 if (res != OK) {
1793 CLOGE("Failed to update zoom ratio for template %d: %s (%d)",
1794 templateId, strerror(-res), res);
1795 return res;
1796 }
1797
Shuzhen Wangd25dc972020-03-24 17:11:43 -07001798 // Fill in JPEG_QUALITY if not available
1799 if (!mRequestTemplateCache[templateId].exists(ANDROID_JPEG_QUALITY)) {
1800 static const uint8_t kDefaultJpegQuality = 95;
1801 mRequestTemplateCache[templateId].update(ANDROID_JPEG_QUALITY,
1802 &kDefaultJpegQuality, 1);
1803 }
1804
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001805 *request = mRequestTemplateCache[templateId];
Emilian Peev811d2952018-05-25 11:08:40 +01001806 mLastTemplateId = templateId;
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001807 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001808 return OK;
1809}
1810
1811status_t Camera3Device::waitUntilDrained() {
1812 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001813 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001814 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001815 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001816
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001817 return waitUntilDrainedLocked(maxExpectedDuration);
Zhijun He69a37482014-03-23 18:44:49 -07001818}
1819
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001820status_t Camera3Device::waitUntilDrainedLocked(nsecs_t maxExpectedDuration) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001821 switch (mStatus) {
1822 case STATUS_UNINITIALIZED:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001823 case STATUS_UNCONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001824 ALOGV("%s: Already idle", __FUNCTION__);
1825 return OK;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001826 case STATUS_CONFIGURED:
1827 // To avoid race conditions, check with tracker to be sure
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001828 case STATUS_ERROR:
1829 case STATUS_ACTIVE:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001830 // Need to verify shut down
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001831 break;
1832 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001833 SET_ERR_L("Unexpected status: %d",mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001834 return INVALID_OPERATION;
1835 }
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07001836 ALOGV("%s: Camera %s: Waiting until idle (%" PRIi64 "ns)", __FUNCTION__, mId.string(),
1837 maxExpectedDuration);
1838 status_t res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
Eino-Ville Talvala9c8a0912014-09-14 14:52:19 -07001839 if (res != OK) {
Yin-Chia Yeh87b3ec02019-06-03 10:44:39 -07001840 mStatusTracker->dumpActiveComponents();
Eino-Ville Talvala9c8a0912014-09-14 14:52:19 -07001841 SET_ERR_L("Error waiting for HAL to drain: %s (%d)", strerror(-res),
1842 res);
1843 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001844 return res;
1845}
1846
Ruben Brunk183f0562015-08-12 12:55:02 -07001847void Camera3Device::internalUpdateStatusLocked(Status status) {
1848 mStatus = status;
1849 mRecentStatusUpdates.add(mStatus);
1850 mStatusChanged.broadcast();
1851}
1852
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001853// Pause to reconfigure
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001854status_t Camera3Device::internalPauseAndWaitLocked(nsecs_t maxExpectedDuration) {
Emilian Peeve86358b2019-02-15 13:51:39 -08001855 if (mRequestThread.get() != nullptr) {
1856 mRequestThread->setPaused(true);
1857 } else {
1858 return NO_INIT;
1859 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001860
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07001861 ALOGV("%s: Camera %s: Internal wait until idle (% " PRIi64 " ns)", __FUNCTION__, mId.string(),
1862 maxExpectedDuration);
1863 status_t res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001864 if (res != OK) {
1865 SET_ERR_L("Can't idle device in %f seconds!",
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07001866 maxExpectedDuration/1e9);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001867 }
1868
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001869 return res;
1870}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001871
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001872// Resume after internalPauseAndWaitLocked
1873status_t Camera3Device::internalResumeLocked() {
1874 status_t res;
1875
1876 mRequestThread->setPaused(false);
1877
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08001878 ALOGV("%s: Camera %s: Internal wait until active (% " PRIi64 " ns)", __FUNCTION__, mId.string(),
1879 kActiveTimeout);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001880 res = waitUntilStateThenRelock(/*active*/ true, kActiveTimeout);
1881 if (res != OK) {
1882 SET_ERR_L("Can't transition to active in %f seconds!",
1883 kActiveTimeout/1e9);
1884 }
1885 mPauseStateNotify = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001886 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001887}
1888
Ruben Brunk183f0562015-08-12 12:55:02 -07001889status_t Camera3Device::waitUntilStateThenRelock(bool active, nsecs_t timeout) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001890 status_t res = OK;
Ruben Brunk183f0562015-08-12 12:55:02 -07001891
1892 size_t startIndex = 0;
1893 if (mStatusWaiters == 0) {
1894 // Clear the list of recent statuses if there are no existing threads waiting on updates to
1895 // this status list
1896 mRecentStatusUpdates.clear();
1897 } else {
1898 // If other threads are waiting on updates to this status list, set the position of the
1899 // first element that this list will check rather than clearing the list.
1900 startIndex = mRecentStatusUpdates.size();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001901 }
1902
Ruben Brunk183f0562015-08-12 12:55:02 -07001903 mStatusWaiters++;
1904
Yin-Chia Yehe52b8fa2020-07-28 00:17:58 -07001905 bool signalPipelineDrain = false;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07001906 if (!active && mUseHalBufManager) {
1907 auto streamIds = mOutputStreams.getStreamIds();
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08001908 if (mStatus == STATUS_ACTIVE) {
1909 mRequestThread->signalPipelineDrain(streamIds);
Yin-Chia Yehe52b8fa2020-07-28 00:17:58 -07001910 signalPipelineDrain = true;
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08001911 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07001912 mRequestBufferSM.onWaitUntilIdle();
1913 }
1914
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001915 bool stateSeen = false;
1916 do {
Ruben Brunk183f0562015-08-12 12:55:02 -07001917 if (active == (mStatus == STATUS_ACTIVE)) {
1918 // Desired state is current
1919 break;
1920 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001921
1922 res = mStatusChanged.waitRelative(mLock, timeout);
1923 if (res != OK) break;
1924
Ruben Brunk183f0562015-08-12 12:55:02 -07001925 // This is impossible, but if not, could result in subtle deadlocks and invalid state
1926 // transitions.
1927 LOG_ALWAYS_FATAL_IF(startIndex > mRecentStatusUpdates.size(),
1928 "%s: Skipping status updates in Camera3Device, may result in deadlock.",
1929 __FUNCTION__);
1930
1931 // Encountered desired state since we began waiting
1932 for (size_t i = startIndex; i < mRecentStatusUpdates.size(); i++) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001933 if (active == (mRecentStatusUpdates[i] == STATUS_ACTIVE) ) {
1934 stateSeen = true;
1935 break;
1936 }
1937 }
1938 } while (!stateSeen);
1939
Yin-Chia Yehe52b8fa2020-07-28 00:17:58 -07001940 if (signalPipelineDrain) {
1941 mRequestThread->resetPipelineDrain();
1942 }
1943
Ruben Brunk183f0562015-08-12 12:55:02 -07001944 mStatusWaiters--;
1945
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001946 return res;
1947}
1948
1949
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001950status_t Camera3Device::setNotifyCallback(wp<NotificationListener> listener) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001951 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001952 std::lock_guard<std::mutex> l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001953
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001954 if (listener != NULL && mListener != NULL) {
1955 ALOGW("%s: Replacing old callback listener", __FUNCTION__);
1956 }
1957 mListener = listener;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001958 mRequestThread->setNotificationListener(listener);
1959 mPreparerThread->setNotificationListener(listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001960
1961 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001962}
1963
Eino-Ville Talvala46910bd2013-07-18 19:15:17 -07001964bool Camera3Device::willNotify3A() {
1965 return false;
1966}
1967
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001968status_t Camera3Device::waitForNextFrame(nsecs_t timeout) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07001969 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001970 std::unique_lock<std::mutex> l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001971
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001972 while (mResultQueue.empty()) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001973 auto st = mResultSignal.wait_for(l, std::chrono::nanoseconds(timeout));
1974 if (st == std::cv_status::timeout) {
1975 return TIMED_OUT;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001976 }
1977 }
1978 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001979}
1980
Jianing Weicb0652e2014-03-12 18:29:36 -07001981status_t Camera3Device::getNextResult(CaptureResult *frame) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001982 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001983 std::lock_guard<std::mutex> l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001984
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001985 if (mResultQueue.empty()) {
1986 return NOT_ENOUGH_DATA;
1987 }
1988
Jianing Weicb0652e2014-03-12 18:29:36 -07001989 if (frame == NULL) {
1990 ALOGE("%s: argument cannot be NULL", __FUNCTION__);
1991 return BAD_VALUE;
1992 }
1993
1994 CaptureResult &result = *(mResultQueue.begin());
1995 frame->mResultExtras = result.mResultExtras;
1996 frame->mMetadata.acquire(result.mMetadata);
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001997 frame->mPhysicalMetadatas = std::move(result.mPhysicalMetadatas);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001998 mResultQueue.erase(mResultQueue.begin());
1999
2000 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002001}
2002
2003status_t Camera3Device::triggerAutofocus(uint32_t id) {
2004 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002005 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002006
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002007 ALOGV("%s: Triggering autofocus, id %d", __FUNCTION__, id);
2008 // Mix-in this trigger into the next request and only the next request.
2009 RequestTrigger trigger[] = {
2010 {
2011 ANDROID_CONTROL_AF_TRIGGER,
2012 ANDROID_CONTROL_AF_TRIGGER_START
2013 },
2014 {
2015 ANDROID_CONTROL_AF_TRIGGER_ID,
2016 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07002017 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002018 };
2019
2020 return mRequestThread->queueTrigger(trigger,
2021 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002022}
2023
2024status_t Camera3Device::triggerCancelAutofocus(uint32_t id) {
2025 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002026 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002027
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002028 ALOGV("%s: Triggering cancel autofocus, id %d", __FUNCTION__, id);
2029 // Mix-in this trigger into the next request and only the next request.
2030 RequestTrigger trigger[] = {
2031 {
2032 ANDROID_CONTROL_AF_TRIGGER,
2033 ANDROID_CONTROL_AF_TRIGGER_CANCEL
2034 },
2035 {
2036 ANDROID_CONTROL_AF_TRIGGER_ID,
2037 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07002038 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002039 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002040
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002041 return mRequestThread->queueTrigger(trigger,
2042 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002043}
2044
2045status_t Camera3Device::triggerPrecaptureMetering(uint32_t id) {
2046 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002047 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002048
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002049 ALOGV("%s: Triggering precapture metering, id %d", __FUNCTION__, id);
2050 // Mix-in this trigger into the next request and only the next request.
2051 RequestTrigger trigger[] = {
2052 {
2053 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER,
2054 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_START
2055 },
2056 {
2057 ANDROID_CONTROL_AE_PRECAPTURE_ID,
2058 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07002059 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002060 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002061
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002062 return mRequestThread->queueTrigger(trigger,
2063 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002064}
2065
Jianing Weicb0652e2014-03-12 18:29:36 -07002066status_t Camera3Device::flush(int64_t *frameNumber) {
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07002067 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002068 ALOGV("%s: Camera %s: Flushing all requests", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002069 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07002070
Zhijun He7ef20392014-04-21 16:04:17 -07002071 {
2072 Mutex::Autolock l(mLock);
Emilian Peeved2ebe42018-09-25 16:59:09 +01002073
2074 // b/116514106 "disconnect()" can get called twice for the same device. The
2075 // camera device will not be initialized during the second run.
2076 if (mStatus == STATUS_UNINITIALIZED) {
2077 return OK;
2078 }
2079
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002080 mRequestThread->clear(/*out*/frameNumber);
Shuzhen Wang316781a2020-08-18 18:11:01 -07002081
2082 // Stop session and stream counter
2083 mSessionStatsBuilder.stopCounter();
Zhijun He7ef20392014-04-21 16:04:17 -07002084 }
2085
Emilian Peev08dd2452017-04-06 16:55:14 +01002086 return mRequestThread->flush();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07002087}
2088
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002089status_t Camera3Device::prepare(int streamId) {
Ruben Brunkc78ac262015-08-13 17:58:46 -07002090 return prepare(camera3::Camera3StreamInterface::ALLOCATE_PIPELINE_MAX, streamId);
2091}
2092
2093status_t Camera3Device::prepare(int maxCount, int streamId) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002094 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002095 ALOGV("%s: Camera %s: Preparing stream %d", __FUNCTION__, mId.string(), streamId);
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07002096 Mutex::Autolock il(mInterfaceLock);
2097 Mutex::Autolock l(mLock);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002098
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002099 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
2100 if (stream == nullptr) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002101 CLOGE("Stream %d does not exist", streamId);
2102 return BAD_VALUE;
2103 }
2104
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002105 if (stream->isUnpreparable() || stream->hasOutstandingBuffers() ) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07002106 CLOGE("Stream %d has already been a request target", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002107 return BAD_VALUE;
2108 }
2109
2110 if (mRequestThread->isStreamPending(stream)) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07002111 CLOGE("Stream %d is already a target in a pending request", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002112 return BAD_VALUE;
2113 }
2114
Ruben Brunkc78ac262015-08-13 17:58:46 -07002115 return mPreparerThread->prepare(maxCount, stream);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002116}
2117
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002118status_t Camera3Device::tearDown(int streamId) {
2119 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002120 ALOGV("%s: Camera %s: Tearing down stream %d", __FUNCTION__, mId.string(), streamId);
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002121 Mutex::Autolock il(mInterfaceLock);
2122 Mutex::Autolock l(mLock);
2123
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002124 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
2125 if (stream == nullptr) {
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002126 CLOGE("Stream %d does not exist", streamId);
2127 return BAD_VALUE;
2128 }
2129
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002130 if (stream->hasOutstandingBuffers() || mRequestThread->isStreamPending(stream)) {
2131 CLOGE("Stream %d is a target of a in-progress request", streamId);
2132 return BAD_VALUE;
2133 }
2134
2135 return stream->tearDown();
2136}
2137
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002138status_t Camera3Device::addBufferListenerForStream(int streamId,
2139 wp<Camera3StreamBufferListener> listener) {
2140 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002141 ALOGV("%s: Camera %s: Adding buffer listener for stream %d", __FUNCTION__, mId.string(), streamId);
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002142 Mutex::Autolock il(mInterfaceLock);
2143 Mutex::Autolock l(mLock);
2144
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002145 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
2146 if (stream == nullptr) {
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002147 CLOGE("Stream %d does not exist", streamId);
2148 return BAD_VALUE;
2149 }
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002150 stream->addBufferListener(listener);
2151
2152 return OK;
2153}
2154
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002155/**
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002156 * Methods called by subclasses
2157 */
2158
2159void Camera3Device::notifyStatus(bool idle) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002160 ATRACE_CALL();
Shuzhen Wang316781a2020-08-18 18:11:01 -07002161 std::vector<int> streamIds;
2162 std::vector<hardware::CameraStreamStats> streamStats;
2163
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002164 {
2165 // Need mLock to safely update state and synchronize to current
2166 // state of methods in flight.
2167 Mutex::Autolock l(mLock);
2168 // We can get various system-idle notices from the status tracker
2169 // while starting up. Only care about them if we've actually sent
2170 // in some requests recently.
2171 if (mStatus != STATUS_ACTIVE && mStatus != STATUS_CONFIGURED) {
2172 return;
2173 }
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08002174 ALOGV("%s: Camera %s: Now %s, pauseState: %s", __FUNCTION__, mId.string(),
2175 idle ? "idle" : "active", mPauseStateNotify ? "true" : "false");
Ruben Brunk183f0562015-08-12 12:55:02 -07002176 internalUpdateStatusLocked(idle ? STATUS_CONFIGURED : STATUS_ACTIVE);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002177
2178 // Skip notifying listener if we're doing some user-transparent
2179 // state changes
2180 if (mPauseStateNotify) return;
Shuzhen Wang316781a2020-08-18 18:11:01 -07002181
2182 // Populate stream statistics in case of Idle
2183 if (idle) {
2184 for (size_t i = 0; i < mOutputStreams.size(); i++) {
2185 auto stream = mOutputStreams[i];
2186 if (stream.get() == nullptr) continue;
2187 streamIds.push_back(stream->getId());
2188 Camera3Stream* camera3Stream = Camera3Stream::cast(stream->asHalStream());
2189 int64_t usage = 0LL;
2190 if (camera3Stream != nullptr) {
2191 usage = camera3Stream->getUsage();
2192 }
2193 streamStats.emplace_back(stream->getWidth(), stream->getHeight(),
2194 stream->getFormat(), stream->getDataSpace(), usage,
2195 stream->getMaxHalBuffers(),
2196 stream->getMaxTotalBuffers() - stream->getMaxHalBuffers());
2197 }
2198 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002199 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002200
2201 sp<NotificationListener> listener;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002202 {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002203 std::lock_guard<std::mutex> l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002204 listener = mListener.promote();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002205 }
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07002206 status_t res = OK;
2207 if (listener != nullptr) {
2208 if (idle) {
2209 // Get session stats from the builder, and notify the listener.
2210 int64_t requestCount, resultErrorCount;
2211 bool deviceError;
2212 std::map<int, StreamStats> streamStatsMap;
2213 mSessionStatsBuilder.buildAndReset(&requestCount, &resultErrorCount,
2214 &deviceError, &streamStatsMap);
2215 for (size_t i = 0; i < streamIds.size(); i++) {
2216 int streamId = streamIds[i];
2217 auto stats = streamStatsMap.find(streamId);
2218 if (stats != streamStatsMap.end()) {
2219 streamStats[i].mRequestCount = stats->second.mRequestedFrameCount;
2220 streamStats[i].mErrorCount = stats->second.mDroppedFrameCount;
2221 streamStats[i].mStartLatencyMs = stats->second.mStartLatencyMs;
2222 streamStats[i].mHistogramType =
2223 hardware::CameraStreamStats::HISTOGRAM_TYPE_CAPTURE_LATENCY;
2224 streamStats[i].mHistogramBins.assign(
2225 stats->second.mCaptureLatencyBins.begin(),
2226 stats->second.mCaptureLatencyBins.end());
2227 streamStats[i].mHistogramCounts.assign(
2228 stats->second.mCaptureLatencyHistogram.begin(),
2229 stats->second.mCaptureLatencyHistogram.end());
2230 }
Shuzhen Wang316781a2020-08-18 18:11:01 -07002231 }
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07002232 listener->notifyIdle(requestCount, resultErrorCount, deviceError, streamStats);
2233 } else {
2234 res = listener->notifyActive();
Shuzhen Wang316781a2020-08-18 18:11:01 -07002235 }
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07002236 }
2237 if (res != OK) {
2238 SET_ERR("Camera access permission lost mid-operation: %s (%d)",
2239 strerror(-res), res);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002240 }
2241}
2242
Shuzhen Wang758c2152017-01-10 18:26:18 -08002243status_t Camera3Device::setConsumerSurfaces(int streamId,
Emilian Peev40ead602017-09-26 15:46:36 +01002244 const std::vector<sp<Surface>>& consumers, std::vector<int> *surfaceIds) {
Zhijun He5d677d12016-05-29 16:52:39 -07002245 ATRACE_CALL();
Shuzhen Wang758c2152017-01-10 18:26:18 -08002246 ALOGV("%s: Camera %s: set consumer surface for stream %d",
2247 __FUNCTION__, mId.string(), streamId);
Emilian Peev40ead602017-09-26 15:46:36 +01002248
2249 if (surfaceIds == nullptr) {
2250 return BAD_VALUE;
2251 }
2252
Zhijun He5d677d12016-05-29 16:52:39 -07002253 Mutex::Autolock il(mInterfaceLock);
2254 Mutex::Autolock l(mLock);
2255
Shuzhen Wang758c2152017-01-10 18:26:18 -08002256 if (consumers.size() == 0) {
2257 CLOGE("No consumer is passed!");
Zhijun He5d677d12016-05-29 16:52:39 -07002258 return BAD_VALUE;
2259 }
2260
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002261 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
2262 if (stream == nullptr) {
Zhijun He5d677d12016-05-29 16:52:39 -07002263 CLOGE("Stream %d is unknown", streamId);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002264 return BAD_VALUE;
Zhijun He5d677d12016-05-29 16:52:39 -07002265 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002266
2267 // isConsumerConfigurationDeferred will be off after setConsumers
2268 bool isDeferred = stream->isConsumerConfigurationDeferred();
Shuzhen Wang758c2152017-01-10 18:26:18 -08002269 status_t res = stream->setConsumers(consumers);
Zhijun He5d677d12016-05-29 16:52:39 -07002270 if (res != OK) {
2271 CLOGE("Stream %d set consumer failed (error %d %s) ", streamId, res, strerror(-res));
2272 return res;
2273 }
2274
Emilian Peev40ead602017-09-26 15:46:36 +01002275 for (auto &consumer : consumers) {
2276 int id = stream->getSurfaceId(consumer);
2277 if (id < 0) {
2278 CLOGE("Invalid surface id!");
2279 return BAD_VALUE;
2280 }
2281 surfaceIds->push_back(id);
2282 }
2283
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002284 if (isDeferred) {
Shuzhen Wang0129d522016-10-30 22:43:41 -07002285 if (!stream->isConfiguring()) {
2286 CLOGE("Stream %d was already fully configured.", streamId);
2287 return INVALID_OPERATION;
2288 }
Zhijun He5d677d12016-05-29 16:52:39 -07002289
Shuzhen Wang0129d522016-10-30 22:43:41 -07002290 res = stream->finishConfiguration();
2291 if (res != OK) {
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002292 // If finishConfiguration fails due to abandoned surface, do not set
2293 // device to error state.
2294 bool isSurfaceAbandoned =
2295 (res == NO_INIT || res == DEAD_OBJECT) && stream->isAbandoned();
2296 if (!isSurfaceAbandoned) {
2297 SET_ERR_L("Can't finish configuring output stream %d: %s (%d)",
2298 stream->getId(), strerror(-res), res);
2299 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07002300 return res;
2301 }
Zhijun He5d677d12016-05-29 16:52:39 -07002302 }
2303
2304 return OK;
2305}
2306
Emilian Peev40ead602017-09-26 15:46:36 +01002307status_t Camera3Device::updateStream(int streamId, const std::vector<sp<Surface>> &newSurfaces,
2308 const std::vector<OutputStreamInfo> &outputInfo,
2309 const std::vector<size_t> &removedSurfaceIds, KeyedVector<sp<Surface>, size_t> *outputMap) {
2310 Mutex::Autolock il(mInterfaceLock);
2311 Mutex::Autolock l(mLock);
2312
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002313 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
2314 if (stream == nullptr) {
Emilian Peev40ead602017-09-26 15:46:36 +01002315 CLOGE("Stream %d is unknown", streamId);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002316 return BAD_VALUE;
Emilian Peev40ead602017-09-26 15:46:36 +01002317 }
2318
2319 for (const auto &it : removedSurfaceIds) {
2320 if (mRequestThread->isOutputSurfacePending(streamId, it)) {
2321 CLOGE("Shared surface still part of a pending request!");
2322 return -EBUSY;
2323 }
2324 }
2325
Emilian Peev40ead602017-09-26 15:46:36 +01002326 status_t res = stream->updateStream(newSurfaces, outputInfo, removedSurfaceIds, outputMap);
2327 if (res != OK) {
2328 CLOGE("Stream %d failed to update stream (error %d %s) ",
2329 streamId, res, strerror(-res));
2330 if (res == UNKNOWN_ERROR) {
2331 SET_ERR_L("%s: Stream update failed to revert to previous output configuration!",
2332 __FUNCTION__);
2333 }
2334 return res;
2335 }
2336
2337 return res;
2338}
2339
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002340status_t Camera3Device::dropStreamBuffers(bool dropping, int streamId) {
2341 Mutex::Autolock il(mInterfaceLock);
2342 Mutex::Autolock l(mLock);
2343
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002344 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
2345 if (stream == nullptr) {
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002346 ALOGE("%s: Stream %d is not found.", __FUNCTION__, streamId);
2347 return BAD_VALUE;
2348 }
Shuzhen Wang316781a2020-08-18 18:11:01 -07002349
2350 if (dropping) {
2351 mSessionStatsBuilder.stopCounter(streamId);
2352 } else {
2353 mSessionStatsBuilder.startCounter(streamId);
2354 }
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002355 return stream->dropBuffers(dropping);
2356}
2357
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002358/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002359 * Camera3Device private methods
2360 */
2361
2362sp<Camera3Device::CaptureRequest> Camera3Device::createCaptureRequest(
Emilian Peevaebbe412018-01-15 13:53:24 +00002363 const PhysicalCameraSettingsList &request, const SurfaceMap &surfaceMap) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002364 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002365
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08002366 sp<CaptureRequest> newRequest = new CaptureRequest();
Emilian Peevaebbe412018-01-15 13:53:24 +00002367 newRequest->mSettingsList = request;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002368
2369 camera_metadata_entry_t inputStreams =
Emilian Peevaebbe412018-01-15 13:53:24 +00002370 newRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_INPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002371 if (inputStreams.count > 0) {
2372 if (mInputStream == NULL ||
Zhijun Hed1d64672013-09-06 15:00:01 -07002373 mInputStream->getId() != inputStreams.data.i32[0]) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002374 CLOGE("Request references unknown input stream %d",
2375 inputStreams.data.u8[0]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002376 return NULL;
2377 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002378
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002379 if (mInputStream->isConfiguring()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002380 SET_ERR_L("%s: input stream %d is not configured!",
2381 __FUNCTION__, mInputStream->getId());
2382 return NULL;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002383 }
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07002384 // Check if stream prepare is blocking requests.
2385 if (mInputStream->isBlockedByPrepare()) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002386 CLOGE("Request references an input stream that's being prepared!");
2387 return NULL;
2388 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002389
2390 newRequest->mInputStream = mInputStream;
Emilian Peevaebbe412018-01-15 13:53:24 +00002391 newRequest->mSettingsList.begin()->metadata.erase(ANDROID_REQUEST_INPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002392 }
2393
2394 camera_metadata_entry_t streams =
Emilian Peevaebbe412018-01-15 13:53:24 +00002395 newRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_OUTPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002396 if (streams.count == 0) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002397 CLOGE("Zero output streams specified!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002398 return NULL;
2399 }
2400
2401 for (size_t i = 0; i < streams.count; i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002402 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streams.data.i32[i]);
2403 if (stream == nullptr) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002404 CLOGE("Request references unknown stream %d",
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002405 streams.data.i32[i]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002406 return NULL;
2407 }
Zhijun He5d677d12016-05-29 16:52:39 -07002408 // It is illegal to include a deferred consumer output stream into a request
Shuzhen Wang0129d522016-10-30 22:43:41 -07002409 auto iter = surfaceMap.find(streams.data.i32[i]);
2410 if (iter != surfaceMap.end()) {
2411 const std::vector<size_t>& surfaces = iter->second;
2412 for (const auto& surface : surfaces) {
2413 if (stream->isConsumerConfigurationDeferred(surface)) {
2414 CLOGE("Stream %d surface %zu hasn't finished configuration yet "
2415 "due to deferred consumer", stream->getId(), surface);
2416 return NULL;
2417 }
2418 }
Yin-Chia Yeh0b287572018-10-15 12:38:13 -07002419 newRequest->mOutputSurfaces[streams.data.i32[i]] = surfaces;
Zhijun He5d677d12016-05-29 16:52:39 -07002420 }
2421
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002422 if (stream->isConfiguring()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002423 SET_ERR_L("%s: stream %d is not configured!", __FUNCTION__, stream->getId());
2424 return NULL;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002425 }
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07002426 // Check if stream prepare is blocking requests.
2427 if (stream->isBlockedByPrepare()) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002428 CLOGE("Request references an output stream that's being prepared!");
2429 return NULL;
2430 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002431
2432 newRequest->mOutputStreams.push(stream);
2433 }
Emilian Peevaebbe412018-01-15 13:53:24 +00002434 newRequest->mSettingsList.begin()->metadata.erase(ANDROID_REQUEST_OUTPUT_STREAMS);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07002435 newRequest->mBatchSize = 1;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002436
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08002437 auto rotateAndCropEntry =
2438 newRequest->mSettingsList.begin()->metadata.find(ANDROID_SCALER_ROTATE_AND_CROP);
2439 if (rotateAndCropEntry.count > 0 &&
2440 rotateAndCropEntry.data.u8[0] == ANDROID_SCALER_ROTATE_AND_CROP_AUTO) {
2441 newRequest->mRotateAndCropAuto = true;
2442 } else {
2443 newRequest->mRotateAndCropAuto = false;
2444 }
2445
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07002446 auto zoomRatioEntry =
2447 newRequest->mSettingsList.begin()->metadata.find(ANDROID_CONTROL_ZOOM_RATIO);
2448 if (zoomRatioEntry.count > 0 &&
2449 zoomRatioEntry.data.f[0] == 1.0f) {
2450 newRequest->mZoomRatioIs1x = true;
2451 } else {
2452 newRequest->mZoomRatioIs1x = false;
2453 }
2454
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08002455 if (mSupportCameraMute) {
2456 auto testPatternModeEntry =
2457 newRequest->mSettingsList.begin()->metadata.find(ANDROID_SENSOR_TEST_PATTERN_MODE);
2458 newRequest->mOriginalTestPatternMode = testPatternModeEntry.count > 0 ?
2459 testPatternModeEntry.data.i32[0] :
2460 ANDROID_SENSOR_TEST_PATTERN_MODE_OFF;
2461
2462 auto testPatternDataEntry =
2463 newRequest->mSettingsList.begin()->metadata.find(ANDROID_SENSOR_TEST_PATTERN_DATA);
2464 if (testPatternDataEntry.count > 0) {
2465 memcpy(newRequest->mOriginalTestPatternData, testPatternModeEntry.data.i32,
2466 sizeof(newRequest->mOriginalTestPatternData));
2467 } else {
2468 newRequest->mOriginalTestPatternData[0] = 0;
2469 newRequest->mOriginalTestPatternData[1] = 0;
2470 newRequest->mOriginalTestPatternData[2] = 0;
2471 newRequest->mOriginalTestPatternData[3] = 0;
2472 }
2473 }
2474
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002475 return newRequest;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002476}
2477
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002478void Camera3Device::cancelStreamsConfigurationLocked() {
2479 int res = OK;
2480 if (mInputStream != NULL && mInputStream->isConfiguring()) {
2481 res = mInputStream->cancelConfiguration();
2482 if (res != OK) {
2483 CLOGE("Can't cancel configuring input stream %d: %s (%d)",
2484 mInputStream->getId(), strerror(-res), res);
2485 }
2486 }
2487
2488 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002489 sp<Camera3OutputStreamInterface> outputStream = mOutputStreams[i];
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002490 if (outputStream->isConfiguring()) {
2491 res = outputStream->cancelConfiguration();
2492 if (res != OK) {
2493 CLOGE("Can't cancel configuring output stream %d: %s (%d)",
2494 outputStream->getId(), strerror(-res), res);
2495 }
2496 }
2497 }
2498
2499 // Return state to that at start of call, so that future configures
2500 // properly clean things up
2501 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
2502 mNeedConfig = true;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002503
2504 res = mPreparerThread->resume();
2505 if (res != OK) {
2506 ALOGE("%s: Camera %s: Preparer thread failed to resume!", __FUNCTION__, mId.string());
2507 }
2508}
2509
Emilian Peev0d0191e2020-04-21 17:01:18 -07002510bool Camera3Device::checkAbandonedStreamsLocked() {
2511 if ((mInputStream.get() != nullptr) && (mInputStream->isAbandoned())) {
2512 return true;
2513 }
2514
2515 for (size_t i = 0; i < mOutputStreams.size(); i++) {
2516 auto stream = mOutputStreams[i];
2517 if ((stream.get() != nullptr) && (stream->isAbandoned())) {
2518 return true;
2519 }
2520 }
2521
2522 return false;
2523}
2524
Emilian Peev3bead5f2020-05-28 17:29:08 -07002525bool Camera3Device::reconfigureCamera(const CameraMetadata& sessionParams, int clientStatusId) {
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002526 ATRACE_CALL();
2527 bool ret = false;
2528
Shuzhen Wang316781a2020-08-18 18:11:01 -07002529 nsecs_t startTime = systemTime();
2530
Jayant Chowdhary646c31b2020-01-30 13:09:59 -08002531 Mutex::Autolock il(mInterfaceLock);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002532 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
2533
2534 Mutex::Autolock l(mLock);
Emilian Peev0d0191e2020-04-21 17:01:18 -07002535 if (checkAbandonedStreamsLocked()) {
2536 ALOGW("%s: Abandoned stream detected, session parameters can't be applied correctly!",
2537 __FUNCTION__);
2538 return true;
2539 }
2540
Emilian Peev3bead5f2020-05-28 17:29:08 -07002541 status_t rc = NO_ERROR;
2542 bool markClientActive = false;
2543 if (mStatus == STATUS_ACTIVE) {
2544 markClientActive = true;
2545 mPauseStateNotify = true;
2546 mStatusTracker->markComponentIdle(clientStatusId, Fence::NO_FENCE);
2547
2548 rc = internalPauseAndWaitLocked(maxExpectedDuration);
2549 }
2550
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002551 if (rc == NO_ERROR) {
2552 mNeedConfig = true;
2553 rc = configureStreamsLocked(mOperatingMode, sessionParams, /*notifyRequestThread*/ false);
2554 if (rc == NO_ERROR) {
2555 ret = true;
2556 mPauseStateNotify = false;
2557 //Moving to active state while holding 'mLock' is important.
2558 //There could be pending calls to 'create-/deleteStream' which
2559 //will trigger another stream configuration while the already
2560 //present streams end up with outstanding buffers that will
2561 //not get drained.
2562 internalUpdateStatusLocked(STATUS_ACTIVE);
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002563 } else if (rc == DEAD_OBJECT) {
2564 // DEAD_OBJECT can be returned if either the consumer surface is
2565 // abandoned, or the HAL has died.
2566 // - If the HAL has died, configureStreamsLocked call will set
2567 // device to error state,
2568 // - If surface is abandoned, we should not set device to error
2569 // state.
2570 ALOGE("Failed to re-configure camera due to abandoned surface");
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002571 } else {
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002572 SET_ERR_L("Failed to re-configure camera: %d", rc);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002573 }
2574 } else {
2575 ALOGE("%s: Failed to pause streaming: %d", __FUNCTION__, rc);
2576 }
2577
Shuzhen Wang316781a2020-08-18 18:11:01 -07002578 CameraServiceProxyWrapper::logStreamConfigured(mId, mOperatingMode, true /*internalReconfig*/,
2579 ns2ms(systemTime() - startTime));
2580
Emilian Peev3bead5f2020-05-28 17:29:08 -07002581 if (markClientActive) {
2582 mStatusTracker->markComponentActive(clientStatusId);
2583 }
2584
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002585 return ret;
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002586}
2587
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002588status_t Camera3Device::configureStreamsLocked(int operatingMode,
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002589 const CameraMetadata& sessionParams, bool notifyRequestThread) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002590 ATRACE_CALL();
2591 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002592
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002593 if (mStatus != STATUS_UNCONFIGURED && mStatus != STATUS_CONFIGURED) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002594 CLOGE("Not idle");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002595 return INVALID_OPERATION;
2596 }
2597
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08002598 if (operatingMode < 0) {
2599 CLOGE("Invalid operating mode: %d", operatingMode);
2600 return BAD_VALUE;
2601 }
2602
2603 bool isConstrainedHighSpeed =
2604 static_cast<int>(StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE) ==
2605 operatingMode;
2606
2607 if (mOperatingMode != operatingMode) {
2608 mNeedConfig = true;
2609 mIsConstrainedHighSpeedConfiguration = isConstrainedHighSpeed;
2610 mOperatingMode = operatingMode;
2611 }
2612
Shuzhen Wang0cf01cb2019-09-05 13:33:06 -07002613 // In case called from configureStreams, abort queued input buffers not belonging to
2614 // any pending requests.
2615 if (mInputStream != NULL && notifyRequestThread) {
2616 while (true) {
Emilian Peevf4816702020-04-03 15:44:51 -07002617 camera_stream_buffer_t inputBuffer;
Shuzhen Wang83bff122020-11-20 15:51:39 -08002618 camera3::Size inputBufferSize;
Shuzhen Wang0cf01cb2019-09-05 13:33:06 -07002619 status_t res = mInputStream->getInputBuffer(&inputBuffer,
Shuzhen Wang83bff122020-11-20 15:51:39 -08002620 &inputBufferSize, /*respectHalLimit*/ false);
Shuzhen Wang0cf01cb2019-09-05 13:33:06 -07002621 if (res != OK) {
2622 // Exhausted acquiring all input buffers.
2623 break;
2624 }
2625
Emilian Peevf4816702020-04-03 15:44:51 -07002626 inputBuffer.status = CAMERA_BUFFER_STATUS_ERROR;
Shuzhen Wang0cf01cb2019-09-05 13:33:06 -07002627 res = mInputStream->returnInputBuffer(inputBuffer);
2628 if (res != OK) {
2629 ALOGE("%s: %d: couldn't return input buffer while clearing input queue: "
2630 "%s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
2631 }
2632 }
2633 }
2634
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002635 if (!mNeedConfig) {
2636 ALOGV("%s: Skipping config, no stream changes", __FUNCTION__);
2637 return OK;
2638 }
2639
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002640 // Workaround for device HALv3.2 or older spec bug - zero streams requires
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002641 // adding a fake stream instead.
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002642 // TODO: Bug: 17321404 for fixing the HAL spec and removing this workaround.
2643 if (mOutputStreams.size() == 0) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002644 addFakeStreamLocked();
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002645 } else {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002646 tryRemoveFakeStreamLocked();
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002647 }
2648
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002649 // Start configuring the streams
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002650 ALOGV("%s: Camera %s: Starting stream configuration", __FUNCTION__, mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002651
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002652 mPreparerThread->pause();
2653
Emilian Peevf4816702020-04-03 15:44:51 -07002654 camera_stream_configuration config;
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -08002655 config.operation_mode = mOperatingMode;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002656 config.num_streams = (mInputStream != NULL) + mOutputStreams.size();
Shuzhen Wang83bff122020-11-20 15:51:39 -08002657 config.input_is_multi_resolution = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002658
Emilian Peevf4816702020-04-03 15:44:51 -07002659 Vector<camera3::camera_stream_t*> streams;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002660 streams.setCapacity(config.num_streams);
Emilian Peev192ee832018-01-31 14:46:47 +00002661 std::vector<uint32_t> bufferSizes(config.num_streams, 0);
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002662
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002663
2664 if (mInputStream != NULL) {
Emilian Peevf4816702020-04-03 15:44:51 -07002665 camera3::camera_stream_t *inputStream;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002666 inputStream = mInputStream->startConfiguration();
2667 if (inputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002668 CLOGE("Can't start input stream configuration");
2669 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002670 return INVALID_OPERATION;
2671 }
2672 streams.add(inputStream);
Shuzhen Wang83bff122020-11-20 15:51:39 -08002673
2674 config.input_is_multi_resolution = mIsInputStreamMultiResolution;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002675 }
2676
Shuzhen Wang99080502021-03-07 21:08:20 -08002677 mGroupIdPhysicalCameraMap.clear();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002678 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Igor Murashkin2fba5842013-04-22 14:03:54 -07002679
2680 // Don't configure bidi streams twice, nor add them twice to the list
2681 if (mOutputStreams[i].get() ==
2682 static_cast<Camera3StreamInterface*>(mInputStream.get())) {
2683
2684 config.num_streams--;
2685 continue;
2686 }
2687
Emilian Peevf4816702020-04-03 15:44:51 -07002688 camera3::camera_stream_t *outputStream;
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002689 outputStream = mOutputStreams[i]->startConfiguration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002690 if (outputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002691 CLOGE("Can't start output stream configuration");
2692 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002693 return INVALID_OPERATION;
2694 }
2695 streams.add(outputStream);
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002696
Shuzhen Wangb7ab1e42019-02-20 15:42:23 -08002697 if (outputStream->format == HAL_PIXEL_FORMAT_BLOB) {
Emilian Peev192ee832018-01-31 14:46:47 +00002698 size_t k = i + ((mInputStream != nullptr) ? 1 : 0); // Input stream if present should
2699 // always occupy the initial entry.
Shuzhen Wangb7ab1e42019-02-20 15:42:23 -08002700 if (outputStream->data_space == HAL_DATASPACE_V0_JFIF) {
2701 bufferSizes[k] = static_cast<uint32_t>(
2702 getJpegBufferSize(outputStream->width, outputStream->height));
2703 } else if (outputStream->data_space ==
2704 static_cast<android_dataspace>(HAL_DATASPACE_JPEG_APP_SEGMENTS)) {
2705 bufferSizes[k] = outputStream->width * outputStream->height;
2706 } else {
2707 ALOGW("%s: Blob dataSpace %d not supported",
2708 __FUNCTION__, outputStream->data_space);
2709 }
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002710 }
Shuzhen Wang99080502021-03-07 21:08:20 -08002711
2712 if (mOutputStreams[i]->isMultiResolution()) {
2713 int32_t streamGroupId = mOutputStreams[i]->getHalStreamGroupId();
2714 const String8& physicalCameraId = mOutputStreams[i]->getPhysicalCameraId();
2715 mGroupIdPhysicalCameraMap[streamGroupId].insert(physicalCameraId);
2716 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002717 }
2718
2719 config.streams = streams.editArray();
2720
2721 // Do the HAL configuration; will potentially touch stream
Shuzhen Wang92653952019-05-07 15:11:43 -07002722 // max_buffers, usage, and priv fields, as well as data_space and format
2723 // fields for IMPLEMENTATION_DEFINED formats.
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002724
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002725 const camera_metadata_t *sessionBuffer = sessionParams.getAndLock();
Emilian Peev192ee832018-01-31 14:46:47 +00002726 res = mInterface->configureStreams(sessionBuffer, &config, bufferSizes);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002727 sessionParams.unlock(sessionBuffer);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002728
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002729 if (res == BAD_VALUE) {
2730 // HAL rejected this set of streams as unsupported, clean up config
2731 // attempt and return to unconfigured state
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002732 CLOGE("Set of requested inputs/outputs not supported by HAL");
2733 cancelStreamsConfigurationLocked();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002734 return BAD_VALUE;
2735 } else if (res != OK) {
2736 // Some other kind of error from configure_streams - this is not
2737 // expected
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002738 SET_ERR_L("Unable to configure streams with HAL: %s (%d)",
2739 strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002740 return res;
2741 }
2742
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002743 // Finish all stream configuration immediately.
2744 // TODO: Try to relax this later back to lazy completion, which should be
2745 // faster
2746
Igor Murashkin073f8572013-05-02 14:59:28 -07002747 if (mInputStream != NULL && mInputStream->isConfiguring()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002748 bool streamReConfigured = false;
2749 res = mInputStream->finishConfiguration(&streamReConfigured);
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002750 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002751 CLOGE("Can't finish configuring input stream %d: %s (%d)",
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002752 mInputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002753 cancelStreamsConfigurationLocked();
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002754 if ((res == NO_INIT || res == DEAD_OBJECT) && mInputStream->isAbandoned()) {
2755 return DEAD_OBJECT;
2756 }
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002757 return BAD_VALUE;
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002758 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002759 if (streamReConfigured) {
2760 mInterface->onStreamReConfigured(mInputStream->getId());
2761 }
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002762 }
2763
2764 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002765 sp<Camera3OutputStreamInterface> outputStream = mOutputStreams[i];
Zhijun He5d677d12016-05-29 16:52:39 -07002766 if (outputStream->isConfiguring() && !outputStream->isConsumerConfigurationDeferred()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002767 bool streamReConfigured = false;
2768 res = outputStream->finishConfiguration(&streamReConfigured);
Igor Murashkin073f8572013-05-02 14:59:28 -07002769 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002770 CLOGE("Can't finish configuring output stream %d: %s (%d)",
Igor Murashkin073f8572013-05-02 14:59:28 -07002771 outputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002772 cancelStreamsConfigurationLocked();
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002773 if ((res == NO_INIT || res == DEAD_OBJECT) && outputStream->isAbandoned()) {
2774 return DEAD_OBJECT;
2775 }
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002776 return BAD_VALUE;
Igor Murashkin073f8572013-05-02 14:59:28 -07002777 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002778 if (streamReConfigured) {
2779 mInterface->onStreamReConfigured(outputStream->getId());
2780 }
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002781 }
2782 }
2783
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002784 // Request thread needs to know to avoid using repeat-last-settings protocol
2785 // across configure_streams() calls
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002786 if (notifyRequestThread) {
Shuzhen Wang99080502021-03-07 21:08:20 -08002787 mRequestThread->configurationComplete(mIsConstrainedHighSpeedConfiguration,
2788 sessionParams, mGroupIdPhysicalCameraMap);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002789 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002790
Zhijun He90f7c372016-08-16 16:19:43 -07002791 char value[PROPERTY_VALUE_MAX];
2792 property_get("camera.fifo.disable", value, "0");
2793 int32_t disableFifo = atoi(value);
2794 if (disableFifo != 1) {
2795 // Boost priority of request thread to SCHED_FIFO.
2796 pid_t requestThreadTid = mRequestThread->getTid();
2797 res = requestPriority(getpid(), requestThreadTid,
Mikhail Naganov83f04272017-02-07 10:45:09 -08002798 kRequestThreadPriority, /*isForApp*/ false, /*asynchronous*/ false);
Zhijun He90f7c372016-08-16 16:19:43 -07002799 if (res != OK) {
2800 ALOGW("Can't set realtime priority for request processing thread: %s (%d)",
2801 strerror(-res), res);
2802 } else {
2803 ALOGD("Set real time priority for request queue thread (tid %d)", requestThreadTid);
2804 }
Eino-Ville Talvalaf99498e2015-09-25 16:52:55 -07002805 }
2806
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002807 // Update device state
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002808 const camera_metadata_t *newSessionParams = sessionParams.getAndLock();
2809 const camera_metadata_t *currentSessionParams = mSessionParams.getAndLock();
2810 bool updateSessionParams = (newSessionParams != currentSessionParams) ? true : false;
2811 sessionParams.unlock(newSessionParams);
2812 mSessionParams.unlock(currentSessionParams);
2813 if (updateSessionParams) {
2814 mSessionParams = sessionParams;
2815 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002816
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002817 mNeedConfig = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002818
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002819 internalUpdateStatusLocked((mFakeStreamId == NO_STREAM) ?
Ruben Brunk183f0562015-08-12 12:55:02 -07002820 STATUS_CONFIGURED : STATUS_UNCONFIGURED);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002821
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002822 ALOGV("%s: Camera %s: Stream configuration complete", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002823
Zhijun He0a210512014-07-24 13:45:15 -07002824 // tear down the deleted streams after configure streams.
2825 mDeletedStreams.clear();
2826
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002827 auto rc = mPreparerThread->resume();
2828 if (rc != OK) {
2829 SET_ERR_L("%s: Camera %s: Preparer thread failed to resume!", __FUNCTION__, mId.string());
2830 return rc;
2831 }
2832
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002833 if (mFakeStreamId == NO_STREAM) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07002834 mRequestBufferSM.onStreamsConfigured();
2835 }
2836
Cliff Wuc2ad9c82021-04-21 00:58:58 +08002837 // Since the streams configuration of the injection camera is based on the internal camera, we
2838 // must wait until the internal camera configure streams before calling injectCamera() to
2839 // configure the injection streams.
2840 if (mInjectionMethods->isInjecting()) {
2841 ALOGV("%s: Injection camera %s: Start to configure streams.",
2842 __FUNCTION__, mInjectionMethods->getInjectedCamId().string());
2843 res = mInjectionMethods->injectCamera(config, bufferSizes);
2844 if (res != OK) {
2845 ALOGE("Can't finish inject camera process!");
2846 return res;
2847 }
2848 }
2849
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002850 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002851}
2852
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002853status_t Camera3Device::addFakeStreamLocked() {
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002854 ATRACE_CALL();
2855 status_t res;
2856
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002857 if (mFakeStreamId != NO_STREAM) {
2858 // Should never be adding a second fake stream when one is already
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002859 // active
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002860 SET_ERR_L("%s: Camera %s: A fake stream already exists!",
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002861 __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002862 return INVALID_OPERATION;
2863 }
2864
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002865 ALOGV("%s: Camera %s: Adding a fake stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002866
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002867 sp<Camera3OutputStreamInterface> fakeStream =
2868 new Camera3FakeStream(mNextStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002869
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002870 res = mOutputStreams.add(mNextStreamId, fakeStream);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002871 if (res < 0) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002872 SET_ERR_L("Can't add fake stream to set: %s (%d)", strerror(-res), res);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002873 return res;
2874 }
2875
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002876 mFakeStreamId = mNextStreamId;
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002877 mNextStreamId++;
2878
2879 return OK;
2880}
2881
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002882status_t Camera3Device::tryRemoveFakeStreamLocked() {
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002883 ATRACE_CALL();
2884 status_t res;
2885
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002886 if (mFakeStreamId == NO_STREAM) return OK;
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002887 if (mOutputStreams.size() == 1) return OK;
2888
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002889 ALOGV("%s: Camera %s: Removing the fake stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002890
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002891 // Ok, have a fake stream and there's at least one other output stream,
2892 // so remove the fake
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002893
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002894 sp<Camera3StreamInterface> deletedStream = mOutputStreams.get(mFakeStreamId);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002895 if (deletedStream == nullptr) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002896 SET_ERR_L("Fake stream %d does not appear to exist", mFakeStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002897 return INVALID_OPERATION;
2898 }
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002899 mOutputStreams.remove(mFakeStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002900
2901 // Free up the stream endpoint so that it can be used by some other stream
2902 res = deletedStream->disconnect();
2903 if (res != OK) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002904 SET_ERR_L("Can't disconnect deleted fake stream %d", mFakeStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002905 // fall through since we want to still list the stream as deleted.
2906 }
2907 mDeletedStreams.add(deletedStream);
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002908 mFakeStreamId = NO_STREAM;
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002909
2910 return res;
2911}
2912
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002913void Camera3Device::setErrorState(const char *fmt, ...) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002914 ATRACE_CALL();
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002915 Mutex::Autolock l(mLock);
2916 va_list args;
2917 va_start(args, fmt);
2918
2919 setErrorStateLockedV(fmt, args);
2920
2921 va_end(args);
2922}
2923
2924void Camera3Device::setErrorStateV(const char *fmt, va_list args) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002925 ATRACE_CALL();
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002926 Mutex::Autolock l(mLock);
2927 setErrorStateLockedV(fmt, args);
2928}
2929
2930void Camera3Device::setErrorStateLocked(const char *fmt, ...) {
2931 va_list args;
2932 va_start(args, fmt);
2933
2934 setErrorStateLockedV(fmt, args);
2935
2936 va_end(args);
2937}
2938
2939void Camera3Device::setErrorStateLockedV(const char *fmt, va_list args) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002940 // Print out all error messages to log
2941 String8 errorCause = String8::formatV(fmt, args);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002942 ALOGE("Camera %s: %s", mId.string(), errorCause.string());
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002943
2944 // But only do error state transition steps for the first error
Zhijun Heb05eeae2013-06-06 13:51:22 -07002945 if (mStatus == STATUS_ERROR || mStatus == STATUS_UNINITIALIZED) return;
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002946
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002947 mErrorCause = errorCause;
2948
Yin-Chia Yeh3d145ae2017-07-27 12:47:03 -07002949 if (mRequestThread != nullptr) {
2950 mRequestThread->setPaused(true);
2951 }
Ruben Brunk183f0562015-08-12 12:55:02 -07002952 internalUpdateStatusLocked(STATUS_ERROR);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002953
2954 // Notify upstream about a device error
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002955 sp<NotificationListener> listener = mListener.promote();
2956 if (listener != NULL) {
2957 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002958 CaptureResultExtras());
Shuzhen Wang316781a2020-08-18 18:11:01 -07002959 mSessionStatsBuilder.onDeviceError();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002960 }
2961
2962 // Save stack trace. View by dumping it later.
2963 CameraTraces::saveTrace();
2964 // TODO: consider adding errorCause and client pid/procname
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002965}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002966
2967/**
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002968 * In-flight request management
2969 */
2970
Jianing Weicb0652e2014-03-12 18:29:36 -07002971status_t Camera3Device::registerInFlight(uint32_t frameNumber,
Chien-Yu Chend196d612015-06-22 19:49:01 -07002972 int32_t numBuffers, CaptureResultExtras resultExtras, bool hasInput,
Shuzhen Wang5c22c152017-12-31 17:12:25 -08002973 bool hasAppCallback, nsecs_t maxExpectedDuration,
Shuzhen Wang99080502021-03-07 21:08:20 -08002974 const std::set<std::set<String8>>& physicalCameraIds,
2975 bool isStillCapture, bool isZslCapture, bool rotateAndCropAuto,
2976 const std::set<std::string>& cameraIdsWithZoom,
Shuzhen Wang316781a2020-08-18 18:11:01 -07002977 const SurfaceMap& outputSurfaces, nsecs_t requestTimeNs) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002978 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002979 std::lock_guard<std::mutex> l(mInFlightLock);
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002980
2981 ssize_t res;
Chien-Yu Chend196d612015-06-22 19:49:01 -07002982 res = mInFlightMap.add(frameNumber, InFlightRequest(numBuffers, resultExtras, hasInput,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07002983 hasAppCallback, maxExpectedDuration, physicalCameraIds, isStillCapture, isZslCapture,
Shuzhen Wang316781a2020-08-18 18:11:01 -07002984 rotateAndCropAuto, cameraIdsWithZoom, requestTimeNs, outputSurfaces));
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002985 if (res < 0) return res;
2986
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07002987 if (mInFlightMap.size() == 1) {
Emilian Peev26d975d2018-07-05 14:52:57 +01002988 // Hold a separate dedicated tracker lock to prevent race with disconnect and also
2989 // avoid a deadlock during reprocess requests.
2990 Mutex::Autolock l(mTrackerLock);
Yin-Chia Yeh38dfde52017-06-27 17:13:33 -07002991 if (mStatusTracker != nullptr) {
2992 mStatusTracker->markComponentActive(mInFlightStatusId);
2993 }
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07002994 }
2995
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07002996 mExpectedInflightDuration += maxExpectedDuration;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002997 return OK;
2998}
2999
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003000void Camera3Device::onInflightEntryRemovedLocked(nsecs_t duration) {
Shuzhen Wangcadb3302016-11-04 14:17:56 -07003001 // Indicate idle inFlightMap to the status tracker
3002 if (mInFlightMap.size() == 0) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07003003 mRequestBufferSM.onInflightMapEmpty();
Emilian Peev26d975d2018-07-05 14:52:57 +01003004 // Hold a separate dedicated tracker lock to prevent race with disconnect and also
3005 // avoid a deadlock during reprocess requests.
3006 Mutex::Autolock l(mTrackerLock);
Yin-Chia Yeh38dfde52017-06-27 17:13:33 -07003007 if (mStatusTracker != nullptr) {
3008 mStatusTracker->markComponentIdle(mInFlightStatusId, Fence::NO_FENCE);
3009 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07003010 }
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003011 mExpectedInflightDuration -= duration;
Shuzhen Wangcadb3302016-11-04 14:17:56 -07003012}
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003013
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003014void Camera3Device::checkInflightMapLengthLocked() {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04003015 // Validation check - if we have too many in-flight frames with long total inflight duration,
Yin-Chia Yeh99fd0972019-06-27 14:22:44 -07003016 // something has likely gone wrong. This might still be legit only if application send in
3017 // a long burst of long exposure requests.
3018 if (mExpectedInflightDuration > kMinWarnInflightDuration) {
3019 if (!mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() > kInFlightWarnLimit) {
3020 CLOGW("In-flight list too large: %zu, total inflight duration %" PRIu64,
3021 mInFlightMap.size(), mExpectedInflightDuration);
3022 } else if (mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() >
3023 kInFlightWarnLimitHighSpeed) {
3024 CLOGW("In-flight list too large for high speed configuration: %zu,"
3025 "total inflight duration %" PRIu64,
3026 mInFlightMap.size(), mExpectedInflightDuration);
3027 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003028 }
3029}
3030
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003031void Camera3Device::onInflightMapFlushedLocked() {
3032 mExpectedInflightDuration = 0;
3033}
3034
3035void Camera3Device::removeInFlightMapEntryLocked(int idx) {
Jayant Chowdharyd4776262020-06-23 23:45:57 -07003036 ATRACE_HFR_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003037 nsecs_t duration = mInFlightMap.valueAt(idx).maxExpectedDuration;
3038 mInFlightMap.removeItemsAt(idx, 1);
3039
3040 onInflightEntryRemovedLocked(duration);
3041}
3042
3043
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003044void Camera3Device::flushInflightRequests() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003045 ATRACE_CALL();
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003046 sp<NotificationListener> listener;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003047 {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003048 std::lock_guard<std::mutex> l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003049 listener = mListener.promote();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003050 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003051
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003052 FlushInflightReqStates states {
3053 mId, mInFlightLock, mInFlightMap, mUseHalBufManager,
Shuzhen Wang316781a2020-08-18 18:11:01 -07003054 listener, *this, *mInterface, *this, mSessionStatsBuilder};
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003055
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003056 camera3::flushInflightRequests(states);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003057}
3058
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003059CameraMetadata Camera3Device::getLatestRequestLocked() {
Igor Murashkin1e479c02013-09-06 16:55:14 -07003060 ALOGV("%s", __FUNCTION__);
3061
Igor Murashkin1e479c02013-09-06 16:55:14 -07003062 CameraMetadata retVal;
3063
3064 if (mRequestThread != NULL) {
3065 retVal = mRequestThread->getLatestRequest();
3066 }
3067
Igor Murashkin1e479c02013-09-06 16:55:14 -07003068 return retVal;
3069}
3070
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07003071void Camera3Device::monitorMetadata(TagMonitor::eventSource source,
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003072 int64_t frameNumber, nsecs_t timestamp, const CameraMetadata& metadata,
3073 const std::unordered_map<std::string, CameraMetadata>& physicalMetadata) {
3074
3075 mTagMonitor.monitorMetadata(source, frameNumber, timestamp, metadata,
3076 physicalMetadata);
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07003077}
3078
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003079/**
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003080 * HalInterface inner class methods
3081 */
3082
Yifan Hongf79b5542017-04-11 14:44:25 -07003083Camera3Device::HalInterface::HalInterface(
3084 sp<ICameraDeviceSession> &session,
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003085 std::shared_ptr<RequestMetadataQueue> queue,
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003086 bool useHalBufManager, bool supportOfflineProcessing) :
Yifan Hongf79b5542017-04-11 14:44:25 -07003087 mHidlSession(session),
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003088 mRequestMetadataQueue(queue),
Emilian Peev4ec17882019-01-24 17:16:58 -08003089 mUseHalBufManager(useHalBufManager),
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003090 mIsReconfigurationQuerySupported(true),
3091 mSupportOfflineProcessing(supportOfflineProcessing) {
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003092 // Check with hardware service manager if we can downcast these interfaces
3093 // Somewhat expensive, so cache the results at startup
Shuzhen Wang83bff122020-11-20 15:51:39 -08003094 auto castResult_3_7 = device::V3_7::ICameraDeviceSession::castFrom(mHidlSession);
3095 if (castResult_3_7.isOk()) {
3096 mHidlSession_3_7 = castResult_3_7;
3097 }
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003098 auto castResult_3_6 = device::V3_6::ICameraDeviceSession::castFrom(mHidlSession);
3099 if (castResult_3_6.isOk()) {
3100 mHidlSession_3_6 = castResult_3_6;
3101 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003102 auto castResult_3_5 = device::V3_5::ICameraDeviceSession::castFrom(mHidlSession);
3103 if (castResult_3_5.isOk()) {
3104 mHidlSession_3_5 = castResult_3_5;
3105 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003106 auto castResult_3_4 = device::V3_4::ICameraDeviceSession::castFrom(mHidlSession);
3107 if (castResult_3_4.isOk()) {
3108 mHidlSession_3_4 = castResult_3_4;
3109 }
3110 auto castResult_3_3 = device::V3_3::ICameraDeviceSession::castFrom(mHidlSession);
3111 if (castResult_3_3.isOk()) {
3112 mHidlSession_3_3 = castResult_3_3;
3113 }
3114}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003115
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003116Camera3Device::HalInterface::HalInterface() :
3117 mUseHalBufManager(false),
3118 mSupportOfflineProcessing(false) {}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003119
3120Camera3Device::HalInterface::HalInterface(const HalInterface& other) :
Yifan Hongf79b5542017-04-11 14:44:25 -07003121 mHidlSession(other.mHidlSession),
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003122 mRequestMetadataQueue(other.mRequestMetadataQueue),
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003123 mUseHalBufManager(other.mUseHalBufManager),
3124 mSupportOfflineProcessing(other.mSupportOfflineProcessing) {}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003125
3126bool Camera3Device::HalInterface::valid() {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003127 return (mHidlSession != nullptr);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003128}
3129
3130void Camera3Device::HalInterface::clear() {
Shuzhen Wang83bff122020-11-20 15:51:39 -08003131 mHidlSession_3_7.clear();
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003132 mHidlSession_3_6.clear();
Emilian Peev644a3e12018-11-23 13:52:39 +00003133 mHidlSession_3_5.clear();
Emilian Peev9e740b02018-01-30 18:28:03 +00003134 mHidlSession_3_4.clear();
3135 mHidlSession_3_3.clear();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003136 mHidlSession.clear();
3137}
3138
3139status_t Camera3Device::HalInterface::constructDefaultRequestSettings(
Emilian Peevf4816702020-04-03 15:44:51 -07003140 camera_request_template_t templateId,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003141 /*out*/ camera_metadata_t **requestTemplate) {
3142 ATRACE_NAME("CameraHal::constructDefaultRequestSettings");
3143 if (!valid()) return INVALID_OPERATION;
3144 status_t res = OK;
3145
Emilian Peev31abd0a2017-05-11 18:37:46 +01003146 common::V1_0::Status status;
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003147
3148 auto requestCallback = [&status, &requestTemplate]
Emilian Peev31abd0a2017-05-11 18:37:46 +01003149 (common::V1_0::Status s, const device::V3_2::CameraMetadata& request) {
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003150 status = s;
3151 if (status == common::V1_0::Status::OK) {
3152 const camera_metadata *r =
3153 reinterpret_cast<const camera_metadata_t*>(request.data());
3154 size_t expectedSize = request.size();
3155 int ret = validate_camera_metadata_structure(r, &expectedSize);
3156 if (ret == OK || ret == CAMERA_METADATA_VALIDATION_SHIFTED) {
3157 *requestTemplate = clone_camera_metadata(r);
3158 if (*requestTemplate == nullptr) {
3159 ALOGE("%s: Unable to clone camera metadata received from HAL",
3160 __FUNCTION__);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003161 status = common::V1_0::Status::INTERNAL_ERROR;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003162 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003163 } else {
3164 ALOGE("%s: Malformed camera metadata received from HAL", __FUNCTION__);
3165 status = common::V1_0::Status::INTERNAL_ERROR;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003166 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003167 }
3168 };
3169 hardware::Return<void> err;
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003170 RequestTemplate id;
3171 switch (templateId) {
Emilian Peevf4816702020-04-03 15:44:51 -07003172 case CAMERA_TEMPLATE_PREVIEW:
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003173 id = RequestTemplate::PREVIEW;
3174 break;
Emilian Peevf4816702020-04-03 15:44:51 -07003175 case CAMERA_TEMPLATE_STILL_CAPTURE:
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003176 id = RequestTemplate::STILL_CAPTURE;
3177 break;
Emilian Peevf4816702020-04-03 15:44:51 -07003178 case CAMERA_TEMPLATE_VIDEO_RECORD:
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003179 id = RequestTemplate::VIDEO_RECORD;
3180 break;
Emilian Peevf4816702020-04-03 15:44:51 -07003181 case CAMERA_TEMPLATE_VIDEO_SNAPSHOT:
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003182 id = RequestTemplate::VIDEO_SNAPSHOT;
3183 break;
Emilian Peevf4816702020-04-03 15:44:51 -07003184 case CAMERA_TEMPLATE_ZERO_SHUTTER_LAG:
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003185 id = RequestTemplate::ZERO_SHUTTER_LAG;
3186 break;
Emilian Peevf4816702020-04-03 15:44:51 -07003187 case CAMERA_TEMPLATE_MANUAL:
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003188 id = RequestTemplate::MANUAL;
3189 break;
3190 default:
3191 // Unknown template ID, or this HAL is too old to support it
3192 return BAD_VALUE;
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003193 }
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003194 err = mHidlSession->constructDefaultRequestSettings(id, requestCallback);
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003195
Emilian Peev31abd0a2017-05-11 18:37:46 +01003196 if (!err.isOk()) {
3197 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3198 res = DEAD_OBJECT;
3199 } else {
3200 res = CameraProviderManager::mapToStatusT(status);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003201 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003202
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003203 return res;
3204}
3205
Emilian Peev4ec17882019-01-24 17:16:58 -08003206bool Camera3Device::HalInterface::isReconfigurationRequired(CameraMetadata& oldSessionParams,
3207 CameraMetadata& newSessionParams) {
3208 // We do reconfiguration by default;
3209 bool ret = true;
3210 if ((mHidlSession_3_5 != nullptr) && mIsReconfigurationQuerySupported) {
3211 android::hardware::hidl_vec<uint8_t> oldParams, newParams;
3212 camera_metadata_t* oldSessioMeta = const_cast<camera_metadata_t*>(
3213 oldSessionParams.getAndLock());
3214 camera_metadata_t* newSessioMeta = const_cast<camera_metadata_t*>(
3215 newSessionParams.getAndLock());
3216 oldParams.setToExternal(reinterpret_cast<uint8_t*>(oldSessioMeta),
3217 get_camera_metadata_size(oldSessioMeta));
3218 newParams.setToExternal(reinterpret_cast<uint8_t*>(newSessioMeta),
3219 get_camera_metadata_size(newSessioMeta));
3220 hardware::camera::common::V1_0::Status callStatus;
3221 bool required;
3222 auto hidlCb = [&callStatus, &required] (hardware::camera::common::V1_0::Status s,
3223 bool requiredFlag) {
3224 callStatus = s;
3225 required = requiredFlag;
3226 };
3227 auto err = mHidlSession_3_5->isReconfigurationRequired(oldParams, newParams, hidlCb);
3228 oldSessionParams.unlock(oldSessioMeta);
3229 newSessionParams.unlock(newSessioMeta);
3230 if (err.isOk()) {
3231 switch (callStatus) {
3232 case hardware::camera::common::V1_0::Status::OK:
3233 ret = required;
3234 break;
3235 case hardware::camera::common::V1_0::Status::METHOD_NOT_SUPPORTED:
3236 mIsReconfigurationQuerySupported = false;
3237 ret = true;
3238 break;
3239 default:
3240 ALOGV("%s: Reconfiguration query failed: %d", __FUNCTION__, callStatus);
3241 ret = true;
3242 }
3243 } else {
3244 ALOGE("%s: Unexpected binder error: %s", __FUNCTION__, err.description().c_str());
3245 ret = true;
3246 }
3247 }
3248
3249 return ret;
3250}
3251
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003252status_t Camera3Device::HalInterface::configureStreams(const camera_metadata_t *sessionParams,
Emilian Peevf4816702020-04-03 15:44:51 -07003253 camera_stream_configuration *config, const std::vector<uint32_t>& bufferSizes) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003254 ATRACE_NAME("CameraHal::configureStreams");
3255 if (!valid()) return INVALID_OPERATION;
3256 status_t res = OK;
3257
Shuzhen Wang83bff122020-11-20 15:51:39 -08003258 if (config->input_is_multi_resolution && mHidlSession_3_7 == nullptr) {
3259 ALOGE("%s: Camera device doesn't support multi-resolution input stream", __FUNCTION__);
3260 return BAD_VALUE;
3261 }
3262
Emilian Peev31abd0a2017-05-11 18:37:46 +01003263 // Convert stream config to HIDL
3264 std::set<int> activeStreams;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003265 device::V3_2::StreamConfiguration requestedConfiguration3_2;
3266 device::V3_4::StreamConfiguration requestedConfiguration3_4;
Shuzhen Wang83bff122020-11-20 15:51:39 -08003267 device::V3_7::StreamConfiguration requestedConfiguration3_7;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003268 requestedConfiguration3_2.streams.resize(config->num_streams);
3269 requestedConfiguration3_4.streams.resize(config->num_streams);
Shuzhen Wang83bff122020-11-20 15:51:39 -08003270 requestedConfiguration3_7.streams.resize(config->num_streams);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003271 for (size_t i = 0; i < config->num_streams; i++) {
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003272 device::V3_2::Stream &dst3_2 = requestedConfiguration3_2.streams[i];
3273 device::V3_4::Stream &dst3_4 = requestedConfiguration3_4.streams[i];
Shuzhen Wang83bff122020-11-20 15:51:39 -08003274 device::V3_7::Stream &dst3_7 = requestedConfiguration3_7.streams[i];
Emilian Peevf4816702020-04-03 15:44:51 -07003275 camera3::camera_stream_t *src = config->streams[i];
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003276
Emilian Peev31abd0a2017-05-11 18:37:46 +01003277 Camera3Stream* cam3stream = Camera3Stream::cast(src);
3278 cam3stream->setBufferFreedListener(this);
3279 int streamId = cam3stream->getId();
3280 StreamType streamType;
3281 switch (src->stream_type) {
Emilian Peevf4816702020-04-03 15:44:51 -07003282 case CAMERA_STREAM_OUTPUT:
Emilian Peev31abd0a2017-05-11 18:37:46 +01003283 streamType = StreamType::OUTPUT;
3284 break;
Emilian Peevf4816702020-04-03 15:44:51 -07003285 case CAMERA_STREAM_INPUT:
Emilian Peev31abd0a2017-05-11 18:37:46 +01003286 streamType = StreamType::INPUT;
3287 break;
3288 default:
3289 ALOGE("%s: Stream %d: Unsupported stream type %d",
3290 __FUNCTION__, streamId, config->streams[i]->stream_type);
3291 return BAD_VALUE;
3292 }
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003293 dst3_2.id = streamId;
3294 dst3_2.streamType = streamType;
3295 dst3_2.width = src->width;
3296 dst3_2.height = src->height;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003297 dst3_2.usage = mapToConsumerUsage(cam3stream->getUsage());
Emilian Peevf4816702020-04-03 15:44:51 -07003298 dst3_2.rotation = mapToStreamRotation((camera_stream_rotation_t) src->rotation);
Shuzhen Wang92653952019-05-07 15:11:43 -07003299 // For HidlSession version 3.5 or newer, the format and dataSpace sent
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08003300 // to HAL are original, not the overridden ones.
Shuzhen Wang92653952019-05-07 15:11:43 -07003301 if (mHidlSession_3_5 != nullptr) {
3302 dst3_2.format = mapToPixelFormat(cam3stream->isFormatOverridden() ?
3303 cam3stream->getOriginalFormat() : src->format);
3304 dst3_2.dataSpace = mapToHidlDataspace(cam3stream->isDataSpaceOverridden() ?
3305 cam3stream->getOriginalDataSpace() : src->data_space);
3306 } else {
3307 dst3_2.format = mapToPixelFormat(src->format);
3308 dst3_2.dataSpace = mapToHidlDataspace(src->data_space);
3309 }
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003310 dst3_4.v3_2 = dst3_2;
Emilian Peev192ee832018-01-31 14:46:47 +00003311 dst3_4.bufferSize = bufferSizes[i];
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003312 if (src->physical_camera_id != nullptr) {
3313 dst3_4.physicalCameraId = src->physical_camera_id;
3314 }
Shuzhen Wang83bff122020-11-20 15:51:39 -08003315 dst3_7.v3_4 = dst3_4;
3316 dst3_7.groupId = cam3stream->getHalStreamGroupId();
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08003317 dst3_7.sensorPixelModesUsed.resize(src->sensor_pixel_modes_used.size());
3318 size_t j = 0;
3319 for (int mode : src->sensor_pixel_modes_used) {
3320 dst3_7.sensorPixelModesUsed[j++] =
3321 static_cast<CameraMetadataEnumAndroidSensorPixelMode>(mode);
3322 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003323 activeStreams.insert(streamId);
3324 // Create Buffer ID map if necessary
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003325 mBufferRecords.tryCreateBufferCache(streamId);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003326 }
3327 // remove BufferIdMap for deleted streams
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003328 mBufferRecords.removeInactiveBufferCaches(activeStreams);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003329
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003330 StreamConfigurationMode operationMode;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003331 res = mapToStreamConfigurationMode(
Emilian Peevf4816702020-04-03 15:44:51 -07003332 (camera_stream_configuration_mode_t) config->operation_mode,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003333 /*out*/ &operationMode);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003334 if (res != OK) {
3335 return res;
3336 }
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003337 requestedConfiguration3_2.operationMode = operationMode;
3338 requestedConfiguration3_4.operationMode = operationMode;
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08003339 requestedConfiguration3_7.operationMode = operationMode;
3340 size_t sessionParamSize = get_camera_metadata_size(sessionParams);
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003341 requestedConfiguration3_4.sessionParams.setToExternal(
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003342 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(sessionParams)),
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08003343 sessionParamSize);
Shuzhen Wang83bff122020-11-20 15:51:39 -08003344 requestedConfiguration3_7.operationMode = operationMode;
3345 requestedConfiguration3_7.sessionParams.setToExternal(
3346 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(sessionParams)),
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08003347 sessionParamSize);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003348
Emilian Peev31abd0a2017-05-11 18:37:46 +01003349 // Invoke configureStreams
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003350 device::V3_3::HalStreamConfiguration finalConfiguration;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003351 device::V3_4::HalStreamConfiguration finalConfiguration3_4;
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003352 device::V3_6::HalStreamConfiguration finalConfiguration3_6;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003353 common::V1_0::Status status;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003354
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003355 auto configStream34Cb = [&status, &finalConfiguration3_4]
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003356 (common::V1_0::Status s, const device::V3_4::HalStreamConfiguration& halConfiguration) {
3357 finalConfiguration3_4 = halConfiguration;
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003358 status = s;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003359 };
3360
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003361 auto configStream36Cb = [&status, &finalConfiguration3_6]
3362 (common::V1_0::Status s, const device::V3_6::HalStreamConfiguration& halConfiguration) {
3363 finalConfiguration3_6 = halConfiguration;
3364 status = s;
3365 };
3366
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003367 auto postprocConfigStream34 = [&finalConfiguration, &finalConfiguration3_4]
3368 (hardware::Return<void>& err) -> status_t {
3369 if (!err.isOk()) {
3370 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3371 return DEAD_OBJECT;
3372 }
3373 finalConfiguration.streams.resize(finalConfiguration3_4.streams.size());
3374 for (size_t i = 0; i < finalConfiguration3_4.streams.size(); i++) {
3375 finalConfiguration.streams[i] = finalConfiguration3_4.streams[i].v3_3;
3376 }
3377 return OK;
3378 };
3379
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003380 auto postprocConfigStream36 = [&finalConfiguration, &finalConfiguration3_6]
3381 (hardware::Return<void>& err) -> status_t {
3382 if (!err.isOk()) {
3383 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3384 return DEAD_OBJECT;
3385 }
3386 finalConfiguration.streams.resize(finalConfiguration3_6.streams.size());
3387 for (size_t i = 0; i < finalConfiguration3_6.streams.size(); i++) {
3388 finalConfiguration.streams[i] = finalConfiguration3_6.streams[i].v3_4.v3_3;
3389 }
3390 return OK;
3391 };
3392
Shuzhen Wang92653952019-05-07 15:11:43 -07003393 // See which version of HAL we have
Shuzhen Wang83bff122020-11-20 15:51:39 -08003394 if (mHidlSession_3_7 != nullptr) {
3395 ALOGV("%s: v3.7 device found", __FUNCTION__);
3396 requestedConfiguration3_7.streamConfigCounter = mNextStreamConfigCounter++;
3397 requestedConfiguration3_7.multiResolutionInputImage = config->input_is_multi_resolution;
3398 auto err = mHidlSession_3_7->configureStreams_3_7(
3399 requestedConfiguration3_7, configStream36Cb);
3400 res = postprocConfigStream36(err);
3401 if (res != OK) {
3402 return res;
3403 }
3404 } else if (mHidlSession_3_6 != nullptr) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003405 ALOGV("%s: v3.6 device found", __FUNCTION__);
3406 device::V3_5::StreamConfiguration requestedConfiguration3_5;
3407 requestedConfiguration3_5.v3_4 = requestedConfiguration3_4;
3408 requestedConfiguration3_5.streamConfigCounter = mNextStreamConfigCounter++;
3409 auto err = mHidlSession_3_6->configureStreams_3_6(
3410 requestedConfiguration3_5, configStream36Cb);
3411 res = postprocConfigStream36(err);
3412 if (res != OK) {
3413 return res;
3414 }
3415 } else if (mHidlSession_3_5 != nullptr) {
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003416 ALOGV("%s: v3.5 device found", __FUNCTION__);
3417 device::V3_5::StreamConfiguration requestedConfiguration3_5;
3418 requestedConfiguration3_5.v3_4 = requestedConfiguration3_4;
3419 requestedConfiguration3_5.streamConfigCounter = mNextStreamConfigCounter++;
3420 auto err = mHidlSession_3_5->configureStreams_3_5(
3421 requestedConfiguration3_5, configStream34Cb);
3422 res = postprocConfigStream34(err);
3423 if (res != OK) {
3424 return res;
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003425 }
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003426 } else if (mHidlSession_3_4 != nullptr) {
3427 // We do; use v3.4 for the call
3428 ALOGV("%s: v3.4 device found", __FUNCTION__);
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003429 auto err = mHidlSession_3_4->configureStreams_3_4(
3430 requestedConfiguration3_4, configStream34Cb);
3431 res = postprocConfigStream34(err);
3432 if (res != OK) {
3433 return res;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003434 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003435 } else if (mHidlSession_3_3 != nullptr) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003436 // We do; use v3.3 for the call
3437 ALOGV("%s: v3.3 device found", __FUNCTION__);
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003438 auto err = mHidlSession_3_3->configureStreams_3_3(requestedConfiguration3_2,
Emilian Peev31abd0a2017-05-11 18:37:46 +01003439 [&status, &finalConfiguration]
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003440 (common::V1_0::Status s, const device::V3_3::HalStreamConfiguration& halConfiguration) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003441 finalConfiguration = halConfiguration;
3442 status = s;
3443 });
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003444 if (!err.isOk()) {
3445 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3446 return DEAD_OBJECT;
3447 }
3448 } else {
3449 // We don't; use v3.2 call and construct a v3.3 HalStreamConfiguration
3450 ALOGV("%s: v3.2 device found", __FUNCTION__);
3451 HalStreamConfiguration finalConfiguration_3_2;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003452 auto err = mHidlSession->configureStreams(requestedConfiguration3_2,
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003453 [&status, &finalConfiguration_3_2]
3454 (common::V1_0::Status s, const HalStreamConfiguration& halConfiguration) {
3455 finalConfiguration_3_2 = halConfiguration;
3456 status = s;
3457 });
3458 if (!err.isOk()) {
3459 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3460 return DEAD_OBJECT;
3461 }
3462 finalConfiguration.streams.resize(finalConfiguration_3_2.streams.size());
3463 for (size_t i = 0; i < finalConfiguration_3_2.streams.size(); i++) {
3464 finalConfiguration.streams[i].v3_2 = finalConfiguration_3_2.streams[i];
3465 finalConfiguration.streams[i].overrideDataSpace =
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003466 requestedConfiguration3_2.streams[i].dataSpace;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003467 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003468 }
3469
3470 if (status != common::V1_0::Status::OK ) {
3471 return CameraProviderManager::mapToStatusT(status);
3472 }
3473
3474 // And convert output stream configuration from HIDL
3475
3476 for (size_t i = 0; i < config->num_streams; i++) {
Emilian Peevf4816702020-04-03 15:44:51 -07003477 camera3::camera_stream_t *dst = config->streams[i];
Emilian Peev31abd0a2017-05-11 18:37:46 +01003478 int streamId = Camera3Stream::cast(dst)->getId();
3479
3480 // Start scan at i, with the assumption that the stream order matches
3481 size_t realIdx = i;
3482 bool found = false;
Eino-Ville Talvala370875f2019-04-12 12:40:27 -07003483 size_t halStreamCount = finalConfiguration.streams.size();
3484 for (size_t idx = 0; idx < halStreamCount; idx++) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003485 if (finalConfiguration.streams[realIdx].v3_2.id == streamId) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003486 found = true;
3487 break;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003488 }
Eino-Ville Talvala370875f2019-04-12 12:40:27 -07003489 realIdx = (realIdx >= halStreamCount - 1) ? 0 : realIdx + 1;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003490 }
3491 if (!found) {
3492 ALOGE("%s: Stream %d not found in stream configuration response from HAL",
3493 __FUNCTION__, streamId);
3494 return INVALID_OPERATION;
3495 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003496 device::V3_3::HalStream &src = finalConfiguration.streams[realIdx];
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003497 device::V3_6::HalStream &src_36 = finalConfiguration3_6.streams[realIdx];
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003498
Emilian Peev710c1422017-08-30 11:19:38 +01003499 Camera3Stream* dstStream = Camera3Stream::cast(dst);
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003500 int overrideFormat = mapToFrameworkFormat(src.v3_2.overrideFormat);
3501 android_dataspace overrideDataSpace = mapToFrameworkDataspace(src.overrideDataSpace);
3502
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003503 if (mHidlSession_3_6 != nullptr) {
3504 dstStream->setOfflineProcessingSupport(src_36.supportOffline);
3505 }
3506
Yin-Chia Yeh90667662019-07-01 15:45:00 -07003507 if (dstStream->getOriginalFormat() != HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
Shuzhen Wang92653952019-05-07 15:11:43 -07003508 dstStream->setFormatOverride(false);
3509 dstStream->setDataSpaceOverride(false);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003510 if (dst->format != overrideFormat) {
3511 ALOGE("%s: Stream %d: Format override not allowed for format 0x%x", __FUNCTION__,
3512 streamId, dst->format);
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003513 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003514 if (dst->data_space != overrideDataSpace) {
3515 ALOGE("%s: Stream %d: DataSpace override not allowed for format 0x%x", __FUNCTION__,
3516 streamId, dst->format);
3517 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003518 } else {
Shuzhen Wang92653952019-05-07 15:11:43 -07003519 bool needFormatOverride =
3520 requestedConfiguration3_2.streams[i].format != src.v3_2.overrideFormat;
3521 bool needDataspaceOverride =
3522 requestedConfiguration3_2.streams[i].dataSpace != src.overrideDataSpace;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003523 // Override allowed with IMPLEMENTATION_DEFINED
Shuzhen Wang92653952019-05-07 15:11:43 -07003524 dstStream->setFormatOverride(needFormatOverride);
3525 dstStream->setDataSpaceOverride(needDataspaceOverride);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003526 dst->format = overrideFormat;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003527 dst->data_space = overrideDataSpace;
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003528 }
3529
Emilian Peevf4816702020-04-03 15:44:51 -07003530 if (dst->stream_type == CAMERA_STREAM_INPUT) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003531 if (src.v3_2.producerUsage != 0) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003532 ALOGE("%s: Stream %d: INPUT streams must have 0 for producer usage",
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003533 __FUNCTION__, streamId);
3534 return INVALID_OPERATION;
3535 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003536 dstStream->setUsage(
3537 mapConsumerToFrameworkUsage(src.v3_2.consumerUsage));
Emilian Peev31abd0a2017-05-11 18:37:46 +01003538 } else {
3539 // OUTPUT
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003540 if (src.v3_2.consumerUsage != 0) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003541 ALOGE("%s: Stream %d: OUTPUT streams must have 0 for consumer usage",
3542 __FUNCTION__, streamId);
3543 return INVALID_OPERATION;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003544 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003545 dstStream->setUsage(
3546 mapProducerToFrameworkUsage(src.v3_2.producerUsage));
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003547 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003548 dst->max_buffers = src.v3_2.maxBuffers;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003549 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003550
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003551 return res;
3552}
3553
Cliff Wuc2ad9c82021-04-21 00:58:58 +08003554status_t Camera3Device::HalInterface::configureInjectedStreams(
3555 const camera_metadata_t* sessionParams, camera_stream_configuration* config,
3556 const std::vector<uint32_t>& bufferSizes,
3557 const CameraMetadata& cameraCharacteristics) {
3558 ATRACE_NAME("InjectionCameraHal::configureStreams");
3559 if (!valid()) return INVALID_OPERATION;
3560 status_t res = OK;
3561
3562 if (config->input_is_multi_resolution) {
3563 ALOGE("%s: Injection camera device doesn't support multi-resolution input "
3564 "stream", __FUNCTION__);
3565 return BAD_VALUE;
3566 }
3567
3568 // Convert stream config to HIDL
3569 std::set<int> activeStreams;
3570 device::V3_2::StreamConfiguration requestedConfiguration3_2;
3571 device::V3_4::StreamConfiguration requestedConfiguration3_4;
3572 device::V3_7::StreamConfiguration requestedConfiguration3_7;
3573 requestedConfiguration3_2.streams.resize(config->num_streams);
3574 requestedConfiguration3_4.streams.resize(config->num_streams);
3575 requestedConfiguration3_7.streams.resize(config->num_streams);
3576 for (size_t i = 0; i < config->num_streams; i++) {
3577 device::V3_2::Stream& dst3_2 = requestedConfiguration3_2.streams[i];
3578 device::V3_4::Stream& dst3_4 = requestedConfiguration3_4.streams[i];
3579 device::V3_7::Stream& dst3_7 = requestedConfiguration3_7.streams[i];
3580 camera3::camera_stream_t* src = config->streams[i];
3581
3582 Camera3Stream* cam3stream = Camera3Stream::cast(src);
3583 cam3stream->setBufferFreedListener(this);
3584 int streamId = cam3stream->getId();
3585 StreamType streamType;
3586 switch (src->stream_type) {
3587 case CAMERA_STREAM_OUTPUT:
3588 streamType = StreamType::OUTPUT;
3589 break;
3590 case CAMERA_STREAM_INPUT:
3591 streamType = StreamType::INPUT;
3592 break;
3593 default:
3594 ALOGE("%s: Stream %d: Unsupported stream type %d", __FUNCTION__,
3595 streamId, config->streams[i]->stream_type);
3596 return BAD_VALUE;
3597 }
3598 dst3_2.id = streamId;
3599 dst3_2.streamType = streamType;
3600 dst3_2.width = src->width;
3601 dst3_2.height = src->height;
3602 dst3_2.usage = mapToConsumerUsage(cam3stream->getUsage());
3603 dst3_2.rotation =
3604 mapToStreamRotation((camera_stream_rotation_t)src->rotation);
3605 // For HidlSession version 3.5 or newer, the format and dataSpace sent
3606 // to HAL are original, not the overridden ones.
3607 if (mHidlSession_3_5 != nullptr) {
3608 dst3_2.format = mapToPixelFormat(cam3stream->isFormatOverridden()
3609 ? cam3stream->getOriginalFormat()
3610 : src->format);
3611 dst3_2.dataSpace =
3612 mapToHidlDataspace(cam3stream->isDataSpaceOverridden()
3613 ? cam3stream->getOriginalDataSpace()
3614 : src->data_space);
3615 } else {
3616 dst3_2.format = mapToPixelFormat(src->format);
3617 dst3_2.dataSpace = mapToHidlDataspace(src->data_space);
3618 }
3619 dst3_4.v3_2 = dst3_2;
3620 dst3_4.bufferSize = bufferSizes[i];
3621 if (src->physical_camera_id != nullptr) {
3622 dst3_4.physicalCameraId = src->physical_camera_id;
3623 }
3624 dst3_7.v3_4 = dst3_4;
3625 dst3_7.groupId = cam3stream->getHalStreamGroupId();
3626 dst3_7.sensorPixelModesUsed.resize(src->sensor_pixel_modes_used.size());
3627 size_t j = 0;
3628 for (int mode : src->sensor_pixel_modes_used) {
3629 dst3_7.sensorPixelModesUsed[j++] =
3630 static_cast<CameraMetadataEnumAndroidSensorPixelMode>(mode);
3631 }
3632 activeStreams.insert(streamId);
3633 // Create Buffer ID map if necessary
3634 mBufferRecords.tryCreateBufferCache(streamId);
3635 }
3636 // remove BufferIdMap for deleted streams
3637 mBufferRecords.removeInactiveBufferCaches(activeStreams);
3638
3639 StreamConfigurationMode operationMode;
3640 res = mapToStreamConfigurationMode(
3641 (camera_stream_configuration_mode_t)config->operation_mode,
3642 /*out*/ &operationMode);
3643 if (res != OK) {
3644 return res;
3645 }
3646 requestedConfiguration3_7.operationMode = operationMode;
3647 size_t sessionParamSize = get_camera_metadata_size(sessionParams);
3648 requestedConfiguration3_7.operationMode = operationMode;
3649 requestedConfiguration3_7.sessionParams.setToExternal(
3650 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(sessionParams)),
3651 sessionParamSize);
3652
3653 // See which version of HAL we have
3654 if (mHidlSession_3_7 != nullptr) {
3655 requestedConfiguration3_7.streamConfigCounter = mNextStreamConfigCounter++;
3656 requestedConfiguration3_7.multiResolutionInputImage =
3657 config->input_is_multi_resolution;
3658
3659 const camera_metadata_t* rawMetadata = cameraCharacteristics.getAndLock();
3660 ::android::hardware::camera::device::V3_2::CameraMetadata hidlChars = {};
3661 hidlChars.setToExternal(
3662 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(rawMetadata)),
3663 get_camera_metadata_size(rawMetadata));
3664 cameraCharacteristics.unlock(rawMetadata);
3665
3666 sp<hardware::camera::device::V3_7::ICameraInjectionSession>
3667 hidlInjectionSession_3_7;
3668 auto castInjectionResult_3_7 =
3669 device::V3_7::ICameraInjectionSession::castFrom(mHidlSession_3_7);
3670 if (castInjectionResult_3_7.isOk()) {
3671 hidlInjectionSession_3_7 = castInjectionResult_3_7;
3672 } else {
3673 ALOGE("%s: Transaction error: %s", __FUNCTION__,
3674 castInjectionResult_3_7.description().c_str());
3675 return DEAD_OBJECT;
3676 }
3677
3678 auto err = hidlInjectionSession_3_7->configureInjectionStreams(
3679 requestedConfiguration3_7, hidlChars);
3680 if (!err.isOk()) {
3681 ALOGE("%s: Transaction error: %s", __FUNCTION__,
3682 err.description().c_str());
3683 return DEAD_OBJECT;
3684 }
3685 } else {
3686 ALOGE("%s: mHidlSession_3_7 does not exist, the lowest version of injection "
3687 "session is 3.7", __FUNCTION__);
3688 return DEAD_OBJECT;
3689 }
3690
3691 return res;
3692}
3693
Emilian Peevf4816702020-04-03 15:44:51 -07003694status_t Camera3Device::HalInterface::wrapAsHidlRequest(camera_capture_request_t* request,
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003695 /*out*/device::V3_2::CaptureRequest* captureRequest,
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003696 /*out*/std::vector<native_handle_t*>* handlesCreated,
3697 /*out*/std::vector<std::pair<int32_t, int32_t>>* inflightBuffers) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003698 ATRACE_CALL();
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003699 if (captureRequest == nullptr || handlesCreated == nullptr || inflightBuffers == nullptr) {
3700 ALOGE("%s: captureRequest (%p), handlesCreated (%p), and inflightBuffers(%p) "
3701 "must not be null", __FUNCTION__, captureRequest, handlesCreated, inflightBuffers);
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003702 return BAD_VALUE;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003703 }
3704
3705 captureRequest->frameNumber = request->frame_number;
Yifan Hongf79b5542017-04-11 14:44:25 -07003706
3707 captureRequest->fmqSettingsSize = 0;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003708
3709 {
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003710 if (request->input_buffer != nullptr) {
3711 int32_t streamId = Camera3Stream::cast(request->input_buffer->stream)->getId();
3712 buffer_handle_t buf = *(request->input_buffer->buffer);
3713 auto pair = getBufferId(buf, streamId);
3714 bool isNewBuffer = pair.first;
3715 uint64_t bufferId = pair.second;
3716 captureRequest->inputBuffer.streamId = streamId;
3717 captureRequest->inputBuffer.bufferId = bufferId;
3718 captureRequest->inputBuffer.buffer = (isNewBuffer) ? buf : nullptr;
3719 captureRequest->inputBuffer.status = BufferStatus::OK;
3720 native_handle_t *acquireFence = nullptr;
3721 if (request->input_buffer->acquire_fence != -1) {
3722 acquireFence = native_handle_create(1,0);
3723 acquireFence->data[0] = request->input_buffer->acquire_fence;
3724 handlesCreated->push_back(acquireFence);
3725 }
3726 captureRequest->inputBuffer.acquireFence = acquireFence;
3727 captureRequest->inputBuffer.releaseFence = nullptr;
3728
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003729 mBufferRecords.pushInflightBuffer(captureRequest->frameNumber, streamId,
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003730 request->input_buffer->buffer);
3731 inflightBuffers->push_back(std::make_pair(captureRequest->frameNumber, streamId));
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003732 } else {
3733 captureRequest->inputBuffer.streamId = -1;
3734 captureRequest->inputBuffer.bufferId = BUFFER_ID_NO_BUFFER;
3735 }
3736
3737 captureRequest->outputBuffers.resize(request->num_output_buffers);
3738 for (size_t i = 0; i < request->num_output_buffers; i++) {
Emilian Peevf4816702020-04-03 15:44:51 -07003739 const camera_stream_buffer_t *src = request->output_buffers + i;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003740 StreamBuffer &dst = captureRequest->outputBuffers[i];
3741 int32_t streamId = Camera3Stream::cast(src->stream)->getId();
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003742 if (src->buffer != nullptr) {
3743 buffer_handle_t buf = *(src->buffer);
3744 auto pair = getBufferId(buf, streamId);
3745 bool isNewBuffer = pair.first;
3746 dst.bufferId = pair.second;
3747 dst.buffer = isNewBuffer ? buf : nullptr;
3748 native_handle_t *acquireFence = nullptr;
3749 if (src->acquire_fence != -1) {
3750 acquireFence = native_handle_create(1,0);
3751 acquireFence->data[0] = src->acquire_fence;
3752 handlesCreated->push_back(acquireFence);
3753 }
3754 dst.acquireFence = acquireFence;
3755 } else if (mUseHalBufManager) {
3756 // HAL buffer management path
3757 dst.bufferId = BUFFER_ID_NO_BUFFER;
3758 dst.buffer = nullptr;
3759 dst.acquireFence = nullptr;
3760 } else {
3761 ALOGE("%s: cannot send a null buffer in capture request!", __FUNCTION__);
3762 return BAD_VALUE;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003763 }
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003764 dst.streamId = streamId;
3765 dst.status = BufferStatus::OK;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003766 dst.releaseFence = nullptr;
3767
Yin-Chia Yeh5f840f82019-03-05 11:59:04 -08003768 // Output buffers are empty when using HAL buffer manager
3769 if (!mUseHalBufManager) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003770 mBufferRecords.pushInflightBuffer(
3771 captureRequest->frameNumber, streamId, src->buffer);
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003772 inflightBuffers->push_back(std::make_pair(captureRequest->frameNumber, streamId));
Yin-Chia Yeh5f840f82019-03-05 11:59:04 -08003773 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003774 }
3775 }
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003776 return OK;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003777}
3778
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003779void Camera3Device::HalInterface::cleanupNativeHandles(
3780 std::vector<native_handle_t*> *handles, bool closeFd) {
3781 if (handles == nullptr) {
3782 return;
3783 }
3784 if (closeFd) {
3785 for (auto& handle : *handles) {
3786 native_handle_close(handle);
3787 }
3788 }
3789 for (auto& handle : *handles) {
3790 native_handle_delete(handle);
3791 }
3792 handles->clear();
3793 return;
3794}
3795
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003796status_t Camera3Device::HalInterface::processBatchCaptureRequests(
Emilian Peevf4816702020-04-03 15:44:51 -07003797 std::vector<camera_capture_request_t*>& requests,/*out*/uint32_t* numRequestProcessed) {
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003798 ATRACE_NAME("CameraHal::processBatchCaptureRequests");
3799 if (!valid()) return INVALID_OPERATION;
3800
Emilian Peevaebbe412018-01-15 13:53:24 +00003801 sp<device::V3_4::ICameraDeviceSession> hidlSession_3_4;
Shuzhen Wang83bff122020-11-20 15:51:39 -08003802 sp<device::V3_7::ICameraDeviceSession> hidlSession_3_7;
3803 auto castResult_3_7 = device::V3_7::ICameraDeviceSession::castFrom(mHidlSession);
3804 if (castResult_3_7.isOk()) {
3805 hidlSession_3_7 = castResult_3_7;
3806 }
Emilian Peevaebbe412018-01-15 13:53:24 +00003807 auto castResult_3_4 = device::V3_4::ICameraDeviceSession::castFrom(mHidlSession);
3808 if (castResult_3_4.isOk()) {
3809 hidlSession_3_4 = castResult_3_4;
3810 }
3811
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003812 hardware::hidl_vec<device::V3_2::CaptureRequest> captureRequests;
Emilian Peevaebbe412018-01-15 13:53:24 +00003813 hardware::hidl_vec<device::V3_4::CaptureRequest> captureRequests_3_4;
Shuzhen Wang83bff122020-11-20 15:51:39 -08003814 hardware::hidl_vec<device::V3_7::CaptureRequest> captureRequests_3_7;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003815 size_t batchSize = requests.size();
Shuzhen Wang83bff122020-11-20 15:51:39 -08003816 if (hidlSession_3_7 != nullptr) {
3817 captureRequests_3_7.resize(batchSize);
3818 } else if (hidlSession_3_4 != nullptr) {
Emilian Peevaebbe412018-01-15 13:53:24 +00003819 captureRequests_3_4.resize(batchSize);
3820 } else {
3821 captureRequests.resize(batchSize);
3822 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003823 std::vector<native_handle_t*> handlesCreated;
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003824 std::vector<std::pair<int32_t, int32_t>> inflightBuffers;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003825
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003826 status_t res = OK;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003827 for (size_t i = 0; i < batchSize; i++) {
Shuzhen Wang83bff122020-11-20 15:51:39 -08003828 if (hidlSession_3_7 != nullptr) {
3829 res = wrapAsHidlRequest(requests[i], /*out*/&captureRequests_3_7[i].v3_4.v3_2,
3830 /*out*/&handlesCreated, /*out*/&inflightBuffers);
3831 } else if (hidlSession_3_4 != nullptr) {
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003832 res = wrapAsHidlRequest(requests[i], /*out*/&captureRequests_3_4[i].v3_2,
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003833 /*out*/&handlesCreated, /*out*/&inflightBuffers);
Emilian Peevaebbe412018-01-15 13:53:24 +00003834 } else {
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003835 res = wrapAsHidlRequest(requests[i], /*out*/&captureRequests[i],
3836 /*out*/&handlesCreated, /*out*/&inflightBuffers);
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003837 }
3838 if (res != OK) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003839 mBufferRecords.popInflightBuffers(inflightBuffers);
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003840 cleanupNativeHandles(&handlesCreated);
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003841 return res;
Emilian Peevaebbe412018-01-15 13:53:24 +00003842 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003843 }
3844
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003845 std::vector<device::V3_2::BufferCache> cachesToRemove;
3846 {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003847 std::lock_guard<std::mutex> lock(mFreedBuffersLock);
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003848 for (auto& pair : mFreedBuffers) {
3849 // The stream might have been removed since onBufferFreed
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003850 if (mBufferRecords.isStreamCached(pair.first)) {
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003851 cachesToRemove.push_back({pair.first, pair.second});
3852 }
3853 }
3854 mFreedBuffers.clear();
3855 }
3856
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003857 common::V1_0::Status status = common::V1_0::Status::INTERNAL_ERROR;
3858 *numRequestProcessed = 0;
Yifan Hongf79b5542017-04-11 14:44:25 -07003859
3860 // Write metadata to FMQ.
3861 for (size_t i = 0; i < batchSize; i++) {
Emilian Peevf4816702020-04-03 15:44:51 -07003862 camera_capture_request_t* request = requests[i];
Emilian Peevaebbe412018-01-15 13:53:24 +00003863 device::V3_2::CaptureRequest* captureRequest;
Shuzhen Wang83bff122020-11-20 15:51:39 -08003864 if (hidlSession_3_7 != nullptr) {
3865 captureRequest = &captureRequests_3_7[i].v3_4.v3_2;
3866 } else if (hidlSession_3_4 != nullptr) {
Emilian Peevaebbe412018-01-15 13:53:24 +00003867 captureRequest = &captureRequests_3_4[i].v3_2;
3868 } else {
3869 captureRequest = &captureRequests[i];
3870 }
Yifan Hongf79b5542017-04-11 14:44:25 -07003871
3872 if (request->settings != nullptr) {
3873 size_t settingsSize = get_camera_metadata_size(request->settings);
3874 if (mRequestMetadataQueue != nullptr && mRequestMetadataQueue->write(
3875 reinterpret_cast<const uint8_t*>(request->settings), settingsSize)) {
3876 captureRequest->settings.resize(0);
3877 captureRequest->fmqSettingsSize = settingsSize;
3878 } else {
3879 if (mRequestMetadataQueue != nullptr) {
3880 ALOGW("%s: couldn't utilize fmq, fallback to hwbinder", __FUNCTION__);
3881 }
3882 captureRequest->settings.setToExternal(
3883 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(request->settings)),
3884 get_camera_metadata_size(request->settings));
3885 captureRequest->fmqSettingsSize = 0u;
3886 }
3887 } else {
3888 // A null request settings maps to a size-0 CameraMetadata
3889 captureRequest->settings.resize(0);
3890 captureRequest->fmqSettingsSize = 0u;
3891 }
Emilian Peevaebbe412018-01-15 13:53:24 +00003892
Shuzhen Wang83bff122020-11-20 15:51:39 -08003893 // hidl session 3.7 specific handling.
3894 if (hidlSession_3_7 != nullptr) {
3895 captureRequests_3_7[i].inputWidth = request->input_width;
3896 captureRequests_3_7[i].inputHeight = request->input_height;
3897 }
3898
3899 // hidl session 3.7 and 3.4 specific handling.
3900 if (hidlSession_3_7 != nullptr || hidlSession_3_4 != nullptr) {
3901 hardware::hidl_vec<device::V3_4::PhysicalCameraSetting>& physicalCameraSettings =
3902 (hidlSession_3_7 != nullptr) ?
3903 captureRequests_3_7[i].v3_4.physicalCameraSettings :
3904 captureRequests_3_4[i].physicalCameraSettings;
3905 physicalCameraSettings.resize(request->num_physcam_settings);
Emilian Peevaebbe412018-01-15 13:53:24 +00003906 for (size_t j = 0; j < request->num_physcam_settings; j++) {
Emilian Peev00420d22018-02-05 21:33:13 +00003907 if (request->physcam_settings != nullptr) {
3908 size_t settingsSize = get_camera_metadata_size(request->physcam_settings[j]);
3909 if (mRequestMetadataQueue != nullptr && mRequestMetadataQueue->write(
3910 reinterpret_cast<const uint8_t*>(request->physcam_settings[j]),
3911 settingsSize)) {
Shuzhen Wang83bff122020-11-20 15:51:39 -08003912 physicalCameraSettings[j].settings.resize(0);
3913 physicalCameraSettings[j].fmqSettingsSize = settingsSize;
Emilian Peev00420d22018-02-05 21:33:13 +00003914 } else {
3915 if (mRequestMetadataQueue != nullptr) {
3916 ALOGW("%s: couldn't utilize fmq, fallback to hwbinder", __FUNCTION__);
3917 }
Shuzhen Wang83bff122020-11-20 15:51:39 -08003918 physicalCameraSettings[j].settings.setToExternal(
Emilian Peev00420d22018-02-05 21:33:13 +00003919 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(
3920 request->physcam_settings[j])),
3921 get_camera_metadata_size(request->physcam_settings[j]));
Shuzhen Wang83bff122020-11-20 15:51:39 -08003922 physicalCameraSettings[j].fmqSettingsSize = 0u;
Emilian Peevaebbe412018-01-15 13:53:24 +00003923 }
Emilian Peev00420d22018-02-05 21:33:13 +00003924 } else {
Yin-Chia Yeha2849702021-03-10 10:11:33 -08003925 physicalCameraSettings[j].fmqSettingsSize = 0u;
3926 physicalCameraSettings[j].settings.resize(0);
Emilian Peevaebbe412018-01-15 13:53:24 +00003927 }
Shuzhen Wang83bff122020-11-20 15:51:39 -08003928 physicalCameraSettings[j].physicalCameraId = request->physcam_id[j];
Emilian Peevaebbe412018-01-15 13:53:24 +00003929 }
3930 }
Yifan Hongf79b5542017-04-11 14:44:25 -07003931 }
Emilian Peevaebbe412018-01-15 13:53:24 +00003932
3933 hardware::details::return_status err;
Jayant Chowdharyc8d581e2018-07-16 14:46:23 -07003934 auto resultCallback =
3935 [&status, &numRequestProcessed] (auto s, uint32_t n) {
3936 status = s;
3937 *numRequestProcessed = n;
3938 };
Shuzhen Wang83bff122020-11-20 15:51:39 -08003939 if (hidlSession_3_7 != nullptr) {
3940 err = hidlSession_3_7->processCaptureRequest_3_7(captureRequests_3_7, cachesToRemove,
3941 resultCallback);
3942 } else if (hidlSession_3_4 != nullptr) {
Emilian Peevaebbe412018-01-15 13:53:24 +00003943 err = hidlSession_3_4->processCaptureRequest_3_4(captureRequests_3_4, cachesToRemove,
Jayant Chowdharyc8d581e2018-07-16 14:46:23 -07003944 resultCallback);
Emilian Peevaebbe412018-01-15 13:53:24 +00003945 } else {
3946 err = mHidlSession->processCaptureRequest(captureRequests, cachesToRemove,
Jayant Chowdharyc8d581e2018-07-16 14:46:23 -07003947 resultCallback);
Emilian Peevaebbe412018-01-15 13:53:24 +00003948 }
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -07003949 if (!err.isOk()) {
3950 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003951 status = common::V1_0::Status::CAMERA_DISCONNECTED;
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -07003952 }
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003953
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003954 if (status == common::V1_0::Status::OK && *numRequestProcessed != batchSize) {
3955 ALOGE("%s: processCaptureRequest returns OK but processed %d/%zu requests",
3956 __FUNCTION__, *numRequestProcessed, batchSize);
3957 status = common::V1_0::Status::INTERNAL_ERROR;
3958 }
3959
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003960 res = CameraProviderManager::mapToStatusT(status);
3961 if (res == OK) {
3962 if (mHidlSession->isRemote()) {
3963 // Only close acquire fence FDs when the HIDL transaction succeeds (so the FDs have been
3964 // sent to camera HAL processes)
3965 cleanupNativeHandles(&handlesCreated, /*closeFd*/true);
3966 } else {
3967 // In passthrough mode the FDs are now owned by HAL
3968 cleanupNativeHandles(&handlesCreated);
3969 }
3970 } else {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003971 mBufferRecords.popInflightBuffers(inflightBuffers);
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003972 cleanupNativeHandles(&handlesCreated);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003973 }
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003974 return res;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003975}
3976
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003977status_t Camera3Device::HalInterface::flush() {
3978 ATRACE_NAME("CameraHal::flush");
3979 if (!valid()) return INVALID_OPERATION;
3980 status_t res = OK;
3981
Emilian Peev31abd0a2017-05-11 18:37:46 +01003982 auto err = mHidlSession->flush();
3983 if (!err.isOk()) {
3984 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3985 res = DEAD_OBJECT;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003986 } else {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003987 res = CameraProviderManager::mapToStatusT(err);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003988 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003989
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003990 return res;
3991}
3992
Emilian Peev31abd0a2017-05-11 18:37:46 +01003993status_t Camera3Device::HalInterface::dump(int /*fd*/) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003994 ATRACE_NAME("CameraHal::dump");
3995 if (!valid()) return INVALID_OPERATION;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003996
Emilian Peev31abd0a2017-05-11 18:37:46 +01003997 // Handled by CameraProviderManager::dump
3998
3999 return OK;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004000}
4001
4002status_t Camera3Device::HalInterface::close() {
4003 ATRACE_NAME("CameraHal::close()");
4004 if (!valid()) return INVALID_OPERATION;
4005 status_t res = OK;
4006
Emilian Peev31abd0a2017-05-11 18:37:46 +01004007 auto err = mHidlSession->close();
4008 // Interface will be dead shortly anyway, so don't log errors
4009 if (!err.isOk()) {
4010 res = DEAD_OBJECT;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004011 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01004012
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004013 return res;
4014}
4015
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004016void Camera3Device::HalInterface::signalPipelineDrain(const std::vector<int>& streamIds) {
4017 ATRACE_NAME("CameraHal::signalPipelineDrain");
4018 if (!valid() || mHidlSession_3_5 == nullptr) {
4019 ALOGE("%s called on invalid camera!", __FUNCTION__);
4020 return;
4021 }
4022
Yin-Chia Yehc300a072019-02-13 14:56:57 -08004023 auto err = mHidlSession_3_5->signalStreamFlush(streamIds, mNextStreamConfigCounter - 1);
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004024 if (!err.isOk()) {
4025 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
4026 return;
4027 }
4028}
4029
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004030status_t Camera3Device::HalInterface::switchToOffline(
4031 const std::vector<int32_t>& streamsToKeep,
4032 /*out*/hardware::camera::device::V3_6::CameraOfflineSessionInfo* offlineSessionInfo,
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004033 /*out*/sp<hardware::camera::device::V3_6::ICameraOfflineSession>* offlineSession,
4034 /*out*/camera3::BufferRecords* bufferRecords) {
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004035 ATRACE_NAME("CameraHal::switchToOffline");
4036 if (!valid() || mHidlSession_3_6 == nullptr) {
4037 ALOGE("%s called on invalid camera!", __FUNCTION__);
4038 return INVALID_OPERATION;
4039 }
4040
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004041 if (offlineSessionInfo == nullptr || offlineSession == nullptr || bufferRecords == nullptr) {
4042 ALOGE("%s: output arguments must not be null!", __FUNCTION__);
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004043 return INVALID_OPERATION;
4044 }
4045
4046 common::V1_0::Status status = common::V1_0::Status::INTERNAL_ERROR;
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004047 auto resultCallback =
4048 [&status, &offlineSessionInfo, &offlineSession] (auto s, auto info, auto session) {
4049 status = s;
4050 *offlineSessionInfo = info;
4051 *offlineSession = session;
4052 };
4053 auto err = mHidlSession_3_6->switchToOffline(streamsToKeep, resultCallback);
4054
4055 if (!err.isOk()) {
4056 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
4057 return DEAD_OBJECT;
4058 }
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004059
4060 status_t ret = CameraProviderManager::mapToStatusT(status);
4061 if (ret != OK) {
4062 return ret;
4063 }
4064
4065 // TODO: assert no ongoing requestBuffer/returnBuffer call here
4066 // TODO: update RequestBufferStateMachine to block requestBuffer/returnBuffer once HAL
4067 // returns from switchToOffline.
4068
4069
4070 // Validate buffer caches
4071 std::vector<int32_t> streams;
4072 streams.reserve(offlineSessionInfo->offlineStreams.size());
4073 for (auto offlineStream : offlineSessionInfo->offlineStreams) {
4074 int32_t id = offlineStream.id;
4075 streams.push_back(id);
4076 // Verify buffer caches
4077 std::vector<uint64_t> bufIds(offlineStream.circulatingBufferIds.begin(),
4078 offlineStream.circulatingBufferIds.end());
4079 if (!verifyBufferIds(id, bufIds)) {
4080 ALOGE("%s: stream ID %d buffer cache records mismatch!", __FUNCTION__, id);
4081 return UNKNOWN_ERROR;
4082 }
4083 }
4084
4085 // Move buffer records
4086 bufferRecords->takeBufferCaches(mBufferRecords, streams);
4087 bufferRecords->takeInflightBufferMap(mBufferRecords);
4088 bufferRecords->takeRequestedBufferMap(mBufferRecords);
4089 return ret;
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004090}
4091
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07004092void Camera3Device::HalInterface::getInflightBufferKeys(
4093 std::vector<std::pair<int32_t, int32_t>>* out) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004094 mBufferRecords.getInflightBufferKeys(out);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07004095 return;
4096}
4097
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08004098void Camera3Device::HalInterface::getInflightRequestBufferKeys(
4099 std::vector<uint64_t>* out) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004100 mBufferRecords.getInflightRequestBufferKeys(out);
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08004101 return;
4102}
4103
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004104bool Camera3Device::HalInterface::verifyBufferIds(
4105 int32_t streamId, std::vector<uint64_t>& bufIds) {
4106 return mBufferRecords.verifyBufferIds(streamId, bufIds);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004107}
4108
4109status_t Camera3Device::HalInterface::popInflightBuffer(
Yin-Chia Yehf4650602017-01-10 13:13:39 -08004110 int32_t frameNumber, int32_t streamId,
4111 /*out*/ buffer_handle_t **buffer) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004112 return mBufferRecords.popInflightBuffer(frameNumber, streamId, buffer);
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07004113}
4114
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004115status_t Camera3Device::HalInterface::pushInflightRequestBuffer(
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08004116 uint64_t bufferId, buffer_handle_t* buf, int32_t streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004117 return mBufferRecords.pushInflightRequestBuffer(bufferId, buf, streamId);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004118}
4119
4120// Find and pop a buffer_handle_t based on bufferId
4121status_t Camera3Device::HalInterface::popInflightRequestBuffer(
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08004122 uint64_t bufferId,
4123 /*out*/ buffer_handle_t** buffer,
4124 /*optional out*/ int32_t* streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004125 return mBufferRecords.popInflightRequestBuffer(bufferId, buffer, streamId);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004126}
4127
Yin-Chia Yeh77327052017-01-09 18:23:07 -08004128std::pair<bool, uint64_t> Camera3Device::HalInterface::getBufferId(
4129 const buffer_handle_t& buf, int streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004130 return mBufferRecords.getBufferId(buf, streamId);
Yin-Chia Yeh77327052017-01-09 18:23:07 -08004131}
4132
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07004133void Camera3Device::HalInterface::onBufferFreed(
4134 int streamId, const native_handle_t* handle) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004135 uint32_t bufferId = mBufferRecords.removeOneBufferCache(streamId, handle);
4136 std::lock_guard<std::mutex> lock(mFreedBuffersLock);
4137 if (bufferId != BUFFER_ID_NO_BUFFER) {
4138 mFreedBuffers.push_back(std::make_pair(streamId, bufferId));
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07004139 }
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07004140}
4141
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07004142void Camera3Device::HalInterface::onStreamReConfigured(int streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004143 std::vector<uint64_t> bufIds = mBufferRecords.clearBufferCaches(streamId);
4144 std::lock_guard<std::mutex> lock(mFreedBuffersLock);
4145 for (auto bufferId : bufIds) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07004146 mFreedBuffers.push_back(std::make_pair(streamId, bufferId));
4147 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07004148}
4149
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004150/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004151 * RequestThread inner class methods
4152 */
4153
4154Camera3Device::RequestThread::RequestThread(wp<Camera3Device> parent,
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004155 sp<StatusTracker> statusTracker,
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004156 sp<HalInterface> interface, const Vector<int32_t>& sessionParamKeys,
4157 bool useHalBufManager) :
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004158 Thread(/*canCallJava*/false),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004159 mParent(parent),
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004160 mStatusTracker(statusTracker),
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004161 mInterface(interface),
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07004162 mListener(nullptr),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004163 mId(getId(parent)),
Shuzhen Wang316781a2020-08-18 18:11:01 -07004164 mFirstRepeating(false),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004165 mReconfigured(false),
4166 mDoPause(false),
4167 mPaused(true),
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004168 mNotifyPipelineDrain(false),
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004169 mFrameNumber(0),
Jianing Weicb0652e2014-03-12 18:29:36 -07004170 mLatestRequestId(NAME_NOT_FOUND),
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07004171 mCurrentAfTriggerId(0),
4172 mCurrentPreCaptureTriggerId(0),
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004173 mRotateAndCropOverride(ANDROID_SCALER_ROTATE_AND_CROP_NONE),
Eino-Ville Talvala11afe4f2021-05-27 14:45:31 -07004174 mCameraMute(ANDROID_SENSOR_TEST_PATTERN_MODE_OFF),
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004175 mCameraMuteChanged(false),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004176 mRepeatingLastFrameNumber(
4177 hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES),
Shuzhen Wang686f6442017-06-20 16:16:04 -07004178 mPrepareVideoStream(false),
Emilian Peeva14b4dd2018-05-15 11:00:31 +01004179 mConstrainedMode(false),
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004180 mRequestLatency(kRequestLatencyBinSize),
4181 mSessionParamKeys(sessionParamKeys),
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004182 mLatestSessionParams(sessionParamKeys.size()),
4183 mUseHalBufManager(useHalBufManager) {
Yin-Chia Yeh87b3ec02019-06-03 10:44:39 -07004184 mStatusId = statusTracker->addComponent("RequestThread");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004185}
4186
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004187Camera3Device::RequestThread::~RequestThread() {}
4188
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004189void Camera3Device::RequestThread::setNotificationListener(
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004190 wp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004191 ATRACE_CALL();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004192 Mutex::Autolock l(mRequestLock);
4193 mListener = listener;
4194}
4195
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004196void Camera3Device::RequestThread::configurationComplete(bool isConstrainedHighSpeed,
Shuzhen Wang99080502021-03-07 21:08:20 -08004197 const CameraMetadata& sessionParams,
4198 const std::map<int32_t, std::set<String8>>& groupIdPhysicalCameraMap) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004199 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004200 Mutex::Autolock l(mRequestLock);
4201 mReconfigured = true;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004202 mLatestSessionParams = sessionParams;
Shuzhen Wang99080502021-03-07 21:08:20 -08004203 mGroupIdPhysicalCameraMap = groupIdPhysicalCameraMap;
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07004204 // Prepare video stream for high speed recording.
4205 mPrepareVideoStream = isConstrainedHighSpeed;
Emilian Peeva14b4dd2018-05-15 11:00:31 +01004206 mConstrainedMode = isConstrainedHighSpeed;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004207}
4208
Jianing Wei90e59c92014-03-12 18:29:36 -07004209status_t Camera3Device::RequestThread::queueRequestList(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004210 List<sp<CaptureRequest> > &requests,
4211 /*out*/
4212 int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004213 ATRACE_CALL();
Jianing Wei90e59c92014-03-12 18:29:36 -07004214 Mutex::Autolock l(mRequestLock);
4215 for (List<sp<CaptureRequest> >::iterator it = requests.begin(); it != requests.end();
4216 ++it) {
4217 mRequestQueue.push_back(*it);
4218 }
4219
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004220 if (lastFrameNumber != NULL) {
4221 *lastFrameNumber = mFrameNumber + mRequestQueue.size() - 1;
4222 ALOGV("%s: requestId %d, mFrameNumber %" PRId32 ", lastFrameNumber %" PRId64 ".",
4223 __FUNCTION__, (*(requests.begin()))->mResultExtras.requestId, mFrameNumber,
4224 *lastFrameNumber);
4225 }
Jianing Weicb0652e2014-03-12 18:29:36 -07004226
Jianing Wei90e59c92014-03-12 18:29:36 -07004227 unpauseForNewRequests();
4228
4229 return OK;
4230}
4231
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004232
4233status_t Camera3Device::RequestThread::queueTrigger(
4234 RequestTrigger trigger[],
4235 size_t count) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004236 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004237 Mutex::Autolock l(mTriggerMutex);
4238 status_t ret;
4239
4240 for (size_t i = 0; i < count; ++i) {
4241 ret = queueTriggerLocked(trigger[i]);
4242
4243 if (ret != OK) {
4244 return ret;
4245 }
4246 }
4247
4248 return OK;
4249}
4250
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004251const String8& Camera3Device::RequestThread::getId(const wp<Camera3Device> &device) {
4252 static String8 deadId("<DeadDevice>");
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004253 sp<Camera3Device> d = device.promote();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004254 if (d != nullptr) return d->mId;
4255 return deadId;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004256}
4257
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004258status_t Camera3Device::RequestThread::queueTriggerLocked(
4259 RequestTrigger trigger) {
4260
4261 uint32_t tag = trigger.metadataTag;
4262 ssize_t index = mTriggerMap.indexOfKey(tag);
4263
4264 switch (trigger.getTagType()) {
4265 case TYPE_BYTE:
4266 // fall-through
4267 case TYPE_INT32:
4268 break;
4269 default:
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004270 ALOGE("%s: Type not supported: 0x%x", __FUNCTION__,
4271 trigger.getTagType());
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004272 return INVALID_OPERATION;
4273 }
4274
4275 /**
4276 * Collect only the latest trigger, since we only have 1 field
4277 * in the request settings per trigger tag, and can't send more than 1
4278 * trigger per request.
4279 */
4280 if (index != NAME_NOT_FOUND) {
4281 mTriggerMap.editValueAt(index) = trigger;
4282 } else {
4283 mTriggerMap.add(tag, trigger);
4284 }
4285
4286 return OK;
4287}
4288
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004289status_t Camera3Device::RequestThread::setRepeatingRequests(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004290 const RequestList &requests,
4291 /*out*/
4292 int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004293 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004294 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004295 if (lastFrameNumber != NULL) {
4296 *lastFrameNumber = mRepeatingLastFrameNumber;
4297 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004298 mRepeatingRequests.clear();
Shuzhen Wang316781a2020-08-18 18:11:01 -07004299 mFirstRepeating = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004300 mRepeatingRequests.insert(mRepeatingRequests.begin(),
4301 requests.begin(), requests.end());
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004302
4303 unpauseForNewRequests();
4304
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004305 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004306 return OK;
4307}
4308
Chih-Hung Hsieh8b0b9712016-08-09 14:25:53 -07004309bool Camera3Device::RequestThread::isRepeatingRequestLocked(const sp<CaptureRequest>& requestIn) {
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07004310 if (mRepeatingRequests.empty()) {
4311 return false;
4312 }
4313 int32_t requestId = requestIn->mResultExtras.requestId;
4314 const RequestList &repeatRequests = mRepeatingRequests;
4315 // All repeating requests are guaranteed to have same id so only check first quest
4316 const sp<CaptureRequest> firstRequest = *repeatRequests.begin();
4317 return (firstRequest->mResultExtras.requestId == requestId);
4318}
4319
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004320status_t Camera3Device::RequestThread::clearRepeatingRequests(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004321 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004322 Mutex::Autolock l(mRequestLock);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004323 return clearRepeatingRequestsLocked(lastFrameNumber);
4324
4325}
4326
4327status_t Camera3Device::RequestThread::clearRepeatingRequestsLocked(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004328 mRepeatingRequests.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004329 if (lastFrameNumber != NULL) {
4330 *lastFrameNumber = mRepeatingLastFrameNumber;
4331 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004332 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004333 return OK;
4334}
4335
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004336status_t Camera3Device::RequestThread::clear(
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004337 /*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004338 ATRACE_CALL();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004339 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004340 ALOGV("RequestThread::%s:", __FUNCTION__);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004341
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004342 mRepeatingRequests.clear();
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07004343
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004344 // Send errors for all requests pending in the request queue, including
4345 // pending repeating requests
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004346 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004347 if (listener != NULL) {
4348 for (RequestList::iterator it = mRequestQueue.begin();
4349 it != mRequestQueue.end(); ++it) {
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004350 // Abort the input buffers for reprocess requests.
4351 if ((*it)->mInputStream != NULL) {
Emilian Peevf4816702020-04-03 15:44:51 -07004352 camera_stream_buffer_t inputBuffer;
Shuzhen Wang83bff122020-11-20 15:51:39 -08004353 camera3::Size inputBufferSize;
Eino-Ville Talvalaba435252017-06-21 16:07:25 -07004354 status_t res = (*it)->mInputStream->getInputBuffer(&inputBuffer,
Shuzhen Wang83bff122020-11-20 15:51:39 -08004355 &inputBufferSize, /*respectHalLimit*/ false);
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004356 if (res != OK) {
4357 ALOGW("%s: %d: couldn't get input buffer while clearing the request "
4358 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
4359 } else {
Emilian Peevf4816702020-04-03 15:44:51 -07004360 inputBuffer.status = CAMERA_BUFFER_STATUS_ERROR;
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004361 res = (*it)->mInputStream->returnInputBuffer(inputBuffer);
4362 if (res != OK) {
4363 ALOGE("%s: %d: couldn't return input buffer while clearing the request "
4364 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
4365 }
4366 }
4367 }
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004368 // Set the frame number this request would have had, if it
4369 // had been submitted; this frame number will not be reused.
4370 // The requestId and burstId fields were set when the request was
4371 // submitted originally (in convertMetadataListToRequestListLocked)
4372 (*it)->mResultExtras.frameNumber = mFrameNumber++;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004373 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004374 (*it)->mResultExtras);
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07004375 }
4376 }
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004377 mRequestQueue.clear();
Jinguang Dongb26e7a02016-11-14 16:04:02 +08004378
4379 Mutex::Autolock al(mTriggerMutex);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004380 mTriggerMap.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004381 if (lastFrameNumber != NULL) {
4382 *lastFrameNumber = mRepeatingLastFrameNumber;
4383 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004384 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Emilian Peev8dae54c2019-12-02 15:17:17 -08004385 mRequestSignal.signal();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004386 return OK;
4387}
4388
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004389status_t Camera3Device::RequestThread::flush() {
4390 ATRACE_CALL();
4391 Mutex::Autolock l(mFlushLock);
4392
Emilian Peev08dd2452017-04-06 16:55:14 +01004393 return mInterface->flush();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004394}
4395
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004396void Camera3Device::RequestThread::setPaused(bool paused) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004397 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004398 Mutex::Autolock l(mPauseLock);
4399 mDoPause = paused;
4400 mDoPauseSignal.signal();
4401}
4402
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004403status_t Camera3Device::RequestThread::waitUntilRequestProcessed(
4404 int32_t requestId, nsecs_t timeout) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004405 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004406 Mutex::Autolock l(mLatestRequestMutex);
4407 status_t res;
4408 while (mLatestRequestId != requestId) {
4409 nsecs_t startTime = systemTime();
4410
4411 res = mLatestRequestSignal.waitRelative(mLatestRequestMutex, timeout);
4412 if (res != OK) return res;
4413
4414 timeout -= (systemTime() - startTime);
4415 }
4416
4417 return OK;
4418}
4419
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004420void Camera3Device::RequestThread::requestExit() {
4421 // Call parent to set up shutdown
4422 Thread::requestExit();
4423 // The exit from any possible waits
4424 mDoPauseSignal.signal();
4425 mRequestSignal.signal();
Shuzhen Wang686f6442017-06-20 16:16:04 -07004426
4427 mRequestLatency.log("ProcessCaptureRequest latency histogram");
4428 mRequestLatency.reset();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004429}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004430
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004431void Camera3Device::RequestThread::checkAndStopRepeatingRequest() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004432 ATRACE_CALL();
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07004433 bool surfaceAbandoned = false;
4434 int64_t lastFrameNumber = 0;
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004435 sp<NotificationListener> listener;
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07004436 {
4437 Mutex::Autolock l(mRequestLock);
4438 // Check all streams needed by repeating requests are still valid. Otherwise, stop
4439 // repeating requests.
4440 for (const auto& request : mRepeatingRequests) {
4441 for (const auto& s : request->mOutputStreams) {
4442 if (s->isAbandoned()) {
4443 surfaceAbandoned = true;
4444 clearRepeatingRequestsLocked(&lastFrameNumber);
4445 break;
4446 }
4447 }
4448 if (surfaceAbandoned) {
4449 break;
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004450 }
4451 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004452 listener = mListener.promote();
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004453 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004454
4455 if (listener != NULL && surfaceAbandoned) {
4456 listener->notifyRepeatingRequestError(lastFrameNumber);
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07004457 }
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004458}
4459
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004460bool Camera3Device::RequestThread::sendRequestsBatch() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004461 ATRACE_CALL();
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004462 status_t res;
4463 size_t batchSize = mNextRequests.size();
Emilian Peevf4816702020-04-03 15:44:51 -07004464 std::vector<camera_capture_request_t*> requests(batchSize);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004465 uint32_t numRequestProcessed = 0;
4466 for (size_t i = 0; i < batchSize; i++) {
4467 requests[i] = &mNextRequests.editItemAt(i).halRequest;
Yin-Chia Yeh885691c2018-05-01 15:54:24 -07004468 ATRACE_ASYNC_BEGIN("frame capture", mNextRequests[i].halRequest.frame_number);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004469 }
4470
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004471 res = mInterface->processBatchCaptureRequests(requests, &numRequestProcessed);
4472
4473 bool triggerRemoveFailed = false;
4474 NextRequest& triggerFailedRequest = mNextRequests.editItemAt(0);
4475 for (size_t i = 0; i < numRequestProcessed; i++) {
4476 NextRequest& nextRequest = mNextRequests.editItemAt(i);
4477 nextRequest.submitted = true;
4478
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004479 updateNextRequest(nextRequest);
Emilian Peevaebbe412018-01-15 13:53:24 +00004480
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004481 if (!triggerRemoveFailed) {
4482 // Remove any previously queued triggers (after unlock)
4483 status_t removeTriggerRes = removeTriggers(mPrevRequest);
4484 if (removeTriggerRes != OK) {
4485 triggerRemoveFailed = true;
4486 triggerFailedRequest = nextRequest;
4487 }
4488 }
4489 }
4490
4491 if (triggerRemoveFailed) {
4492 SET_ERR("RequestThread: Unable to remove triggers "
4493 "(capture request %d, HAL device: %s (%d)",
4494 triggerFailedRequest.halRequest.frame_number, strerror(-res), res);
4495 cleanUpFailedRequests(/*sendRequestError*/ false);
4496 return false;
4497 }
4498
4499 if (res != OK) {
4500 // Should only get a failure here for malformed requests or device-level
4501 // errors, so consider all errors fatal. Bad metadata failures should
4502 // come through notify.
4503 SET_ERR("RequestThread: Unable to submit capture request %d to HAL device: %s (%d)",
4504 mNextRequests[numRequestProcessed].halRequest.frame_number,
4505 strerror(-res), res);
4506 cleanUpFailedRequests(/*sendRequestError*/ false);
4507 return false;
4508 }
4509 return true;
4510}
4511
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07004512nsecs_t Camera3Device::RequestThread::calculateMaxExpectedDuration(const camera_metadata_t *request) {
4513 nsecs_t maxExpectedDuration = kDefaultExpectedDuration;
4514 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
4515 find_camera_metadata_ro_entry(request,
4516 ANDROID_CONTROL_AE_MODE,
4517 &e);
4518 if (e.count == 0) return maxExpectedDuration;
4519
4520 switch (e.data.u8[0]) {
4521 case ANDROID_CONTROL_AE_MODE_OFF:
4522 find_camera_metadata_ro_entry(request,
4523 ANDROID_SENSOR_EXPOSURE_TIME,
4524 &e);
4525 if (e.count > 0) {
4526 maxExpectedDuration = e.data.i64[0];
4527 }
4528 find_camera_metadata_ro_entry(request,
4529 ANDROID_SENSOR_FRAME_DURATION,
4530 &e);
4531 if (e.count > 0) {
4532 maxExpectedDuration = std::max(e.data.i64[0], maxExpectedDuration);
4533 }
4534 break;
4535 default:
4536 find_camera_metadata_ro_entry(request,
4537 ANDROID_CONTROL_AE_TARGET_FPS_RANGE,
4538 &e);
4539 if (e.count > 1) {
4540 maxExpectedDuration = 1e9 / e.data.u8[0];
4541 }
4542 break;
4543 }
4544
4545 return maxExpectedDuration;
4546}
4547
Emilian Peeva14b4dd2018-05-15 11:00:31 +01004548bool Camera3Device::RequestThread::skipHFRTargetFPSUpdate(int32_t tag,
4549 const camera_metadata_ro_entry_t& newEntry, const camera_metadata_entry_t& currentEntry) {
4550 if (mConstrainedMode && (ANDROID_CONTROL_AE_TARGET_FPS_RANGE == tag) &&
4551 (newEntry.count == currentEntry.count) && (currentEntry.count == 2) &&
4552 (currentEntry.data.i32[1] == newEntry.data.i32[1])) {
4553 return true;
4554 }
4555
4556 return false;
4557}
4558
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004559void Camera3Device::RequestThread::updateNextRequest(NextRequest& nextRequest) {
4560 // Update the latest request sent to HAL
Shuzhen Wang83bff122020-11-20 15:51:39 -08004561 camera_capture_request_t& halRequest = nextRequest.halRequest;
4562 if (halRequest.settings != NULL) { // Don't update if they were unchanged
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004563 Mutex::Autolock al(mLatestRequestMutex);
4564
Shuzhen Wang83bff122020-11-20 15:51:39 -08004565 camera_metadata_t* cloned = clone_camera_metadata(halRequest.settings);
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004566 mLatestRequest.acquire(cloned);
4567
4568 mLatestPhysicalRequest.clear();
Shuzhen Wang83bff122020-11-20 15:51:39 -08004569 for (uint32_t i = 0; i < halRequest.num_physcam_settings; i++) {
4570 cloned = clone_camera_metadata(halRequest.physcam_settings[i]);
4571 mLatestPhysicalRequest.emplace(halRequest.physcam_id[i],
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004572 CameraMetadata(cloned));
4573 }
4574
4575 sp<Camera3Device> parent = mParent.promote();
4576 if (parent != NULL) {
4577 parent->monitorMetadata(TagMonitor::REQUEST,
Shuzhen Wang83bff122020-11-20 15:51:39 -08004578 halRequest.frame_number,
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004579 0, mLatestRequest, mLatestPhysicalRequest);
4580 }
4581 }
4582
Shuzhen Wang83bff122020-11-20 15:51:39 -08004583 if (halRequest.settings != NULL) {
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004584 nextRequest.captureRequest->mSettingsList.begin()->metadata.unlock(
Shuzhen Wang83bff122020-11-20 15:51:39 -08004585 halRequest.settings);
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004586 }
4587
Shuzhen Wang83bff122020-11-20 15:51:39 -08004588 cleanupPhysicalSettings(nextRequest.captureRequest, &halRequest);
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004589}
4590
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004591bool Camera3Device::RequestThread::updateSessionParameters(const CameraMetadata& settings) {
4592 ATRACE_CALL();
4593 bool updatesDetected = false;
4594
Emilian Peev4ec17882019-01-24 17:16:58 -08004595 CameraMetadata updatedParams(mLatestSessionParams);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004596 for (auto tag : mSessionParamKeys) {
4597 camera_metadata_ro_entry entry = settings.find(tag);
Emilian Peev4ec17882019-01-24 17:16:58 -08004598 camera_metadata_entry lastEntry = updatedParams.find(tag);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004599
4600 if (entry.count > 0) {
4601 bool isDifferent = false;
4602 if (lastEntry.count > 0) {
4603 // Have a last value, compare to see if changed
4604 if (lastEntry.type == entry.type &&
4605 lastEntry.count == entry.count) {
4606 // Same type and count, compare values
4607 size_t bytesPerValue = camera_metadata_type_size[lastEntry.type];
4608 size_t entryBytes = bytesPerValue * lastEntry.count;
4609 int cmp = memcmp(entry.data.u8, lastEntry.data.u8, entryBytes);
4610 if (cmp != 0) {
4611 isDifferent = true;
4612 }
4613 } else {
4614 // Count or type has changed
4615 isDifferent = true;
4616 }
4617 } else {
4618 // No last entry, so always consider to be different
4619 isDifferent = true;
4620 }
4621
4622 if (isDifferent) {
4623 ALOGV("%s: Session parameter tag id %d changed", __FUNCTION__, tag);
Emilian Peeva14b4dd2018-05-15 11:00:31 +01004624 if (!skipHFRTargetFPSUpdate(tag, entry, lastEntry)) {
4625 updatesDetected = true;
4626 }
Emilian Peev4ec17882019-01-24 17:16:58 -08004627 updatedParams.update(entry);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004628 }
4629 } else if (lastEntry.count > 0) {
4630 // Value has been removed
4631 ALOGV("%s: Session parameter tag id %d removed", __FUNCTION__, tag);
Emilian Peev4ec17882019-01-24 17:16:58 -08004632 updatedParams.erase(tag);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004633 updatesDetected = true;
4634 }
4635 }
4636
Emilian Peev4ec17882019-01-24 17:16:58 -08004637 bool reconfigureRequired;
4638 if (updatesDetected) {
4639 reconfigureRequired = mInterface->isReconfigurationRequired(mLatestSessionParams,
4640 updatedParams);
4641 mLatestSessionParams = updatedParams;
4642 } else {
4643 reconfigureRequired = false;
4644 }
4645
4646 return reconfigureRequired;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004647}
4648
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004649bool Camera3Device::RequestThread::threadLoop() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004650 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004651 status_t res;
Jayant Chowdhary37eca242019-11-18 08:55:56 -08004652 // Any function called from threadLoop() must not hold mInterfaceLock since
4653 // it could lead to deadlocks (disconnect() -> hold mInterfaceMutex -> wait for request thread
4654 // to finish -> request thread waits on mInterfaceMutex) http://b/143513518
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004655
4656 // Handle paused state.
4657 if (waitIfPaused()) {
4658 return true;
4659 }
4660
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004661 // Wait for the next batch of requests.
4662 waitForNextRequestBatch();
4663 if (mNextRequests.size() == 0) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004664 return true;
4665 }
4666
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004667 // Get the latest request ID, if any
4668 int latestRequestId;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004669 camera_metadata_entry_t requestIdEntry = mNextRequests[mNextRequests.size() - 1].
Emilian Peevaebbe412018-01-15 13:53:24 +00004670 captureRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_ID);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004671 if (requestIdEntry.count > 0) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004672 latestRequestId = requestIdEntry.data.i32[0];
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004673 } else {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004674 ALOGW("%s: Did not have android.request.id set in the request.", __FUNCTION__);
4675 latestRequestId = NAME_NOT_FOUND;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004676 }
4677
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004678 // 'mNextRequests' will at this point contain either a set of HFR batched requests
4679 // or a single request from streaming or burst. In either case the first element
4680 // should contain the latest camera settings that we need to check for any session
4681 // parameter updates.
Emilian Peevaebbe412018-01-15 13:53:24 +00004682 if (updateSessionParameters(mNextRequests[0].captureRequest->mSettingsList.begin()->metadata)) {
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004683 res = OK;
4684
4685 //Input stream buffers are already acquired at this point so an input stream
4686 //will not be able to move to idle state unless we force it.
4687 if (mNextRequests[0].captureRequest->mInputStream != nullptr) {
4688 res = mNextRequests[0].captureRequest->mInputStream->forceToIdle();
4689 if (res != OK) {
4690 ALOGE("%s: Failed to force idle input stream: %d", __FUNCTION__, res);
4691 cleanUpFailedRequests(/*sendRequestError*/ false);
4692 return false;
4693 }
4694 }
4695
4696 if (res == OK) {
Emilian Peev3bead5f2020-05-28 17:29:08 -07004697 sp<Camera3Device> parent = mParent.promote();
4698 if (parent != nullptr) {
4699 mReconfigured |= parent->reconfigureCamera(mLatestSessionParams, mStatusId);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004700 }
Emilian Peev3bead5f2020-05-28 17:29:08 -07004701 setPaused(false);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004702
4703 if (mNextRequests[0].captureRequest->mInputStream != nullptr) {
4704 mNextRequests[0].captureRequest->mInputStream->restoreConfiguredState();
4705 if (res != OK) {
4706 ALOGE("%s: Failed to restore configured input stream: %d", __FUNCTION__, res);
4707 cleanUpFailedRequests(/*sendRequestError*/ false);
4708 return false;
4709 }
4710 }
4711 }
4712 }
4713
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004714 // Prepare a batch of HAL requests and output buffers.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004715 res = prepareHalRequests();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004716 if (res == TIMED_OUT) {
4717 // Not a fatal error if getting output buffers time out.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004718 cleanUpFailedRequests(/*sendRequestError*/ true);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004719 // Check if any stream is abandoned.
4720 checkAndStopRepeatingRequest();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004721 return true;
4722 } else if (res != OK) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004723 cleanUpFailedRequests(/*sendRequestError*/ false);
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004724 return false;
4725 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004726
Zhijun Hecc27e112013-10-03 16:12:43 -07004727 // Inform waitUntilRequestProcessed thread of a new request ID
4728 {
4729 Mutex::Autolock al(mLatestRequestMutex);
4730
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004731 mLatestRequestId = latestRequestId;
Zhijun Hecc27e112013-10-03 16:12:43 -07004732 mLatestRequestSignal.signal();
4733 }
4734
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004735 // Submit a batch of requests to HAL.
4736 // Use flush lock only when submitting multilple requests in a batch.
4737 // TODO: The problem with flush lock is flush() will be blocked by process_capture_request()
4738 // which may take a long time to finish so synchronizing flush() and
4739 // process_capture_request() defeats the purpose of cancelling requests ASAP with flush().
4740 // For now, only synchronize for high speed recording and we should figure something out for
4741 // removing the synchronization.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004742 bool useFlushLock = mNextRequests.size() > 1;
Eino-Ville Talvala17a61ad2013-06-03 16:53:32 -07004743
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004744 if (useFlushLock) {
4745 mFlushLock.lock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004746 }
4747
Zhijun Hef0645c12016-08-02 00:58:11 -07004748 ALOGVV("%s: %d: submitting %zu requests in a batch.", __FUNCTION__, __LINE__,
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004749 mNextRequests.size());
Igor Murashkin1e479c02013-09-06 16:55:14 -07004750
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08004751 sp<Camera3Device> parent = mParent.promote();
4752 if (parent != nullptr) {
4753 parent->mRequestBufferSM.onSubmittingRequest();
4754 }
4755
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004756 bool submitRequestSuccess = false;
Shuzhen Wang686f6442017-06-20 16:16:04 -07004757 nsecs_t tRequestStart = systemTime(SYSTEM_TIME_MONOTONIC);
Yin-Chia Yeh11648852019-05-16 10:42:54 -07004758 submitRequestSuccess = sendRequestsBatch();
4759
Shuzhen Wang686f6442017-06-20 16:16:04 -07004760 nsecs_t tRequestEnd = systemTime(SYSTEM_TIME_MONOTONIC);
4761 mRequestLatency.add(tRequestStart, tRequestEnd);
Igor Murashkin1e479c02013-09-06 16:55:14 -07004762
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004763 if (useFlushLock) {
4764 mFlushLock.unlock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004765 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004766
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004767 // Unset as current request
4768 {
4769 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004770 mNextRequests.clear();
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004771 }
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004772 mRequestSubmittedSignal.signal();
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004773
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004774 return submitRequestSuccess;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004775}
4776
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004777status_t Camera3Device::RequestThread::prepareHalRequests() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004778 ATRACE_CALL();
4779
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07004780 bool batchedRequest = mNextRequests[0].captureRequest->mBatchSize > 1;
Shuzhen Wang4a472662017-02-26 23:29:04 -08004781 for (size_t i = 0; i < mNextRequests.size(); i++) {
4782 auto& nextRequest = mNextRequests.editItemAt(i);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004783 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
Emilian Peevf4816702020-04-03 15:44:51 -07004784 camera_capture_request_t* halRequest = &nextRequest.halRequest;
4785 Vector<camera_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004786
4787 // Prepare a request to HAL
4788 halRequest->frame_number = captureRequest->mResultExtras.frameNumber;
4789
4790 // Insert any queued triggers (before metadata is locked)
4791 status_t res = insertTriggers(captureRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004792 if (res < 0) {
4793 SET_ERR("RequestThread: Unable to insert triggers "
4794 "(capture request %d, HAL device: %s (%d)",
4795 halRequest->frame_number, strerror(-res), res);
4796 return INVALID_OPERATION;
4797 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07004798
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004799 int triggerCount = res;
4800 bool triggersMixedIn = (triggerCount > 0 || mPrevTriggers > 0);
4801 mPrevTriggers = triggerCount;
4802
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004803 bool rotateAndCropChanged = overrideAutoRotateAndCrop(captureRequest);
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004804 bool testPatternChanged = overrideTestPattern(captureRequest);
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004805
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004806 // If the request is the same as last, or we had triggers now or last time or
4807 // changing overrides this time
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004808 bool newRequest =
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004809 (mPrevRequest != captureRequest || triggersMixedIn ||
4810 rotateAndCropChanged || testPatternChanged) &&
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07004811 // Request settings are all the same within one batch, so only treat the first
4812 // request in a batch as new
Zhijun He54c36822018-07-18 09:33:39 -07004813 !(batchedRequest && i > 0);
Emilian Peev00420d22018-02-05 21:33:13 +00004814 if (newRequest) {
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08004815 std::set<std::string> cameraIdsWithZoom;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004816 /**
4817 * HAL workaround:
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004818 * Insert a fake trigger ID if a trigger is set but no trigger ID is
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004819 */
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004820 res = addFakeTriggerIds(captureRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004821 if (res != OK) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004822 SET_ERR("RequestThread: Unable to insert fake trigger IDs "
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004823 "(capture request %d, HAL device: %s (%d)",
4824 halRequest->frame_number, strerror(-res), res);
4825 return INVALID_OPERATION;
4826 }
4827
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07004828 {
4829 // Correct metadata regions for distortion correction if enabled
4830 sp<Camera3Device> parent = mParent.promote();
4831 if (parent != nullptr) {
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -07004832 List<PhysicalCameraSettings>::iterator it;
4833 for (it = captureRequest->mSettingsList.begin();
4834 it != captureRequest->mSettingsList.end(); it++) {
4835 if (parent->mDistortionMappers.find(it->cameraId) ==
4836 parent->mDistortionMappers.end()) {
4837 continue;
4838 }
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07004839
4840 if (!captureRequest->mDistortionCorrectionUpdated) {
4841 res = parent->mDistortionMappers[it->cameraId].correctCaptureRequest(
4842 &(it->metadata));
4843 if (res != OK) {
4844 SET_ERR("RequestThread: Unable to correct capture requests "
4845 "for lens distortion for request %d: %s (%d)",
4846 halRequest->frame_number, strerror(-res), res);
4847 return INVALID_OPERATION;
4848 }
4849 captureRequest->mDistortionCorrectionUpdated = true;
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -07004850 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07004851 }
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08004852
4853 for (it = captureRequest->mSettingsList.begin();
4854 it != captureRequest->mSettingsList.end(); it++) {
4855 if (parent->mZoomRatioMappers.find(it->cameraId) ==
4856 parent->mZoomRatioMappers.end()) {
4857 continue;
4858 }
4859
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07004860 if (!captureRequest->mZoomRatioIs1x) {
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08004861 cameraIdsWithZoom.insert(it->cameraId);
4862 }
4863
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07004864 if (!captureRequest->mZoomRatioUpdated) {
4865 res = parent->mZoomRatioMappers[it->cameraId].updateCaptureRequest(
4866 &(it->metadata));
4867 if (res != OK) {
4868 SET_ERR("RequestThread: Unable to correct capture requests "
4869 "for zoom ratio for request %d: %s (%d)",
4870 halRequest->frame_number, strerror(-res), res);
4871 return INVALID_OPERATION;
4872 }
4873 captureRequest->mZoomRatioUpdated = true;
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08004874 }
4875 }
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07004876 if (captureRequest->mRotateAndCropAuto &&
4877 !captureRequest->mRotationAndCropUpdated) {
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004878 for (it = captureRequest->mSettingsList.begin();
4879 it != captureRequest->mSettingsList.end(); it++) {
4880 auto mapper = parent->mRotateAndCropMappers.find(it->cameraId);
4881 if (mapper != parent->mRotateAndCropMappers.end()) {
4882 res = mapper->second.updateCaptureRequest(&(it->metadata));
4883 if (res != OK) {
4884 SET_ERR("RequestThread: Unable to correct capture requests "
4885 "for rotate-and-crop for request %d: %s (%d)",
4886 halRequest->frame_number, strerror(-res), res);
4887 return INVALID_OPERATION;
4888 }
4889 }
4890 }
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07004891 captureRequest->mRotationAndCropUpdated = true;
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004892 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07004893 }
4894 }
4895
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004896 /**
4897 * The request should be presorted so accesses in HAL
4898 * are O(logn). Sidenote, sorting a sorted metadata is nop.
4899 */
Emilian Peevaebbe412018-01-15 13:53:24 +00004900 captureRequest->mSettingsList.begin()->metadata.sort();
4901 halRequest->settings = captureRequest->mSettingsList.begin()->metadata.getAndLock();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004902 mPrevRequest = captureRequest;
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08004903 mPrevCameraIdsWithZoom = cameraIdsWithZoom;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004904 ALOGVV("%s: Request settings are NEW", __FUNCTION__);
4905
4906 IF_ALOGV() {
4907 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
4908 find_camera_metadata_ro_entry(
4909 halRequest->settings,
4910 ANDROID_CONTROL_AF_TRIGGER,
4911 &e
4912 );
4913 if (e.count > 0) {
4914 ALOGV("%s: Request (frame num %d) had AF trigger 0x%x",
4915 __FUNCTION__,
4916 halRequest->frame_number,
4917 e.data.u8[0]);
4918 }
4919 }
4920 } else {
4921 // leave request.settings NULL to indicate 'reuse latest given'
4922 ALOGVV("%s: Request settings are REUSED",
4923 __FUNCTION__);
4924 }
4925
Emilian Peevaebbe412018-01-15 13:53:24 +00004926 if (captureRequest->mSettingsList.size() > 1) {
4927 halRequest->num_physcam_settings = captureRequest->mSettingsList.size() - 1;
4928 halRequest->physcam_id = new const char* [halRequest->num_physcam_settings];
Emilian Peev00420d22018-02-05 21:33:13 +00004929 if (newRequest) {
4930 halRequest->physcam_settings =
4931 new const camera_metadata* [halRequest->num_physcam_settings];
4932 } else {
4933 halRequest->physcam_settings = nullptr;
4934 }
Emilian Peevaebbe412018-01-15 13:53:24 +00004935 auto it = ++captureRequest->mSettingsList.begin();
4936 size_t i = 0;
4937 for (; it != captureRequest->mSettingsList.end(); it++, i++) {
4938 halRequest->physcam_id[i] = it->cameraId.c_str();
Emilian Peev00420d22018-02-05 21:33:13 +00004939 if (newRequest) {
4940 it->metadata.sort();
4941 halRequest->physcam_settings[i] = it->metadata.getAndLock();
4942 }
Emilian Peevaebbe412018-01-15 13:53:24 +00004943 }
4944 }
4945
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004946 uint32_t totalNumBuffers = 0;
4947
4948 // Fill in buffers
4949 if (captureRequest->mInputStream != NULL) {
4950 halRequest->input_buffer = &captureRequest->mInputBuffer;
Shuzhen Wang83bff122020-11-20 15:51:39 -08004951
4952 halRequest->input_width = captureRequest->mInputBufferSize.width;
4953 halRequest->input_height = captureRequest->mInputBufferSize.height;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004954 totalNumBuffers += 1;
4955 } else {
4956 halRequest->input_buffer = NULL;
4957 }
4958
Emilian Peevf4816702020-04-03 15:44:51 -07004959 outputBuffers->insertAt(camera_stream_buffer_t(), 0,
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004960 captureRequest->mOutputStreams.size());
4961 halRequest->output_buffers = outputBuffers->array();
Shuzhen Wang99080502021-03-07 21:08:20 -08004962 std::set<std::set<String8>> requestedPhysicalCameras;
Yin-Chia Yehb3a80b12018-09-04 12:13:05 -07004963
4964 sp<Camera3Device> parent = mParent.promote();
4965 if (parent == NULL) {
4966 // Should not happen, and nowhere to send errors to, so just log it
4967 CLOGE("RequestThread: Parent is gone");
4968 return INVALID_OPERATION;
4969 }
4970 nsecs_t waitDuration = kBaseGetBufferWait + parent->getExpectedInFlightDuration();
4971
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07004972 SurfaceMap uniqueSurfaceIdMap;
Shuzhen Wang4a472662017-02-26 23:29:04 -08004973 for (size_t j = 0; j < captureRequest->mOutputStreams.size(); j++) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07004974 sp<Camera3OutputStreamInterface> outputStream =
4975 captureRequest->mOutputStreams.editItemAt(j);
4976 int streamId = outputStream->getId();
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07004977
4978 // Prepare video buffers for high speed recording on the first video request.
4979 if (mPrepareVideoStream && outputStream->isVideoStream()) {
4980 // Only try to prepare video stream on the first video request.
4981 mPrepareVideoStream = false;
4982
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07004983 res = outputStream->startPrepare(Camera3StreamInterface::ALLOCATE_PIPELINE_MAX,
4984 false /*blockRequest*/);
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07004985 while (res == NOT_ENOUGH_DATA) {
4986 res = outputStream->prepareNextBuffer();
4987 }
4988 if (res != OK) {
4989 ALOGW("%s: Preparing video buffers for high speed failed: %s (%d)",
4990 __FUNCTION__, strerror(-res), res);
4991 outputStream->cancelPrepare();
4992 }
4993 }
4994
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07004995 std::vector<size_t> uniqueSurfaceIds;
4996 res = outputStream->getUniqueSurfaceIds(
4997 captureRequest->mOutputSurfaces[streamId],
4998 &uniqueSurfaceIds);
4999 // INVALID_OPERATION is normal output for streams not supporting surfaceIds
5000 if (res != OK && res != INVALID_OPERATION) {
5001 ALOGE("%s: failed to query stream %d unique surface IDs",
5002 __FUNCTION__, streamId);
5003 return res;
5004 }
5005 if (res == OK) {
5006 uniqueSurfaceIdMap.insert({streamId, std::move(uniqueSurfaceIds)});
5007 }
5008
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07005009 if (mUseHalBufManager) {
Yin-Chia Yeh110342b2018-11-19 11:47:46 -08005010 if (outputStream->isAbandoned()) {
Yin-Chia Yeha1b56c82019-03-27 15:50:39 -07005011 ALOGV("%s: stream %d is abandoned, skipping request", __FUNCTION__, streamId);
Yin-Chia Yeh110342b2018-11-19 11:47:46 -08005012 return TIMED_OUT;
5013 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07005014 // HAL will request buffer through requestStreamBuffer API
Emilian Peevf4816702020-04-03 15:44:51 -07005015 camera_stream_buffer_t& buffer = outputBuffers->editItemAt(j);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07005016 buffer.stream = outputStream->asHalStream();
5017 buffer.buffer = nullptr;
Emilian Peevf4816702020-04-03 15:44:51 -07005018 buffer.status = CAMERA_BUFFER_STATUS_OK;
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07005019 buffer.acquire_fence = -1;
5020 buffer.release_fence = -1;
Emilian Peevf0348ae2021-01-13 13:39:45 -08005021 // Mark the output stream as unpreparable to block clients from calling
5022 // 'prepare' after this request reaches CameraHal and before the respective
5023 // buffers are requested.
5024 outputStream->markUnpreparable();
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07005025 } else {
5026 res = outputStream->getBuffer(&outputBuffers->editItemAt(j),
5027 waitDuration,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005028 captureRequest->mOutputSurfaces[streamId]);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07005029 if (res != OK) {
5030 // Can't get output buffer from gralloc queue - this could be due to
5031 // abandoned queue or other consumer misbehavior, so not a fatal
5032 // error
Yin-Chia Yeha1b56c82019-03-27 15:50:39 -07005033 ALOGV("RequestThread: Can't get output buffer, skipping request:"
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07005034 " %s (%d)", strerror(-res), res);
5035
5036 return TIMED_OUT;
5037 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005038 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08005039
5040 {
5041 sp<Camera3Device> parent = mParent.promote();
5042 if (parent != nullptr) {
5043 const String8& streamCameraId = outputStream->getPhysicalCameraId();
5044 for (const auto& settings : captureRequest->mSettingsList) {
5045 if ((streamCameraId.isEmpty() &&
5046 parent->getId() == settings.cameraId.c_str()) ||
5047 streamCameraId == settings.cameraId.c_str()) {
5048 outputStream->fireBufferRequestForFrameNumber(
5049 captureRequest->mResultExtras.frameNumber,
5050 settings.metadata);
5051 }
5052 }
5053 }
5054 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07005055
Shuzhen Wang5c22c152017-12-31 17:12:25 -08005056 String8 physicalCameraId = outputStream->getPhysicalCameraId();
Shuzhen Wang99080502021-03-07 21:08:20 -08005057 int32_t streamGroupId = outputStream->getHalStreamGroupId();
5058 if (streamGroupId != -1 && mGroupIdPhysicalCameraMap.count(streamGroupId) == 1) {
5059 requestedPhysicalCameras.insert(mGroupIdPhysicalCameraMap[streamGroupId]);
5060 } else if (!physicalCameraId.isEmpty()) {
5061 requestedPhysicalCameras.insert(std::set<String8>({physicalCameraId}));
Shuzhen Wang5c22c152017-12-31 17:12:25 -08005062 }
5063 halRequest->num_output_buffers++;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005064 }
5065 totalNumBuffers += halRequest->num_output_buffers;
5066
5067 // Log request in the in-flight queue
Shuzhen Wang4a472662017-02-26 23:29:04 -08005068 // If this request list is for constrained high speed recording (not
5069 // preview), and the current request is not the last one in the batch,
5070 // do not send callback to the app.
5071 bool hasCallback = true;
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07005072 if (batchedRequest && i != mNextRequests.size()-1) {
Shuzhen Wang4a472662017-02-26 23:29:04 -08005073 hasCallback = false;
5074 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01005075 bool isStillCapture = false;
Shuzhen Wang26abaf42018-08-28 15:41:20 -07005076 bool isZslCapture = false;
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08005077 const camera_metadata_t* settings = halRequest->settings;
5078 bool shouldUnlockSettings = false;
5079 if (settings == nullptr) {
5080 shouldUnlockSettings = true;
5081 settings = captureRequest->mSettingsList.begin()->metadata.getAndLock();
5082 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01005083 if (!mNextRequests[0].captureRequest->mSettingsList.begin()->metadata.isEmpty()) {
5084 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08005085 find_camera_metadata_ro_entry(settings, ANDROID_CONTROL_CAPTURE_INTENT, &e);
Emilian Peev9dd21f42018-08-03 13:39:29 +01005086 if ((e.count > 0) && (e.data.u8[0] == ANDROID_CONTROL_CAPTURE_INTENT_STILL_CAPTURE)) {
5087 isStillCapture = true;
5088 ATRACE_ASYNC_BEGIN("still capture", mNextRequests[i].halRequest.frame_number);
5089 }
Shuzhen Wang26abaf42018-08-28 15:41:20 -07005090
Emilian Peevaf8416e2021-02-04 17:52:43 -08005091 e = camera_metadata_ro_entry_t();
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08005092 find_camera_metadata_ro_entry(settings, ANDROID_CONTROL_ENABLE_ZSL, &e);
Shuzhen Wang26abaf42018-08-28 15:41:20 -07005093 if ((e.count > 0) && (e.data.u8[0] == ANDROID_CONTROL_ENABLE_ZSL_TRUE)) {
5094 isZslCapture = true;
5095 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01005096 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005097 res = parent->registerInFlight(halRequest->frame_number,
5098 totalNumBuffers, captureRequest->mResultExtras,
5099 /*hasInput*/halRequest->input_buffer != NULL,
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07005100 hasCallback,
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08005101 calculateMaxExpectedDuration(settings),
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005102 requestedPhysicalCameras, isStillCapture, isZslCapture,
5103 captureRequest->mRotateAndCropAuto, mPrevCameraIdsWithZoom,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005104 (mUseHalBufManager) ? uniqueSurfaceIdMap :
Shuzhen Wang316781a2020-08-18 18:11:01 -07005105 SurfaceMap{}, captureRequest->mRequestTimeNs);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005106 ALOGVV("%s: registered in flight requestId = %" PRId32 ", frameNumber = %" PRId64
5107 ", burstId = %" PRId32 ".",
5108 __FUNCTION__,
5109 captureRequest->mResultExtras.requestId, captureRequest->mResultExtras.frameNumber,
5110 captureRequest->mResultExtras.burstId);
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08005111
5112 if (shouldUnlockSettings) {
5113 captureRequest->mSettingsList.begin()->metadata.unlock(settings);
5114 }
5115
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005116 if (res != OK) {
5117 SET_ERR("RequestThread: Unable to register new in-flight request:"
5118 " %s (%d)", strerror(-res), res);
5119 return INVALID_OPERATION;
5120 }
5121 }
5122
5123 return OK;
5124}
5125
Igor Murashkin1e479c02013-09-06 16:55:14 -07005126CameraMetadata Camera3Device::RequestThread::getLatestRequest() const {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005127 ATRACE_CALL();
Igor Murashkin1e479c02013-09-06 16:55:14 -07005128 Mutex::Autolock al(mLatestRequestMutex);
5129
5130 ALOGV("RequestThread::%s", __FUNCTION__);
5131
5132 return mLatestRequest;
5133}
5134
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005135bool Camera3Device::RequestThread::isStreamPending(
5136 sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005137 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005138 Mutex::Autolock l(mRequestLock);
5139
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005140 for (const auto& nextRequest : mNextRequests) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005141 if (!nextRequest.submitted) {
5142 for (const auto& s : nextRequest.captureRequest->mOutputStreams) {
5143 if (stream == s) return true;
5144 }
5145 if (stream == nextRequest.captureRequest->mInputStream) return true;
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07005146 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07005147 }
5148
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005149 for (const auto& request : mRequestQueue) {
5150 for (const auto& s : request->mOutputStreams) {
5151 if (stream == s) return true;
5152 }
5153 if (stream == request->mInputStream) return true;
5154 }
5155
5156 for (const auto& request : mRepeatingRequests) {
5157 for (const auto& s : request->mOutputStreams) {
5158 if (stream == s) return true;
5159 }
5160 if (stream == request->mInputStream) return true;
5161 }
5162
5163 return false;
5164}
Jianing Weicb0652e2014-03-12 18:29:36 -07005165
Emilian Peev40ead602017-09-26 15:46:36 +01005166bool Camera3Device::RequestThread::isOutputSurfacePending(int streamId, size_t surfaceId) {
5167 ATRACE_CALL();
5168 Mutex::Autolock l(mRequestLock);
5169
5170 for (const auto& nextRequest : mNextRequests) {
5171 for (const auto& s : nextRequest.captureRequest->mOutputSurfaces) {
5172 if (s.first == streamId) {
5173 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
5174 if (it != s.second.end()) {
5175 return true;
5176 }
5177 }
5178 }
5179 }
5180
5181 for (const auto& request : mRequestQueue) {
5182 for (const auto& s : request->mOutputSurfaces) {
5183 if (s.first == streamId) {
5184 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
5185 if (it != s.second.end()) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005186 return true;
Emilian Peev40ead602017-09-26 15:46:36 +01005187 }
5188 }
5189 }
5190 }
5191
5192 for (const auto& request : mRepeatingRequests) {
5193 for (const auto& s : request->mOutputSurfaces) {
5194 if (s.first == streamId) {
5195 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
5196 if (it != s.second.end()) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005197 return true;
Emilian Peev40ead602017-09-26 15:46:36 +01005198 }
5199 }
5200 }
5201 }
5202
5203 return false;
5204}
5205
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07005206void Camera3Device::RequestThread::signalPipelineDrain(const std::vector<int>& streamIds) {
5207 if (!mUseHalBufManager) {
5208 ALOGE("%s called for camera device not supporting HAL buffer management", __FUNCTION__);
5209 return;
5210 }
5211
5212 Mutex::Autolock pl(mPauseLock);
5213 if (mPaused) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005214 mInterface->signalPipelineDrain(streamIds);
5215 return;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07005216 }
5217 // If request thread is still busy, wait until paused then notify HAL
5218 mNotifyPipelineDrain = true;
5219 mStreamIdsToBeDrained = streamIds;
5220}
5221
Yin-Chia Yehe52b8fa2020-07-28 00:17:58 -07005222void Camera3Device::RequestThread::resetPipelineDrain() {
5223 Mutex::Autolock pl(mPauseLock);
5224 mNotifyPipelineDrain = false;
5225 mStreamIdsToBeDrained.clear();
5226}
5227
Emilian Peevc0fe54c2020-03-11 14:05:07 -07005228void Camera3Device::RequestThread::clearPreviousRequest() {
5229 Mutex::Autolock l(mRequestLock);
5230 mPrevRequest.clear();
5231}
5232
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005233status_t Camera3Device::RequestThread::switchToOffline(
5234 const std::vector<int32_t>& streamsToKeep,
5235 /*out*/hardware::camera::device::V3_6::CameraOfflineSessionInfo* offlineSessionInfo,
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005236 /*out*/sp<hardware::camera::device::V3_6::ICameraOfflineSession>* offlineSession,
5237 /*out*/camera3::BufferRecords* bufferRecords) {
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005238 Mutex::Autolock l(mRequestLock);
5239 clearRepeatingRequestsLocked(/*lastFrameNumber*/nullptr);
5240
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005241 // Wait until request thread is fully stopped
5242 // TBD: check if request thread is being paused by other APIs (shouldn't be)
5243
5244 // We could also check for mRepeatingRequests.empty(), but the API interface
5245 // is serialized by Camera3Device::mInterfaceLock so no one should be able to submit any
5246 // new requests during the call; hence skip that check.
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005247 bool queueEmpty = mNextRequests.empty() && mRequestQueue.empty();
5248 while (!queueEmpty) {
5249 status_t res = mRequestSubmittedSignal.waitRelative(mRequestLock, kRequestSubmitTimeout);
5250 if (res == TIMED_OUT) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005251 ALOGE("%s: request thread failed to submit one request within timeout!", __FUNCTION__);
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005252 return res;
5253 } else if (res != OK) {
5254 ALOGE("%s: request thread failed to submit a request: %s (%d)!",
5255 __FUNCTION__, strerror(-res), res);
5256 return res;
5257 }
5258 queueEmpty = mNextRequests.empty() && mRequestQueue.empty();
5259 }
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005260
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005261 return mInterface->switchToOffline(
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005262 streamsToKeep, offlineSessionInfo, offlineSession, bufferRecords);
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005263}
5264
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005265status_t Camera3Device::RequestThread::setRotateAndCropAutoBehavior(
5266 camera_metadata_enum_android_scaler_rotate_and_crop_t rotateAndCropValue) {
5267 ATRACE_CALL();
5268 Mutex::Autolock l(mTriggerMutex);
5269 if (rotateAndCropValue == ANDROID_SCALER_ROTATE_AND_CROP_AUTO) {
5270 return BAD_VALUE;
5271 }
5272 mRotateAndCropOverride = rotateAndCropValue;
5273 return OK;
5274}
5275
Eino-Ville Talvala11afe4f2021-05-27 14:45:31 -07005276status_t Camera3Device::RequestThread::setCameraMute(int32_t muteMode) {
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005277 ATRACE_CALL();
5278 Mutex::Autolock l(mTriggerMutex);
Eino-Ville Talvala11afe4f2021-05-27 14:45:31 -07005279 if (muteMode != mCameraMute) {
5280 mCameraMute = muteMode;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005281 mCameraMuteChanged = true;
5282 }
5283 return OK;
5284}
5285
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07005286nsecs_t Camera3Device::getExpectedInFlightDuration() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005287 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005288 std::lock_guard<std::mutex> l(mInFlightLock);
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07005289 return mExpectedInflightDuration > kMinInflightDuration ?
5290 mExpectedInflightDuration : kMinInflightDuration;
5291}
5292
Emilian Peevaebbe412018-01-15 13:53:24 +00005293void Camera3Device::RequestThread::cleanupPhysicalSettings(sp<CaptureRequest> request,
Emilian Peevf4816702020-04-03 15:44:51 -07005294 camera_capture_request_t *halRequest) {
Emilian Peevaebbe412018-01-15 13:53:24 +00005295 if ((request == nullptr) || (halRequest == nullptr)) {
5296 ALOGE("%s: Invalid request!", __FUNCTION__);
5297 return;
5298 }
5299
5300 if (halRequest->num_physcam_settings > 0) {
5301 if (halRequest->physcam_id != nullptr) {
5302 delete [] halRequest->physcam_id;
5303 halRequest->physcam_id = nullptr;
5304 }
5305 if (halRequest->physcam_settings != nullptr) {
5306 auto it = ++(request->mSettingsList.begin());
5307 size_t i = 0;
5308 for (; it != request->mSettingsList.end(); it++, i++) {
5309 it->metadata.unlock(halRequest->physcam_settings[i]);
5310 }
5311 delete [] halRequest->physcam_settings;
5312 halRequest->physcam_settings = nullptr;
5313 }
5314 }
5315}
5316
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005317void Camera3Device::RequestThread::cleanUpFailedRequests(bool sendRequestError) {
5318 if (mNextRequests.empty()) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005319 return;
5320 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005321
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005322 for (auto& nextRequest : mNextRequests) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005323 // Skip the ones that have been submitted successfully.
5324 if (nextRequest.submitted) {
5325 continue;
5326 }
5327
5328 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
Emilian Peevf4816702020-04-03 15:44:51 -07005329 camera_capture_request_t* halRequest = &nextRequest.halRequest;
5330 Vector<camera_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005331
5332 if (halRequest->settings != NULL) {
Emilian Peevaebbe412018-01-15 13:53:24 +00005333 captureRequest->mSettingsList.begin()->metadata.unlock(halRequest->settings);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005334 }
5335
Emilian Peevaebbe412018-01-15 13:53:24 +00005336 cleanupPhysicalSettings(captureRequest, halRequest);
5337
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005338 if (captureRequest->mInputStream != NULL) {
Emilian Peevf4816702020-04-03 15:44:51 -07005339 captureRequest->mInputBuffer.status = CAMERA_BUFFER_STATUS_ERROR;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005340 captureRequest->mInputStream->returnInputBuffer(captureRequest->mInputBuffer);
5341 }
5342
Yin-Chia Yeh21cb47b2019-01-18 15:08:17 -08005343 // No output buffer can be returned when using HAL buffer manager
5344 if (!mUseHalBufManager) {
5345 for (size_t i = 0; i < halRequest->num_output_buffers; i++) {
5346 //Buffers that failed processing could still have
5347 //valid acquire fence.
5348 int acquireFence = (*outputBuffers)[i].acquire_fence;
5349 if (0 <= acquireFence) {
5350 close(acquireFence);
5351 outputBuffers->editItemAt(i).acquire_fence = -1;
5352 }
Emilian Peevf4816702020-04-03 15:44:51 -07005353 outputBuffers->editItemAt(i).status = CAMERA_BUFFER_STATUS_ERROR;
Yin-Chia Yeh21cb47b2019-01-18 15:08:17 -08005354 captureRequest->mOutputStreams.editItemAt(i)->returnBuffer((*outputBuffers)[i], 0,
5355 /*timestampIncreasing*/true, std::vector<size_t> (),
5356 captureRequest->mResultExtras.frameNumber);
Emilian Peevc58cf4c2017-05-11 17:23:41 +01005357 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005358 }
5359
5360 if (sendRequestError) {
5361 Mutex::Autolock l(mRequestLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005362 sp<NotificationListener> listener = mListener.promote();
5363 if (listener != NULL) {
5364 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08005365 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005366 captureRequest->mResultExtras);
5367 }
5368 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07005369
5370 // Remove yet-to-be submitted inflight request from inflightMap
5371 {
5372 sp<Camera3Device> parent = mParent.promote();
5373 if (parent != NULL) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005374 std::lock_guard<std::mutex> l(parent->mInFlightLock);
Shuzhen Wangcadb3302016-11-04 14:17:56 -07005375 ssize_t idx = parent->mInFlightMap.indexOfKey(captureRequest->mResultExtras.frameNumber);
5376 if (idx >= 0) {
5377 ALOGV("%s: Remove inflight request from queue: frameNumber %" PRId64,
5378 __FUNCTION__, captureRequest->mResultExtras.frameNumber);
5379 parent->removeInFlightMapEntryLocked(idx);
5380 }
5381 }
5382 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005383 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07005384
5385 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005386 mNextRequests.clear();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005387}
5388
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005389void Camera3Device::RequestThread::waitForNextRequestBatch() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005390 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005391 // Optimized a bit for the simple steady-state case (single repeating
5392 // request), to avoid putting that request in the queue temporarily.
5393 Mutex::Autolock l(mRequestLock);
5394
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005395 assert(mNextRequests.empty());
5396
5397 NextRequest nextRequest;
5398 nextRequest.captureRequest = waitForNextRequestLocked();
5399 if (nextRequest.captureRequest == nullptr) {
5400 return;
5401 }
5402
Emilian Peevf4816702020-04-03 15:44:51 -07005403 nextRequest.halRequest = camera_capture_request_t();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005404 nextRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005405 mNextRequests.add(nextRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005406
5407 // Wait for additional requests
5408 const size_t batchSize = nextRequest.captureRequest->mBatchSize;
5409
5410 for (size_t i = 1; i < batchSize; i++) {
5411 NextRequest additionalRequest;
5412 additionalRequest.captureRequest = waitForNextRequestLocked();
5413 if (additionalRequest.captureRequest == nullptr) {
5414 break;
5415 }
5416
Emilian Peevf4816702020-04-03 15:44:51 -07005417 additionalRequest.halRequest = camera_capture_request_t();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005418 additionalRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005419 mNextRequests.add(additionalRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005420 }
5421
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005422 if (mNextRequests.size() < batchSize) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08005423 ALOGE("RequestThread: only get %zu out of %zu requests. Skipping requests.",
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005424 mNextRequests.size(), batchSize);
5425 cleanUpFailedRequests(/*sendRequestError*/true);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005426 }
5427
5428 return;
5429}
5430
5431sp<Camera3Device::CaptureRequest>
5432 Camera3Device::RequestThread::waitForNextRequestLocked() {
5433 status_t res;
5434 sp<CaptureRequest> nextRequest;
5435
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005436 while (mRequestQueue.empty()) {
5437 if (!mRepeatingRequests.empty()) {
5438 // Always atomically enqueue all requests in a repeating request
5439 // list. Guarantees a complete in-sequence set of captures to
5440 // application.
5441 const RequestList &requests = mRepeatingRequests;
Shuzhen Wang316781a2020-08-18 18:11:01 -07005442 if (mFirstRepeating) {
5443 mFirstRepeating = false;
5444 } else {
5445 for (auto& request : requests) {
5446 // For repeating requests, override timestamp request using
5447 // the time a request is inserted into the request queue,
5448 // because the original repeating request will have an old
5449 // fixed timestamp.
5450 request->mRequestTimeNs = systemTime();
5451 }
5452 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005453 RequestList::const_iterator firstRequest =
5454 requests.begin();
5455 nextRequest = *firstRequest;
5456 mRequestQueue.insert(mRequestQueue.end(),
5457 ++firstRequest,
5458 requests.end());
5459 // No need to wait any longer
Jianing Weicb0652e2014-03-12 18:29:36 -07005460
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005461 mRepeatingLastFrameNumber = mFrameNumber + requests.size() - 1;
Jianing Weicb0652e2014-03-12 18:29:36 -07005462
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005463 break;
5464 }
5465
5466 res = mRequestSignal.waitRelative(mRequestLock, kRequestTimeout);
5467
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005468 if ((mRequestQueue.empty() && mRepeatingRequests.empty()) ||
5469 exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005470 Mutex::Autolock pl(mPauseLock);
5471 if (mPaused == false) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005472 ALOGV("%s: RequestThread: Going idle", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005473 mPaused = true;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07005474 if (mNotifyPipelineDrain) {
5475 mInterface->signalPipelineDrain(mStreamIdsToBeDrained);
5476 mNotifyPipelineDrain = false;
5477 mStreamIdsToBeDrained.clear();
5478 }
Yin-Chia Yehc300a072019-02-13 14:56:57 -08005479 // Let the tracker know
5480 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5481 if (statusTracker != 0) {
5482 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
5483 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005484 sp<Camera3Device> parent = mParent.promote();
5485 if (parent != nullptr) {
5486 parent->mRequestBufferSM.onRequestThreadPaused();
5487 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005488 }
5489 // Stop waiting for now and let thread management happen
5490 return NULL;
5491 }
5492 }
5493
5494 if (nextRequest == NULL) {
5495 // Don't have a repeating request already in hand, so queue
5496 // must have an entry now.
5497 RequestList::iterator firstRequest =
5498 mRequestQueue.begin();
5499 nextRequest = *firstRequest;
5500 mRequestQueue.erase(firstRequest);
Shuzhen Wang9d066012016-09-30 11:30:20 -07005501 if (mRequestQueue.empty() && !nextRequest->mRepeating) {
5502 sp<NotificationListener> listener = mListener.promote();
5503 if (listener != NULL) {
5504 listener->notifyRequestQueueEmpty();
5505 }
5506 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005507 }
5508
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005509 // In case we've been unpaused by setPaused clearing mDoPause, need to
5510 // update internal pause state (capture/setRepeatingRequest unpause
5511 // directly).
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005512 Mutex::Autolock pl(mPauseLock);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005513 if (mPaused) {
5514 ALOGV("%s: RequestThread: Unpaused", __FUNCTION__);
5515 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5516 if (statusTracker != 0) {
5517 statusTracker->markComponentActive(mStatusId);
5518 }
5519 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005520 mPaused = false;
5521
5522 // Check if we've reconfigured since last time, and reset the preview
5523 // request if so. Can't use 'NULL request == repeat' across configure calls.
5524 if (mReconfigured) {
5525 mPrevRequest.clear();
5526 mReconfigured = false;
5527 }
5528
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005529 if (nextRequest != NULL) {
5530 nextRequest->mResultExtras.frameNumber = mFrameNumber++;
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07005531 nextRequest->mResultExtras.afTriggerId = mCurrentAfTriggerId;
5532 nextRequest->mResultExtras.precaptureTriggerId = mCurrentPreCaptureTriggerId;
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07005533
5534 // Since RequestThread::clear() removes buffers from the input stream,
5535 // get the right buffer here before unlocking mRequestLock
5536 if (nextRequest->mInputStream != NULL) {
Shuzhen Wang83bff122020-11-20 15:51:39 -08005537 res = nextRequest->mInputStream->getInputBuffer(&nextRequest->mInputBuffer,
5538 &nextRequest->mInputBufferSize);
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07005539 if (res != OK) {
5540 // Can't get input buffer from gralloc queue - this could be due to
5541 // disconnected queue or other producer misbehavior, so not a fatal
5542 // error
5543 ALOGE("%s: Can't get input buffer, skipping request:"
5544 " %s (%d)", __FUNCTION__, strerror(-res), res);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005545
5546 sp<NotificationListener> listener = mListener.promote();
5547 if (listener != NULL) {
5548 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08005549 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07005550 nextRequest->mResultExtras);
5551 }
5552 return NULL;
5553 }
5554 }
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005555 }
Chien-Yu Chend196d612015-06-22 19:49:01 -07005556
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005557 return nextRequest;
5558}
5559
5560bool Camera3Device::RequestThread::waitIfPaused() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005561 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005562 status_t res;
5563 Mutex::Autolock l(mPauseLock);
5564 while (mDoPause) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005565 if (mPaused == false) {
5566 mPaused = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005567 ALOGV("%s: RequestThread: Paused", __FUNCTION__);
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07005568 if (mNotifyPipelineDrain) {
5569 mInterface->signalPipelineDrain(mStreamIdsToBeDrained);
5570 mNotifyPipelineDrain = false;
5571 mStreamIdsToBeDrained.clear();
5572 }
Yin-Chia Yehc300a072019-02-13 14:56:57 -08005573 // Let the tracker know
5574 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5575 if (statusTracker != 0) {
5576 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
5577 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005578 sp<Camera3Device> parent = mParent.promote();
5579 if (parent != nullptr) {
5580 parent->mRequestBufferSM.onRequestThreadPaused();
5581 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005582 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005583
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005584 res = mDoPauseSignal.waitRelative(mPauseLock, kRequestTimeout);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005585 if (res == TIMED_OUT || exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005586 return true;
5587 }
5588 }
5589 // We don't set mPaused to false here, because waitForNextRequest needs
5590 // to further manage the paused state in case of starvation.
5591 return false;
5592}
5593
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005594void Camera3Device::RequestThread::unpauseForNewRequests() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005595 ATRACE_CALL();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005596 // With work to do, mark thread as unpaused.
5597 // If paused by request (setPaused), don't resume, to avoid
5598 // extra signaling/waiting overhead to waitUntilPaused
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005599 mRequestSignal.signal();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005600 Mutex::Autolock p(mPauseLock);
5601 if (!mDoPause) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005602 ALOGV("%s: RequestThread: Going active", __FUNCTION__);
5603 if (mPaused) {
5604 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5605 if (statusTracker != 0) {
5606 statusTracker->markComponentActive(mStatusId);
5607 }
5608 }
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005609 mPaused = false;
5610 }
5611}
5612
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07005613void Camera3Device::RequestThread::setErrorState(const char *fmt, ...) {
5614 sp<Camera3Device> parent = mParent.promote();
5615 if (parent != NULL) {
5616 va_list args;
5617 va_start(args, fmt);
5618
5619 parent->setErrorStateV(fmt, args);
5620
5621 va_end(args);
5622 }
5623}
5624
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005625status_t Camera3Device::RequestThread::insertTriggers(
5626 const sp<CaptureRequest> &request) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005627 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005628 Mutex::Autolock al(mTriggerMutex);
5629
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07005630 sp<Camera3Device> parent = mParent.promote();
5631 if (parent == NULL) {
5632 CLOGE("RequestThread: Parent is gone");
5633 return DEAD_OBJECT;
5634 }
5635
Emilian Peevaebbe412018-01-15 13:53:24 +00005636 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005637 size_t count = mTriggerMap.size();
5638
5639 for (size_t i = 0; i < count; ++i) {
5640 RequestTrigger trigger = mTriggerMap.valueAt(i);
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005641 uint32_t tag = trigger.metadataTag;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07005642
5643 if (tag == ANDROID_CONTROL_AF_TRIGGER_ID || tag == ANDROID_CONTROL_AE_PRECAPTURE_ID) {
5644 bool isAeTrigger = (trigger.metadataTag == ANDROID_CONTROL_AE_PRECAPTURE_ID);
5645 uint32_t triggerId = static_cast<uint32_t>(trigger.entryValue);
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07005646 if (isAeTrigger) {
5647 request->mResultExtras.precaptureTriggerId = triggerId;
5648 mCurrentPreCaptureTriggerId = triggerId;
5649 } else {
5650 request->mResultExtras.afTriggerId = triggerId;
5651 mCurrentAfTriggerId = triggerId;
5652 }
Emilian Peev7e25e5e2017-04-07 15:48:49 +01005653 continue;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07005654 }
5655
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005656 camera_metadata_entry entry = metadata.find(tag);
5657
5658 if (entry.count > 0) {
5659 /**
5660 * Already has an entry for this trigger in the request.
5661 * Rewrite it with our requested trigger value.
5662 */
5663 RequestTrigger oldTrigger = trigger;
5664
5665 oldTrigger.entryValue = entry.data.u8[0];
5666
5667 mTriggerReplacedMap.add(tag, oldTrigger);
5668 } else {
5669 /**
5670 * More typical, no trigger entry, so we just add it
5671 */
5672 mTriggerRemovedMap.add(tag, trigger);
5673 }
5674
5675 status_t res;
5676
5677 switch (trigger.getTagType()) {
5678 case TYPE_BYTE: {
5679 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
5680 res = metadata.update(tag,
5681 &entryValue,
5682 /*count*/1);
5683 break;
5684 }
5685 case TYPE_INT32:
5686 res = metadata.update(tag,
5687 &trigger.entryValue,
5688 /*count*/1);
5689 break;
5690 default:
5691 ALOGE("%s: Type not supported: 0x%x",
5692 __FUNCTION__,
5693 trigger.getTagType());
5694 return INVALID_OPERATION;
5695 }
5696
5697 if (res != OK) {
5698 ALOGE("%s: Failed to update request metadata with trigger tag %s"
5699 ", value %d", __FUNCTION__, trigger.getTagName(),
5700 trigger.entryValue);
5701 return res;
5702 }
5703
5704 ALOGV("%s: Mixed in trigger %s, value %d", __FUNCTION__,
5705 trigger.getTagName(),
5706 trigger.entryValue);
5707 }
5708
5709 mTriggerMap.clear();
5710
5711 return count;
5712}
5713
5714status_t Camera3Device::RequestThread::removeTriggers(
5715 const sp<CaptureRequest> &request) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005716 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005717 Mutex::Autolock al(mTriggerMutex);
5718
Emilian Peevaebbe412018-01-15 13:53:24 +00005719 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005720
5721 /**
5722 * Replace all old entries with their old values.
5723 */
5724 for (size_t i = 0; i < mTriggerReplacedMap.size(); ++i) {
5725 RequestTrigger trigger = mTriggerReplacedMap.valueAt(i);
5726
5727 status_t res;
5728
5729 uint32_t tag = trigger.metadataTag;
5730 switch (trigger.getTagType()) {
5731 case TYPE_BYTE: {
5732 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
5733 res = metadata.update(tag,
5734 &entryValue,
5735 /*count*/1);
5736 break;
5737 }
5738 case TYPE_INT32:
5739 res = metadata.update(tag,
5740 &trigger.entryValue,
5741 /*count*/1);
5742 break;
5743 default:
5744 ALOGE("%s: Type not supported: 0x%x",
5745 __FUNCTION__,
5746 trigger.getTagType());
5747 return INVALID_OPERATION;
5748 }
5749
5750 if (res != OK) {
5751 ALOGE("%s: Failed to restore request metadata with trigger tag %s"
5752 ", trigger value %d", __FUNCTION__,
5753 trigger.getTagName(), trigger.entryValue);
5754 return res;
5755 }
5756 }
5757 mTriggerReplacedMap.clear();
5758
5759 /**
5760 * Remove all new entries.
5761 */
5762 for (size_t i = 0; i < mTriggerRemovedMap.size(); ++i) {
5763 RequestTrigger trigger = mTriggerRemovedMap.valueAt(i);
5764 status_t res = metadata.erase(trigger.metadataTag);
5765
5766 if (res != OK) {
5767 ALOGE("%s: Failed to erase metadata with trigger tag %s"
5768 ", trigger value %d", __FUNCTION__,
5769 trigger.getTagName(), trigger.entryValue);
5770 return res;
5771 }
5772 }
5773 mTriggerRemovedMap.clear();
5774
5775 return OK;
5776}
5777
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04005778status_t Camera3Device::RequestThread::addFakeTriggerIds(
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005779 const sp<CaptureRequest> &request) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08005780 // Trigger ID 0 had special meaning in the HAL2 spec, so avoid it here
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04005781 static const int32_t fakeTriggerId = 1;
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005782 status_t res;
5783
Emilian Peevaebbe412018-01-15 13:53:24 +00005784 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005785
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04005786 // If AF trigger is active, insert a fake AF trigger ID if none already
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005787 // exists
5788 camera_metadata_entry afTrigger = metadata.find(ANDROID_CONTROL_AF_TRIGGER);
5789 camera_metadata_entry afId = metadata.find(ANDROID_CONTROL_AF_TRIGGER_ID);
5790 if (afTrigger.count > 0 &&
5791 afTrigger.data.u8[0] != ANDROID_CONTROL_AF_TRIGGER_IDLE &&
5792 afId.count == 0) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04005793 res = metadata.update(ANDROID_CONTROL_AF_TRIGGER_ID, &fakeTriggerId, 1);
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005794 if (res != OK) return res;
5795 }
5796
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04005797 // If AE precapture trigger is active, insert a fake precapture trigger ID
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005798 // if none already exists
5799 camera_metadata_entry pcTrigger =
5800 metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER);
5801 camera_metadata_entry pcId = metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_ID);
5802 if (pcTrigger.count > 0 &&
5803 pcTrigger.data.u8[0] != ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_IDLE &&
5804 pcId.count == 0) {
5805 res = metadata.update(ANDROID_CONTROL_AE_PRECAPTURE_ID,
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04005806 &fakeTriggerId, 1);
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005807 if (res != OK) return res;
5808 }
5809
5810 return OK;
5811}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005812
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005813bool Camera3Device::RequestThread::overrideAutoRotateAndCrop(
5814 const sp<CaptureRequest> &request) {
5815 ATRACE_CALL();
5816
5817 if (request->mRotateAndCropAuto) {
5818 Mutex::Autolock l(mTriggerMutex);
5819 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
5820
5821 auto rotateAndCropEntry = metadata.find(ANDROID_SCALER_ROTATE_AND_CROP);
5822 if (rotateAndCropEntry.count > 0) {
5823 if (rotateAndCropEntry.data.u8[0] == mRotateAndCropOverride) {
5824 return false;
5825 } else {
5826 rotateAndCropEntry.data.u8[0] = mRotateAndCropOverride;
5827 return true;
5828 }
5829 } else {
5830 uint8_t rotateAndCrop_u8 = mRotateAndCropOverride;
5831 metadata.update(ANDROID_SCALER_ROTATE_AND_CROP,
5832 &rotateAndCrop_u8, 1);
5833 return true;
5834 }
5835 }
5836 return false;
5837}
5838
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005839bool Camera3Device::RequestThread::overrideTestPattern(
5840 const sp<CaptureRequest> &request) {
5841 ATRACE_CALL();
5842
5843 Mutex::Autolock l(mTriggerMutex);
5844
5845 bool changed = false;
5846
5847 int32_t testPatternMode = request->mOriginalTestPatternMode;
5848 int32_t testPatternData[4] = {
5849 request->mOriginalTestPatternData[0],
5850 request->mOriginalTestPatternData[1],
5851 request->mOriginalTestPatternData[2],
5852 request->mOriginalTestPatternData[3]
5853 };
5854
Eino-Ville Talvala11afe4f2021-05-27 14:45:31 -07005855 if (mCameraMute != ANDROID_SENSOR_TEST_PATTERN_MODE_OFF) {
5856 testPatternMode = mCameraMute;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005857 testPatternData[0] = 0;
5858 testPatternData[1] = 0;
5859 testPatternData[2] = 0;
5860 testPatternData[3] = 0;
5861 }
5862
5863 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
5864
5865 auto testPatternEntry = metadata.find(ANDROID_SENSOR_TEST_PATTERN_MODE);
5866 if (testPatternEntry.count > 0) {
5867 if (testPatternEntry.data.i32[0] != testPatternMode) {
5868 testPatternEntry.data.i32[0] = testPatternMode;
5869 changed = true;
5870 }
5871 } else {
5872 metadata.update(ANDROID_SENSOR_TEST_PATTERN_MODE,
5873 &testPatternMode, 1);
5874 changed = true;
5875 }
5876
5877 auto testPatternColor = metadata.find(ANDROID_SENSOR_TEST_PATTERN_DATA);
5878 if (testPatternColor.count > 0) {
5879 for (size_t i = 0; i < 4; i++) {
5880 if (testPatternColor.data.i32[i] != (int32_t)testPatternData[i]) {
5881 testPatternColor.data.i32[i] = testPatternData[i];
5882 changed = true;
5883 }
5884 }
5885 } else {
5886 metadata.update(ANDROID_SENSOR_TEST_PATTERN_DATA,
5887 (int32_t*)testPatternData, 4);
5888 changed = true;
5889 }
5890
5891 return changed;
5892}
5893
Cliff Wuc2ad9c82021-04-21 00:58:58 +08005894status_t Camera3Device::RequestThread::setHalInterface(
5895 sp<HalInterface> newHalInterface) {
5896 if (newHalInterface.get() == nullptr) {
5897 ALOGE("%s: The newHalInterface does not exist!", __FUNCTION__);
5898 return DEAD_OBJECT;
5899 }
5900
5901 mInterface = newHalInterface;
5902
5903 return OK;
5904}
5905
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005906/**
5907 * PreparerThread inner class methods
5908 */
5909
5910Camera3Device::PreparerThread::PreparerThread() :
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07005911 Thread(/*canCallJava*/false), mListener(nullptr),
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005912 mActive(false), mCancelNow(false), mCurrentMaxCount(0), mCurrentPrepareComplete(false) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005913}
5914
5915Camera3Device::PreparerThread::~PreparerThread() {
5916 Thread::requestExitAndWait();
5917 if (mCurrentStream != nullptr) {
5918 mCurrentStream->cancelPrepare();
5919 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
5920 mCurrentStream.clear();
5921 }
5922 clear();
5923}
5924
Ruben Brunkc78ac262015-08-13 17:58:46 -07005925status_t Camera3Device::PreparerThread::prepare(int maxCount, sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005926 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005927 status_t res;
5928
5929 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005930 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005931
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07005932 res = stream->startPrepare(maxCount, true /*blockRequest*/);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005933 if (res == OK) {
5934 // No preparation needed, fire listener right off
5935 ALOGV("%s: Stream %d already prepared", __FUNCTION__, stream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005936 if (listener != NULL) {
5937 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005938 }
5939 return OK;
5940 } else if (res != NOT_ENOUGH_DATA) {
5941 return res;
5942 }
5943
5944 // Need to prepare, start up thread if necessary
5945 if (!mActive) {
5946 // mRunning will change to false before the thread fully shuts down, so wait to be sure it
5947 // isn't running
5948 Thread::requestExitAndWait();
5949 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
5950 if (res != OK) {
5951 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__, res, strerror(-res));
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005952 if (listener != NULL) {
5953 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005954 }
5955 return res;
5956 }
5957 mCancelNow = false;
5958 mActive = true;
5959 ALOGV("%s: Preparer stream started", __FUNCTION__);
5960 }
5961
5962 // queue up the work
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005963 mPendingStreams.emplace(maxCount, stream);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005964 ALOGV("%s: Stream %d queued for preparing", __FUNCTION__, stream->getId());
5965
5966 return OK;
5967}
5968
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005969void Camera3Device::PreparerThread::pause() {
5970 ATRACE_CALL();
5971
5972 Mutex::Autolock l(mLock);
5973
5974 std::unordered_map<int, sp<camera3::Camera3StreamInterface> > pendingStreams;
5975 pendingStreams.insert(mPendingStreams.begin(), mPendingStreams.end());
5976 sp<camera3::Camera3StreamInterface> currentStream = mCurrentStream;
5977 int currentMaxCount = mCurrentMaxCount;
5978 mPendingStreams.clear();
5979 mCancelNow = true;
5980 while (mActive) {
5981 auto res = mThreadActiveSignal.waitRelative(mLock, kActiveTimeout);
5982 if (res == TIMED_OUT) {
5983 ALOGE("%s: Timed out waiting on prepare thread!", __FUNCTION__);
5984 return;
5985 } else if (res != OK) {
5986 ALOGE("%s: Encountered an error: %d waiting on prepare thread!", __FUNCTION__, res);
5987 return;
5988 }
5989 }
5990
5991 //Check whether the prepare thread was able to complete the current
5992 //stream. In case work is still pending emplace it along with the rest
5993 //of the streams in the pending list.
5994 if (currentStream != nullptr) {
5995 if (!mCurrentPrepareComplete) {
5996 pendingStreams.emplace(currentMaxCount, currentStream);
5997 }
5998 }
5999
6000 mPendingStreams.insert(pendingStreams.begin(), pendingStreams.end());
6001 for (const auto& it : mPendingStreams) {
6002 it.second->cancelPrepare();
6003 }
6004}
6005
6006status_t Camera3Device::PreparerThread::resume() {
6007 ATRACE_CALL();
6008 status_t res;
6009
6010 Mutex::Autolock l(mLock);
6011 sp<NotificationListener> listener = mListener.promote();
6012
6013 if (mActive) {
6014 ALOGE("%s: Trying to resume an already active prepare thread!", __FUNCTION__);
6015 return NO_INIT;
6016 }
6017
6018 auto it = mPendingStreams.begin();
6019 for (; it != mPendingStreams.end();) {
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07006020 res = it->second->startPrepare(it->first, true /*blockRequest*/);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006021 if (res == OK) {
6022 if (listener != NULL) {
6023 listener->notifyPrepared(it->second->getId());
6024 }
6025 it = mPendingStreams.erase(it);
6026 } else if (res != NOT_ENOUGH_DATA) {
6027 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__,
6028 res, strerror(-res));
6029 it = mPendingStreams.erase(it);
6030 } else {
6031 it++;
6032 }
6033 }
6034
6035 if (mPendingStreams.empty()) {
6036 return OK;
6037 }
6038
6039 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
6040 if (res != OK) {
6041 ALOGE("%s: Unable to start preparer stream: %d (%s)",
6042 __FUNCTION__, res, strerror(-res));
6043 return res;
6044 }
6045 mCancelNow = false;
6046 mActive = true;
6047 ALOGV("%s: Preparer stream started", __FUNCTION__);
6048
6049 return OK;
6050}
6051
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006052status_t Camera3Device::PreparerThread::clear() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07006053 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006054 Mutex::Autolock l(mLock);
6055
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006056 for (const auto& it : mPendingStreams) {
6057 it.second->cancelPrepare();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006058 }
6059 mPendingStreams.clear();
6060 mCancelNow = true;
6061
6062 return OK;
6063}
6064
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006065void Camera3Device::PreparerThread::setNotificationListener(wp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07006066 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006067 Mutex::Autolock l(mLock);
6068 mListener = listener;
6069}
6070
6071bool Camera3Device::PreparerThread::threadLoop() {
6072 status_t res;
6073 {
6074 Mutex::Autolock l(mLock);
6075 if (mCurrentStream == nullptr) {
6076 // End thread if done with work
6077 if (mPendingStreams.empty()) {
6078 ALOGV("%s: Preparer stream out of work", __FUNCTION__);
6079 // threadLoop _must not_ re-acquire mLock after it sets mActive to false; would
6080 // cause deadlock with prepare()'s requestExitAndWait triggered by !mActive.
6081 mActive = false;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006082 mThreadActiveSignal.signal();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006083 return false;
6084 }
6085
6086 // Get next stream to prepare
6087 auto it = mPendingStreams.begin();
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006088 mCurrentStream = it->second;
6089 mCurrentMaxCount = it->first;
6090 mCurrentPrepareComplete = false;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006091 mPendingStreams.erase(it);
6092 ATRACE_ASYNC_BEGIN("stream prepare", mCurrentStream->getId());
6093 ALOGV("%s: Preparing stream %d", __FUNCTION__, mCurrentStream->getId());
6094 } else if (mCancelNow) {
6095 mCurrentStream->cancelPrepare();
6096 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
6097 ALOGV("%s: Cancelling stream %d prepare", __FUNCTION__, mCurrentStream->getId());
6098 mCurrentStream.clear();
6099 mCancelNow = false;
6100 return true;
6101 }
6102 }
6103
6104 res = mCurrentStream->prepareNextBuffer();
6105 if (res == NOT_ENOUGH_DATA) return true;
6106 if (res != OK) {
6107 // Something bad happened; try to recover by cancelling prepare and
6108 // signalling listener anyway
6109 ALOGE("%s: Stream %d returned error %d (%s) during prepare", __FUNCTION__,
6110 mCurrentStream->getId(), res, strerror(-res));
6111 mCurrentStream->cancelPrepare();
6112 }
6113
6114 // This stream has finished, notify listener
6115 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006116 sp<NotificationListener> listener = mListener.promote();
6117 if (listener != NULL) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006118 ALOGV("%s: Stream %d prepare done, signaling listener", __FUNCTION__,
6119 mCurrentStream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006120 listener->notifyPrepared(mCurrentStream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006121 }
6122
6123 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
6124 mCurrentStream.clear();
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006125 mCurrentPrepareComplete = true;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006126
6127 return true;
6128}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07006129
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006130status_t Camera3Device::RequestBufferStateMachine::initialize(
6131 sp<camera3::StatusTracker> statusTracker) {
6132 if (statusTracker == nullptr) {
6133 ALOGE("%s: statusTracker is null", __FUNCTION__);
6134 return BAD_VALUE;
6135 }
6136
6137 std::lock_guard<std::mutex> lock(mLock);
6138 mStatusTracker = statusTracker;
Yin-Chia Yeh87b3ec02019-06-03 10:44:39 -07006139 mRequestBufferStatusId = statusTracker->addComponent("BufferRequestSM");
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006140 return OK;
6141}
6142
6143bool Camera3Device::RequestBufferStateMachine::startRequestBuffer() {
6144 std::lock_guard<std::mutex> lock(mLock);
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08006145 if (mStatus == RB_STATUS_READY || mStatus == RB_STATUS_PENDING_STOP) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006146 mRequestBufferOngoing = true;
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08006147 notifyTrackerLocked(/*active*/true);
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006148 return true;
6149 }
6150 return false;
6151}
6152
6153void Camera3Device::RequestBufferStateMachine::endRequestBuffer() {
6154 std::lock_guard<std::mutex> lock(mLock);
6155 if (!mRequestBufferOngoing) {
6156 ALOGE("%s called without a successful startRequestBuffer call first!", __FUNCTION__);
6157 return;
6158 }
6159 mRequestBufferOngoing = false;
6160 if (mStatus == RB_STATUS_PENDING_STOP) {
6161 checkSwitchToStopLocked();
6162 }
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08006163 notifyTrackerLocked(/*active*/false);
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006164}
6165
6166void Camera3Device::RequestBufferStateMachine::onStreamsConfigured() {
6167 std::lock_guard<std::mutex> lock(mLock);
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006168 mSwitchedToOffline = false;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006169 mStatus = RB_STATUS_READY;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006170 return;
6171}
6172
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08006173void Camera3Device::RequestBufferStateMachine::onSubmittingRequest() {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006174 std::lock_guard<std::mutex> lock(mLock);
6175 mRequestThreadPaused = false;
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08006176 // inflight map register actually happens in prepareHalRequest now, but it is close enough
6177 // approximation.
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006178 mInflightMapEmpty = false;
6179 if (mStatus == RB_STATUS_STOPPED) {
6180 mStatus = RB_STATUS_READY;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006181 }
6182 return;
6183}
6184
6185void Camera3Device::RequestBufferStateMachine::onRequestThreadPaused() {
6186 std::lock_guard<std::mutex> lock(mLock);
6187 mRequestThreadPaused = true;
6188 if (mStatus == RB_STATUS_PENDING_STOP) {
6189 checkSwitchToStopLocked();
6190 }
6191 return;
6192}
6193
6194void Camera3Device::RequestBufferStateMachine::onInflightMapEmpty() {
6195 std::lock_guard<std::mutex> lock(mLock);
6196 mInflightMapEmpty = true;
6197 if (mStatus == RB_STATUS_PENDING_STOP) {
6198 checkSwitchToStopLocked();
6199 }
6200 return;
6201}
6202
6203void Camera3Device::RequestBufferStateMachine::onWaitUntilIdle() {
6204 std::lock_guard<std::mutex> lock(mLock);
6205 if (!checkSwitchToStopLocked()) {
6206 mStatus = RB_STATUS_PENDING_STOP;
6207 }
6208 return;
6209}
6210
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006211bool Camera3Device::RequestBufferStateMachine::onSwitchToOfflineSuccess() {
6212 std::lock_guard<std::mutex> lock(mLock);
6213 if (mRequestBufferOngoing) {
6214 ALOGE("%s: HAL must not be requesting buffer after HAL returns switchToOffline!",
6215 __FUNCTION__);
6216 return false;
6217 }
6218 mSwitchedToOffline = true;
6219 mInflightMapEmpty = true;
6220 mRequestThreadPaused = true;
6221 mStatus = RB_STATUS_STOPPED;
6222 return true;
6223}
6224
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006225void Camera3Device::RequestBufferStateMachine::notifyTrackerLocked(bool active) {
6226 sp<StatusTracker> statusTracker = mStatusTracker.promote();
6227 if (statusTracker != nullptr) {
6228 if (active) {
6229 statusTracker->markComponentActive(mRequestBufferStatusId);
6230 } else {
6231 statusTracker->markComponentIdle(mRequestBufferStatusId, Fence::NO_FENCE);
6232 }
6233 }
6234}
6235
6236bool Camera3Device::RequestBufferStateMachine::checkSwitchToStopLocked() {
6237 if (mInflightMapEmpty && mRequestThreadPaused && !mRequestBufferOngoing) {
6238 mStatus = RB_STATUS_STOPPED;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006239 return true;
6240 }
6241 return false;
6242}
6243
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006244bool Camera3Device::startRequestBuffer() {
6245 return mRequestBufferSM.startRequestBuffer();
6246}
Shuzhen Wang268a1362018-10-16 16:32:59 -07006247
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006248void Camera3Device::endRequestBuffer() {
6249 mRequestBufferSM.endRequestBuffer();
6250}
Shuzhen Wang268a1362018-10-16 16:32:59 -07006251
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006252nsecs_t Camera3Device::getWaitDuration() {
6253 return kBaseGetBufferWait + getExpectedInFlightDuration();
6254}
Shuzhen Wang268a1362018-10-16 16:32:59 -07006255
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006256void Camera3Device::getInflightBufferKeys(std::vector<std::pair<int32_t, int32_t>>* out) {
6257 mInterface->getInflightBufferKeys(out);
6258}
Shuzhen Wang268a1362018-10-16 16:32:59 -07006259
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006260void Camera3Device::getInflightRequestBufferKeys(std::vector<uint64_t>* out) {
6261 mInterface->getInflightRequestBufferKeys(out);
6262}
Shuzhen Wang268a1362018-10-16 16:32:59 -07006263
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006264std::vector<sp<Camera3StreamInterface>> Camera3Device::getAllStreams() {
6265 std::vector<sp<Camera3StreamInterface>> ret;
6266 bool hasInputStream = mInputStream != nullptr;
6267 ret.reserve(mOutputStreams.size() + mDeletedStreams.size() + ((hasInputStream) ? 1 : 0));
6268 if (hasInputStream) {
6269 ret.push_back(mInputStream);
Shuzhen Wang268a1362018-10-16 16:32:59 -07006270 }
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006271 for (size_t i = 0; i < mOutputStreams.size(); i++) {
6272 ret.push_back(mOutputStreams[i]);
6273 }
6274 for (size_t i = 0; i < mDeletedStreams.size(); i++) {
6275 ret.push_back(mDeletedStreams[i]);
6276 }
6277 return ret;
Shuzhen Wang268a1362018-10-16 16:32:59 -07006278}
6279
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006280status_t Camera3Device::switchToOffline(
6281 const std::vector<int32_t>& streamsToKeep,
6282 /*out*/ sp<CameraOfflineSessionBase>* session) {
6283 ATRACE_CALL();
6284 if (session == nullptr) {
6285 ALOGE("%s: session must not be null", __FUNCTION__);
6286 return BAD_VALUE;
6287 }
6288
6289 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006290
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006291 bool hasInputStream = mInputStream != nullptr;
6292 int32_t inputStreamId = hasInputStream ? mInputStream->getId() : -1;
6293 bool inputStreamSupportsOffline = hasInputStream ?
6294 mInputStream->getOfflineProcessingSupport() : false;
6295 auto outputStreamIds = mOutputStreams.getStreamIds();
6296 auto streamIds = outputStreamIds;
6297 if (hasInputStream) {
6298 streamIds.push_back(mInputStream->getId());
6299 }
6300
6301 // Check all streams in streamsToKeep supports offline mode
6302 for (auto id : streamsToKeep) {
6303 if (std::find(streamIds.begin(), streamIds.end(), id) == streamIds.end()) {
6304 ALOGE("%s: Unknown stream ID %d", __FUNCTION__, id);
6305 return BAD_VALUE;
6306 } else if (id == inputStreamId) {
6307 if (!inputStreamSupportsOffline) {
6308 ALOGE("%s: input stream %d cannot be switched to offline",
6309 __FUNCTION__, id);
6310 return BAD_VALUE;
6311 }
6312 } else {
6313 sp<camera3::Camera3OutputStreamInterface> stream = mOutputStreams.get(id);
6314 if (!stream->getOfflineProcessingSupport()) {
6315 ALOGE("%s: output stream %d cannot be switched to offline",
6316 __FUNCTION__, id);
6317 return BAD_VALUE;
6318 }
6319 }
6320 }
6321
6322 // TODO: block surface sharing and surface group streams until we can support them
6323
6324 // Stop repeating request, wait until all remaining requests are submitted, then call into
6325 // HAL switchToOffline
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006326 hardware::camera::device::V3_6::CameraOfflineSessionInfo offlineSessionInfo;
6327 sp<hardware::camera::device::V3_6::ICameraOfflineSession> offlineSession;
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006328 camera3::BufferRecords bufferRecords;
6329 status_t ret = mRequestThread->switchToOffline(
6330 streamsToKeep, &offlineSessionInfo, &offlineSession, &bufferRecords);
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006331
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006332 if (ret != OK) {
6333 SET_ERR("Switch to offline failed: %s (%d)", strerror(-ret), ret);
6334 return ret;
6335 }
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006336
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006337 bool succ = mRequestBufferSM.onSwitchToOfflineSuccess();
6338 if (!succ) {
6339 SET_ERR("HAL must not be calling requestStreamBuffers call");
6340 // TODO: block ALL callbacks from HAL till app configured new streams?
6341 return UNKNOWN_ERROR;
6342 }
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006343
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006344 // Verify offlineSessionInfo
6345 std::vector<int32_t> offlineStreamIds;
6346 offlineStreamIds.reserve(offlineSessionInfo.offlineStreams.size());
6347 for (auto offlineStream : offlineSessionInfo.offlineStreams) {
6348 // verify stream IDs
6349 int32_t id = offlineStream.id;
6350 if (std::find(streamIds.begin(), streamIds.end(), id) == streamIds.end()) {
6351 SET_ERR("stream ID %d not found!", id);
6352 return UNKNOWN_ERROR;
6353 }
6354
6355 // When not using HAL buf manager, only allow streams requested by app to be preserved
6356 if (!mUseHalBufManager) {
6357 if (std::find(streamsToKeep.begin(), streamsToKeep.end(), id) == streamsToKeep.end()) {
6358 SET_ERR("stream ID %d must not be switched to offline!", id);
6359 return UNKNOWN_ERROR;
6360 }
6361 }
6362
6363 offlineStreamIds.push_back(id);
6364 sp<Camera3StreamInterface> stream = (id == inputStreamId) ?
6365 static_cast<sp<Camera3StreamInterface>>(mInputStream) :
6366 static_cast<sp<Camera3StreamInterface>>(mOutputStreams.get(id));
6367 // Verify number of outstanding buffers
6368 if (stream->getOutstandingBuffersCount() != offlineStream.numOutstandingBuffers) {
6369 SET_ERR("Offline stream %d # of remaining buffer mismatch: (%zu,%d) (service/HAL)",
6370 id, stream->getOutstandingBuffersCount(), offlineStream.numOutstandingBuffers);
6371 return UNKNOWN_ERROR;
6372 }
6373 }
6374
6375 // Verify all streams to be deleted don't have any outstanding buffers
6376 if (hasInputStream && std::find(offlineStreamIds.begin(), offlineStreamIds.end(),
6377 inputStreamId) == offlineStreamIds.end()) {
6378 if (mInputStream->hasOutstandingBuffers()) {
6379 SET_ERR("Input stream %d still has %zu outstanding buffer!",
6380 inputStreamId, mInputStream->getOutstandingBuffersCount());
6381 return UNKNOWN_ERROR;
6382 }
6383 }
6384
6385 for (const auto& outStreamId : outputStreamIds) {
6386 if (std::find(offlineStreamIds.begin(), offlineStreamIds.end(),
6387 outStreamId) == offlineStreamIds.end()) {
6388 auto outStream = mOutputStreams.get(outStreamId);
6389 if (outStream->hasOutstandingBuffers()) {
6390 SET_ERR("Output stream %d still has %zu outstanding buffer!",
6391 outStreamId, outStream->getOutstandingBuffersCount());
6392 return UNKNOWN_ERROR;
6393 }
6394 }
6395 }
6396
6397 InFlightRequestMap offlineReqs;
6398 // Verify inflight requests and their pending buffers
6399 {
6400 std::lock_guard<std::mutex> l(mInFlightLock);
6401 for (auto offlineReq : offlineSessionInfo.offlineRequests) {
6402 int idx = mInFlightMap.indexOfKey(offlineReq.frameNumber);
6403 if (idx == NAME_NOT_FOUND) {
6404 SET_ERR("Offline request frame number %d not found!", offlineReq.frameNumber);
6405 return UNKNOWN_ERROR;
6406 }
6407
6408 const auto& inflightReq = mInFlightMap.valueAt(idx);
6409 // TODO: check specific stream IDs
6410 size_t numBuffersLeft = static_cast<size_t>(inflightReq.numBuffersLeft);
6411 if (numBuffersLeft != offlineReq.pendingStreams.size()) {
6412 SET_ERR("Offline request # of remaining buffer mismatch: (%d,%d) (service/HAL)",
6413 inflightReq.numBuffersLeft, offlineReq.pendingStreams.size());
6414 return UNKNOWN_ERROR;
6415 }
6416 offlineReqs.add(offlineReq.frameNumber, inflightReq);
6417 }
6418 }
6419
6420 // Create Camera3OfflineSession and transfer object ownership
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006421 // (streams, inflight requests, buffer caches)
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006422 camera3::StreamSet offlineStreamSet;
6423 sp<camera3::Camera3Stream> inputStream;
6424 for (auto offlineStream : offlineSessionInfo.offlineStreams) {
6425 int32_t id = offlineStream.id;
6426 if (mInputStream != nullptr && id == mInputStream->getId()) {
6427 inputStream = mInputStream;
6428 } else {
6429 offlineStreamSet.add(id, mOutputStreams.get(id));
6430 }
6431 }
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006432
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006433 // TODO: check if we need to lock before copying states
6434 // though technically no other thread should be talking to Camera3Device at this point
6435 Camera3OfflineStates offlineStates(
6436 mTagMonitor, mVendorTagId, mUseHalBufManager, mNeedFixupMonochromeTags,
Shuzhen Wangb7b42652020-05-07 11:59:02 -07006437 mUsePartialResult, mNumPartialResults, mLastCompletedRegularFrameNumber,
6438 mLastCompletedReprocessFrameNumber, mLastCompletedZslFrameNumber,
6439 mNextResultFrameNumber, mNextReprocessResultFrameNumber,
6440 mNextZslStillResultFrameNumber, mNextShutterFrameNumber,
6441 mNextReprocessShutterFrameNumber, mNextZslStillShutterFrameNumber,
6442 mDeviceInfo, mPhysicalDeviceInfoMap, mDistortionMappers,
6443 mZoomRatioMappers, mRotateAndCropMappers);
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006444
6445 *session = new Camera3OfflineSession(mId, inputStream, offlineStreamSet,
6446 std::move(bufferRecords), offlineReqs, offlineStates, offlineSession);
6447
6448 // Delete all streams that has been transferred to offline session
6449 Mutex::Autolock l(mLock);
6450 for (auto offlineStream : offlineSessionInfo.offlineStreams) {
6451 int32_t id = offlineStream.id;
6452 if (mInputStream != nullptr && id == mInputStream->getId()) {
6453 mInputStream.clear();
6454 } else {
6455 mOutputStreams.remove(id);
6456 }
6457 }
6458
6459 // disconnect all other streams and switch to UNCONFIGURED state
6460 if (mInputStream != nullptr) {
6461 ret = mInputStream->disconnect();
6462 if (ret != OK) {
6463 SET_ERR_L("disconnect input stream failed!");
6464 return UNKNOWN_ERROR;
6465 }
6466 }
6467
6468 for (auto streamId : mOutputStreams.getStreamIds()) {
6469 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
6470 ret = stream->disconnect();
6471 if (ret != OK) {
6472 SET_ERR_L("disconnect output stream %d failed!", streamId);
6473 return UNKNOWN_ERROR;
6474 }
6475 }
6476
6477 mInputStream.clear();
6478 mOutputStreams.clear();
6479 mNeedConfig = true;
6480 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
6481 mOperatingMode = NO_MODE;
6482 mIsConstrainedHighSpeedConfiguration = false;
Emilian Peevc0fe54c2020-03-11 14:05:07 -07006483 mRequestThread->clearPreviousRequest();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006484
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006485 return OK;
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006486 // TO be done by CameraDeviceClient/Camera3OfflineSession
6487 // register the offline client to camera service
6488 // Setup result passthing threads etc
6489 // Initialize offline session so HAL can start sending callback to it (result Fmq)
6490 // TODO: check how many onIdle callback will be sent
6491 // Java side to make sure the CameraCaptureSession is properly closed
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006492}
6493
Emilian Peevcc0b7952020-01-07 13:54:47 -08006494void Camera3Device::getOfflineStreamIds(std::vector<int> *offlineStreamIds) {
6495 ATRACE_CALL();
6496
6497 if (offlineStreamIds == nullptr) {
6498 return;
6499 }
6500
6501 Mutex::Autolock il(mInterfaceLock);
6502
6503 auto streamIds = mOutputStreams.getStreamIds();
6504 bool hasInputStream = mInputStream != nullptr;
6505 if (hasInputStream && mInputStream->getOfflineProcessingSupport()) {
6506 offlineStreamIds->push_back(mInputStream->getId());
6507 }
6508
6509 for (const auto & streamId : streamIds) {
6510 sp<camera3::Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
6511 // Streams that use the camera buffer manager are currently not supported in
6512 // offline mode
6513 if (stream->getOfflineProcessingSupport() &&
6514 (stream->getStreamSetId() == CAMERA3_STREAM_SET_ID_INVALID)) {
6515 offlineStreamIds->push_back(streamId);
6516 }
6517 }
6518}
6519
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08006520status_t Camera3Device::setRotateAndCropAutoBehavior(
6521 camera_metadata_enum_android_scaler_rotate_and_crop_t rotateAndCropValue) {
6522 ATRACE_CALL();
6523 Mutex::Autolock il(mInterfaceLock);
6524 Mutex::Autolock l(mLock);
6525 if (mRequestThread == nullptr) {
6526 return INVALID_OPERATION;
6527 }
6528 return mRequestThread->setRotateAndCropAutoBehavior(rotateAndCropValue);
6529}
6530
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08006531bool Camera3Device::supportsCameraMute() {
6532 Mutex::Autolock il(mInterfaceLock);
6533 Mutex::Autolock l(mLock);
6534
6535 return mSupportCameraMute;
6536}
6537
6538status_t Camera3Device::setCameraMute(bool enabled) {
6539 ATRACE_CALL();
6540 Mutex::Autolock il(mInterfaceLock);
6541 Mutex::Autolock l(mLock);
6542
6543 if (mRequestThread == nullptr || !mSupportCameraMute) {
6544 return INVALID_OPERATION;
6545 }
Eino-Ville Talvala11afe4f2021-05-27 14:45:31 -07006546 int32_t muteMode =
6547 !enabled ? ANDROID_SENSOR_TEST_PATTERN_MODE_OFF :
6548 mSupportTestPatternSolidColor ? ANDROID_SENSOR_TEST_PATTERN_MODE_SOLID_COLOR :
6549 ANDROID_SENSOR_TEST_PATTERN_MODE_BLACK;
6550 return mRequestThread->setCameraMute(muteMode);
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08006551}
6552
Cliff Wuc2ad9c82021-04-21 00:58:58 +08006553status_t Camera3Device::injectCamera(const String8& injectedCamId,
6554 sp<CameraProviderManager> manager) {
6555 ALOGI("%s Injection camera: injectedCamId = %s", __FUNCTION__, injectedCamId.string());
6556 ATRACE_CALL();
6557 Mutex::Autolock il(mInterfaceLock);
6558
6559 status_t res = NO_ERROR;
6560 if (mInjectionMethods->isInjecting()) {
6561 if (injectedCamId == mInjectionMethods->getInjectedCamId()) {
6562 return OK;
6563 } else {
6564 res = mInjectionMethods->stopInjection();
6565 if (res != OK) {
6566 ALOGE("%s: Failed to stop the injection camera! ret != NO_ERROR: %d",
6567 __FUNCTION__, res);
6568 return res;
6569 }
6570 }
6571 }
6572
6573 res = mInjectionMethods->injectionInitialize(injectedCamId, manager, this);
6574 if (res != OK) {
6575 ALOGE("%s: Failed to initialize the injection camera! ret != NO_ERROR: %d",
6576 __FUNCTION__, res);
6577 return res;
6578 }
6579
6580 camera3::camera_stream_configuration injectionConfig;
6581 std::vector<uint32_t> injectionBufferSizes;
6582 mInjectionMethods->getInjectionConfig(&injectionConfig, &injectionBufferSizes);
6583 // When the second display of android is cast to the remote device, and the opened camera is
6584 // also cast to the second display, in this case, because the camera has configured the streams
6585 // at this time, we can directly call injectCamera() to replace the internal camera with
6586 // injection camera.
6587 if (mOperatingMode >= 0 && injectionConfig.num_streams > 0
6588 && injectionBufferSizes.size() > 0) {
6589 ALOGV("%s: The opened camera is directly cast to the remote device.", __FUNCTION__);
6590 res = mInjectionMethods->injectCamera(
6591 injectionConfig, injectionBufferSizes);
6592 if (res != OK) {
6593 ALOGE("Can't finish inject camera process!");
6594 return res;
6595 }
6596 }
6597
6598 return OK;
6599}
6600
6601status_t Camera3Device::stopInjection() {
6602 ALOGI("%s: Injection camera: stopInjection", __FUNCTION__);
6603 Mutex::Autolock il(mInterfaceLock);
6604 return mInjectionMethods->stopInjection();
6605}
6606
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08006607}; // namespace android