blob: d05a2e152afc976be94b24e839bc04b00e12a850 [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
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -080078Camera3Device::Camera3Device(const String8 &id):
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),
96 mNeedFixupMonochromeTags(false)
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080097{
98 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080099 ALOGV("%s: Created device for camera %s", __FUNCTION__, mId.string());
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800100}
101
102Camera3Device::~Camera3Device()
103{
104 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800105 ALOGV("%s: Tearing down for camera id %s", __FUNCTION__, mId.string());
Yin-Chia Yehc5248132018-08-15 12:19:20 -0700106 disconnectImpl();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800107}
108
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800109const String8& Camera3Device::getId() const {
Igor Murashkin71381052013-03-04 14:53:08 -0800110 return mId;
111}
112
Emilian Peevbd8c5032018-02-14 23:05:40 +0000113status_t Camera3Device::initialize(sp<CameraProviderManager> manager, const String8& monitorTags) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800114 ATRACE_CALL();
115 Mutex::Autolock il(mInterfaceLock);
116 Mutex::Autolock l(mLock);
117
118 ALOGV("%s: Initializing HIDL device for camera %s", __FUNCTION__, mId.string());
119 if (mStatus != STATUS_UNINITIALIZED) {
120 CLOGE("Already initialized!");
121 return INVALID_OPERATION;
122 }
123 if (manager == nullptr) return INVALID_OPERATION;
124
125 sp<ICameraDeviceSession> session;
126 ATRACE_BEGIN("CameraHal::openSession");
Steven Moreland5ff9c912017-03-09 23:13:00 -0800127 status_t res = manager->openSession(mId.string(), this,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800128 /*out*/ &session);
129 ATRACE_END();
130 if (res != OK) {
131 SET_ERR_L("Could not open camera session: %s (%d)", strerror(-res), res);
132 return res;
133 }
134
Steven Moreland5ff9c912017-03-09 23:13:00 -0800135 res = manager->getCameraCharacteristics(mId.string(), &mDeviceInfo);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800136 if (res != OK) {
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700137 SET_ERR_L("Could not retrieve camera characteristics: %s (%d)", strerror(-res), res);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800138 session->close();
139 return res;
140 }
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800141 mSupportNativeZoomRatio = manager->supportNativeZoomRatio(mId.string());
Yin-Chia Yeh52778d42016-12-22 18:20:43 -0800142
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700143 std::vector<std::string> physicalCameraIds;
Shuzhen Wang03d8cc12018-09-12 14:17:09 -0700144 bool isLogical = manager->isLogicalCamera(mId.string(), &physicalCameraIds);
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700145 if (isLogical) {
146 for (auto& physicalId : physicalCameraIds) {
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -0700147 res = manager->getCameraCharacteristics(
148 physicalId, &mPhysicalDeviceInfoMap[physicalId]);
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700149 if (res != OK) {
150 SET_ERR_L("Could not retrieve camera %s characteristics: %s (%d)",
151 physicalId.c_str(), strerror(-res), res);
152 session->close();
153 return res;
154 }
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -0700155
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800156 bool usePrecorrectArray =
157 DistortionMapper::isDistortionSupported(mPhysicalDeviceInfoMap[physicalId]);
158 if (usePrecorrectArray) {
159 res = mDistortionMappers[physicalId].setupStaticInfo(
160 mPhysicalDeviceInfoMap[physicalId]);
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -0700161 if (res != OK) {
162 SET_ERR_L("Unable to read camera %s's calibration fields for distortion "
163 "correction", physicalId.c_str());
164 session->close();
165 return res;
166 }
167 }
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800168
Shuzhen Wang1c834da2019-12-18 11:17:03 -0800169 mZoomRatioMappers[physicalId] = ZoomRatioMapper(
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800170 &mPhysicalDeviceInfoMap[physicalId],
171 mSupportNativeZoomRatio, usePrecorrectArray);
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700172 }
173 }
174
Yifan Hongf79b5542017-04-11 14:44:25 -0700175 std::shared_ptr<RequestMetadataQueue> queue;
Yifan Honga640c5a2017-04-12 16:30:31 -0700176 auto requestQueueRet = session->getCaptureRequestMetadataQueue(
177 [&queue](const auto& descriptor) {
178 queue = std::make_shared<RequestMetadataQueue>(descriptor);
179 if (!queue->isValid() || queue->availableToWrite() <= 0) {
180 ALOGE("HAL returns empty request metadata fmq, not use it");
181 queue = nullptr;
182 // don't use the queue onwards.
183 }
184 });
185 if (!requestQueueRet.isOk()) {
186 ALOGE("Transaction error when getting request metadata fmq: %s, not use it",
187 requestQueueRet.description().c_str());
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -0700188 return DEAD_OBJECT;
Yifan Hongf79b5542017-04-11 14:44:25 -0700189 }
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700190
191 std::unique_ptr<ResultMetadataQueue>& resQueue = mResultMetadataQueue;
Yifan Honga640c5a2017-04-12 16:30:31 -0700192 auto resultQueueRet = session->getCaptureResultMetadataQueue(
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700193 [&resQueue](const auto& descriptor) {
194 resQueue = std::make_unique<ResultMetadataQueue>(descriptor);
195 if (!resQueue->isValid() || resQueue->availableToWrite() <= 0) {
Yifan Honga640c5a2017-04-12 16:30:31 -0700196 ALOGE("HAL returns empty result metadata fmq, not use it");
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700197 resQueue = nullptr;
198 // Don't use the resQueue onwards.
Yifan Honga640c5a2017-04-12 16:30:31 -0700199 }
200 });
201 if (!resultQueueRet.isOk()) {
202 ALOGE("Transaction error when getting result metadata queue from camera session: %s",
203 resultQueueRet.description().c_str());
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -0700204 return DEAD_OBJECT;
Yifan Honga640c5a2017-04-12 16:30:31 -0700205 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -0700206 IF_ALOGV() {
207 session->interfaceChain([](
208 ::android::hardware::hidl_vec<::android::hardware::hidl_string> interfaceChain) {
209 ALOGV("Session interface chain:");
Chih-Hung Hsieh3ef324d2018-12-11 11:48:12 -0800210 for (const auto& iface : interfaceChain) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -0700211 ALOGV(" %s", iface.c_str());
212 }
213 });
214 }
Yifan Hongf79b5542017-04-11 14:44:25 -0700215
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -0800216 camera_metadata_entry bufMgrMode =
217 mDeviceInfo.find(ANDROID_INFO_SUPPORTED_BUFFER_MANAGEMENT_VERSION);
218 if (bufMgrMode.count > 0) {
219 mUseHalBufManager = (bufMgrMode.data.u8[0] ==
220 ANDROID_INFO_SUPPORTED_BUFFER_MANAGEMENT_VERSION_HIDL_DEVICE_3_5);
221 }
222
Yin-Chia Yehb978c382019-10-30 00:22:37 -0700223 camera_metadata_entry_t capabilities = mDeviceInfo.find(ANDROID_REQUEST_AVAILABLE_CAPABILITIES);
224 for (size_t i = 0; i < capabilities.count; i++) {
225 uint8_t capability = capabilities.data.u8[i];
226 if (capability == ANDROID_REQUEST_AVAILABLE_CAPABILITIES_OFFLINE_PROCESSING) {
227 mSupportOfflineProcessing = true;
228 }
229 }
230
231 mInterface = new HalInterface(session, queue, mUseHalBufManager, mSupportOfflineProcessing);
Emilian Peev71c73a22017-03-21 16:35:51 +0000232 std::string providerType;
233 mVendorTagId = manager->getProviderTagIdLocked(mId.string());
Emilian Peevbd8c5032018-02-14 23:05:40 +0000234 mTagMonitor.initialize(mVendorTagId);
235 if (!monitorTags.isEmpty()) {
236 mTagMonitor.parseTagsToMonitor(String8(monitorTags));
237 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800238
Shuzhen Wang268a1362018-10-16 16:32:59 -0700239 // Metadata tags needs fixup for monochrome camera device version less
240 // than 3.5.
241 hardware::hidl_version maxVersion{0,0};
242 res = manager->getHighestSupportedVersion(mId.string(), &maxVersion);
243 if (res != OK) {
244 ALOGE("%s: Error in getting camera device version id: %s (%d)",
245 __FUNCTION__, strerror(-res), res);
246 return res;
247 }
248 int deviceVersion = HARDWARE_DEVICE_API_VERSION(
249 maxVersion.get_major(), maxVersion.get_minor());
250
251 bool isMonochrome = false;
Yin-Chia Yehb978c382019-10-30 00:22:37 -0700252 for (size_t i = 0; i < capabilities.count; i++) {
253 uint8_t capability = capabilities.data.u8[i];
Shuzhen Wang268a1362018-10-16 16:32:59 -0700254 if (capability == ANDROID_REQUEST_AVAILABLE_CAPABILITIES_MONOCHROME) {
255 isMonochrome = true;
256 }
257 }
258 mNeedFixupMonochromeTags = (isMonochrome && deviceVersion < CAMERA_DEVICE_API_VERSION_3_5);
259
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800260 return initializeCommonLocked();
261}
262
263status_t Camera3Device::initializeCommonLocked() {
264
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700265 /** Start up status tracker thread */
266 mStatusTracker = new StatusTracker(this);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800267 status_t res = mStatusTracker->run(String8::format("C3Dev-%s-Status", mId.string()).string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700268 if (res != OK) {
269 SET_ERR_L("Unable to start status tracking thread: %s (%d)",
270 strerror(-res), res);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800271 mInterface->close();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700272 mStatusTracker.clear();
273 return res;
274 }
275
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -0700276 /** Register in-flight map to the status tracker */
Yin-Chia Yeh87b3ec02019-06-03 10:44:39 -0700277 mInFlightStatusId = mStatusTracker->addComponent("InflightRequests");
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -0700278
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -0700279 if (mUseHalBufManager) {
280 res = mRequestBufferSM.initialize(mStatusTracker);
281 if (res != OK) {
282 SET_ERR_L("Unable to start request buffer state machine: %s (%d)",
283 strerror(-res), res);
284 mInterface->close();
285 mStatusTracker.clear();
286 return res;
287 }
288 }
289
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -0800290 /** Create buffer manager */
291 mBufferManager = new Camera3BufferManager();
292
293 Vector<int32_t> sessionParamKeys;
294 camera_metadata_entry_t sessionKeysEntry = mDeviceInfo.find(
295 ANDROID_REQUEST_AVAILABLE_SESSION_KEYS);
296 if (sessionKeysEntry.count > 0) {
297 sessionParamKeys.insertArrayAt(sessionKeysEntry.data.i32, 0, sessionKeysEntry.count);
298 }
299
Chien-Yu Chenab5135b2015-06-30 11:20:58 -0700300 /** Start up request queue thread */
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -0700301 mRequestThread = new RequestThread(
302 this, mStatusTracker, mInterface, sessionParamKeys, mUseHalBufManager);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800303 res = mRequestThread->run(String8::format("C3Dev-%s-ReqQueue", mId.string()).string());
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800304 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700305 SET_ERR_L("Unable to start request queue thread: %s (%d)",
306 strerror(-res), res);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800307 mInterface->close();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800308 mRequestThread.clear();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800309 return res;
310 }
311
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -0700312 mPreparerThread = new PreparerThread();
313
Ruben Brunk183f0562015-08-12 12:55:02 -0700314 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800315 mNextStreamId = 0;
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -0400316 mFakeStreamId = NO_STREAM;
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -0700317 mNeedConfig = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700318 mPauseStateNotify = false;
Shuzhen Wang83bff122020-11-20 15:51:39 -0800319 mIsInputStreamMultiResolution = false;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800320
Shuzhen Wangc28dccc2016-02-11 23:48:46 -0800321 // Measure the clock domain offset between camera and video/hw_composer
322 camera_metadata_entry timestampSource =
323 mDeviceInfo.find(ANDROID_SENSOR_INFO_TIMESTAMP_SOURCE);
324 if (timestampSource.count > 0 && timestampSource.data.u8[0] ==
325 ANDROID_SENSOR_INFO_TIMESTAMP_SOURCE_REALTIME) {
326 mTimestampOffset = getMonoToBoottimeOffset();
327 }
328
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -0700329 // Will the HAL be sending in early partial result metadata?
Emilian Peev08dd2452017-04-06 16:55:14 +0100330 camera_metadata_entry partialResultsCount =
331 mDeviceInfo.find(ANDROID_REQUEST_PARTIAL_RESULT_COUNT);
332 if (partialResultsCount.count > 0) {
333 mNumPartialResults = partialResultsCount.data.i32[0];
334 mUsePartialResult = (mNumPartialResults > 1);
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -0700335 }
336
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800337 bool usePrecorrectArray = DistortionMapper::isDistortionSupported(mDeviceInfo);
338 if (usePrecorrectArray) {
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -0700339 res = mDistortionMappers[mId.c_str()].setupStaticInfo(mDeviceInfo);
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -0700340 if (res != OK) {
341 SET_ERR_L("Unable to read necessary calibration fields for distortion correction");
342 return res;
343 }
344 }
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800345
Shuzhen Wang1c834da2019-12-18 11:17:03 -0800346 mZoomRatioMappers[mId.c_str()] = ZoomRatioMapper(&mDeviceInfo,
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800347 mSupportNativeZoomRatio, usePrecorrectArray);
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800348
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -0800349 if (RotateAndCropMapper::isNeeded(&mDeviceInfo)) {
350 mRotateAndCropMappers.emplace(mId.c_str(), &mDeviceInfo);
351 }
352
Eino-Ville Talvala305cec62020-11-12 14:18:17 -0800353 camera_metadata_entry_t availableTestPatternModes = mDeviceInfo.find(
354 ANDROID_SENSOR_AVAILABLE_TEST_PATTERN_MODES);
355 for (size_t i = 0; i < availableTestPatternModes.count; i++) {
356 if (availableTestPatternModes.data.i32[i] == ANDROID_SENSOR_TEST_PATTERN_MODE_SOLID_COLOR) {
357 mSupportCameraMute = true;
358 break;
359 }
360 }
361
Cliff Wuc2ad9c82021-04-21 00:58:58 +0800362 mInjectionMethods = new Camera3DeviceInjectionMethods(this);
363
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800364 return OK;
365}
366
367status_t Camera3Device::disconnect() {
Yin-Chia Yehc5248132018-08-15 12:19:20 -0700368 return disconnectImpl();
369}
370
371status_t Camera3Device::disconnectImpl() {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800372 ATRACE_CALL();
Yin-Chia Yehe1c80632016-08-08 14:48:05 -0700373 ALOGI("%s: E", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800374
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700375 status_t res = OK;
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700376 std::vector<wp<Camera3StreamInterface>> streams;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700377 {
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800378 Mutex::Autolock il(mInterfaceLock);
379 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
380 {
381 Mutex::Autolock l(mLock);
382 if (mStatus == STATUS_UNINITIALIZED) return res;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700383
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800384 if (mStatus == STATUS_ACTIVE ||
385 (mStatus == STATUS_ERROR && mRequestThread != NULL)) {
386 res = mRequestThread->clearRepeatingRequests();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700387 if (res != OK) {
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800388 SET_ERR_L("Can't stop streaming");
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700389 // Continue to close device even in case of error
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800390 } else {
391 res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
392 if (res != OK) {
393 SET_ERR_L("Timeout waiting for HAL to drain (% " PRIi64 " ns)",
394 maxExpectedDuration);
395 // Continue to close device even in case of error
396 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700397 }
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700398 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800399
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800400 if (mStatus == STATUS_ERROR) {
401 CLOGE("Shutting down in an error state");
402 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700403
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800404 if (mStatusTracker != NULL) {
405 mStatusTracker->requestExit();
406 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700407
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800408 if (mRequestThread != NULL) {
409 mRequestThread->requestExit();
410 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700411
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800412 streams.reserve(mOutputStreams.size() + (mInputStream != nullptr ? 1 : 0));
413 for (size_t i = 0; i < mOutputStreams.size(); i++) {
414 streams.push_back(mOutputStreams[i]);
415 }
416 if (mInputStream != nullptr) {
417 streams.push_back(mInputStream);
418 }
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700419 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700420 }
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800421 // Joining done without holding mLock and mInterfaceLock, otherwise deadlocks may ensue
422 // as the threads try to access parent state (b/143513518)
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700423 if (mRequestThread != NULL && mStatus != STATUS_ERROR) {
424 // HAL may be in a bad state, so waiting for request thread
425 // (which may be stuck in the HAL processCaptureRequest call)
426 // could be dangerous.
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800427 // give up mInterfaceLock here and then lock it again. Could this lead
428 // to other deadlocks
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700429 mRequestThread->join();
430 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700431 {
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800432 Mutex::Autolock il(mInterfaceLock);
433 if (mStatusTracker != NULL) {
434 mStatusTracker->join();
435 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800436
Cliff Wuc2ad9c82021-04-21 00:58:58 +0800437 if (mInjectionMethods->isInjecting()) {
438 mInjectionMethods->stopInjection();
439 }
440
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800441 HalInterface* interface;
442 {
443 Mutex::Autolock l(mLock);
444 mRequestThread.clear();
445 Mutex::Autolock stLock(mTrackerLock);
446 mStatusTracker.clear();
447 interface = mInterface.get();
448 }
Eino-Ville Talvalaefff1c42015-08-28 16:27:27 -0700449
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800450 // Call close without internal mutex held, as the HAL close may need to
451 // wait on assorted callbacks,etc, to complete before it can return.
452 interface->close();
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700453
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800454 flushInflightRequests();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800455
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800456 {
457 Mutex::Autolock l(mLock);
458 mInterface->clear();
459 mOutputStreams.clear();
460 mInputStream.clear();
461 mDeletedStreams.clear();
462 mBufferManager.clear();
463 internalUpdateStatusLocked(STATUS_UNINITIALIZED);
464 }
465
466 for (auto& weakStream : streams) {
467 sp<Camera3StreamInterface> stream = weakStream.promote();
468 if (stream != nullptr) {
469 ALOGE("%s: Stream %d leaked! strong reference (%d)!",
470 __FUNCTION__, stream->getId(), stream->getStrongCount() - 1);
471 }
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700472 }
473 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -0700474 ALOGI("%s: X", __FUNCTION__);
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700475 return res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800476}
477
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700478// For dumping/debugging only -
479// try to acquire a lock a few times, eventually give up to proceed with
480// debug/dump operations
481bool Camera3Device::tryLockSpinRightRound(Mutex& lock) {
482 bool gotLock = false;
483 for (size_t i = 0; i < kDumpLockAttempts; ++i) {
484 if (lock.tryLock() == NO_ERROR) {
485 gotLock = true;
486 break;
487 } else {
488 usleep(kDumpSleepDuration);
489 }
490 }
491 return gotLock;
492}
493
Shuzhen Wang83bff122020-11-20 15:51:39 -0800494camera3::Size Camera3Device::getMaxJpegResolution() const {
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700495 int32_t maxJpegWidth = 0, maxJpegHeight = 0;
Emilian Peev08dd2452017-04-06 16:55:14 +0100496 const int STREAM_CONFIGURATION_SIZE = 4;
497 const int STREAM_FORMAT_OFFSET = 0;
498 const int STREAM_WIDTH_OFFSET = 1;
499 const int STREAM_HEIGHT_OFFSET = 2;
500 const int STREAM_IS_INPUT_OFFSET = 3;
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -0800501 bool isHighResolutionSensor =
502 camera3::SessionConfigurationUtils::isUltraHighResolutionSensor(mDeviceInfo);
503 int32_t scalerSizesTag = isHighResolutionSensor ?
504 ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS_MAXIMUM_RESOLUTION :
505 ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS;
Emilian Peev08dd2452017-04-06 16:55:14 +0100506 camera_metadata_ro_entry_t availableStreamConfigs =
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -0800507 mDeviceInfo.find(scalerSizesTag);
Emilian Peev08dd2452017-04-06 16:55:14 +0100508 if (availableStreamConfigs.count == 0 ||
509 availableStreamConfigs.count % STREAM_CONFIGURATION_SIZE != 0) {
Shuzhen Wang83bff122020-11-20 15:51:39 -0800510 return camera3::Size(0, 0);
Emilian Peev08dd2452017-04-06 16:55:14 +0100511 }
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700512
Emilian Peev08dd2452017-04-06 16:55:14 +0100513 // Get max jpeg size (area-wise).
514 for (size_t i=0; i < availableStreamConfigs.count; i+= STREAM_CONFIGURATION_SIZE) {
515 int32_t format = availableStreamConfigs.data.i32[i + STREAM_FORMAT_OFFSET];
516 int32_t width = availableStreamConfigs.data.i32[i + STREAM_WIDTH_OFFSET];
517 int32_t height = availableStreamConfigs.data.i32[i + STREAM_HEIGHT_OFFSET];
518 int32_t isInput = availableStreamConfigs.data.i32[i + STREAM_IS_INPUT_OFFSET];
519 if (isInput == ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS_OUTPUT
520 && format == HAL_PIXEL_FORMAT_BLOB &&
521 (width * height > maxJpegWidth * maxJpegHeight)) {
522 maxJpegWidth = width;
523 maxJpegHeight = height;
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700524 }
525 }
Emilian Peev08dd2452017-04-06 16:55:14 +0100526
Shuzhen Wang83bff122020-11-20 15:51:39 -0800527 return camera3::Size(maxJpegWidth, maxJpegHeight);
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700528}
529
Shuzhen Wangc28dccc2016-02-11 23:48:46 -0800530nsecs_t Camera3Device::getMonoToBoottimeOffset() {
531 // try three times to get the clock offset, choose the one
532 // with the minimum gap in measurements.
533 const int tries = 3;
534 nsecs_t bestGap, measured;
535 for (int i = 0; i < tries; ++i) {
536 const nsecs_t tmono = systemTime(SYSTEM_TIME_MONOTONIC);
537 const nsecs_t tbase = systemTime(SYSTEM_TIME_BOOTTIME);
538 const nsecs_t tmono2 = systemTime(SYSTEM_TIME_MONOTONIC);
539 const nsecs_t gap = tmono2 - tmono;
540 if (i == 0 || gap < bestGap) {
541 bestGap = gap;
542 measured = tbase - ((tmono + tmono2) >> 1);
543 }
544 }
545 return measured;
546}
547
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800548hardware::graphics::common::V1_0::PixelFormat Camera3Device::mapToPixelFormat(
549 int frameworkFormat) {
550 return (hardware::graphics::common::V1_0::PixelFormat) frameworkFormat;
551}
552
553DataspaceFlags Camera3Device::mapToHidlDataspace(
554 android_dataspace dataSpace) {
555 return dataSpace;
556}
557
Chia-I Wu67a0c0e2017-04-06 13:37:01 -0700558BufferUsageFlags Camera3Device::mapToConsumerUsage(
Emilian Peev050f5dc2017-05-18 14:43:56 +0100559 uint64_t usage) {
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -0700560 return usage;
561}
562
Emilian Peevf4816702020-04-03 15:44:51 -0700563StreamRotation Camera3Device::mapToStreamRotation(camera_stream_rotation_t rotation) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800564 switch (rotation) {
Emilian Peevf4816702020-04-03 15:44:51 -0700565 case CAMERA_STREAM_ROTATION_0:
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800566 return StreamRotation::ROTATION_0;
Emilian Peevf4816702020-04-03 15:44:51 -0700567 case CAMERA_STREAM_ROTATION_90:
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800568 return StreamRotation::ROTATION_90;
Emilian Peevf4816702020-04-03 15:44:51 -0700569 case CAMERA_STREAM_ROTATION_180:
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800570 return StreamRotation::ROTATION_180;
Emilian Peevf4816702020-04-03 15:44:51 -0700571 case CAMERA_STREAM_ROTATION_270:
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800572 return StreamRotation::ROTATION_270;
573 }
574 ALOGE("%s: Unknown stream rotation %d", __FUNCTION__, rotation);
575 return StreamRotation::ROTATION_0;
576}
577
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800578status_t Camera3Device::mapToStreamConfigurationMode(
Emilian Peevf4816702020-04-03 15:44:51 -0700579 camera_stream_configuration_mode_t operationMode, StreamConfigurationMode *mode) {
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800580 if (mode == nullptr) return BAD_VALUE;
Emilian Peevf4816702020-04-03 15:44:51 -0700581 if (operationMode < CAMERA_VENDOR_STREAM_CONFIGURATION_MODE_START) {
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800582 switch(operationMode) {
Emilian Peevf4816702020-04-03 15:44:51 -0700583 case CAMERA_STREAM_CONFIGURATION_NORMAL_MODE:
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800584 *mode = StreamConfigurationMode::NORMAL_MODE;
585 break;
Emilian Peevf4816702020-04-03 15:44:51 -0700586 case CAMERA_STREAM_CONFIGURATION_CONSTRAINED_HIGH_SPEED_MODE:
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800587 *mode = StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE;
588 break;
589 default:
590 ALOGE("%s: Unknown stream configuration mode %d", __FUNCTION__, operationMode);
591 return BAD_VALUE;
592 }
593 } else {
594 *mode = static_cast<StreamConfigurationMode>(operationMode);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800595 }
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800596 return OK;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800597}
598
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800599int Camera3Device::mapToFrameworkFormat(
600 hardware::graphics::common::V1_0::PixelFormat pixelFormat) {
601 return static_cast<uint32_t>(pixelFormat);
602}
603
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -0700604android_dataspace Camera3Device::mapToFrameworkDataspace(
605 DataspaceFlags dataSpace) {
606 return static_cast<android_dataspace>(dataSpace);
607}
608
Emilian Peev050f5dc2017-05-18 14:43:56 +0100609uint64_t Camera3Device::mapConsumerToFrameworkUsage(
Chia-I Wu67a0c0e2017-04-06 13:37:01 -0700610 BufferUsageFlags usage) {
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -0700611 return usage;
612}
613
Emilian Peev050f5dc2017-05-18 14:43:56 +0100614uint64_t Camera3Device::mapProducerToFrameworkUsage(
Chia-I Wu67a0c0e2017-04-06 13:37:01 -0700615 BufferUsageFlags usage) {
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -0700616 return usage;
617}
618
Zhijun Hef7da0962014-04-24 13:27:56 -0700619ssize_t Camera3Device::getJpegBufferSize(uint32_t width, uint32_t height) const {
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700620 // Get max jpeg size (area-wise).
Shuzhen Wang83bff122020-11-20 15:51:39 -0800621 camera3::Size maxJpegResolution = getMaxJpegResolution();
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700622 if (maxJpegResolution.width == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800623 ALOGE("%s: Camera %s: Can't find valid available jpeg sizes in static metadata!",
624 __FUNCTION__, mId.string());
Zhijun Hef7da0962014-04-24 13:27:56 -0700625 return BAD_VALUE;
626 }
627
Zhijun Hef7da0962014-04-24 13:27:56 -0700628 // Get max jpeg buffer size
629 ssize_t maxJpegBufferSize = 0;
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700630 camera_metadata_ro_entry jpegBufMaxSize = mDeviceInfo.find(ANDROID_JPEG_MAX_SIZE);
631 if (jpegBufMaxSize.count == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800632 ALOGE("%s: Camera %s: Can't find maximum JPEG size in static metadata!", __FUNCTION__,
633 mId.string());
Zhijun Hef7da0962014-04-24 13:27:56 -0700634 return BAD_VALUE;
635 }
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700636 maxJpegBufferSize = jpegBufMaxSize.data.i32[0];
Yin-Chia Yeh0c4e56d2015-01-09 15:21:27 -0800637 assert(kMinJpegBufferSize < maxJpegBufferSize);
Zhijun Hef7da0962014-04-24 13:27:56 -0700638
639 // Calculate final jpeg buffer size for the given resolution.
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700640 float scaleFactor = ((float) (width * height)) /
641 (maxJpegResolution.width * maxJpegResolution.height);
Yin-Chia Yeh0c4e56d2015-01-09 15:21:27 -0800642 ssize_t jpegBufferSize = scaleFactor * (maxJpegBufferSize - kMinJpegBufferSize) +
643 kMinJpegBufferSize;
Zhijun Hef7da0962014-04-24 13:27:56 -0700644 if (jpegBufferSize > maxJpegBufferSize) {
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -0800645 ALOGI("%s: jpeg buffer size calculated is > maxJpeg bufferSize(%zd), clamping",
646 __FUNCTION__, maxJpegBufferSize);
Zhijun Hef7da0962014-04-24 13:27:56 -0700647 jpegBufferSize = maxJpegBufferSize;
Zhijun Hef7da0962014-04-24 13:27:56 -0700648 }
649
650 return jpegBufferSize;
651}
652
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700653ssize_t Camera3Device::getPointCloudBufferSize() const {
654 const int FLOATS_PER_POINT=4;
655 camera_metadata_ro_entry maxPointCount = mDeviceInfo.find(ANDROID_DEPTH_MAX_DEPTH_SAMPLES);
656 if (maxPointCount.count == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800657 ALOGE("%s: Camera %s: Can't find maximum depth point cloud size in static metadata!",
658 __FUNCTION__, mId.string());
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700659 return BAD_VALUE;
660 }
661 ssize_t maxBytesForPointCloud = sizeof(android_depth_points) +
662 maxPointCount.data.i32[0] * sizeof(float) * FLOATS_PER_POINT;
663 return maxBytesForPointCloud;
664}
665
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -0800666ssize_t Camera3Device::getRawOpaqueBufferSize(int32_t width, int32_t height,
667 bool maxResolution) const {
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800668 const int PER_CONFIGURATION_SIZE = 3;
669 const int WIDTH_OFFSET = 0;
670 const int HEIGHT_OFFSET = 1;
671 const int SIZE_OFFSET = 2;
672 camera_metadata_ro_entry rawOpaqueSizes =
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -0800673 mDeviceInfo.find(
674 camera3::SessionConfigurationUtils::getAppropriateModeTag(
675 ANDROID_SENSOR_OPAQUE_RAW_SIZE,
676 maxResolution));
Aurimas Liutikasbc57b122016-02-16 09:59:16 -0800677 size_t count = rawOpaqueSizes.count;
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800678 if (count == 0 || (count % PER_CONFIGURATION_SIZE)) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800679 ALOGE("%s: Camera %s: bad opaque RAW size static metadata length(%zu)!",
680 __FUNCTION__, mId.string(), count);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800681 return BAD_VALUE;
682 }
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700683
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800684 for (size_t i = 0; i < count; i += PER_CONFIGURATION_SIZE) {
685 if (width == rawOpaqueSizes.data.i32[i + WIDTH_OFFSET] &&
686 height == rawOpaqueSizes.data.i32[i + HEIGHT_OFFSET]) {
687 return rawOpaqueSizes.data.i32[i + SIZE_OFFSET];
688 }
689 }
690
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800691 ALOGE("%s: Camera %s: cannot find size for %dx%d opaque RAW image!",
692 __FUNCTION__, mId.string(), width, height);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800693 return BAD_VALUE;
694}
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700695
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800696status_t Camera3Device::dump(int fd, const Vector<String16> &args) {
697 ATRACE_CALL();
698 (void)args;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700699
700 // Try to lock, but continue in case of failure (to avoid blocking in
701 // deadlocks)
702 bool gotInterfaceLock = tryLockSpinRightRound(mInterfaceLock);
703 bool gotLock = tryLockSpinRightRound(mLock);
704
705 ALOGW_IF(!gotInterfaceLock,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800706 "Camera %s: %s: Unable to lock interface lock, proceeding anyway",
707 mId.string(), __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700708 ALOGW_IF(!gotLock,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800709 "Camera %s: %s: Unable to lock main lock, proceeding anyway",
710 mId.string(), __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700711
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800712 bool dumpTemplates = false;
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700713
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800714 String16 templatesOption("-t");
715 int n = args.size();
716 for (int i = 0; i < n; i++) {
717 if (args[i] == templatesOption) {
718 dumpTemplates = true;
719 }
Emilian Peevbd8c5032018-02-14 23:05:40 +0000720 if (args[i] == TagMonitor::kMonitorOption) {
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700721 if (i + 1 < n) {
722 String8 monitorTags = String8(args[i + 1]);
723 if (monitorTags == "off") {
724 mTagMonitor.disableMonitoring();
725 } else {
726 mTagMonitor.parseTagsToMonitor(monitorTags);
727 }
728 } else {
729 mTagMonitor.disableMonitoring();
730 }
731 }
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800732 }
733
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800734 String8 lines;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800735
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800736 const char *status =
737 mStatus == STATUS_ERROR ? "ERROR" :
738 mStatus == STATUS_UNINITIALIZED ? "UNINITIALIZED" :
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700739 mStatus == STATUS_UNCONFIGURED ? "UNCONFIGURED" :
740 mStatus == STATUS_CONFIGURED ? "CONFIGURED" :
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800741 mStatus == STATUS_ACTIVE ? "ACTIVE" :
742 "Unknown";
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700743
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800744 lines.appendFormat(" Device status: %s\n", status);
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700745 if (mStatus == STATUS_ERROR) {
746 lines.appendFormat(" Error cause: %s\n", mErrorCause.string());
747 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800748 lines.appendFormat(" Stream configuration:\n");
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800749 const char *mode =
750 mOperatingMode == static_cast<int>(StreamConfigurationMode::NORMAL_MODE) ? "NORMAL" :
751 mOperatingMode == static_cast<int>(
752 StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE) ? "CONSTRAINED_HIGH_SPEED" :
753 "CUSTOM";
754 lines.appendFormat(" Operation mode: %s (%d) \n", mode, mOperatingMode);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800755
756 if (mInputStream != NULL) {
757 write(fd, lines.string(), lines.size());
758 mInputStream->dump(fd, args);
759 } else {
760 lines.appendFormat(" No input stream.\n");
761 write(fd, lines.string(), lines.size());
762 }
763 for (size_t i = 0; i < mOutputStreams.size(); i++) {
764 mOutputStreams[i]->dump(fd,args);
765 }
766
Zhijun He431503c2016-03-07 17:30:16 -0800767 if (mBufferManager != NULL) {
768 lines = String8(" Camera3 Buffer Manager:\n");
769 write(fd, lines.string(), lines.size());
770 mBufferManager->dump(fd, args);
771 }
Zhijun He125684a2015-12-26 15:07:30 -0800772
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700773 lines = String8(" In-flight requests:\n");
774 if (mInFlightMap.size() == 0) {
775 lines.append(" None\n");
776 } else {
777 for (size_t i = 0; i < mInFlightMap.size(); i++) {
778 InFlightRequest r = mInFlightMap.valueAt(i);
Colin Crosse5729fa2014-03-21 15:04:25 -0700779 lines.appendFormat(" Frame %d | Timestamp: %" PRId64 ", metadata"
Greg Kaiser51b882c2020-06-10 05:41:44 +0000780 " arrived: %s, buffers left: %d\n", mInFlightMap.keyAt(i),
Chien-Yu Chen43e69a62014-11-25 16:38:33 -0800781 r.shutterTimestamp, r.haveResultMetadata ? "true" : "false",
Greg Kaiser51b882c2020-06-10 05:41:44 +0000782 r.numBuffersLeft);
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700783 }
784 }
785 write(fd, lines.string(), lines.size());
786
Shuzhen Wang686f6442017-06-20 16:16:04 -0700787 if (mRequestThread != NULL) {
788 mRequestThread->dumpCaptureRequestLatency(fd,
789 " ProcessCaptureRequest latency histogram:");
790 }
791
Igor Murashkin1e479c02013-09-06 16:55:14 -0700792 {
793 lines = String8(" Last request sent:\n");
794 write(fd, lines.string(), lines.size());
795
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700796 CameraMetadata lastRequest = getLatestRequestLocked();
Igor Murashkin1e479c02013-09-06 16:55:14 -0700797 lastRequest.dump(fd, /*verbosity*/2, /*indentation*/6);
798 }
799
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800800 if (dumpTemplates) {
Emilian Peevf4816702020-04-03 15:44:51 -0700801 const char *templateNames[CAMERA_TEMPLATE_COUNT] = {
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800802 "TEMPLATE_PREVIEW",
803 "TEMPLATE_STILL_CAPTURE",
804 "TEMPLATE_VIDEO_RECORD",
805 "TEMPLATE_VIDEO_SNAPSHOT",
806 "TEMPLATE_ZERO_SHUTTER_LAG",
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -0800807 "TEMPLATE_MANUAL",
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800808 };
809
Emilian Peevf4816702020-04-03 15:44:51 -0700810 for (int i = 1; i < CAMERA_TEMPLATE_COUNT; i++) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800811 camera_metadata_t *templateRequest = nullptr;
812 mInterface->constructDefaultRequestSettings(
Emilian Peevf4816702020-04-03 15:44:51 -0700813 (camera_request_template_t) i, &templateRequest);
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800814 lines = String8::format(" HAL Request %s:\n", templateNames[i-1]);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800815 if (templateRequest == nullptr) {
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800816 lines.append(" Not supported\n");
817 write(fd, lines.string(), lines.size());
818 } else {
819 write(fd, lines.string(), lines.size());
820 dump_indented_camera_metadata(templateRequest,
821 fd, /*verbosity*/2, /*indentation*/8);
822 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800823 free_camera_metadata(templateRequest);
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800824 }
825 }
826
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700827 mTagMonitor.dumpMonitoredMetadata(fd);
828
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800829 if (mInterface->valid()) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -0800830 lines = String8(" HAL device dump:\n");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800831 write(fd, lines.string(), lines.size());
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800832 mInterface->dump(fd);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800833 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800834
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700835 if (gotLock) mLock.unlock();
836 if (gotInterfaceLock) mInterfaceLock.unlock();
837
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800838 return OK;
839}
840
Emilian Peevfaa4bde2020-01-23 12:19:37 -0800841const CameraMetadata& Camera3Device::infoPhysical(const String8& physicalId) const {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800842 ALOGVV("%s: E", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800843 if (CC_UNLIKELY(mStatus == STATUS_UNINITIALIZED ||
844 mStatus == STATUS_ERROR)) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700845 ALOGW("%s: Access to static info %s!", __FUNCTION__,
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800846 mStatus == STATUS_ERROR ?
847 "when in error state" : "before init");
848 }
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700849 if (physicalId.isEmpty()) {
850 return mDeviceInfo;
851 } else {
852 std::string id(physicalId.c_str());
853 if (mPhysicalDeviceInfoMap.find(id) != mPhysicalDeviceInfoMap.end()) {
854 return mPhysicalDeviceInfoMap.at(id);
855 } else {
856 ALOGE("%s: Invalid physical camera id %s", __FUNCTION__, physicalId.c_str());
857 return mDeviceInfo;
858 }
859 }
860}
861
862const CameraMetadata& Camera3Device::info() const {
863 String8 emptyId;
Emilian Peevfaa4bde2020-01-23 12:19:37 -0800864 return infoPhysical(emptyId);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800865}
866
Jianing Wei90e59c92014-03-12 18:29:36 -0700867status_t Camera3Device::checkStatusOkToCaptureLocked() {
868 switch (mStatus) {
869 case STATUS_ERROR:
870 CLOGE("Device has encountered a serious error");
871 return INVALID_OPERATION;
872 case STATUS_UNINITIALIZED:
873 CLOGE("Device not initialized");
874 return INVALID_OPERATION;
875 case STATUS_UNCONFIGURED:
876 case STATUS_CONFIGURED:
877 case STATUS_ACTIVE:
878 // OK
879 break;
880 default:
881 SET_ERR_L("Unexpected status: %d", mStatus);
882 return INVALID_OPERATION;
883 }
884 return OK;
885}
886
887status_t Camera3Device::convertMetadataListToRequestListLocked(
Emilian Peevaebbe412018-01-15 13:53:24 +0000888 const List<const PhysicalCameraSettingsList> &metadataList,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700889 const std::list<const SurfaceMap> &surfaceMaps,
Shuzhen Wang316781a2020-08-18 18:11:01 -0700890 bool repeating, nsecs_t requestTimeNs,
Shuzhen Wang9d066012016-09-30 11:30:20 -0700891 RequestList *requestList) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700892 if (requestList == NULL) {
893 CLOGE("requestList cannot be NULL.");
894 return BAD_VALUE;
895 }
896
Jianing Weicb0652e2014-03-12 18:29:36 -0700897 int32_t burstId = 0;
Emilian Peevaebbe412018-01-15 13:53:24 +0000898 List<const PhysicalCameraSettingsList>::const_iterator metadataIt = metadataList.begin();
Shuzhen Wang0129d522016-10-30 22:43:41 -0700899 std::list<const SurfaceMap>::const_iterator surfaceMapIt = surfaceMaps.begin();
900 for (; metadataIt != metadataList.end() && surfaceMapIt != surfaceMaps.end();
901 ++metadataIt, ++surfaceMapIt) {
902 sp<CaptureRequest> newRequest = setUpRequestLocked(*metadataIt, *surfaceMapIt);
Jianing Wei90e59c92014-03-12 18:29:36 -0700903 if (newRequest == 0) {
904 CLOGE("Can't create capture request");
905 return BAD_VALUE;
906 }
Jianing Weicb0652e2014-03-12 18:29:36 -0700907
Shuzhen Wang9d066012016-09-30 11:30:20 -0700908 newRequest->mRepeating = repeating;
Shuzhen Wang316781a2020-08-18 18:11:01 -0700909 newRequest->mRequestTimeNs = requestTimeNs;
Shuzhen Wang9d066012016-09-30 11:30:20 -0700910
Jianing Weicb0652e2014-03-12 18:29:36 -0700911 // Setup burst Id and request Id
912 newRequest->mResultExtras.burstId = burstId++;
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -0800913 auto requestIdEntry = metadataIt->begin()->metadata.find(ANDROID_REQUEST_ID);
914 if (requestIdEntry.count == 0) {
Jianing Weicb0652e2014-03-12 18:29:36 -0700915 CLOGE("RequestID does not exist in metadata");
916 return BAD_VALUE;
917 }
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -0800918 newRequest->mResultExtras.requestId = requestIdEntry.data.i32[0];
Jianing Weicb0652e2014-03-12 18:29:36 -0700919
Jianing Wei90e59c92014-03-12 18:29:36 -0700920 requestList->push_back(newRequest);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700921
922 ALOGV("%s: requestId = %" PRId32, __FUNCTION__, newRequest->mResultExtras.requestId);
Jianing Wei90e59c92014-03-12 18:29:36 -0700923 }
Shuzhen Wang0129d522016-10-30 22:43:41 -0700924 if (metadataIt != metadataList.end() || surfaceMapIt != surfaceMaps.end()) {
925 ALOGE("%s: metadataList and surfaceMaps are not the same size!", __FUNCTION__);
926 return BAD_VALUE;
927 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -0700928
929 // Setup batch size if this is a high speed video recording request.
930 if (mIsConstrainedHighSpeedConfiguration && requestList->size() > 0) {
931 auto firstRequest = requestList->begin();
932 for (auto& outputStream : (*firstRequest)->mOutputStreams) {
933 if (outputStream->isVideoStream()) {
934 (*firstRequest)->mBatchSize = requestList->size();
Yin-Chia Yeh14ef48d2020-02-10 15:06:37 -0800935 outputStream->setBatchSize(requestList->size());
Chien-Yu Chen85a64552015-08-28 15:46:12 -0700936 break;
937 }
938 }
939 }
940
Jianing Wei90e59c92014-03-12 18:29:36 -0700941 return OK;
942}
943
Yin-Chia Yeh7e5a2042019-02-06 16:01:06 -0800944status_t Camera3Device::capture(CameraMetadata &request, int64_t* lastFrameNumber) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800945 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800946
Emilian Peevaebbe412018-01-15 13:53:24 +0000947 List<const PhysicalCameraSettingsList> requestsList;
Shuzhen Wang0129d522016-10-30 22:43:41 -0700948 std::list<const SurfaceMap> surfaceMaps;
Emilian Peevaebbe412018-01-15 13:53:24 +0000949 convertToRequestList(requestsList, surfaceMaps, request);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700950
Yin-Chia Yeh7e5a2042019-02-06 16:01:06 -0800951 return captureList(requestsList, surfaceMaps, lastFrameNumber);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700952}
953
Emilian Peevaebbe412018-01-15 13:53:24 +0000954void Camera3Device::convertToRequestList(List<const PhysicalCameraSettingsList>& requestsList,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700955 std::list<const SurfaceMap>& surfaceMaps,
956 const CameraMetadata& request) {
Emilian Peevaebbe412018-01-15 13:53:24 +0000957 PhysicalCameraSettingsList requestList;
958 requestList.push_back({std::string(getId().string()), request});
959 requestsList.push_back(requestList);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700960
961 SurfaceMap surfaceMap;
962 camera_metadata_ro_entry streams = request.find(ANDROID_REQUEST_OUTPUT_STREAMS);
963 // With no surface list passed in, stream and surface will have 1-to-1
964 // mapping. So the surface index is 0 for each stream in the surfaceMap.
965 for (size_t i = 0; i < streams.count; i++) {
966 surfaceMap[streams.data.i32[i]].push_back(0);
967 }
968 surfaceMaps.push_back(surfaceMap);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800969}
970
Jianing Wei90e59c92014-03-12 18:29:36 -0700971status_t Camera3Device::submitRequestsHelper(
Emilian Peevaebbe412018-01-15 13:53:24 +0000972 const List<const PhysicalCameraSettingsList> &requests,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700973 const std::list<const SurfaceMap> &surfaceMaps,
974 bool repeating,
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700975 /*out*/
976 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700977 ATRACE_CALL();
Shuzhen Wang316781a2020-08-18 18:11:01 -0700978 nsecs_t requestTimeNs = systemTime();
979
Jianing Wei90e59c92014-03-12 18:29:36 -0700980 Mutex::Autolock il(mInterfaceLock);
981 Mutex::Autolock l(mLock);
982
983 status_t res = checkStatusOkToCaptureLocked();
984 if (res != OK) {
985 // error logged by previous call
986 return res;
987 }
988
989 RequestList requestList;
990
Shuzhen Wang0129d522016-10-30 22:43:41 -0700991 res = convertMetadataListToRequestListLocked(requests, surfaceMaps,
Shuzhen Wang316781a2020-08-18 18:11:01 -0700992 repeating, requestTimeNs, /*out*/&requestList);
Jianing Wei90e59c92014-03-12 18:29:36 -0700993 if (res != OK) {
994 // error logged by previous call
995 return res;
996 }
997
998 if (repeating) {
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700999 res = mRequestThread->setRepeatingRequests(requestList, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -07001000 } else {
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07001001 res = mRequestThread->queueRequestList(requestList, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -07001002 }
1003
1004 if (res == OK) {
1005 waitUntilStateThenRelock(/*active*/true, kActiveTimeout);
1006 if (res != OK) {
1007 SET_ERR_L("Can't transition to active in %f seconds!",
1008 kActiveTimeout/1e9);
1009 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001010 ALOGV("Camera %s: Capture request %" PRId32 " enqueued", mId.string(),
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07001011 (*(requestList.begin()))->mResultExtras.requestId);
Jianing Wei90e59c92014-03-12 18:29:36 -07001012 } else {
1013 CLOGE("Cannot queue request. Impossible.");
1014 return BAD_VALUE;
1015 }
1016
1017 return res;
1018}
1019
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001020hardware::Return<void> Camera3Device::requestStreamBuffers(
1021 const hardware::hidl_vec<hardware::camera::device::V3_5::BufferRequest>& bufReqs,
1022 requestStreamBuffers_cb _hidl_cb) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001023 RequestBufferStates states {
Shuzhen Wang316781a2020-08-18 18:11:01 -07001024 mId, mRequestBufferInterfaceLock, mUseHalBufManager, mOutputStreams, mSessionStatsBuilder,
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001025 *this, *mInterface, *this};
1026 camera3::requestStreamBuffers(states, bufReqs, _hidl_cb);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001027 return hardware::Void();
1028}
1029
1030hardware::Return<void> Camera3Device::returnStreamBuffers(
1031 const hardware::hidl_vec<hardware::camera::device::V3_2::StreamBuffer>& buffers) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001032 ReturnBufferStates states {
Shuzhen Wang316781a2020-08-18 18:11:01 -07001033 mId, mUseHalBufManager, mOutputStreams, mSessionStatsBuilder, *mInterface};
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001034 camera3::returnStreamBuffers(states, buffers);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001035 return hardware::Void();
1036}
1037
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001038hardware::Return<void> Camera3Device::processCaptureResult_3_4(
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001039 const hardware::hidl_vec<
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001040 hardware::camera::device::V3_4::CaptureResult>& results) {
Yin-Chia Yeh657c1872017-07-18 18:09:57 -07001041 // Ideally we should grab mLock, but that can lead to deadlock, and
1042 // it's not super important to get up to date value of mStatus for this
1043 // warning print, hence skipping the lock here
1044 if (mStatus == STATUS_ERROR) {
1045 // Per API contract, HAL should act as closed after device error
1046 // But mStatus can be set to error by framework as well, so just log
1047 // a warning here.
1048 ALOGW("%s: received capture result in error state.", __FUNCTION__);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07001049 }
Yifan Honga640c5a2017-04-12 16:30:31 -07001050
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001051 sp<NotificationListener> listener;
1052 {
1053 std::lock_guard<std::mutex> l(mOutputLock);
1054 listener = mListener.promote();
1055 }
1056
Yifan Honga640c5a2017-04-12 16:30:31 -07001057 if (mProcessCaptureResultLock.tryLock() != OK) {
1058 // This should never happen; it indicates a wrong client implementation
1059 // that doesn't follow the contract. But, we can be tolerant here.
1060 ALOGE("%s: callback overlapped! waiting 1s...",
1061 __FUNCTION__);
1062 if (mProcessCaptureResultLock.timedLock(1000000000 /* 1s */) != OK) {
1063 ALOGE("%s: cannot acquire lock in 1s, dropping results",
1064 __FUNCTION__);
1065 // really don't know what to do, so bail out.
1066 return hardware::Void();
1067 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001068 }
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001069 CaptureOutputStates states {
1070 mId,
Shuzhen Wangb7b42652020-05-07 11:59:02 -07001071 mInFlightLock, mLastCompletedRegularFrameNumber,
1072 mLastCompletedReprocessFrameNumber, mLastCompletedZslFrameNumber,
1073 mInFlightMap, mOutputLock, mResultQueue, mResultSignal,
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001074 mNextShutterFrameNumber,
1075 mNextReprocessShutterFrameNumber, mNextZslStillShutterFrameNumber,
1076 mNextResultFrameNumber,
1077 mNextReprocessResultFrameNumber, mNextZslStillResultFrameNumber,
1078 mUseHalBufManager, mUsePartialResult, mNeedFixupMonochromeTags,
1079 mNumPartialResults, mVendorTagId, mDeviceInfo, mPhysicalDeviceInfoMap,
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08001080 mResultMetadataQueue, mDistortionMappers, mZoomRatioMappers, mRotateAndCropMappers,
Shuzhen Wang316781a2020-08-18 18:11:01 -07001081 mTagMonitor, mInputStream, mOutputStreams, mSessionStatsBuilder, listener, *this, *this,
1082 *mInterface
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001083 };
1084
Yifan Honga640c5a2017-04-12 16:30:31 -07001085 for (const auto& result : results) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001086 processOneCaptureResultLocked(states, result.v3_2, result.physicalCameraMetadata);
Yifan Honga640c5a2017-04-12 16:30:31 -07001087 }
1088 mProcessCaptureResultLock.unlock();
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001089 return hardware::Void();
1090}
1091
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001092// Only one processCaptureResult should be called at a time, so
1093// the locks won't block. The locks are present here simply to enforce this.
1094hardware::Return<void> Camera3Device::processCaptureResult(
1095 const hardware::hidl_vec<
1096 hardware::camera::device::V3_2::CaptureResult>& results) {
1097 hardware::hidl_vec<hardware::camera::device::V3_4::PhysicalCameraMetadata> noPhysMetadata;
1098
1099 // Ideally we should grab mLock, but that can lead to deadlock, and
1100 // it's not super important to get up to date value of mStatus for this
1101 // warning print, hence skipping the lock here
1102 if (mStatus == STATUS_ERROR) {
1103 // Per API contract, HAL should act as closed after device error
1104 // But mStatus can be set to error by framework as well, so just log
1105 // a warning here.
1106 ALOGW("%s: received capture result in error state.", __FUNCTION__);
1107 }
1108
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001109 sp<NotificationListener> listener;
1110 {
1111 std::lock_guard<std::mutex> l(mOutputLock);
1112 listener = mListener.promote();
1113 }
1114
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001115 if (mProcessCaptureResultLock.tryLock() != OK) {
1116 // This should never happen; it indicates a wrong client implementation
1117 // that doesn't follow the contract. But, we can be tolerant here.
1118 ALOGE("%s: callback overlapped! waiting 1s...",
1119 __FUNCTION__);
1120 if (mProcessCaptureResultLock.timedLock(1000000000 /* 1s */) != OK) {
1121 ALOGE("%s: cannot acquire lock in 1s, dropping results",
1122 __FUNCTION__);
1123 // really don't know what to do, so bail out.
1124 return hardware::Void();
1125 }
1126 }
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001127
1128 CaptureOutputStates states {
1129 mId,
Shuzhen Wangb7b42652020-05-07 11:59:02 -07001130 mInFlightLock, mLastCompletedRegularFrameNumber,
1131 mLastCompletedReprocessFrameNumber, mLastCompletedZslFrameNumber,
1132 mInFlightMap, mOutputLock, mResultQueue, mResultSignal,
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001133 mNextShutterFrameNumber,
1134 mNextReprocessShutterFrameNumber, mNextZslStillShutterFrameNumber,
1135 mNextResultFrameNumber,
1136 mNextReprocessResultFrameNumber, mNextZslStillResultFrameNumber,
1137 mUseHalBufManager, mUsePartialResult, mNeedFixupMonochromeTags,
1138 mNumPartialResults, mVendorTagId, mDeviceInfo, mPhysicalDeviceInfoMap,
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08001139 mResultMetadataQueue, mDistortionMappers, mZoomRatioMappers, mRotateAndCropMappers,
Shuzhen Wang316781a2020-08-18 18:11:01 -07001140 mTagMonitor, mInputStream, mOutputStreams, mSessionStatsBuilder, listener, *this, *this,
1141 *mInterface
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001142 };
1143
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001144 for (const auto& result : results) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001145 processOneCaptureResultLocked(states, result, noPhysMetadata);
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001146 }
1147 mProcessCaptureResultLock.unlock();
1148 return hardware::Void();
1149}
1150
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001151hardware::Return<void> Camera3Device::notify(
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001152 const hardware::hidl_vec<hardware::camera::device::V3_2::NotifyMsg>& msgs) {
Yin-Chia Yeh657c1872017-07-18 18:09:57 -07001153 // Ideally we should grab mLock, but that can lead to deadlock, and
1154 // it's not super important to get up to date value of mStatus for this
1155 // warning print, hence skipping the lock here
1156 if (mStatus == STATUS_ERROR) {
1157 // Per API contract, HAL should act as closed after device error
1158 // But mStatus can be set to error by framework as well, so just log
1159 // a warning here.
1160 ALOGW("%s: received notify message in error state.", __FUNCTION__);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07001161 }
Yin-Chia Yeh657c1872017-07-18 18:09:57 -07001162
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001163 sp<NotificationListener> listener;
1164 {
1165 std::lock_guard<std::mutex> l(mOutputLock);
1166 listener = mListener.promote();
1167 }
1168
1169 CaptureOutputStates states {
1170 mId,
Shuzhen Wangb7b42652020-05-07 11:59:02 -07001171 mInFlightLock, mLastCompletedRegularFrameNumber,
1172 mLastCompletedReprocessFrameNumber, mLastCompletedZslFrameNumber,
1173 mInFlightMap, mOutputLock, mResultQueue, mResultSignal,
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001174 mNextShutterFrameNumber,
1175 mNextReprocessShutterFrameNumber, mNextZslStillShutterFrameNumber,
1176 mNextResultFrameNumber,
1177 mNextReprocessResultFrameNumber, mNextZslStillResultFrameNumber,
1178 mUseHalBufManager, mUsePartialResult, mNeedFixupMonochromeTags,
1179 mNumPartialResults, mVendorTagId, mDeviceInfo, mPhysicalDeviceInfoMap,
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08001180 mResultMetadataQueue, mDistortionMappers, mZoomRatioMappers, mRotateAndCropMappers,
Shuzhen Wang316781a2020-08-18 18:11:01 -07001181 mTagMonitor, mInputStream, mOutputStreams, mSessionStatsBuilder, listener, *this, *this,
1182 *mInterface
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001183 };
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001184 for (const auto& msg : msgs) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001185 camera3::notify(states, msg);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001186 }
1187 return hardware::Void();
1188}
1189
Emilian Peevaebbe412018-01-15 13:53:24 +00001190status_t Camera3Device::captureList(const List<const PhysicalCameraSettingsList> &requestsList,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001191 const std::list<const SurfaceMap> &surfaceMaps,
Jianing Weicb0652e2014-03-12 18:29:36 -07001192 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -07001193 ATRACE_CALL();
1194
Emilian Peevaebbe412018-01-15 13:53:24 +00001195 return submitRequestsHelper(requestsList, surfaceMaps, /*repeating*/false, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -07001196}
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001197
Jianing Weicb0652e2014-03-12 18:29:36 -07001198status_t Camera3Device::setStreamingRequest(const CameraMetadata &request,
1199 int64_t* /*lastFrameNumber*/) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001200 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001201
Emilian Peevaebbe412018-01-15 13:53:24 +00001202 List<const PhysicalCameraSettingsList> requestsList;
Shuzhen Wang0129d522016-10-30 22:43:41 -07001203 std::list<const SurfaceMap> surfaceMaps;
Emilian Peevaebbe412018-01-15 13:53:24 +00001204 convertToRequestList(requestsList, surfaceMaps, request);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001205
Emilian Peevaebbe412018-01-15 13:53:24 +00001206 return setStreamingRequestList(requestsList, /*surfaceMap*/surfaceMaps,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001207 /*lastFrameNumber*/NULL);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001208}
1209
Emilian Peevaebbe412018-01-15 13:53:24 +00001210status_t Camera3Device::setStreamingRequestList(
1211 const List<const PhysicalCameraSettingsList> &requestsList,
1212 const std::list<const SurfaceMap> &surfaceMaps, int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -07001213 ATRACE_CALL();
1214
Emilian Peevaebbe412018-01-15 13:53:24 +00001215 return submitRequestsHelper(requestsList, surfaceMaps, /*repeating*/true, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -07001216}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001217
1218sp<Camera3Device::CaptureRequest> Camera3Device::setUpRequestLocked(
Emilian Peevaebbe412018-01-15 13:53:24 +00001219 const PhysicalCameraSettingsList &request, const SurfaceMap &surfaceMap) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001220 status_t res;
1221
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001222 if (mStatus == STATUS_UNCONFIGURED || mNeedConfig) {
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08001223 // This point should only be reached via API1 (API2 must explicitly call configureStreams)
1224 // so unilaterally select normal operating mode.
Emilian Peevaebbe412018-01-15 13:53:24 +00001225 res = filterParamsAndConfigureLocked(request.begin()->metadata,
Emilian Peevf4816702020-04-03 15:44:51 -07001226 CAMERA_STREAM_CONFIGURATION_NORMAL_MODE);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001227 // Stream configuration failed. Client might try other configuraitons.
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001228 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001229 CLOGE("Can't set up streams: %s (%d)", strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001230 return NULL;
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001231 } else if (mStatus == STATUS_UNCONFIGURED) {
1232 // Stream configuration successfully configure to empty stream configuration.
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001233 CLOGE("No streams configured");
1234 return NULL;
1235 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001236 }
1237
Shuzhen Wang0129d522016-10-30 22:43:41 -07001238 sp<CaptureRequest> newRequest = createCaptureRequest(request, surfaceMap);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001239 return newRequest;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001240}
1241
Jianing Weicb0652e2014-03-12 18:29:36 -07001242status_t Camera3Device::clearStreamingRequest(int64_t *lastFrameNumber) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001243 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001244 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001245 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001246
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001247 switch (mStatus) {
1248 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001249 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001250 return INVALID_OPERATION;
1251 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001252 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001253 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001254 case STATUS_UNCONFIGURED:
1255 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001256 case STATUS_ACTIVE:
1257 // OK
1258 break;
1259 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001260 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001261 return INVALID_OPERATION;
1262 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001263 ALOGV("Camera %s: Clearing repeating request", mId.string());
Jianing Weicb0652e2014-03-12 18:29:36 -07001264
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07001265 return mRequestThread->clearRepeatingRequests(lastFrameNumber);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001266}
1267
1268status_t Camera3Device::waitUntilRequestReceived(int32_t requestId, nsecs_t timeout) {
1269 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001270 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001271
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001272 return mRequestThread->waitUntilRequestProcessed(requestId, timeout);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001273}
1274
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001275status_t Camera3Device::createInputStream(
Shuzhen Wang83bff122020-11-20 15:51:39 -08001276 uint32_t width, uint32_t height, int format, bool isMultiResolution, int *id) {
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001277 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001278 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001279 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001280 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001281 ALOGV("Camera %s: Creating new input stream %d: %d x %d, format %d",
1282 mId.string(), mNextStreamId, width, height, format);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001283
1284 status_t res;
1285 bool wasActive = false;
1286
1287 switch (mStatus) {
1288 case STATUS_ERROR:
1289 ALOGE("%s: Device has encountered a serious error", __FUNCTION__);
1290 return INVALID_OPERATION;
1291 case STATUS_UNINITIALIZED:
1292 ALOGE("%s: Device not initialized", __FUNCTION__);
1293 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001294 case STATUS_UNCONFIGURED:
1295 case STATUS_CONFIGURED:
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001296 // OK
1297 break;
1298 case STATUS_ACTIVE:
1299 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001300 res = internalPauseAndWaitLocked(maxExpectedDuration);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001301 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001302 SET_ERR_L("Can't pause captures to reconfigure streams!");
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001303 return res;
1304 }
1305 wasActive = true;
1306 break;
1307 default:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001308 SET_ERR_L("%s: Unexpected status: %d", mStatus);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001309 return INVALID_OPERATION;
1310 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001311 assert(mStatus != STATUS_ACTIVE);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001312
1313 if (mInputStream != 0) {
1314 ALOGE("%s: Cannot create more than 1 input stream", __FUNCTION__);
1315 return INVALID_OPERATION;
1316 }
1317
1318 sp<Camera3InputStream> newStream = new Camera3InputStream(mNextStreamId,
1319 width, height, format);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001320 newStream->setStatusTracker(mStatusTracker);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001321
1322 mInputStream = newStream;
Shuzhen Wang83bff122020-11-20 15:51:39 -08001323 mIsInputStreamMultiResolution = isMultiResolution;
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001324
1325 *id = mNextStreamId++;
1326
1327 // Continue captures if active at start
1328 if (wasActive) {
1329 ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001330 // Reuse current operating mode and session parameters for new stream config
1331 res = configureStreamsLocked(mOperatingMode, mSessionParams);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001332 if (res != OK) {
1333 ALOGE("%s: Can't reconfigure device for new stream %d: %s (%d)",
1334 __FUNCTION__, mNextStreamId, strerror(-res), res);
1335 return res;
1336 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001337 internalResumeLocked();
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001338 }
1339
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001340 ALOGV("Camera %s: Created input stream", mId.string());
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001341 return OK;
1342}
1343
Eino-Ville Talvala727d1722015-06-09 13:44:19 -07001344status_t Camera3Device::createStream(sp<Surface> consumer,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001345 uint32_t width, uint32_t height, int format,
Emilian Peevf4816702020-04-03 15:44:51 -07001346 android_dataspace dataSpace, camera_stream_rotation_t rotation, int *id,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001347 const String8& physicalCameraId,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001348 const std::unordered_set<int32_t> &sensorPixelModesUsed,
1349 std::vector<int> *surfaceIds, int streamSetId, bool isShared, bool isMultiResolution,
1350 uint64_t consumerUsage) {
Shuzhen Wang0129d522016-10-30 22:43:41 -07001351 ATRACE_CALL();
1352
1353 if (consumer == nullptr) {
1354 ALOGE("%s: consumer must not be null", __FUNCTION__);
1355 return BAD_VALUE;
1356 }
1357
1358 std::vector<sp<Surface>> consumers;
1359 consumers.push_back(consumer);
1360
1361 return createStream(consumers, /*hasDeferredConsumer*/ false, width, height,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001362 format, dataSpace, rotation, id, physicalCameraId, sensorPixelModesUsed, surfaceIds,
1363 streamSetId, isShared, isMultiResolution, consumerUsage);
1364}
1365
1366static bool isRawFormat(int format) {
1367 switch (format) {
1368 case HAL_PIXEL_FORMAT_RAW16:
1369 case HAL_PIXEL_FORMAT_RAW12:
1370 case HAL_PIXEL_FORMAT_RAW10:
1371 case HAL_PIXEL_FORMAT_RAW_OPAQUE:
1372 return true;
1373 default:
1374 return false;
1375 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001376}
1377
1378status_t Camera3Device::createStream(const std::vector<sp<Surface>>& consumers,
1379 bool hasDeferredConsumer, uint32_t width, uint32_t height, int format,
Emilian Peevf4816702020-04-03 15:44:51 -07001380 android_dataspace dataSpace, camera_stream_rotation_t rotation, int *id,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001381 const String8& physicalCameraId, const std::unordered_set<int32_t> &sensorPixelModesUsed,
Shuzhen Wang83bff122020-11-20 15:51:39 -08001382 std::vector<int> *surfaceIds, int streamSetId, bool isShared, bool isMultiResolution,
1383 uint64_t consumerUsage) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001384 ATRACE_CALL();
Emilian Peev40ead602017-09-26 15:46:36 +01001385
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001386 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001387 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001388 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001389 ALOGV("Camera %s: Creating new stream %d: %d x %d, format %d, dataspace %d rotation %d"
Shuzhen Wang83bff122020-11-20 15:51:39 -08001390 " consumer usage %" PRIu64 ", isShared %d, physicalCameraId %s, isMultiResolution %d",
1391 mId.string(), mNextStreamId, width, height, format, dataSpace, rotation,
1392 consumerUsage, isShared, physicalCameraId.string(), isMultiResolution);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001393
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001394 status_t res;
1395 bool wasActive = false;
1396
1397 switch (mStatus) {
1398 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001399 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001400 return INVALID_OPERATION;
1401 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001402 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001403 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001404 case STATUS_UNCONFIGURED:
1405 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001406 // OK
1407 break;
1408 case STATUS_ACTIVE:
1409 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001410 res = internalPauseAndWaitLocked(maxExpectedDuration);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001411 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001412 SET_ERR_L("Can't pause captures to reconfigure streams!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001413 return res;
1414 }
1415 wasActive = true;
1416 break;
1417 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001418 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001419 return INVALID_OPERATION;
1420 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001421 assert(mStatus != STATUS_ACTIVE);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001422
1423 sp<Camera3OutputStream> newStream;
Zhijun He5d677d12016-05-29 16:52:39 -07001424
Shuzhen Wang0129d522016-10-30 22:43:41 -07001425 if (consumers.size() == 0 && !hasDeferredConsumer) {
1426 ALOGE("%s: Number of consumers cannot be smaller than 1", __FUNCTION__);
1427 return BAD_VALUE;
1428 }
Zhijun He5d677d12016-05-29 16:52:39 -07001429
Shuzhen Wang0129d522016-10-30 22:43:41 -07001430 if (hasDeferredConsumer && format != HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
Zhijun He5d677d12016-05-29 16:52:39 -07001431 ALOGE("Deferred consumer stream creation only support IMPLEMENTATION_DEFINED format");
1432 return BAD_VALUE;
1433 }
1434
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001435 if (isRawFormat(format) && sensorPixelModesUsed.size() > 1) {
1436 // We can't use one stream with a raw format in both sensor pixel modes since its going to
1437 // be found in only one sensor pixel mode.
1438 ALOGE("%s: RAW opaque stream cannot be used with > 1 sensor pixel modes", __FUNCTION__);
1439 return BAD_VALUE;
1440 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001441 if (format == HAL_PIXEL_FORMAT_BLOB) {
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -07001442 ssize_t blobBufferSize;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001443 if (dataSpace == HAL_DATASPACE_DEPTH) {
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -07001444 blobBufferSize = getPointCloudBufferSize();
1445 if (blobBufferSize <= 0) {
1446 SET_ERR_L("Invalid point cloud buffer size %zd", blobBufferSize);
1447 return BAD_VALUE;
1448 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001449 } else if (dataSpace == static_cast<android_dataspace>(HAL_DATASPACE_JPEG_APP_SEGMENTS)) {
1450 blobBufferSize = width * height;
1451 } else {
1452 blobBufferSize = getJpegBufferSize(width, height);
1453 if (blobBufferSize <= 0) {
1454 SET_ERR_L("Invalid jpeg buffer size %zd", blobBufferSize);
1455 return BAD_VALUE;
1456 }
Zhijun Hef7da0962014-04-24 13:27:56 -07001457 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001458 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001459 width, height, blobBufferSize, format, dataSpace, rotation,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001460 mTimestampOffset, physicalCameraId, sensorPixelModesUsed, streamSetId,
1461 isMultiResolution);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -08001462 } else if (format == HAL_PIXEL_FORMAT_RAW_OPAQUE) {
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001463 bool maxResolution =
1464 sensorPixelModesUsed.find(ANDROID_SENSOR_PIXEL_MODE_MAXIMUM_RESOLUTION) !=
1465 sensorPixelModesUsed.end();
1466 ssize_t rawOpaqueBufferSize = getRawOpaqueBufferSize(width, height, maxResolution);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -08001467 if (rawOpaqueBufferSize <= 0) {
1468 SET_ERR_L("Invalid RAW opaque buffer size %zd", rawOpaqueBufferSize);
1469 return BAD_VALUE;
1470 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001471 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001472 width, height, rawOpaqueBufferSize, format, dataSpace, rotation,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001473 mTimestampOffset, physicalCameraId, sensorPixelModesUsed, streamSetId,
1474 isMultiResolution);
Shuzhen Wang758c2152017-01-10 18:26:18 -08001475 } else if (isShared) {
1476 newStream = new Camera3SharedOutputStream(mNextStreamId, consumers,
1477 width, height, format, consumerUsage, dataSpace, rotation,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001478 mTimestampOffset, physicalCameraId, sensorPixelModesUsed, streamSetId,
1479 mUseHalBufManager);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001480 } else if (consumers.size() == 0 && hasDeferredConsumer) {
Zhijun He5d677d12016-05-29 16:52:39 -07001481 newStream = new Camera3OutputStream(mNextStreamId,
1482 width, height, format, consumerUsage, dataSpace, rotation,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001483 mTimestampOffset, physicalCameraId, sensorPixelModesUsed, streamSetId,
1484 isMultiResolution);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001485 } else {
Shuzhen Wang0129d522016-10-30 22:43:41 -07001486 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001487 width, height, format, dataSpace, rotation,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001488 mTimestampOffset, physicalCameraId, sensorPixelModesUsed, streamSetId,
1489 isMultiResolution);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001490 }
Emilian Peev40ead602017-09-26 15:46:36 +01001491
1492 size_t consumerCount = consumers.size();
1493 for (size_t i = 0; i < consumerCount; i++) {
1494 int id = newStream->getSurfaceId(consumers[i]);
1495 if (id < 0) {
1496 SET_ERR_L("Invalid surface id");
1497 return BAD_VALUE;
1498 }
1499 if (surfaceIds != nullptr) {
1500 surfaceIds->push_back(id);
1501 }
1502 }
1503
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001504 newStream->setStatusTracker(mStatusTracker);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001505
Emilian Peev08dd2452017-04-06 16:55:14 +01001506 newStream->setBufferManager(mBufferManager);
Zhijun He125684a2015-12-26 15:07:30 -08001507
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08001508 newStream->setImageDumpMask(mImageDumpMask);
1509
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001510 res = mOutputStreams.add(mNextStreamId, newStream);
1511 if (res < 0) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001512 SET_ERR_L("Can't add new stream to set: %s (%d)", strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001513 return res;
1514 }
1515
Shuzhen Wang316781a2020-08-18 18:11:01 -07001516 mSessionStatsBuilder.addStream(mNextStreamId);
1517
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001518 *id = mNextStreamId++;
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07001519 mNeedConfig = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001520
1521 // Continue captures if active at start
1522 if (wasActive) {
1523 ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001524 // Reuse current operating mode and session parameters for new stream config
1525 res = configureStreamsLocked(mOperatingMode, mSessionParams);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001526 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001527 CLOGE("Can't reconfigure device for new stream %d: %s (%d)",
1528 mNextStreamId, strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001529 return res;
1530 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001531 internalResumeLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001532 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001533 ALOGV("Camera %s: Created new stream", mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001534 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001535}
1536
Emilian Peev710c1422017-08-30 11:19:38 +01001537status_t Camera3Device::getStreamInfo(int id, StreamInfo *streamInfo) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001538 ATRACE_CALL();
Emilian Peev710c1422017-08-30 11:19:38 +01001539 if (nullptr == streamInfo) {
1540 return BAD_VALUE;
1541 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001542 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001543 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001544
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001545 switch (mStatus) {
1546 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001547 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001548 return INVALID_OPERATION;
1549 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001550 CLOGE("Device not initialized!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001551 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001552 case STATUS_UNCONFIGURED:
1553 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001554 case STATUS_ACTIVE:
1555 // OK
1556 break;
1557 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001558 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001559 return INVALID_OPERATION;
1560 }
1561
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001562 sp<Camera3StreamInterface> stream = mOutputStreams.get(id);
1563 if (stream == nullptr) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001564 CLOGE("Stream %d is unknown", id);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001565 return BAD_VALUE;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001566 }
1567
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001568 streamInfo->width = stream->getWidth();
1569 streamInfo->height = stream->getHeight();
1570 streamInfo->format = stream->getFormat();
1571 streamInfo->dataSpace = stream->getDataSpace();
1572 streamInfo->formatOverridden = stream->isFormatOverridden();
1573 streamInfo->originalFormat = stream->getOriginalFormat();
1574 streamInfo->dataSpaceOverridden = stream->isDataSpaceOverridden();
1575 streamInfo->originalDataSpace = stream->getOriginalDataSpace();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001576 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001577}
1578
1579status_t Camera3Device::setStreamTransform(int id,
1580 int transform) {
1581 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001582 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001583 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001584
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001585 switch (mStatus) {
1586 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001587 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001588 return INVALID_OPERATION;
1589 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001590 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001591 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001592 case STATUS_UNCONFIGURED:
1593 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001594 case STATUS_ACTIVE:
1595 // OK
1596 break;
1597 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001598 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001599 return INVALID_OPERATION;
1600 }
1601
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001602 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(id);
1603 if (stream == nullptr) {
1604 CLOGE("Stream %d does not exist", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001605 return BAD_VALUE;
1606 }
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001607 return stream->setTransform(transform);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001608}
1609
1610status_t Camera3Device::deleteStream(int id) {
1611 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001612 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001613 Mutex::Autolock l(mLock);
1614 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001615
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001616 ALOGV("%s: Camera %s: Deleting stream %d", __FUNCTION__, mId.string(), id);
Igor Murashkine2172be2013-05-28 15:31:39 -07001617
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001618 // CameraDevice semantics require device to already be idle before
1619 // deleteStream is called, unlike for createStream.
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001620 if (mStatus == STATUS_ACTIVE) {
Yin-Chia Yeh693047d2018-03-08 12:14:19 -08001621 ALOGW("%s: Camera %s: Device not idle", __FUNCTION__, mId.string());
Igor Murashkin52827132013-05-13 14:53:44 -07001622 return -EBUSY;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001623 }
1624
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07001625 if (mStatus == STATUS_ERROR) {
1626 ALOGW("%s: Camera %s: deleteStream not allowed in ERROR state",
1627 __FUNCTION__, mId.string());
1628 return -EBUSY;
1629 }
1630
Igor Murashkin2fba5842013-04-22 14:03:54 -07001631 sp<Camera3StreamInterface> deletedStream;
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001632 sp<Camera3StreamInterface> stream = mOutputStreams.get(id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001633 if (mInputStream != NULL && id == mInputStream->getId()) {
1634 deletedStream = mInputStream;
1635 mInputStream.clear();
1636 } else {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001637 if (stream == nullptr) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001638 CLOGE("Stream %d does not exist", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001639 return BAD_VALUE;
1640 }
Shuzhen Wang316781a2020-08-18 18:11:01 -07001641 mSessionStatsBuilder.removeStream(id);
Zhijun He5f446352014-01-22 09:49:33 -08001642 }
1643
1644 // Delete output stream or the output part of a bi-directional stream.
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001645 if (stream != nullptr) {
1646 deletedStream = stream;
1647 mOutputStreams.remove(id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001648 }
1649
1650 // Free up the stream endpoint so that it can be used by some other stream
1651 res = deletedStream->disconnect();
1652 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001653 SET_ERR_L("Can't disconnect deleted stream %d", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001654 // fall through since we want to still list the stream as deleted.
1655 }
1656 mDeletedStreams.add(deletedStream);
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07001657 mNeedConfig = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001658
1659 return res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001660}
1661
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001662status_t Camera3Device::configureStreams(const CameraMetadata& sessionParams, int operatingMode) {
Igor Murashkine2d167e2014-08-19 16:19:59 -07001663 ATRACE_CALL();
1664 ALOGV("%s: E", __FUNCTION__);
1665
1666 Mutex::Autolock il(mInterfaceLock);
1667 Mutex::Autolock l(mLock);
Chien-Yu Chen17338fc2015-06-18 16:30:12 -07001668
Emilian Peev811d2952018-05-25 11:08:40 +01001669 // In case the client doesn't include any session parameter, try a
1670 // speculative configuration using the values from the last cached
1671 // default request.
1672 if (sessionParams.isEmpty() &&
Emilian Peevf4816702020-04-03 15:44:51 -07001673 ((mLastTemplateId > 0) && (mLastTemplateId < CAMERA_TEMPLATE_COUNT)) &&
Emilian Peev811d2952018-05-25 11:08:40 +01001674 (!mRequestTemplateCache[mLastTemplateId].isEmpty())) {
1675 ALOGV("%s: Speculative session param configuration with template id: %d", __func__,
1676 mLastTemplateId);
1677 return filterParamsAndConfigureLocked(mRequestTemplateCache[mLastTemplateId],
1678 operatingMode);
1679 }
1680
Emilian Peevac3ce6c2017-12-12 15:27:02 +00001681 return filterParamsAndConfigureLocked(sessionParams, operatingMode);
1682}
1683
1684status_t Camera3Device::filterParamsAndConfigureLocked(const CameraMetadata& sessionParams,
1685 int operatingMode) {
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001686 //Filter out any incoming session parameters
1687 const CameraMetadata params(sessionParams);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001688 camera_metadata_entry_t availableSessionKeys = mDeviceInfo.find(
1689 ANDROID_REQUEST_AVAILABLE_SESSION_KEYS);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00001690 CameraMetadata filteredParams(availableSessionKeys.count);
1691 camera_metadata_t *meta = const_cast<camera_metadata_t *>(
1692 filteredParams.getAndLock());
1693 set_camera_metadata_vendor_id(meta, mVendorTagId);
1694 filteredParams.unlock(meta);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001695 if (availableSessionKeys.count > 0) {
1696 for (size_t i = 0; i < availableSessionKeys.count; i++) {
1697 camera_metadata_ro_entry entry = params.find(
1698 availableSessionKeys.data.i32[i]);
1699 if (entry.count > 0) {
1700 filteredParams.update(entry);
1701 }
1702 }
1703 }
1704
1705 return configureStreamsLocked(operatingMode, filteredParams);
Igor Murashkine2d167e2014-08-19 16:19:59 -07001706}
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001707
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07001708status_t Camera3Device::getInputBufferProducer(
1709 sp<IGraphicBufferProducer> *producer) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07001710 ATRACE_CALL();
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07001711 Mutex::Autolock il(mInterfaceLock);
1712 Mutex::Autolock l(mLock);
1713
1714 if (producer == NULL) {
1715 return BAD_VALUE;
1716 } else if (mInputStream == NULL) {
1717 return INVALID_OPERATION;
1718 }
1719
1720 return mInputStream->getInputBufferProducer(producer);
1721}
1722
Emilian Peevf4816702020-04-03 15:44:51 -07001723status_t Camera3Device::createDefaultRequest(camera_request_template_t templateId,
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001724 CameraMetadata *request) {
1725 ATRACE_CALL();
Alex Rayfe7e0c62013-05-30 00:12:13 -07001726 ALOGV("%s: for template %d", __FUNCTION__, templateId);
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08001727
Emilian Peevf4816702020-04-03 15:44:51 -07001728 if (templateId <= 0 || templateId >= CAMERA_TEMPLATE_COUNT) {
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08001729 android_errorWriteWithInfoLog(CameraService::SN_EVENT_LOG_ID, "26866110",
Jayant Chowdhary12361932018-08-27 14:46:13 -07001730 CameraThreadState::getCallingUid(), nullptr, 0);
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08001731 return BAD_VALUE;
1732 }
1733
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001734 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001735
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001736 {
1737 Mutex::Autolock l(mLock);
1738 switch (mStatus) {
1739 case STATUS_ERROR:
1740 CLOGE("Device has encountered a serious error");
1741 return INVALID_OPERATION;
1742 case STATUS_UNINITIALIZED:
1743 CLOGE("Device is not initialized!");
1744 return INVALID_OPERATION;
1745 case STATUS_UNCONFIGURED:
1746 case STATUS_CONFIGURED:
1747 case STATUS_ACTIVE:
1748 // OK
1749 break;
1750 default:
1751 SET_ERR_L("Unexpected status: %d", mStatus);
1752 return INVALID_OPERATION;
1753 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001754
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001755 if (!mRequestTemplateCache[templateId].isEmpty()) {
1756 *request = mRequestTemplateCache[templateId];
Emilian Peev811d2952018-05-25 11:08:40 +01001757 mLastTemplateId = templateId;
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001758 return OK;
1759 }
Zhijun Hea1530f12014-09-14 12:44:20 -07001760 }
1761
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001762 camera_metadata_t *rawRequest;
1763 status_t res = mInterface->constructDefaultRequestSettings(
Emilian Peevf4816702020-04-03 15:44:51 -07001764 (camera_request_template_t) templateId, &rawRequest);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001765
1766 {
1767 Mutex::Autolock l(mLock);
1768 if (res == BAD_VALUE) {
1769 ALOGI("%s: template %d is not supported on this camera device",
1770 __FUNCTION__, templateId);
1771 return res;
1772 } else if (res != OK) {
1773 CLOGE("Unable to construct request template %d: %s (%d)",
1774 templateId, strerror(-res), res);
1775 return res;
1776 }
1777
1778 set_camera_metadata_vendor_id(rawRequest, mVendorTagId);
1779 mRequestTemplateCache[templateId].acquire(rawRequest);
1780
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08001781 // Override the template request with zoomRatioMapper
1782 res = mZoomRatioMappers[mId.c_str()].initZoomRatioInTemplate(
1783 &mRequestTemplateCache[templateId]);
1784 if (res != OK) {
1785 CLOGE("Failed to update zoom ratio for template %d: %s (%d)",
1786 templateId, strerror(-res), res);
1787 return res;
1788 }
1789
Shuzhen Wangd25dc972020-03-24 17:11:43 -07001790 // Fill in JPEG_QUALITY if not available
1791 if (!mRequestTemplateCache[templateId].exists(ANDROID_JPEG_QUALITY)) {
1792 static const uint8_t kDefaultJpegQuality = 95;
1793 mRequestTemplateCache[templateId].update(ANDROID_JPEG_QUALITY,
1794 &kDefaultJpegQuality, 1);
1795 }
1796
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001797 *request = mRequestTemplateCache[templateId];
Emilian Peev811d2952018-05-25 11:08:40 +01001798 mLastTemplateId = templateId;
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001799 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001800 return OK;
1801}
1802
1803status_t Camera3Device::waitUntilDrained() {
1804 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001805 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001806 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001807 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001808
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001809 return waitUntilDrainedLocked(maxExpectedDuration);
Zhijun He69a37482014-03-23 18:44:49 -07001810}
1811
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001812status_t Camera3Device::waitUntilDrainedLocked(nsecs_t maxExpectedDuration) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001813 switch (mStatus) {
1814 case STATUS_UNINITIALIZED:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001815 case STATUS_UNCONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001816 ALOGV("%s: Already idle", __FUNCTION__);
1817 return OK;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001818 case STATUS_CONFIGURED:
1819 // To avoid race conditions, check with tracker to be sure
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001820 case STATUS_ERROR:
1821 case STATUS_ACTIVE:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001822 // Need to verify shut down
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001823 break;
1824 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001825 SET_ERR_L("Unexpected status: %d",mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001826 return INVALID_OPERATION;
1827 }
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07001828 ALOGV("%s: Camera %s: Waiting until idle (%" PRIi64 "ns)", __FUNCTION__, mId.string(),
1829 maxExpectedDuration);
1830 status_t res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
Eino-Ville Talvala9c8a0912014-09-14 14:52:19 -07001831 if (res != OK) {
Yin-Chia Yeh87b3ec02019-06-03 10:44:39 -07001832 mStatusTracker->dumpActiveComponents();
Eino-Ville Talvala9c8a0912014-09-14 14:52:19 -07001833 SET_ERR_L("Error waiting for HAL to drain: %s (%d)", strerror(-res),
1834 res);
1835 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001836 return res;
1837}
1838
Ruben Brunk183f0562015-08-12 12:55:02 -07001839void Camera3Device::internalUpdateStatusLocked(Status status) {
1840 mStatus = status;
1841 mRecentStatusUpdates.add(mStatus);
1842 mStatusChanged.broadcast();
1843}
1844
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001845// Pause to reconfigure
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001846status_t Camera3Device::internalPauseAndWaitLocked(nsecs_t maxExpectedDuration) {
Emilian Peeve86358b2019-02-15 13:51:39 -08001847 if (mRequestThread.get() != nullptr) {
1848 mRequestThread->setPaused(true);
1849 } else {
1850 return NO_INIT;
1851 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001852
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07001853 ALOGV("%s: Camera %s: Internal wait until idle (% " PRIi64 " ns)", __FUNCTION__, mId.string(),
1854 maxExpectedDuration);
1855 status_t res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001856 if (res != OK) {
1857 SET_ERR_L("Can't idle device in %f seconds!",
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07001858 maxExpectedDuration/1e9);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001859 }
1860
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001861 return res;
1862}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001863
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001864// Resume after internalPauseAndWaitLocked
1865status_t Camera3Device::internalResumeLocked() {
1866 status_t res;
1867
1868 mRequestThread->setPaused(false);
1869
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08001870 ALOGV("%s: Camera %s: Internal wait until active (% " PRIi64 " ns)", __FUNCTION__, mId.string(),
1871 kActiveTimeout);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001872 res = waitUntilStateThenRelock(/*active*/ true, kActiveTimeout);
1873 if (res != OK) {
1874 SET_ERR_L("Can't transition to active in %f seconds!",
1875 kActiveTimeout/1e9);
1876 }
1877 mPauseStateNotify = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001878 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001879}
1880
Ruben Brunk183f0562015-08-12 12:55:02 -07001881status_t Camera3Device::waitUntilStateThenRelock(bool active, nsecs_t timeout) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001882 status_t res = OK;
Ruben Brunk183f0562015-08-12 12:55:02 -07001883
1884 size_t startIndex = 0;
1885 if (mStatusWaiters == 0) {
1886 // Clear the list of recent statuses if there are no existing threads waiting on updates to
1887 // this status list
1888 mRecentStatusUpdates.clear();
1889 } else {
1890 // If other threads are waiting on updates to this status list, set the position of the
1891 // first element that this list will check rather than clearing the list.
1892 startIndex = mRecentStatusUpdates.size();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001893 }
1894
Ruben Brunk183f0562015-08-12 12:55:02 -07001895 mStatusWaiters++;
1896
Yin-Chia Yehe52b8fa2020-07-28 00:17:58 -07001897 bool signalPipelineDrain = false;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07001898 if (!active && mUseHalBufManager) {
1899 auto streamIds = mOutputStreams.getStreamIds();
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08001900 if (mStatus == STATUS_ACTIVE) {
1901 mRequestThread->signalPipelineDrain(streamIds);
Yin-Chia Yehe52b8fa2020-07-28 00:17:58 -07001902 signalPipelineDrain = true;
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08001903 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07001904 mRequestBufferSM.onWaitUntilIdle();
1905 }
1906
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001907 bool stateSeen = false;
1908 do {
Ruben Brunk183f0562015-08-12 12:55:02 -07001909 if (active == (mStatus == STATUS_ACTIVE)) {
1910 // Desired state is current
1911 break;
1912 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001913
1914 res = mStatusChanged.waitRelative(mLock, timeout);
1915 if (res != OK) break;
1916
Ruben Brunk183f0562015-08-12 12:55:02 -07001917 // This is impossible, but if not, could result in subtle deadlocks and invalid state
1918 // transitions.
1919 LOG_ALWAYS_FATAL_IF(startIndex > mRecentStatusUpdates.size(),
1920 "%s: Skipping status updates in Camera3Device, may result in deadlock.",
1921 __FUNCTION__);
1922
1923 // Encountered desired state since we began waiting
1924 for (size_t i = startIndex; i < mRecentStatusUpdates.size(); i++) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001925 if (active == (mRecentStatusUpdates[i] == STATUS_ACTIVE) ) {
1926 stateSeen = true;
1927 break;
1928 }
1929 }
1930 } while (!stateSeen);
1931
Yin-Chia Yehe52b8fa2020-07-28 00:17:58 -07001932 if (signalPipelineDrain) {
1933 mRequestThread->resetPipelineDrain();
1934 }
1935
Ruben Brunk183f0562015-08-12 12:55:02 -07001936 mStatusWaiters--;
1937
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001938 return res;
1939}
1940
1941
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001942status_t Camera3Device::setNotifyCallback(wp<NotificationListener> listener) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001943 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001944 std::lock_guard<std::mutex> l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001945
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001946 if (listener != NULL && mListener != NULL) {
1947 ALOGW("%s: Replacing old callback listener", __FUNCTION__);
1948 }
1949 mListener = listener;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001950 mRequestThread->setNotificationListener(listener);
1951 mPreparerThread->setNotificationListener(listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001952
1953 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001954}
1955
Eino-Ville Talvala46910bd2013-07-18 19:15:17 -07001956bool Camera3Device::willNotify3A() {
1957 return false;
1958}
1959
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001960status_t Camera3Device::waitForNextFrame(nsecs_t timeout) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07001961 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001962 std::unique_lock<std::mutex> l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001963
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001964 while (mResultQueue.empty()) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001965 auto st = mResultSignal.wait_for(l, std::chrono::nanoseconds(timeout));
1966 if (st == std::cv_status::timeout) {
1967 return TIMED_OUT;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001968 }
1969 }
1970 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001971}
1972
Jianing Weicb0652e2014-03-12 18:29:36 -07001973status_t Camera3Device::getNextResult(CaptureResult *frame) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001974 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001975 std::lock_guard<std::mutex> l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001976
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001977 if (mResultQueue.empty()) {
1978 return NOT_ENOUGH_DATA;
1979 }
1980
Jianing Weicb0652e2014-03-12 18:29:36 -07001981 if (frame == NULL) {
1982 ALOGE("%s: argument cannot be NULL", __FUNCTION__);
1983 return BAD_VALUE;
1984 }
1985
1986 CaptureResult &result = *(mResultQueue.begin());
1987 frame->mResultExtras = result.mResultExtras;
1988 frame->mMetadata.acquire(result.mMetadata);
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001989 frame->mPhysicalMetadatas = std::move(result.mPhysicalMetadatas);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001990 mResultQueue.erase(mResultQueue.begin());
1991
1992 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001993}
1994
1995status_t Camera3Device::triggerAutofocus(uint32_t id) {
1996 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001997 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001998
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001999 ALOGV("%s: Triggering autofocus, id %d", __FUNCTION__, id);
2000 // Mix-in this trigger into the next request and only the next request.
2001 RequestTrigger trigger[] = {
2002 {
2003 ANDROID_CONTROL_AF_TRIGGER,
2004 ANDROID_CONTROL_AF_TRIGGER_START
2005 },
2006 {
2007 ANDROID_CONTROL_AF_TRIGGER_ID,
2008 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07002009 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002010 };
2011
2012 return mRequestThread->queueTrigger(trigger,
2013 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002014}
2015
2016status_t Camera3Device::triggerCancelAutofocus(uint32_t id) {
2017 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002018 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002019
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002020 ALOGV("%s: Triggering cancel autofocus, id %d", __FUNCTION__, id);
2021 // Mix-in this trigger into the next request and only the next request.
2022 RequestTrigger trigger[] = {
2023 {
2024 ANDROID_CONTROL_AF_TRIGGER,
2025 ANDROID_CONTROL_AF_TRIGGER_CANCEL
2026 },
2027 {
2028 ANDROID_CONTROL_AF_TRIGGER_ID,
2029 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07002030 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002031 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002032
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002033 return mRequestThread->queueTrigger(trigger,
2034 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002035}
2036
2037status_t Camera3Device::triggerPrecaptureMetering(uint32_t id) {
2038 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002039 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002040
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002041 ALOGV("%s: Triggering precapture metering, id %d", __FUNCTION__, id);
2042 // Mix-in this trigger into the next request and only the next request.
2043 RequestTrigger trigger[] = {
2044 {
2045 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER,
2046 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_START
2047 },
2048 {
2049 ANDROID_CONTROL_AE_PRECAPTURE_ID,
2050 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07002051 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002052 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002053
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002054 return mRequestThread->queueTrigger(trigger,
2055 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002056}
2057
Jianing Weicb0652e2014-03-12 18:29:36 -07002058status_t Camera3Device::flush(int64_t *frameNumber) {
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07002059 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002060 ALOGV("%s: Camera %s: Flushing all requests", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002061 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07002062
Zhijun He7ef20392014-04-21 16:04:17 -07002063 {
2064 Mutex::Autolock l(mLock);
Emilian Peeved2ebe42018-09-25 16:59:09 +01002065
2066 // b/116514106 "disconnect()" can get called twice for the same device. The
2067 // camera device will not be initialized during the second run.
2068 if (mStatus == STATUS_UNINITIALIZED) {
2069 return OK;
2070 }
2071
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002072 mRequestThread->clear(/*out*/frameNumber);
Shuzhen Wang316781a2020-08-18 18:11:01 -07002073
2074 // Stop session and stream counter
2075 mSessionStatsBuilder.stopCounter();
Zhijun He7ef20392014-04-21 16:04:17 -07002076 }
2077
Emilian Peev08dd2452017-04-06 16:55:14 +01002078 return mRequestThread->flush();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07002079}
2080
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002081status_t Camera3Device::prepare(int streamId) {
Ruben Brunkc78ac262015-08-13 17:58:46 -07002082 return prepare(camera3::Camera3StreamInterface::ALLOCATE_PIPELINE_MAX, streamId);
2083}
2084
2085status_t Camera3Device::prepare(int maxCount, int streamId) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002086 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002087 ALOGV("%s: Camera %s: Preparing stream %d", __FUNCTION__, mId.string(), streamId);
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07002088 Mutex::Autolock il(mInterfaceLock);
2089 Mutex::Autolock l(mLock);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002090
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002091 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
2092 if (stream == nullptr) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002093 CLOGE("Stream %d does not exist", streamId);
2094 return BAD_VALUE;
2095 }
2096
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002097 if (stream->isUnpreparable() || stream->hasOutstandingBuffers() ) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07002098 CLOGE("Stream %d has already been a request target", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002099 return BAD_VALUE;
2100 }
2101
2102 if (mRequestThread->isStreamPending(stream)) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07002103 CLOGE("Stream %d is already a target in a pending request", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002104 return BAD_VALUE;
2105 }
2106
Ruben Brunkc78ac262015-08-13 17:58:46 -07002107 return mPreparerThread->prepare(maxCount, stream);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002108}
2109
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002110status_t Camera3Device::tearDown(int streamId) {
2111 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002112 ALOGV("%s: Camera %s: Tearing down stream %d", __FUNCTION__, mId.string(), streamId);
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002113 Mutex::Autolock il(mInterfaceLock);
2114 Mutex::Autolock l(mLock);
2115
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002116 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
2117 if (stream == nullptr) {
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002118 CLOGE("Stream %d does not exist", streamId);
2119 return BAD_VALUE;
2120 }
2121
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002122 if (stream->hasOutstandingBuffers() || mRequestThread->isStreamPending(stream)) {
2123 CLOGE("Stream %d is a target of a in-progress request", streamId);
2124 return BAD_VALUE;
2125 }
2126
2127 return stream->tearDown();
2128}
2129
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002130status_t Camera3Device::addBufferListenerForStream(int streamId,
2131 wp<Camera3StreamBufferListener> listener) {
2132 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002133 ALOGV("%s: Camera %s: Adding buffer listener for stream %d", __FUNCTION__, mId.string(), streamId);
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002134 Mutex::Autolock il(mInterfaceLock);
2135 Mutex::Autolock l(mLock);
2136
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002137 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
2138 if (stream == nullptr) {
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002139 CLOGE("Stream %d does not exist", streamId);
2140 return BAD_VALUE;
2141 }
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002142 stream->addBufferListener(listener);
2143
2144 return OK;
2145}
2146
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002147/**
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002148 * Methods called by subclasses
2149 */
2150
2151void Camera3Device::notifyStatus(bool idle) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002152 ATRACE_CALL();
Shuzhen Wang316781a2020-08-18 18:11:01 -07002153 std::vector<int> streamIds;
2154 std::vector<hardware::CameraStreamStats> streamStats;
2155
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002156 {
2157 // Need mLock to safely update state and synchronize to current
2158 // state of methods in flight.
2159 Mutex::Autolock l(mLock);
2160 // We can get various system-idle notices from the status tracker
2161 // while starting up. Only care about them if we've actually sent
2162 // in some requests recently.
2163 if (mStatus != STATUS_ACTIVE && mStatus != STATUS_CONFIGURED) {
2164 return;
2165 }
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08002166 ALOGV("%s: Camera %s: Now %s, pauseState: %s", __FUNCTION__, mId.string(),
2167 idle ? "idle" : "active", mPauseStateNotify ? "true" : "false");
Ruben Brunk183f0562015-08-12 12:55:02 -07002168 internalUpdateStatusLocked(idle ? STATUS_CONFIGURED : STATUS_ACTIVE);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002169
2170 // Skip notifying listener if we're doing some user-transparent
2171 // state changes
2172 if (mPauseStateNotify) return;
Shuzhen Wang316781a2020-08-18 18:11:01 -07002173
2174 // Populate stream statistics in case of Idle
2175 if (idle) {
2176 for (size_t i = 0; i < mOutputStreams.size(); i++) {
2177 auto stream = mOutputStreams[i];
2178 if (stream.get() == nullptr) continue;
2179 streamIds.push_back(stream->getId());
2180 Camera3Stream* camera3Stream = Camera3Stream::cast(stream->asHalStream());
2181 int64_t usage = 0LL;
2182 if (camera3Stream != nullptr) {
2183 usage = camera3Stream->getUsage();
2184 }
2185 streamStats.emplace_back(stream->getWidth(), stream->getHeight(),
2186 stream->getFormat(), stream->getDataSpace(), usage,
2187 stream->getMaxHalBuffers(),
2188 stream->getMaxTotalBuffers() - stream->getMaxHalBuffers());
2189 }
2190 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002191 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002192
2193 sp<NotificationListener> listener;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002194 {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002195 std::lock_guard<std::mutex> l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002196 listener = mListener.promote();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002197 }
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07002198 status_t res = OK;
2199 if (listener != nullptr) {
2200 if (idle) {
2201 // Get session stats from the builder, and notify the listener.
2202 int64_t requestCount, resultErrorCount;
2203 bool deviceError;
2204 std::map<int, StreamStats> streamStatsMap;
2205 mSessionStatsBuilder.buildAndReset(&requestCount, &resultErrorCount,
2206 &deviceError, &streamStatsMap);
2207 for (size_t i = 0; i < streamIds.size(); i++) {
2208 int streamId = streamIds[i];
2209 auto stats = streamStatsMap.find(streamId);
2210 if (stats != streamStatsMap.end()) {
2211 streamStats[i].mRequestCount = stats->second.mRequestedFrameCount;
2212 streamStats[i].mErrorCount = stats->second.mDroppedFrameCount;
2213 streamStats[i].mStartLatencyMs = stats->second.mStartLatencyMs;
2214 streamStats[i].mHistogramType =
2215 hardware::CameraStreamStats::HISTOGRAM_TYPE_CAPTURE_LATENCY;
2216 streamStats[i].mHistogramBins.assign(
2217 stats->second.mCaptureLatencyBins.begin(),
2218 stats->second.mCaptureLatencyBins.end());
2219 streamStats[i].mHistogramCounts.assign(
2220 stats->second.mCaptureLatencyHistogram.begin(),
2221 stats->second.mCaptureLatencyHistogram.end());
2222 }
Shuzhen Wang316781a2020-08-18 18:11:01 -07002223 }
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07002224 listener->notifyIdle(requestCount, resultErrorCount, deviceError, streamStats);
2225 } else {
2226 res = listener->notifyActive();
Shuzhen Wang316781a2020-08-18 18:11:01 -07002227 }
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07002228 }
2229 if (res != OK) {
2230 SET_ERR("Camera access permission lost mid-operation: %s (%d)",
2231 strerror(-res), res);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002232 }
2233}
2234
Shuzhen Wang758c2152017-01-10 18:26:18 -08002235status_t Camera3Device::setConsumerSurfaces(int streamId,
Emilian Peev40ead602017-09-26 15:46:36 +01002236 const std::vector<sp<Surface>>& consumers, std::vector<int> *surfaceIds) {
Zhijun He5d677d12016-05-29 16:52:39 -07002237 ATRACE_CALL();
Shuzhen Wang758c2152017-01-10 18:26:18 -08002238 ALOGV("%s: Camera %s: set consumer surface for stream %d",
2239 __FUNCTION__, mId.string(), streamId);
Emilian Peev40ead602017-09-26 15:46:36 +01002240
2241 if (surfaceIds == nullptr) {
2242 return BAD_VALUE;
2243 }
2244
Zhijun He5d677d12016-05-29 16:52:39 -07002245 Mutex::Autolock il(mInterfaceLock);
2246 Mutex::Autolock l(mLock);
2247
Shuzhen Wang758c2152017-01-10 18:26:18 -08002248 if (consumers.size() == 0) {
2249 CLOGE("No consumer is passed!");
Zhijun He5d677d12016-05-29 16:52:39 -07002250 return BAD_VALUE;
2251 }
2252
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002253 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
2254 if (stream == nullptr) {
Zhijun He5d677d12016-05-29 16:52:39 -07002255 CLOGE("Stream %d is unknown", streamId);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002256 return BAD_VALUE;
Zhijun He5d677d12016-05-29 16:52:39 -07002257 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002258
2259 // isConsumerConfigurationDeferred will be off after setConsumers
2260 bool isDeferred = stream->isConsumerConfigurationDeferred();
Shuzhen Wang758c2152017-01-10 18:26:18 -08002261 status_t res = stream->setConsumers(consumers);
Zhijun He5d677d12016-05-29 16:52:39 -07002262 if (res != OK) {
2263 CLOGE("Stream %d set consumer failed (error %d %s) ", streamId, res, strerror(-res));
2264 return res;
2265 }
2266
Emilian Peev40ead602017-09-26 15:46:36 +01002267 for (auto &consumer : consumers) {
2268 int id = stream->getSurfaceId(consumer);
2269 if (id < 0) {
2270 CLOGE("Invalid surface id!");
2271 return BAD_VALUE;
2272 }
2273 surfaceIds->push_back(id);
2274 }
2275
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002276 if (isDeferred) {
Shuzhen Wang0129d522016-10-30 22:43:41 -07002277 if (!stream->isConfiguring()) {
2278 CLOGE("Stream %d was already fully configured.", streamId);
2279 return INVALID_OPERATION;
2280 }
Zhijun He5d677d12016-05-29 16:52:39 -07002281
Shuzhen Wang0129d522016-10-30 22:43:41 -07002282 res = stream->finishConfiguration();
2283 if (res != OK) {
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002284 // If finishConfiguration fails due to abandoned surface, do not set
2285 // device to error state.
2286 bool isSurfaceAbandoned =
2287 (res == NO_INIT || res == DEAD_OBJECT) && stream->isAbandoned();
2288 if (!isSurfaceAbandoned) {
2289 SET_ERR_L("Can't finish configuring output stream %d: %s (%d)",
2290 stream->getId(), strerror(-res), res);
2291 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07002292 return res;
2293 }
Zhijun He5d677d12016-05-29 16:52:39 -07002294 }
2295
2296 return OK;
2297}
2298
Emilian Peev40ead602017-09-26 15:46:36 +01002299status_t Camera3Device::updateStream(int streamId, const std::vector<sp<Surface>> &newSurfaces,
2300 const std::vector<OutputStreamInfo> &outputInfo,
2301 const std::vector<size_t> &removedSurfaceIds, KeyedVector<sp<Surface>, size_t> *outputMap) {
2302 Mutex::Autolock il(mInterfaceLock);
2303 Mutex::Autolock l(mLock);
2304
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002305 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
2306 if (stream == nullptr) {
Emilian Peev40ead602017-09-26 15:46:36 +01002307 CLOGE("Stream %d is unknown", streamId);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002308 return BAD_VALUE;
Emilian Peev40ead602017-09-26 15:46:36 +01002309 }
2310
2311 for (const auto &it : removedSurfaceIds) {
2312 if (mRequestThread->isOutputSurfacePending(streamId, it)) {
2313 CLOGE("Shared surface still part of a pending request!");
2314 return -EBUSY;
2315 }
2316 }
2317
Emilian Peev40ead602017-09-26 15:46:36 +01002318 status_t res = stream->updateStream(newSurfaces, outputInfo, removedSurfaceIds, outputMap);
2319 if (res != OK) {
2320 CLOGE("Stream %d failed to update stream (error %d %s) ",
2321 streamId, res, strerror(-res));
2322 if (res == UNKNOWN_ERROR) {
2323 SET_ERR_L("%s: Stream update failed to revert to previous output configuration!",
2324 __FUNCTION__);
2325 }
2326 return res;
2327 }
2328
2329 return res;
2330}
2331
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002332status_t Camera3Device::dropStreamBuffers(bool dropping, int streamId) {
2333 Mutex::Autolock il(mInterfaceLock);
2334 Mutex::Autolock l(mLock);
2335
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002336 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
2337 if (stream == nullptr) {
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002338 ALOGE("%s: Stream %d is not found.", __FUNCTION__, streamId);
2339 return BAD_VALUE;
2340 }
Shuzhen Wang316781a2020-08-18 18:11:01 -07002341
2342 if (dropping) {
2343 mSessionStatsBuilder.stopCounter(streamId);
2344 } else {
2345 mSessionStatsBuilder.startCounter(streamId);
2346 }
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002347 return stream->dropBuffers(dropping);
2348}
2349
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002350/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002351 * Camera3Device private methods
2352 */
2353
2354sp<Camera3Device::CaptureRequest> Camera3Device::createCaptureRequest(
Emilian Peevaebbe412018-01-15 13:53:24 +00002355 const PhysicalCameraSettingsList &request, const SurfaceMap &surfaceMap) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002356 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002357
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08002358 sp<CaptureRequest> newRequest = new CaptureRequest();
Emilian Peevaebbe412018-01-15 13:53:24 +00002359 newRequest->mSettingsList = request;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002360
2361 camera_metadata_entry_t inputStreams =
Emilian Peevaebbe412018-01-15 13:53:24 +00002362 newRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_INPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002363 if (inputStreams.count > 0) {
2364 if (mInputStream == NULL ||
Zhijun Hed1d64672013-09-06 15:00:01 -07002365 mInputStream->getId() != inputStreams.data.i32[0]) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002366 CLOGE("Request references unknown input stream %d",
2367 inputStreams.data.u8[0]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002368 return NULL;
2369 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002370
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002371 if (mInputStream->isConfiguring()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002372 SET_ERR_L("%s: input stream %d is not configured!",
2373 __FUNCTION__, mInputStream->getId());
2374 return NULL;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002375 }
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07002376 // Check if stream prepare is blocking requests.
2377 if (mInputStream->isBlockedByPrepare()) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002378 CLOGE("Request references an input stream that's being prepared!");
2379 return NULL;
2380 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002381
2382 newRequest->mInputStream = mInputStream;
Emilian Peevaebbe412018-01-15 13:53:24 +00002383 newRequest->mSettingsList.begin()->metadata.erase(ANDROID_REQUEST_INPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002384 }
2385
2386 camera_metadata_entry_t streams =
Emilian Peevaebbe412018-01-15 13:53:24 +00002387 newRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_OUTPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002388 if (streams.count == 0) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002389 CLOGE("Zero output streams specified!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002390 return NULL;
2391 }
2392
2393 for (size_t i = 0; i < streams.count; i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002394 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streams.data.i32[i]);
2395 if (stream == nullptr) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002396 CLOGE("Request references unknown stream %d",
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002397 streams.data.i32[i]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002398 return NULL;
2399 }
Zhijun He5d677d12016-05-29 16:52:39 -07002400 // It is illegal to include a deferred consumer output stream into a request
Shuzhen Wang0129d522016-10-30 22:43:41 -07002401 auto iter = surfaceMap.find(streams.data.i32[i]);
2402 if (iter != surfaceMap.end()) {
2403 const std::vector<size_t>& surfaces = iter->second;
2404 for (const auto& surface : surfaces) {
2405 if (stream->isConsumerConfigurationDeferred(surface)) {
2406 CLOGE("Stream %d surface %zu hasn't finished configuration yet "
2407 "due to deferred consumer", stream->getId(), surface);
2408 return NULL;
2409 }
2410 }
Yin-Chia Yeh0b287572018-10-15 12:38:13 -07002411 newRequest->mOutputSurfaces[streams.data.i32[i]] = surfaces;
Zhijun He5d677d12016-05-29 16:52:39 -07002412 }
2413
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002414 if (stream->isConfiguring()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002415 SET_ERR_L("%s: stream %d is not configured!", __FUNCTION__, stream->getId());
2416 return NULL;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002417 }
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07002418 // Check if stream prepare is blocking requests.
2419 if (stream->isBlockedByPrepare()) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002420 CLOGE("Request references an output stream that's being prepared!");
2421 return NULL;
2422 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002423
2424 newRequest->mOutputStreams.push(stream);
2425 }
Emilian Peevaebbe412018-01-15 13:53:24 +00002426 newRequest->mSettingsList.begin()->metadata.erase(ANDROID_REQUEST_OUTPUT_STREAMS);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07002427 newRequest->mBatchSize = 1;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002428
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08002429 auto rotateAndCropEntry =
2430 newRequest->mSettingsList.begin()->metadata.find(ANDROID_SCALER_ROTATE_AND_CROP);
2431 if (rotateAndCropEntry.count > 0 &&
2432 rotateAndCropEntry.data.u8[0] == ANDROID_SCALER_ROTATE_AND_CROP_AUTO) {
2433 newRequest->mRotateAndCropAuto = true;
2434 } else {
2435 newRequest->mRotateAndCropAuto = false;
2436 }
2437
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07002438 auto zoomRatioEntry =
2439 newRequest->mSettingsList.begin()->metadata.find(ANDROID_CONTROL_ZOOM_RATIO);
2440 if (zoomRatioEntry.count > 0 &&
2441 zoomRatioEntry.data.f[0] == 1.0f) {
2442 newRequest->mZoomRatioIs1x = true;
2443 } else {
2444 newRequest->mZoomRatioIs1x = false;
2445 }
2446
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08002447 if (mSupportCameraMute) {
2448 auto testPatternModeEntry =
2449 newRequest->mSettingsList.begin()->metadata.find(ANDROID_SENSOR_TEST_PATTERN_MODE);
2450 newRequest->mOriginalTestPatternMode = testPatternModeEntry.count > 0 ?
2451 testPatternModeEntry.data.i32[0] :
2452 ANDROID_SENSOR_TEST_PATTERN_MODE_OFF;
2453
2454 auto testPatternDataEntry =
2455 newRequest->mSettingsList.begin()->metadata.find(ANDROID_SENSOR_TEST_PATTERN_DATA);
2456 if (testPatternDataEntry.count > 0) {
2457 memcpy(newRequest->mOriginalTestPatternData, testPatternModeEntry.data.i32,
2458 sizeof(newRequest->mOriginalTestPatternData));
2459 } else {
2460 newRequest->mOriginalTestPatternData[0] = 0;
2461 newRequest->mOriginalTestPatternData[1] = 0;
2462 newRequest->mOriginalTestPatternData[2] = 0;
2463 newRequest->mOriginalTestPatternData[3] = 0;
2464 }
2465 }
2466
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002467 return newRequest;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002468}
2469
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002470void Camera3Device::cancelStreamsConfigurationLocked() {
2471 int res = OK;
2472 if (mInputStream != NULL && mInputStream->isConfiguring()) {
2473 res = mInputStream->cancelConfiguration();
2474 if (res != OK) {
2475 CLOGE("Can't cancel configuring input stream %d: %s (%d)",
2476 mInputStream->getId(), strerror(-res), res);
2477 }
2478 }
2479
2480 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002481 sp<Camera3OutputStreamInterface> outputStream = mOutputStreams[i];
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002482 if (outputStream->isConfiguring()) {
2483 res = outputStream->cancelConfiguration();
2484 if (res != OK) {
2485 CLOGE("Can't cancel configuring output stream %d: %s (%d)",
2486 outputStream->getId(), strerror(-res), res);
2487 }
2488 }
2489 }
2490
2491 // Return state to that at start of call, so that future configures
2492 // properly clean things up
2493 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
2494 mNeedConfig = true;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002495
2496 res = mPreparerThread->resume();
2497 if (res != OK) {
2498 ALOGE("%s: Camera %s: Preparer thread failed to resume!", __FUNCTION__, mId.string());
2499 }
2500}
2501
Emilian Peev0d0191e2020-04-21 17:01:18 -07002502bool Camera3Device::checkAbandonedStreamsLocked() {
2503 if ((mInputStream.get() != nullptr) && (mInputStream->isAbandoned())) {
2504 return true;
2505 }
2506
2507 for (size_t i = 0; i < mOutputStreams.size(); i++) {
2508 auto stream = mOutputStreams[i];
2509 if ((stream.get() != nullptr) && (stream->isAbandoned())) {
2510 return true;
2511 }
2512 }
2513
2514 return false;
2515}
2516
Emilian Peev3bead5f2020-05-28 17:29:08 -07002517bool Camera3Device::reconfigureCamera(const CameraMetadata& sessionParams, int clientStatusId) {
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002518 ATRACE_CALL();
2519 bool ret = false;
2520
Shuzhen Wang316781a2020-08-18 18:11:01 -07002521 nsecs_t startTime = systemTime();
2522
Jayant Chowdhary646c31b2020-01-30 13:09:59 -08002523 Mutex::Autolock il(mInterfaceLock);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002524 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
2525
2526 Mutex::Autolock l(mLock);
Emilian Peev0d0191e2020-04-21 17:01:18 -07002527 if (checkAbandonedStreamsLocked()) {
2528 ALOGW("%s: Abandoned stream detected, session parameters can't be applied correctly!",
2529 __FUNCTION__);
2530 return true;
2531 }
2532
Emilian Peev3bead5f2020-05-28 17:29:08 -07002533 status_t rc = NO_ERROR;
2534 bool markClientActive = false;
2535 if (mStatus == STATUS_ACTIVE) {
2536 markClientActive = true;
2537 mPauseStateNotify = true;
2538 mStatusTracker->markComponentIdle(clientStatusId, Fence::NO_FENCE);
2539
2540 rc = internalPauseAndWaitLocked(maxExpectedDuration);
2541 }
2542
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002543 if (rc == NO_ERROR) {
2544 mNeedConfig = true;
2545 rc = configureStreamsLocked(mOperatingMode, sessionParams, /*notifyRequestThread*/ false);
2546 if (rc == NO_ERROR) {
2547 ret = true;
2548 mPauseStateNotify = false;
2549 //Moving to active state while holding 'mLock' is important.
2550 //There could be pending calls to 'create-/deleteStream' which
2551 //will trigger another stream configuration while the already
2552 //present streams end up with outstanding buffers that will
2553 //not get drained.
2554 internalUpdateStatusLocked(STATUS_ACTIVE);
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002555 } else if (rc == DEAD_OBJECT) {
2556 // DEAD_OBJECT can be returned if either the consumer surface is
2557 // abandoned, or the HAL has died.
2558 // - If the HAL has died, configureStreamsLocked call will set
2559 // device to error state,
2560 // - If surface is abandoned, we should not set device to error
2561 // state.
2562 ALOGE("Failed to re-configure camera due to abandoned surface");
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002563 } else {
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002564 SET_ERR_L("Failed to re-configure camera: %d", rc);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002565 }
2566 } else {
2567 ALOGE("%s: Failed to pause streaming: %d", __FUNCTION__, rc);
2568 }
2569
Shuzhen Wang316781a2020-08-18 18:11:01 -07002570 CameraServiceProxyWrapper::logStreamConfigured(mId, mOperatingMode, true /*internalReconfig*/,
2571 ns2ms(systemTime() - startTime));
2572
Emilian Peev3bead5f2020-05-28 17:29:08 -07002573 if (markClientActive) {
2574 mStatusTracker->markComponentActive(clientStatusId);
2575 }
2576
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002577 return ret;
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002578}
2579
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002580status_t Camera3Device::configureStreamsLocked(int operatingMode,
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002581 const CameraMetadata& sessionParams, bool notifyRequestThread) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002582 ATRACE_CALL();
2583 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002584
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002585 if (mStatus != STATUS_UNCONFIGURED && mStatus != STATUS_CONFIGURED) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002586 CLOGE("Not idle");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002587 return INVALID_OPERATION;
2588 }
2589
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08002590 if (operatingMode < 0) {
2591 CLOGE("Invalid operating mode: %d", operatingMode);
2592 return BAD_VALUE;
2593 }
2594
2595 bool isConstrainedHighSpeed =
2596 static_cast<int>(StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE) ==
2597 operatingMode;
2598
2599 if (mOperatingMode != operatingMode) {
2600 mNeedConfig = true;
2601 mIsConstrainedHighSpeedConfiguration = isConstrainedHighSpeed;
2602 mOperatingMode = operatingMode;
2603 }
2604
Shuzhen Wang0cf01cb2019-09-05 13:33:06 -07002605 // In case called from configureStreams, abort queued input buffers not belonging to
2606 // any pending requests.
2607 if (mInputStream != NULL && notifyRequestThread) {
2608 while (true) {
Emilian Peevf4816702020-04-03 15:44:51 -07002609 camera_stream_buffer_t inputBuffer;
Shuzhen Wang83bff122020-11-20 15:51:39 -08002610 camera3::Size inputBufferSize;
Shuzhen Wang0cf01cb2019-09-05 13:33:06 -07002611 status_t res = mInputStream->getInputBuffer(&inputBuffer,
Shuzhen Wang83bff122020-11-20 15:51:39 -08002612 &inputBufferSize, /*respectHalLimit*/ false);
Shuzhen Wang0cf01cb2019-09-05 13:33:06 -07002613 if (res != OK) {
2614 // Exhausted acquiring all input buffers.
2615 break;
2616 }
2617
Emilian Peevf4816702020-04-03 15:44:51 -07002618 inputBuffer.status = CAMERA_BUFFER_STATUS_ERROR;
Shuzhen Wang0cf01cb2019-09-05 13:33:06 -07002619 res = mInputStream->returnInputBuffer(inputBuffer);
2620 if (res != OK) {
2621 ALOGE("%s: %d: couldn't return input buffer while clearing input queue: "
2622 "%s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
2623 }
2624 }
2625 }
2626
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002627 if (!mNeedConfig) {
2628 ALOGV("%s: Skipping config, no stream changes", __FUNCTION__);
2629 return OK;
2630 }
2631
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002632 // Workaround for device HALv3.2 or older spec bug - zero streams requires
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002633 // adding a fake stream instead.
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002634 // TODO: Bug: 17321404 for fixing the HAL spec and removing this workaround.
2635 if (mOutputStreams.size() == 0) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002636 addFakeStreamLocked();
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002637 } else {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002638 tryRemoveFakeStreamLocked();
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002639 }
2640
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002641 // Start configuring the streams
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002642 ALOGV("%s: Camera %s: Starting stream configuration", __FUNCTION__, mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002643
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002644 mPreparerThread->pause();
2645
Emilian Peevf4816702020-04-03 15:44:51 -07002646 camera_stream_configuration config;
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -08002647 config.operation_mode = mOperatingMode;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002648 config.num_streams = (mInputStream != NULL) + mOutputStreams.size();
Shuzhen Wang83bff122020-11-20 15:51:39 -08002649 config.input_is_multi_resolution = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002650
Emilian Peevf4816702020-04-03 15:44:51 -07002651 Vector<camera3::camera_stream_t*> streams;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002652 streams.setCapacity(config.num_streams);
Emilian Peev192ee832018-01-31 14:46:47 +00002653 std::vector<uint32_t> bufferSizes(config.num_streams, 0);
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002654
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002655
2656 if (mInputStream != NULL) {
Emilian Peevf4816702020-04-03 15:44:51 -07002657 camera3::camera_stream_t *inputStream;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002658 inputStream = mInputStream->startConfiguration();
2659 if (inputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002660 CLOGE("Can't start input stream configuration");
2661 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002662 return INVALID_OPERATION;
2663 }
2664 streams.add(inputStream);
Shuzhen Wang83bff122020-11-20 15:51:39 -08002665
2666 config.input_is_multi_resolution = mIsInputStreamMultiResolution;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002667 }
2668
Shuzhen Wang99080502021-03-07 21:08:20 -08002669 mGroupIdPhysicalCameraMap.clear();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002670 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Igor Murashkin2fba5842013-04-22 14:03:54 -07002671
2672 // Don't configure bidi streams twice, nor add them twice to the list
2673 if (mOutputStreams[i].get() ==
2674 static_cast<Camera3StreamInterface*>(mInputStream.get())) {
2675
2676 config.num_streams--;
2677 continue;
2678 }
2679
Emilian Peevf4816702020-04-03 15:44:51 -07002680 camera3::camera_stream_t *outputStream;
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002681 outputStream = mOutputStreams[i]->startConfiguration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002682 if (outputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002683 CLOGE("Can't start output stream configuration");
2684 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002685 return INVALID_OPERATION;
2686 }
2687 streams.add(outputStream);
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002688
Shuzhen Wangb7ab1e42019-02-20 15:42:23 -08002689 if (outputStream->format == HAL_PIXEL_FORMAT_BLOB) {
Emilian Peev192ee832018-01-31 14:46:47 +00002690 size_t k = i + ((mInputStream != nullptr) ? 1 : 0); // Input stream if present should
2691 // always occupy the initial entry.
Shuzhen Wangb7ab1e42019-02-20 15:42:23 -08002692 if (outputStream->data_space == HAL_DATASPACE_V0_JFIF) {
2693 bufferSizes[k] = static_cast<uint32_t>(
2694 getJpegBufferSize(outputStream->width, outputStream->height));
2695 } else if (outputStream->data_space ==
2696 static_cast<android_dataspace>(HAL_DATASPACE_JPEG_APP_SEGMENTS)) {
2697 bufferSizes[k] = outputStream->width * outputStream->height;
2698 } else {
2699 ALOGW("%s: Blob dataSpace %d not supported",
2700 __FUNCTION__, outputStream->data_space);
2701 }
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002702 }
Shuzhen Wang99080502021-03-07 21:08:20 -08002703
2704 if (mOutputStreams[i]->isMultiResolution()) {
2705 int32_t streamGroupId = mOutputStreams[i]->getHalStreamGroupId();
2706 const String8& physicalCameraId = mOutputStreams[i]->getPhysicalCameraId();
2707 mGroupIdPhysicalCameraMap[streamGroupId].insert(physicalCameraId);
2708 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002709 }
2710
2711 config.streams = streams.editArray();
2712
2713 // Do the HAL configuration; will potentially touch stream
Shuzhen Wang92653952019-05-07 15:11:43 -07002714 // max_buffers, usage, and priv fields, as well as data_space and format
2715 // fields for IMPLEMENTATION_DEFINED formats.
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002716
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002717 const camera_metadata_t *sessionBuffer = sessionParams.getAndLock();
Emilian Peev192ee832018-01-31 14:46:47 +00002718 res = mInterface->configureStreams(sessionBuffer, &config, bufferSizes);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002719 sessionParams.unlock(sessionBuffer);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002720
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002721 if (res == BAD_VALUE) {
2722 // HAL rejected this set of streams as unsupported, clean up config
2723 // attempt and return to unconfigured state
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002724 CLOGE("Set of requested inputs/outputs not supported by HAL");
2725 cancelStreamsConfigurationLocked();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002726 return BAD_VALUE;
2727 } else if (res != OK) {
2728 // Some other kind of error from configure_streams - this is not
2729 // expected
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002730 SET_ERR_L("Unable to configure streams with HAL: %s (%d)",
2731 strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002732 return res;
2733 }
2734
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002735 // Finish all stream configuration immediately.
2736 // TODO: Try to relax this later back to lazy completion, which should be
2737 // faster
2738
Igor Murashkin073f8572013-05-02 14:59:28 -07002739 if (mInputStream != NULL && mInputStream->isConfiguring()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002740 bool streamReConfigured = false;
2741 res = mInputStream->finishConfiguration(&streamReConfigured);
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002742 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002743 CLOGE("Can't finish configuring input stream %d: %s (%d)",
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002744 mInputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002745 cancelStreamsConfigurationLocked();
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002746 if ((res == NO_INIT || res == DEAD_OBJECT) && mInputStream->isAbandoned()) {
2747 return DEAD_OBJECT;
2748 }
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002749 return BAD_VALUE;
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002750 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002751 if (streamReConfigured) {
2752 mInterface->onStreamReConfigured(mInputStream->getId());
2753 }
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002754 }
2755
2756 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002757 sp<Camera3OutputStreamInterface> outputStream = mOutputStreams[i];
Zhijun He5d677d12016-05-29 16:52:39 -07002758 if (outputStream->isConfiguring() && !outputStream->isConsumerConfigurationDeferred()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002759 bool streamReConfigured = false;
2760 res = outputStream->finishConfiguration(&streamReConfigured);
Igor Murashkin073f8572013-05-02 14:59:28 -07002761 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002762 CLOGE("Can't finish configuring output stream %d: %s (%d)",
Igor Murashkin073f8572013-05-02 14:59:28 -07002763 outputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002764 cancelStreamsConfigurationLocked();
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002765 if ((res == NO_INIT || res == DEAD_OBJECT) && outputStream->isAbandoned()) {
2766 return DEAD_OBJECT;
2767 }
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002768 return BAD_VALUE;
Igor Murashkin073f8572013-05-02 14:59:28 -07002769 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002770 if (streamReConfigured) {
2771 mInterface->onStreamReConfigured(outputStream->getId());
2772 }
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002773 }
2774 }
2775
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002776 // Request thread needs to know to avoid using repeat-last-settings protocol
2777 // across configure_streams() calls
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002778 if (notifyRequestThread) {
Shuzhen Wang99080502021-03-07 21:08:20 -08002779 mRequestThread->configurationComplete(mIsConstrainedHighSpeedConfiguration,
2780 sessionParams, mGroupIdPhysicalCameraMap);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002781 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002782
Zhijun He90f7c372016-08-16 16:19:43 -07002783 char value[PROPERTY_VALUE_MAX];
2784 property_get("camera.fifo.disable", value, "0");
2785 int32_t disableFifo = atoi(value);
2786 if (disableFifo != 1) {
2787 // Boost priority of request thread to SCHED_FIFO.
2788 pid_t requestThreadTid = mRequestThread->getTid();
2789 res = requestPriority(getpid(), requestThreadTid,
Mikhail Naganov83f04272017-02-07 10:45:09 -08002790 kRequestThreadPriority, /*isForApp*/ false, /*asynchronous*/ false);
Zhijun He90f7c372016-08-16 16:19:43 -07002791 if (res != OK) {
2792 ALOGW("Can't set realtime priority for request processing thread: %s (%d)",
2793 strerror(-res), res);
2794 } else {
2795 ALOGD("Set real time priority for request queue thread (tid %d)", requestThreadTid);
2796 }
Eino-Ville Talvalaf99498e2015-09-25 16:52:55 -07002797 }
2798
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002799 // Update device state
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002800 const camera_metadata_t *newSessionParams = sessionParams.getAndLock();
2801 const camera_metadata_t *currentSessionParams = mSessionParams.getAndLock();
2802 bool updateSessionParams = (newSessionParams != currentSessionParams) ? true : false;
2803 sessionParams.unlock(newSessionParams);
2804 mSessionParams.unlock(currentSessionParams);
2805 if (updateSessionParams) {
2806 mSessionParams = sessionParams;
2807 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002808
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002809 mNeedConfig = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002810
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002811 internalUpdateStatusLocked((mFakeStreamId == NO_STREAM) ?
Ruben Brunk183f0562015-08-12 12:55:02 -07002812 STATUS_CONFIGURED : STATUS_UNCONFIGURED);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002813
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002814 ALOGV("%s: Camera %s: Stream configuration complete", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002815
Zhijun He0a210512014-07-24 13:45:15 -07002816 // tear down the deleted streams after configure streams.
2817 mDeletedStreams.clear();
2818
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002819 auto rc = mPreparerThread->resume();
2820 if (rc != OK) {
2821 SET_ERR_L("%s: Camera %s: Preparer thread failed to resume!", __FUNCTION__, mId.string());
2822 return rc;
2823 }
2824
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002825 if (mFakeStreamId == NO_STREAM) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07002826 mRequestBufferSM.onStreamsConfigured();
2827 }
2828
Cliff Wuc2ad9c82021-04-21 00:58:58 +08002829 // Since the streams configuration of the injection camera is based on the internal camera, we
2830 // must wait until the internal camera configure streams before calling injectCamera() to
2831 // configure the injection streams.
2832 if (mInjectionMethods->isInjecting()) {
2833 ALOGV("%s: Injection camera %s: Start to configure streams.",
2834 __FUNCTION__, mInjectionMethods->getInjectedCamId().string());
2835 res = mInjectionMethods->injectCamera(config, bufferSizes);
2836 if (res != OK) {
2837 ALOGE("Can't finish inject camera process!");
2838 return res;
2839 }
2840 }
2841
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002842 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002843}
2844
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002845status_t Camera3Device::addFakeStreamLocked() {
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002846 ATRACE_CALL();
2847 status_t res;
2848
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002849 if (mFakeStreamId != NO_STREAM) {
2850 // Should never be adding a second fake stream when one is already
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002851 // active
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002852 SET_ERR_L("%s: Camera %s: A fake stream already exists!",
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002853 __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002854 return INVALID_OPERATION;
2855 }
2856
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002857 ALOGV("%s: Camera %s: Adding a fake stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002858
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002859 sp<Camera3OutputStreamInterface> fakeStream =
2860 new Camera3FakeStream(mNextStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002861
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002862 res = mOutputStreams.add(mNextStreamId, fakeStream);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002863 if (res < 0) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002864 SET_ERR_L("Can't add fake stream to set: %s (%d)", strerror(-res), res);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002865 return res;
2866 }
2867
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002868 mFakeStreamId = mNextStreamId;
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002869 mNextStreamId++;
2870
2871 return OK;
2872}
2873
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002874status_t Camera3Device::tryRemoveFakeStreamLocked() {
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002875 ATRACE_CALL();
2876 status_t res;
2877
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002878 if (mFakeStreamId == NO_STREAM) return OK;
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002879 if (mOutputStreams.size() == 1) return OK;
2880
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002881 ALOGV("%s: Camera %s: Removing the fake stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002882
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002883 // Ok, have a fake stream and there's at least one other output stream,
2884 // so remove the fake
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002885
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002886 sp<Camera3StreamInterface> deletedStream = mOutputStreams.get(mFakeStreamId);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002887 if (deletedStream == nullptr) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002888 SET_ERR_L("Fake stream %d does not appear to exist", mFakeStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002889 return INVALID_OPERATION;
2890 }
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002891 mOutputStreams.remove(mFakeStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002892
2893 // Free up the stream endpoint so that it can be used by some other stream
2894 res = deletedStream->disconnect();
2895 if (res != OK) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002896 SET_ERR_L("Can't disconnect deleted fake stream %d", mFakeStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002897 // fall through since we want to still list the stream as deleted.
2898 }
2899 mDeletedStreams.add(deletedStream);
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002900 mFakeStreamId = NO_STREAM;
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002901
2902 return res;
2903}
2904
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002905void Camera3Device::setErrorState(const char *fmt, ...) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002906 ATRACE_CALL();
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002907 Mutex::Autolock l(mLock);
2908 va_list args;
2909 va_start(args, fmt);
2910
2911 setErrorStateLockedV(fmt, args);
2912
2913 va_end(args);
2914}
2915
2916void Camera3Device::setErrorStateV(const char *fmt, va_list args) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002917 ATRACE_CALL();
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002918 Mutex::Autolock l(mLock);
2919 setErrorStateLockedV(fmt, args);
2920}
2921
2922void Camera3Device::setErrorStateLocked(const char *fmt, ...) {
2923 va_list args;
2924 va_start(args, fmt);
2925
2926 setErrorStateLockedV(fmt, args);
2927
2928 va_end(args);
2929}
2930
2931void Camera3Device::setErrorStateLockedV(const char *fmt, va_list args) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002932 // Print out all error messages to log
2933 String8 errorCause = String8::formatV(fmt, args);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002934 ALOGE("Camera %s: %s", mId.string(), errorCause.string());
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002935
2936 // But only do error state transition steps for the first error
Zhijun Heb05eeae2013-06-06 13:51:22 -07002937 if (mStatus == STATUS_ERROR || mStatus == STATUS_UNINITIALIZED) return;
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002938
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002939 mErrorCause = errorCause;
2940
Yin-Chia Yeh3d145ae2017-07-27 12:47:03 -07002941 if (mRequestThread != nullptr) {
2942 mRequestThread->setPaused(true);
2943 }
Ruben Brunk183f0562015-08-12 12:55:02 -07002944 internalUpdateStatusLocked(STATUS_ERROR);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002945
2946 // Notify upstream about a device error
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002947 sp<NotificationListener> listener = mListener.promote();
2948 if (listener != NULL) {
2949 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002950 CaptureResultExtras());
Shuzhen Wang316781a2020-08-18 18:11:01 -07002951 mSessionStatsBuilder.onDeviceError();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002952 }
2953
2954 // Save stack trace. View by dumping it later.
2955 CameraTraces::saveTrace();
2956 // TODO: consider adding errorCause and client pid/procname
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002957}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002958
2959/**
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002960 * In-flight request management
2961 */
2962
Jianing Weicb0652e2014-03-12 18:29:36 -07002963status_t Camera3Device::registerInFlight(uint32_t frameNumber,
Chien-Yu Chend196d612015-06-22 19:49:01 -07002964 int32_t numBuffers, CaptureResultExtras resultExtras, bool hasInput,
Shuzhen Wang5c22c152017-12-31 17:12:25 -08002965 bool hasAppCallback, nsecs_t maxExpectedDuration,
Shuzhen Wang99080502021-03-07 21:08:20 -08002966 const std::set<std::set<String8>>& physicalCameraIds,
2967 bool isStillCapture, bool isZslCapture, bool rotateAndCropAuto,
2968 const std::set<std::string>& cameraIdsWithZoom,
Shuzhen Wang316781a2020-08-18 18:11:01 -07002969 const SurfaceMap& outputSurfaces, nsecs_t requestTimeNs) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002970 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002971 std::lock_guard<std::mutex> l(mInFlightLock);
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002972
2973 ssize_t res;
Chien-Yu Chend196d612015-06-22 19:49:01 -07002974 res = mInFlightMap.add(frameNumber, InFlightRequest(numBuffers, resultExtras, hasInput,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07002975 hasAppCallback, maxExpectedDuration, physicalCameraIds, isStillCapture, isZslCapture,
Shuzhen Wang316781a2020-08-18 18:11:01 -07002976 rotateAndCropAuto, cameraIdsWithZoom, requestTimeNs, outputSurfaces));
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002977 if (res < 0) return res;
2978
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07002979 if (mInFlightMap.size() == 1) {
Emilian Peev26d975d2018-07-05 14:52:57 +01002980 // Hold a separate dedicated tracker lock to prevent race with disconnect and also
2981 // avoid a deadlock during reprocess requests.
2982 Mutex::Autolock l(mTrackerLock);
Yin-Chia Yeh38dfde52017-06-27 17:13:33 -07002983 if (mStatusTracker != nullptr) {
2984 mStatusTracker->markComponentActive(mInFlightStatusId);
2985 }
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07002986 }
2987
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07002988 mExpectedInflightDuration += maxExpectedDuration;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002989 return OK;
2990}
2991
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002992void Camera3Device::onInflightEntryRemovedLocked(nsecs_t duration) {
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002993 // Indicate idle inFlightMap to the status tracker
2994 if (mInFlightMap.size() == 0) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07002995 mRequestBufferSM.onInflightMapEmpty();
Emilian Peev26d975d2018-07-05 14:52:57 +01002996 // Hold a separate dedicated tracker lock to prevent race with disconnect and also
2997 // avoid a deadlock during reprocess requests.
2998 Mutex::Autolock l(mTrackerLock);
Yin-Chia Yeh38dfde52017-06-27 17:13:33 -07002999 if (mStatusTracker != nullptr) {
3000 mStatusTracker->markComponentIdle(mInFlightStatusId, Fence::NO_FENCE);
3001 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07003002 }
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003003 mExpectedInflightDuration -= duration;
Shuzhen Wangcadb3302016-11-04 14:17:56 -07003004}
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003005
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003006void Camera3Device::checkInflightMapLengthLocked() {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04003007 // Validation check - if we have too many in-flight frames with long total inflight duration,
Yin-Chia Yeh99fd0972019-06-27 14:22:44 -07003008 // something has likely gone wrong. This might still be legit only if application send in
3009 // a long burst of long exposure requests.
3010 if (mExpectedInflightDuration > kMinWarnInflightDuration) {
3011 if (!mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() > kInFlightWarnLimit) {
3012 CLOGW("In-flight list too large: %zu, total inflight duration %" PRIu64,
3013 mInFlightMap.size(), mExpectedInflightDuration);
3014 } else if (mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() >
3015 kInFlightWarnLimitHighSpeed) {
3016 CLOGW("In-flight list too large for high speed configuration: %zu,"
3017 "total inflight duration %" PRIu64,
3018 mInFlightMap.size(), mExpectedInflightDuration);
3019 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003020 }
3021}
3022
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003023void Camera3Device::onInflightMapFlushedLocked() {
3024 mExpectedInflightDuration = 0;
3025}
3026
3027void Camera3Device::removeInFlightMapEntryLocked(int idx) {
Jayant Chowdharyd4776262020-06-23 23:45:57 -07003028 ATRACE_HFR_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003029 nsecs_t duration = mInFlightMap.valueAt(idx).maxExpectedDuration;
3030 mInFlightMap.removeItemsAt(idx, 1);
3031
3032 onInflightEntryRemovedLocked(duration);
3033}
3034
3035
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003036void Camera3Device::flushInflightRequests() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003037 ATRACE_CALL();
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003038 sp<NotificationListener> listener;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003039 {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003040 std::lock_guard<std::mutex> l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003041 listener = mListener.promote();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003042 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003043
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003044 FlushInflightReqStates states {
3045 mId, mInFlightLock, mInFlightMap, mUseHalBufManager,
Shuzhen Wang316781a2020-08-18 18:11:01 -07003046 listener, *this, *mInterface, *this, mSessionStatsBuilder};
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003047
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003048 camera3::flushInflightRequests(states);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003049}
3050
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003051CameraMetadata Camera3Device::getLatestRequestLocked() {
Igor Murashkin1e479c02013-09-06 16:55:14 -07003052 ALOGV("%s", __FUNCTION__);
3053
Igor Murashkin1e479c02013-09-06 16:55:14 -07003054 CameraMetadata retVal;
3055
3056 if (mRequestThread != NULL) {
3057 retVal = mRequestThread->getLatestRequest();
3058 }
3059
Igor Murashkin1e479c02013-09-06 16:55:14 -07003060 return retVal;
3061}
3062
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07003063void Camera3Device::monitorMetadata(TagMonitor::eventSource source,
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003064 int64_t frameNumber, nsecs_t timestamp, const CameraMetadata& metadata,
3065 const std::unordered_map<std::string, CameraMetadata>& physicalMetadata) {
3066
3067 mTagMonitor.monitorMetadata(source, frameNumber, timestamp, metadata,
3068 physicalMetadata);
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07003069}
3070
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003071/**
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003072 * HalInterface inner class methods
3073 */
3074
Yifan Hongf79b5542017-04-11 14:44:25 -07003075Camera3Device::HalInterface::HalInterface(
3076 sp<ICameraDeviceSession> &session,
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003077 std::shared_ptr<RequestMetadataQueue> queue,
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003078 bool useHalBufManager, bool supportOfflineProcessing) :
Yifan Hongf79b5542017-04-11 14:44:25 -07003079 mHidlSession(session),
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003080 mRequestMetadataQueue(queue),
Emilian Peev4ec17882019-01-24 17:16:58 -08003081 mUseHalBufManager(useHalBufManager),
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003082 mIsReconfigurationQuerySupported(true),
3083 mSupportOfflineProcessing(supportOfflineProcessing) {
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003084 // Check with hardware service manager if we can downcast these interfaces
3085 // Somewhat expensive, so cache the results at startup
Shuzhen Wang83bff122020-11-20 15:51:39 -08003086 auto castResult_3_7 = device::V3_7::ICameraDeviceSession::castFrom(mHidlSession);
3087 if (castResult_3_7.isOk()) {
3088 mHidlSession_3_7 = castResult_3_7;
3089 }
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003090 auto castResult_3_6 = device::V3_6::ICameraDeviceSession::castFrom(mHidlSession);
3091 if (castResult_3_6.isOk()) {
3092 mHidlSession_3_6 = castResult_3_6;
3093 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003094 auto castResult_3_5 = device::V3_5::ICameraDeviceSession::castFrom(mHidlSession);
3095 if (castResult_3_5.isOk()) {
3096 mHidlSession_3_5 = castResult_3_5;
3097 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003098 auto castResult_3_4 = device::V3_4::ICameraDeviceSession::castFrom(mHidlSession);
3099 if (castResult_3_4.isOk()) {
3100 mHidlSession_3_4 = castResult_3_4;
3101 }
3102 auto castResult_3_3 = device::V3_3::ICameraDeviceSession::castFrom(mHidlSession);
3103 if (castResult_3_3.isOk()) {
3104 mHidlSession_3_3 = castResult_3_3;
3105 }
3106}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003107
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003108Camera3Device::HalInterface::HalInterface() :
3109 mUseHalBufManager(false),
3110 mSupportOfflineProcessing(false) {}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003111
3112Camera3Device::HalInterface::HalInterface(const HalInterface& other) :
Yifan Hongf79b5542017-04-11 14:44:25 -07003113 mHidlSession(other.mHidlSession),
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003114 mRequestMetadataQueue(other.mRequestMetadataQueue),
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003115 mUseHalBufManager(other.mUseHalBufManager),
3116 mSupportOfflineProcessing(other.mSupportOfflineProcessing) {}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003117
3118bool Camera3Device::HalInterface::valid() {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003119 return (mHidlSession != nullptr);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003120}
3121
3122void Camera3Device::HalInterface::clear() {
Shuzhen Wang83bff122020-11-20 15:51:39 -08003123 mHidlSession_3_7.clear();
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003124 mHidlSession_3_6.clear();
Emilian Peev644a3e12018-11-23 13:52:39 +00003125 mHidlSession_3_5.clear();
Emilian Peev9e740b02018-01-30 18:28:03 +00003126 mHidlSession_3_4.clear();
3127 mHidlSession_3_3.clear();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003128 mHidlSession.clear();
3129}
3130
3131status_t Camera3Device::HalInterface::constructDefaultRequestSettings(
Emilian Peevf4816702020-04-03 15:44:51 -07003132 camera_request_template_t templateId,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003133 /*out*/ camera_metadata_t **requestTemplate) {
3134 ATRACE_NAME("CameraHal::constructDefaultRequestSettings");
3135 if (!valid()) return INVALID_OPERATION;
3136 status_t res = OK;
3137
Emilian Peev31abd0a2017-05-11 18:37:46 +01003138 common::V1_0::Status status;
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003139
3140 auto requestCallback = [&status, &requestTemplate]
Emilian Peev31abd0a2017-05-11 18:37:46 +01003141 (common::V1_0::Status s, const device::V3_2::CameraMetadata& request) {
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003142 status = s;
3143 if (status == common::V1_0::Status::OK) {
3144 const camera_metadata *r =
3145 reinterpret_cast<const camera_metadata_t*>(request.data());
3146 size_t expectedSize = request.size();
3147 int ret = validate_camera_metadata_structure(r, &expectedSize);
3148 if (ret == OK || ret == CAMERA_METADATA_VALIDATION_SHIFTED) {
3149 *requestTemplate = clone_camera_metadata(r);
3150 if (*requestTemplate == nullptr) {
3151 ALOGE("%s: Unable to clone camera metadata received from HAL",
3152 __FUNCTION__);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003153 status = common::V1_0::Status::INTERNAL_ERROR;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003154 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003155 } else {
3156 ALOGE("%s: Malformed camera metadata received from HAL", __FUNCTION__);
3157 status = common::V1_0::Status::INTERNAL_ERROR;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003158 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003159 }
3160 };
3161 hardware::Return<void> err;
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003162 RequestTemplate id;
3163 switch (templateId) {
Emilian Peevf4816702020-04-03 15:44:51 -07003164 case CAMERA_TEMPLATE_PREVIEW:
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003165 id = RequestTemplate::PREVIEW;
3166 break;
Emilian Peevf4816702020-04-03 15:44:51 -07003167 case CAMERA_TEMPLATE_STILL_CAPTURE:
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003168 id = RequestTemplate::STILL_CAPTURE;
3169 break;
Emilian Peevf4816702020-04-03 15:44:51 -07003170 case CAMERA_TEMPLATE_VIDEO_RECORD:
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003171 id = RequestTemplate::VIDEO_RECORD;
3172 break;
Emilian Peevf4816702020-04-03 15:44:51 -07003173 case CAMERA_TEMPLATE_VIDEO_SNAPSHOT:
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003174 id = RequestTemplate::VIDEO_SNAPSHOT;
3175 break;
Emilian Peevf4816702020-04-03 15:44:51 -07003176 case CAMERA_TEMPLATE_ZERO_SHUTTER_LAG:
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003177 id = RequestTemplate::ZERO_SHUTTER_LAG;
3178 break;
Emilian Peevf4816702020-04-03 15:44:51 -07003179 case CAMERA_TEMPLATE_MANUAL:
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003180 id = RequestTemplate::MANUAL;
3181 break;
3182 default:
3183 // Unknown template ID, or this HAL is too old to support it
3184 return BAD_VALUE;
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003185 }
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003186 err = mHidlSession->constructDefaultRequestSettings(id, requestCallback);
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003187
Emilian Peev31abd0a2017-05-11 18:37:46 +01003188 if (!err.isOk()) {
3189 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3190 res = DEAD_OBJECT;
3191 } else {
3192 res = CameraProviderManager::mapToStatusT(status);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003193 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003194
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003195 return res;
3196}
3197
Emilian Peev4ec17882019-01-24 17:16:58 -08003198bool Camera3Device::HalInterface::isReconfigurationRequired(CameraMetadata& oldSessionParams,
3199 CameraMetadata& newSessionParams) {
3200 // We do reconfiguration by default;
3201 bool ret = true;
3202 if ((mHidlSession_3_5 != nullptr) && mIsReconfigurationQuerySupported) {
3203 android::hardware::hidl_vec<uint8_t> oldParams, newParams;
3204 camera_metadata_t* oldSessioMeta = const_cast<camera_metadata_t*>(
3205 oldSessionParams.getAndLock());
3206 camera_metadata_t* newSessioMeta = const_cast<camera_metadata_t*>(
3207 newSessionParams.getAndLock());
3208 oldParams.setToExternal(reinterpret_cast<uint8_t*>(oldSessioMeta),
3209 get_camera_metadata_size(oldSessioMeta));
3210 newParams.setToExternal(reinterpret_cast<uint8_t*>(newSessioMeta),
3211 get_camera_metadata_size(newSessioMeta));
3212 hardware::camera::common::V1_0::Status callStatus;
3213 bool required;
3214 auto hidlCb = [&callStatus, &required] (hardware::camera::common::V1_0::Status s,
3215 bool requiredFlag) {
3216 callStatus = s;
3217 required = requiredFlag;
3218 };
3219 auto err = mHidlSession_3_5->isReconfigurationRequired(oldParams, newParams, hidlCb);
3220 oldSessionParams.unlock(oldSessioMeta);
3221 newSessionParams.unlock(newSessioMeta);
3222 if (err.isOk()) {
3223 switch (callStatus) {
3224 case hardware::camera::common::V1_0::Status::OK:
3225 ret = required;
3226 break;
3227 case hardware::camera::common::V1_0::Status::METHOD_NOT_SUPPORTED:
3228 mIsReconfigurationQuerySupported = false;
3229 ret = true;
3230 break;
3231 default:
3232 ALOGV("%s: Reconfiguration query failed: %d", __FUNCTION__, callStatus);
3233 ret = true;
3234 }
3235 } else {
3236 ALOGE("%s: Unexpected binder error: %s", __FUNCTION__, err.description().c_str());
3237 ret = true;
3238 }
3239 }
3240
3241 return ret;
3242}
3243
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003244status_t Camera3Device::HalInterface::configureStreams(const camera_metadata_t *sessionParams,
Emilian Peevf4816702020-04-03 15:44:51 -07003245 camera_stream_configuration *config, const std::vector<uint32_t>& bufferSizes) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003246 ATRACE_NAME("CameraHal::configureStreams");
3247 if (!valid()) return INVALID_OPERATION;
3248 status_t res = OK;
3249
Shuzhen Wang83bff122020-11-20 15:51:39 -08003250 if (config->input_is_multi_resolution && mHidlSession_3_7 == nullptr) {
3251 ALOGE("%s: Camera device doesn't support multi-resolution input stream", __FUNCTION__);
3252 return BAD_VALUE;
3253 }
3254
Emilian Peev31abd0a2017-05-11 18:37:46 +01003255 // Convert stream config to HIDL
3256 std::set<int> activeStreams;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003257 device::V3_2::StreamConfiguration requestedConfiguration3_2;
3258 device::V3_4::StreamConfiguration requestedConfiguration3_4;
Shuzhen Wang83bff122020-11-20 15:51:39 -08003259 device::V3_7::StreamConfiguration requestedConfiguration3_7;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003260 requestedConfiguration3_2.streams.resize(config->num_streams);
3261 requestedConfiguration3_4.streams.resize(config->num_streams);
Shuzhen Wang83bff122020-11-20 15:51:39 -08003262 requestedConfiguration3_7.streams.resize(config->num_streams);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003263 for (size_t i = 0; i < config->num_streams; i++) {
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003264 device::V3_2::Stream &dst3_2 = requestedConfiguration3_2.streams[i];
3265 device::V3_4::Stream &dst3_4 = requestedConfiguration3_4.streams[i];
Shuzhen Wang83bff122020-11-20 15:51:39 -08003266 device::V3_7::Stream &dst3_7 = requestedConfiguration3_7.streams[i];
Emilian Peevf4816702020-04-03 15:44:51 -07003267 camera3::camera_stream_t *src = config->streams[i];
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003268
Emilian Peev31abd0a2017-05-11 18:37:46 +01003269 Camera3Stream* cam3stream = Camera3Stream::cast(src);
3270 cam3stream->setBufferFreedListener(this);
3271 int streamId = cam3stream->getId();
3272 StreamType streamType;
3273 switch (src->stream_type) {
Emilian Peevf4816702020-04-03 15:44:51 -07003274 case CAMERA_STREAM_OUTPUT:
Emilian Peev31abd0a2017-05-11 18:37:46 +01003275 streamType = StreamType::OUTPUT;
3276 break;
Emilian Peevf4816702020-04-03 15:44:51 -07003277 case CAMERA_STREAM_INPUT:
Emilian Peev31abd0a2017-05-11 18:37:46 +01003278 streamType = StreamType::INPUT;
3279 break;
3280 default:
3281 ALOGE("%s: Stream %d: Unsupported stream type %d",
3282 __FUNCTION__, streamId, config->streams[i]->stream_type);
3283 return BAD_VALUE;
3284 }
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003285 dst3_2.id = streamId;
3286 dst3_2.streamType = streamType;
3287 dst3_2.width = src->width;
3288 dst3_2.height = src->height;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003289 dst3_2.usage = mapToConsumerUsage(cam3stream->getUsage());
Emilian Peevf4816702020-04-03 15:44:51 -07003290 dst3_2.rotation = mapToStreamRotation((camera_stream_rotation_t) src->rotation);
Shuzhen Wang92653952019-05-07 15:11:43 -07003291 // For HidlSession version 3.5 or newer, the format and dataSpace sent
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08003292 // to HAL are original, not the overridden ones.
Shuzhen Wang92653952019-05-07 15:11:43 -07003293 if (mHidlSession_3_5 != nullptr) {
3294 dst3_2.format = mapToPixelFormat(cam3stream->isFormatOverridden() ?
3295 cam3stream->getOriginalFormat() : src->format);
3296 dst3_2.dataSpace = mapToHidlDataspace(cam3stream->isDataSpaceOverridden() ?
3297 cam3stream->getOriginalDataSpace() : src->data_space);
3298 } else {
3299 dst3_2.format = mapToPixelFormat(src->format);
3300 dst3_2.dataSpace = mapToHidlDataspace(src->data_space);
3301 }
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003302 dst3_4.v3_2 = dst3_2;
Emilian Peev192ee832018-01-31 14:46:47 +00003303 dst3_4.bufferSize = bufferSizes[i];
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003304 if (src->physical_camera_id != nullptr) {
3305 dst3_4.physicalCameraId = src->physical_camera_id;
3306 }
Shuzhen Wang83bff122020-11-20 15:51:39 -08003307 dst3_7.v3_4 = dst3_4;
3308 dst3_7.groupId = cam3stream->getHalStreamGroupId();
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08003309 dst3_7.sensorPixelModesUsed.resize(src->sensor_pixel_modes_used.size());
3310 size_t j = 0;
3311 for (int mode : src->sensor_pixel_modes_used) {
3312 dst3_7.sensorPixelModesUsed[j++] =
3313 static_cast<CameraMetadataEnumAndroidSensorPixelMode>(mode);
3314 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003315 activeStreams.insert(streamId);
3316 // Create Buffer ID map if necessary
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003317 mBufferRecords.tryCreateBufferCache(streamId);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003318 }
3319 // remove BufferIdMap for deleted streams
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003320 mBufferRecords.removeInactiveBufferCaches(activeStreams);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003321
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003322 StreamConfigurationMode operationMode;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003323 res = mapToStreamConfigurationMode(
Emilian Peevf4816702020-04-03 15:44:51 -07003324 (camera_stream_configuration_mode_t) config->operation_mode,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003325 /*out*/ &operationMode);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003326 if (res != OK) {
3327 return res;
3328 }
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003329 requestedConfiguration3_2.operationMode = operationMode;
3330 requestedConfiguration3_4.operationMode = operationMode;
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08003331 requestedConfiguration3_7.operationMode = operationMode;
3332 size_t sessionParamSize = get_camera_metadata_size(sessionParams);
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003333 requestedConfiguration3_4.sessionParams.setToExternal(
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003334 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(sessionParams)),
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08003335 sessionParamSize);
Shuzhen Wang83bff122020-11-20 15:51:39 -08003336 requestedConfiguration3_7.operationMode = operationMode;
3337 requestedConfiguration3_7.sessionParams.setToExternal(
3338 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(sessionParams)),
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08003339 sessionParamSize);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003340
Emilian Peev31abd0a2017-05-11 18:37:46 +01003341 // Invoke configureStreams
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003342 device::V3_3::HalStreamConfiguration finalConfiguration;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003343 device::V3_4::HalStreamConfiguration finalConfiguration3_4;
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003344 device::V3_6::HalStreamConfiguration finalConfiguration3_6;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003345 common::V1_0::Status status;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003346
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003347 auto configStream34Cb = [&status, &finalConfiguration3_4]
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003348 (common::V1_0::Status s, const device::V3_4::HalStreamConfiguration& halConfiguration) {
3349 finalConfiguration3_4 = halConfiguration;
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003350 status = s;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003351 };
3352
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003353 auto configStream36Cb = [&status, &finalConfiguration3_6]
3354 (common::V1_0::Status s, const device::V3_6::HalStreamConfiguration& halConfiguration) {
3355 finalConfiguration3_6 = halConfiguration;
3356 status = s;
3357 };
3358
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003359 auto postprocConfigStream34 = [&finalConfiguration, &finalConfiguration3_4]
3360 (hardware::Return<void>& err) -> status_t {
3361 if (!err.isOk()) {
3362 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3363 return DEAD_OBJECT;
3364 }
3365 finalConfiguration.streams.resize(finalConfiguration3_4.streams.size());
3366 for (size_t i = 0; i < finalConfiguration3_4.streams.size(); i++) {
3367 finalConfiguration.streams[i] = finalConfiguration3_4.streams[i].v3_3;
3368 }
3369 return OK;
3370 };
3371
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003372 auto postprocConfigStream36 = [&finalConfiguration, &finalConfiguration3_6]
3373 (hardware::Return<void>& err) -> status_t {
3374 if (!err.isOk()) {
3375 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3376 return DEAD_OBJECT;
3377 }
3378 finalConfiguration.streams.resize(finalConfiguration3_6.streams.size());
3379 for (size_t i = 0; i < finalConfiguration3_6.streams.size(); i++) {
3380 finalConfiguration.streams[i] = finalConfiguration3_6.streams[i].v3_4.v3_3;
3381 }
3382 return OK;
3383 };
3384
Shuzhen Wang92653952019-05-07 15:11:43 -07003385 // See which version of HAL we have
Shuzhen Wang83bff122020-11-20 15:51:39 -08003386 if (mHidlSession_3_7 != nullptr) {
3387 ALOGV("%s: v3.7 device found", __FUNCTION__);
3388 requestedConfiguration3_7.streamConfigCounter = mNextStreamConfigCounter++;
3389 requestedConfiguration3_7.multiResolutionInputImage = config->input_is_multi_resolution;
3390 auto err = mHidlSession_3_7->configureStreams_3_7(
3391 requestedConfiguration3_7, configStream36Cb);
3392 res = postprocConfigStream36(err);
3393 if (res != OK) {
3394 return res;
3395 }
3396 } else if (mHidlSession_3_6 != nullptr) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003397 ALOGV("%s: v3.6 device found", __FUNCTION__);
3398 device::V3_5::StreamConfiguration requestedConfiguration3_5;
3399 requestedConfiguration3_5.v3_4 = requestedConfiguration3_4;
3400 requestedConfiguration3_5.streamConfigCounter = mNextStreamConfigCounter++;
3401 auto err = mHidlSession_3_6->configureStreams_3_6(
3402 requestedConfiguration3_5, configStream36Cb);
3403 res = postprocConfigStream36(err);
3404 if (res != OK) {
3405 return res;
3406 }
3407 } else if (mHidlSession_3_5 != nullptr) {
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003408 ALOGV("%s: v3.5 device found", __FUNCTION__);
3409 device::V3_5::StreamConfiguration requestedConfiguration3_5;
3410 requestedConfiguration3_5.v3_4 = requestedConfiguration3_4;
3411 requestedConfiguration3_5.streamConfigCounter = mNextStreamConfigCounter++;
3412 auto err = mHidlSession_3_5->configureStreams_3_5(
3413 requestedConfiguration3_5, configStream34Cb);
3414 res = postprocConfigStream34(err);
3415 if (res != OK) {
3416 return res;
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003417 }
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003418 } else if (mHidlSession_3_4 != nullptr) {
3419 // We do; use v3.4 for the call
3420 ALOGV("%s: v3.4 device found", __FUNCTION__);
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003421 auto err = mHidlSession_3_4->configureStreams_3_4(
3422 requestedConfiguration3_4, configStream34Cb);
3423 res = postprocConfigStream34(err);
3424 if (res != OK) {
3425 return res;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003426 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003427 } else if (mHidlSession_3_3 != nullptr) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003428 // We do; use v3.3 for the call
3429 ALOGV("%s: v3.3 device found", __FUNCTION__);
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003430 auto err = mHidlSession_3_3->configureStreams_3_3(requestedConfiguration3_2,
Emilian Peev31abd0a2017-05-11 18:37:46 +01003431 [&status, &finalConfiguration]
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003432 (common::V1_0::Status s, const device::V3_3::HalStreamConfiguration& halConfiguration) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003433 finalConfiguration = halConfiguration;
3434 status = s;
3435 });
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003436 if (!err.isOk()) {
3437 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3438 return DEAD_OBJECT;
3439 }
3440 } else {
3441 // We don't; use v3.2 call and construct a v3.3 HalStreamConfiguration
3442 ALOGV("%s: v3.2 device found", __FUNCTION__);
3443 HalStreamConfiguration finalConfiguration_3_2;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003444 auto err = mHidlSession->configureStreams(requestedConfiguration3_2,
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003445 [&status, &finalConfiguration_3_2]
3446 (common::V1_0::Status s, const HalStreamConfiguration& halConfiguration) {
3447 finalConfiguration_3_2 = halConfiguration;
3448 status = s;
3449 });
3450 if (!err.isOk()) {
3451 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3452 return DEAD_OBJECT;
3453 }
3454 finalConfiguration.streams.resize(finalConfiguration_3_2.streams.size());
3455 for (size_t i = 0; i < finalConfiguration_3_2.streams.size(); i++) {
3456 finalConfiguration.streams[i].v3_2 = finalConfiguration_3_2.streams[i];
3457 finalConfiguration.streams[i].overrideDataSpace =
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003458 requestedConfiguration3_2.streams[i].dataSpace;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003459 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003460 }
3461
3462 if (status != common::V1_0::Status::OK ) {
3463 return CameraProviderManager::mapToStatusT(status);
3464 }
3465
3466 // And convert output stream configuration from HIDL
3467
3468 for (size_t i = 0; i < config->num_streams; i++) {
Emilian Peevf4816702020-04-03 15:44:51 -07003469 camera3::camera_stream_t *dst = config->streams[i];
Emilian Peev31abd0a2017-05-11 18:37:46 +01003470 int streamId = Camera3Stream::cast(dst)->getId();
3471
3472 // Start scan at i, with the assumption that the stream order matches
3473 size_t realIdx = i;
3474 bool found = false;
Eino-Ville Talvala370875f2019-04-12 12:40:27 -07003475 size_t halStreamCount = finalConfiguration.streams.size();
3476 for (size_t idx = 0; idx < halStreamCount; idx++) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003477 if (finalConfiguration.streams[realIdx].v3_2.id == streamId) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003478 found = true;
3479 break;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003480 }
Eino-Ville Talvala370875f2019-04-12 12:40:27 -07003481 realIdx = (realIdx >= halStreamCount - 1) ? 0 : realIdx + 1;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003482 }
3483 if (!found) {
3484 ALOGE("%s: Stream %d not found in stream configuration response from HAL",
3485 __FUNCTION__, streamId);
3486 return INVALID_OPERATION;
3487 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003488 device::V3_3::HalStream &src = finalConfiguration.streams[realIdx];
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003489 device::V3_6::HalStream &src_36 = finalConfiguration3_6.streams[realIdx];
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003490
Emilian Peev710c1422017-08-30 11:19:38 +01003491 Camera3Stream* dstStream = Camera3Stream::cast(dst);
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003492 int overrideFormat = mapToFrameworkFormat(src.v3_2.overrideFormat);
3493 android_dataspace overrideDataSpace = mapToFrameworkDataspace(src.overrideDataSpace);
3494
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003495 if (mHidlSession_3_6 != nullptr) {
3496 dstStream->setOfflineProcessingSupport(src_36.supportOffline);
3497 }
3498
Yin-Chia Yeh90667662019-07-01 15:45:00 -07003499 if (dstStream->getOriginalFormat() != HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
Shuzhen Wang92653952019-05-07 15:11:43 -07003500 dstStream->setFormatOverride(false);
3501 dstStream->setDataSpaceOverride(false);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003502 if (dst->format != overrideFormat) {
3503 ALOGE("%s: Stream %d: Format override not allowed for format 0x%x", __FUNCTION__,
3504 streamId, dst->format);
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003505 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003506 if (dst->data_space != overrideDataSpace) {
3507 ALOGE("%s: Stream %d: DataSpace override not allowed for format 0x%x", __FUNCTION__,
3508 streamId, dst->format);
3509 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003510 } else {
Shuzhen Wang92653952019-05-07 15:11:43 -07003511 bool needFormatOverride =
3512 requestedConfiguration3_2.streams[i].format != src.v3_2.overrideFormat;
3513 bool needDataspaceOverride =
3514 requestedConfiguration3_2.streams[i].dataSpace != src.overrideDataSpace;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003515 // Override allowed with IMPLEMENTATION_DEFINED
Shuzhen Wang92653952019-05-07 15:11:43 -07003516 dstStream->setFormatOverride(needFormatOverride);
3517 dstStream->setDataSpaceOverride(needDataspaceOverride);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003518 dst->format = overrideFormat;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003519 dst->data_space = overrideDataSpace;
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003520 }
3521
Emilian Peevf4816702020-04-03 15:44:51 -07003522 if (dst->stream_type == CAMERA_STREAM_INPUT) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003523 if (src.v3_2.producerUsage != 0) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003524 ALOGE("%s: Stream %d: INPUT streams must have 0 for producer usage",
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003525 __FUNCTION__, streamId);
3526 return INVALID_OPERATION;
3527 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003528 dstStream->setUsage(
3529 mapConsumerToFrameworkUsage(src.v3_2.consumerUsage));
Emilian Peev31abd0a2017-05-11 18:37:46 +01003530 } else {
3531 // OUTPUT
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003532 if (src.v3_2.consumerUsage != 0) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003533 ALOGE("%s: Stream %d: OUTPUT streams must have 0 for consumer usage",
3534 __FUNCTION__, streamId);
3535 return INVALID_OPERATION;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003536 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003537 dstStream->setUsage(
3538 mapProducerToFrameworkUsage(src.v3_2.producerUsage));
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003539 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003540 dst->max_buffers = src.v3_2.maxBuffers;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003541 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003542
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003543 return res;
3544}
3545
Cliff Wuc2ad9c82021-04-21 00:58:58 +08003546status_t Camera3Device::HalInterface::configureInjectedStreams(
3547 const camera_metadata_t* sessionParams, camera_stream_configuration* config,
3548 const std::vector<uint32_t>& bufferSizes,
3549 const CameraMetadata& cameraCharacteristics) {
3550 ATRACE_NAME("InjectionCameraHal::configureStreams");
3551 if (!valid()) return INVALID_OPERATION;
3552 status_t res = OK;
3553
3554 if (config->input_is_multi_resolution) {
3555 ALOGE("%s: Injection camera device doesn't support multi-resolution input "
3556 "stream", __FUNCTION__);
3557 return BAD_VALUE;
3558 }
3559
3560 // Convert stream config to HIDL
3561 std::set<int> activeStreams;
3562 device::V3_2::StreamConfiguration requestedConfiguration3_2;
3563 device::V3_4::StreamConfiguration requestedConfiguration3_4;
3564 device::V3_7::StreamConfiguration requestedConfiguration3_7;
3565 requestedConfiguration3_2.streams.resize(config->num_streams);
3566 requestedConfiguration3_4.streams.resize(config->num_streams);
3567 requestedConfiguration3_7.streams.resize(config->num_streams);
3568 for (size_t i = 0; i < config->num_streams; i++) {
3569 device::V3_2::Stream& dst3_2 = requestedConfiguration3_2.streams[i];
3570 device::V3_4::Stream& dst3_4 = requestedConfiguration3_4.streams[i];
3571 device::V3_7::Stream& dst3_7 = requestedConfiguration3_7.streams[i];
3572 camera3::camera_stream_t* src = config->streams[i];
3573
3574 Camera3Stream* cam3stream = Camera3Stream::cast(src);
3575 cam3stream->setBufferFreedListener(this);
3576 int streamId = cam3stream->getId();
3577 StreamType streamType;
3578 switch (src->stream_type) {
3579 case CAMERA_STREAM_OUTPUT:
3580 streamType = StreamType::OUTPUT;
3581 break;
3582 case CAMERA_STREAM_INPUT:
3583 streamType = StreamType::INPUT;
3584 break;
3585 default:
3586 ALOGE("%s: Stream %d: Unsupported stream type %d", __FUNCTION__,
3587 streamId, config->streams[i]->stream_type);
3588 return BAD_VALUE;
3589 }
3590 dst3_2.id = streamId;
3591 dst3_2.streamType = streamType;
3592 dst3_2.width = src->width;
3593 dst3_2.height = src->height;
3594 dst3_2.usage = mapToConsumerUsage(cam3stream->getUsage());
3595 dst3_2.rotation =
3596 mapToStreamRotation((camera_stream_rotation_t)src->rotation);
3597 // For HidlSession version 3.5 or newer, the format and dataSpace sent
3598 // to HAL are original, not the overridden ones.
3599 if (mHidlSession_3_5 != nullptr) {
3600 dst3_2.format = mapToPixelFormat(cam3stream->isFormatOverridden()
3601 ? cam3stream->getOriginalFormat()
3602 : src->format);
3603 dst3_2.dataSpace =
3604 mapToHidlDataspace(cam3stream->isDataSpaceOverridden()
3605 ? cam3stream->getOriginalDataSpace()
3606 : src->data_space);
3607 } else {
3608 dst3_2.format = mapToPixelFormat(src->format);
3609 dst3_2.dataSpace = mapToHidlDataspace(src->data_space);
3610 }
3611 dst3_4.v3_2 = dst3_2;
3612 dst3_4.bufferSize = bufferSizes[i];
3613 if (src->physical_camera_id != nullptr) {
3614 dst3_4.physicalCameraId = src->physical_camera_id;
3615 }
3616 dst3_7.v3_4 = dst3_4;
3617 dst3_7.groupId = cam3stream->getHalStreamGroupId();
3618 dst3_7.sensorPixelModesUsed.resize(src->sensor_pixel_modes_used.size());
3619 size_t j = 0;
3620 for (int mode : src->sensor_pixel_modes_used) {
3621 dst3_7.sensorPixelModesUsed[j++] =
3622 static_cast<CameraMetadataEnumAndroidSensorPixelMode>(mode);
3623 }
3624 activeStreams.insert(streamId);
3625 // Create Buffer ID map if necessary
3626 mBufferRecords.tryCreateBufferCache(streamId);
3627 }
3628 // remove BufferIdMap for deleted streams
3629 mBufferRecords.removeInactiveBufferCaches(activeStreams);
3630
3631 StreamConfigurationMode operationMode;
3632 res = mapToStreamConfigurationMode(
3633 (camera_stream_configuration_mode_t)config->operation_mode,
3634 /*out*/ &operationMode);
3635 if (res != OK) {
3636 return res;
3637 }
3638 requestedConfiguration3_7.operationMode = operationMode;
3639 size_t sessionParamSize = get_camera_metadata_size(sessionParams);
3640 requestedConfiguration3_7.operationMode = operationMode;
3641 requestedConfiguration3_7.sessionParams.setToExternal(
3642 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(sessionParams)),
3643 sessionParamSize);
3644
3645 // See which version of HAL we have
3646 if (mHidlSession_3_7 != nullptr) {
3647 requestedConfiguration3_7.streamConfigCounter = mNextStreamConfigCounter++;
3648 requestedConfiguration3_7.multiResolutionInputImage =
3649 config->input_is_multi_resolution;
3650
3651 const camera_metadata_t* rawMetadata = cameraCharacteristics.getAndLock();
3652 ::android::hardware::camera::device::V3_2::CameraMetadata hidlChars = {};
3653 hidlChars.setToExternal(
3654 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(rawMetadata)),
3655 get_camera_metadata_size(rawMetadata));
3656 cameraCharacteristics.unlock(rawMetadata);
3657
3658 sp<hardware::camera::device::V3_7::ICameraInjectionSession>
3659 hidlInjectionSession_3_7;
3660 auto castInjectionResult_3_7 =
3661 device::V3_7::ICameraInjectionSession::castFrom(mHidlSession_3_7);
3662 if (castInjectionResult_3_7.isOk()) {
3663 hidlInjectionSession_3_7 = castInjectionResult_3_7;
3664 } else {
3665 ALOGE("%s: Transaction error: %s", __FUNCTION__,
3666 castInjectionResult_3_7.description().c_str());
3667 return DEAD_OBJECT;
3668 }
3669
3670 auto err = hidlInjectionSession_3_7->configureInjectionStreams(
3671 requestedConfiguration3_7, hidlChars);
3672 if (!err.isOk()) {
3673 ALOGE("%s: Transaction error: %s", __FUNCTION__,
3674 err.description().c_str());
3675 return DEAD_OBJECT;
3676 }
3677 } else {
3678 ALOGE("%s: mHidlSession_3_7 does not exist, the lowest version of injection "
3679 "session is 3.7", __FUNCTION__);
3680 return DEAD_OBJECT;
3681 }
3682
3683 return res;
3684}
3685
Emilian Peevf4816702020-04-03 15:44:51 -07003686status_t Camera3Device::HalInterface::wrapAsHidlRequest(camera_capture_request_t* request,
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003687 /*out*/device::V3_2::CaptureRequest* captureRequest,
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003688 /*out*/std::vector<native_handle_t*>* handlesCreated,
3689 /*out*/std::vector<std::pair<int32_t, int32_t>>* inflightBuffers) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003690 ATRACE_CALL();
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003691 if (captureRequest == nullptr || handlesCreated == nullptr || inflightBuffers == nullptr) {
3692 ALOGE("%s: captureRequest (%p), handlesCreated (%p), and inflightBuffers(%p) "
3693 "must not be null", __FUNCTION__, captureRequest, handlesCreated, inflightBuffers);
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003694 return BAD_VALUE;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003695 }
3696
3697 captureRequest->frameNumber = request->frame_number;
Yifan Hongf79b5542017-04-11 14:44:25 -07003698
3699 captureRequest->fmqSettingsSize = 0;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003700
3701 {
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003702 if (request->input_buffer != nullptr) {
3703 int32_t streamId = Camera3Stream::cast(request->input_buffer->stream)->getId();
3704 buffer_handle_t buf = *(request->input_buffer->buffer);
3705 auto pair = getBufferId(buf, streamId);
3706 bool isNewBuffer = pair.first;
3707 uint64_t bufferId = pair.second;
3708 captureRequest->inputBuffer.streamId = streamId;
3709 captureRequest->inputBuffer.bufferId = bufferId;
3710 captureRequest->inputBuffer.buffer = (isNewBuffer) ? buf : nullptr;
3711 captureRequest->inputBuffer.status = BufferStatus::OK;
3712 native_handle_t *acquireFence = nullptr;
3713 if (request->input_buffer->acquire_fence != -1) {
3714 acquireFence = native_handle_create(1,0);
3715 acquireFence->data[0] = request->input_buffer->acquire_fence;
3716 handlesCreated->push_back(acquireFence);
3717 }
3718 captureRequest->inputBuffer.acquireFence = acquireFence;
3719 captureRequest->inputBuffer.releaseFence = nullptr;
3720
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003721 mBufferRecords.pushInflightBuffer(captureRequest->frameNumber, streamId,
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003722 request->input_buffer->buffer);
3723 inflightBuffers->push_back(std::make_pair(captureRequest->frameNumber, streamId));
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003724 } else {
3725 captureRequest->inputBuffer.streamId = -1;
3726 captureRequest->inputBuffer.bufferId = BUFFER_ID_NO_BUFFER;
3727 }
3728
3729 captureRequest->outputBuffers.resize(request->num_output_buffers);
3730 for (size_t i = 0; i < request->num_output_buffers; i++) {
Emilian Peevf4816702020-04-03 15:44:51 -07003731 const camera_stream_buffer_t *src = request->output_buffers + i;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003732 StreamBuffer &dst = captureRequest->outputBuffers[i];
3733 int32_t streamId = Camera3Stream::cast(src->stream)->getId();
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003734 if (src->buffer != nullptr) {
3735 buffer_handle_t buf = *(src->buffer);
3736 auto pair = getBufferId(buf, streamId);
3737 bool isNewBuffer = pair.first;
3738 dst.bufferId = pair.second;
3739 dst.buffer = isNewBuffer ? buf : nullptr;
3740 native_handle_t *acquireFence = nullptr;
3741 if (src->acquire_fence != -1) {
3742 acquireFence = native_handle_create(1,0);
3743 acquireFence->data[0] = src->acquire_fence;
3744 handlesCreated->push_back(acquireFence);
3745 }
3746 dst.acquireFence = acquireFence;
3747 } else if (mUseHalBufManager) {
3748 // HAL buffer management path
3749 dst.bufferId = BUFFER_ID_NO_BUFFER;
3750 dst.buffer = nullptr;
3751 dst.acquireFence = nullptr;
3752 } else {
3753 ALOGE("%s: cannot send a null buffer in capture request!", __FUNCTION__);
3754 return BAD_VALUE;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003755 }
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003756 dst.streamId = streamId;
3757 dst.status = BufferStatus::OK;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003758 dst.releaseFence = nullptr;
3759
Yin-Chia Yeh5f840f82019-03-05 11:59:04 -08003760 // Output buffers are empty when using HAL buffer manager
3761 if (!mUseHalBufManager) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003762 mBufferRecords.pushInflightBuffer(
3763 captureRequest->frameNumber, streamId, src->buffer);
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003764 inflightBuffers->push_back(std::make_pair(captureRequest->frameNumber, streamId));
Yin-Chia Yeh5f840f82019-03-05 11:59:04 -08003765 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003766 }
3767 }
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003768 return OK;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003769}
3770
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003771void Camera3Device::HalInterface::cleanupNativeHandles(
3772 std::vector<native_handle_t*> *handles, bool closeFd) {
3773 if (handles == nullptr) {
3774 return;
3775 }
3776 if (closeFd) {
3777 for (auto& handle : *handles) {
3778 native_handle_close(handle);
3779 }
3780 }
3781 for (auto& handle : *handles) {
3782 native_handle_delete(handle);
3783 }
3784 handles->clear();
3785 return;
3786}
3787
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003788status_t Camera3Device::HalInterface::processBatchCaptureRequests(
Emilian Peevf4816702020-04-03 15:44:51 -07003789 std::vector<camera_capture_request_t*>& requests,/*out*/uint32_t* numRequestProcessed) {
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003790 ATRACE_NAME("CameraHal::processBatchCaptureRequests");
3791 if (!valid()) return INVALID_OPERATION;
3792
Emilian Peevaebbe412018-01-15 13:53:24 +00003793 sp<device::V3_4::ICameraDeviceSession> hidlSession_3_4;
Shuzhen Wang83bff122020-11-20 15:51:39 -08003794 sp<device::V3_7::ICameraDeviceSession> hidlSession_3_7;
3795 auto castResult_3_7 = device::V3_7::ICameraDeviceSession::castFrom(mHidlSession);
3796 if (castResult_3_7.isOk()) {
3797 hidlSession_3_7 = castResult_3_7;
3798 }
Emilian Peevaebbe412018-01-15 13:53:24 +00003799 auto castResult_3_4 = device::V3_4::ICameraDeviceSession::castFrom(mHidlSession);
3800 if (castResult_3_4.isOk()) {
3801 hidlSession_3_4 = castResult_3_4;
3802 }
3803
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003804 hardware::hidl_vec<device::V3_2::CaptureRequest> captureRequests;
Emilian Peevaebbe412018-01-15 13:53:24 +00003805 hardware::hidl_vec<device::V3_4::CaptureRequest> captureRequests_3_4;
Shuzhen Wang83bff122020-11-20 15:51:39 -08003806 hardware::hidl_vec<device::V3_7::CaptureRequest> captureRequests_3_7;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003807 size_t batchSize = requests.size();
Shuzhen Wang83bff122020-11-20 15:51:39 -08003808 if (hidlSession_3_7 != nullptr) {
3809 captureRequests_3_7.resize(batchSize);
3810 } else if (hidlSession_3_4 != nullptr) {
Emilian Peevaebbe412018-01-15 13:53:24 +00003811 captureRequests_3_4.resize(batchSize);
3812 } else {
3813 captureRequests.resize(batchSize);
3814 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003815 std::vector<native_handle_t*> handlesCreated;
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003816 std::vector<std::pair<int32_t, int32_t>> inflightBuffers;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003817
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003818 status_t res = OK;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003819 for (size_t i = 0; i < batchSize; i++) {
Shuzhen Wang83bff122020-11-20 15:51:39 -08003820 if (hidlSession_3_7 != nullptr) {
3821 res = wrapAsHidlRequest(requests[i], /*out*/&captureRequests_3_7[i].v3_4.v3_2,
3822 /*out*/&handlesCreated, /*out*/&inflightBuffers);
3823 } else if (hidlSession_3_4 != nullptr) {
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003824 res = wrapAsHidlRequest(requests[i], /*out*/&captureRequests_3_4[i].v3_2,
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003825 /*out*/&handlesCreated, /*out*/&inflightBuffers);
Emilian Peevaebbe412018-01-15 13:53:24 +00003826 } else {
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003827 res = wrapAsHidlRequest(requests[i], /*out*/&captureRequests[i],
3828 /*out*/&handlesCreated, /*out*/&inflightBuffers);
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003829 }
3830 if (res != OK) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003831 mBufferRecords.popInflightBuffers(inflightBuffers);
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003832 cleanupNativeHandles(&handlesCreated);
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003833 return res;
Emilian Peevaebbe412018-01-15 13:53:24 +00003834 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003835 }
3836
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003837 std::vector<device::V3_2::BufferCache> cachesToRemove;
3838 {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003839 std::lock_guard<std::mutex> lock(mFreedBuffersLock);
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003840 for (auto& pair : mFreedBuffers) {
3841 // The stream might have been removed since onBufferFreed
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003842 if (mBufferRecords.isStreamCached(pair.first)) {
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003843 cachesToRemove.push_back({pair.first, pair.second});
3844 }
3845 }
3846 mFreedBuffers.clear();
3847 }
3848
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003849 common::V1_0::Status status = common::V1_0::Status::INTERNAL_ERROR;
3850 *numRequestProcessed = 0;
Yifan Hongf79b5542017-04-11 14:44:25 -07003851
3852 // Write metadata to FMQ.
3853 for (size_t i = 0; i < batchSize; i++) {
Emilian Peevf4816702020-04-03 15:44:51 -07003854 camera_capture_request_t* request = requests[i];
Emilian Peevaebbe412018-01-15 13:53:24 +00003855 device::V3_2::CaptureRequest* captureRequest;
Shuzhen Wang83bff122020-11-20 15:51:39 -08003856 if (hidlSession_3_7 != nullptr) {
3857 captureRequest = &captureRequests_3_7[i].v3_4.v3_2;
3858 } else if (hidlSession_3_4 != nullptr) {
Emilian Peevaebbe412018-01-15 13:53:24 +00003859 captureRequest = &captureRequests_3_4[i].v3_2;
3860 } else {
3861 captureRequest = &captureRequests[i];
3862 }
Yifan Hongf79b5542017-04-11 14:44:25 -07003863
3864 if (request->settings != nullptr) {
3865 size_t settingsSize = get_camera_metadata_size(request->settings);
3866 if (mRequestMetadataQueue != nullptr && mRequestMetadataQueue->write(
3867 reinterpret_cast<const uint8_t*>(request->settings), settingsSize)) {
3868 captureRequest->settings.resize(0);
3869 captureRequest->fmqSettingsSize = settingsSize;
3870 } else {
3871 if (mRequestMetadataQueue != nullptr) {
3872 ALOGW("%s: couldn't utilize fmq, fallback to hwbinder", __FUNCTION__);
3873 }
3874 captureRequest->settings.setToExternal(
3875 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(request->settings)),
3876 get_camera_metadata_size(request->settings));
3877 captureRequest->fmqSettingsSize = 0u;
3878 }
3879 } else {
3880 // A null request settings maps to a size-0 CameraMetadata
3881 captureRequest->settings.resize(0);
3882 captureRequest->fmqSettingsSize = 0u;
3883 }
Emilian Peevaebbe412018-01-15 13:53:24 +00003884
Shuzhen Wang83bff122020-11-20 15:51:39 -08003885 // hidl session 3.7 specific handling.
3886 if (hidlSession_3_7 != nullptr) {
3887 captureRequests_3_7[i].inputWidth = request->input_width;
3888 captureRequests_3_7[i].inputHeight = request->input_height;
3889 }
3890
3891 // hidl session 3.7 and 3.4 specific handling.
3892 if (hidlSession_3_7 != nullptr || hidlSession_3_4 != nullptr) {
3893 hardware::hidl_vec<device::V3_4::PhysicalCameraSetting>& physicalCameraSettings =
3894 (hidlSession_3_7 != nullptr) ?
3895 captureRequests_3_7[i].v3_4.physicalCameraSettings :
3896 captureRequests_3_4[i].physicalCameraSettings;
3897 physicalCameraSettings.resize(request->num_physcam_settings);
Emilian Peevaebbe412018-01-15 13:53:24 +00003898 for (size_t j = 0; j < request->num_physcam_settings; j++) {
Emilian Peev00420d22018-02-05 21:33:13 +00003899 if (request->physcam_settings != nullptr) {
3900 size_t settingsSize = get_camera_metadata_size(request->physcam_settings[j]);
3901 if (mRequestMetadataQueue != nullptr && mRequestMetadataQueue->write(
3902 reinterpret_cast<const uint8_t*>(request->physcam_settings[j]),
3903 settingsSize)) {
Shuzhen Wang83bff122020-11-20 15:51:39 -08003904 physicalCameraSettings[j].settings.resize(0);
3905 physicalCameraSettings[j].fmqSettingsSize = settingsSize;
Emilian Peev00420d22018-02-05 21:33:13 +00003906 } else {
3907 if (mRequestMetadataQueue != nullptr) {
3908 ALOGW("%s: couldn't utilize fmq, fallback to hwbinder", __FUNCTION__);
3909 }
Shuzhen Wang83bff122020-11-20 15:51:39 -08003910 physicalCameraSettings[j].settings.setToExternal(
Emilian Peev00420d22018-02-05 21:33:13 +00003911 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(
3912 request->physcam_settings[j])),
3913 get_camera_metadata_size(request->physcam_settings[j]));
Shuzhen Wang83bff122020-11-20 15:51:39 -08003914 physicalCameraSettings[j].fmqSettingsSize = 0u;
Emilian Peevaebbe412018-01-15 13:53:24 +00003915 }
Emilian Peev00420d22018-02-05 21:33:13 +00003916 } else {
Yin-Chia Yeha2849702021-03-10 10:11:33 -08003917 physicalCameraSettings[j].fmqSettingsSize = 0u;
3918 physicalCameraSettings[j].settings.resize(0);
Emilian Peevaebbe412018-01-15 13:53:24 +00003919 }
Shuzhen Wang83bff122020-11-20 15:51:39 -08003920 physicalCameraSettings[j].physicalCameraId = request->physcam_id[j];
Emilian Peevaebbe412018-01-15 13:53:24 +00003921 }
3922 }
Yifan Hongf79b5542017-04-11 14:44:25 -07003923 }
Emilian Peevaebbe412018-01-15 13:53:24 +00003924
3925 hardware::details::return_status err;
Jayant Chowdharyc8d581e2018-07-16 14:46:23 -07003926 auto resultCallback =
3927 [&status, &numRequestProcessed] (auto s, uint32_t n) {
3928 status = s;
3929 *numRequestProcessed = n;
3930 };
Shuzhen Wang83bff122020-11-20 15:51:39 -08003931 if (hidlSession_3_7 != nullptr) {
3932 err = hidlSession_3_7->processCaptureRequest_3_7(captureRequests_3_7, cachesToRemove,
3933 resultCallback);
3934 } else if (hidlSession_3_4 != nullptr) {
Emilian Peevaebbe412018-01-15 13:53:24 +00003935 err = hidlSession_3_4->processCaptureRequest_3_4(captureRequests_3_4, cachesToRemove,
Jayant Chowdharyc8d581e2018-07-16 14:46:23 -07003936 resultCallback);
Emilian Peevaebbe412018-01-15 13:53:24 +00003937 } else {
3938 err = mHidlSession->processCaptureRequest(captureRequests, cachesToRemove,
Jayant Chowdharyc8d581e2018-07-16 14:46:23 -07003939 resultCallback);
Emilian Peevaebbe412018-01-15 13:53:24 +00003940 }
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -07003941 if (!err.isOk()) {
3942 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003943 status = common::V1_0::Status::CAMERA_DISCONNECTED;
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -07003944 }
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003945
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003946 if (status == common::V1_0::Status::OK && *numRequestProcessed != batchSize) {
3947 ALOGE("%s: processCaptureRequest returns OK but processed %d/%zu requests",
3948 __FUNCTION__, *numRequestProcessed, batchSize);
3949 status = common::V1_0::Status::INTERNAL_ERROR;
3950 }
3951
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003952 res = CameraProviderManager::mapToStatusT(status);
3953 if (res == OK) {
3954 if (mHidlSession->isRemote()) {
3955 // Only close acquire fence FDs when the HIDL transaction succeeds (so the FDs have been
3956 // sent to camera HAL processes)
3957 cleanupNativeHandles(&handlesCreated, /*closeFd*/true);
3958 } else {
3959 // In passthrough mode the FDs are now owned by HAL
3960 cleanupNativeHandles(&handlesCreated);
3961 }
3962 } else {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003963 mBufferRecords.popInflightBuffers(inflightBuffers);
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003964 cleanupNativeHandles(&handlesCreated);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003965 }
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003966 return res;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003967}
3968
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003969status_t Camera3Device::HalInterface::flush() {
3970 ATRACE_NAME("CameraHal::flush");
3971 if (!valid()) return INVALID_OPERATION;
3972 status_t res = OK;
3973
Emilian Peev31abd0a2017-05-11 18:37:46 +01003974 auto err = mHidlSession->flush();
3975 if (!err.isOk()) {
3976 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3977 res = DEAD_OBJECT;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003978 } else {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003979 res = CameraProviderManager::mapToStatusT(err);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003980 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003981
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003982 return res;
3983}
3984
Emilian Peev31abd0a2017-05-11 18:37:46 +01003985status_t Camera3Device::HalInterface::dump(int /*fd*/) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003986 ATRACE_NAME("CameraHal::dump");
3987 if (!valid()) return INVALID_OPERATION;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003988
Emilian Peev31abd0a2017-05-11 18:37:46 +01003989 // Handled by CameraProviderManager::dump
3990
3991 return OK;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003992}
3993
3994status_t Camera3Device::HalInterface::close() {
3995 ATRACE_NAME("CameraHal::close()");
3996 if (!valid()) return INVALID_OPERATION;
3997 status_t res = OK;
3998
Emilian Peev31abd0a2017-05-11 18:37:46 +01003999 auto err = mHidlSession->close();
4000 // Interface will be dead shortly anyway, so don't log errors
4001 if (!err.isOk()) {
4002 res = DEAD_OBJECT;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004003 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01004004
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004005 return res;
4006}
4007
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004008void Camera3Device::HalInterface::signalPipelineDrain(const std::vector<int>& streamIds) {
4009 ATRACE_NAME("CameraHal::signalPipelineDrain");
4010 if (!valid() || mHidlSession_3_5 == nullptr) {
4011 ALOGE("%s called on invalid camera!", __FUNCTION__);
4012 return;
4013 }
4014
Yin-Chia Yehc300a072019-02-13 14:56:57 -08004015 auto err = mHidlSession_3_5->signalStreamFlush(streamIds, mNextStreamConfigCounter - 1);
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004016 if (!err.isOk()) {
4017 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
4018 return;
4019 }
4020}
4021
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004022status_t Camera3Device::HalInterface::switchToOffline(
4023 const std::vector<int32_t>& streamsToKeep,
4024 /*out*/hardware::camera::device::V3_6::CameraOfflineSessionInfo* offlineSessionInfo,
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004025 /*out*/sp<hardware::camera::device::V3_6::ICameraOfflineSession>* offlineSession,
4026 /*out*/camera3::BufferRecords* bufferRecords) {
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004027 ATRACE_NAME("CameraHal::switchToOffline");
4028 if (!valid() || mHidlSession_3_6 == nullptr) {
4029 ALOGE("%s called on invalid camera!", __FUNCTION__);
4030 return INVALID_OPERATION;
4031 }
4032
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004033 if (offlineSessionInfo == nullptr || offlineSession == nullptr || bufferRecords == nullptr) {
4034 ALOGE("%s: output arguments must not be null!", __FUNCTION__);
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004035 return INVALID_OPERATION;
4036 }
4037
4038 common::V1_0::Status status = common::V1_0::Status::INTERNAL_ERROR;
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004039 auto resultCallback =
4040 [&status, &offlineSessionInfo, &offlineSession] (auto s, auto info, auto session) {
4041 status = s;
4042 *offlineSessionInfo = info;
4043 *offlineSession = session;
4044 };
4045 auto err = mHidlSession_3_6->switchToOffline(streamsToKeep, resultCallback);
4046
4047 if (!err.isOk()) {
4048 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
4049 return DEAD_OBJECT;
4050 }
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004051
4052 status_t ret = CameraProviderManager::mapToStatusT(status);
4053 if (ret != OK) {
4054 return ret;
4055 }
4056
4057 // TODO: assert no ongoing requestBuffer/returnBuffer call here
4058 // TODO: update RequestBufferStateMachine to block requestBuffer/returnBuffer once HAL
4059 // returns from switchToOffline.
4060
4061
4062 // Validate buffer caches
4063 std::vector<int32_t> streams;
4064 streams.reserve(offlineSessionInfo->offlineStreams.size());
4065 for (auto offlineStream : offlineSessionInfo->offlineStreams) {
4066 int32_t id = offlineStream.id;
4067 streams.push_back(id);
4068 // Verify buffer caches
4069 std::vector<uint64_t> bufIds(offlineStream.circulatingBufferIds.begin(),
4070 offlineStream.circulatingBufferIds.end());
4071 if (!verifyBufferIds(id, bufIds)) {
4072 ALOGE("%s: stream ID %d buffer cache records mismatch!", __FUNCTION__, id);
4073 return UNKNOWN_ERROR;
4074 }
4075 }
4076
4077 // Move buffer records
4078 bufferRecords->takeBufferCaches(mBufferRecords, streams);
4079 bufferRecords->takeInflightBufferMap(mBufferRecords);
4080 bufferRecords->takeRequestedBufferMap(mBufferRecords);
4081 return ret;
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004082}
4083
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07004084void Camera3Device::HalInterface::getInflightBufferKeys(
4085 std::vector<std::pair<int32_t, int32_t>>* out) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004086 mBufferRecords.getInflightBufferKeys(out);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07004087 return;
4088}
4089
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08004090void Camera3Device::HalInterface::getInflightRequestBufferKeys(
4091 std::vector<uint64_t>* out) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004092 mBufferRecords.getInflightRequestBufferKeys(out);
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08004093 return;
4094}
4095
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004096bool Camera3Device::HalInterface::verifyBufferIds(
4097 int32_t streamId, std::vector<uint64_t>& bufIds) {
4098 return mBufferRecords.verifyBufferIds(streamId, bufIds);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004099}
4100
4101status_t Camera3Device::HalInterface::popInflightBuffer(
Yin-Chia Yehf4650602017-01-10 13:13:39 -08004102 int32_t frameNumber, int32_t streamId,
4103 /*out*/ buffer_handle_t **buffer) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004104 return mBufferRecords.popInflightBuffer(frameNumber, streamId, buffer);
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07004105}
4106
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004107status_t Camera3Device::HalInterface::pushInflightRequestBuffer(
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08004108 uint64_t bufferId, buffer_handle_t* buf, int32_t streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004109 return mBufferRecords.pushInflightRequestBuffer(bufferId, buf, streamId);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004110}
4111
4112// Find and pop a buffer_handle_t based on bufferId
4113status_t Camera3Device::HalInterface::popInflightRequestBuffer(
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08004114 uint64_t bufferId,
4115 /*out*/ buffer_handle_t** buffer,
4116 /*optional out*/ int32_t* streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004117 return mBufferRecords.popInflightRequestBuffer(bufferId, buffer, streamId);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004118}
4119
Yin-Chia Yeh77327052017-01-09 18:23:07 -08004120std::pair<bool, uint64_t> Camera3Device::HalInterface::getBufferId(
4121 const buffer_handle_t& buf, int streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004122 return mBufferRecords.getBufferId(buf, streamId);
Yin-Chia Yeh77327052017-01-09 18:23:07 -08004123}
4124
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07004125void Camera3Device::HalInterface::onBufferFreed(
4126 int streamId, const native_handle_t* handle) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004127 uint32_t bufferId = mBufferRecords.removeOneBufferCache(streamId, handle);
4128 std::lock_guard<std::mutex> lock(mFreedBuffersLock);
4129 if (bufferId != BUFFER_ID_NO_BUFFER) {
4130 mFreedBuffers.push_back(std::make_pair(streamId, bufferId));
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07004131 }
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07004132}
4133
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07004134void Camera3Device::HalInterface::onStreamReConfigured(int streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004135 std::vector<uint64_t> bufIds = mBufferRecords.clearBufferCaches(streamId);
4136 std::lock_guard<std::mutex> lock(mFreedBuffersLock);
4137 for (auto bufferId : bufIds) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07004138 mFreedBuffers.push_back(std::make_pair(streamId, bufferId));
4139 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07004140}
4141
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004142/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004143 * RequestThread inner class methods
4144 */
4145
4146Camera3Device::RequestThread::RequestThread(wp<Camera3Device> parent,
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004147 sp<StatusTracker> statusTracker,
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004148 sp<HalInterface> interface, const Vector<int32_t>& sessionParamKeys,
4149 bool useHalBufManager) :
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004150 Thread(/*canCallJava*/false),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004151 mParent(parent),
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004152 mStatusTracker(statusTracker),
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004153 mInterface(interface),
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07004154 mListener(nullptr),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004155 mId(getId(parent)),
Shuzhen Wang316781a2020-08-18 18:11:01 -07004156 mFirstRepeating(false),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004157 mReconfigured(false),
4158 mDoPause(false),
4159 mPaused(true),
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004160 mNotifyPipelineDrain(false),
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004161 mFrameNumber(0),
Jianing Weicb0652e2014-03-12 18:29:36 -07004162 mLatestRequestId(NAME_NOT_FOUND),
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07004163 mCurrentAfTriggerId(0),
4164 mCurrentPreCaptureTriggerId(0),
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004165 mRotateAndCropOverride(ANDROID_SCALER_ROTATE_AND_CROP_NONE),
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004166 mCameraMute(false),
4167 mCameraMuteChanged(false),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004168 mRepeatingLastFrameNumber(
4169 hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES),
Shuzhen Wang686f6442017-06-20 16:16:04 -07004170 mPrepareVideoStream(false),
Emilian Peeva14b4dd2018-05-15 11:00:31 +01004171 mConstrainedMode(false),
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004172 mRequestLatency(kRequestLatencyBinSize),
4173 mSessionParamKeys(sessionParamKeys),
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004174 mLatestSessionParams(sessionParamKeys.size()),
4175 mUseHalBufManager(useHalBufManager) {
Yin-Chia Yeh87b3ec02019-06-03 10:44:39 -07004176 mStatusId = statusTracker->addComponent("RequestThread");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004177}
4178
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004179Camera3Device::RequestThread::~RequestThread() {}
4180
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004181void Camera3Device::RequestThread::setNotificationListener(
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004182 wp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004183 ATRACE_CALL();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004184 Mutex::Autolock l(mRequestLock);
4185 mListener = listener;
4186}
4187
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004188void Camera3Device::RequestThread::configurationComplete(bool isConstrainedHighSpeed,
Shuzhen Wang99080502021-03-07 21:08:20 -08004189 const CameraMetadata& sessionParams,
4190 const std::map<int32_t, std::set<String8>>& groupIdPhysicalCameraMap) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004191 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004192 Mutex::Autolock l(mRequestLock);
4193 mReconfigured = true;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004194 mLatestSessionParams = sessionParams;
Shuzhen Wang99080502021-03-07 21:08:20 -08004195 mGroupIdPhysicalCameraMap = groupIdPhysicalCameraMap;
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07004196 // Prepare video stream for high speed recording.
4197 mPrepareVideoStream = isConstrainedHighSpeed;
Emilian Peeva14b4dd2018-05-15 11:00:31 +01004198 mConstrainedMode = isConstrainedHighSpeed;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004199}
4200
Jianing Wei90e59c92014-03-12 18:29:36 -07004201status_t Camera3Device::RequestThread::queueRequestList(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004202 List<sp<CaptureRequest> > &requests,
4203 /*out*/
4204 int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004205 ATRACE_CALL();
Jianing Wei90e59c92014-03-12 18:29:36 -07004206 Mutex::Autolock l(mRequestLock);
4207 for (List<sp<CaptureRequest> >::iterator it = requests.begin(); it != requests.end();
4208 ++it) {
4209 mRequestQueue.push_back(*it);
4210 }
4211
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004212 if (lastFrameNumber != NULL) {
4213 *lastFrameNumber = mFrameNumber + mRequestQueue.size() - 1;
4214 ALOGV("%s: requestId %d, mFrameNumber %" PRId32 ", lastFrameNumber %" PRId64 ".",
4215 __FUNCTION__, (*(requests.begin()))->mResultExtras.requestId, mFrameNumber,
4216 *lastFrameNumber);
4217 }
Jianing Weicb0652e2014-03-12 18:29:36 -07004218
Jianing Wei90e59c92014-03-12 18:29:36 -07004219 unpauseForNewRequests();
4220
4221 return OK;
4222}
4223
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004224
4225status_t Camera3Device::RequestThread::queueTrigger(
4226 RequestTrigger trigger[],
4227 size_t count) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004228 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004229 Mutex::Autolock l(mTriggerMutex);
4230 status_t ret;
4231
4232 for (size_t i = 0; i < count; ++i) {
4233 ret = queueTriggerLocked(trigger[i]);
4234
4235 if (ret != OK) {
4236 return ret;
4237 }
4238 }
4239
4240 return OK;
4241}
4242
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004243const String8& Camera3Device::RequestThread::getId(const wp<Camera3Device> &device) {
4244 static String8 deadId("<DeadDevice>");
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004245 sp<Camera3Device> d = device.promote();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004246 if (d != nullptr) return d->mId;
4247 return deadId;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004248}
4249
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004250status_t Camera3Device::RequestThread::queueTriggerLocked(
4251 RequestTrigger trigger) {
4252
4253 uint32_t tag = trigger.metadataTag;
4254 ssize_t index = mTriggerMap.indexOfKey(tag);
4255
4256 switch (trigger.getTagType()) {
4257 case TYPE_BYTE:
4258 // fall-through
4259 case TYPE_INT32:
4260 break;
4261 default:
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004262 ALOGE("%s: Type not supported: 0x%x", __FUNCTION__,
4263 trigger.getTagType());
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004264 return INVALID_OPERATION;
4265 }
4266
4267 /**
4268 * Collect only the latest trigger, since we only have 1 field
4269 * in the request settings per trigger tag, and can't send more than 1
4270 * trigger per request.
4271 */
4272 if (index != NAME_NOT_FOUND) {
4273 mTriggerMap.editValueAt(index) = trigger;
4274 } else {
4275 mTriggerMap.add(tag, trigger);
4276 }
4277
4278 return OK;
4279}
4280
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004281status_t Camera3Device::RequestThread::setRepeatingRequests(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004282 const RequestList &requests,
4283 /*out*/
4284 int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004285 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004286 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004287 if (lastFrameNumber != NULL) {
4288 *lastFrameNumber = mRepeatingLastFrameNumber;
4289 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004290 mRepeatingRequests.clear();
Shuzhen Wang316781a2020-08-18 18:11:01 -07004291 mFirstRepeating = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004292 mRepeatingRequests.insert(mRepeatingRequests.begin(),
4293 requests.begin(), requests.end());
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004294
4295 unpauseForNewRequests();
4296
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004297 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004298 return OK;
4299}
4300
Chih-Hung Hsieh8b0b9712016-08-09 14:25:53 -07004301bool Camera3Device::RequestThread::isRepeatingRequestLocked(const sp<CaptureRequest>& requestIn) {
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07004302 if (mRepeatingRequests.empty()) {
4303 return false;
4304 }
4305 int32_t requestId = requestIn->mResultExtras.requestId;
4306 const RequestList &repeatRequests = mRepeatingRequests;
4307 // All repeating requests are guaranteed to have same id so only check first quest
4308 const sp<CaptureRequest> firstRequest = *repeatRequests.begin();
4309 return (firstRequest->mResultExtras.requestId == requestId);
4310}
4311
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004312status_t Camera3Device::RequestThread::clearRepeatingRequests(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004313 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004314 Mutex::Autolock l(mRequestLock);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004315 return clearRepeatingRequestsLocked(lastFrameNumber);
4316
4317}
4318
4319status_t Camera3Device::RequestThread::clearRepeatingRequestsLocked(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004320 mRepeatingRequests.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004321 if (lastFrameNumber != NULL) {
4322 *lastFrameNumber = mRepeatingLastFrameNumber;
4323 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004324 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004325 return OK;
4326}
4327
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004328status_t Camera3Device::RequestThread::clear(
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004329 /*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004330 ATRACE_CALL();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004331 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004332 ALOGV("RequestThread::%s:", __FUNCTION__);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004333
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004334 mRepeatingRequests.clear();
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07004335
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004336 // Send errors for all requests pending in the request queue, including
4337 // pending repeating requests
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004338 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004339 if (listener != NULL) {
4340 for (RequestList::iterator it = mRequestQueue.begin();
4341 it != mRequestQueue.end(); ++it) {
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004342 // Abort the input buffers for reprocess requests.
4343 if ((*it)->mInputStream != NULL) {
Emilian Peevf4816702020-04-03 15:44:51 -07004344 camera_stream_buffer_t inputBuffer;
Shuzhen Wang83bff122020-11-20 15:51:39 -08004345 camera3::Size inputBufferSize;
Eino-Ville Talvalaba435252017-06-21 16:07:25 -07004346 status_t res = (*it)->mInputStream->getInputBuffer(&inputBuffer,
Shuzhen Wang83bff122020-11-20 15:51:39 -08004347 &inputBufferSize, /*respectHalLimit*/ false);
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004348 if (res != OK) {
4349 ALOGW("%s: %d: couldn't get input buffer while clearing the request "
4350 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
4351 } else {
Emilian Peevf4816702020-04-03 15:44:51 -07004352 inputBuffer.status = CAMERA_BUFFER_STATUS_ERROR;
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004353 res = (*it)->mInputStream->returnInputBuffer(inputBuffer);
4354 if (res != OK) {
4355 ALOGE("%s: %d: couldn't return input buffer while clearing the request "
4356 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
4357 }
4358 }
4359 }
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004360 // Set the frame number this request would have had, if it
4361 // had been submitted; this frame number will not be reused.
4362 // The requestId and burstId fields were set when the request was
4363 // submitted originally (in convertMetadataListToRequestListLocked)
4364 (*it)->mResultExtras.frameNumber = mFrameNumber++;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004365 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004366 (*it)->mResultExtras);
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07004367 }
4368 }
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004369 mRequestQueue.clear();
Jinguang Dongb26e7a02016-11-14 16:04:02 +08004370
4371 Mutex::Autolock al(mTriggerMutex);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004372 mTriggerMap.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004373 if (lastFrameNumber != NULL) {
4374 *lastFrameNumber = mRepeatingLastFrameNumber;
4375 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004376 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Emilian Peev8dae54c2019-12-02 15:17:17 -08004377 mRequestSignal.signal();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004378 return OK;
4379}
4380
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004381status_t Camera3Device::RequestThread::flush() {
4382 ATRACE_CALL();
4383 Mutex::Autolock l(mFlushLock);
4384
Emilian Peev08dd2452017-04-06 16:55:14 +01004385 return mInterface->flush();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004386}
4387
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004388void Camera3Device::RequestThread::setPaused(bool paused) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004389 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004390 Mutex::Autolock l(mPauseLock);
4391 mDoPause = paused;
4392 mDoPauseSignal.signal();
4393}
4394
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004395status_t Camera3Device::RequestThread::waitUntilRequestProcessed(
4396 int32_t requestId, nsecs_t timeout) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004397 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004398 Mutex::Autolock l(mLatestRequestMutex);
4399 status_t res;
4400 while (mLatestRequestId != requestId) {
4401 nsecs_t startTime = systemTime();
4402
4403 res = mLatestRequestSignal.waitRelative(mLatestRequestMutex, timeout);
4404 if (res != OK) return res;
4405
4406 timeout -= (systemTime() - startTime);
4407 }
4408
4409 return OK;
4410}
4411
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004412void Camera3Device::RequestThread::requestExit() {
4413 // Call parent to set up shutdown
4414 Thread::requestExit();
4415 // The exit from any possible waits
4416 mDoPauseSignal.signal();
4417 mRequestSignal.signal();
Shuzhen Wang686f6442017-06-20 16:16:04 -07004418
4419 mRequestLatency.log("ProcessCaptureRequest latency histogram");
4420 mRequestLatency.reset();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004421}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004422
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004423void Camera3Device::RequestThread::checkAndStopRepeatingRequest() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004424 ATRACE_CALL();
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07004425 bool surfaceAbandoned = false;
4426 int64_t lastFrameNumber = 0;
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004427 sp<NotificationListener> listener;
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07004428 {
4429 Mutex::Autolock l(mRequestLock);
4430 // Check all streams needed by repeating requests are still valid. Otherwise, stop
4431 // repeating requests.
4432 for (const auto& request : mRepeatingRequests) {
4433 for (const auto& s : request->mOutputStreams) {
4434 if (s->isAbandoned()) {
4435 surfaceAbandoned = true;
4436 clearRepeatingRequestsLocked(&lastFrameNumber);
4437 break;
4438 }
4439 }
4440 if (surfaceAbandoned) {
4441 break;
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004442 }
4443 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004444 listener = mListener.promote();
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004445 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004446
4447 if (listener != NULL && surfaceAbandoned) {
4448 listener->notifyRepeatingRequestError(lastFrameNumber);
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07004449 }
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004450}
4451
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004452bool Camera3Device::RequestThread::sendRequestsBatch() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004453 ATRACE_CALL();
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004454 status_t res;
4455 size_t batchSize = mNextRequests.size();
Emilian Peevf4816702020-04-03 15:44:51 -07004456 std::vector<camera_capture_request_t*> requests(batchSize);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004457 uint32_t numRequestProcessed = 0;
4458 for (size_t i = 0; i < batchSize; i++) {
4459 requests[i] = &mNextRequests.editItemAt(i).halRequest;
Yin-Chia Yeh885691c2018-05-01 15:54:24 -07004460 ATRACE_ASYNC_BEGIN("frame capture", mNextRequests[i].halRequest.frame_number);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004461 }
4462
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004463 res = mInterface->processBatchCaptureRequests(requests, &numRequestProcessed);
4464
4465 bool triggerRemoveFailed = false;
4466 NextRequest& triggerFailedRequest = mNextRequests.editItemAt(0);
4467 for (size_t i = 0; i < numRequestProcessed; i++) {
4468 NextRequest& nextRequest = mNextRequests.editItemAt(i);
4469 nextRequest.submitted = true;
4470
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004471 updateNextRequest(nextRequest);
Emilian Peevaebbe412018-01-15 13:53:24 +00004472
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004473 if (!triggerRemoveFailed) {
4474 // Remove any previously queued triggers (after unlock)
4475 status_t removeTriggerRes = removeTriggers(mPrevRequest);
4476 if (removeTriggerRes != OK) {
4477 triggerRemoveFailed = true;
4478 triggerFailedRequest = nextRequest;
4479 }
4480 }
4481 }
4482
4483 if (triggerRemoveFailed) {
4484 SET_ERR("RequestThread: Unable to remove triggers "
4485 "(capture request %d, HAL device: %s (%d)",
4486 triggerFailedRequest.halRequest.frame_number, strerror(-res), res);
4487 cleanUpFailedRequests(/*sendRequestError*/ false);
4488 return false;
4489 }
4490
4491 if (res != OK) {
4492 // Should only get a failure here for malformed requests or device-level
4493 // errors, so consider all errors fatal. Bad metadata failures should
4494 // come through notify.
4495 SET_ERR("RequestThread: Unable to submit capture request %d to HAL device: %s (%d)",
4496 mNextRequests[numRequestProcessed].halRequest.frame_number,
4497 strerror(-res), res);
4498 cleanUpFailedRequests(/*sendRequestError*/ false);
4499 return false;
4500 }
4501 return true;
4502}
4503
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07004504nsecs_t Camera3Device::RequestThread::calculateMaxExpectedDuration(const camera_metadata_t *request) {
4505 nsecs_t maxExpectedDuration = kDefaultExpectedDuration;
4506 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
4507 find_camera_metadata_ro_entry(request,
4508 ANDROID_CONTROL_AE_MODE,
4509 &e);
4510 if (e.count == 0) return maxExpectedDuration;
4511
4512 switch (e.data.u8[0]) {
4513 case ANDROID_CONTROL_AE_MODE_OFF:
4514 find_camera_metadata_ro_entry(request,
4515 ANDROID_SENSOR_EXPOSURE_TIME,
4516 &e);
4517 if (e.count > 0) {
4518 maxExpectedDuration = e.data.i64[0];
4519 }
4520 find_camera_metadata_ro_entry(request,
4521 ANDROID_SENSOR_FRAME_DURATION,
4522 &e);
4523 if (e.count > 0) {
4524 maxExpectedDuration = std::max(e.data.i64[0], maxExpectedDuration);
4525 }
4526 break;
4527 default:
4528 find_camera_metadata_ro_entry(request,
4529 ANDROID_CONTROL_AE_TARGET_FPS_RANGE,
4530 &e);
4531 if (e.count > 1) {
4532 maxExpectedDuration = 1e9 / e.data.u8[0];
4533 }
4534 break;
4535 }
4536
4537 return maxExpectedDuration;
4538}
4539
Emilian Peeva14b4dd2018-05-15 11:00:31 +01004540bool Camera3Device::RequestThread::skipHFRTargetFPSUpdate(int32_t tag,
4541 const camera_metadata_ro_entry_t& newEntry, const camera_metadata_entry_t& currentEntry) {
4542 if (mConstrainedMode && (ANDROID_CONTROL_AE_TARGET_FPS_RANGE == tag) &&
4543 (newEntry.count == currentEntry.count) && (currentEntry.count == 2) &&
4544 (currentEntry.data.i32[1] == newEntry.data.i32[1])) {
4545 return true;
4546 }
4547
4548 return false;
4549}
4550
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004551void Camera3Device::RequestThread::updateNextRequest(NextRequest& nextRequest) {
4552 // Update the latest request sent to HAL
Shuzhen Wang83bff122020-11-20 15:51:39 -08004553 camera_capture_request_t& halRequest = nextRequest.halRequest;
4554 if (halRequest.settings != NULL) { // Don't update if they were unchanged
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004555 Mutex::Autolock al(mLatestRequestMutex);
4556
Shuzhen Wang83bff122020-11-20 15:51:39 -08004557 camera_metadata_t* cloned = clone_camera_metadata(halRequest.settings);
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004558 mLatestRequest.acquire(cloned);
4559
4560 mLatestPhysicalRequest.clear();
Shuzhen Wang83bff122020-11-20 15:51:39 -08004561 for (uint32_t i = 0; i < halRequest.num_physcam_settings; i++) {
4562 cloned = clone_camera_metadata(halRequest.physcam_settings[i]);
4563 mLatestPhysicalRequest.emplace(halRequest.physcam_id[i],
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004564 CameraMetadata(cloned));
4565 }
4566
4567 sp<Camera3Device> parent = mParent.promote();
4568 if (parent != NULL) {
4569 parent->monitorMetadata(TagMonitor::REQUEST,
Shuzhen Wang83bff122020-11-20 15:51:39 -08004570 halRequest.frame_number,
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004571 0, mLatestRequest, mLatestPhysicalRequest);
4572 }
4573 }
4574
Shuzhen Wang83bff122020-11-20 15:51:39 -08004575 if (halRequest.settings != NULL) {
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004576 nextRequest.captureRequest->mSettingsList.begin()->metadata.unlock(
Shuzhen Wang83bff122020-11-20 15:51:39 -08004577 halRequest.settings);
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004578 }
4579
Shuzhen Wang83bff122020-11-20 15:51:39 -08004580 cleanupPhysicalSettings(nextRequest.captureRequest, &halRequest);
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004581}
4582
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004583bool Camera3Device::RequestThread::updateSessionParameters(const CameraMetadata& settings) {
4584 ATRACE_CALL();
4585 bool updatesDetected = false;
4586
Emilian Peev4ec17882019-01-24 17:16:58 -08004587 CameraMetadata updatedParams(mLatestSessionParams);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004588 for (auto tag : mSessionParamKeys) {
4589 camera_metadata_ro_entry entry = settings.find(tag);
Emilian Peev4ec17882019-01-24 17:16:58 -08004590 camera_metadata_entry lastEntry = updatedParams.find(tag);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004591
4592 if (entry.count > 0) {
4593 bool isDifferent = false;
4594 if (lastEntry.count > 0) {
4595 // Have a last value, compare to see if changed
4596 if (lastEntry.type == entry.type &&
4597 lastEntry.count == entry.count) {
4598 // Same type and count, compare values
4599 size_t bytesPerValue = camera_metadata_type_size[lastEntry.type];
4600 size_t entryBytes = bytesPerValue * lastEntry.count;
4601 int cmp = memcmp(entry.data.u8, lastEntry.data.u8, entryBytes);
4602 if (cmp != 0) {
4603 isDifferent = true;
4604 }
4605 } else {
4606 // Count or type has changed
4607 isDifferent = true;
4608 }
4609 } else {
4610 // No last entry, so always consider to be different
4611 isDifferent = true;
4612 }
4613
4614 if (isDifferent) {
4615 ALOGV("%s: Session parameter tag id %d changed", __FUNCTION__, tag);
Emilian Peeva14b4dd2018-05-15 11:00:31 +01004616 if (!skipHFRTargetFPSUpdate(tag, entry, lastEntry)) {
4617 updatesDetected = true;
4618 }
Emilian Peev4ec17882019-01-24 17:16:58 -08004619 updatedParams.update(entry);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004620 }
4621 } else if (lastEntry.count > 0) {
4622 // Value has been removed
4623 ALOGV("%s: Session parameter tag id %d removed", __FUNCTION__, tag);
Emilian Peev4ec17882019-01-24 17:16:58 -08004624 updatedParams.erase(tag);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004625 updatesDetected = true;
4626 }
4627 }
4628
Emilian Peev4ec17882019-01-24 17:16:58 -08004629 bool reconfigureRequired;
4630 if (updatesDetected) {
4631 reconfigureRequired = mInterface->isReconfigurationRequired(mLatestSessionParams,
4632 updatedParams);
4633 mLatestSessionParams = updatedParams;
4634 } else {
4635 reconfigureRequired = false;
4636 }
4637
4638 return reconfigureRequired;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004639}
4640
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004641bool Camera3Device::RequestThread::threadLoop() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004642 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004643 status_t res;
Jayant Chowdhary37eca242019-11-18 08:55:56 -08004644 // Any function called from threadLoop() must not hold mInterfaceLock since
4645 // it could lead to deadlocks (disconnect() -> hold mInterfaceMutex -> wait for request thread
4646 // to finish -> request thread waits on mInterfaceMutex) http://b/143513518
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004647
4648 // Handle paused state.
4649 if (waitIfPaused()) {
4650 return true;
4651 }
4652
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004653 // Wait for the next batch of requests.
4654 waitForNextRequestBatch();
4655 if (mNextRequests.size() == 0) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004656 return true;
4657 }
4658
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004659 // Get the latest request ID, if any
4660 int latestRequestId;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004661 camera_metadata_entry_t requestIdEntry = mNextRequests[mNextRequests.size() - 1].
Emilian Peevaebbe412018-01-15 13:53:24 +00004662 captureRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_ID);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004663 if (requestIdEntry.count > 0) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004664 latestRequestId = requestIdEntry.data.i32[0];
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004665 } else {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004666 ALOGW("%s: Did not have android.request.id set in the request.", __FUNCTION__);
4667 latestRequestId = NAME_NOT_FOUND;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004668 }
4669
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004670 // 'mNextRequests' will at this point contain either a set of HFR batched requests
4671 // or a single request from streaming or burst. In either case the first element
4672 // should contain the latest camera settings that we need to check for any session
4673 // parameter updates.
Emilian Peevaebbe412018-01-15 13:53:24 +00004674 if (updateSessionParameters(mNextRequests[0].captureRequest->mSettingsList.begin()->metadata)) {
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004675 res = OK;
4676
4677 //Input stream buffers are already acquired at this point so an input stream
4678 //will not be able to move to idle state unless we force it.
4679 if (mNextRequests[0].captureRequest->mInputStream != nullptr) {
4680 res = mNextRequests[0].captureRequest->mInputStream->forceToIdle();
4681 if (res != OK) {
4682 ALOGE("%s: Failed to force idle input stream: %d", __FUNCTION__, res);
4683 cleanUpFailedRequests(/*sendRequestError*/ false);
4684 return false;
4685 }
4686 }
4687
4688 if (res == OK) {
Emilian Peev3bead5f2020-05-28 17:29:08 -07004689 sp<Camera3Device> parent = mParent.promote();
4690 if (parent != nullptr) {
4691 mReconfigured |= parent->reconfigureCamera(mLatestSessionParams, mStatusId);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004692 }
Emilian Peev3bead5f2020-05-28 17:29:08 -07004693 setPaused(false);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004694
4695 if (mNextRequests[0].captureRequest->mInputStream != nullptr) {
4696 mNextRequests[0].captureRequest->mInputStream->restoreConfiguredState();
4697 if (res != OK) {
4698 ALOGE("%s: Failed to restore configured input stream: %d", __FUNCTION__, res);
4699 cleanUpFailedRequests(/*sendRequestError*/ false);
4700 return false;
4701 }
4702 }
4703 }
4704 }
4705
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004706 // Prepare a batch of HAL requests and output buffers.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004707 res = prepareHalRequests();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004708 if (res == TIMED_OUT) {
4709 // Not a fatal error if getting output buffers time out.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004710 cleanUpFailedRequests(/*sendRequestError*/ true);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004711 // Check if any stream is abandoned.
4712 checkAndStopRepeatingRequest();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004713 return true;
4714 } else if (res != OK) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004715 cleanUpFailedRequests(/*sendRequestError*/ false);
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004716 return false;
4717 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004718
Zhijun Hecc27e112013-10-03 16:12:43 -07004719 // Inform waitUntilRequestProcessed thread of a new request ID
4720 {
4721 Mutex::Autolock al(mLatestRequestMutex);
4722
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004723 mLatestRequestId = latestRequestId;
Zhijun Hecc27e112013-10-03 16:12:43 -07004724 mLatestRequestSignal.signal();
4725 }
4726
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004727 // Submit a batch of requests to HAL.
4728 // Use flush lock only when submitting multilple requests in a batch.
4729 // TODO: The problem with flush lock is flush() will be blocked by process_capture_request()
4730 // which may take a long time to finish so synchronizing flush() and
4731 // process_capture_request() defeats the purpose of cancelling requests ASAP with flush().
4732 // For now, only synchronize for high speed recording and we should figure something out for
4733 // removing the synchronization.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004734 bool useFlushLock = mNextRequests.size() > 1;
Eino-Ville Talvala17a61ad2013-06-03 16:53:32 -07004735
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004736 if (useFlushLock) {
4737 mFlushLock.lock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004738 }
4739
Zhijun Hef0645c12016-08-02 00:58:11 -07004740 ALOGVV("%s: %d: submitting %zu requests in a batch.", __FUNCTION__, __LINE__,
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004741 mNextRequests.size());
Igor Murashkin1e479c02013-09-06 16:55:14 -07004742
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08004743 sp<Camera3Device> parent = mParent.promote();
4744 if (parent != nullptr) {
4745 parent->mRequestBufferSM.onSubmittingRequest();
4746 }
4747
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004748 bool submitRequestSuccess = false;
Shuzhen Wang686f6442017-06-20 16:16:04 -07004749 nsecs_t tRequestStart = systemTime(SYSTEM_TIME_MONOTONIC);
Yin-Chia Yeh11648852019-05-16 10:42:54 -07004750 submitRequestSuccess = sendRequestsBatch();
4751
Shuzhen Wang686f6442017-06-20 16:16:04 -07004752 nsecs_t tRequestEnd = systemTime(SYSTEM_TIME_MONOTONIC);
4753 mRequestLatency.add(tRequestStart, tRequestEnd);
Igor Murashkin1e479c02013-09-06 16:55:14 -07004754
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004755 if (useFlushLock) {
4756 mFlushLock.unlock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004757 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004758
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004759 // Unset as current request
4760 {
4761 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004762 mNextRequests.clear();
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004763 }
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004764 mRequestSubmittedSignal.signal();
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004765
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004766 return submitRequestSuccess;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004767}
4768
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004769status_t Camera3Device::RequestThread::prepareHalRequests() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004770 ATRACE_CALL();
4771
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07004772 bool batchedRequest = mNextRequests[0].captureRequest->mBatchSize > 1;
Shuzhen Wang4a472662017-02-26 23:29:04 -08004773 for (size_t i = 0; i < mNextRequests.size(); i++) {
4774 auto& nextRequest = mNextRequests.editItemAt(i);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004775 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
Emilian Peevf4816702020-04-03 15:44:51 -07004776 camera_capture_request_t* halRequest = &nextRequest.halRequest;
4777 Vector<camera_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004778
4779 // Prepare a request to HAL
4780 halRequest->frame_number = captureRequest->mResultExtras.frameNumber;
4781
4782 // Insert any queued triggers (before metadata is locked)
4783 status_t res = insertTriggers(captureRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004784 if (res < 0) {
4785 SET_ERR("RequestThread: Unable to insert triggers "
4786 "(capture request %d, HAL device: %s (%d)",
4787 halRequest->frame_number, strerror(-res), res);
4788 return INVALID_OPERATION;
4789 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07004790
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004791 int triggerCount = res;
4792 bool triggersMixedIn = (triggerCount > 0 || mPrevTriggers > 0);
4793 mPrevTriggers = triggerCount;
4794
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004795 bool rotateAndCropChanged = overrideAutoRotateAndCrop(captureRequest);
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004796 bool testPatternChanged = overrideTestPattern(captureRequest);
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004797
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004798 // If the request is the same as last, or we had triggers now or last time or
4799 // changing overrides this time
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004800 bool newRequest =
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004801 (mPrevRequest != captureRequest || triggersMixedIn ||
4802 rotateAndCropChanged || testPatternChanged) &&
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07004803 // Request settings are all the same within one batch, so only treat the first
4804 // request in a batch as new
Zhijun He54c36822018-07-18 09:33:39 -07004805 !(batchedRequest && i > 0);
Emilian Peev00420d22018-02-05 21:33:13 +00004806 if (newRequest) {
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08004807 std::set<std::string> cameraIdsWithZoom;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004808 /**
4809 * HAL workaround:
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004810 * Insert a fake trigger ID if a trigger is set but no trigger ID is
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004811 */
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004812 res = addFakeTriggerIds(captureRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004813 if (res != OK) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004814 SET_ERR("RequestThread: Unable to insert fake trigger IDs "
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004815 "(capture request %d, HAL device: %s (%d)",
4816 halRequest->frame_number, strerror(-res), res);
4817 return INVALID_OPERATION;
4818 }
4819
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07004820 {
4821 // Correct metadata regions for distortion correction if enabled
4822 sp<Camera3Device> parent = mParent.promote();
4823 if (parent != nullptr) {
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -07004824 List<PhysicalCameraSettings>::iterator it;
4825 for (it = captureRequest->mSettingsList.begin();
4826 it != captureRequest->mSettingsList.end(); it++) {
4827 if (parent->mDistortionMappers.find(it->cameraId) ==
4828 parent->mDistortionMappers.end()) {
4829 continue;
4830 }
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07004831
4832 if (!captureRequest->mDistortionCorrectionUpdated) {
4833 res = parent->mDistortionMappers[it->cameraId].correctCaptureRequest(
4834 &(it->metadata));
4835 if (res != OK) {
4836 SET_ERR("RequestThread: Unable to correct capture requests "
4837 "for lens distortion for request %d: %s (%d)",
4838 halRequest->frame_number, strerror(-res), res);
4839 return INVALID_OPERATION;
4840 }
4841 captureRequest->mDistortionCorrectionUpdated = true;
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -07004842 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07004843 }
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08004844
4845 for (it = captureRequest->mSettingsList.begin();
4846 it != captureRequest->mSettingsList.end(); it++) {
4847 if (parent->mZoomRatioMappers.find(it->cameraId) ==
4848 parent->mZoomRatioMappers.end()) {
4849 continue;
4850 }
4851
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07004852 if (!captureRequest->mZoomRatioIs1x) {
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08004853 cameraIdsWithZoom.insert(it->cameraId);
4854 }
4855
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07004856 if (!captureRequest->mZoomRatioUpdated) {
4857 res = parent->mZoomRatioMappers[it->cameraId].updateCaptureRequest(
4858 &(it->metadata));
4859 if (res != OK) {
4860 SET_ERR("RequestThread: Unable to correct capture requests "
4861 "for zoom ratio for request %d: %s (%d)",
4862 halRequest->frame_number, strerror(-res), res);
4863 return INVALID_OPERATION;
4864 }
4865 captureRequest->mZoomRatioUpdated = true;
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08004866 }
4867 }
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07004868 if (captureRequest->mRotateAndCropAuto &&
4869 !captureRequest->mRotationAndCropUpdated) {
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004870 for (it = captureRequest->mSettingsList.begin();
4871 it != captureRequest->mSettingsList.end(); it++) {
4872 auto mapper = parent->mRotateAndCropMappers.find(it->cameraId);
4873 if (mapper != parent->mRotateAndCropMappers.end()) {
4874 res = mapper->second.updateCaptureRequest(&(it->metadata));
4875 if (res != OK) {
4876 SET_ERR("RequestThread: Unable to correct capture requests "
4877 "for rotate-and-crop for request %d: %s (%d)",
4878 halRequest->frame_number, strerror(-res), res);
4879 return INVALID_OPERATION;
4880 }
4881 }
4882 }
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07004883 captureRequest->mRotationAndCropUpdated = true;
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004884 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07004885 }
4886 }
4887
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004888 /**
4889 * The request should be presorted so accesses in HAL
4890 * are O(logn). Sidenote, sorting a sorted metadata is nop.
4891 */
Emilian Peevaebbe412018-01-15 13:53:24 +00004892 captureRequest->mSettingsList.begin()->metadata.sort();
4893 halRequest->settings = captureRequest->mSettingsList.begin()->metadata.getAndLock();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004894 mPrevRequest = captureRequest;
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08004895 mPrevCameraIdsWithZoom = cameraIdsWithZoom;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004896 ALOGVV("%s: Request settings are NEW", __FUNCTION__);
4897
4898 IF_ALOGV() {
4899 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
4900 find_camera_metadata_ro_entry(
4901 halRequest->settings,
4902 ANDROID_CONTROL_AF_TRIGGER,
4903 &e
4904 );
4905 if (e.count > 0) {
4906 ALOGV("%s: Request (frame num %d) had AF trigger 0x%x",
4907 __FUNCTION__,
4908 halRequest->frame_number,
4909 e.data.u8[0]);
4910 }
4911 }
4912 } else {
4913 // leave request.settings NULL to indicate 'reuse latest given'
4914 ALOGVV("%s: Request settings are REUSED",
4915 __FUNCTION__);
4916 }
4917
Emilian Peevaebbe412018-01-15 13:53:24 +00004918 if (captureRequest->mSettingsList.size() > 1) {
4919 halRequest->num_physcam_settings = captureRequest->mSettingsList.size() - 1;
4920 halRequest->physcam_id = new const char* [halRequest->num_physcam_settings];
Emilian Peev00420d22018-02-05 21:33:13 +00004921 if (newRequest) {
4922 halRequest->physcam_settings =
4923 new const camera_metadata* [halRequest->num_physcam_settings];
4924 } else {
4925 halRequest->physcam_settings = nullptr;
4926 }
Emilian Peevaebbe412018-01-15 13:53:24 +00004927 auto it = ++captureRequest->mSettingsList.begin();
4928 size_t i = 0;
4929 for (; it != captureRequest->mSettingsList.end(); it++, i++) {
4930 halRequest->physcam_id[i] = it->cameraId.c_str();
Emilian Peev00420d22018-02-05 21:33:13 +00004931 if (newRequest) {
4932 it->metadata.sort();
4933 halRequest->physcam_settings[i] = it->metadata.getAndLock();
4934 }
Emilian Peevaebbe412018-01-15 13:53:24 +00004935 }
4936 }
4937
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004938 uint32_t totalNumBuffers = 0;
4939
4940 // Fill in buffers
4941 if (captureRequest->mInputStream != NULL) {
4942 halRequest->input_buffer = &captureRequest->mInputBuffer;
Shuzhen Wang83bff122020-11-20 15:51:39 -08004943
4944 halRequest->input_width = captureRequest->mInputBufferSize.width;
4945 halRequest->input_height = captureRequest->mInputBufferSize.height;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004946 totalNumBuffers += 1;
4947 } else {
4948 halRequest->input_buffer = NULL;
4949 }
4950
Emilian Peevf4816702020-04-03 15:44:51 -07004951 outputBuffers->insertAt(camera_stream_buffer_t(), 0,
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004952 captureRequest->mOutputStreams.size());
4953 halRequest->output_buffers = outputBuffers->array();
Shuzhen Wang99080502021-03-07 21:08:20 -08004954 std::set<std::set<String8>> requestedPhysicalCameras;
Yin-Chia Yehb3a80b12018-09-04 12:13:05 -07004955
4956 sp<Camera3Device> parent = mParent.promote();
4957 if (parent == NULL) {
4958 // Should not happen, and nowhere to send errors to, so just log it
4959 CLOGE("RequestThread: Parent is gone");
4960 return INVALID_OPERATION;
4961 }
4962 nsecs_t waitDuration = kBaseGetBufferWait + parent->getExpectedInFlightDuration();
4963
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07004964 SurfaceMap uniqueSurfaceIdMap;
Shuzhen Wang4a472662017-02-26 23:29:04 -08004965 for (size_t j = 0; j < captureRequest->mOutputStreams.size(); j++) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07004966 sp<Camera3OutputStreamInterface> outputStream =
4967 captureRequest->mOutputStreams.editItemAt(j);
4968 int streamId = outputStream->getId();
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07004969
4970 // Prepare video buffers for high speed recording on the first video request.
4971 if (mPrepareVideoStream && outputStream->isVideoStream()) {
4972 // Only try to prepare video stream on the first video request.
4973 mPrepareVideoStream = false;
4974
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07004975 res = outputStream->startPrepare(Camera3StreamInterface::ALLOCATE_PIPELINE_MAX,
4976 false /*blockRequest*/);
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07004977 while (res == NOT_ENOUGH_DATA) {
4978 res = outputStream->prepareNextBuffer();
4979 }
4980 if (res != OK) {
4981 ALOGW("%s: Preparing video buffers for high speed failed: %s (%d)",
4982 __FUNCTION__, strerror(-res), res);
4983 outputStream->cancelPrepare();
4984 }
4985 }
4986
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07004987 std::vector<size_t> uniqueSurfaceIds;
4988 res = outputStream->getUniqueSurfaceIds(
4989 captureRequest->mOutputSurfaces[streamId],
4990 &uniqueSurfaceIds);
4991 // INVALID_OPERATION is normal output for streams not supporting surfaceIds
4992 if (res != OK && res != INVALID_OPERATION) {
4993 ALOGE("%s: failed to query stream %d unique surface IDs",
4994 __FUNCTION__, streamId);
4995 return res;
4996 }
4997 if (res == OK) {
4998 uniqueSurfaceIdMap.insert({streamId, std::move(uniqueSurfaceIds)});
4999 }
5000
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07005001 if (mUseHalBufManager) {
Yin-Chia Yeh110342b2018-11-19 11:47:46 -08005002 if (outputStream->isAbandoned()) {
Yin-Chia Yeha1b56c82019-03-27 15:50:39 -07005003 ALOGV("%s: stream %d is abandoned, skipping request", __FUNCTION__, streamId);
Yin-Chia Yeh110342b2018-11-19 11:47:46 -08005004 return TIMED_OUT;
5005 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07005006 // HAL will request buffer through requestStreamBuffer API
Emilian Peevf4816702020-04-03 15:44:51 -07005007 camera_stream_buffer_t& buffer = outputBuffers->editItemAt(j);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07005008 buffer.stream = outputStream->asHalStream();
5009 buffer.buffer = nullptr;
Emilian Peevf4816702020-04-03 15:44:51 -07005010 buffer.status = CAMERA_BUFFER_STATUS_OK;
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07005011 buffer.acquire_fence = -1;
5012 buffer.release_fence = -1;
Emilian Peevf0348ae2021-01-13 13:39:45 -08005013 // Mark the output stream as unpreparable to block clients from calling
5014 // 'prepare' after this request reaches CameraHal and before the respective
5015 // buffers are requested.
5016 outputStream->markUnpreparable();
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07005017 } else {
5018 res = outputStream->getBuffer(&outputBuffers->editItemAt(j),
5019 waitDuration,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005020 captureRequest->mOutputSurfaces[streamId]);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07005021 if (res != OK) {
5022 // Can't get output buffer from gralloc queue - this could be due to
5023 // abandoned queue or other consumer misbehavior, so not a fatal
5024 // error
Yin-Chia Yeha1b56c82019-03-27 15:50:39 -07005025 ALOGV("RequestThread: Can't get output buffer, skipping request:"
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07005026 " %s (%d)", strerror(-res), res);
5027
5028 return TIMED_OUT;
5029 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005030 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08005031
5032 {
5033 sp<Camera3Device> parent = mParent.promote();
5034 if (parent != nullptr) {
5035 const String8& streamCameraId = outputStream->getPhysicalCameraId();
5036 for (const auto& settings : captureRequest->mSettingsList) {
5037 if ((streamCameraId.isEmpty() &&
5038 parent->getId() == settings.cameraId.c_str()) ||
5039 streamCameraId == settings.cameraId.c_str()) {
5040 outputStream->fireBufferRequestForFrameNumber(
5041 captureRequest->mResultExtras.frameNumber,
5042 settings.metadata);
5043 }
5044 }
5045 }
5046 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07005047
Shuzhen Wang5c22c152017-12-31 17:12:25 -08005048 String8 physicalCameraId = outputStream->getPhysicalCameraId();
Shuzhen Wang99080502021-03-07 21:08:20 -08005049 int32_t streamGroupId = outputStream->getHalStreamGroupId();
5050 if (streamGroupId != -1 && mGroupIdPhysicalCameraMap.count(streamGroupId) == 1) {
5051 requestedPhysicalCameras.insert(mGroupIdPhysicalCameraMap[streamGroupId]);
5052 } else if (!physicalCameraId.isEmpty()) {
5053 requestedPhysicalCameras.insert(std::set<String8>({physicalCameraId}));
Shuzhen Wang5c22c152017-12-31 17:12:25 -08005054 }
5055 halRequest->num_output_buffers++;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005056 }
5057 totalNumBuffers += halRequest->num_output_buffers;
5058
5059 // Log request in the in-flight queue
Shuzhen Wang4a472662017-02-26 23:29:04 -08005060 // If this request list is for constrained high speed recording (not
5061 // preview), and the current request is not the last one in the batch,
5062 // do not send callback to the app.
5063 bool hasCallback = true;
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07005064 if (batchedRequest && i != mNextRequests.size()-1) {
Shuzhen Wang4a472662017-02-26 23:29:04 -08005065 hasCallback = false;
5066 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01005067 bool isStillCapture = false;
Shuzhen Wang26abaf42018-08-28 15:41:20 -07005068 bool isZslCapture = false;
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08005069 const camera_metadata_t* settings = halRequest->settings;
5070 bool shouldUnlockSettings = false;
5071 if (settings == nullptr) {
5072 shouldUnlockSettings = true;
5073 settings = captureRequest->mSettingsList.begin()->metadata.getAndLock();
5074 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01005075 if (!mNextRequests[0].captureRequest->mSettingsList.begin()->metadata.isEmpty()) {
5076 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08005077 find_camera_metadata_ro_entry(settings, ANDROID_CONTROL_CAPTURE_INTENT, &e);
Emilian Peev9dd21f42018-08-03 13:39:29 +01005078 if ((e.count > 0) && (e.data.u8[0] == ANDROID_CONTROL_CAPTURE_INTENT_STILL_CAPTURE)) {
5079 isStillCapture = true;
5080 ATRACE_ASYNC_BEGIN("still capture", mNextRequests[i].halRequest.frame_number);
5081 }
Shuzhen Wang26abaf42018-08-28 15:41:20 -07005082
Emilian Peevaf8416e2021-02-04 17:52:43 -08005083 e = camera_metadata_ro_entry_t();
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08005084 find_camera_metadata_ro_entry(settings, ANDROID_CONTROL_ENABLE_ZSL, &e);
Shuzhen Wang26abaf42018-08-28 15:41:20 -07005085 if ((e.count > 0) && (e.data.u8[0] == ANDROID_CONTROL_ENABLE_ZSL_TRUE)) {
5086 isZslCapture = true;
5087 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01005088 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005089 res = parent->registerInFlight(halRequest->frame_number,
5090 totalNumBuffers, captureRequest->mResultExtras,
5091 /*hasInput*/halRequest->input_buffer != NULL,
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07005092 hasCallback,
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08005093 calculateMaxExpectedDuration(settings),
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005094 requestedPhysicalCameras, isStillCapture, isZslCapture,
5095 captureRequest->mRotateAndCropAuto, mPrevCameraIdsWithZoom,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005096 (mUseHalBufManager) ? uniqueSurfaceIdMap :
Shuzhen Wang316781a2020-08-18 18:11:01 -07005097 SurfaceMap{}, captureRequest->mRequestTimeNs);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005098 ALOGVV("%s: registered in flight requestId = %" PRId32 ", frameNumber = %" PRId64
5099 ", burstId = %" PRId32 ".",
5100 __FUNCTION__,
5101 captureRequest->mResultExtras.requestId, captureRequest->mResultExtras.frameNumber,
5102 captureRequest->mResultExtras.burstId);
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08005103
5104 if (shouldUnlockSettings) {
5105 captureRequest->mSettingsList.begin()->metadata.unlock(settings);
5106 }
5107
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005108 if (res != OK) {
5109 SET_ERR("RequestThread: Unable to register new in-flight request:"
5110 " %s (%d)", strerror(-res), res);
5111 return INVALID_OPERATION;
5112 }
5113 }
5114
5115 return OK;
5116}
5117
Igor Murashkin1e479c02013-09-06 16:55:14 -07005118CameraMetadata Camera3Device::RequestThread::getLatestRequest() const {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005119 ATRACE_CALL();
Igor Murashkin1e479c02013-09-06 16:55:14 -07005120 Mutex::Autolock al(mLatestRequestMutex);
5121
5122 ALOGV("RequestThread::%s", __FUNCTION__);
5123
5124 return mLatestRequest;
5125}
5126
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005127bool Camera3Device::RequestThread::isStreamPending(
5128 sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005129 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005130 Mutex::Autolock l(mRequestLock);
5131
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005132 for (const auto& nextRequest : mNextRequests) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005133 if (!nextRequest.submitted) {
5134 for (const auto& s : nextRequest.captureRequest->mOutputStreams) {
5135 if (stream == s) return true;
5136 }
5137 if (stream == nextRequest.captureRequest->mInputStream) return true;
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07005138 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07005139 }
5140
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005141 for (const auto& request : mRequestQueue) {
5142 for (const auto& s : request->mOutputStreams) {
5143 if (stream == s) return true;
5144 }
5145 if (stream == request->mInputStream) return true;
5146 }
5147
5148 for (const auto& request : mRepeatingRequests) {
5149 for (const auto& s : request->mOutputStreams) {
5150 if (stream == s) return true;
5151 }
5152 if (stream == request->mInputStream) return true;
5153 }
5154
5155 return false;
5156}
Jianing Weicb0652e2014-03-12 18:29:36 -07005157
Emilian Peev40ead602017-09-26 15:46:36 +01005158bool Camera3Device::RequestThread::isOutputSurfacePending(int streamId, size_t surfaceId) {
5159 ATRACE_CALL();
5160 Mutex::Autolock l(mRequestLock);
5161
5162 for (const auto& nextRequest : mNextRequests) {
5163 for (const auto& s : nextRequest.captureRequest->mOutputSurfaces) {
5164 if (s.first == streamId) {
5165 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
5166 if (it != s.second.end()) {
5167 return true;
5168 }
5169 }
5170 }
5171 }
5172
5173 for (const auto& request : mRequestQueue) {
5174 for (const auto& s : request->mOutputSurfaces) {
5175 if (s.first == streamId) {
5176 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
5177 if (it != s.second.end()) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005178 return true;
Emilian Peev40ead602017-09-26 15:46:36 +01005179 }
5180 }
5181 }
5182 }
5183
5184 for (const auto& request : mRepeatingRequests) {
5185 for (const auto& s : request->mOutputSurfaces) {
5186 if (s.first == streamId) {
5187 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
5188 if (it != s.second.end()) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005189 return true;
Emilian Peev40ead602017-09-26 15:46:36 +01005190 }
5191 }
5192 }
5193 }
5194
5195 return false;
5196}
5197
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07005198void Camera3Device::RequestThread::signalPipelineDrain(const std::vector<int>& streamIds) {
5199 if (!mUseHalBufManager) {
5200 ALOGE("%s called for camera device not supporting HAL buffer management", __FUNCTION__);
5201 return;
5202 }
5203
5204 Mutex::Autolock pl(mPauseLock);
5205 if (mPaused) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005206 mInterface->signalPipelineDrain(streamIds);
5207 return;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07005208 }
5209 // If request thread is still busy, wait until paused then notify HAL
5210 mNotifyPipelineDrain = true;
5211 mStreamIdsToBeDrained = streamIds;
5212}
5213
Yin-Chia Yehe52b8fa2020-07-28 00:17:58 -07005214void Camera3Device::RequestThread::resetPipelineDrain() {
5215 Mutex::Autolock pl(mPauseLock);
5216 mNotifyPipelineDrain = false;
5217 mStreamIdsToBeDrained.clear();
5218}
5219
Emilian Peevc0fe54c2020-03-11 14:05:07 -07005220void Camera3Device::RequestThread::clearPreviousRequest() {
5221 Mutex::Autolock l(mRequestLock);
5222 mPrevRequest.clear();
5223}
5224
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005225status_t Camera3Device::RequestThread::switchToOffline(
5226 const std::vector<int32_t>& streamsToKeep,
5227 /*out*/hardware::camera::device::V3_6::CameraOfflineSessionInfo* offlineSessionInfo,
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005228 /*out*/sp<hardware::camera::device::V3_6::ICameraOfflineSession>* offlineSession,
5229 /*out*/camera3::BufferRecords* bufferRecords) {
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005230 Mutex::Autolock l(mRequestLock);
5231 clearRepeatingRequestsLocked(/*lastFrameNumber*/nullptr);
5232
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005233 // Wait until request thread is fully stopped
5234 // TBD: check if request thread is being paused by other APIs (shouldn't be)
5235
5236 // We could also check for mRepeatingRequests.empty(), but the API interface
5237 // is serialized by Camera3Device::mInterfaceLock so no one should be able to submit any
5238 // new requests during the call; hence skip that check.
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005239 bool queueEmpty = mNextRequests.empty() && mRequestQueue.empty();
5240 while (!queueEmpty) {
5241 status_t res = mRequestSubmittedSignal.waitRelative(mRequestLock, kRequestSubmitTimeout);
5242 if (res == TIMED_OUT) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005243 ALOGE("%s: request thread failed to submit one request within timeout!", __FUNCTION__);
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005244 return res;
5245 } else if (res != OK) {
5246 ALOGE("%s: request thread failed to submit a request: %s (%d)!",
5247 __FUNCTION__, strerror(-res), res);
5248 return res;
5249 }
5250 queueEmpty = mNextRequests.empty() && mRequestQueue.empty();
5251 }
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005252
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005253 return mInterface->switchToOffline(
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005254 streamsToKeep, offlineSessionInfo, offlineSession, bufferRecords);
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005255}
5256
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005257status_t Camera3Device::RequestThread::setRotateAndCropAutoBehavior(
5258 camera_metadata_enum_android_scaler_rotate_and_crop_t rotateAndCropValue) {
5259 ATRACE_CALL();
5260 Mutex::Autolock l(mTriggerMutex);
5261 if (rotateAndCropValue == ANDROID_SCALER_ROTATE_AND_CROP_AUTO) {
5262 return BAD_VALUE;
5263 }
5264 mRotateAndCropOverride = rotateAndCropValue;
5265 return OK;
5266}
5267
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005268status_t Camera3Device::RequestThread::setCameraMute(bool enabled) {
5269 ATRACE_CALL();
5270 Mutex::Autolock l(mTriggerMutex);
5271 if (enabled != mCameraMute) {
5272 mCameraMute = enabled;
5273 mCameraMuteChanged = true;
5274 }
5275 return OK;
5276}
5277
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07005278nsecs_t Camera3Device::getExpectedInFlightDuration() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005279 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005280 std::lock_guard<std::mutex> l(mInFlightLock);
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07005281 return mExpectedInflightDuration > kMinInflightDuration ?
5282 mExpectedInflightDuration : kMinInflightDuration;
5283}
5284
Emilian Peevaebbe412018-01-15 13:53:24 +00005285void Camera3Device::RequestThread::cleanupPhysicalSettings(sp<CaptureRequest> request,
Emilian Peevf4816702020-04-03 15:44:51 -07005286 camera_capture_request_t *halRequest) {
Emilian Peevaebbe412018-01-15 13:53:24 +00005287 if ((request == nullptr) || (halRequest == nullptr)) {
5288 ALOGE("%s: Invalid request!", __FUNCTION__);
5289 return;
5290 }
5291
5292 if (halRequest->num_physcam_settings > 0) {
5293 if (halRequest->physcam_id != nullptr) {
5294 delete [] halRequest->physcam_id;
5295 halRequest->physcam_id = nullptr;
5296 }
5297 if (halRequest->physcam_settings != nullptr) {
5298 auto it = ++(request->mSettingsList.begin());
5299 size_t i = 0;
5300 for (; it != request->mSettingsList.end(); it++, i++) {
5301 it->metadata.unlock(halRequest->physcam_settings[i]);
5302 }
5303 delete [] halRequest->physcam_settings;
5304 halRequest->physcam_settings = nullptr;
5305 }
5306 }
5307}
5308
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005309void Camera3Device::RequestThread::cleanUpFailedRequests(bool sendRequestError) {
5310 if (mNextRequests.empty()) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005311 return;
5312 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005313
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005314 for (auto& nextRequest : mNextRequests) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005315 // Skip the ones that have been submitted successfully.
5316 if (nextRequest.submitted) {
5317 continue;
5318 }
5319
5320 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
Emilian Peevf4816702020-04-03 15:44:51 -07005321 camera_capture_request_t* halRequest = &nextRequest.halRequest;
5322 Vector<camera_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005323
5324 if (halRequest->settings != NULL) {
Emilian Peevaebbe412018-01-15 13:53:24 +00005325 captureRequest->mSettingsList.begin()->metadata.unlock(halRequest->settings);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005326 }
5327
Emilian Peevaebbe412018-01-15 13:53:24 +00005328 cleanupPhysicalSettings(captureRequest, halRequest);
5329
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005330 if (captureRequest->mInputStream != NULL) {
Emilian Peevf4816702020-04-03 15:44:51 -07005331 captureRequest->mInputBuffer.status = CAMERA_BUFFER_STATUS_ERROR;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005332 captureRequest->mInputStream->returnInputBuffer(captureRequest->mInputBuffer);
5333 }
5334
Yin-Chia Yeh21cb47b2019-01-18 15:08:17 -08005335 // No output buffer can be returned when using HAL buffer manager
5336 if (!mUseHalBufManager) {
5337 for (size_t i = 0; i < halRequest->num_output_buffers; i++) {
5338 //Buffers that failed processing could still have
5339 //valid acquire fence.
5340 int acquireFence = (*outputBuffers)[i].acquire_fence;
5341 if (0 <= acquireFence) {
5342 close(acquireFence);
5343 outputBuffers->editItemAt(i).acquire_fence = -1;
5344 }
Emilian Peevf4816702020-04-03 15:44:51 -07005345 outputBuffers->editItemAt(i).status = CAMERA_BUFFER_STATUS_ERROR;
Yin-Chia Yeh21cb47b2019-01-18 15:08:17 -08005346 captureRequest->mOutputStreams.editItemAt(i)->returnBuffer((*outputBuffers)[i], 0,
5347 /*timestampIncreasing*/true, std::vector<size_t> (),
5348 captureRequest->mResultExtras.frameNumber);
Emilian Peevc58cf4c2017-05-11 17:23:41 +01005349 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005350 }
5351
5352 if (sendRequestError) {
5353 Mutex::Autolock l(mRequestLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005354 sp<NotificationListener> listener = mListener.promote();
5355 if (listener != NULL) {
5356 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08005357 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005358 captureRequest->mResultExtras);
5359 }
5360 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07005361
5362 // Remove yet-to-be submitted inflight request from inflightMap
5363 {
5364 sp<Camera3Device> parent = mParent.promote();
5365 if (parent != NULL) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005366 std::lock_guard<std::mutex> l(parent->mInFlightLock);
Shuzhen Wangcadb3302016-11-04 14:17:56 -07005367 ssize_t idx = parent->mInFlightMap.indexOfKey(captureRequest->mResultExtras.frameNumber);
5368 if (idx >= 0) {
5369 ALOGV("%s: Remove inflight request from queue: frameNumber %" PRId64,
5370 __FUNCTION__, captureRequest->mResultExtras.frameNumber);
5371 parent->removeInFlightMapEntryLocked(idx);
5372 }
5373 }
5374 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005375 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07005376
5377 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005378 mNextRequests.clear();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005379}
5380
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005381void Camera3Device::RequestThread::waitForNextRequestBatch() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005382 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005383 // Optimized a bit for the simple steady-state case (single repeating
5384 // request), to avoid putting that request in the queue temporarily.
5385 Mutex::Autolock l(mRequestLock);
5386
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005387 assert(mNextRequests.empty());
5388
5389 NextRequest nextRequest;
5390 nextRequest.captureRequest = waitForNextRequestLocked();
5391 if (nextRequest.captureRequest == nullptr) {
5392 return;
5393 }
5394
Emilian Peevf4816702020-04-03 15:44:51 -07005395 nextRequest.halRequest = camera_capture_request_t();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005396 nextRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005397 mNextRequests.add(nextRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005398
5399 // Wait for additional requests
5400 const size_t batchSize = nextRequest.captureRequest->mBatchSize;
5401
5402 for (size_t i = 1; i < batchSize; i++) {
5403 NextRequest additionalRequest;
5404 additionalRequest.captureRequest = waitForNextRequestLocked();
5405 if (additionalRequest.captureRequest == nullptr) {
5406 break;
5407 }
5408
Emilian Peevf4816702020-04-03 15:44:51 -07005409 additionalRequest.halRequest = camera_capture_request_t();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005410 additionalRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005411 mNextRequests.add(additionalRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005412 }
5413
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005414 if (mNextRequests.size() < batchSize) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08005415 ALOGE("RequestThread: only get %zu out of %zu requests. Skipping requests.",
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005416 mNextRequests.size(), batchSize);
5417 cleanUpFailedRequests(/*sendRequestError*/true);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005418 }
5419
5420 return;
5421}
5422
5423sp<Camera3Device::CaptureRequest>
5424 Camera3Device::RequestThread::waitForNextRequestLocked() {
5425 status_t res;
5426 sp<CaptureRequest> nextRequest;
5427
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005428 while (mRequestQueue.empty()) {
5429 if (!mRepeatingRequests.empty()) {
5430 // Always atomically enqueue all requests in a repeating request
5431 // list. Guarantees a complete in-sequence set of captures to
5432 // application.
5433 const RequestList &requests = mRepeatingRequests;
Shuzhen Wang316781a2020-08-18 18:11:01 -07005434 if (mFirstRepeating) {
5435 mFirstRepeating = false;
5436 } else {
5437 for (auto& request : requests) {
5438 // For repeating requests, override timestamp request using
5439 // the time a request is inserted into the request queue,
5440 // because the original repeating request will have an old
5441 // fixed timestamp.
5442 request->mRequestTimeNs = systemTime();
5443 }
5444 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005445 RequestList::const_iterator firstRequest =
5446 requests.begin();
5447 nextRequest = *firstRequest;
5448 mRequestQueue.insert(mRequestQueue.end(),
5449 ++firstRequest,
5450 requests.end());
5451 // No need to wait any longer
Jianing Weicb0652e2014-03-12 18:29:36 -07005452
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005453 mRepeatingLastFrameNumber = mFrameNumber + requests.size() - 1;
Jianing Weicb0652e2014-03-12 18:29:36 -07005454
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005455 break;
5456 }
5457
5458 res = mRequestSignal.waitRelative(mRequestLock, kRequestTimeout);
5459
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005460 if ((mRequestQueue.empty() && mRepeatingRequests.empty()) ||
5461 exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005462 Mutex::Autolock pl(mPauseLock);
5463 if (mPaused == false) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005464 ALOGV("%s: RequestThread: Going idle", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005465 mPaused = true;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07005466 if (mNotifyPipelineDrain) {
5467 mInterface->signalPipelineDrain(mStreamIdsToBeDrained);
5468 mNotifyPipelineDrain = false;
5469 mStreamIdsToBeDrained.clear();
5470 }
Yin-Chia Yehc300a072019-02-13 14:56:57 -08005471 // Let the tracker know
5472 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5473 if (statusTracker != 0) {
5474 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
5475 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005476 sp<Camera3Device> parent = mParent.promote();
5477 if (parent != nullptr) {
5478 parent->mRequestBufferSM.onRequestThreadPaused();
5479 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005480 }
5481 // Stop waiting for now and let thread management happen
5482 return NULL;
5483 }
5484 }
5485
5486 if (nextRequest == NULL) {
5487 // Don't have a repeating request already in hand, so queue
5488 // must have an entry now.
5489 RequestList::iterator firstRequest =
5490 mRequestQueue.begin();
5491 nextRequest = *firstRequest;
5492 mRequestQueue.erase(firstRequest);
Shuzhen Wang9d066012016-09-30 11:30:20 -07005493 if (mRequestQueue.empty() && !nextRequest->mRepeating) {
5494 sp<NotificationListener> listener = mListener.promote();
5495 if (listener != NULL) {
5496 listener->notifyRequestQueueEmpty();
5497 }
5498 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005499 }
5500
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005501 // In case we've been unpaused by setPaused clearing mDoPause, need to
5502 // update internal pause state (capture/setRepeatingRequest unpause
5503 // directly).
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005504 Mutex::Autolock pl(mPauseLock);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005505 if (mPaused) {
5506 ALOGV("%s: RequestThread: Unpaused", __FUNCTION__);
5507 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5508 if (statusTracker != 0) {
5509 statusTracker->markComponentActive(mStatusId);
5510 }
5511 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005512 mPaused = false;
5513
5514 // Check if we've reconfigured since last time, and reset the preview
5515 // request if so. Can't use 'NULL request == repeat' across configure calls.
5516 if (mReconfigured) {
5517 mPrevRequest.clear();
5518 mReconfigured = false;
5519 }
5520
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005521 if (nextRequest != NULL) {
5522 nextRequest->mResultExtras.frameNumber = mFrameNumber++;
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07005523 nextRequest->mResultExtras.afTriggerId = mCurrentAfTriggerId;
5524 nextRequest->mResultExtras.precaptureTriggerId = mCurrentPreCaptureTriggerId;
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07005525
5526 // Since RequestThread::clear() removes buffers from the input stream,
5527 // get the right buffer here before unlocking mRequestLock
5528 if (nextRequest->mInputStream != NULL) {
Shuzhen Wang83bff122020-11-20 15:51:39 -08005529 res = nextRequest->mInputStream->getInputBuffer(&nextRequest->mInputBuffer,
5530 &nextRequest->mInputBufferSize);
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07005531 if (res != OK) {
5532 // Can't get input buffer from gralloc queue - this could be due to
5533 // disconnected queue or other producer misbehavior, so not a fatal
5534 // error
5535 ALOGE("%s: Can't get input buffer, skipping request:"
5536 " %s (%d)", __FUNCTION__, strerror(-res), res);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005537
5538 sp<NotificationListener> listener = mListener.promote();
5539 if (listener != NULL) {
5540 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08005541 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07005542 nextRequest->mResultExtras);
5543 }
5544 return NULL;
5545 }
5546 }
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005547 }
Chien-Yu Chend196d612015-06-22 19:49:01 -07005548
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005549 return nextRequest;
5550}
5551
5552bool Camera3Device::RequestThread::waitIfPaused() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005553 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005554 status_t res;
5555 Mutex::Autolock l(mPauseLock);
5556 while (mDoPause) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005557 if (mPaused == false) {
5558 mPaused = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005559 ALOGV("%s: RequestThread: Paused", __FUNCTION__);
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07005560 if (mNotifyPipelineDrain) {
5561 mInterface->signalPipelineDrain(mStreamIdsToBeDrained);
5562 mNotifyPipelineDrain = false;
5563 mStreamIdsToBeDrained.clear();
5564 }
Yin-Chia Yehc300a072019-02-13 14:56:57 -08005565 // Let the tracker know
5566 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5567 if (statusTracker != 0) {
5568 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
5569 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005570 sp<Camera3Device> parent = mParent.promote();
5571 if (parent != nullptr) {
5572 parent->mRequestBufferSM.onRequestThreadPaused();
5573 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005574 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005575
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005576 res = mDoPauseSignal.waitRelative(mPauseLock, kRequestTimeout);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005577 if (res == TIMED_OUT || exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005578 return true;
5579 }
5580 }
5581 // We don't set mPaused to false here, because waitForNextRequest needs
5582 // to further manage the paused state in case of starvation.
5583 return false;
5584}
5585
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005586void Camera3Device::RequestThread::unpauseForNewRequests() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005587 ATRACE_CALL();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005588 // With work to do, mark thread as unpaused.
5589 // If paused by request (setPaused), don't resume, to avoid
5590 // extra signaling/waiting overhead to waitUntilPaused
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005591 mRequestSignal.signal();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005592 Mutex::Autolock p(mPauseLock);
5593 if (!mDoPause) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005594 ALOGV("%s: RequestThread: Going active", __FUNCTION__);
5595 if (mPaused) {
5596 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5597 if (statusTracker != 0) {
5598 statusTracker->markComponentActive(mStatusId);
5599 }
5600 }
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005601 mPaused = false;
5602 }
5603}
5604
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07005605void Camera3Device::RequestThread::setErrorState(const char *fmt, ...) {
5606 sp<Camera3Device> parent = mParent.promote();
5607 if (parent != NULL) {
5608 va_list args;
5609 va_start(args, fmt);
5610
5611 parent->setErrorStateV(fmt, args);
5612
5613 va_end(args);
5614 }
5615}
5616
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005617status_t Camera3Device::RequestThread::insertTriggers(
5618 const sp<CaptureRequest> &request) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005619 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005620 Mutex::Autolock al(mTriggerMutex);
5621
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07005622 sp<Camera3Device> parent = mParent.promote();
5623 if (parent == NULL) {
5624 CLOGE("RequestThread: Parent is gone");
5625 return DEAD_OBJECT;
5626 }
5627
Emilian Peevaebbe412018-01-15 13:53:24 +00005628 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005629 size_t count = mTriggerMap.size();
5630
5631 for (size_t i = 0; i < count; ++i) {
5632 RequestTrigger trigger = mTriggerMap.valueAt(i);
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005633 uint32_t tag = trigger.metadataTag;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07005634
5635 if (tag == ANDROID_CONTROL_AF_TRIGGER_ID || tag == ANDROID_CONTROL_AE_PRECAPTURE_ID) {
5636 bool isAeTrigger = (trigger.metadataTag == ANDROID_CONTROL_AE_PRECAPTURE_ID);
5637 uint32_t triggerId = static_cast<uint32_t>(trigger.entryValue);
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07005638 if (isAeTrigger) {
5639 request->mResultExtras.precaptureTriggerId = triggerId;
5640 mCurrentPreCaptureTriggerId = triggerId;
5641 } else {
5642 request->mResultExtras.afTriggerId = triggerId;
5643 mCurrentAfTriggerId = triggerId;
5644 }
Emilian Peev7e25e5e2017-04-07 15:48:49 +01005645 continue;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07005646 }
5647
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005648 camera_metadata_entry entry = metadata.find(tag);
5649
5650 if (entry.count > 0) {
5651 /**
5652 * Already has an entry for this trigger in the request.
5653 * Rewrite it with our requested trigger value.
5654 */
5655 RequestTrigger oldTrigger = trigger;
5656
5657 oldTrigger.entryValue = entry.data.u8[0];
5658
5659 mTriggerReplacedMap.add(tag, oldTrigger);
5660 } else {
5661 /**
5662 * More typical, no trigger entry, so we just add it
5663 */
5664 mTriggerRemovedMap.add(tag, trigger);
5665 }
5666
5667 status_t res;
5668
5669 switch (trigger.getTagType()) {
5670 case TYPE_BYTE: {
5671 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
5672 res = metadata.update(tag,
5673 &entryValue,
5674 /*count*/1);
5675 break;
5676 }
5677 case TYPE_INT32:
5678 res = metadata.update(tag,
5679 &trigger.entryValue,
5680 /*count*/1);
5681 break;
5682 default:
5683 ALOGE("%s: Type not supported: 0x%x",
5684 __FUNCTION__,
5685 trigger.getTagType());
5686 return INVALID_OPERATION;
5687 }
5688
5689 if (res != OK) {
5690 ALOGE("%s: Failed to update request metadata with trigger tag %s"
5691 ", value %d", __FUNCTION__, trigger.getTagName(),
5692 trigger.entryValue);
5693 return res;
5694 }
5695
5696 ALOGV("%s: Mixed in trigger %s, value %d", __FUNCTION__,
5697 trigger.getTagName(),
5698 trigger.entryValue);
5699 }
5700
5701 mTriggerMap.clear();
5702
5703 return count;
5704}
5705
5706status_t Camera3Device::RequestThread::removeTriggers(
5707 const sp<CaptureRequest> &request) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005708 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005709 Mutex::Autolock al(mTriggerMutex);
5710
Emilian Peevaebbe412018-01-15 13:53:24 +00005711 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005712
5713 /**
5714 * Replace all old entries with their old values.
5715 */
5716 for (size_t i = 0; i < mTriggerReplacedMap.size(); ++i) {
5717 RequestTrigger trigger = mTriggerReplacedMap.valueAt(i);
5718
5719 status_t res;
5720
5721 uint32_t tag = trigger.metadataTag;
5722 switch (trigger.getTagType()) {
5723 case TYPE_BYTE: {
5724 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
5725 res = metadata.update(tag,
5726 &entryValue,
5727 /*count*/1);
5728 break;
5729 }
5730 case TYPE_INT32:
5731 res = metadata.update(tag,
5732 &trigger.entryValue,
5733 /*count*/1);
5734 break;
5735 default:
5736 ALOGE("%s: Type not supported: 0x%x",
5737 __FUNCTION__,
5738 trigger.getTagType());
5739 return INVALID_OPERATION;
5740 }
5741
5742 if (res != OK) {
5743 ALOGE("%s: Failed to restore request metadata with trigger tag %s"
5744 ", trigger value %d", __FUNCTION__,
5745 trigger.getTagName(), trigger.entryValue);
5746 return res;
5747 }
5748 }
5749 mTriggerReplacedMap.clear();
5750
5751 /**
5752 * Remove all new entries.
5753 */
5754 for (size_t i = 0; i < mTriggerRemovedMap.size(); ++i) {
5755 RequestTrigger trigger = mTriggerRemovedMap.valueAt(i);
5756 status_t res = metadata.erase(trigger.metadataTag);
5757
5758 if (res != OK) {
5759 ALOGE("%s: Failed to erase metadata with trigger tag %s"
5760 ", trigger value %d", __FUNCTION__,
5761 trigger.getTagName(), trigger.entryValue);
5762 return res;
5763 }
5764 }
5765 mTriggerRemovedMap.clear();
5766
5767 return OK;
5768}
5769
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04005770status_t Camera3Device::RequestThread::addFakeTriggerIds(
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005771 const sp<CaptureRequest> &request) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08005772 // Trigger ID 0 had special meaning in the HAL2 spec, so avoid it here
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04005773 static const int32_t fakeTriggerId = 1;
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005774 status_t res;
5775
Emilian Peevaebbe412018-01-15 13:53:24 +00005776 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005777
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04005778 // If AF trigger is active, insert a fake AF trigger ID if none already
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005779 // exists
5780 camera_metadata_entry afTrigger = metadata.find(ANDROID_CONTROL_AF_TRIGGER);
5781 camera_metadata_entry afId = metadata.find(ANDROID_CONTROL_AF_TRIGGER_ID);
5782 if (afTrigger.count > 0 &&
5783 afTrigger.data.u8[0] != ANDROID_CONTROL_AF_TRIGGER_IDLE &&
5784 afId.count == 0) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04005785 res = metadata.update(ANDROID_CONTROL_AF_TRIGGER_ID, &fakeTriggerId, 1);
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005786 if (res != OK) return res;
5787 }
5788
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04005789 // If AE precapture trigger is active, insert a fake precapture trigger ID
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005790 // if none already exists
5791 camera_metadata_entry pcTrigger =
5792 metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER);
5793 camera_metadata_entry pcId = metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_ID);
5794 if (pcTrigger.count > 0 &&
5795 pcTrigger.data.u8[0] != ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_IDLE &&
5796 pcId.count == 0) {
5797 res = metadata.update(ANDROID_CONTROL_AE_PRECAPTURE_ID,
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04005798 &fakeTriggerId, 1);
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005799 if (res != OK) return res;
5800 }
5801
5802 return OK;
5803}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005804
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005805bool Camera3Device::RequestThread::overrideAutoRotateAndCrop(
5806 const sp<CaptureRequest> &request) {
5807 ATRACE_CALL();
5808
5809 if (request->mRotateAndCropAuto) {
5810 Mutex::Autolock l(mTriggerMutex);
5811 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
5812
5813 auto rotateAndCropEntry = metadata.find(ANDROID_SCALER_ROTATE_AND_CROP);
5814 if (rotateAndCropEntry.count > 0) {
5815 if (rotateAndCropEntry.data.u8[0] == mRotateAndCropOverride) {
5816 return false;
5817 } else {
5818 rotateAndCropEntry.data.u8[0] = mRotateAndCropOverride;
5819 return true;
5820 }
5821 } else {
5822 uint8_t rotateAndCrop_u8 = mRotateAndCropOverride;
5823 metadata.update(ANDROID_SCALER_ROTATE_AND_CROP,
5824 &rotateAndCrop_u8, 1);
5825 return true;
5826 }
5827 }
5828 return false;
5829}
5830
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005831bool Camera3Device::RequestThread::overrideTestPattern(
5832 const sp<CaptureRequest> &request) {
5833 ATRACE_CALL();
5834
5835 Mutex::Autolock l(mTriggerMutex);
5836
5837 bool changed = false;
5838
5839 int32_t testPatternMode = request->mOriginalTestPatternMode;
5840 int32_t testPatternData[4] = {
5841 request->mOriginalTestPatternData[0],
5842 request->mOriginalTestPatternData[1],
5843 request->mOriginalTestPatternData[2],
5844 request->mOriginalTestPatternData[3]
5845 };
5846
5847 if (mCameraMute) {
5848 testPatternMode = ANDROID_SENSOR_TEST_PATTERN_MODE_SOLID_COLOR;
5849 testPatternData[0] = 0;
5850 testPatternData[1] = 0;
5851 testPatternData[2] = 0;
5852 testPatternData[3] = 0;
5853 }
5854
5855 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
5856
5857 auto testPatternEntry = metadata.find(ANDROID_SENSOR_TEST_PATTERN_MODE);
5858 if (testPatternEntry.count > 0) {
5859 if (testPatternEntry.data.i32[0] != testPatternMode) {
5860 testPatternEntry.data.i32[0] = testPatternMode;
5861 changed = true;
5862 }
5863 } else {
5864 metadata.update(ANDROID_SENSOR_TEST_PATTERN_MODE,
5865 &testPatternMode, 1);
5866 changed = true;
5867 }
5868
5869 auto testPatternColor = metadata.find(ANDROID_SENSOR_TEST_PATTERN_DATA);
5870 if (testPatternColor.count > 0) {
5871 for (size_t i = 0; i < 4; i++) {
5872 if (testPatternColor.data.i32[i] != (int32_t)testPatternData[i]) {
5873 testPatternColor.data.i32[i] = testPatternData[i];
5874 changed = true;
5875 }
5876 }
5877 } else {
5878 metadata.update(ANDROID_SENSOR_TEST_PATTERN_DATA,
5879 (int32_t*)testPatternData, 4);
5880 changed = true;
5881 }
5882
5883 return changed;
5884}
5885
Cliff Wuc2ad9c82021-04-21 00:58:58 +08005886status_t Camera3Device::RequestThread::setHalInterface(
5887 sp<HalInterface> newHalInterface) {
5888 if (newHalInterface.get() == nullptr) {
5889 ALOGE("%s: The newHalInterface does not exist!", __FUNCTION__);
5890 return DEAD_OBJECT;
5891 }
5892
5893 mInterface = newHalInterface;
5894
5895 return OK;
5896}
5897
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005898/**
5899 * PreparerThread inner class methods
5900 */
5901
5902Camera3Device::PreparerThread::PreparerThread() :
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07005903 Thread(/*canCallJava*/false), mListener(nullptr),
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005904 mActive(false), mCancelNow(false), mCurrentMaxCount(0), mCurrentPrepareComplete(false) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005905}
5906
5907Camera3Device::PreparerThread::~PreparerThread() {
5908 Thread::requestExitAndWait();
5909 if (mCurrentStream != nullptr) {
5910 mCurrentStream->cancelPrepare();
5911 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
5912 mCurrentStream.clear();
5913 }
5914 clear();
5915}
5916
Ruben Brunkc78ac262015-08-13 17:58:46 -07005917status_t Camera3Device::PreparerThread::prepare(int maxCount, sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005918 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005919 status_t res;
5920
5921 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005922 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005923
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07005924 res = stream->startPrepare(maxCount, true /*blockRequest*/);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005925 if (res == OK) {
5926 // No preparation needed, fire listener right off
5927 ALOGV("%s: Stream %d already prepared", __FUNCTION__, stream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005928 if (listener != NULL) {
5929 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005930 }
5931 return OK;
5932 } else if (res != NOT_ENOUGH_DATA) {
5933 return res;
5934 }
5935
5936 // Need to prepare, start up thread if necessary
5937 if (!mActive) {
5938 // mRunning will change to false before the thread fully shuts down, so wait to be sure it
5939 // isn't running
5940 Thread::requestExitAndWait();
5941 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
5942 if (res != OK) {
5943 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__, res, strerror(-res));
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005944 if (listener != NULL) {
5945 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005946 }
5947 return res;
5948 }
5949 mCancelNow = false;
5950 mActive = true;
5951 ALOGV("%s: Preparer stream started", __FUNCTION__);
5952 }
5953
5954 // queue up the work
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005955 mPendingStreams.emplace(maxCount, stream);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005956 ALOGV("%s: Stream %d queued for preparing", __FUNCTION__, stream->getId());
5957
5958 return OK;
5959}
5960
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005961void Camera3Device::PreparerThread::pause() {
5962 ATRACE_CALL();
5963
5964 Mutex::Autolock l(mLock);
5965
5966 std::unordered_map<int, sp<camera3::Camera3StreamInterface> > pendingStreams;
5967 pendingStreams.insert(mPendingStreams.begin(), mPendingStreams.end());
5968 sp<camera3::Camera3StreamInterface> currentStream = mCurrentStream;
5969 int currentMaxCount = mCurrentMaxCount;
5970 mPendingStreams.clear();
5971 mCancelNow = true;
5972 while (mActive) {
5973 auto res = mThreadActiveSignal.waitRelative(mLock, kActiveTimeout);
5974 if (res == TIMED_OUT) {
5975 ALOGE("%s: Timed out waiting on prepare thread!", __FUNCTION__);
5976 return;
5977 } else if (res != OK) {
5978 ALOGE("%s: Encountered an error: %d waiting on prepare thread!", __FUNCTION__, res);
5979 return;
5980 }
5981 }
5982
5983 //Check whether the prepare thread was able to complete the current
5984 //stream. In case work is still pending emplace it along with the rest
5985 //of the streams in the pending list.
5986 if (currentStream != nullptr) {
5987 if (!mCurrentPrepareComplete) {
5988 pendingStreams.emplace(currentMaxCount, currentStream);
5989 }
5990 }
5991
5992 mPendingStreams.insert(pendingStreams.begin(), pendingStreams.end());
5993 for (const auto& it : mPendingStreams) {
5994 it.second->cancelPrepare();
5995 }
5996}
5997
5998status_t Camera3Device::PreparerThread::resume() {
5999 ATRACE_CALL();
6000 status_t res;
6001
6002 Mutex::Autolock l(mLock);
6003 sp<NotificationListener> listener = mListener.promote();
6004
6005 if (mActive) {
6006 ALOGE("%s: Trying to resume an already active prepare thread!", __FUNCTION__);
6007 return NO_INIT;
6008 }
6009
6010 auto it = mPendingStreams.begin();
6011 for (; it != mPendingStreams.end();) {
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07006012 res = it->second->startPrepare(it->first, true /*blockRequest*/);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006013 if (res == OK) {
6014 if (listener != NULL) {
6015 listener->notifyPrepared(it->second->getId());
6016 }
6017 it = mPendingStreams.erase(it);
6018 } else if (res != NOT_ENOUGH_DATA) {
6019 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__,
6020 res, strerror(-res));
6021 it = mPendingStreams.erase(it);
6022 } else {
6023 it++;
6024 }
6025 }
6026
6027 if (mPendingStreams.empty()) {
6028 return OK;
6029 }
6030
6031 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
6032 if (res != OK) {
6033 ALOGE("%s: Unable to start preparer stream: %d (%s)",
6034 __FUNCTION__, res, strerror(-res));
6035 return res;
6036 }
6037 mCancelNow = false;
6038 mActive = true;
6039 ALOGV("%s: Preparer stream started", __FUNCTION__);
6040
6041 return OK;
6042}
6043
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006044status_t Camera3Device::PreparerThread::clear() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07006045 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006046 Mutex::Autolock l(mLock);
6047
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006048 for (const auto& it : mPendingStreams) {
6049 it.second->cancelPrepare();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006050 }
6051 mPendingStreams.clear();
6052 mCancelNow = true;
6053
6054 return OK;
6055}
6056
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006057void Camera3Device::PreparerThread::setNotificationListener(wp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07006058 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006059 Mutex::Autolock l(mLock);
6060 mListener = listener;
6061}
6062
6063bool Camera3Device::PreparerThread::threadLoop() {
6064 status_t res;
6065 {
6066 Mutex::Autolock l(mLock);
6067 if (mCurrentStream == nullptr) {
6068 // End thread if done with work
6069 if (mPendingStreams.empty()) {
6070 ALOGV("%s: Preparer stream out of work", __FUNCTION__);
6071 // threadLoop _must not_ re-acquire mLock after it sets mActive to false; would
6072 // cause deadlock with prepare()'s requestExitAndWait triggered by !mActive.
6073 mActive = false;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006074 mThreadActiveSignal.signal();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006075 return false;
6076 }
6077
6078 // Get next stream to prepare
6079 auto it = mPendingStreams.begin();
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006080 mCurrentStream = it->second;
6081 mCurrentMaxCount = it->first;
6082 mCurrentPrepareComplete = false;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006083 mPendingStreams.erase(it);
6084 ATRACE_ASYNC_BEGIN("stream prepare", mCurrentStream->getId());
6085 ALOGV("%s: Preparing stream %d", __FUNCTION__, mCurrentStream->getId());
6086 } else if (mCancelNow) {
6087 mCurrentStream->cancelPrepare();
6088 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
6089 ALOGV("%s: Cancelling stream %d prepare", __FUNCTION__, mCurrentStream->getId());
6090 mCurrentStream.clear();
6091 mCancelNow = false;
6092 return true;
6093 }
6094 }
6095
6096 res = mCurrentStream->prepareNextBuffer();
6097 if (res == NOT_ENOUGH_DATA) return true;
6098 if (res != OK) {
6099 // Something bad happened; try to recover by cancelling prepare and
6100 // signalling listener anyway
6101 ALOGE("%s: Stream %d returned error %d (%s) during prepare", __FUNCTION__,
6102 mCurrentStream->getId(), res, strerror(-res));
6103 mCurrentStream->cancelPrepare();
6104 }
6105
6106 // This stream has finished, notify listener
6107 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006108 sp<NotificationListener> listener = mListener.promote();
6109 if (listener != NULL) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006110 ALOGV("%s: Stream %d prepare done, signaling listener", __FUNCTION__,
6111 mCurrentStream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006112 listener->notifyPrepared(mCurrentStream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006113 }
6114
6115 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
6116 mCurrentStream.clear();
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006117 mCurrentPrepareComplete = true;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006118
6119 return true;
6120}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07006121
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006122status_t Camera3Device::RequestBufferStateMachine::initialize(
6123 sp<camera3::StatusTracker> statusTracker) {
6124 if (statusTracker == nullptr) {
6125 ALOGE("%s: statusTracker is null", __FUNCTION__);
6126 return BAD_VALUE;
6127 }
6128
6129 std::lock_guard<std::mutex> lock(mLock);
6130 mStatusTracker = statusTracker;
Yin-Chia Yeh87b3ec02019-06-03 10:44:39 -07006131 mRequestBufferStatusId = statusTracker->addComponent("BufferRequestSM");
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006132 return OK;
6133}
6134
6135bool Camera3Device::RequestBufferStateMachine::startRequestBuffer() {
6136 std::lock_guard<std::mutex> lock(mLock);
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08006137 if (mStatus == RB_STATUS_READY || mStatus == RB_STATUS_PENDING_STOP) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006138 mRequestBufferOngoing = true;
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08006139 notifyTrackerLocked(/*active*/true);
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006140 return true;
6141 }
6142 return false;
6143}
6144
6145void Camera3Device::RequestBufferStateMachine::endRequestBuffer() {
6146 std::lock_guard<std::mutex> lock(mLock);
6147 if (!mRequestBufferOngoing) {
6148 ALOGE("%s called without a successful startRequestBuffer call first!", __FUNCTION__);
6149 return;
6150 }
6151 mRequestBufferOngoing = false;
6152 if (mStatus == RB_STATUS_PENDING_STOP) {
6153 checkSwitchToStopLocked();
6154 }
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08006155 notifyTrackerLocked(/*active*/false);
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006156}
6157
6158void Camera3Device::RequestBufferStateMachine::onStreamsConfigured() {
6159 std::lock_guard<std::mutex> lock(mLock);
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006160 mSwitchedToOffline = false;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006161 mStatus = RB_STATUS_READY;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006162 return;
6163}
6164
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08006165void Camera3Device::RequestBufferStateMachine::onSubmittingRequest() {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006166 std::lock_guard<std::mutex> lock(mLock);
6167 mRequestThreadPaused = false;
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08006168 // inflight map register actually happens in prepareHalRequest now, but it is close enough
6169 // approximation.
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006170 mInflightMapEmpty = false;
6171 if (mStatus == RB_STATUS_STOPPED) {
6172 mStatus = RB_STATUS_READY;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006173 }
6174 return;
6175}
6176
6177void Camera3Device::RequestBufferStateMachine::onRequestThreadPaused() {
6178 std::lock_guard<std::mutex> lock(mLock);
6179 mRequestThreadPaused = true;
6180 if (mStatus == RB_STATUS_PENDING_STOP) {
6181 checkSwitchToStopLocked();
6182 }
6183 return;
6184}
6185
6186void Camera3Device::RequestBufferStateMachine::onInflightMapEmpty() {
6187 std::lock_guard<std::mutex> lock(mLock);
6188 mInflightMapEmpty = true;
6189 if (mStatus == RB_STATUS_PENDING_STOP) {
6190 checkSwitchToStopLocked();
6191 }
6192 return;
6193}
6194
6195void Camera3Device::RequestBufferStateMachine::onWaitUntilIdle() {
6196 std::lock_guard<std::mutex> lock(mLock);
6197 if (!checkSwitchToStopLocked()) {
6198 mStatus = RB_STATUS_PENDING_STOP;
6199 }
6200 return;
6201}
6202
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006203bool Camera3Device::RequestBufferStateMachine::onSwitchToOfflineSuccess() {
6204 std::lock_guard<std::mutex> lock(mLock);
6205 if (mRequestBufferOngoing) {
6206 ALOGE("%s: HAL must not be requesting buffer after HAL returns switchToOffline!",
6207 __FUNCTION__);
6208 return false;
6209 }
6210 mSwitchedToOffline = true;
6211 mInflightMapEmpty = true;
6212 mRequestThreadPaused = true;
6213 mStatus = RB_STATUS_STOPPED;
6214 return true;
6215}
6216
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006217void Camera3Device::RequestBufferStateMachine::notifyTrackerLocked(bool active) {
6218 sp<StatusTracker> statusTracker = mStatusTracker.promote();
6219 if (statusTracker != nullptr) {
6220 if (active) {
6221 statusTracker->markComponentActive(mRequestBufferStatusId);
6222 } else {
6223 statusTracker->markComponentIdle(mRequestBufferStatusId, Fence::NO_FENCE);
6224 }
6225 }
6226}
6227
6228bool Camera3Device::RequestBufferStateMachine::checkSwitchToStopLocked() {
6229 if (mInflightMapEmpty && mRequestThreadPaused && !mRequestBufferOngoing) {
6230 mStatus = RB_STATUS_STOPPED;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006231 return true;
6232 }
6233 return false;
6234}
6235
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006236bool Camera3Device::startRequestBuffer() {
6237 return mRequestBufferSM.startRequestBuffer();
6238}
Shuzhen Wang268a1362018-10-16 16:32:59 -07006239
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006240void Camera3Device::endRequestBuffer() {
6241 mRequestBufferSM.endRequestBuffer();
6242}
Shuzhen Wang268a1362018-10-16 16:32:59 -07006243
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006244nsecs_t Camera3Device::getWaitDuration() {
6245 return kBaseGetBufferWait + getExpectedInFlightDuration();
6246}
Shuzhen Wang268a1362018-10-16 16:32:59 -07006247
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006248void Camera3Device::getInflightBufferKeys(std::vector<std::pair<int32_t, int32_t>>* out) {
6249 mInterface->getInflightBufferKeys(out);
6250}
Shuzhen Wang268a1362018-10-16 16:32:59 -07006251
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006252void Camera3Device::getInflightRequestBufferKeys(std::vector<uint64_t>* out) {
6253 mInterface->getInflightRequestBufferKeys(out);
6254}
Shuzhen Wang268a1362018-10-16 16:32:59 -07006255
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006256std::vector<sp<Camera3StreamInterface>> Camera3Device::getAllStreams() {
6257 std::vector<sp<Camera3StreamInterface>> ret;
6258 bool hasInputStream = mInputStream != nullptr;
6259 ret.reserve(mOutputStreams.size() + mDeletedStreams.size() + ((hasInputStream) ? 1 : 0));
6260 if (hasInputStream) {
6261 ret.push_back(mInputStream);
Shuzhen Wang268a1362018-10-16 16:32:59 -07006262 }
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006263 for (size_t i = 0; i < mOutputStreams.size(); i++) {
6264 ret.push_back(mOutputStreams[i]);
6265 }
6266 for (size_t i = 0; i < mDeletedStreams.size(); i++) {
6267 ret.push_back(mDeletedStreams[i]);
6268 }
6269 return ret;
Shuzhen Wang268a1362018-10-16 16:32:59 -07006270}
6271
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006272status_t Camera3Device::switchToOffline(
6273 const std::vector<int32_t>& streamsToKeep,
6274 /*out*/ sp<CameraOfflineSessionBase>* session) {
6275 ATRACE_CALL();
6276 if (session == nullptr) {
6277 ALOGE("%s: session must not be null", __FUNCTION__);
6278 return BAD_VALUE;
6279 }
6280
6281 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006282
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006283 bool hasInputStream = mInputStream != nullptr;
6284 int32_t inputStreamId = hasInputStream ? mInputStream->getId() : -1;
6285 bool inputStreamSupportsOffline = hasInputStream ?
6286 mInputStream->getOfflineProcessingSupport() : false;
6287 auto outputStreamIds = mOutputStreams.getStreamIds();
6288 auto streamIds = outputStreamIds;
6289 if (hasInputStream) {
6290 streamIds.push_back(mInputStream->getId());
6291 }
6292
6293 // Check all streams in streamsToKeep supports offline mode
6294 for (auto id : streamsToKeep) {
6295 if (std::find(streamIds.begin(), streamIds.end(), id) == streamIds.end()) {
6296 ALOGE("%s: Unknown stream ID %d", __FUNCTION__, id);
6297 return BAD_VALUE;
6298 } else if (id == inputStreamId) {
6299 if (!inputStreamSupportsOffline) {
6300 ALOGE("%s: input stream %d cannot be switched to offline",
6301 __FUNCTION__, id);
6302 return BAD_VALUE;
6303 }
6304 } else {
6305 sp<camera3::Camera3OutputStreamInterface> stream = mOutputStreams.get(id);
6306 if (!stream->getOfflineProcessingSupport()) {
6307 ALOGE("%s: output stream %d cannot be switched to offline",
6308 __FUNCTION__, id);
6309 return BAD_VALUE;
6310 }
6311 }
6312 }
6313
6314 // TODO: block surface sharing and surface group streams until we can support them
6315
6316 // Stop repeating request, wait until all remaining requests are submitted, then call into
6317 // HAL switchToOffline
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006318 hardware::camera::device::V3_6::CameraOfflineSessionInfo offlineSessionInfo;
6319 sp<hardware::camera::device::V3_6::ICameraOfflineSession> offlineSession;
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006320 camera3::BufferRecords bufferRecords;
6321 status_t ret = mRequestThread->switchToOffline(
6322 streamsToKeep, &offlineSessionInfo, &offlineSession, &bufferRecords);
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006323
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006324 if (ret != OK) {
6325 SET_ERR("Switch to offline failed: %s (%d)", strerror(-ret), ret);
6326 return ret;
6327 }
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006328
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006329 bool succ = mRequestBufferSM.onSwitchToOfflineSuccess();
6330 if (!succ) {
6331 SET_ERR("HAL must not be calling requestStreamBuffers call");
6332 // TODO: block ALL callbacks from HAL till app configured new streams?
6333 return UNKNOWN_ERROR;
6334 }
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006335
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006336 // Verify offlineSessionInfo
6337 std::vector<int32_t> offlineStreamIds;
6338 offlineStreamIds.reserve(offlineSessionInfo.offlineStreams.size());
6339 for (auto offlineStream : offlineSessionInfo.offlineStreams) {
6340 // verify stream IDs
6341 int32_t id = offlineStream.id;
6342 if (std::find(streamIds.begin(), streamIds.end(), id) == streamIds.end()) {
6343 SET_ERR("stream ID %d not found!", id);
6344 return UNKNOWN_ERROR;
6345 }
6346
6347 // When not using HAL buf manager, only allow streams requested by app to be preserved
6348 if (!mUseHalBufManager) {
6349 if (std::find(streamsToKeep.begin(), streamsToKeep.end(), id) == streamsToKeep.end()) {
6350 SET_ERR("stream ID %d must not be switched to offline!", id);
6351 return UNKNOWN_ERROR;
6352 }
6353 }
6354
6355 offlineStreamIds.push_back(id);
6356 sp<Camera3StreamInterface> stream = (id == inputStreamId) ?
6357 static_cast<sp<Camera3StreamInterface>>(mInputStream) :
6358 static_cast<sp<Camera3StreamInterface>>(mOutputStreams.get(id));
6359 // Verify number of outstanding buffers
6360 if (stream->getOutstandingBuffersCount() != offlineStream.numOutstandingBuffers) {
6361 SET_ERR("Offline stream %d # of remaining buffer mismatch: (%zu,%d) (service/HAL)",
6362 id, stream->getOutstandingBuffersCount(), offlineStream.numOutstandingBuffers);
6363 return UNKNOWN_ERROR;
6364 }
6365 }
6366
6367 // Verify all streams to be deleted don't have any outstanding buffers
6368 if (hasInputStream && std::find(offlineStreamIds.begin(), offlineStreamIds.end(),
6369 inputStreamId) == offlineStreamIds.end()) {
6370 if (mInputStream->hasOutstandingBuffers()) {
6371 SET_ERR("Input stream %d still has %zu outstanding buffer!",
6372 inputStreamId, mInputStream->getOutstandingBuffersCount());
6373 return UNKNOWN_ERROR;
6374 }
6375 }
6376
6377 for (const auto& outStreamId : outputStreamIds) {
6378 if (std::find(offlineStreamIds.begin(), offlineStreamIds.end(),
6379 outStreamId) == offlineStreamIds.end()) {
6380 auto outStream = mOutputStreams.get(outStreamId);
6381 if (outStream->hasOutstandingBuffers()) {
6382 SET_ERR("Output stream %d still has %zu outstanding buffer!",
6383 outStreamId, outStream->getOutstandingBuffersCount());
6384 return UNKNOWN_ERROR;
6385 }
6386 }
6387 }
6388
6389 InFlightRequestMap offlineReqs;
6390 // Verify inflight requests and their pending buffers
6391 {
6392 std::lock_guard<std::mutex> l(mInFlightLock);
6393 for (auto offlineReq : offlineSessionInfo.offlineRequests) {
6394 int idx = mInFlightMap.indexOfKey(offlineReq.frameNumber);
6395 if (idx == NAME_NOT_FOUND) {
6396 SET_ERR("Offline request frame number %d not found!", offlineReq.frameNumber);
6397 return UNKNOWN_ERROR;
6398 }
6399
6400 const auto& inflightReq = mInFlightMap.valueAt(idx);
6401 // TODO: check specific stream IDs
6402 size_t numBuffersLeft = static_cast<size_t>(inflightReq.numBuffersLeft);
6403 if (numBuffersLeft != offlineReq.pendingStreams.size()) {
6404 SET_ERR("Offline request # of remaining buffer mismatch: (%d,%d) (service/HAL)",
6405 inflightReq.numBuffersLeft, offlineReq.pendingStreams.size());
6406 return UNKNOWN_ERROR;
6407 }
6408 offlineReqs.add(offlineReq.frameNumber, inflightReq);
6409 }
6410 }
6411
6412 // Create Camera3OfflineSession and transfer object ownership
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006413 // (streams, inflight requests, buffer caches)
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006414 camera3::StreamSet offlineStreamSet;
6415 sp<camera3::Camera3Stream> inputStream;
6416 for (auto offlineStream : offlineSessionInfo.offlineStreams) {
6417 int32_t id = offlineStream.id;
6418 if (mInputStream != nullptr && id == mInputStream->getId()) {
6419 inputStream = mInputStream;
6420 } else {
6421 offlineStreamSet.add(id, mOutputStreams.get(id));
6422 }
6423 }
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006424
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006425 // TODO: check if we need to lock before copying states
6426 // though technically no other thread should be talking to Camera3Device at this point
6427 Camera3OfflineStates offlineStates(
6428 mTagMonitor, mVendorTagId, mUseHalBufManager, mNeedFixupMonochromeTags,
Shuzhen Wangb7b42652020-05-07 11:59:02 -07006429 mUsePartialResult, mNumPartialResults, mLastCompletedRegularFrameNumber,
6430 mLastCompletedReprocessFrameNumber, mLastCompletedZslFrameNumber,
6431 mNextResultFrameNumber, mNextReprocessResultFrameNumber,
6432 mNextZslStillResultFrameNumber, mNextShutterFrameNumber,
6433 mNextReprocessShutterFrameNumber, mNextZslStillShutterFrameNumber,
6434 mDeviceInfo, mPhysicalDeviceInfoMap, mDistortionMappers,
6435 mZoomRatioMappers, mRotateAndCropMappers);
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006436
6437 *session = new Camera3OfflineSession(mId, inputStream, offlineStreamSet,
6438 std::move(bufferRecords), offlineReqs, offlineStates, offlineSession);
6439
6440 // Delete all streams that has been transferred to offline session
6441 Mutex::Autolock l(mLock);
6442 for (auto offlineStream : offlineSessionInfo.offlineStreams) {
6443 int32_t id = offlineStream.id;
6444 if (mInputStream != nullptr && id == mInputStream->getId()) {
6445 mInputStream.clear();
6446 } else {
6447 mOutputStreams.remove(id);
6448 }
6449 }
6450
6451 // disconnect all other streams and switch to UNCONFIGURED state
6452 if (mInputStream != nullptr) {
6453 ret = mInputStream->disconnect();
6454 if (ret != OK) {
6455 SET_ERR_L("disconnect input stream failed!");
6456 return UNKNOWN_ERROR;
6457 }
6458 }
6459
6460 for (auto streamId : mOutputStreams.getStreamIds()) {
6461 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
6462 ret = stream->disconnect();
6463 if (ret != OK) {
6464 SET_ERR_L("disconnect output stream %d failed!", streamId);
6465 return UNKNOWN_ERROR;
6466 }
6467 }
6468
6469 mInputStream.clear();
6470 mOutputStreams.clear();
6471 mNeedConfig = true;
6472 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
6473 mOperatingMode = NO_MODE;
6474 mIsConstrainedHighSpeedConfiguration = false;
Emilian Peevc0fe54c2020-03-11 14:05:07 -07006475 mRequestThread->clearPreviousRequest();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006476
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006477 return OK;
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006478 // TO be done by CameraDeviceClient/Camera3OfflineSession
6479 // register the offline client to camera service
6480 // Setup result passthing threads etc
6481 // Initialize offline session so HAL can start sending callback to it (result Fmq)
6482 // TODO: check how many onIdle callback will be sent
6483 // Java side to make sure the CameraCaptureSession is properly closed
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006484}
6485
Emilian Peevcc0b7952020-01-07 13:54:47 -08006486void Camera3Device::getOfflineStreamIds(std::vector<int> *offlineStreamIds) {
6487 ATRACE_CALL();
6488
6489 if (offlineStreamIds == nullptr) {
6490 return;
6491 }
6492
6493 Mutex::Autolock il(mInterfaceLock);
6494
6495 auto streamIds = mOutputStreams.getStreamIds();
6496 bool hasInputStream = mInputStream != nullptr;
6497 if (hasInputStream && mInputStream->getOfflineProcessingSupport()) {
6498 offlineStreamIds->push_back(mInputStream->getId());
6499 }
6500
6501 for (const auto & streamId : streamIds) {
6502 sp<camera3::Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
6503 // Streams that use the camera buffer manager are currently not supported in
6504 // offline mode
6505 if (stream->getOfflineProcessingSupport() &&
6506 (stream->getStreamSetId() == CAMERA3_STREAM_SET_ID_INVALID)) {
6507 offlineStreamIds->push_back(streamId);
6508 }
6509 }
6510}
6511
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08006512status_t Camera3Device::setRotateAndCropAutoBehavior(
6513 camera_metadata_enum_android_scaler_rotate_and_crop_t rotateAndCropValue) {
6514 ATRACE_CALL();
6515 Mutex::Autolock il(mInterfaceLock);
6516 Mutex::Autolock l(mLock);
6517 if (mRequestThread == nullptr) {
6518 return INVALID_OPERATION;
6519 }
6520 return mRequestThread->setRotateAndCropAutoBehavior(rotateAndCropValue);
6521}
6522
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08006523bool Camera3Device::supportsCameraMute() {
6524 Mutex::Autolock il(mInterfaceLock);
6525 Mutex::Autolock l(mLock);
6526
6527 return mSupportCameraMute;
6528}
6529
6530status_t Camera3Device::setCameraMute(bool enabled) {
6531 ATRACE_CALL();
6532 Mutex::Autolock il(mInterfaceLock);
6533 Mutex::Autolock l(mLock);
6534
6535 if (mRequestThread == nullptr || !mSupportCameraMute) {
6536 return INVALID_OPERATION;
6537 }
6538 return mRequestThread->setCameraMute(enabled);
6539}
6540
Cliff Wuc2ad9c82021-04-21 00:58:58 +08006541status_t Camera3Device::injectCamera(const String8& injectedCamId,
6542 sp<CameraProviderManager> manager) {
6543 ALOGI("%s Injection camera: injectedCamId = %s", __FUNCTION__, injectedCamId.string());
6544 ATRACE_CALL();
6545 Mutex::Autolock il(mInterfaceLock);
6546
6547 status_t res = NO_ERROR;
6548 if (mInjectionMethods->isInjecting()) {
6549 if (injectedCamId == mInjectionMethods->getInjectedCamId()) {
6550 return OK;
6551 } else {
6552 res = mInjectionMethods->stopInjection();
6553 if (res != OK) {
6554 ALOGE("%s: Failed to stop the injection camera! ret != NO_ERROR: %d",
6555 __FUNCTION__, res);
6556 return res;
6557 }
6558 }
6559 }
6560
6561 res = mInjectionMethods->injectionInitialize(injectedCamId, manager, this);
6562 if (res != OK) {
6563 ALOGE("%s: Failed to initialize the injection camera! ret != NO_ERROR: %d",
6564 __FUNCTION__, res);
6565 return res;
6566 }
6567
6568 camera3::camera_stream_configuration injectionConfig;
6569 std::vector<uint32_t> injectionBufferSizes;
6570 mInjectionMethods->getInjectionConfig(&injectionConfig, &injectionBufferSizes);
6571 // When the second display of android is cast to the remote device, and the opened camera is
6572 // also cast to the second display, in this case, because the camera has configured the streams
6573 // at this time, we can directly call injectCamera() to replace the internal camera with
6574 // injection camera.
6575 if (mOperatingMode >= 0 && injectionConfig.num_streams > 0
6576 && injectionBufferSizes.size() > 0) {
6577 ALOGV("%s: The opened camera is directly cast to the remote device.", __FUNCTION__);
6578 res = mInjectionMethods->injectCamera(
6579 injectionConfig, injectionBufferSizes);
6580 if (res != OK) {
6581 ALOGE("Can't finish inject camera process!");
6582 return res;
6583 }
6584 }
6585
6586 return OK;
6587}
6588
6589status_t Camera3Device::stopInjection() {
6590 ALOGI("%s: Injection camera: stopInjection", __FUNCTION__);
6591 Mutex::Autolock il(mInterfaceLock);
6592 return mInjectionMethods->stopInjection();
6593}
6594
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08006595}; // namespace android