blob: 73a133f8e68c96e26cedeb5ed93091f3c87e389b [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
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -080052#include <android/hardware/camera2/ICameraDeviceUser.h>
53
Igor Murashkinff3e31d2013-10-23 16:40:06 -070054#include "utils/CameraTraces.h"
Eino-Ville Talvalaf99498e2015-09-25 16:52:55 -070055#include "mediautils/SchedulingPolicyService.h"
Eino-Ville Talvala7b82efe2013-07-25 17:12:35 -070056#include "device3/Camera3Device.h"
57#include "device3/Camera3OutputStream.h"
58#include "device3/Camera3InputStream.h"
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -040059#include "device3/Camera3FakeStream.h"
Shuzhen Wang0129d522016-10-30 22:43:41 -070060#include "device3/Camera3SharedOutputStream.h"
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -070061#include "CameraService.h"
Jayant Chowdhary12361932018-08-27 14:46:13 -070062#include "utils/CameraThreadState.h"
Jayant Chowdharyd4776262020-06-23 23:45:57 -070063#include "utils/TraceHFR.h"
Shuzhen Wang316781a2020-08-18 18:11:01 -070064#include "utils/CameraServiceProxyWrapper.h"
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -080065
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -080066#include <algorithm>
Yin-Chia Yeh84be5782019-03-01 11:47:02 -080067#include <tuple>
68
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -080069using namespace android::camera3;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080070using namespace android::hardware::camera;
71using namespace android::hardware::camera::device::V3_2;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080072
73namespace android {
74
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -080075Camera3Device::Camera3Device(const String8 &id):
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080076 mId(id),
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -080077 mOperatingMode(NO_MODE),
Eino-Ville Talvala9a179412015-06-09 13:15:16 -070078 mIsConstrainedHighSpeedConfiguration(false),
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -070079 mStatus(STATUS_UNINITIALIZED),
Ruben Brunk183f0562015-08-12 12:55:02 -070080 mStatusWaiters(0),
Zhijun He204e3292014-07-14 17:09:23 -070081 mUsePartialResult(false),
82 mNumPartialResults(1),
Shuzhen Wangc28dccc2016-02-11 23:48:46 -080083 mTimestampOffset(0),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -070084 mNextResultFrameNumber(0),
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -070085 mNextReprocessResultFrameNumber(0),
Shuzhen Wang5ee99842019-04-12 11:55:48 -070086 mNextZslStillResultFrameNumber(0),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -070087 mNextShutterFrameNumber(0),
Chien-Yu Chen3df11ce2015-09-30 14:13:30 -070088 mNextReprocessShutterFrameNumber(0),
Shuzhen Wang5ee99842019-04-12 11:55:48 -070089 mNextZslStillShutterFrameNumber(0),
Emilian Peev71c73a22017-03-21 16:35:51 +000090 mListener(NULL),
Emilian Peev811d2952018-05-25 11:08:40 +010091 mVendorTagId(CAMERA_METADATA_INVALID_VENDOR_ID),
Shuzhen Wang268a1362018-10-16 16:32:59 -070092 mLastTemplateId(-1),
93 mNeedFixupMonochromeTags(false)
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080094{
95 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080096 ALOGV("%s: Created device for camera %s", __FUNCTION__, mId.string());
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080097}
98
99Camera3Device::~Camera3Device()
100{
101 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800102 ALOGV("%s: Tearing down for camera id %s", __FUNCTION__, mId.string());
Yin-Chia Yehc5248132018-08-15 12:19:20 -0700103 disconnectImpl();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800104}
105
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800106const String8& Camera3Device::getId() const {
Igor Murashkin71381052013-03-04 14:53:08 -0800107 return mId;
108}
109
Emilian Peevbd8c5032018-02-14 23:05:40 +0000110status_t Camera3Device::initialize(sp<CameraProviderManager> manager, const String8& monitorTags) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800111 ATRACE_CALL();
112 Mutex::Autolock il(mInterfaceLock);
113 Mutex::Autolock l(mLock);
114
115 ALOGV("%s: Initializing HIDL device for camera %s", __FUNCTION__, mId.string());
116 if (mStatus != STATUS_UNINITIALIZED) {
117 CLOGE("Already initialized!");
118 return INVALID_OPERATION;
119 }
120 if (manager == nullptr) return INVALID_OPERATION;
121
122 sp<ICameraDeviceSession> session;
123 ATRACE_BEGIN("CameraHal::openSession");
Steven Moreland5ff9c912017-03-09 23:13:00 -0800124 status_t res = manager->openSession(mId.string(), this,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800125 /*out*/ &session);
126 ATRACE_END();
127 if (res != OK) {
128 SET_ERR_L("Could not open camera session: %s (%d)", strerror(-res), res);
129 return res;
130 }
131
Steven Moreland5ff9c912017-03-09 23:13:00 -0800132 res = manager->getCameraCharacteristics(mId.string(), &mDeviceInfo);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800133 if (res != OK) {
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700134 SET_ERR_L("Could not retrieve camera characteristics: %s (%d)", strerror(-res), res);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800135 session->close();
136 return res;
137 }
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800138 mSupportNativeZoomRatio = manager->supportNativeZoomRatio(mId.string());
Yin-Chia Yeh52778d42016-12-22 18:20:43 -0800139
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700140 std::vector<std::string> physicalCameraIds;
Shuzhen Wang03d8cc12018-09-12 14:17:09 -0700141 bool isLogical = manager->isLogicalCamera(mId.string(), &physicalCameraIds);
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700142 if (isLogical) {
143 for (auto& physicalId : physicalCameraIds) {
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -0700144 res = manager->getCameraCharacteristics(
145 physicalId, &mPhysicalDeviceInfoMap[physicalId]);
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700146 if (res != OK) {
147 SET_ERR_L("Could not retrieve camera %s characteristics: %s (%d)",
148 physicalId.c_str(), strerror(-res), res);
149 session->close();
150 return res;
151 }
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -0700152
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800153 bool usePrecorrectArray =
154 DistortionMapper::isDistortionSupported(mPhysicalDeviceInfoMap[physicalId]);
155 if (usePrecorrectArray) {
156 res = mDistortionMappers[physicalId].setupStaticInfo(
157 mPhysicalDeviceInfoMap[physicalId]);
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -0700158 if (res != OK) {
159 SET_ERR_L("Unable to read camera %s's calibration fields for distortion "
160 "correction", physicalId.c_str());
161 session->close();
162 return res;
163 }
164 }
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800165
Shuzhen Wang1c834da2019-12-18 11:17:03 -0800166 mZoomRatioMappers[physicalId] = ZoomRatioMapper(
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800167 &mPhysicalDeviceInfoMap[physicalId],
168 mSupportNativeZoomRatio, usePrecorrectArray);
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700169 }
170 }
171
Yifan Hongf79b5542017-04-11 14:44:25 -0700172 std::shared_ptr<RequestMetadataQueue> queue;
Yifan Honga640c5a2017-04-12 16:30:31 -0700173 auto requestQueueRet = session->getCaptureRequestMetadataQueue(
174 [&queue](const auto& descriptor) {
175 queue = std::make_shared<RequestMetadataQueue>(descriptor);
176 if (!queue->isValid() || queue->availableToWrite() <= 0) {
177 ALOGE("HAL returns empty request metadata fmq, not use it");
178 queue = nullptr;
179 // don't use the queue onwards.
180 }
181 });
182 if (!requestQueueRet.isOk()) {
183 ALOGE("Transaction error when getting request metadata fmq: %s, not use it",
184 requestQueueRet.description().c_str());
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -0700185 return DEAD_OBJECT;
Yifan Hongf79b5542017-04-11 14:44:25 -0700186 }
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700187
188 std::unique_ptr<ResultMetadataQueue>& resQueue = mResultMetadataQueue;
Yifan Honga640c5a2017-04-12 16:30:31 -0700189 auto resultQueueRet = session->getCaptureResultMetadataQueue(
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700190 [&resQueue](const auto& descriptor) {
191 resQueue = std::make_unique<ResultMetadataQueue>(descriptor);
192 if (!resQueue->isValid() || resQueue->availableToWrite() <= 0) {
Yifan Honga640c5a2017-04-12 16:30:31 -0700193 ALOGE("HAL returns empty result metadata fmq, not use it");
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700194 resQueue = nullptr;
195 // Don't use the resQueue onwards.
Yifan Honga640c5a2017-04-12 16:30:31 -0700196 }
197 });
198 if (!resultQueueRet.isOk()) {
199 ALOGE("Transaction error when getting result metadata queue from camera session: %s",
200 resultQueueRet.description().c_str());
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -0700201 return DEAD_OBJECT;
Yifan Honga640c5a2017-04-12 16:30:31 -0700202 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -0700203 IF_ALOGV() {
204 session->interfaceChain([](
205 ::android::hardware::hidl_vec<::android::hardware::hidl_string> interfaceChain) {
206 ALOGV("Session interface chain:");
Chih-Hung Hsieh3ef324d2018-12-11 11:48:12 -0800207 for (const auto& iface : interfaceChain) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -0700208 ALOGV(" %s", iface.c_str());
209 }
210 });
211 }
Yifan Hongf79b5542017-04-11 14:44:25 -0700212
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -0800213 camera_metadata_entry bufMgrMode =
214 mDeviceInfo.find(ANDROID_INFO_SUPPORTED_BUFFER_MANAGEMENT_VERSION);
215 if (bufMgrMode.count > 0) {
216 mUseHalBufManager = (bufMgrMode.data.u8[0] ==
217 ANDROID_INFO_SUPPORTED_BUFFER_MANAGEMENT_VERSION_HIDL_DEVICE_3_5);
218 }
219
Yin-Chia Yehb978c382019-10-30 00:22:37 -0700220 camera_metadata_entry_t capabilities = mDeviceInfo.find(ANDROID_REQUEST_AVAILABLE_CAPABILITIES);
221 for (size_t i = 0; i < capabilities.count; i++) {
222 uint8_t capability = capabilities.data.u8[i];
223 if (capability == ANDROID_REQUEST_AVAILABLE_CAPABILITIES_OFFLINE_PROCESSING) {
224 mSupportOfflineProcessing = true;
225 }
226 }
227
228 mInterface = new HalInterface(session, queue, mUseHalBufManager, mSupportOfflineProcessing);
Emilian Peev71c73a22017-03-21 16:35:51 +0000229 std::string providerType;
230 mVendorTagId = manager->getProviderTagIdLocked(mId.string());
Emilian Peevbd8c5032018-02-14 23:05:40 +0000231 mTagMonitor.initialize(mVendorTagId);
232 if (!monitorTags.isEmpty()) {
233 mTagMonitor.parseTagsToMonitor(String8(monitorTags));
234 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800235
Shuzhen Wang268a1362018-10-16 16:32:59 -0700236 // Metadata tags needs fixup for monochrome camera device version less
237 // than 3.5.
238 hardware::hidl_version maxVersion{0,0};
239 res = manager->getHighestSupportedVersion(mId.string(), &maxVersion);
240 if (res != OK) {
241 ALOGE("%s: Error in getting camera device version id: %s (%d)",
242 __FUNCTION__, strerror(-res), res);
243 return res;
244 }
245 int deviceVersion = HARDWARE_DEVICE_API_VERSION(
246 maxVersion.get_major(), maxVersion.get_minor());
247
248 bool isMonochrome = false;
Yin-Chia Yehb978c382019-10-30 00:22:37 -0700249 for (size_t i = 0; i < capabilities.count; i++) {
250 uint8_t capability = capabilities.data.u8[i];
Shuzhen Wang268a1362018-10-16 16:32:59 -0700251 if (capability == ANDROID_REQUEST_AVAILABLE_CAPABILITIES_MONOCHROME) {
252 isMonochrome = true;
253 }
254 }
255 mNeedFixupMonochromeTags = (isMonochrome && deviceVersion < CAMERA_DEVICE_API_VERSION_3_5);
256
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800257 return initializeCommonLocked();
258}
259
260status_t Camera3Device::initializeCommonLocked() {
261
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700262 /** Start up status tracker thread */
263 mStatusTracker = new StatusTracker(this);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800264 status_t res = mStatusTracker->run(String8::format("C3Dev-%s-Status", mId.string()).string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700265 if (res != OK) {
266 SET_ERR_L("Unable to start status tracking thread: %s (%d)",
267 strerror(-res), res);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800268 mInterface->close();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700269 mStatusTracker.clear();
270 return res;
271 }
272
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -0700273 /** Register in-flight map to the status tracker */
Yin-Chia Yeh87b3ec02019-06-03 10:44:39 -0700274 mInFlightStatusId = mStatusTracker->addComponent("InflightRequests");
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -0700275
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -0700276 if (mUseHalBufManager) {
277 res = mRequestBufferSM.initialize(mStatusTracker);
278 if (res != OK) {
279 SET_ERR_L("Unable to start request buffer state machine: %s (%d)",
280 strerror(-res), res);
281 mInterface->close();
282 mStatusTracker.clear();
283 return res;
284 }
285 }
286
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -0800287 /** Create buffer manager */
288 mBufferManager = new Camera3BufferManager();
289
290 Vector<int32_t> sessionParamKeys;
291 camera_metadata_entry_t sessionKeysEntry = mDeviceInfo.find(
292 ANDROID_REQUEST_AVAILABLE_SESSION_KEYS);
293 if (sessionKeysEntry.count > 0) {
294 sessionParamKeys.insertArrayAt(sessionKeysEntry.data.i32, 0, sessionKeysEntry.count);
295 }
296
Chien-Yu Chenab5135b2015-06-30 11:20:58 -0700297 /** Start up request queue thread */
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -0700298 mRequestThread = new RequestThread(
299 this, mStatusTracker, mInterface, sessionParamKeys, mUseHalBufManager);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800300 res = mRequestThread->run(String8::format("C3Dev-%s-ReqQueue", mId.string()).string());
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800301 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700302 SET_ERR_L("Unable to start request queue thread: %s (%d)",
303 strerror(-res), res);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800304 mInterface->close();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800305 mRequestThread.clear();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800306 return res;
307 }
308
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -0700309 mPreparerThread = new PreparerThread();
310
Ruben Brunk183f0562015-08-12 12:55:02 -0700311 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800312 mNextStreamId = 0;
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -0400313 mFakeStreamId = NO_STREAM;
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -0700314 mNeedConfig = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700315 mPauseStateNotify = false;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800316
Shuzhen Wangc28dccc2016-02-11 23:48:46 -0800317 // Measure the clock domain offset between camera and video/hw_composer
318 camera_metadata_entry timestampSource =
319 mDeviceInfo.find(ANDROID_SENSOR_INFO_TIMESTAMP_SOURCE);
320 if (timestampSource.count > 0 && timestampSource.data.u8[0] ==
321 ANDROID_SENSOR_INFO_TIMESTAMP_SOURCE_REALTIME) {
322 mTimestampOffset = getMonoToBoottimeOffset();
323 }
324
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -0700325 // Will the HAL be sending in early partial result metadata?
Emilian Peev08dd2452017-04-06 16:55:14 +0100326 camera_metadata_entry partialResultsCount =
327 mDeviceInfo.find(ANDROID_REQUEST_PARTIAL_RESULT_COUNT);
328 if (partialResultsCount.count > 0) {
329 mNumPartialResults = partialResultsCount.data.i32[0];
330 mUsePartialResult = (mNumPartialResults > 1);
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -0700331 }
332
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800333 bool usePrecorrectArray = DistortionMapper::isDistortionSupported(mDeviceInfo);
334 if (usePrecorrectArray) {
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -0700335 res = mDistortionMappers[mId.c_str()].setupStaticInfo(mDeviceInfo);
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -0700336 if (res != OK) {
337 SET_ERR_L("Unable to read necessary calibration fields for distortion correction");
338 return res;
339 }
340 }
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800341
Shuzhen Wang1c834da2019-12-18 11:17:03 -0800342 mZoomRatioMappers[mId.c_str()] = ZoomRatioMapper(&mDeviceInfo,
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800343 mSupportNativeZoomRatio, usePrecorrectArray);
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800344
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -0800345 if (RotateAndCropMapper::isNeeded(&mDeviceInfo)) {
346 mRotateAndCropMappers.emplace(mId.c_str(), &mDeviceInfo);
347 }
348
Eino-Ville Talvala305cec62020-11-12 14:18:17 -0800349 camera_metadata_entry_t availableTestPatternModes = mDeviceInfo.find(
350 ANDROID_SENSOR_AVAILABLE_TEST_PATTERN_MODES);
351 for (size_t i = 0; i < availableTestPatternModes.count; i++) {
352 if (availableTestPatternModes.data.i32[i] == ANDROID_SENSOR_TEST_PATTERN_MODE_SOLID_COLOR) {
353 mSupportCameraMute = true;
354 break;
355 }
356 }
357
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800358 return OK;
359}
360
361status_t Camera3Device::disconnect() {
Yin-Chia Yehc5248132018-08-15 12:19:20 -0700362 return disconnectImpl();
363}
364
365status_t Camera3Device::disconnectImpl() {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800366 ATRACE_CALL();
Yin-Chia Yehe1c80632016-08-08 14:48:05 -0700367 ALOGI("%s: E", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800368
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700369 status_t res = OK;
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700370 std::vector<wp<Camera3StreamInterface>> streams;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700371 {
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800372 Mutex::Autolock il(mInterfaceLock);
373 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
374 {
375 Mutex::Autolock l(mLock);
376 if (mStatus == STATUS_UNINITIALIZED) return res;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700377
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800378 if (mStatus == STATUS_ACTIVE ||
379 (mStatus == STATUS_ERROR && mRequestThread != NULL)) {
380 res = mRequestThread->clearRepeatingRequests();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700381 if (res != OK) {
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800382 SET_ERR_L("Can't stop streaming");
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700383 // Continue to close device even in case of error
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800384 } else {
385 res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
386 if (res != OK) {
387 SET_ERR_L("Timeout waiting for HAL to drain (% " PRIi64 " ns)",
388 maxExpectedDuration);
389 // Continue to close device even in case of error
390 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700391 }
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700392 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800393
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800394 if (mStatus == STATUS_ERROR) {
395 CLOGE("Shutting down in an error state");
396 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700397
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800398 if (mStatusTracker != NULL) {
399 mStatusTracker->requestExit();
400 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700401
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800402 if (mRequestThread != NULL) {
403 mRequestThread->requestExit();
404 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700405
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800406 streams.reserve(mOutputStreams.size() + (mInputStream != nullptr ? 1 : 0));
407 for (size_t i = 0; i < mOutputStreams.size(); i++) {
408 streams.push_back(mOutputStreams[i]);
409 }
410 if (mInputStream != nullptr) {
411 streams.push_back(mInputStream);
412 }
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700413 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700414 }
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800415 // Joining done without holding mLock and mInterfaceLock, otherwise deadlocks may ensue
416 // as the threads try to access parent state (b/143513518)
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700417 if (mRequestThread != NULL && mStatus != STATUS_ERROR) {
418 // HAL may be in a bad state, so waiting for request thread
419 // (which may be stuck in the HAL processCaptureRequest call)
420 // could be dangerous.
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800421 // give up mInterfaceLock here and then lock it again. Could this lead
422 // to other deadlocks
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700423 mRequestThread->join();
424 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700425 {
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800426 Mutex::Autolock il(mInterfaceLock);
427 if (mStatusTracker != NULL) {
428 mStatusTracker->join();
429 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800430
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800431 HalInterface* interface;
432 {
433 Mutex::Autolock l(mLock);
434 mRequestThread.clear();
435 Mutex::Autolock stLock(mTrackerLock);
436 mStatusTracker.clear();
437 interface = mInterface.get();
438 }
Eino-Ville Talvalaefff1c42015-08-28 16:27:27 -0700439
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800440 // Call close without internal mutex held, as the HAL close may need to
441 // wait on assorted callbacks,etc, to complete before it can return.
442 interface->close();
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700443
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800444 flushInflightRequests();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800445
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800446 {
447 Mutex::Autolock l(mLock);
448 mInterface->clear();
449 mOutputStreams.clear();
450 mInputStream.clear();
451 mDeletedStreams.clear();
452 mBufferManager.clear();
453 internalUpdateStatusLocked(STATUS_UNINITIALIZED);
454 }
455
456 for (auto& weakStream : streams) {
457 sp<Camera3StreamInterface> stream = weakStream.promote();
458 if (stream != nullptr) {
459 ALOGE("%s: Stream %d leaked! strong reference (%d)!",
460 __FUNCTION__, stream->getId(), stream->getStrongCount() - 1);
461 }
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700462 }
463 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -0700464 ALOGI("%s: X", __FUNCTION__);
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700465 return res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800466}
467
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700468// For dumping/debugging only -
469// try to acquire a lock a few times, eventually give up to proceed with
470// debug/dump operations
471bool Camera3Device::tryLockSpinRightRound(Mutex& lock) {
472 bool gotLock = false;
473 for (size_t i = 0; i < kDumpLockAttempts; ++i) {
474 if (lock.tryLock() == NO_ERROR) {
475 gotLock = true;
476 break;
477 } else {
478 usleep(kDumpSleepDuration);
479 }
480 }
481 return gotLock;
482}
483
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700484Camera3Device::Size Camera3Device::getMaxJpegResolution() const {
485 int32_t maxJpegWidth = 0, maxJpegHeight = 0;
Emilian Peev08dd2452017-04-06 16:55:14 +0100486 const int STREAM_CONFIGURATION_SIZE = 4;
487 const int STREAM_FORMAT_OFFSET = 0;
488 const int STREAM_WIDTH_OFFSET = 1;
489 const int STREAM_HEIGHT_OFFSET = 2;
490 const int STREAM_IS_INPUT_OFFSET = 3;
491 camera_metadata_ro_entry_t availableStreamConfigs =
492 mDeviceInfo.find(ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS);
493 if (availableStreamConfigs.count == 0 ||
494 availableStreamConfigs.count % STREAM_CONFIGURATION_SIZE != 0) {
495 return Size(0, 0);
496 }
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700497
Emilian Peev08dd2452017-04-06 16:55:14 +0100498 // Get max jpeg size (area-wise).
499 for (size_t i=0; i < availableStreamConfigs.count; i+= STREAM_CONFIGURATION_SIZE) {
500 int32_t format = availableStreamConfigs.data.i32[i + STREAM_FORMAT_OFFSET];
501 int32_t width = availableStreamConfigs.data.i32[i + STREAM_WIDTH_OFFSET];
502 int32_t height = availableStreamConfigs.data.i32[i + STREAM_HEIGHT_OFFSET];
503 int32_t isInput = availableStreamConfigs.data.i32[i + STREAM_IS_INPUT_OFFSET];
504 if (isInput == ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS_OUTPUT
505 && format == HAL_PIXEL_FORMAT_BLOB &&
506 (width * height > maxJpegWidth * maxJpegHeight)) {
507 maxJpegWidth = width;
508 maxJpegHeight = height;
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700509 }
510 }
Emilian Peev08dd2452017-04-06 16:55:14 +0100511
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700512 return Size(maxJpegWidth, maxJpegHeight);
513}
514
Shuzhen Wangc28dccc2016-02-11 23:48:46 -0800515nsecs_t Camera3Device::getMonoToBoottimeOffset() {
516 // try three times to get the clock offset, choose the one
517 // with the minimum gap in measurements.
518 const int tries = 3;
519 nsecs_t bestGap, measured;
520 for (int i = 0; i < tries; ++i) {
521 const nsecs_t tmono = systemTime(SYSTEM_TIME_MONOTONIC);
522 const nsecs_t tbase = systemTime(SYSTEM_TIME_BOOTTIME);
523 const nsecs_t tmono2 = systemTime(SYSTEM_TIME_MONOTONIC);
524 const nsecs_t gap = tmono2 - tmono;
525 if (i == 0 || gap < bestGap) {
526 bestGap = gap;
527 measured = tbase - ((tmono + tmono2) >> 1);
528 }
529 }
530 return measured;
531}
532
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800533hardware::graphics::common::V1_0::PixelFormat Camera3Device::mapToPixelFormat(
534 int frameworkFormat) {
535 return (hardware::graphics::common::V1_0::PixelFormat) frameworkFormat;
536}
537
538DataspaceFlags Camera3Device::mapToHidlDataspace(
539 android_dataspace dataSpace) {
540 return dataSpace;
541}
542
Chia-I Wu67a0c0e2017-04-06 13:37:01 -0700543BufferUsageFlags Camera3Device::mapToConsumerUsage(
Emilian Peev050f5dc2017-05-18 14:43:56 +0100544 uint64_t usage) {
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -0700545 return usage;
546}
547
Emilian Peevf4816702020-04-03 15:44:51 -0700548StreamRotation Camera3Device::mapToStreamRotation(camera_stream_rotation_t rotation) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800549 switch (rotation) {
Emilian Peevf4816702020-04-03 15:44:51 -0700550 case CAMERA_STREAM_ROTATION_0:
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800551 return StreamRotation::ROTATION_0;
Emilian Peevf4816702020-04-03 15:44:51 -0700552 case CAMERA_STREAM_ROTATION_90:
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800553 return StreamRotation::ROTATION_90;
Emilian Peevf4816702020-04-03 15:44:51 -0700554 case CAMERA_STREAM_ROTATION_180:
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800555 return StreamRotation::ROTATION_180;
Emilian Peevf4816702020-04-03 15:44:51 -0700556 case CAMERA_STREAM_ROTATION_270:
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800557 return StreamRotation::ROTATION_270;
558 }
559 ALOGE("%s: Unknown stream rotation %d", __FUNCTION__, rotation);
560 return StreamRotation::ROTATION_0;
561}
562
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800563status_t Camera3Device::mapToStreamConfigurationMode(
Emilian Peevf4816702020-04-03 15:44:51 -0700564 camera_stream_configuration_mode_t operationMode, StreamConfigurationMode *mode) {
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800565 if (mode == nullptr) return BAD_VALUE;
Emilian Peevf4816702020-04-03 15:44:51 -0700566 if (operationMode < CAMERA_VENDOR_STREAM_CONFIGURATION_MODE_START) {
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800567 switch(operationMode) {
Emilian Peevf4816702020-04-03 15:44:51 -0700568 case CAMERA_STREAM_CONFIGURATION_NORMAL_MODE:
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800569 *mode = StreamConfigurationMode::NORMAL_MODE;
570 break;
Emilian Peevf4816702020-04-03 15:44:51 -0700571 case CAMERA_STREAM_CONFIGURATION_CONSTRAINED_HIGH_SPEED_MODE:
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800572 *mode = StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE;
573 break;
574 default:
575 ALOGE("%s: Unknown stream configuration mode %d", __FUNCTION__, operationMode);
576 return BAD_VALUE;
577 }
578 } else {
579 *mode = static_cast<StreamConfigurationMode>(operationMode);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800580 }
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800581 return OK;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800582}
583
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800584int Camera3Device::mapToFrameworkFormat(
585 hardware::graphics::common::V1_0::PixelFormat pixelFormat) {
586 return static_cast<uint32_t>(pixelFormat);
587}
588
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -0700589android_dataspace Camera3Device::mapToFrameworkDataspace(
590 DataspaceFlags dataSpace) {
591 return static_cast<android_dataspace>(dataSpace);
592}
593
Emilian Peev050f5dc2017-05-18 14:43:56 +0100594uint64_t Camera3Device::mapConsumerToFrameworkUsage(
Chia-I Wu67a0c0e2017-04-06 13:37:01 -0700595 BufferUsageFlags usage) {
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -0700596 return usage;
597}
598
Emilian Peev050f5dc2017-05-18 14:43:56 +0100599uint64_t Camera3Device::mapProducerToFrameworkUsage(
Chia-I Wu67a0c0e2017-04-06 13:37:01 -0700600 BufferUsageFlags usage) {
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -0700601 return usage;
602}
603
Zhijun Hef7da0962014-04-24 13:27:56 -0700604ssize_t Camera3Device::getJpegBufferSize(uint32_t width, uint32_t height) const {
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700605 // Get max jpeg size (area-wise).
606 Size maxJpegResolution = getMaxJpegResolution();
607 if (maxJpegResolution.width == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800608 ALOGE("%s: Camera %s: Can't find valid available jpeg sizes in static metadata!",
609 __FUNCTION__, mId.string());
Zhijun Hef7da0962014-04-24 13:27:56 -0700610 return BAD_VALUE;
611 }
612
Zhijun Hef7da0962014-04-24 13:27:56 -0700613 // Get max jpeg buffer size
614 ssize_t maxJpegBufferSize = 0;
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700615 camera_metadata_ro_entry jpegBufMaxSize = mDeviceInfo.find(ANDROID_JPEG_MAX_SIZE);
616 if (jpegBufMaxSize.count == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800617 ALOGE("%s: Camera %s: Can't find maximum JPEG size in static metadata!", __FUNCTION__,
618 mId.string());
Zhijun Hef7da0962014-04-24 13:27:56 -0700619 return BAD_VALUE;
620 }
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700621 maxJpegBufferSize = jpegBufMaxSize.data.i32[0];
Yin-Chia Yeh0c4e56d2015-01-09 15:21:27 -0800622 assert(kMinJpegBufferSize < maxJpegBufferSize);
Zhijun Hef7da0962014-04-24 13:27:56 -0700623
624 // Calculate final jpeg buffer size for the given resolution.
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700625 float scaleFactor = ((float) (width * height)) /
626 (maxJpegResolution.width * maxJpegResolution.height);
Yin-Chia Yeh0c4e56d2015-01-09 15:21:27 -0800627 ssize_t jpegBufferSize = scaleFactor * (maxJpegBufferSize - kMinJpegBufferSize) +
628 kMinJpegBufferSize;
Zhijun Hef7da0962014-04-24 13:27:56 -0700629 if (jpegBufferSize > maxJpegBufferSize) {
630 jpegBufferSize = maxJpegBufferSize;
Zhijun Hef7da0962014-04-24 13:27:56 -0700631 }
632
633 return jpegBufferSize;
634}
635
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700636ssize_t Camera3Device::getPointCloudBufferSize() const {
637 const int FLOATS_PER_POINT=4;
638 camera_metadata_ro_entry maxPointCount = mDeviceInfo.find(ANDROID_DEPTH_MAX_DEPTH_SAMPLES);
639 if (maxPointCount.count == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800640 ALOGE("%s: Camera %s: Can't find maximum depth point cloud size in static metadata!",
641 __FUNCTION__, mId.string());
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700642 return BAD_VALUE;
643 }
644 ssize_t maxBytesForPointCloud = sizeof(android_depth_points) +
645 maxPointCount.data.i32[0] * sizeof(float) * FLOATS_PER_POINT;
646 return maxBytesForPointCloud;
647}
648
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800649ssize_t Camera3Device::getRawOpaqueBufferSize(int32_t width, int32_t height) const {
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800650 const int PER_CONFIGURATION_SIZE = 3;
651 const int WIDTH_OFFSET = 0;
652 const int HEIGHT_OFFSET = 1;
653 const int SIZE_OFFSET = 2;
654 camera_metadata_ro_entry rawOpaqueSizes =
655 mDeviceInfo.find(ANDROID_SENSOR_OPAQUE_RAW_SIZE);
Aurimas Liutikasbc57b122016-02-16 09:59:16 -0800656 size_t count = rawOpaqueSizes.count;
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800657 if (count == 0 || (count % PER_CONFIGURATION_SIZE)) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800658 ALOGE("%s: Camera %s: bad opaque RAW size static metadata length(%zu)!",
659 __FUNCTION__, mId.string(), count);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800660 return BAD_VALUE;
661 }
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700662
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800663 for (size_t i = 0; i < count; i += PER_CONFIGURATION_SIZE) {
664 if (width == rawOpaqueSizes.data.i32[i + WIDTH_OFFSET] &&
665 height == rawOpaqueSizes.data.i32[i + HEIGHT_OFFSET]) {
666 return rawOpaqueSizes.data.i32[i + SIZE_OFFSET];
667 }
668 }
669
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800670 ALOGE("%s: Camera %s: cannot find size for %dx%d opaque RAW image!",
671 __FUNCTION__, mId.string(), width, height);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800672 return BAD_VALUE;
673}
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700674
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800675status_t Camera3Device::dump(int fd, const Vector<String16> &args) {
676 ATRACE_CALL();
677 (void)args;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700678
679 // Try to lock, but continue in case of failure (to avoid blocking in
680 // deadlocks)
681 bool gotInterfaceLock = tryLockSpinRightRound(mInterfaceLock);
682 bool gotLock = tryLockSpinRightRound(mLock);
683
684 ALOGW_IF(!gotInterfaceLock,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800685 "Camera %s: %s: Unable to lock interface lock, proceeding anyway",
686 mId.string(), __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700687 ALOGW_IF(!gotLock,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800688 "Camera %s: %s: Unable to lock main lock, proceeding anyway",
689 mId.string(), __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700690
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800691 bool dumpTemplates = false;
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700692
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800693 String16 templatesOption("-t");
694 int n = args.size();
695 for (int i = 0; i < n; i++) {
696 if (args[i] == templatesOption) {
697 dumpTemplates = true;
698 }
Emilian Peevbd8c5032018-02-14 23:05:40 +0000699 if (args[i] == TagMonitor::kMonitorOption) {
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700700 if (i + 1 < n) {
701 String8 monitorTags = String8(args[i + 1]);
702 if (monitorTags == "off") {
703 mTagMonitor.disableMonitoring();
704 } else {
705 mTagMonitor.parseTagsToMonitor(monitorTags);
706 }
707 } else {
708 mTagMonitor.disableMonitoring();
709 }
710 }
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800711 }
712
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800713 String8 lines;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800714
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800715 const char *status =
716 mStatus == STATUS_ERROR ? "ERROR" :
717 mStatus == STATUS_UNINITIALIZED ? "UNINITIALIZED" :
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700718 mStatus == STATUS_UNCONFIGURED ? "UNCONFIGURED" :
719 mStatus == STATUS_CONFIGURED ? "CONFIGURED" :
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800720 mStatus == STATUS_ACTIVE ? "ACTIVE" :
721 "Unknown";
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700722
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800723 lines.appendFormat(" Device status: %s\n", status);
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700724 if (mStatus == STATUS_ERROR) {
725 lines.appendFormat(" Error cause: %s\n", mErrorCause.string());
726 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800727 lines.appendFormat(" Stream configuration:\n");
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800728 const char *mode =
729 mOperatingMode == static_cast<int>(StreamConfigurationMode::NORMAL_MODE) ? "NORMAL" :
730 mOperatingMode == static_cast<int>(
731 StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE) ? "CONSTRAINED_HIGH_SPEED" :
732 "CUSTOM";
733 lines.appendFormat(" Operation mode: %s (%d) \n", mode, mOperatingMode);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800734
735 if (mInputStream != NULL) {
736 write(fd, lines.string(), lines.size());
737 mInputStream->dump(fd, args);
738 } else {
739 lines.appendFormat(" No input stream.\n");
740 write(fd, lines.string(), lines.size());
741 }
742 for (size_t i = 0; i < mOutputStreams.size(); i++) {
743 mOutputStreams[i]->dump(fd,args);
744 }
745
Zhijun He431503c2016-03-07 17:30:16 -0800746 if (mBufferManager != NULL) {
747 lines = String8(" Camera3 Buffer Manager:\n");
748 write(fd, lines.string(), lines.size());
749 mBufferManager->dump(fd, args);
750 }
Zhijun He125684a2015-12-26 15:07:30 -0800751
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700752 lines = String8(" In-flight requests:\n");
753 if (mInFlightMap.size() == 0) {
754 lines.append(" None\n");
755 } else {
756 for (size_t i = 0; i < mInFlightMap.size(); i++) {
757 InFlightRequest r = mInFlightMap.valueAt(i);
Colin Crosse5729fa2014-03-21 15:04:25 -0700758 lines.appendFormat(" Frame %d | Timestamp: %" PRId64 ", metadata"
Greg Kaiser51b882c2020-06-10 05:41:44 +0000759 " arrived: %s, buffers left: %d\n", mInFlightMap.keyAt(i),
Chien-Yu Chen43e69a62014-11-25 16:38:33 -0800760 r.shutterTimestamp, r.haveResultMetadata ? "true" : "false",
Greg Kaiser51b882c2020-06-10 05:41:44 +0000761 r.numBuffersLeft);
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700762 }
763 }
764 write(fd, lines.string(), lines.size());
765
Shuzhen Wang686f6442017-06-20 16:16:04 -0700766 if (mRequestThread != NULL) {
767 mRequestThread->dumpCaptureRequestLatency(fd,
768 " ProcessCaptureRequest latency histogram:");
769 }
770
Igor Murashkin1e479c02013-09-06 16:55:14 -0700771 {
772 lines = String8(" Last request sent:\n");
773 write(fd, lines.string(), lines.size());
774
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700775 CameraMetadata lastRequest = getLatestRequestLocked();
Igor Murashkin1e479c02013-09-06 16:55:14 -0700776 lastRequest.dump(fd, /*verbosity*/2, /*indentation*/6);
777 }
778
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800779 if (dumpTemplates) {
Emilian Peevf4816702020-04-03 15:44:51 -0700780 const char *templateNames[CAMERA_TEMPLATE_COUNT] = {
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800781 "TEMPLATE_PREVIEW",
782 "TEMPLATE_STILL_CAPTURE",
783 "TEMPLATE_VIDEO_RECORD",
784 "TEMPLATE_VIDEO_SNAPSHOT",
785 "TEMPLATE_ZERO_SHUTTER_LAG",
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -0800786 "TEMPLATE_MANUAL",
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800787 };
788
Emilian Peevf4816702020-04-03 15:44:51 -0700789 for (int i = 1; i < CAMERA_TEMPLATE_COUNT; i++) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800790 camera_metadata_t *templateRequest = nullptr;
791 mInterface->constructDefaultRequestSettings(
Emilian Peevf4816702020-04-03 15:44:51 -0700792 (camera_request_template_t) i, &templateRequest);
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800793 lines = String8::format(" HAL Request %s:\n", templateNames[i-1]);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800794 if (templateRequest == nullptr) {
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800795 lines.append(" Not supported\n");
796 write(fd, lines.string(), lines.size());
797 } else {
798 write(fd, lines.string(), lines.size());
799 dump_indented_camera_metadata(templateRequest,
800 fd, /*verbosity*/2, /*indentation*/8);
801 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800802 free_camera_metadata(templateRequest);
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800803 }
804 }
805
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700806 mTagMonitor.dumpMonitoredMetadata(fd);
807
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800808 if (mInterface->valid()) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -0800809 lines = String8(" HAL device dump:\n");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800810 write(fd, lines.string(), lines.size());
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800811 mInterface->dump(fd);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800812 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800813
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700814 if (gotLock) mLock.unlock();
815 if (gotInterfaceLock) mInterfaceLock.unlock();
816
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800817 return OK;
818}
819
Emilian Peevfaa4bde2020-01-23 12:19:37 -0800820const CameraMetadata& Camera3Device::infoPhysical(const String8& physicalId) const {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800821 ALOGVV("%s: E", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800822 if (CC_UNLIKELY(mStatus == STATUS_UNINITIALIZED ||
823 mStatus == STATUS_ERROR)) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700824 ALOGW("%s: Access to static info %s!", __FUNCTION__,
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800825 mStatus == STATUS_ERROR ?
826 "when in error state" : "before init");
827 }
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700828 if (physicalId.isEmpty()) {
829 return mDeviceInfo;
830 } else {
831 std::string id(physicalId.c_str());
832 if (mPhysicalDeviceInfoMap.find(id) != mPhysicalDeviceInfoMap.end()) {
833 return mPhysicalDeviceInfoMap.at(id);
834 } else {
835 ALOGE("%s: Invalid physical camera id %s", __FUNCTION__, physicalId.c_str());
836 return mDeviceInfo;
837 }
838 }
839}
840
841const CameraMetadata& Camera3Device::info() const {
842 String8 emptyId;
Emilian Peevfaa4bde2020-01-23 12:19:37 -0800843 return infoPhysical(emptyId);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800844}
845
Jianing Wei90e59c92014-03-12 18:29:36 -0700846status_t Camera3Device::checkStatusOkToCaptureLocked() {
847 switch (mStatus) {
848 case STATUS_ERROR:
849 CLOGE("Device has encountered a serious error");
850 return INVALID_OPERATION;
851 case STATUS_UNINITIALIZED:
852 CLOGE("Device not initialized");
853 return INVALID_OPERATION;
854 case STATUS_UNCONFIGURED:
855 case STATUS_CONFIGURED:
856 case STATUS_ACTIVE:
857 // OK
858 break;
859 default:
860 SET_ERR_L("Unexpected status: %d", mStatus);
861 return INVALID_OPERATION;
862 }
863 return OK;
864}
865
866status_t Camera3Device::convertMetadataListToRequestListLocked(
Emilian Peevaebbe412018-01-15 13:53:24 +0000867 const List<const PhysicalCameraSettingsList> &metadataList,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700868 const std::list<const SurfaceMap> &surfaceMaps,
Shuzhen Wang316781a2020-08-18 18:11:01 -0700869 bool repeating, nsecs_t requestTimeNs,
Shuzhen Wang9d066012016-09-30 11:30:20 -0700870 RequestList *requestList) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700871 if (requestList == NULL) {
872 CLOGE("requestList cannot be NULL.");
873 return BAD_VALUE;
874 }
875
Jianing Weicb0652e2014-03-12 18:29:36 -0700876 int32_t burstId = 0;
Emilian Peevaebbe412018-01-15 13:53:24 +0000877 List<const PhysicalCameraSettingsList>::const_iterator metadataIt = metadataList.begin();
Shuzhen Wang0129d522016-10-30 22:43:41 -0700878 std::list<const SurfaceMap>::const_iterator surfaceMapIt = surfaceMaps.begin();
879 for (; metadataIt != metadataList.end() && surfaceMapIt != surfaceMaps.end();
880 ++metadataIt, ++surfaceMapIt) {
881 sp<CaptureRequest> newRequest = setUpRequestLocked(*metadataIt, *surfaceMapIt);
Jianing Wei90e59c92014-03-12 18:29:36 -0700882 if (newRequest == 0) {
883 CLOGE("Can't create capture request");
884 return BAD_VALUE;
885 }
Jianing Weicb0652e2014-03-12 18:29:36 -0700886
Shuzhen Wang9d066012016-09-30 11:30:20 -0700887 newRequest->mRepeating = repeating;
Shuzhen Wang316781a2020-08-18 18:11:01 -0700888 newRequest->mRequestTimeNs = requestTimeNs;
Shuzhen Wang9d066012016-09-30 11:30:20 -0700889
Jianing Weicb0652e2014-03-12 18:29:36 -0700890 // Setup burst Id and request Id
891 newRequest->mResultExtras.burstId = burstId++;
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -0800892 auto requestIdEntry = metadataIt->begin()->metadata.find(ANDROID_REQUEST_ID);
893 if (requestIdEntry.count == 0) {
Jianing Weicb0652e2014-03-12 18:29:36 -0700894 CLOGE("RequestID does not exist in metadata");
895 return BAD_VALUE;
896 }
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -0800897 newRequest->mResultExtras.requestId = requestIdEntry.data.i32[0];
Jianing Weicb0652e2014-03-12 18:29:36 -0700898
Jianing Wei90e59c92014-03-12 18:29:36 -0700899 requestList->push_back(newRequest);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700900
901 ALOGV("%s: requestId = %" PRId32, __FUNCTION__, newRequest->mResultExtras.requestId);
Jianing Wei90e59c92014-03-12 18:29:36 -0700902 }
Shuzhen Wang0129d522016-10-30 22:43:41 -0700903 if (metadataIt != metadataList.end() || surfaceMapIt != surfaceMaps.end()) {
904 ALOGE("%s: metadataList and surfaceMaps are not the same size!", __FUNCTION__);
905 return BAD_VALUE;
906 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -0700907
908 // Setup batch size if this is a high speed video recording request.
909 if (mIsConstrainedHighSpeedConfiguration && requestList->size() > 0) {
910 auto firstRequest = requestList->begin();
911 for (auto& outputStream : (*firstRequest)->mOutputStreams) {
912 if (outputStream->isVideoStream()) {
913 (*firstRequest)->mBatchSize = requestList->size();
Yin-Chia Yeh14ef48d2020-02-10 15:06:37 -0800914 outputStream->setBatchSize(requestList->size());
Chien-Yu Chen85a64552015-08-28 15:46:12 -0700915 break;
916 }
917 }
918 }
919
Jianing Wei90e59c92014-03-12 18:29:36 -0700920 return OK;
921}
922
Yin-Chia Yeh7e5a2042019-02-06 16:01:06 -0800923status_t Camera3Device::capture(CameraMetadata &request, int64_t* lastFrameNumber) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800924 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800925
Emilian Peevaebbe412018-01-15 13:53:24 +0000926 List<const PhysicalCameraSettingsList> requestsList;
Shuzhen Wang0129d522016-10-30 22:43:41 -0700927 std::list<const SurfaceMap> surfaceMaps;
Emilian Peevaebbe412018-01-15 13:53:24 +0000928 convertToRequestList(requestsList, surfaceMaps, request);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700929
Yin-Chia Yeh7e5a2042019-02-06 16:01:06 -0800930 return captureList(requestsList, surfaceMaps, lastFrameNumber);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700931}
932
Emilian Peevaebbe412018-01-15 13:53:24 +0000933void Camera3Device::convertToRequestList(List<const PhysicalCameraSettingsList>& requestsList,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700934 std::list<const SurfaceMap>& surfaceMaps,
935 const CameraMetadata& request) {
Emilian Peevaebbe412018-01-15 13:53:24 +0000936 PhysicalCameraSettingsList requestList;
937 requestList.push_back({std::string(getId().string()), request});
938 requestsList.push_back(requestList);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700939
940 SurfaceMap surfaceMap;
941 camera_metadata_ro_entry streams = request.find(ANDROID_REQUEST_OUTPUT_STREAMS);
942 // With no surface list passed in, stream and surface will have 1-to-1
943 // mapping. So the surface index is 0 for each stream in the surfaceMap.
944 for (size_t i = 0; i < streams.count; i++) {
945 surfaceMap[streams.data.i32[i]].push_back(0);
946 }
947 surfaceMaps.push_back(surfaceMap);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800948}
949
Jianing Wei90e59c92014-03-12 18:29:36 -0700950status_t Camera3Device::submitRequestsHelper(
Emilian Peevaebbe412018-01-15 13:53:24 +0000951 const List<const PhysicalCameraSettingsList> &requests,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700952 const std::list<const SurfaceMap> &surfaceMaps,
953 bool repeating,
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700954 /*out*/
955 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700956 ATRACE_CALL();
Shuzhen Wang316781a2020-08-18 18:11:01 -0700957 nsecs_t requestTimeNs = systemTime();
958
Jianing Wei90e59c92014-03-12 18:29:36 -0700959 Mutex::Autolock il(mInterfaceLock);
960 Mutex::Autolock l(mLock);
961
962 status_t res = checkStatusOkToCaptureLocked();
963 if (res != OK) {
964 // error logged by previous call
965 return res;
966 }
967
968 RequestList requestList;
969
Shuzhen Wang0129d522016-10-30 22:43:41 -0700970 res = convertMetadataListToRequestListLocked(requests, surfaceMaps,
Shuzhen Wang316781a2020-08-18 18:11:01 -0700971 repeating, requestTimeNs, /*out*/&requestList);
Jianing Wei90e59c92014-03-12 18:29:36 -0700972 if (res != OK) {
973 // error logged by previous call
974 return res;
975 }
976
977 if (repeating) {
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700978 res = mRequestThread->setRepeatingRequests(requestList, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -0700979 } else {
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700980 res = mRequestThread->queueRequestList(requestList, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -0700981 }
982
983 if (res == OK) {
984 waitUntilStateThenRelock(/*active*/true, kActiveTimeout);
985 if (res != OK) {
986 SET_ERR_L("Can't transition to active in %f seconds!",
987 kActiveTimeout/1e9);
988 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800989 ALOGV("Camera %s: Capture request %" PRId32 " enqueued", mId.string(),
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700990 (*(requestList.begin()))->mResultExtras.requestId);
Jianing Wei90e59c92014-03-12 18:29:36 -0700991 } else {
992 CLOGE("Cannot queue request. Impossible.");
993 return BAD_VALUE;
994 }
995
996 return res;
997}
998
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -0700999hardware::Return<void> Camera3Device::requestStreamBuffers(
1000 const hardware::hidl_vec<hardware::camera::device::V3_5::BufferRequest>& bufReqs,
1001 requestStreamBuffers_cb _hidl_cb) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001002 RequestBufferStates states {
Shuzhen Wang316781a2020-08-18 18:11:01 -07001003 mId, mRequestBufferInterfaceLock, mUseHalBufManager, mOutputStreams, mSessionStatsBuilder,
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001004 *this, *mInterface, *this};
1005 camera3::requestStreamBuffers(states, bufReqs, _hidl_cb);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001006 return hardware::Void();
1007}
1008
1009hardware::Return<void> Camera3Device::returnStreamBuffers(
1010 const hardware::hidl_vec<hardware::camera::device::V3_2::StreamBuffer>& buffers) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001011 ReturnBufferStates states {
Shuzhen Wang316781a2020-08-18 18:11:01 -07001012 mId, mUseHalBufManager, mOutputStreams, mSessionStatsBuilder, *mInterface};
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001013 camera3::returnStreamBuffers(states, buffers);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001014 return hardware::Void();
1015}
1016
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001017hardware::Return<void> Camera3Device::processCaptureResult_3_4(
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001018 const hardware::hidl_vec<
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001019 hardware::camera::device::V3_4::CaptureResult>& results) {
Yin-Chia Yeh657c1872017-07-18 18:09:57 -07001020 // Ideally we should grab mLock, but that can lead to deadlock, and
1021 // it's not super important to get up to date value of mStatus for this
1022 // warning print, hence skipping the lock here
1023 if (mStatus == STATUS_ERROR) {
1024 // Per API contract, HAL should act as closed after device error
1025 // But mStatus can be set to error by framework as well, so just log
1026 // a warning here.
1027 ALOGW("%s: received capture result in error state.", __FUNCTION__);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07001028 }
Yifan Honga640c5a2017-04-12 16:30:31 -07001029
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001030 sp<NotificationListener> listener;
1031 {
1032 std::lock_guard<std::mutex> l(mOutputLock);
1033 listener = mListener.promote();
1034 }
1035
Yifan Honga640c5a2017-04-12 16:30:31 -07001036 if (mProcessCaptureResultLock.tryLock() != OK) {
1037 // This should never happen; it indicates a wrong client implementation
1038 // that doesn't follow the contract. But, we can be tolerant here.
1039 ALOGE("%s: callback overlapped! waiting 1s...",
1040 __FUNCTION__);
1041 if (mProcessCaptureResultLock.timedLock(1000000000 /* 1s */) != OK) {
1042 ALOGE("%s: cannot acquire lock in 1s, dropping results",
1043 __FUNCTION__);
1044 // really don't know what to do, so bail out.
1045 return hardware::Void();
1046 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001047 }
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001048 CaptureOutputStates states {
1049 mId,
Shuzhen Wangb7b42652020-05-07 11:59:02 -07001050 mInFlightLock, mLastCompletedRegularFrameNumber,
1051 mLastCompletedReprocessFrameNumber, mLastCompletedZslFrameNumber,
1052 mInFlightMap, mOutputLock, mResultQueue, mResultSignal,
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001053 mNextShutterFrameNumber,
1054 mNextReprocessShutterFrameNumber, mNextZslStillShutterFrameNumber,
1055 mNextResultFrameNumber,
1056 mNextReprocessResultFrameNumber, mNextZslStillResultFrameNumber,
1057 mUseHalBufManager, mUsePartialResult, mNeedFixupMonochromeTags,
1058 mNumPartialResults, mVendorTagId, mDeviceInfo, mPhysicalDeviceInfoMap,
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08001059 mResultMetadataQueue, mDistortionMappers, mZoomRatioMappers, mRotateAndCropMappers,
Shuzhen Wang316781a2020-08-18 18:11:01 -07001060 mTagMonitor, mInputStream, mOutputStreams, mSessionStatsBuilder, listener, *this, *this,
1061 *mInterface
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001062 };
1063
Yifan Honga640c5a2017-04-12 16:30:31 -07001064 for (const auto& result : results) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001065 processOneCaptureResultLocked(states, result.v3_2, result.physicalCameraMetadata);
Yifan Honga640c5a2017-04-12 16:30:31 -07001066 }
1067 mProcessCaptureResultLock.unlock();
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001068 return hardware::Void();
1069}
1070
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001071// Only one processCaptureResult should be called at a time, so
1072// the locks won't block. The locks are present here simply to enforce this.
1073hardware::Return<void> Camera3Device::processCaptureResult(
1074 const hardware::hidl_vec<
1075 hardware::camera::device::V3_2::CaptureResult>& results) {
1076 hardware::hidl_vec<hardware::camera::device::V3_4::PhysicalCameraMetadata> noPhysMetadata;
1077
1078 // Ideally we should grab mLock, but that can lead to deadlock, and
1079 // it's not super important to get up to date value of mStatus for this
1080 // warning print, hence skipping the lock here
1081 if (mStatus == STATUS_ERROR) {
1082 // Per API contract, HAL should act as closed after device error
1083 // But mStatus can be set to error by framework as well, so just log
1084 // a warning here.
1085 ALOGW("%s: received capture result in error state.", __FUNCTION__);
1086 }
1087
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001088 sp<NotificationListener> listener;
1089 {
1090 std::lock_guard<std::mutex> l(mOutputLock);
1091 listener = mListener.promote();
1092 }
1093
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001094 if (mProcessCaptureResultLock.tryLock() != OK) {
1095 // This should never happen; it indicates a wrong client implementation
1096 // that doesn't follow the contract. But, we can be tolerant here.
1097 ALOGE("%s: callback overlapped! waiting 1s...",
1098 __FUNCTION__);
1099 if (mProcessCaptureResultLock.timedLock(1000000000 /* 1s */) != OK) {
1100 ALOGE("%s: cannot acquire lock in 1s, dropping results",
1101 __FUNCTION__);
1102 // really don't know what to do, so bail out.
1103 return hardware::Void();
1104 }
1105 }
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001106
1107 CaptureOutputStates states {
1108 mId,
Shuzhen Wangb7b42652020-05-07 11:59:02 -07001109 mInFlightLock, mLastCompletedRegularFrameNumber,
1110 mLastCompletedReprocessFrameNumber, mLastCompletedZslFrameNumber,
1111 mInFlightMap, mOutputLock, mResultQueue, mResultSignal,
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001112 mNextShutterFrameNumber,
1113 mNextReprocessShutterFrameNumber, mNextZslStillShutterFrameNumber,
1114 mNextResultFrameNumber,
1115 mNextReprocessResultFrameNumber, mNextZslStillResultFrameNumber,
1116 mUseHalBufManager, mUsePartialResult, mNeedFixupMonochromeTags,
1117 mNumPartialResults, mVendorTagId, mDeviceInfo, mPhysicalDeviceInfoMap,
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08001118 mResultMetadataQueue, mDistortionMappers, mZoomRatioMappers, mRotateAndCropMappers,
Shuzhen Wang316781a2020-08-18 18:11:01 -07001119 mTagMonitor, mInputStream, mOutputStreams, mSessionStatsBuilder, listener, *this, *this,
1120 *mInterface
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001121 };
1122
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001123 for (const auto& result : results) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001124 processOneCaptureResultLocked(states, result, noPhysMetadata);
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001125 }
1126 mProcessCaptureResultLock.unlock();
1127 return hardware::Void();
1128}
1129
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001130hardware::Return<void> Camera3Device::notify(
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001131 const hardware::hidl_vec<hardware::camera::device::V3_2::NotifyMsg>& msgs) {
Yin-Chia Yeh657c1872017-07-18 18:09:57 -07001132 // Ideally we should grab mLock, but that can lead to deadlock, and
1133 // it's not super important to get up to date value of mStatus for this
1134 // warning print, hence skipping the lock here
1135 if (mStatus == STATUS_ERROR) {
1136 // Per API contract, HAL should act as closed after device error
1137 // But mStatus can be set to error by framework as well, so just log
1138 // a warning here.
1139 ALOGW("%s: received notify message in error state.", __FUNCTION__);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07001140 }
Yin-Chia Yeh657c1872017-07-18 18:09:57 -07001141
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001142 sp<NotificationListener> listener;
1143 {
1144 std::lock_guard<std::mutex> l(mOutputLock);
1145 listener = mListener.promote();
1146 }
1147
1148 CaptureOutputStates states {
1149 mId,
Shuzhen Wangb7b42652020-05-07 11:59:02 -07001150 mInFlightLock, mLastCompletedRegularFrameNumber,
1151 mLastCompletedReprocessFrameNumber, mLastCompletedZslFrameNumber,
1152 mInFlightMap, mOutputLock, mResultQueue, mResultSignal,
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001153 mNextShutterFrameNumber,
1154 mNextReprocessShutterFrameNumber, mNextZslStillShutterFrameNumber,
1155 mNextResultFrameNumber,
1156 mNextReprocessResultFrameNumber, mNextZslStillResultFrameNumber,
1157 mUseHalBufManager, mUsePartialResult, mNeedFixupMonochromeTags,
1158 mNumPartialResults, mVendorTagId, mDeviceInfo, mPhysicalDeviceInfoMap,
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08001159 mResultMetadataQueue, mDistortionMappers, mZoomRatioMappers, mRotateAndCropMappers,
Shuzhen Wang316781a2020-08-18 18:11:01 -07001160 mTagMonitor, mInputStream, mOutputStreams, mSessionStatsBuilder, listener, *this, *this,
1161 *mInterface
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001162 };
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001163 for (const auto& msg : msgs) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001164 camera3::notify(states, msg);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001165 }
1166 return hardware::Void();
1167}
1168
Emilian Peevaebbe412018-01-15 13:53:24 +00001169status_t Camera3Device::captureList(const List<const PhysicalCameraSettingsList> &requestsList,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001170 const std::list<const SurfaceMap> &surfaceMaps,
Jianing Weicb0652e2014-03-12 18:29:36 -07001171 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -07001172 ATRACE_CALL();
1173
Emilian Peevaebbe412018-01-15 13:53:24 +00001174 return submitRequestsHelper(requestsList, surfaceMaps, /*repeating*/false, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -07001175}
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001176
Jianing Weicb0652e2014-03-12 18:29:36 -07001177status_t Camera3Device::setStreamingRequest(const CameraMetadata &request,
1178 int64_t* /*lastFrameNumber*/) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001179 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001180
Emilian Peevaebbe412018-01-15 13:53:24 +00001181 List<const PhysicalCameraSettingsList> requestsList;
Shuzhen Wang0129d522016-10-30 22:43:41 -07001182 std::list<const SurfaceMap> surfaceMaps;
Emilian Peevaebbe412018-01-15 13:53:24 +00001183 convertToRequestList(requestsList, surfaceMaps, request);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001184
Emilian Peevaebbe412018-01-15 13:53:24 +00001185 return setStreamingRequestList(requestsList, /*surfaceMap*/surfaceMaps,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001186 /*lastFrameNumber*/NULL);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001187}
1188
Emilian Peevaebbe412018-01-15 13:53:24 +00001189status_t Camera3Device::setStreamingRequestList(
1190 const List<const PhysicalCameraSettingsList> &requestsList,
1191 const std::list<const SurfaceMap> &surfaceMaps, int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -07001192 ATRACE_CALL();
1193
Emilian Peevaebbe412018-01-15 13:53:24 +00001194 return submitRequestsHelper(requestsList, surfaceMaps, /*repeating*/true, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -07001195}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001196
1197sp<Camera3Device::CaptureRequest> Camera3Device::setUpRequestLocked(
Emilian Peevaebbe412018-01-15 13:53:24 +00001198 const PhysicalCameraSettingsList &request, const SurfaceMap &surfaceMap) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001199 status_t res;
1200
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001201 if (mStatus == STATUS_UNCONFIGURED || mNeedConfig) {
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08001202 // This point should only be reached via API1 (API2 must explicitly call configureStreams)
1203 // so unilaterally select normal operating mode.
Emilian Peevaebbe412018-01-15 13:53:24 +00001204 res = filterParamsAndConfigureLocked(request.begin()->metadata,
Emilian Peevf4816702020-04-03 15:44:51 -07001205 CAMERA_STREAM_CONFIGURATION_NORMAL_MODE);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001206 // Stream configuration failed. Client might try other configuraitons.
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001207 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001208 CLOGE("Can't set up streams: %s (%d)", strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001209 return NULL;
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001210 } else if (mStatus == STATUS_UNCONFIGURED) {
1211 // Stream configuration successfully configure to empty stream configuration.
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001212 CLOGE("No streams configured");
1213 return NULL;
1214 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001215 }
1216
Shuzhen Wang0129d522016-10-30 22:43:41 -07001217 sp<CaptureRequest> newRequest = createCaptureRequest(request, surfaceMap);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001218 return newRequest;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001219}
1220
Jianing Weicb0652e2014-03-12 18:29:36 -07001221status_t Camera3Device::clearStreamingRequest(int64_t *lastFrameNumber) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001222 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001223 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001224 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001225
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001226 switch (mStatus) {
1227 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001228 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001229 return INVALID_OPERATION;
1230 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001231 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001232 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001233 case STATUS_UNCONFIGURED:
1234 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001235 case STATUS_ACTIVE:
1236 // OK
1237 break;
1238 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001239 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001240 return INVALID_OPERATION;
1241 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001242 ALOGV("Camera %s: Clearing repeating request", mId.string());
Jianing Weicb0652e2014-03-12 18:29:36 -07001243
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07001244 return mRequestThread->clearRepeatingRequests(lastFrameNumber);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001245}
1246
1247status_t Camera3Device::waitUntilRequestReceived(int32_t requestId, nsecs_t timeout) {
1248 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001249 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001250
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001251 return mRequestThread->waitUntilRequestProcessed(requestId, timeout);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001252}
1253
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001254status_t Camera3Device::createInputStream(
1255 uint32_t width, uint32_t height, int format, int *id) {
1256 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001257 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001258 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001259 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001260 ALOGV("Camera %s: Creating new input stream %d: %d x %d, format %d",
1261 mId.string(), mNextStreamId, width, height, format);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001262
1263 status_t res;
1264 bool wasActive = false;
1265
1266 switch (mStatus) {
1267 case STATUS_ERROR:
1268 ALOGE("%s: Device has encountered a serious error", __FUNCTION__);
1269 return INVALID_OPERATION;
1270 case STATUS_UNINITIALIZED:
1271 ALOGE("%s: Device not initialized", __FUNCTION__);
1272 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001273 case STATUS_UNCONFIGURED:
1274 case STATUS_CONFIGURED:
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001275 // OK
1276 break;
1277 case STATUS_ACTIVE:
1278 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001279 res = internalPauseAndWaitLocked(maxExpectedDuration);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001280 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001281 SET_ERR_L("Can't pause captures to reconfigure streams!");
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001282 return res;
1283 }
1284 wasActive = true;
1285 break;
1286 default:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001287 SET_ERR_L("%s: Unexpected status: %d", mStatus);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001288 return INVALID_OPERATION;
1289 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001290 assert(mStatus != STATUS_ACTIVE);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001291
1292 if (mInputStream != 0) {
1293 ALOGE("%s: Cannot create more than 1 input stream", __FUNCTION__);
1294 return INVALID_OPERATION;
1295 }
1296
1297 sp<Camera3InputStream> newStream = new Camera3InputStream(mNextStreamId,
1298 width, height, format);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001299 newStream->setStatusTracker(mStatusTracker);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001300
1301 mInputStream = newStream;
1302
1303 *id = mNextStreamId++;
1304
1305 // Continue captures if active at start
1306 if (wasActive) {
1307 ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001308 // Reuse current operating mode and session parameters for new stream config
1309 res = configureStreamsLocked(mOperatingMode, mSessionParams);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001310 if (res != OK) {
1311 ALOGE("%s: Can't reconfigure device for new stream %d: %s (%d)",
1312 __FUNCTION__, mNextStreamId, strerror(-res), res);
1313 return res;
1314 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001315 internalResumeLocked();
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001316 }
1317
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001318 ALOGV("Camera %s: Created input stream", mId.string());
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001319 return OK;
1320}
1321
Eino-Ville Talvala727d1722015-06-09 13:44:19 -07001322status_t Camera3Device::createStream(sp<Surface> consumer,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001323 uint32_t width, uint32_t height, int format,
Emilian Peevf4816702020-04-03 15:44:51 -07001324 android_dataspace dataSpace, camera_stream_rotation_t rotation, int *id,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001325 const String8& physicalCameraId,
Emilian Peev40ead602017-09-26 15:46:36 +01001326 std::vector<int> *surfaceIds, int streamSetId, bool isShared, uint64_t consumerUsage) {
Shuzhen Wang0129d522016-10-30 22:43:41 -07001327 ATRACE_CALL();
1328
1329 if (consumer == nullptr) {
1330 ALOGE("%s: consumer must not be null", __FUNCTION__);
1331 return BAD_VALUE;
1332 }
1333
1334 std::vector<sp<Surface>> consumers;
1335 consumers.push_back(consumer);
1336
1337 return createStream(consumers, /*hasDeferredConsumer*/ false, width, height,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001338 format, dataSpace, rotation, id, physicalCameraId, surfaceIds, streamSetId,
1339 isShared, consumerUsage);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001340}
1341
1342status_t Camera3Device::createStream(const std::vector<sp<Surface>>& consumers,
1343 bool hasDeferredConsumer, uint32_t width, uint32_t height, int format,
Emilian Peevf4816702020-04-03 15:44:51 -07001344 android_dataspace dataSpace, camera_stream_rotation_t rotation, int *id,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001345 const String8& physicalCameraId,
Emilian Peev40ead602017-09-26 15:46:36 +01001346 std::vector<int> *surfaceIds, int streamSetId, bool isShared, uint64_t consumerUsage) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001347 ATRACE_CALL();
Emilian Peev40ead602017-09-26 15:46:36 +01001348
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001349 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001350 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001351 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001352 ALOGV("Camera %s: Creating new stream %d: %d x %d, format %d, dataspace %d rotation %d"
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001353 " consumer usage %" PRIu64 ", isShared %d, physicalCameraId %s", mId.string(),
1354 mNextStreamId, width, height, format, dataSpace, rotation, consumerUsage, isShared,
1355 physicalCameraId.string());
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001356
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001357 status_t res;
1358 bool wasActive = false;
1359
1360 switch (mStatus) {
1361 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001362 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001363 return INVALID_OPERATION;
1364 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001365 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001366 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001367 case STATUS_UNCONFIGURED:
1368 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001369 // OK
1370 break;
1371 case STATUS_ACTIVE:
1372 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001373 res = internalPauseAndWaitLocked(maxExpectedDuration);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001374 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001375 SET_ERR_L("Can't pause captures to reconfigure streams!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001376 return res;
1377 }
1378 wasActive = true;
1379 break;
1380 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001381 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001382 return INVALID_OPERATION;
1383 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001384 assert(mStatus != STATUS_ACTIVE);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001385
1386 sp<Camera3OutputStream> newStream;
Zhijun He5d677d12016-05-29 16:52:39 -07001387
Shuzhen Wang0129d522016-10-30 22:43:41 -07001388 if (consumers.size() == 0 && !hasDeferredConsumer) {
1389 ALOGE("%s: Number of consumers cannot be smaller than 1", __FUNCTION__);
1390 return BAD_VALUE;
1391 }
Zhijun He5d677d12016-05-29 16:52:39 -07001392
Shuzhen Wang0129d522016-10-30 22:43:41 -07001393 if (hasDeferredConsumer && format != HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
Zhijun He5d677d12016-05-29 16:52:39 -07001394 ALOGE("Deferred consumer stream creation only support IMPLEMENTATION_DEFINED format");
1395 return BAD_VALUE;
1396 }
1397
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001398 if (format == HAL_PIXEL_FORMAT_BLOB) {
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -07001399 ssize_t blobBufferSize;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001400 if (dataSpace == HAL_DATASPACE_DEPTH) {
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -07001401 blobBufferSize = getPointCloudBufferSize();
1402 if (blobBufferSize <= 0) {
1403 SET_ERR_L("Invalid point cloud buffer size %zd", blobBufferSize);
1404 return BAD_VALUE;
1405 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001406 } else if (dataSpace == static_cast<android_dataspace>(HAL_DATASPACE_JPEG_APP_SEGMENTS)) {
1407 blobBufferSize = width * height;
1408 } else {
1409 blobBufferSize = getJpegBufferSize(width, height);
1410 if (blobBufferSize <= 0) {
1411 SET_ERR_L("Invalid jpeg buffer size %zd", blobBufferSize);
1412 return BAD_VALUE;
1413 }
Zhijun Hef7da0962014-04-24 13:27:56 -07001414 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001415 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001416 width, height, blobBufferSize, format, dataSpace, rotation,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001417 mTimestampOffset, physicalCameraId, streamSetId);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -08001418 } else if (format == HAL_PIXEL_FORMAT_RAW_OPAQUE) {
1419 ssize_t rawOpaqueBufferSize = getRawOpaqueBufferSize(width, height);
1420 if (rawOpaqueBufferSize <= 0) {
1421 SET_ERR_L("Invalid RAW opaque buffer size %zd", rawOpaqueBufferSize);
1422 return BAD_VALUE;
1423 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001424 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001425 width, height, rawOpaqueBufferSize, format, dataSpace, rotation,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001426 mTimestampOffset, physicalCameraId, streamSetId);
Shuzhen Wang758c2152017-01-10 18:26:18 -08001427 } else if (isShared) {
1428 newStream = new Camera3SharedOutputStream(mNextStreamId, consumers,
1429 width, height, format, consumerUsage, dataSpace, rotation,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07001430 mTimestampOffset, physicalCameraId, streamSetId,
1431 mUseHalBufManager);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001432 } else if (consumers.size() == 0 && hasDeferredConsumer) {
Zhijun He5d677d12016-05-29 16:52:39 -07001433 newStream = new Camera3OutputStream(mNextStreamId,
1434 width, height, format, consumerUsage, dataSpace, rotation,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001435 mTimestampOffset, physicalCameraId, streamSetId);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001436 } else {
Shuzhen Wang0129d522016-10-30 22:43:41 -07001437 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001438 width, height, format, dataSpace, rotation,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001439 mTimestampOffset, physicalCameraId, streamSetId);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001440 }
Emilian Peev40ead602017-09-26 15:46:36 +01001441
1442 size_t consumerCount = consumers.size();
1443 for (size_t i = 0; i < consumerCount; i++) {
1444 int id = newStream->getSurfaceId(consumers[i]);
1445 if (id < 0) {
1446 SET_ERR_L("Invalid surface id");
1447 return BAD_VALUE;
1448 }
1449 if (surfaceIds != nullptr) {
1450 surfaceIds->push_back(id);
1451 }
1452 }
1453
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001454 newStream->setStatusTracker(mStatusTracker);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001455
Emilian Peev08dd2452017-04-06 16:55:14 +01001456 newStream->setBufferManager(mBufferManager);
Zhijun He125684a2015-12-26 15:07:30 -08001457
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08001458 newStream->setImageDumpMask(mImageDumpMask);
1459
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001460 res = mOutputStreams.add(mNextStreamId, newStream);
1461 if (res < 0) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001462 SET_ERR_L("Can't add new stream to set: %s (%d)", strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001463 return res;
1464 }
1465
Shuzhen Wang316781a2020-08-18 18:11:01 -07001466 mSessionStatsBuilder.addStream(mNextStreamId);
1467
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001468 *id = mNextStreamId++;
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07001469 mNeedConfig = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001470
1471 // Continue captures if active at start
1472 if (wasActive) {
1473 ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001474 // Reuse current operating mode and session parameters for new stream config
1475 res = configureStreamsLocked(mOperatingMode, mSessionParams);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001476 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001477 CLOGE("Can't reconfigure device for new stream %d: %s (%d)",
1478 mNextStreamId, strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001479 return res;
1480 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001481 internalResumeLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001482 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001483 ALOGV("Camera %s: Created new stream", mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001484 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001485}
1486
Emilian Peev710c1422017-08-30 11:19:38 +01001487status_t Camera3Device::getStreamInfo(int id, StreamInfo *streamInfo) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001488 ATRACE_CALL();
Emilian Peev710c1422017-08-30 11:19:38 +01001489 if (nullptr == streamInfo) {
1490 return BAD_VALUE;
1491 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001492 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001493 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001494
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001495 switch (mStatus) {
1496 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001497 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001498 return INVALID_OPERATION;
1499 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001500 CLOGE("Device not initialized!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001501 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001502 case STATUS_UNCONFIGURED:
1503 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001504 case STATUS_ACTIVE:
1505 // OK
1506 break;
1507 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001508 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001509 return INVALID_OPERATION;
1510 }
1511
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001512 sp<Camera3StreamInterface> stream = mOutputStreams.get(id);
1513 if (stream == nullptr) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001514 CLOGE("Stream %d is unknown", id);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001515 return BAD_VALUE;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001516 }
1517
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001518 streamInfo->width = stream->getWidth();
1519 streamInfo->height = stream->getHeight();
1520 streamInfo->format = stream->getFormat();
1521 streamInfo->dataSpace = stream->getDataSpace();
1522 streamInfo->formatOverridden = stream->isFormatOverridden();
1523 streamInfo->originalFormat = stream->getOriginalFormat();
1524 streamInfo->dataSpaceOverridden = stream->isDataSpaceOverridden();
1525 streamInfo->originalDataSpace = stream->getOriginalDataSpace();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001526 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001527}
1528
1529status_t Camera3Device::setStreamTransform(int id,
1530 int transform) {
1531 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001532 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001533 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001534
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001535 switch (mStatus) {
1536 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001537 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001538 return INVALID_OPERATION;
1539 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001540 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001541 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001542 case STATUS_UNCONFIGURED:
1543 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001544 case STATUS_ACTIVE:
1545 // OK
1546 break;
1547 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001548 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001549 return INVALID_OPERATION;
1550 }
1551
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001552 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(id);
1553 if (stream == nullptr) {
1554 CLOGE("Stream %d does not exist", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001555 return BAD_VALUE;
1556 }
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001557 return stream->setTransform(transform);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001558}
1559
1560status_t Camera3Device::deleteStream(int id) {
1561 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001562 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001563 Mutex::Autolock l(mLock);
1564 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001565
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001566 ALOGV("%s: Camera %s: Deleting stream %d", __FUNCTION__, mId.string(), id);
Igor Murashkine2172be2013-05-28 15:31:39 -07001567
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001568 // CameraDevice semantics require device to already be idle before
1569 // deleteStream is called, unlike for createStream.
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001570 if (mStatus == STATUS_ACTIVE) {
Yin-Chia Yeh693047d2018-03-08 12:14:19 -08001571 ALOGW("%s: Camera %s: Device not idle", __FUNCTION__, mId.string());
Igor Murashkin52827132013-05-13 14:53:44 -07001572 return -EBUSY;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001573 }
1574
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07001575 if (mStatus == STATUS_ERROR) {
1576 ALOGW("%s: Camera %s: deleteStream not allowed in ERROR state",
1577 __FUNCTION__, mId.string());
1578 return -EBUSY;
1579 }
1580
Igor Murashkin2fba5842013-04-22 14:03:54 -07001581 sp<Camera3StreamInterface> deletedStream;
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001582 sp<Camera3StreamInterface> stream = mOutputStreams.get(id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001583 if (mInputStream != NULL && id == mInputStream->getId()) {
1584 deletedStream = mInputStream;
1585 mInputStream.clear();
1586 } else {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001587 if (stream == nullptr) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001588 CLOGE("Stream %d does not exist", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001589 return BAD_VALUE;
1590 }
Shuzhen Wang316781a2020-08-18 18:11:01 -07001591 mSessionStatsBuilder.removeStream(id);
Zhijun He5f446352014-01-22 09:49:33 -08001592 }
1593
1594 // Delete output stream or the output part of a bi-directional stream.
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001595 if (stream != nullptr) {
1596 deletedStream = stream;
1597 mOutputStreams.remove(id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001598 }
1599
1600 // Free up the stream endpoint so that it can be used by some other stream
1601 res = deletedStream->disconnect();
1602 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001603 SET_ERR_L("Can't disconnect deleted stream %d", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001604 // fall through since we want to still list the stream as deleted.
1605 }
1606 mDeletedStreams.add(deletedStream);
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07001607 mNeedConfig = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001608
1609 return res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001610}
1611
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001612status_t Camera3Device::configureStreams(const CameraMetadata& sessionParams, int operatingMode) {
Igor Murashkine2d167e2014-08-19 16:19:59 -07001613 ATRACE_CALL();
1614 ALOGV("%s: E", __FUNCTION__);
1615
1616 Mutex::Autolock il(mInterfaceLock);
1617 Mutex::Autolock l(mLock);
Chien-Yu Chen17338fc2015-06-18 16:30:12 -07001618
Emilian Peev811d2952018-05-25 11:08:40 +01001619 // In case the client doesn't include any session parameter, try a
1620 // speculative configuration using the values from the last cached
1621 // default request.
1622 if (sessionParams.isEmpty() &&
Emilian Peevf4816702020-04-03 15:44:51 -07001623 ((mLastTemplateId > 0) && (mLastTemplateId < CAMERA_TEMPLATE_COUNT)) &&
Emilian Peev811d2952018-05-25 11:08:40 +01001624 (!mRequestTemplateCache[mLastTemplateId].isEmpty())) {
1625 ALOGV("%s: Speculative session param configuration with template id: %d", __func__,
1626 mLastTemplateId);
1627 return filterParamsAndConfigureLocked(mRequestTemplateCache[mLastTemplateId],
1628 operatingMode);
1629 }
1630
Emilian Peevac3ce6c2017-12-12 15:27:02 +00001631 return filterParamsAndConfigureLocked(sessionParams, operatingMode);
1632}
1633
1634status_t Camera3Device::filterParamsAndConfigureLocked(const CameraMetadata& sessionParams,
1635 int operatingMode) {
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001636 //Filter out any incoming session parameters
1637 const CameraMetadata params(sessionParams);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001638 camera_metadata_entry_t availableSessionKeys = mDeviceInfo.find(
1639 ANDROID_REQUEST_AVAILABLE_SESSION_KEYS);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00001640 CameraMetadata filteredParams(availableSessionKeys.count);
1641 camera_metadata_t *meta = const_cast<camera_metadata_t *>(
1642 filteredParams.getAndLock());
1643 set_camera_metadata_vendor_id(meta, mVendorTagId);
1644 filteredParams.unlock(meta);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001645 if (availableSessionKeys.count > 0) {
1646 for (size_t i = 0; i < availableSessionKeys.count; i++) {
1647 camera_metadata_ro_entry entry = params.find(
1648 availableSessionKeys.data.i32[i]);
1649 if (entry.count > 0) {
1650 filteredParams.update(entry);
1651 }
1652 }
1653 }
1654
1655 return configureStreamsLocked(operatingMode, filteredParams);
Igor Murashkine2d167e2014-08-19 16:19:59 -07001656}
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001657
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07001658status_t Camera3Device::getInputBufferProducer(
1659 sp<IGraphicBufferProducer> *producer) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07001660 ATRACE_CALL();
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07001661 Mutex::Autolock il(mInterfaceLock);
1662 Mutex::Autolock l(mLock);
1663
1664 if (producer == NULL) {
1665 return BAD_VALUE;
1666 } else if (mInputStream == NULL) {
1667 return INVALID_OPERATION;
1668 }
1669
1670 return mInputStream->getInputBufferProducer(producer);
1671}
1672
Emilian Peevf4816702020-04-03 15:44:51 -07001673status_t Camera3Device::createDefaultRequest(camera_request_template_t templateId,
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001674 CameraMetadata *request) {
1675 ATRACE_CALL();
Alex Rayfe7e0c62013-05-30 00:12:13 -07001676 ALOGV("%s: for template %d", __FUNCTION__, templateId);
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08001677
Emilian Peevf4816702020-04-03 15:44:51 -07001678 if (templateId <= 0 || templateId >= CAMERA_TEMPLATE_COUNT) {
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08001679 android_errorWriteWithInfoLog(CameraService::SN_EVENT_LOG_ID, "26866110",
Jayant Chowdhary12361932018-08-27 14:46:13 -07001680 CameraThreadState::getCallingUid(), nullptr, 0);
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08001681 return BAD_VALUE;
1682 }
1683
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001684 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001685
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001686 {
1687 Mutex::Autolock l(mLock);
1688 switch (mStatus) {
1689 case STATUS_ERROR:
1690 CLOGE("Device has encountered a serious error");
1691 return INVALID_OPERATION;
1692 case STATUS_UNINITIALIZED:
1693 CLOGE("Device is not initialized!");
1694 return INVALID_OPERATION;
1695 case STATUS_UNCONFIGURED:
1696 case STATUS_CONFIGURED:
1697 case STATUS_ACTIVE:
1698 // OK
1699 break;
1700 default:
1701 SET_ERR_L("Unexpected status: %d", mStatus);
1702 return INVALID_OPERATION;
1703 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001704
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001705 if (!mRequestTemplateCache[templateId].isEmpty()) {
1706 *request = mRequestTemplateCache[templateId];
Emilian Peev811d2952018-05-25 11:08:40 +01001707 mLastTemplateId = templateId;
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001708 return OK;
1709 }
Zhijun Hea1530f12014-09-14 12:44:20 -07001710 }
1711
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001712 camera_metadata_t *rawRequest;
1713 status_t res = mInterface->constructDefaultRequestSettings(
Emilian Peevf4816702020-04-03 15:44:51 -07001714 (camera_request_template_t) templateId, &rawRequest);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001715
1716 {
1717 Mutex::Autolock l(mLock);
1718 if (res == BAD_VALUE) {
1719 ALOGI("%s: template %d is not supported on this camera device",
1720 __FUNCTION__, templateId);
1721 return res;
1722 } else if (res != OK) {
1723 CLOGE("Unable to construct request template %d: %s (%d)",
1724 templateId, strerror(-res), res);
1725 return res;
1726 }
1727
1728 set_camera_metadata_vendor_id(rawRequest, mVendorTagId);
1729 mRequestTemplateCache[templateId].acquire(rawRequest);
1730
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08001731 // Override the template request with zoomRatioMapper
1732 res = mZoomRatioMappers[mId.c_str()].initZoomRatioInTemplate(
1733 &mRequestTemplateCache[templateId]);
1734 if (res != OK) {
1735 CLOGE("Failed to update zoom ratio for template %d: %s (%d)",
1736 templateId, strerror(-res), res);
1737 return res;
1738 }
1739
Shuzhen Wangd25dc972020-03-24 17:11:43 -07001740 // Fill in JPEG_QUALITY if not available
1741 if (!mRequestTemplateCache[templateId].exists(ANDROID_JPEG_QUALITY)) {
1742 static const uint8_t kDefaultJpegQuality = 95;
1743 mRequestTemplateCache[templateId].update(ANDROID_JPEG_QUALITY,
1744 &kDefaultJpegQuality, 1);
1745 }
1746
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001747 *request = mRequestTemplateCache[templateId];
Emilian Peev811d2952018-05-25 11:08:40 +01001748 mLastTemplateId = templateId;
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001749 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001750 return OK;
1751}
1752
1753status_t Camera3Device::waitUntilDrained() {
1754 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001755 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001756 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001757 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001758
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001759 return waitUntilDrainedLocked(maxExpectedDuration);
Zhijun He69a37482014-03-23 18:44:49 -07001760}
1761
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001762status_t Camera3Device::waitUntilDrainedLocked(nsecs_t maxExpectedDuration) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001763 switch (mStatus) {
1764 case STATUS_UNINITIALIZED:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001765 case STATUS_UNCONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001766 ALOGV("%s: Already idle", __FUNCTION__);
1767 return OK;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001768 case STATUS_CONFIGURED:
1769 // To avoid race conditions, check with tracker to be sure
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001770 case STATUS_ERROR:
1771 case STATUS_ACTIVE:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001772 // Need to verify shut down
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001773 break;
1774 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001775 SET_ERR_L("Unexpected status: %d",mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001776 return INVALID_OPERATION;
1777 }
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07001778 ALOGV("%s: Camera %s: Waiting until idle (%" PRIi64 "ns)", __FUNCTION__, mId.string(),
1779 maxExpectedDuration);
1780 status_t res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
Eino-Ville Talvala9c8a0912014-09-14 14:52:19 -07001781 if (res != OK) {
Yin-Chia Yeh87b3ec02019-06-03 10:44:39 -07001782 mStatusTracker->dumpActiveComponents();
Eino-Ville Talvala9c8a0912014-09-14 14:52:19 -07001783 SET_ERR_L("Error waiting for HAL to drain: %s (%d)", strerror(-res),
1784 res);
1785 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001786 return res;
1787}
1788
Ruben Brunk183f0562015-08-12 12:55:02 -07001789
1790void Camera3Device::internalUpdateStatusLocked(Status status) {
1791 mStatus = status;
1792 mRecentStatusUpdates.add(mStatus);
1793 mStatusChanged.broadcast();
1794}
1795
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001796// Pause to reconfigure
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001797status_t Camera3Device::internalPauseAndWaitLocked(nsecs_t maxExpectedDuration) {
Emilian Peeve86358b2019-02-15 13:51:39 -08001798 if (mRequestThread.get() != nullptr) {
1799 mRequestThread->setPaused(true);
1800 } else {
1801 return NO_INIT;
1802 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001803
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07001804 ALOGV("%s: Camera %s: Internal wait until idle (% " PRIi64 " ns)", __FUNCTION__, mId.string(),
1805 maxExpectedDuration);
1806 status_t res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001807 if (res != OK) {
1808 SET_ERR_L("Can't idle device in %f seconds!",
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07001809 maxExpectedDuration/1e9);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001810 }
1811
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001812 return res;
1813}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001814
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001815// Resume after internalPauseAndWaitLocked
1816status_t Camera3Device::internalResumeLocked() {
1817 status_t res;
1818
1819 mRequestThread->setPaused(false);
1820
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08001821 ALOGV("%s: Camera %s: Internal wait until active (% " PRIi64 " ns)", __FUNCTION__, mId.string(),
1822 kActiveTimeout);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001823 res = waitUntilStateThenRelock(/*active*/ true, kActiveTimeout);
1824 if (res != OK) {
1825 SET_ERR_L("Can't transition to active in %f seconds!",
1826 kActiveTimeout/1e9);
1827 }
1828 mPauseStateNotify = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001829 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001830}
1831
Ruben Brunk183f0562015-08-12 12:55:02 -07001832status_t Camera3Device::waitUntilStateThenRelock(bool active, nsecs_t timeout) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001833 status_t res = OK;
Ruben Brunk183f0562015-08-12 12:55:02 -07001834
1835 size_t startIndex = 0;
1836 if (mStatusWaiters == 0) {
1837 // Clear the list of recent statuses if there are no existing threads waiting on updates to
1838 // this status list
1839 mRecentStatusUpdates.clear();
1840 } else {
1841 // If other threads are waiting on updates to this status list, set the position of the
1842 // first element that this list will check rather than clearing the list.
1843 startIndex = mRecentStatusUpdates.size();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001844 }
1845
Ruben Brunk183f0562015-08-12 12:55:02 -07001846 mStatusWaiters++;
1847
Yin-Chia Yehe52b8fa2020-07-28 00:17:58 -07001848 bool signalPipelineDrain = false;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07001849 if (!active && mUseHalBufManager) {
1850 auto streamIds = mOutputStreams.getStreamIds();
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08001851 if (mStatus == STATUS_ACTIVE) {
1852 mRequestThread->signalPipelineDrain(streamIds);
Yin-Chia Yehe52b8fa2020-07-28 00:17:58 -07001853 signalPipelineDrain = true;
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08001854 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07001855 mRequestBufferSM.onWaitUntilIdle();
1856 }
1857
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001858 bool stateSeen = false;
1859 do {
Ruben Brunk183f0562015-08-12 12:55:02 -07001860 if (active == (mStatus == STATUS_ACTIVE)) {
1861 // Desired state is current
1862 break;
1863 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001864
1865 res = mStatusChanged.waitRelative(mLock, timeout);
1866 if (res != OK) break;
1867
Ruben Brunk183f0562015-08-12 12:55:02 -07001868 // This is impossible, but if not, could result in subtle deadlocks and invalid state
1869 // transitions.
1870 LOG_ALWAYS_FATAL_IF(startIndex > mRecentStatusUpdates.size(),
1871 "%s: Skipping status updates in Camera3Device, may result in deadlock.",
1872 __FUNCTION__);
1873
1874 // Encountered desired state since we began waiting
1875 for (size_t i = startIndex; i < mRecentStatusUpdates.size(); i++) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001876 if (active == (mRecentStatusUpdates[i] == STATUS_ACTIVE) ) {
1877 stateSeen = true;
1878 break;
1879 }
1880 }
1881 } while (!stateSeen);
1882
Yin-Chia Yehe52b8fa2020-07-28 00:17:58 -07001883 if (signalPipelineDrain) {
1884 mRequestThread->resetPipelineDrain();
1885 }
1886
Ruben Brunk183f0562015-08-12 12:55:02 -07001887 mStatusWaiters--;
1888
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001889 return res;
1890}
1891
1892
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001893status_t Camera3Device::setNotifyCallback(wp<NotificationListener> listener) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001894 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001895 std::lock_guard<std::mutex> l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001896
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001897 if (listener != NULL && mListener != NULL) {
1898 ALOGW("%s: Replacing old callback listener", __FUNCTION__);
1899 }
1900 mListener = listener;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001901 mRequestThread->setNotificationListener(listener);
1902 mPreparerThread->setNotificationListener(listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001903
1904 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001905}
1906
Eino-Ville Talvala46910bd2013-07-18 19:15:17 -07001907bool Camera3Device::willNotify3A() {
1908 return false;
1909}
1910
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001911status_t Camera3Device::waitForNextFrame(nsecs_t timeout) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07001912 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001913 std::unique_lock<std::mutex> l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001914
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001915 while (mResultQueue.empty()) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001916 auto st = mResultSignal.wait_for(l, std::chrono::nanoseconds(timeout));
1917 if (st == std::cv_status::timeout) {
1918 return TIMED_OUT;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001919 }
1920 }
1921 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001922}
1923
Jianing Weicb0652e2014-03-12 18:29:36 -07001924status_t Camera3Device::getNextResult(CaptureResult *frame) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001925 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001926 std::lock_guard<std::mutex> l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001927
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001928 if (mResultQueue.empty()) {
1929 return NOT_ENOUGH_DATA;
1930 }
1931
Jianing Weicb0652e2014-03-12 18:29:36 -07001932 if (frame == NULL) {
1933 ALOGE("%s: argument cannot be NULL", __FUNCTION__);
1934 return BAD_VALUE;
1935 }
1936
1937 CaptureResult &result = *(mResultQueue.begin());
1938 frame->mResultExtras = result.mResultExtras;
1939 frame->mMetadata.acquire(result.mMetadata);
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001940 frame->mPhysicalMetadatas = std::move(result.mPhysicalMetadatas);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001941 mResultQueue.erase(mResultQueue.begin());
1942
1943 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001944}
1945
1946status_t Camera3Device::triggerAutofocus(uint32_t id) {
1947 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001948 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001949
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001950 ALOGV("%s: Triggering autofocus, id %d", __FUNCTION__, id);
1951 // Mix-in this trigger into the next request and only the next request.
1952 RequestTrigger trigger[] = {
1953 {
1954 ANDROID_CONTROL_AF_TRIGGER,
1955 ANDROID_CONTROL_AF_TRIGGER_START
1956 },
1957 {
1958 ANDROID_CONTROL_AF_TRIGGER_ID,
1959 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07001960 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001961 };
1962
1963 return mRequestThread->queueTrigger(trigger,
1964 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001965}
1966
1967status_t Camera3Device::triggerCancelAutofocus(uint32_t id) {
1968 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001969 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001970
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001971 ALOGV("%s: Triggering cancel autofocus, id %d", __FUNCTION__, id);
1972 // Mix-in this trigger into the next request and only the next request.
1973 RequestTrigger trigger[] = {
1974 {
1975 ANDROID_CONTROL_AF_TRIGGER,
1976 ANDROID_CONTROL_AF_TRIGGER_CANCEL
1977 },
1978 {
1979 ANDROID_CONTROL_AF_TRIGGER_ID,
1980 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07001981 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001982 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001983
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001984 return mRequestThread->queueTrigger(trigger,
1985 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001986}
1987
1988status_t Camera3Device::triggerPrecaptureMetering(uint32_t id) {
1989 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001990 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001991
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001992 ALOGV("%s: Triggering precapture metering, id %d", __FUNCTION__, id);
1993 // Mix-in this trigger into the next request and only the next request.
1994 RequestTrigger trigger[] = {
1995 {
1996 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER,
1997 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_START
1998 },
1999 {
2000 ANDROID_CONTROL_AE_PRECAPTURE_ID,
2001 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07002002 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002003 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002004
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002005 return mRequestThread->queueTrigger(trigger,
2006 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002007}
2008
Jianing Weicb0652e2014-03-12 18:29:36 -07002009status_t Camera3Device::flush(int64_t *frameNumber) {
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07002010 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002011 ALOGV("%s: Camera %s: Flushing all requests", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002012 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07002013
Zhijun He7ef20392014-04-21 16:04:17 -07002014 {
2015 Mutex::Autolock l(mLock);
Emilian Peeved2ebe42018-09-25 16:59:09 +01002016
2017 // b/116514106 "disconnect()" can get called twice for the same device. The
2018 // camera device will not be initialized during the second run.
2019 if (mStatus == STATUS_UNINITIALIZED) {
2020 return OK;
2021 }
2022
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002023 mRequestThread->clear(/*out*/frameNumber);
Shuzhen Wang316781a2020-08-18 18:11:01 -07002024
2025 // Stop session and stream counter
2026 mSessionStatsBuilder.stopCounter();
Zhijun He7ef20392014-04-21 16:04:17 -07002027 }
2028
Emilian Peev08dd2452017-04-06 16:55:14 +01002029 return mRequestThread->flush();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07002030}
2031
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002032status_t Camera3Device::prepare(int streamId) {
Ruben Brunkc78ac262015-08-13 17:58:46 -07002033 return prepare(camera3::Camera3StreamInterface::ALLOCATE_PIPELINE_MAX, streamId);
2034}
2035
2036status_t Camera3Device::prepare(int maxCount, int streamId) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002037 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002038 ALOGV("%s: Camera %s: Preparing stream %d", __FUNCTION__, mId.string(), streamId);
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07002039 Mutex::Autolock il(mInterfaceLock);
2040 Mutex::Autolock l(mLock);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002041
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002042 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
2043 if (stream == nullptr) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002044 CLOGE("Stream %d does not exist", streamId);
2045 return BAD_VALUE;
2046 }
2047
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002048 if (stream->isUnpreparable() || stream->hasOutstandingBuffers() ) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07002049 CLOGE("Stream %d has already been a request target", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002050 return BAD_VALUE;
2051 }
2052
2053 if (mRequestThread->isStreamPending(stream)) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07002054 CLOGE("Stream %d is already a target in a pending request", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002055 return BAD_VALUE;
2056 }
2057
Ruben Brunkc78ac262015-08-13 17:58:46 -07002058 return mPreparerThread->prepare(maxCount, stream);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002059}
2060
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002061status_t Camera3Device::tearDown(int streamId) {
2062 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002063 ALOGV("%s: Camera %s: Tearing down stream %d", __FUNCTION__, mId.string(), streamId);
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002064 Mutex::Autolock il(mInterfaceLock);
2065 Mutex::Autolock l(mLock);
2066
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002067 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
2068 if (stream == nullptr) {
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002069 CLOGE("Stream %d does not exist", streamId);
2070 return BAD_VALUE;
2071 }
2072
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002073 if (stream->hasOutstandingBuffers() || mRequestThread->isStreamPending(stream)) {
2074 CLOGE("Stream %d is a target of a in-progress request", streamId);
2075 return BAD_VALUE;
2076 }
2077
2078 return stream->tearDown();
2079}
2080
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002081status_t Camera3Device::addBufferListenerForStream(int streamId,
2082 wp<Camera3StreamBufferListener> listener) {
2083 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002084 ALOGV("%s: Camera %s: Adding buffer listener for stream %d", __FUNCTION__, mId.string(), streamId);
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002085 Mutex::Autolock il(mInterfaceLock);
2086 Mutex::Autolock l(mLock);
2087
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002088 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
2089 if (stream == nullptr) {
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002090 CLOGE("Stream %d does not exist", streamId);
2091 return BAD_VALUE;
2092 }
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002093 stream->addBufferListener(listener);
2094
2095 return OK;
2096}
2097
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002098/**
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002099 * Methods called by subclasses
2100 */
2101
2102void Camera3Device::notifyStatus(bool idle) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002103 ATRACE_CALL();
Shuzhen Wang316781a2020-08-18 18:11:01 -07002104 std::vector<int> streamIds;
2105 std::vector<hardware::CameraStreamStats> streamStats;
2106
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002107 {
2108 // Need mLock to safely update state and synchronize to current
2109 // state of methods in flight.
2110 Mutex::Autolock l(mLock);
2111 // We can get various system-idle notices from the status tracker
2112 // while starting up. Only care about them if we've actually sent
2113 // in some requests recently.
2114 if (mStatus != STATUS_ACTIVE && mStatus != STATUS_CONFIGURED) {
2115 return;
2116 }
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08002117 ALOGV("%s: Camera %s: Now %s, pauseState: %s", __FUNCTION__, mId.string(),
2118 idle ? "idle" : "active", mPauseStateNotify ? "true" : "false");
Ruben Brunk183f0562015-08-12 12:55:02 -07002119 internalUpdateStatusLocked(idle ? STATUS_CONFIGURED : STATUS_ACTIVE);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002120
2121 // Skip notifying listener if we're doing some user-transparent
2122 // state changes
2123 if (mPauseStateNotify) return;
Shuzhen Wang316781a2020-08-18 18:11:01 -07002124
2125 // Populate stream statistics in case of Idle
2126 if (idle) {
2127 for (size_t i = 0; i < mOutputStreams.size(); i++) {
2128 auto stream = mOutputStreams[i];
2129 if (stream.get() == nullptr) continue;
2130 streamIds.push_back(stream->getId());
2131 Camera3Stream* camera3Stream = Camera3Stream::cast(stream->asHalStream());
2132 int64_t usage = 0LL;
2133 if (camera3Stream != nullptr) {
2134 usage = camera3Stream->getUsage();
2135 }
2136 streamStats.emplace_back(stream->getWidth(), stream->getHeight(),
2137 stream->getFormat(), stream->getDataSpace(), usage,
2138 stream->getMaxHalBuffers(),
2139 stream->getMaxTotalBuffers() - stream->getMaxHalBuffers());
2140 }
2141 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002142 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002143
2144 sp<NotificationListener> listener;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002145 {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002146 std::lock_guard<std::mutex> l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002147 listener = mListener.promote();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002148 }
2149 if (idle && listener != NULL) {
Shuzhen Wang316781a2020-08-18 18:11:01 -07002150 // Get session stats from the builder, and notify the listener.
2151 int64_t requestCount, resultErrorCount;
2152 bool deviceError;
2153 std::map<int, StreamStats> streamStatsMap;
2154 mSessionStatsBuilder.buildAndReset(&requestCount, &resultErrorCount,
2155 &deviceError, &streamStatsMap);
2156 for (size_t i = 0; i < streamIds.size(); i++) {
2157 int streamId = streamIds[i];
2158 auto stats = streamStatsMap.find(streamId);
2159 if (stats != streamStatsMap.end()) {
2160 streamStats[i].mRequestCount = stats->second.mRequestedFrameCount;
2161 streamStats[i].mErrorCount = stats->second.mDroppedFrameCount;
2162 streamStats[i].mStartLatencyMs = stats->second.mStartLatencyMs;
Shuzhen Wangdb8f2782020-10-30 08:43:37 -07002163 streamStats[i].mHistogramType =
2164 hardware::CameraStreamStats::HISTOGRAM_TYPE_CAPTURE_LATENCY;
2165 streamStats[i].mHistogramBins.assign(
2166 stats->second.mCaptureLatencyBins.begin(),
2167 stats->second.mCaptureLatencyBins.end());
2168 streamStats[i].mHistogramCounts.assign(
2169 stats->second.mCaptureLatencyHistogram.begin(),
2170 stats->second.mCaptureLatencyHistogram.end());
Shuzhen Wang316781a2020-08-18 18:11:01 -07002171 }
2172 }
2173 listener->notifyIdle(requestCount, resultErrorCount, deviceError, streamStats);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002174 }
2175}
2176
Shuzhen Wang758c2152017-01-10 18:26:18 -08002177status_t Camera3Device::setConsumerSurfaces(int streamId,
Emilian Peev40ead602017-09-26 15:46:36 +01002178 const std::vector<sp<Surface>>& consumers, std::vector<int> *surfaceIds) {
Zhijun He5d677d12016-05-29 16:52:39 -07002179 ATRACE_CALL();
Shuzhen Wang758c2152017-01-10 18:26:18 -08002180 ALOGV("%s: Camera %s: set consumer surface for stream %d",
2181 __FUNCTION__, mId.string(), streamId);
Emilian Peev40ead602017-09-26 15:46:36 +01002182
2183 if (surfaceIds == nullptr) {
2184 return BAD_VALUE;
2185 }
2186
Zhijun He5d677d12016-05-29 16:52:39 -07002187 Mutex::Autolock il(mInterfaceLock);
2188 Mutex::Autolock l(mLock);
2189
Shuzhen Wang758c2152017-01-10 18:26:18 -08002190 if (consumers.size() == 0) {
2191 CLOGE("No consumer is passed!");
Zhijun He5d677d12016-05-29 16:52:39 -07002192 return BAD_VALUE;
2193 }
2194
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002195 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
2196 if (stream == nullptr) {
Zhijun He5d677d12016-05-29 16:52:39 -07002197 CLOGE("Stream %d is unknown", streamId);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002198 return BAD_VALUE;
Zhijun He5d677d12016-05-29 16:52:39 -07002199 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002200
2201 // isConsumerConfigurationDeferred will be off after setConsumers
2202 bool isDeferred = stream->isConsumerConfigurationDeferred();
Shuzhen Wang758c2152017-01-10 18:26:18 -08002203 status_t res = stream->setConsumers(consumers);
Zhijun He5d677d12016-05-29 16:52:39 -07002204 if (res != OK) {
2205 CLOGE("Stream %d set consumer failed (error %d %s) ", streamId, res, strerror(-res));
2206 return res;
2207 }
2208
Emilian Peev40ead602017-09-26 15:46:36 +01002209 for (auto &consumer : consumers) {
2210 int id = stream->getSurfaceId(consumer);
2211 if (id < 0) {
2212 CLOGE("Invalid surface id!");
2213 return BAD_VALUE;
2214 }
2215 surfaceIds->push_back(id);
2216 }
2217
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002218 if (isDeferred) {
Shuzhen Wang0129d522016-10-30 22:43:41 -07002219 if (!stream->isConfiguring()) {
2220 CLOGE("Stream %d was already fully configured.", streamId);
2221 return INVALID_OPERATION;
2222 }
Zhijun He5d677d12016-05-29 16:52:39 -07002223
Shuzhen Wang0129d522016-10-30 22:43:41 -07002224 res = stream->finishConfiguration();
2225 if (res != OK) {
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002226 // If finishConfiguration fails due to abandoned surface, do not set
2227 // device to error state.
2228 bool isSurfaceAbandoned =
2229 (res == NO_INIT || res == DEAD_OBJECT) && stream->isAbandoned();
2230 if (!isSurfaceAbandoned) {
2231 SET_ERR_L("Can't finish configuring output stream %d: %s (%d)",
2232 stream->getId(), strerror(-res), res);
2233 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07002234 return res;
2235 }
Zhijun He5d677d12016-05-29 16:52:39 -07002236 }
2237
2238 return OK;
2239}
2240
Emilian Peev40ead602017-09-26 15:46:36 +01002241status_t Camera3Device::updateStream(int streamId, const std::vector<sp<Surface>> &newSurfaces,
2242 const std::vector<OutputStreamInfo> &outputInfo,
2243 const std::vector<size_t> &removedSurfaceIds, KeyedVector<sp<Surface>, size_t> *outputMap) {
2244 Mutex::Autolock il(mInterfaceLock);
2245 Mutex::Autolock l(mLock);
2246
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002247 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
2248 if (stream == nullptr) {
Emilian Peev40ead602017-09-26 15:46:36 +01002249 CLOGE("Stream %d is unknown", streamId);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002250 return BAD_VALUE;
Emilian Peev40ead602017-09-26 15:46:36 +01002251 }
2252
2253 for (const auto &it : removedSurfaceIds) {
2254 if (mRequestThread->isOutputSurfacePending(streamId, it)) {
2255 CLOGE("Shared surface still part of a pending request!");
2256 return -EBUSY;
2257 }
2258 }
2259
Emilian Peev40ead602017-09-26 15:46:36 +01002260 status_t res = stream->updateStream(newSurfaces, outputInfo, removedSurfaceIds, outputMap);
2261 if (res != OK) {
2262 CLOGE("Stream %d failed to update stream (error %d %s) ",
2263 streamId, res, strerror(-res));
2264 if (res == UNKNOWN_ERROR) {
2265 SET_ERR_L("%s: Stream update failed to revert to previous output configuration!",
2266 __FUNCTION__);
2267 }
2268 return res;
2269 }
2270
2271 return res;
2272}
2273
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002274status_t Camera3Device::dropStreamBuffers(bool dropping, int streamId) {
2275 Mutex::Autolock il(mInterfaceLock);
2276 Mutex::Autolock l(mLock);
2277
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002278 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
2279 if (stream == nullptr) {
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002280 ALOGE("%s: Stream %d is not found.", __FUNCTION__, streamId);
2281 return BAD_VALUE;
2282 }
Shuzhen Wang316781a2020-08-18 18:11:01 -07002283
2284 if (dropping) {
2285 mSessionStatsBuilder.stopCounter(streamId);
2286 } else {
2287 mSessionStatsBuilder.startCounter(streamId);
2288 }
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002289 return stream->dropBuffers(dropping);
2290}
2291
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002292/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002293 * Camera3Device private methods
2294 */
2295
2296sp<Camera3Device::CaptureRequest> Camera3Device::createCaptureRequest(
Emilian Peevaebbe412018-01-15 13:53:24 +00002297 const PhysicalCameraSettingsList &request, const SurfaceMap &surfaceMap) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002298 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002299
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08002300 sp<CaptureRequest> newRequest = new CaptureRequest();
Emilian Peevaebbe412018-01-15 13:53:24 +00002301 newRequest->mSettingsList = request;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002302
2303 camera_metadata_entry_t inputStreams =
Emilian Peevaebbe412018-01-15 13:53:24 +00002304 newRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_INPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002305 if (inputStreams.count > 0) {
2306 if (mInputStream == NULL ||
Zhijun Hed1d64672013-09-06 15:00:01 -07002307 mInputStream->getId() != inputStreams.data.i32[0]) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002308 CLOGE("Request references unknown input stream %d",
2309 inputStreams.data.u8[0]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002310 return NULL;
2311 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002312
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002313 if (mInputStream->isConfiguring()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002314 SET_ERR_L("%s: input stream %d is not configured!",
2315 __FUNCTION__, mInputStream->getId());
2316 return NULL;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002317 }
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07002318 // Check if stream prepare is blocking requests.
2319 if (mInputStream->isBlockedByPrepare()) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002320 CLOGE("Request references an input stream that's being prepared!");
2321 return NULL;
2322 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002323
2324 newRequest->mInputStream = mInputStream;
Emilian Peevaebbe412018-01-15 13:53:24 +00002325 newRequest->mSettingsList.begin()->metadata.erase(ANDROID_REQUEST_INPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002326 }
2327
2328 camera_metadata_entry_t streams =
Emilian Peevaebbe412018-01-15 13:53:24 +00002329 newRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_OUTPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002330 if (streams.count == 0) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002331 CLOGE("Zero output streams specified!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002332 return NULL;
2333 }
2334
2335 for (size_t i = 0; i < streams.count; i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002336 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streams.data.i32[i]);
2337 if (stream == nullptr) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002338 CLOGE("Request references unknown stream %d",
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002339 streams.data.i32[i]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002340 return NULL;
2341 }
Zhijun He5d677d12016-05-29 16:52:39 -07002342 // It is illegal to include a deferred consumer output stream into a request
Shuzhen Wang0129d522016-10-30 22:43:41 -07002343 auto iter = surfaceMap.find(streams.data.i32[i]);
2344 if (iter != surfaceMap.end()) {
2345 const std::vector<size_t>& surfaces = iter->second;
2346 for (const auto& surface : surfaces) {
2347 if (stream->isConsumerConfigurationDeferred(surface)) {
2348 CLOGE("Stream %d surface %zu hasn't finished configuration yet "
2349 "due to deferred consumer", stream->getId(), surface);
2350 return NULL;
2351 }
2352 }
Yin-Chia Yeh0b287572018-10-15 12:38:13 -07002353 newRequest->mOutputSurfaces[streams.data.i32[i]] = surfaces;
Zhijun He5d677d12016-05-29 16:52:39 -07002354 }
2355
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002356 if (stream->isConfiguring()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002357 SET_ERR_L("%s: stream %d is not configured!", __FUNCTION__, stream->getId());
2358 return NULL;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002359 }
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07002360 // Check if stream prepare is blocking requests.
2361 if (stream->isBlockedByPrepare()) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002362 CLOGE("Request references an output stream that's being prepared!");
2363 return NULL;
2364 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002365
2366 newRequest->mOutputStreams.push(stream);
2367 }
Emilian Peevaebbe412018-01-15 13:53:24 +00002368 newRequest->mSettingsList.begin()->metadata.erase(ANDROID_REQUEST_OUTPUT_STREAMS);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07002369 newRequest->mBatchSize = 1;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002370
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08002371 auto rotateAndCropEntry =
2372 newRequest->mSettingsList.begin()->metadata.find(ANDROID_SCALER_ROTATE_AND_CROP);
2373 if (rotateAndCropEntry.count > 0 &&
2374 rotateAndCropEntry.data.u8[0] == ANDROID_SCALER_ROTATE_AND_CROP_AUTO) {
2375 newRequest->mRotateAndCropAuto = true;
2376 } else {
2377 newRequest->mRotateAndCropAuto = false;
2378 }
2379
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07002380 auto zoomRatioEntry =
2381 newRequest->mSettingsList.begin()->metadata.find(ANDROID_CONTROL_ZOOM_RATIO);
2382 if (zoomRatioEntry.count > 0 &&
2383 zoomRatioEntry.data.f[0] == 1.0f) {
2384 newRequest->mZoomRatioIs1x = true;
2385 } else {
2386 newRequest->mZoomRatioIs1x = false;
2387 }
2388
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08002389 if (mSupportCameraMute) {
2390 auto testPatternModeEntry =
2391 newRequest->mSettingsList.begin()->metadata.find(ANDROID_SENSOR_TEST_PATTERN_MODE);
2392 newRequest->mOriginalTestPatternMode = testPatternModeEntry.count > 0 ?
2393 testPatternModeEntry.data.i32[0] :
2394 ANDROID_SENSOR_TEST_PATTERN_MODE_OFF;
2395
2396 auto testPatternDataEntry =
2397 newRequest->mSettingsList.begin()->metadata.find(ANDROID_SENSOR_TEST_PATTERN_DATA);
2398 if (testPatternDataEntry.count > 0) {
2399 memcpy(newRequest->mOriginalTestPatternData, testPatternModeEntry.data.i32,
2400 sizeof(newRequest->mOriginalTestPatternData));
2401 } else {
2402 newRequest->mOriginalTestPatternData[0] = 0;
2403 newRequest->mOriginalTestPatternData[1] = 0;
2404 newRequest->mOriginalTestPatternData[2] = 0;
2405 newRequest->mOriginalTestPatternData[3] = 0;
2406 }
2407 }
2408
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002409 return newRequest;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002410}
2411
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002412void Camera3Device::cancelStreamsConfigurationLocked() {
2413 int res = OK;
2414 if (mInputStream != NULL && mInputStream->isConfiguring()) {
2415 res = mInputStream->cancelConfiguration();
2416 if (res != OK) {
2417 CLOGE("Can't cancel configuring input stream %d: %s (%d)",
2418 mInputStream->getId(), strerror(-res), res);
2419 }
2420 }
2421
2422 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002423 sp<Camera3OutputStreamInterface> outputStream = mOutputStreams[i];
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002424 if (outputStream->isConfiguring()) {
2425 res = outputStream->cancelConfiguration();
2426 if (res != OK) {
2427 CLOGE("Can't cancel configuring output stream %d: %s (%d)",
2428 outputStream->getId(), strerror(-res), res);
2429 }
2430 }
2431 }
2432
2433 // Return state to that at start of call, so that future configures
2434 // properly clean things up
2435 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
2436 mNeedConfig = true;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002437
2438 res = mPreparerThread->resume();
2439 if (res != OK) {
2440 ALOGE("%s: Camera %s: Preparer thread failed to resume!", __FUNCTION__, mId.string());
2441 }
2442}
2443
Emilian Peev0d0191e2020-04-21 17:01:18 -07002444bool Camera3Device::checkAbandonedStreamsLocked() {
2445 if ((mInputStream.get() != nullptr) && (mInputStream->isAbandoned())) {
2446 return true;
2447 }
2448
2449 for (size_t i = 0; i < mOutputStreams.size(); i++) {
2450 auto stream = mOutputStreams[i];
2451 if ((stream.get() != nullptr) && (stream->isAbandoned())) {
2452 return true;
2453 }
2454 }
2455
2456 return false;
2457}
2458
Emilian Peev3bead5f2020-05-28 17:29:08 -07002459bool Camera3Device::reconfigureCamera(const CameraMetadata& sessionParams, int clientStatusId) {
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002460 ATRACE_CALL();
2461 bool ret = false;
2462
Shuzhen Wang316781a2020-08-18 18:11:01 -07002463 nsecs_t startTime = systemTime();
2464
Jayant Chowdhary646c31b2020-01-30 13:09:59 -08002465 Mutex::Autolock il(mInterfaceLock);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002466 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
2467
2468 Mutex::Autolock l(mLock);
Emilian Peev0d0191e2020-04-21 17:01:18 -07002469 if (checkAbandonedStreamsLocked()) {
2470 ALOGW("%s: Abandoned stream detected, session parameters can't be applied correctly!",
2471 __FUNCTION__);
2472 return true;
2473 }
2474
Emilian Peev3bead5f2020-05-28 17:29:08 -07002475 status_t rc = NO_ERROR;
2476 bool markClientActive = false;
2477 if (mStatus == STATUS_ACTIVE) {
2478 markClientActive = true;
2479 mPauseStateNotify = true;
2480 mStatusTracker->markComponentIdle(clientStatusId, Fence::NO_FENCE);
2481
2482 rc = internalPauseAndWaitLocked(maxExpectedDuration);
2483 }
2484
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002485 if (rc == NO_ERROR) {
2486 mNeedConfig = true;
2487 rc = configureStreamsLocked(mOperatingMode, sessionParams, /*notifyRequestThread*/ false);
2488 if (rc == NO_ERROR) {
2489 ret = true;
2490 mPauseStateNotify = false;
2491 //Moving to active state while holding 'mLock' is important.
2492 //There could be pending calls to 'create-/deleteStream' which
2493 //will trigger another stream configuration while the already
2494 //present streams end up with outstanding buffers that will
2495 //not get drained.
2496 internalUpdateStatusLocked(STATUS_ACTIVE);
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002497 } else if (rc == DEAD_OBJECT) {
2498 // DEAD_OBJECT can be returned if either the consumer surface is
2499 // abandoned, or the HAL has died.
2500 // - If the HAL has died, configureStreamsLocked call will set
2501 // device to error state,
2502 // - If surface is abandoned, we should not set device to error
2503 // state.
2504 ALOGE("Failed to re-configure camera due to abandoned surface");
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002505 } else {
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002506 SET_ERR_L("Failed to re-configure camera: %d", rc);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002507 }
2508 } else {
2509 ALOGE("%s: Failed to pause streaming: %d", __FUNCTION__, rc);
2510 }
2511
Shuzhen Wang316781a2020-08-18 18:11:01 -07002512 CameraServiceProxyWrapper::logStreamConfigured(mId, mOperatingMode, true /*internalReconfig*/,
2513 ns2ms(systemTime() - startTime));
2514
Emilian Peev3bead5f2020-05-28 17:29:08 -07002515 if (markClientActive) {
2516 mStatusTracker->markComponentActive(clientStatusId);
2517 }
2518
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002519 return ret;
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002520}
2521
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002522status_t Camera3Device::configureStreamsLocked(int operatingMode,
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002523 const CameraMetadata& sessionParams, bool notifyRequestThread) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002524 ATRACE_CALL();
2525 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002526
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002527 if (mStatus != STATUS_UNCONFIGURED && mStatus != STATUS_CONFIGURED) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002528 CLOGE("Not idle");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002529 return INVALID_OPERATION;
2530 }
2531
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08002532 if (operatingMode < 0) {
2533 CLOGE("Invalid operating mode: %d", operatingMode);
2534 return BAD_VALUE;
2535 }
2536
2537 bool isConstrainedHighSpeed =
2538 static_cast<int>(StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE) ==
2539 operatingMode;
2540
2541 if (mOperatingMode != operatingMode) {
2542 mNeedConfig = true;
2543 mIsConstrainedHighSpeedConfiguration = isConstrainedHighSpeed;
2544 mOperatingMode = operatingMode;
2545 }
2546
Shuzhen Wang0cf01cb2019-09-05 13:33:06 -07002547 // In case called from configureStreams, abort queued input buffers not belonging to
2548 // any pending requests.
2549 if (mInputStream != NULL && notifyRequestThread) {
2550 while (true) {
Emilian Peevf4816702020-04-03 15:44:51 -07002551 camera_stream_buffer_t inputBuffer;
Shuzhen Wang0cf01cb2019-09-05 13:33:06 -07002552 status_t res = mInputStream->getInputBuffer(&inputBuffer,
2553 /*respectHalLimit*/ false);
2554 if (res != OK) {
2555 // Exhausted acquiring all input buffers.
2556 break;
2557 }
2558
Emilian Peevf4816702020-04-03 15:44:51 -07002559 inputBuffer.status = CAMERA_BUFFER_STATUS_ERROR;
Shuzhen Wang0cf01cb2019-09-05 13:33:06 -07002560 res = mInputStream->returnInputBuffer(inputBuffer);
2561 if (res != OK) {
2562 ALOGE("%s: %d: couldn't return input buffer while clearing input queue: "
2563 "%s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
2564 }
2565 }
2566 }
2567
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002568 if (!mNeedConfig) {
2569 ALOGV("%s: Skipping config, no stream changes", __FUNCTION__);
2570 return OK;
2571 }
2572
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002573 // Workaround for device HALv3.2 or older spec bug - zero streams requires
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002574 // adding a fake stream instead.
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002575 // TODO: Bug: 17321404 for fixing the HAL spec and removing this workaround.
2576 if (mOutputStreams.size() == 0) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002577 addFakeStreamLocked();
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002578 } else {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002579 tryRemoveFakeStreamLocked();
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002580 }
2581
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002582 // Start configuring the streams
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002583 ALOGV("%s: Camera %s: Starting stream configuration", __FUNCTION__, mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002584
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002585 mPreparerThread->pause();
2586
Emilian Peevf4816702020-04-03 15:44:51 -07002587 camera_stream_configuration config;
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -08002588 config.operation_mode = mOperatingMode;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002589 config.num_streams = (mInputStream != NULL) + mOutputStreams.size();
2590
Emilian Peevf4816702020-04-03 15:44:51 -07002591 Vector<camera3::camera_stream_t*> streams;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002592 streams.setCapacity(config.num_streams);
Emilian Peev192ee832018-01-31 14:46:47 +00002593 std::vector<uint32_t> bufferSizes(config.num_streams, 0);
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002594
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002595
2596 if (mInputStream != NULL) {
Emilian Peevf4816702020-04-03 15:44:51 -07002597 camera3::camera_stream_t *inputStream;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002598 inputStream = mInputStream->startConfiguration();
2599 if (inputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002600 CLOGE("Can't start input stream configuration");
2601 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002602 return INVALID_OPERATION;
2603 }
2604 streams.add(inputStream);
2605 }
2606
2607 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Igor Murashkin2fba5842013-04-22 14:03:54 -07002608
2609 // Don't configure bidi streams twice, nor add them twice to the list
2610 if (mOutputStreams[i].get() ==
2611 static_cast<Camera3StreamInterface*>(mInputStream.get())) {
2612
2613 config.num_streams--;
2614 continue;
2615 }
2616
Emilian Peevf4816702020-04-03 15:44:51 -07002617 camera3::camera_stream_t *outputStream;
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002618 outputStream = mOutputStreams[i]->startConfiguration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002619 if (outputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002620 CLOGE("Can't start output stream configuration");
2621 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002622 return INVALID_OPERATION;
2623 }
2624 streams.add(outputStream);
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002625
Shuzhen Wangb7ab1e42019-02-20 15:42:23 -08002626 if (outputStream->format == HAL_PIXEL_FORMAT_BLOB) {
Emilian Peev192ee832018-01-31 14:46:47 +00002627 size_t k = i + ((mInputStream != nullptr) ? 1 : 0); // Input stream if present should
2628 // always occupy the initial entry.
Shuzhen Wangb7ab1e42019-02-20 15:42:23 -08002629 if (outputStream->data_space == HAL_DATASPACE_V0_JFIF) {
2630 bufferSizes[k] = static_cast<uint32_t>(
2631 getJpegBufferSize(outputStream->width, outputStream->height));
2632 } else if (outputStream->data_space ==
2633 static_cast<android_dataspace>(HAL_DATASPACE_JPEG_APP_SEGMENTS)) {
2634 bufferSizes[k] = outputStream->width * outputStream->height;
2635 } else {
2636 ALOGW("%s: Blob dataSpace %d not supported",
2637 __FUNCTION__, outputStream->data_space);
2638 }
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002639 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002640 }
2641
2642 config.streams = streams.editArray();
2643
2644 // Do the HAL configuration; will potentially touch stream
Shuzhen Wang92653952019-05-07 15:11:43 -07002645 // max_buffers, usage, and priv fields, as well as data_space and format
2646 // fields for IMPLEMENTATION_DEFINED formats.
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002647
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002648 const camera_metadata_t *sessionBuffer = sessionParams.getAndLock();
Emilian Peev192ee832018-01-31 14:46:47 +00002649 res = mInterface->configureStreams(sessionBuffer, &config, bufferSizes);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002650 sessionParams.unlock(sessionBuffer);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002651
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002652 if (res == BAD_VALUE) {
2653 // HAL rejected this set of streams as unsupported, clean up config
2654 // attempt and return to unconfigured state
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002655 CLOGE("Set of requested inputs/outputs not supported by HAL");
2656 cancelStreamsConfigurationLocked();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002657 return BAD_VALUE;
2658 } else if (res != OK) {
2659 // Some other kind of error from configure_streams - this is not
2660 // expected
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002661 SET_ERR_L("Unable to configure streams with HAL: %s (%d)",
2662 strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002663 return res;
2664 }
2665
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002666 // Finish all stream configuration immediately.
2667 // TODO: Try to relax this later back to lazy completion, which should be
2668 // faster
2669
Igor Murashkin073f8572013-05-02 14:59:28 -07002670 if (mInputStream != NULL && mInputStream->isConfiguring()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002671 bool streamReConfigured = false;
2672 res = mInputStream->finishConfiguration(&streamReConfigured);
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002673 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002674 CLOGE("Can't finish configuring input stream %d: %s (%d)",
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002675 mInputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002676 cancelStreamsConfigurationLocked();
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002677 if ((res == NO_INIT || res == DEAD_OBJECT) && mInputStream->isAbandoned()) {
2678 return DEAD_OBJECT;
2679 }
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002680 return BAD_VALUE;
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002681 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002682 if (streamReConfigured) {
2683 mInterface->onStreamReConfigured(mInputStream->getId());
2684 }
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002685 }
2686
2687 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002688 sp<Camera3OutputStreamInterface> outputStream = mOutputStreams[i];
Zhijun He5d677d12016-05-29 16:52:39 -07002689 if (outputStream->isConfiguring() && !outputStream->isConsumerConfigurationDeferred()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002690 bool streamReConfigured = false;
2691 res = outputStream->finishConfiguration(&streamReConfigured);
Igor Murashkin073f8572013-05-02 14:59:28 -07002692 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002693 CLOGE("Can't finish configuring output stream %d: %s (%d)",
Igor Murashkin073f8572013-05-02 14:59:28 -07002694 outputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002695 cancelStreamsConfigurationLocked();
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002696 if ((res == NO_INIT || res == DEAD_OBJECT) && outputStream->isAbandoned()) {
2697 return DEAD_OBJECT;
2698 }
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002699 return BAD_VALUE;
Igor Murashkin073f8572013-05-02 14:59:28 -07002700 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002701 if (streamReConfigured) {
2702 mInterface->onStreamReConfigured(outputStream->getId());
2703 }
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002704 }
2705 }
2706
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002707 // Request thread needs to know to avoid using repeat-last-settings protocol
2708 // across configure_streams() calls
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002709 if (notifyRequestThread) {
2710 mRequestThread->configurationComplete(mIsConstrainedHighSpeedConfiguration, sessionParams);
2711 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002712
Zhijun He90f7c372016-08-16 16:19:43 -07002713 char value[PROPERTY_VALUE_MAX];
2714 property_get("camera.fifo.disable", value, "0");
2715 int32_t disableFifo = atoi(value);
2716 if (disableFifo != 1) {
2717 // Boost priority of request thread to SCHED_FIFO.
2718 pid_t requestThreadTid = mRequestThread->getTid();
2719 res = requestPriority(getpid(), requestThreadTid,
Mikhail Naganov83f04272017-02-07 10:45:09 -08002720 kRequestThreadPriority, /*isForApp*/ false, /*asynchronous*/ false);
Zhijun He90f7c372016-08-16 16:19:43 -07002721 if (res != OK) {
2722 ALOGW("Can't set realtime priority for request processing thread: %s (%d)",
2723 strerror(-res), res);
2724 } else {
2725 ALOGD("Set real time priority for request queue thread (tid %d)", requestThreadTid);
2726 }
Eino-Ville Talvalaf99498e2015-09-25 16:52:55 -07002727 }
2728
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002729 // Update device state
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002730 const camera_metadata_t *newSessionParams = sessionParams.getAndLock();
2731 const camera_metadata_t *currentSessionParams = mSessionParams.getAndLock();
2732 bool updateSessionParams = (newSessionParams != currentSessionParams) ? true : false;
2733 sessionParams.unlock(newSessionParams);
2734 mSessionParams.unlock(currentSessionParams);
2735 if (updateSessionParams) {
2736 mSessionParams = sessionParams;
2737 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002738
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002739 mNeedConfig = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002740
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002741 internalUpdateStatusLocked((mFakeStreamId == NO_STREAM) ?
Ruben Brunk183f0562015-08-12 12:55:02 -07002742 STATUS_CONFIGURED : STATUS_UNCONFIGURED);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002743
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002744 ALOGV("%s: Camera %s: Stream configuration complete", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002745
Zhijun He0a210512014-07-24 13:45:15 -07002746 // tear down the deleted streams after configure streams.
2747 mDeletedStreams.clear();
2748
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002749 auto rc = mPreparerThread->resume();
2750 if (rc != OK) {
2751 SET_ERR_L("%s: Camera %s: Preparer thread failed to resume!", __FUNCTION__, mId.string());
2752 return rc;
2753 }
2754
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002755 if (mFakeStreamId == NO_STREAM) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07002756 mRequestBufferSM.onStreamsConfigured();
2757 }
2758
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002759 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002760}
2761
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002762status_t Camera3Device::addFakeStreamLocked() {
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002763 ATRACE_CALL();
2764 status_t res;
2765
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002766 if (mFakeStreamId != NO_STREAM) {
2767 // Should never be adding a second fake stream when one is already
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002768 // active
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002769 SET_ERR_L("%s: Camera %s: A fake stream already exists!",
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002770 __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002771 return INVALID_OPERATION;
2772 }
2773
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002774 ALOGV("%s: Camera %s: Adding a fake stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002775
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002776 sp<Camera3OutputStreamInterface> fakeStream =
2777 new Camera3FakeStream(mNextStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002778
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002779 res = mOutputStreams.add(mNextStreamId, fakeStream);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002780 if (res < 0) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002781 SET_ERR_L("Can't add fake stream to set: %s (%d)", strerror(-res), res);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002782 return res;
2783 }
2784
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002785 mFakeStreamId = mNextStreamId;
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002786 mNextStreamId++;
2787
2788 return OK;
2789}
2790
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002791status_t Camera3Device::tryRemoveFakeStreamLocked() {
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002792 ATRACE_CALL();
2793 status_t res;
2794
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002795 if (mFakeStreamId == NO_STREAM) return OK;
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002796 if (mOutputStreams.size() == 1) return OK;
2797
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002798 ALOGV("%s: Camera %s: Removing the fake stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002799
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002800 // Ok, have a fake stream and there's at least one other output stream,
2801 // so remove the fake
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002802
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002803 sp<Camera3StreamInterface> deletedStream = mOutputStreams.get(mFakeStreamId);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002804 if (deletedStream == nullptr) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002805 SET_ERR_L("Fake stream %d does not appear to exist", mFakeStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002806 return INVALID_OPERATION;
2807 }
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002808 mOutputStreams.remove(mFakeStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002809
2810 // Free up the stream endpoint so that it can be used by some other stream
2811 res = deletedStream->disconnect();
2812 if (res != OK) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002813 SET_ERR_L("Can't disconnect deleted fake stream %d", mFakeStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002814 // fall through since we want to still list the stream as deleted.
2815 }
2816 mDeletedStreams.add(deletedStream);
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002817 mFakeStreamId = NO_STREAM;
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002818
2819 return res;
2820}
2821
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002822void Camera3Device::setErrorState(const char *fmt, ...) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002823 ATRACE_CALL();
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002824 Mutex::Autolock l(mLock);
2825 va_list args;
2826 va_start(args, fmt);
2827
2828 setErrorStateLockedV(fmt, args);
2829
2830 va_end(args);
2831}
2832
2833void Camera3Device::setErrorStateV(const char *fmt, va_list args) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002834 ATRACE_CALL();
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002835 Mutex::Autolock l(mLock);
2836 setErrorStateLockedV(fmt, args);
2837}
2838
2839void Camera3Device::setErrorStateLocked(const char *fmt, ...) {
2840 va_list args;
2841 va_start(args, fmt);
2842
2843 setErrorStateLockedV(fmt, args);
2844
2845 va_end(args);
2846}
2847
2848void Camera3Device::setErrorStateLockedV(const char *fmt, va_list args) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002849 // Print out all error messages to log
2850 String8 errorCause = String8::formatV(fmt, args);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002851 ALOGE("Camera %s: %s", mId.string(), errorCause.string());
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002852
2853 // But only do error state transition steps for the first error
Zhijun Heb05eeae2013-06-06 13:51:22 -07002854 if (mStatus == STATUS_ERROR || mStatus == STATUS_UNINITIALIZED) return;
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002855
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002856 mErrorCause = errorCause;
2857
Yin-Chia Yeh3d145ae2017-07-27 12:47:03 -07002858 if (mRequestThread != nullptr) {
2859 mRequestThread->setPaused(true);
2860 }
Ruben Brunk183f0562015-08-12 12:55:02 -07002861 internalUpdateStatusLocked(STATUS_ERROR);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002862
2863 // Notify upstream about a device error
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002864 sp<NotificationListener> listener = mListener.promote();
2865 if (listener != NULL) {
2866 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002867 CaptureResultExtras());
Shuzhen Wang316781a2020-08-18 18:11:01 -07002868 mSessionStatsBuilder.onDeviceError();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002869 }
2870
2871 // Save stack trace. View by dumping it later.
2872 CameraTraces::saveTrace();
2873 // TODO: consider adding errorCause and client pid/procname
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002874}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002875
2876/**
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002877 * In-flight request management
2878 */
2879
Jianing Weicb0652e2014-03-12 18:29:36 -07002880status_t Camera3Device::registerInFlight(uint32_t frameNumber,
Chien-Yu Chend196d612015-06-22 19:49:01 -07002881 int32_t numBuffers, CaptureResultExtras resultExtras, bool hasInput,
Shuzhen Wang5c22c152017-12-31 17:12:25 -08002882 bool hasAppCallback, nsecs_t maxExpectedDuration,
Shuzhen Wang26abaf42018-08-28 15:41:20 -07002883 std::set<String8>& physicalCameraIds, bool isStillCapture,
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08002884 bool isZslCapture, bool rotateAndCropAuto, const std::set<std::string>& cameraIdsWithZoom,
Shuzhen Wang316781a2020-08-18 18:11:01 -07002885 const SurfaceMap& outputSurfaces, nsecs_t requestTimeNs) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002886 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002887 std::lock_guard<std::mutex> l(mInFlightLock);
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002888
2889 ssize_t res;
Chien-Yu Chend196d612015-06-22 19:49:01 -07002890 res = mInFlightMap.add(frameNumber, InFlightRequest(numBuffers, resultExtras, hasInput,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07002891 hasAppCallback, maxExpectedDuration, physicalCameraIds, isStillCapture, isZslCapture,
Shuzhen Wang316781a2020-08-18 18:11:01 -07002892 rotateAndCropAuto, cameraIdsWithZoom, requestTimeNs, outputSurfaces));
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002893 if (res < 0) return res;
2894
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07002895 if (mInFlightMap.size() == 1) {
Emilian Peev26d975d2018-07-05 14:52:57 +01002896 // Hold a separate dedicated tracker lock to prevent race with disconnect and also
2897 // avoid a deadlock during reprocess requests.
2898 Mutex::Autolock l(mTrackerLock);
Yin-Chia Yeh38dfde52017-06-27 17:13:33 -07002899 if (mStatusTracker != nullptr) {
2900 mStatusTracker->markComponentActive(mInFlightStatusId);
2901 }
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07002902 }
2903
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07002904 mExpectedInflightDuration += maxExpectedDuration;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002905 return OK;
2906}
2907
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002908void Camera3Device::onInflightEntryRemovedLocked(nsecs_t duration) {
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002909 // Indicate idle inFlightMap to the status tracker
2910 if (mInFlightMap.size() == 0) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07002911 mRequestBufferSM.onInflightMapEmpty();
Emilian Peev26d975d2018-07-05 14:52:57 +01002912 // Hold a separate dedicated tracker lock to prevent race with disconnect and also
2913 // avoid a deadlock during reprocess requests.
2914 Mutex::Autolock l(mTrackerLock);
Yin-Chia Yeh38dfde52017-06-27 17:13:33 -07002915 if (mStatusTracker != nullptr) {
2916 mStatusTracker->markComponentIdle(mInFlightStatusId, Fence::NO_FENCE);
2917 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002918 }
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07002919 mExpectedInflightDuration -= duration;
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002920}
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002921
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002922void Camera3Device::checkInflightMapLengthLocked() {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002923 // Validation check - if we have too many in-flight frames with long total inflight duration,
Yin-Chia Yeh99fd0972019-06-27 14:22:44 -07002924 // something has likely gone wrong. This might still be legit only if application send in
2925 // a long burst of long exposure requests.
2926 if (mExpectedInflightDuration > kMinWarnInflightDuration) {
2927 if (!mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() > kInFlightWarnLimit) {
2928 CLOGW("In-flight list too large: %zu, total inflight duration %" PRIu64,
2929 mInFlightMap.size(), mExpectedInflightDuration);
2930 } else if (mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() >
2931 kInFlightWarnLimitHighSpeed) {
2932 CLOGW("In-flight list too large for high speed configuration: %zu,"
2933 "total inflight duration %" PRIu64,
2934 mInFlightMap.size(), mExpectedInflightDuration);
2935 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002936 }
2937}
2938
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002939void Camera3Device::onInflightMapFlushedLocked() {
2940 mExpectedInflightDuration = 0;
2941}
2942
2943void Camera3Device::removeInFlightMapEntryLocked(int idx) {
Jayant Chowdharyd4776262020-06-23 23:45:57 -07002944 ATRACE_HFR_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002945 nsecs_t duration = mInFlightMap.valueAt(idx).maxExpectedDuration;
2946 mInFlightMap.removeItemsAt(idx, 1);
2947
2948 onInflightEntryRemovedLocked(duration);
2949}
2950
2951
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07002952void Camera3Device::flushInflightRequests() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002953 ATRACE_CALL();
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002954 sp<NotificationListener> listener;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002955 {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002956 std::lock_guard<std::mutex> l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002957 listener = mListener.promote();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002958 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002959
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002960 FlushInflightReqStates states {
2961 mId, mInFlightLock, mInFlightMap, mUseHalBufManager,
Shuzhen Wang316781a2020-08-18 18:11:01 -07002962 listener, *this, *mInterface, *this, mSessionStatsBuilder};
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002963
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002964 camera3::flushInflightRequests(states);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002965}
2966
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002967CameraMetadata Camera3Device::getLatestRequestLocked() {
Igor Murashkin1e479c02013-09-06 16:55:14 -07002968 ALOGV("%s", __FUNCTION__);
2969
Igor Murashkin1e479c02013-09-06 16:55:14 -07002970 CameraMetadata retVal;
2971
2972 if (mRequestThread != NULL) {
2973 retVal = mRequestThread->getLatestRequest();
2974 }
2975
Igor Murashkin1e479c02013-09-06 16:55:14 -07002976 return retVal;
2977}
2978
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07002979void Camera3Device::monitorMetadata(TagMonitor::eventSource source,
Shuzhen Wangc2cba122018-05-17 18:10:24 -07002980 int64_t frameNumber, nsecs_t timestamp, const CameraMetadata& metadata,
2981 const std::unordered_map<std::string, CameraMetadata>& physicalMetadata) {
2982
2983 mTagMonitor.monitorMetadata(source, frameNumber, timestamp, metadata,
2984 physicalMetadata);
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07002985}
2986
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002987/**
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002988 * HalInterface inner class methods
2989 */
2990
Yifan Hongf79b5542017-04-11 14:44:25 -07002991Camera3Device::HalInterface::HalInterface(
2992 sp<ICameraDeviceSession> &session,
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08002993 std::shared_ptr<RequestMetadataQueue> queue,
Yin-Chia Yehb978c382019-10-30 00:22:37 -07002994 bool useHalBufManager, bool supportOfflineProcessing) :
Yifan Hongf79b5542017-04-11 14:44:25 -07002995 mHidlSession(session),
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08002996 mRequestMetadataQueue(queue),
Emilian Peev4ec17882019-01-24 17:16:58 -08002997 mUseHalBufManager(useHalBufManager),
Yin-Chia Yehb978c382019-10-30 00:22:37 -07002998 mIsReconfigurationQuerySupported(true),
2999 mSupportOfflineProcessing(supportOfflineProcessing) {
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003000 // Check with hardware service manager if we can downcast these interfaces
3001 // Somewhat expensive, so cache the results at startup
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003002 auto castResult_3_6 = device::V3_6::ICameraDeviceSession::castFrom(mHidlSession);
3003 if (castResult_3_6.isOk()) {
3004 mHidlSession_3_6 = castResult_3_6;
3005 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003006 auto castResult_3_5 = device::V3_5::ICameraDeviceSession::castFrom(mHidlSession);
3007 if (castResult_3_5.isOk()) {
3008 mHidlSession_3_5 = castResult_3_5;
3009 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003010 auto castResult_3_4 = device::V3_4::ICameraDeviceSession::castFrom(mHidlSession);
3011 if (castResult_3_4.isOk()) {
3012 mHidlSession_3_4 = castResult_3_4;
3013 }
3014 auto castResult_3_3 = device::V3_3::ICameraDeviceSession::castFrom(mHidlSession);
3015 if (castResult_3_3.isOk()) {
3016 mHidlSession_3_3 = castResult_3_3;
3017 }
3018}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003019
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003020Camera3Device::HalInterface::HalInterface() :
3021 mUseHalBufManager(false),
3022 mSupportOfflineProcessing(false) {}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003023
3024Camera3Device::HalInterface::HalInterface(const HalInterface& other) :
Yifan Hongf79b5542017-04-11 14:44:25 -07003025 mHidlSession(other.mHidlSession),
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003026 mRequestMetadataQueue(other.mRequestMetadataQueue),
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003027 mUseHalBufManager(other.mUseHalBufManager),
3028 mSupportOfflineProcessing(other.mSupportOfflineProcessing) {}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003029
3030bool Camera3Device::HalInterface::valid() {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003031 return (mHidlSession != nullptr);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003032}
3033
3034void Camera3Device::HalInterface::clear() {
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003035 mHidlSession_3_6.clear();
Emilian Peev644a3e12018-11-23 13:52:39 +00003036 mHidlSession_3_5.clear();
Emilian Peev9e740b02018-01-30 18:28:03 +00003037 mHidlSession_3_4.clear();
3038 mHidlSession_3_3.clear();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003039 mHidlSession.clear();
3040}
3041
3042status_t Camera3Device::HalInterface::constructDefaultRequestSettings(
Emilian Peevf4816702020-04-03 15:44:51 -07003043 camera_request_template_t templateId,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003044 /*out*/ camera_metadata_t **requestTemplate) {
3045 ATRACE_NAME("CameraHal::constructDefaultRequestSettings");
3046 if (!valid()) return INVALID_OPERATION;
3047 status_t res = OK;
3048
Emilian Peev31abd0a2017-05-11 18:37:46 +01003049 common::V1_0::Status status;
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003050
3051 auto requestCallback = [&status, &requestTemplate]
Emilian Peev31abd0a2017-05-11 18:37:46 +01003052 (common::V1_0::Status s, const device::V3_2::CameraMetadata& request) {
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003053 status = s;
3054 if (status == common::V1_0::Status::OK) {
3055 const camera_metadata *r =
3056 reinterpret_cast<const camera_metadata_t*>(request.data());
3057 size_t expectedSize = request.size();
3058 int ret = validate_camera_metadata_structure(r, &expectedSize);
3059 if (ret == OK || ret == CAMERA_METADATA_VALIDATION_SHIFTED) {
3060 *requestTemplate = clone_camera_metadata(r);
3061 if (*requestTemplate == nullptr) {
3062 ALOGE("%s: Unable to clone camera metadata received from HAL",
3063 __FUNCTION__);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003064 status = common::V1_0::Status::INTERNAL_ERROR;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003065 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003066 } else {
3067 ALOGE("%s: Malformed camera metadata received from HAL", __FUNCTION__);
3068 status = common::V1_0::Status::INTERNAL_ERROR;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003069 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003070 }
3071 };
3072 hardware::Return<void> err;
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003073 RequestTemplate id;
3074 switch (templateId) {
Emilian Peevf4816702020-04-03 15:44:51 -07003075 case CAMERA_TEMPLATE_PREVIEW:
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003076 id = RequestTemplate::PREVIEW;
3077 break;
Emilian Peevf4816702020-04-03 15:44:51 -07003078 case CAMERA_TEMPLATE_STILL_CAPTURE:
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003079 id = RequestTemplate::STILL_CAPTURE;
3080 break;
Emilian Peevf4816702020-04-03 15:44:51 -07003081 case CAMERA_TEMPLATE_VIDEO_RECORD:
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003082 id = RequestTemplate::VIDEO_RECORD;
3083 break;
Emilian Peevf4816702020-04-03 15:44:51 -07003084 case CAMERA_TEMPLATE_VIDEO_SNAPSHOT:
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003085 id = RequestTemplate::VIDEO_SNAPSHOT;
3086 break;
Emilian Peevf4816702020-04-03 15:44:51 -07003087 case CAMERA_TEMPLATE_ZERO_SHUTTER_LAG:
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003088 id = RequestTemplate::ZERO_SHUTTER_LAG;
3089 break;
Emilian Peevf4816702020-04-03 15:44:51 -07003090 case CAMERA_TEMPLATE_MANUAL:
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003091 id = RequestTemplate::MANUAL;
3092 break;
3093 default:
3094 // Unknown template ID, or this HAL is too old to support it
3095 return BAD_VALUE;
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003096 }
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003097 err = mHidlSession->constructDefaultRequestSettings(id, requestCallback);
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003098
Emilian Peev31abd0a2017-05-11 18:37:46 +01003099 if (!err.isOk()) {
3100 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3101 res = DEAD_OBJECT;
3102 } else {
3103 res = CameraProviderManager::mapToStatusT(status);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003104 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003105
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003106 return res;
3107}
3108
Emilian Peev4ec17882019-01-24 17:16:58 -08003109bool Camera3Device::HalInterface::isReconfigurationRequired(CameraMetadata& oldSessionParams,
3110 CameraMetadata& newSessionParams) {
3111 // We do reconfiguration by default;
3112 bool ret = true;
3113 if ((mHidlSession_3_5 != nullptr) && mIsReconfigurationQuerySupported) {
3114 android::hardware::hidl_vec<uint8_t> oldParams, newParams;
3115 camera_metadata_t* oldSessioMeta = const_cast<camera_metadata_t*>(
3116 oldSessionParams.getAndLock());
3117 camera_metadata_t* newSessioMeta = const_cast<camera_metadata_t*>(
3118 newSessionParams.getAndLock());
3119 oldParams.setToExternal(reinterpret_cast<uint8_t*>(oldSessioMeta),
3120 get_camera_metadata_size(oldSessioMeta));
3121 newParams.setToExternal(reinterpret_cast<uint8_t*>(newSessioMeta),
3122 get_camera_metadata_size(newSessioMeta));
3123 hardware::camera::common::V1_0::Status callStatus;
3124 bool required;
3125 auto hidlCb = [&callStatus, &required] (hardware::camera::common::V1_0::Status s,
3126 bool requiredFlag) {
3127 callStatus = s;
3128 required = requiredFlag;
3129 };
3130 auto err = mHidlSession_3_5->isReconfigurationRequired(oldParams, newParams, hidlCb);
3131 oldSessionParams.unlock(oldSessioMeta);
3132 newSessionParams.unlock(newSessioMeta);
3133 if (err.isOk()) {
3134 switch (callStatus) {
3135 case hardware::camera::common::V1_0::Status::OK:
3136 ret = required;
3137 break;
3138 case hardware::camera::common::V1_0::Status::METHOD_NOT_SUPPORTED:
3139 mIsReconfigurationQuerySupported = false;
3140 ret = true;
3141 break;
3142 default:
3143 ALOGV("%s: Reconfiguration query failed: %d", __FUNCTION__, callStatus);
3144 ret = true;
3145 }
3146 } else {
3147 ALOGE("%s: Unexpected binder error: %s", __FUNCTION__, err.description().c_str());
3148 ret = true;
3149 }
3150 }
3151
3152 return ret;
3153}
3154
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003155status_t Camera3Device::HalInterface::configureStreams(const camera_metadata_t *sessionParams,
Emilian Peevf4816702020-04-03 15:44:51 -07003156 camera_stream_configuration *config, const std::vector<uint32_t>& bufferSizes) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003157 ATRACE_NAME("CameraHal::configureStreams");
3158 if (!valid()) return INVALID_OPERATION;
3159 status_t res = OK;
3160
Emilian Peev31abd0a2017-05-11 18:37:46 +01003161 // Convert stream config to HIDL
3162 std::set<int> activeStreams;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003163 device::V3_2::StreamConfiguration requestedConfiguration3_2;
3164 device::V3_4::StreamConfiguration requestedConfiguration3_4;
3165 requestedConfiguration3_2.streams.resize(config->num_streams);
3166 requestedConfiguration3_4.streams.resize(config->num_streams);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003167 for (size_t i = 0; i < config->num_streams; i++) {
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003168 device::V3_2::Stream &dst3_2 = requestedConfiguration3_2.streams[i];
3169 device::V3_4::Stream &dst3_4 = requestedConfiguration3_4.streams[i];
Emilian Peevf4816702020-04-03 15:44:51 -07003170 camera3::camera_stream_t *src = config->streams[i];
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003171
Emilian Peev31abd0a2017-05-11 18:37:46 +01003172 Camera3Stream* cam3stream = Camera3Stream::cast(src);
3173 cam3stream->setBufferFreedListener(this);
3174 int streamId = cam3stream->getId();
3175 StreamType streamType;
3176 switch (src->stream_type) {
Emilian Peevf4816702020-04-03 15:44:51 -07003177 case CAMERA_STREAM_OUTPUT:
Emilian Peev31abd0a2017-05-11 18:37:46 +01003178 streamType = StreamType::OUTPUT;
3179 break;
Emilian Peevf4816702020-04-03 15:44:51 -07003180 case CAMERA_STREAM_INPUT:
Emilian Peev31abd0a2017-05-11 18:37:46 +01003181 streamType = StreamType::INPUT;
3182 break;
3183 default:
3184 ALOGE("%s: Stream %d: Unsupported stream type %d",
3185 __FUNCTION__, streamId, config->streams[i]->stream_type);
3186 return BAD_VALUE;
3187 }
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003188 dst3_2.id = streamId;
3189 dst3_2.streamType = streamType;
3190 dst3_2.width = src->width;
3191 dst3_2.height = src->height;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003192 dst3_2.usage = mapToConsumerUsage(cam3stream->getUsage());
Emilian Peevf4816702020-04-03 15:44:51 -07003193 dst3_2.rotation = mapToStreamRotation((camera_stream_rotation_t) src->rotation);
Shuzhen Wang92653952019-05-07 15:11:43 -07003194 // For HidlSession version 3.5 or newer, the format and dataSpace sent
3195 // to HAL are original, not the overriden ones.
3196 if (mHidlSession_3_5 != nullptr) {
3197 dst3_2.format = mapToPixelFormat(cam3stream->isFormatOverridden() ?
3198 cam3stream->getOriginalFormat() : src->format);
3199 dst3_2.dataSpace = mapToHidlDataspace(cam3stream->isDataSpaceOverridden() ?
3200 cam3stream->getOriginalDataSpace() : src->data_space);
3201 } else {
3202 dst3_2.format = mapToPixelFormat(src->format);
3203 dst3_2.dataSpace = mapToHidlDataspace(src->data_space);
3204 }
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003205 dst3_4.v3_2 = dst3_2;
Emilian Peev192ee832018-01-31 14:46:47 +00003206 dst3_4.bufferSize = bufferSizes[i];
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003207 if (src->physical_camera_id != nullptr) {
3208 dst3_4.physicalCameraId = src->physical_camera_id;
3209 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003210
3211 activeStreams.insert(streamId);
3212 // Create Buffer ID map if necessary
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003213 mBufferRecords.tryCreateBufferCache(streamId);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003214 }
3215 // remove BufferIdMap for deleted streams
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003216 mBufferRecords.removeInactiveBufferCaches(activeStreams);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003217
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003218 StreamConfigurationMode operationMode;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003219 res = mapToStreamConfigurationMode(
Emilian Peevf4816702020-04-03 15:44:51 -07003220 (camera_stream_configuration_mode_t) config->operation_mode,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003221 /*out*/ &operationMode);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003222 if (res != OK) {
3223 return res;
3224 }
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003225 requestedConfiguration3_2.operationMode = operationMode;
3226 requestedConfiguration3_4.operationMode = operationMode;
3227 requestedConfiguration3_4.sessionParams.setToExternal(
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003228 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(sessionParams)),
3229 get_camera_metadata_size(sessionParams));
3230
Emilian Peev31abd0a2017-05-11 18:37:46 +01003231 // Invoke configureStreams
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003232 device::V3_3::HalStreamConfiguration finalConfiguration;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003233 device::V3_4::HalStreamConfiguration finalConfiguration3_4;
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003234 device::V3_6::HalStreamConfiguration finalConfiguration3_6;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003235 common::V1_0::Status status;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003236
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003237 auto configStream34Cb = [&status, &finalConfiguration3_4]
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003238 (common::V1_0::Status s, const device::V3_4::HalStreamConfiguration& halConfiguration) {
3239 finalConfiguration3_4 = halConfiguration;
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003240 status = s;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003241 };
3242
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003243 auto configStream36Cb = [&status, &finalConfiguration3_6]
3244 (common::V1_0::Status s, const device::V3_6::HalStreamConfiguration& halConfiguration) {
3245 finalConfiguration3_6 = halConfiguration;
3246 status = s;
3247 };
3248
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003249 auto postprocConfigStream34 = [&finalConfiguration, &finalConfiguration3_4]
3250 (hardware::Return<void>& err) -> status_t {
3251 if (!err.isOk()) {
3252 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3253 return DEAD_OBJECT;
3254 }
3255 finalConfiguration.streams.resize(finalConfiguration3_4.streams.size());
3256 for (size_t i = 0; i < finalConfiguration3_4.streams.size(); i++) {
3257 finalConfiguration.streams[i] = finalConfiguration3_4.streams[i].v3_3;
3258 }
3259 return OK;
3260 };
3261
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003262 auto postprocConfigStream36 = [&finalConfiguration, &finalConfiguration3_6]
3263 (hardware::Return<void>& err) -> status_t {
3264 if (!err.isOk()) {
3265 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3266 return DEAD_OBJECT;
3267 }
3268 finalConfiguration.streams.resize(finalConfiguration3_6.streams.size());
3269 for (size_t i = 0; i < finalConfiguration3_6.streams.size(); i++) {
3270 finalConfiguration.streams[i] = finalConfiguration3_6.streams[i].v3_4.v3_3;
3271 }
3272 return OK;
3273 };
3274
Shuzhen Wang92653952019-05-07 15:11:43 -07003275 // See which version of HAL we have
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003276 if (mHidlSession_3_6 != nullptr) {
3277 ALOGV("%s: v3.6 device found", __FUNCTION__);
3278 device::V3_5::StreamConfiguration requestedConfiguration3_5;
3279 requestedConfiguration3_5.v3_4 = requestedConfiguration3_4;
3280 requestedConfiguration3_5.streamConfigCounter = mNextStreamConfigCounter++;
3281 auto err = mHidlSession_3_6->configureStreams_3_6(
3282 requestedConfiguration3_5, configStream36Cb);
3283 res = postprocConfigStream36(err);
3284 if (res != OK) {
3285 return res;
3286 }
3287 } else if (mHidlSession_3_5 != nullptr) {
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003288 ALOGV("%s: v3.5 device found", __FUNCTION__);
3289 device::V3_5::StreamConfiguration requestedConfiguration3_5;
3290 requestedConfiguration3_5.v3_4 = requestedConfiguration3_4;
3291 requestedConfiguration3_5.streamConfigCounter = mNextStreamConfigCounter++;
3292 auto err = mHidlSession_3_5->configureStreams_3_5(
3293 requestedConfiguration3_5, configStream34Cb);
3294 res = postprocConfigStream34(err);
3295 if (res != OK) {
3296 return res;
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003297 }
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003298 } else if (mHidlSession_3_4 != nullptr) {
3299 // We do; use v3.4 for the call
3300 ALOGV("%s: v3.4 device found", __FUNCTION__);
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003301 auto err = mHidlSession_3_4->configureStreams_3_4(
3302 requestedConfiguration3_4, configStream34Cb);
3303 res = postprocConfigStream34(err);
3304 if (res != OK) {
3305 return res;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003306 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003307 } else if (mHidlSession_3_3 != nullptr) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003308 // We do; use v3.3 for the call
3309 ALOGV("%s: v3.3 device found", __FUNCTION__);
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003310 auto err = mHidlSession_3_3->configureStreams_3_3(requestedConfiguration3_2,
Emilian Peev31abd0a2017-05-11 18:37:46 +01003311 [&status, &finalConfiguration]
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003312 (common::V1_0::Status s, const device::V3_3::HalStreamConfiguration& halConfiguration) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003313 finalConfiguration = halConfiguration;
3314 status = s;
3315 });
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003316 if (!err.isOk()) {
3317 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3318 return DEAD_OBJECT;
3319 }
3320 } else {
3321 // We don't; use v3.2 call and construct a v3.3 HalStreamConfiguration
3322 ALOGV("%s: v3.2 device found", __FUNCTION__);
3323 HalStreamConfiguration finalConfiguration_3_2;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003324 auto err = mHidlSession->configureStreams(requestedConfiguration3_2,
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003325 [&status, &finalConfiguration_3_2]
3326 (common::V1_0::Status s, const HalStreamConfiguration& halConfiguration) {
3327 finalConfiguration_3_2 = halConfiguration;
3328 status = s;
3329 });
3330 if (!err.isOk()) {
3331 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3332 return DEAD_OBJECT;
3333 }
3334 finalConfiguration.streams.resize(finalConfiguration_3_2.streams.size());
3335 for (size_t i = 0; i < finalConfiguration_3_2.streams.size(); i++) {
3336 finalConfiguration.streams[i].v3_2 = finalConfiguration_3_2.streams[i];
3337 finalConfiguration.streams[i].overrideDataSpace =
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003338 requestedConfiguration3_2.streams[i].dataSpace;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003339 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003340 }
3341
3342 if (status != common::V1_0::Status::OK ) {
3343 return CameraProviderManager::mapToStatusT(status);
3344 }
3345
3346 // And convert output stream configuration from HIDL
3347
3348 for (size_t i = 0; i < config->num_streams; i++) {
Emilian Peevf4816702020-04-03 15:44:51 -07003349 camera3::camera_stream_t *dst = config->streams[i];
Emilian Peev31abd0a2017-05-11 18:37:46 +01003350 int streamId = Camera3Stream::cast(dst)->getId();
3351
3352 // Start scan at i, with the assumption that the stream order matches
3353 size_t realIdx = i;
3354 bool found = false;
Eino-Ville Talvala370875f2019-04-12 12:40:27 -07003355 size_t halStreamCount = finalConfiguration.streams.size();
3356 for (size_t idx = 0; idx < halStreamCount; idx++) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003357 if (finalConfiguration.streams[realIdx].v3_2.id == streamId) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003358 found = true;
3359 break;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003360 }
Eino-Ville Talvala370875f2019-04-12 12:40:27 -07003361 realIdx = (realIdx >= halStreamCount - 1) ? 0 : realIdx + 1;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003362 }
3363 if (!found) {
3364 ALOGE("%s: Stream %d not found in stream configuration response from HAL",
3365 __FUNCTION__, streamId);
3366 return INVALID_OPERATION;
3367 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003368 device::V3_3::HalStream &src = finalConfiguration.streams[realIdx];
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003369 device::V3_6::HalStream &src_36 = finalConfiguration3_6.streams[realIdx];
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003370
Emilian Peev710c1422017-08-30 11:19:38 +01003371 Camera3Stream* dstStream = Camera3Stream::cast(dst);
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003372 int overrideFormat = mapToFrameworkFormat(src.v3_2.overrideFormat);
3373 android_dataspace overrideDataSpace = mapToFrameworkDataspace(src.overrideDataSpace);
3374
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003375 if (mHidlSession_3_6 != nullptr) {
3376 dstStream->setOfflineProcessingSupport(src_36.supportOffline);
3377 }
3378
Yin-Chia Yeh90667662019-07-01 15:45:00 -07003379 if (dstStream->getOriginalFormat() != HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
Shuzhen Wang92653952019-05-07 15:11:43 -07003380 dstStream->setFormatOverride(false);
3381 dstStream->setDataSpaceOverride(false);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003382 if (dst->format != overrideFormat) {
3383 ALOGE("%s: Stream %d: Format override not allowed for format 0x%x", __FUNCTION__,
3384 streamId, dst->format);
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003385 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003386 if (dst->data_space != overrideDataSpace) {
3387 ALOGE("%s: Stream %d: DataSpace override not allowed for format 0x%x", __FUNCTION__,
3388 streamId, dst->format);
3389 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003390 } else {
Shuzhen Wang92653952019-05-07 15:11:43 -07003391 bool needFormatOverride =
3392 requestedConfiguration3_2.streams[i].format != src.v3_2.overrideFormat;
3393 bool needDataspaceOverride =
3394 requestedConfiguration3_2.streams[i].dataSpace != src.overrideDataSpace;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003395 // Override allowed with IMPLEMENTATION_DEFINED
Shuzhen Wang92653952019-05-07 15:11:43 -07003396 dstStream->setFormatOverride(needFormatOverride);
3397 dstStream->setDataSpaceOverride(needDataspaceOverride);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003398 dst->format = overrideFormat;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003399 dst->data_space = overrideDataSpace;
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003400 }
3401
Emilian Peevf4816702020-04-03 15:44:51 -07003402 if (dst->stream_type == CAMERA_STREAM_INPUT) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003403 if (src.v3_2.producerUsage != 0) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003404 ALOGE("%s: Stream %d: INPUT streams must have 0 for producer usage",
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003405 __FUNCTION__, streamId);
3406 return INVALID_OPERATION;
3407 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003408 dstStream->setUsage(
3409 mapConsumerToFrameworkUsage(src.v3_2.consumerUsage));
Emilian Peev31abd0a2017-05-11 18:37:46 +01003410 } else {
3411 // OUTPUT
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003412 if (src.v3_2.consumerUsage != 0) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003413 ALOGE("%s: Stream %d: OUTPUT streams must have 0 for consumer usage",
3414 __FUNCTION__, streamId);
3415 return INVALID_OPERATION;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003416 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003417 dstStream->setUsage(
3418 mapProducerToFrameworkUsage(src.v3_2.producerUsage));
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003419 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003420 dst->max_buffers = src.v3_2.maxBuffers;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003421 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003422
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003423 return res;
3424}
3425
Emilian Peevf4816702020-04-03 15:44:51 -07003426status_t Camera3Device::HalInterface::wrapAsHidlRequest(camera_capture_request_t* request,
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003427 /*out*/device::V3_2::CaptureRequest* captureRequest,
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003428 /*out*/std::vector<native_handle_t*>* handlesCreated,
3429 /*out*/std::vector<std::pair<int32_t, int32_t>>* inflightBuffers) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003430 ATRACE_CALL();
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003431 if (captureRequest == nullptr || handlesCreated == nullptr || inflightBuffers == nullptr) {
3432 ALOGE("%s: captureRequest (%p), handlesCreated (%p), and inflightBuffers(%p) "
3433 "must not be null", __FUNCTION__, captureRequest, handlesCreated, inflightBuffers);
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003434 return BAD_VALUE;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003435 }
3436
3437 captureRequest->frameNumber = request->frame_number;
Yifan Hongf79b5542017-04-11 14:44:25 -07003438
3439 captureRequest->fmqSettingsSize = 0;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003440
3441 {
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003442 if (request->input_buffer != nullptr) {
3443 int32_t streamId = Camera3Stream::cast(request->input_buffer->stream)->getId();
3444 buffer_handle_t buf = *(request->input_buffer->buffer);
3445 auto pair = getBufferId(buf, streamId);
3446 bool isNewBuffer = pair.first;
3447 uint64_t bufferId = pair.second;
3448 captureRequest->inputBuffer.streamId = streamId;
3449 captureRequest->inputBuffer.bufferId = bufferId;
3450 captureRequest->inputBuffer.buffer = (isNewBuffer) ? buf : nullptr;
3451 captureRequest->inputBuffer.status = BufferStatus::OK;
3452 native_handle_t *acquireFence = nullptr;
3453 if (request->input_buffer->acquire_fence != -1) {
3454 acquireFence = native_handle_create(1,0);
3455 acquireFence->data[0] = request->input_buffer->acquire_fence;
3456 handlesCreated->push_back(acquireFence);
3457 }
3458 captureRequest->inputBuffer.acquireFence = acquireFence;
3459 captureRequest->inputBuffer.releaseFence = nullptr;
3460
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003461 mBufferRecords.pushInflightBuffer(captureRequest->frameNumber, streamId,
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003462 request->input_buffer->buffer);
3463 inflightBuffers->push_back(std::make_pair(captureRequest->frameNumber, streamId));
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003464 } else {
3465 captureRequest->inputBuffer.streamId = -1;
3466 captureRequest->inputBuffer.bufferId = BUFFER_ID_NO_BUFFER;
3467 }
3468
3469 captureRequest->outputBuffers.resize(request->num_output_buffers);
3470 for (size_t i = 0; i < request->num_output_buffers; i++) {
Emilian Peevf4816702020-04-03 15:44:51 -07003471 const camera_stream_buffer_t *src = request->output_buffers + i;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003472 StreamBuffer &dst = captureRequest->outputBuffers[i];
3473 int32_t streamId = Camera3Stream::cast(src->stream)->getId();
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003474 if (src->buffer != nullptr) {
3475 buffer_handle_t buf = *(src->buffer);
3476 auto pair = getBufferId(buf, streamId);
3477 bool isNewBuffer = pair.first;
3478 dst.bufferId = pair.second;
3479 dst.buffer = isNewBuffer ? buf : nullptr;
3480 native_handle_t *acquireFence = nullptr;
3481 if (src->acquire_fence != -1) {
3482 acquireFence = native_handle_create(1,0);
3483 acquireFence->data[0] = src->acquire_fence;
3484 handlesCreated->push_back(acquireFence);
3485 }
3486 dst.acquireFence = acquireFence;
3487 } else if (mUseHalBufManager) {
3488 // HAL buffer management path
3489 dst.bufferId = BUFFER_ID_NO_BUFFER;
3490 dst.buffer = nullptr;
3491 dst.acquireFence = nullptr;
3492 } else {
3493 ALOGE("%s: cannot send a null buffer in capture request!", __FUNCTION__);
3494 return BAD_VALUE;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003495 }
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003496 dst.streamId = streamId;
3497 dst.status = BufferStatus::OK;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003498 dst.releaseFence = nullptr;
3499
Yin-Chia Yeh5f840f82019-03-05 11:59:04 -08003500 // Output buffers are empty when using HAL buffer manager
3501 if (!mUseHalBufManager) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003502 mBufferRecords.pushInflightBuffer(
3503 captureRequest->frameNumber, streamId, src->buffer);
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003504 inflightBuffers->push_back(std::make_pair(captureRequest->frameNumber, streamId));
Yin-Chia Yeh5f840f82019-03-05 11:59:04 -08003505 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003506 }
3507 }
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003508 return OK;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003509}
3510
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003511void Camera3Device::HalInterface::cleanupNativeHandles(
3512 std::vector<native_handle_t*> *handles, bool closeFd) {
3513 if (handles == nullptr) {
3514 return;
3515 }
3516 if (closeFd) {
3517 for (auto& handle : *handles) {
3518 native_handle_close(handle);
3519 }
3520 }
3521 for (auto& handle : *handles) {
3522 native_handle_delete(handle);
3523 }
3524 handles->clear();
3525 return;
3526}
3527
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003528status_t Camera3Device::HalInterface::processBatchCaptureRequests(
Emilian Peevf4816702020-04-03 15:44:51 -07003529 std::vector<camera_capture_request_t*>& requests,/*out*/uint32_t* numRequestProcessed) {
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003530 ATRACE_NAME("CameraHal::processBatchCaptureRequests");
3531 if (!valid()) return INVALID_OPERATION;
3532
Emilian Peevaebbe412018-01-15 13:53:24 +00003533 sp<device::V3_4::ICameraDeviceSession> hidlSession_3_4;
3534 auto castResult_3_4 = device::V3_4::ICameraDeviceSession::castFrom(mHidlSession);
3535 if (castResult_3_4.isOk()) {
3536 hidlSession_3_4 = castResult_3_4;
3537 }
3538
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003539 hardware::hidl_vec<device::V3_2::CaptureRequest> captureRequests;
Emilian Peevaebbe412018-01-15 13:53:24 +00003540 hardware::hidl_vec<device::V3_4::CaptureRequest> captureRequests_3_4;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003541 size_t batchSize = requests.size();
Emilian Peevaebbe412018-01-15 13:53:24 +00003542 if (hidlSession_3_4 != nullptr) {
3543 captureRequests_3_4.resize(batchSize);
3544 } else {
3545 captureRequests.resize(batchSize);
3546 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003547 std::vector<native_handle_t*> handlesCreated;
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003548 std::vector<std::pair<int32_t, int32_t>> inflightBuffers;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003549
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003550 status_t res = OK;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003551 for (size_t i = 0; i < batchSize; i++) {
Emilian Peevaebbe412018-01-15 13:53:24 +00003552 if (hidlSession_3_4 != nullptr) {
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003553 res = wrapAsHidlRequest(requests[i], /*out*/&captureRequests_3_4[i].v3_2,
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003554 /*out*/&handlesCreated, /*out*/&inflightBuffers);
Emilian Peevaebbe412018-01-15 13:53:24 +00003555 } else {
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003556 res = wrapAsHidlRequest(requests[i], /*out*/&captureRequests[i],
3557 /*out*/&handlesCreated, /*out*/&inflightBuffers);
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003558 }
3559 if (res != OK) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003560 mBufferRecords.popInflightBuffers(inflightBuffers);
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003561 cleanupNativeHandles(&handlesCreated);
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003562 return res;
Emilian Peevaebbe412018-01-15 13:53:24 +00003563 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003564 }
3565
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003566 std::vector<device::V3_2::BufferCache> cachesToRemove;
3567 {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003568 std::lock_guard<std::mutex> lock(mFreedBuffersLock);
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003569 for (auto& pair : mFreedBuffers) {
3570 // The stream might have been removed since onBufferFreed
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003571 if (mBufferRecords.isStreamCached(pair.first)) {
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003572 cachesToRemove.push_back({pair.first, pair.second});
3573 }
3574 }
3575 mFreedBuffers.clear();
3576 }
3577
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003578 common::V1_0::Status status = common::V1_0::Status::INTERNAL_ERROR;
3579 *numRequestProcessed = 0;
Yifan Hongf79b5542017-04-11 14:44:25 -07003580
3581 // Write metadata to FMQ.
3582 for (size_t i = 0; i < batchSize; i++) {
Emilian Peevf4816702020-04-03 15:44:51 -07003583 camera_capture_request_t* request = requests[i];
Emilian Peevaebbe412018-01-15 13:53:24 +00003584 device::V3_2::CaptureRequest* captureRequest;
3585 if (hidlSession_3_4 != nullptr) {
3586 captureRequest = &captureRequests_3_4[i].v3_2;
3587 } else {
3588 captureRequest = &captureRequests[i];
3589 }
Yifan Hongf79b5542017-04-11 14:44:25 -07003590
3591 if (request->settings != nullptr) {
3592 size_t settingsSize = get_camera_metadata_size(request->settings);
3593 if (mRequestMetadataQueue != nullptr && mRequestMetadataQueue->write(
3594 reinterpret_cast<const uint8_t*>(request->settings), settingsSize)) {
3595 captureRequest->settings.resize(0);
3596 captureRequest->fmqSettingsSize = settingsSize;
3597 } else {
3598 if (mRequestMetadataQueue != nullptr) {
3599 ALOGW("%s: couldn't utilize fmq, fallback to hwbinder", __FUNCTION__);
3600 }
3601 captureRequest->settings.setToExternal(
3602 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(request->settings)),
3603 get_camera_metadata_size(request->settings));
3604 captureRequest->fmqSettingsSize = 0u;
3605 }
3606 } else {
3607 // A null request settings maps to a size-0 CameraMetadata
3608 captureRequest->settings.resize(0);
3609 captureRequest->fmqSettingsSize = 0u;
3610 }
Emilian Peevaebbe412018-01-15 13:53:24 +00003611
3612 if (hidlSession_3_4 != nullptr) {
3613 captureRequests_3_4[i].physicalCameraSettings.resize(request->num_physcam_settings);
3614 for (size_t j = 0; j < request->num_physcam_settings; j++) {
Emilian Peev00420d22018-02-05 21:33:13 +00003615 if (request->physcam_settings != nullptr) {
3616 size_t settingsSize = get_camera_metadata_size(request->physcam_settings[j]);
3617 if (mRequestMetadataQueue != nullptr && mRequestMetadataQueue->write(
3618 reinterpret_cast<const uint8_t*>(request->physcam_settings[j]),
3619 settingsSize)) {
3620 captureRequests_3_4[i].physicalCameraSettings[j].settings.resize(0);
3621 captureRequests_3_4[i].physicalCameraSettings[j].fmqSettingsSize =
3622 settingsSize;
3623 } else {
3624 if (mRequestMetadataQueue != nullptr) {
3625 ALOGW("%s: couldn't utilize fmq, fallback to hwbinder", __FUNCTION__);
3626 }
3627 captureRequests_3_4[i].physicalCameraSettings[j].settings.setToExternal(
3628 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(
3629 request->physcam_settings[j])),
3630 get_camera_metadata_size(request->physcam_settings[j]));
3631 captureRequests_3_4[i].physicalCameraSettings[j].fmqSettingsSize = 0u;
Emilian Peevaebbe412018-01-15 13:53:24 +00003632 }
Emilian Peev00420d22018-02-05 21:33:13 +00003633 } else {
Emilian Peevaebbe412018-01-15 13:53:24 +00003634 captureRequests_3_4[i].physicalCameraSettings[j].fmqSettingsSize = 0u;
Emilian Peev00420d22018-02-05 21:33:13 +00003635 captureRequests_3_4[i].physicalCameraSettings[j].settings.resize(0);
Emilian Peevaebbe412018-01-15 13:53:24 +00003636 }
3637 captureRequests_3_4[i].physicalCameraSettings[j].physicalCameraId =
3638 request->physcam_id[j];
3639 }
3640 }
Yifan Hongf79b5542017-04-11 14:44:25 -07003641 }
Emilian Peevaebbe412018-01-15 13:53:24 +00003642
3643 hardware::details::return_status err;
Jayant Chowdharyc8d581e2018-07-16 14:46:23 -07003644 auto resultCallback =
3645 [&status, &numRequestProcessed] (auto s, uint32_t n) {
3646 status = s;
3647 *numRequestProcessed = n;
3648 };
Emilian Peevaebbe412018-01-15 13:53:24 +00003649 if (hidlSession_3_4 != nullptr) {
3650 err = hidlSession_3_4->processCaptureRequest_3_4(captureRequests_3_4, cachesToRemove,
Jayant Chowdharyc8d581e2018-07-16 14:46:23 -07003651 resultCallback);
Emilian Peevaebbe412018-01-15 13:53:24 +00003652 } else {
3653 err = mHidlSession->processCaptureRequest(captureRequests, cachesToRemove,
Jayant Chowdharyc8d581e2018-07-16 14:46:23 -07003654 resultCallback);
Emilian Peevaebbe412018-01-15 13:53:24 +00003655 }
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -07003656 if (!err.isOk()) {
3657 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003658 status = common::V1_0::Status::CAMERA_DISCONNECTED;
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -07003659 }
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003660
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003661 if (status == common::V1_0::Status::OK && *numRequestProcessed != batchSize) {
3662 ALOGE("%s: processCaptureRequest returns OK but processed %d/%zu requests",
3663 __FUNCTION__, *numRequestProcessed, batchSize);
3664 status = common::V1_0::Status::INTERNAL_ERROR;
3665 }
3666
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003667 res = CameraProviderManager::mapToStatusT(status);
3668 if (res == OK) {
3669 if (mHidlSession->isRemote()) {
3670 // Only close acquire fence FDs when the HIDL transaction succeeds (so the FDs have been
3671 // sent to camera HAL processes)
3672 cleanupNativeHandles(&handlesCreated, /*closeFd*/true);
3673 } else {
3674 // In passthrough mode the FDs are now owned by HAL
3675 cleanupNativeHandles(&handlesCreated);
3676 }
3677 } else {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003678 mBufferRecords.popInflightBuffers(inflightBuffers);
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003679 cleanupNativeHandles(&handlesCreated);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003680 }
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003681 return res;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003682}
3683
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003684status_t Camera3Device::HalInterface::flush() {
3685 ATRACE_NAME("CameraHal::flush");
3686 if (!valid()) return INVALID_OPERATION;
3687 status_t res = OK;
3688
Emilian Peev31abd0a2017-05-11 18:37:46 +01003689 auto err = mHidlSession->flush();
3690 if (!err.isOk()) {
3691 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3692 res = DEAD_OBJECT;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003693 } else {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003694 res = CameraProviderManager::mapToStatusT(err);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003695 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003696
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003697 return res;
3698}
3699
Emilian Peev31abd0a2017-05-11 18:37:46 +01003700status_t Camera3Device::HalInterface::dump(int /*fd*/) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003701 ATRACE_NAME("CameraHal::dump");
3702 if (!valid()) return INVALID_OPERATION;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003703
Emilian Peev31abd0a2017-05-11 18:37:46 +01003704 // Handled by CameraProviderManager::dump
3705
3706 return OK;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003707}
3708
3709status_t Camera3Device::HalInterface::close() {
3710 ATRACE_NAME("CameraHal::close()");
3711 if (!valid()) return INVALID_OPERATION;
3712 status_t res = OK;
3713
Emilian Peev31abd0a2017-05-11 18:37:46 +01003714 auto err = mHidlSession->close();
3715 // Interface will be dead shortly anyway, so don't log errors
3716 if (!err.isOk()) {
3717 res = DEAD_OBJECT;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003718 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003719
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003720 return res;
3721}
3722
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003723void Camera3Device::HalInterface::signalPipelineDrain(const std::vector<int>& streamIds) {
3724 ATRACE_NAME("CameraHal::signalPipelineDrain");
3725 if (!valid() || mHidlSession_3_5 == nullptr) {
3726 ALOGE("%s called on invalid camera!", __FUNCTION__);
3727 return;
3728 }
3729
Yin-Chia Yehc300a072019-02-13 14:56:57 -08003730 auto err = mHidlSession_3_5->signalStreamFlush(streamIds, mNextStreamConfigCounter - 1);
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003731 if (!err.isOk()) {
3732 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3733 return;
3734 }
3735}
3736
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003737status_t Camera3Device::HalInterface::switchToOffline(
3738 const std::vector<int32_t>& streamsToKeep,
3739 /*out*/hardware::camera::device::V3_6::CameraOfflineSessionInfo* offlineSessionInfo,
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003740 /*out*/sp<hardware::camera::device::V3_6::ICameraOfflineSession>* offlineSession,
3741 /*out*/camera3::BufferRecords* bufferRecords) {
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003742 ATRACE_NAME("CameraHal::switchToOffline");
3743 if (!valid() || mHidlSession_3_6 == nullptr) {
3744 ALOGE("%s called on invalid camera!", __FUNCTION__);
3745 return INVALID_OPERATION;
3746 }
3747
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003748 if (offlineSessionInfo == nullptr || offlineSession == nullptr || bufferRecords == nullptr) {
3749 ALOGE("%s: output arguments must not be null!", __FUNCTION__);
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003750 return INVALID_OPERATION;
3751 }
3752
3753 common::V1_0::Status status = common::V1_0::Status::INTERNAL_ERROR;
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003754 auto resultCallback =
3755 [&status, &offlineSessionInfo, &offlineSession] (auto s, auto info, auto session) {
3756 status = s;
3757 *offlineSessionInfo = info;
3758 *offlineSession = session;
3759 };
3760 auto err = mHidlSession_3_6->switchToOffline(streamsToKeep, resultCallback);
3761
3762 if (!err.isOk()) {
3763 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3764 return DEAD_OBJECT;
3765 }
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003766
3767 status_t ret = CameraProviderManager::mapToStatusT(status);
3768 if (ret != OK) {
3769 return ret;
3770 }
3771
3772 // TODO: assert no ongoing requestBuffer/returnBuffer call here
3773 // TODO: update RequestBufferStateMachine to block requestBuffer/returnBuffer once HAL
3774 // returns from switchToOffline.
3775
3776
3777 // Validate buffer caches
3778 std::vector<int32_t> streams;
3779 streams.reserve(offlineSessionInfo->offlineStreams.size());
3780 for (auto offlineStream : offlineSessionInfo->offlineStreams) {
3781 int32_t id = offlineStream.id;
3782 streams.push_back(id);
3783 // Verify buffer caches
3784 std::vector<uint64_t> bufIds(offlineStream.circulatingBufferIds.begin(),
3785 offlineStream.circulatingBufferIds.end());
3786 if (!verifyBufferIds(id, bufIds)) {
3787 ALOGE("%s: stream ID %d buffer cache records mismatch!", __FUNCTION__, id);
3788 return UNKNOWN_ERROR;
3789 }
3790 }
3791
3792 // Move buffer records
3793 bufferRecords->takeBufferCaches(mBufferRecords, streams);
3794 bufferRecords->takeInflightBufferMap(mBufferRecords);
3795 bufferRecords->takeRequestedBufferMap(mBufferRecords);
3796 return ret;
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003797}
3798
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003799void Camera3Device::HalInterface::getInflightBufferKeys(
3800 std::vector<std::pair<int32_t, int32_t>>* out) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003801 mBufferRecords.getInflightBufferKeys(out);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003802 return;
3803}
3804
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08003805void Camera3Device::HalInterface::getInflightRequestBufferKeys(
3806 std::vector<uint64_t>* out) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003807 mBufferRecords.getInflightRequestBufferKeys(out);
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08003808 return;
3809}
3810
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003811bool Camera3Device::HalInterface::verifyBufferIds(
3812 int32_t streamId, std::vector<uint64_t>& bufIds) {
3813 return mBufferRecords.verifyBufferIds(streamId, bufIds);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003814}
3815
3816status_t Camera3Device::HalInterface::popInflightBuffer(
Yin-Chia Yehf4650602017-01-10 13:13:39 -08003817 int32_t frameNumber, int32_t streamId,
3818 /*out*/ buffer_handle_t **buffer) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003819 return mBufferRecords.popInflightBuffer(frameNumber, streamId, buffer);
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003820}
3821
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003822status_t Camera3Device::HalInterface::pushInflightRequestBuffer(
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08003823 uint64_t bufferId, buffer_handle_t* buf, int32_t streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003824 return mBufferRecords.pushInflightRequestBuffer(bufferId, buf, streamId);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003825}
3826
3827// Find and pop a buffer_handle_t based on bufferId
3828status_t Camera3Device::HalInterface::popInflightRequestBuffer(
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08003829 uint64_t bufferId,
3830 /*out*/ buffer_handle_t** buffer,
3831 /*optional out*/ int32_t* streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003832 return mBufferRecords.popInflightRequestBuffer(bufferId, buffer, streamId);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003833}
3834
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003835std::pair<bool, uint64_t> Camera3Device::HalInterface::getBufferId(
3836 const buffer_handle_t& buf, int streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003837 return mBufferRecords.getBufferId(buf, streamId);
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003838}
3839
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003840void Camera3Device::HalInterface::onBufferFreed(
3841 int streamId, const native_handle_t* handle) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003842 uint32_t bufferId = mBufferRecords.removeOneBufferCache(streamId, handle);
3843 std::lock_guard<std::mutex> lock(mFreedBuffersLock);
3844 if (bufferId != BUFFER_ID_NO_BUFFER) {
3845 mFreedBuffers.push_back(std::make_pair(streamId, bufferId));
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003846 }
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003847}
3848
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07003849void Camera3Device::HalInterface::onStreamReConfigured(int streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003850 std::vector<uint64_t> bufIds = mBufferRecords.clearBufferCaches(streamId);
3851 std::lock_guard<std::mutex> lock(mFreedBuffersLock);
3852 for (auto bufferId : bufIds) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07003853 mFreedBuffers.push_back(std::make_pair(streamId, bufferId));
3854 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07003855}
3856
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003857/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003858 * RequestThread inner class methods
3859 */
3860
3861Camera3Device::RequestThread::RequestThread(wp<Camera3Device> parent,
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003862 sp<StatusTracker> statusTracker,
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003863 sp<HalInterface> interface, const Vector<int32_t>& sessionParamKeys,
3864 bool useHalBufManager) :
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07003865 Thread(/*canCallJava*/false),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003866 mParent(parent),
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003867 mStatusTracker(statusTracker),
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003868 mInterface(interface),
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07003869 mListener(nullptr),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003870 mId(getId(parent)),
Shuzhen Wang316781a2020-08-18 18:11:01 -07003871 mFirstRepeating(false),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003872 mReconfigured(false),
3873 mDoPause(false),
3874 mPaused(true),
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003875 mNotifyPipelineDrain(false),
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003876 mFrameNumber(0),
Jianing Weicb0652e2014-03-12 18:29:36 -07003877 mLatestRequestId(NAME_NOT_FOUND),
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07003878 mCurrentAfTriggerId(0),
3879 mCurrentPreCaptureTriggerId(0),
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08003880 mRotateAndCropOverride(ANDROID_SCALER_ROTATE_AND_CROP_NONE),
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08003881 mCameraMute(false),
3882 mCameraMuteChanged(false),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003883 mRepeatingLastFrameNumber(
3884 hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES),
Shuzhen Wang686f6442017-06-20 16:16:04 -07003885 mPrepareVideoStream(false),
Emilian Peeva14b4dd2018-05-15 11:00:31 +01003886 mConstrainedMode(false),
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003887 mRequestLatency(kRequestLatencyBinSize),
3888 mSessionParamKeys(sessionParamKeys),
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003889 mLatestSessionParams(sessionParamKeys.size()),
3890 mUseHalBufManager(useHalBufManager) {
Yin-Chia Yeh87b3ec02019-06-03 10:44:39 -07003891 mStatusId = statusTracker->addComponent("RequestThread");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003892}
3893
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003894Camera3Device::RequestThread::~RequestThread() {}
3895
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07003896void Camera3Device::RequestThread::setNotificationListener(
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003897 wp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003898 ATRACE_CALL();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003899 Mutex::Autolock l(mRequestLock);
3900 mListener = listener;
3901}
3902
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003903void Camera3Device::RequestThread::configurationComplete(bool isConstrainedHighSpeed,
3904 const CameraMetadata& sessionParams) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003905 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003906 Mutex::Autolock l(mRequestLock);
3907 mReconfigured = true;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003908 mLatestSessionParams = sessionParams;
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07003909 // Prepare video stream for high speed recording.
3910 mPrepareVideoStream = isConstrainedHighSpeed;
Emilian Peeva14b4dd2018-05-15 11:00:31 +01003911 mConstrainedMode = isConstrainedHighSpeed;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003912}
3913
Jianing Wei90e59c92014-03-12 18:29:36 -07003914status_t Camera3Device::RequestThread::queueRequestList(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003915 List<sp<CaptureRequest> > &requests,
3916 /*out*/
3917 int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003918 ATRACE_CALL();
Jianing Wei90e59c92014-03-12 18:29:36 -07003919 Mutex::Autolock l(mRequestLock);
3920 for (List<sp<CaptureRequest> >::iterator it = requests.begin(); it != requests.end();
3921 ++it) {
3922 mRequestQueue.push_back(*it);
3923 }
3924
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003925 if (lastFrameNumber != NULL) {
3926 *lastFrameNumber = mFrameNumber + mRequestQueue.size() - 1;
3927 ALOGV("%s: requestId %d, mFrameNumber %" PRId32 ", lastFrameNumber %" PRId64 ".",
3928 __FUNCTION__, (*(requests.begin()))->mResultExtras.requestId, mFrameNumber,
3929 *lastFrameNumber);
3930 }
Jianing Weicb0652e2014-03-12 18:29:36 -07003931
Jianing Wei90e59c92014-03-12 18:29:36 -07003932 unpauseForNewRequests();
3933
3934 return OK;
3935}
3936
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003937
3938status_t Camera3Device::RequestThread::queueTrigger(
3939 RequestTrigger trigger[],
3940 size_t count) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003941 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003942 Mutex::Autolock l(mTriggerMutex);
3943 status_t ret;
3944
3945 for (size_t i = 0; i < count; ++i) {
3946 ret = queueTriggerLocked(trigger[i]);
3947
3948 if (ret != OK) {
3949 return ret;
3950 }
3951 }
3952
3953 return OK;
3954}
3955
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003956const String8& Camera3Device::RequestThread::getId(const wp<Camera3Device> &device) {
3957 static String8 deadId("<DeadDevice>");
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003958 sp<Camera3Device> d = device.promote();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003959 if (d != nullptr) return d->mId;
3960 return deadId;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003961}
3962
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003963status_t Camera3Device::RequestThread::queueTriggerLocked(
3964 RequestTrigger trigger) {
3965
3966 uint32_t tag = trigger.metadataTag;
3967 ssize_t index = mTriggerMap.indexOfKey(tag);
3968
3969 switch (trigger.getTagType()) {
3970 case TYPE_BYTE:
3971 // fall-through
3972 case TYPE_INT32:
3973 break;
3974 default:
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003975 ALOGE("%s: Type not supported: 0x%x", __FUNCTION__,
3976 trigger.getTagType());
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003977 return INVALID_OPERATION;
3978 }
3979
3980 /**
3981 * Collect only the latest trigger, since we only have 1 field
3982 * in the request settings per trigger tag, and can't send more than 1
3983 * trigger per request.
3984 */
3985 if (index != NAME_NOT_FOUND) {
3986 mTriggerMap.editValueAt(index) = trigger;
3987 } else {
3988 mTriggerMap.add(tag, trigger);
3989 }
3990
3991 return OK;
3992}
3993
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003994status_t Camera3Device::RequestThread::setRepeatingRequests(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003995 const RequestList &requests,
3996 /*out*/
3997 int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003998 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003999 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004000 if (lastFrameNumber != NULL) {
4001 *lastFrameNumber = mRepeatingLastFrameNumber;
4002 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004003 mRepeatingRequests.clear();
Shuzhen Wang316781a2020-08-18 18:11:01 -07004004 mFirstRepeating = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004005 mRepeatingRequests.insert(mRepeatingRequests.begin(),
4006 requests.begin(), requests.end());
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004007
4008 unpauseForNewRequests();
4009
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004010 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004011 return OK;
4012}
4013
Chih-Hung Hsieh8b0b9712016-08-09 14:25:53 -07004014bool Camera3Device::RequestThread::isRepeatingRequestLocked(const sp<CaptureRequest>& requestIn) {
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07004015 if (mRepeatingRequests.empty()) {
4016 return false;
4017 }
4018 int32_t requestId = requestIn->mResultExtras.requestId;
4019 const RequestList &repeatRequests = mRepeatingRequests;
4020 // All repeating requests are guaranteed to have same id so only check first quest
4021 const sp<CaptureRequest> firstRequest = *repeatRequests.begin();
4022 return (firstRequest->mResultExtras.requestId == requestId);
4023}
4024
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004025status_t Camera3Device::RequestThread::clearRepeatingRequests(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004026 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004027 Mutex::Autolock l(mRequestLock);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004028 return clearRepeatingRequestsLocked(lastFrameNumber);
4029
4030}
4031
4032status_t Camera3Device::RequestThread::clearRepeatingRequestsLocked(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004033 mRepeatingRequests.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004034 if (lastFrameNumber != NULL) {
4035 *lastFrameNumber = mRepeatingLastFrameNumber;
4036 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004037 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004038 return OK;
4039}
4040
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004041status_t Camera3Device::RequestThread::clear(
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004042 /*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004043 ATRACE_CALL();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004044 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004045 ALOGV("RequestThread::%s:", __FUNCTION__);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004046
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004047 mRepeatingRequests.clear();
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07004048
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004049 // Send errors for all requests pending in the request queue, including
4050 // pending repeating requests
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004051 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004052 if (listener != NULL) {
4053 for (RequestList::iterator it = mRequestQueue.begin();
4054 it != mRequestQueue.end(); ++it) {
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004055 // Abort the input buffers for reprocess requests.
4056 if ((*it)->mInputStream != NULL) {
Emilian Peevf4816702020-04-03 15:44:51 -07004057 camera_stream_buffer_t inputBuffer;
Eino-Ville Talvalaba435252017-06-21 16:07:25 -07004058 status_t res = (*it)->mInputStream->getInputBuffer(&inputBuffer,
4059 /*respectHalLimit*/ false);
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004060 if (res != OK) {
4061 ALOGW("%s: %d: couldn't get input buffer while clearing the request "
4062 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
4063 } else {
Emilian Peevf4816702020-04-03 15:44:51 -07004064 inputBuffer.status = CAMERA_BUFFER_STATUS_ERROR;
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004065 res = (*it)->mInputStream->returnInputBuffer(inputBuffer);
4066 if (res != OK) {
4067 ALOGE("%s: %d: couldn't return input buffer while clearing the request "
4068 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
4069 }
4070 }
4071 }
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004072 // Set the frame number this request would have had, if it
4073 // had been submitted; this frame number will not be reused.
4074 // The requestId and burstId fields were set when the request was
4075 // submitted originally (in convertMetadataListToRequestListLocked)
4076 (*it)->mResultExtras.frameNumber = mFrameNumber++;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004077 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004078 (*it)->mResultExtras);
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07004079 }
4080 }
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004081 mRequestQueue.clear();
Jinguang Dongb26e7a02016-11-14 16:04:02 +08004082
4083 Mutex::Autolock al(mTriggerMutex);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004084 mTriggerMap.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004085 if (lastFrameNumber != NULL) {
4086 *lastFrameNumber = mRepeatingLastFrameNumber;
4087 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004088 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Emilian Peev8dae54c2019-12-02 15:17:17 -08004089 mRequestSignal.signal();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004090 return OK;
4091}
4092
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004093status_t Camera3Device::RequestThread::flush() {
4094 ATRACE_CALL();
4095 Mutex::Autolock l(mFlushLock);
4096
Emilian Peev08dd2452017-04-06 16:55:14 +01004097 return mInterface->flush();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004098}
4099
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004100void Camera3Device::RequestThread::setPaused(bool paused) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004101 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004102 Mutex::Autolock l(mPauseLock);
4103 mDoPause = paused;
4104 mDoPauseSignal.signal();
4105}
4106
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004107status_t Camera3Device::RequestThread::waitUntilRequestProcessed(
4108 int32_t requestId, nsecs_t timeout) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004109 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004110 Mutex::Autolock l(mLatestRequestMutex);
4111 status_t res;
4112 while (mLatestRequestId != requestId) {
4113 nsecs_t startTime = systemTime();
4114
4115 res = mLatestRequestSignal.waitRelative(mLatestRequestMutex, timeout);
4116 if (res != OK) return res;
4117
4118 timeout -= (systemTime() - startTime);
4119 }
4120
4121 return OK;
4122}
4123
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004124void Camera3Device::RequestThread::requestExit() {
4125 // Call parent to set up shutdown
4126 Thread::requestExit();
4127 // The exit from any possible waits
4128 mDoPauseSignal.signal();
4129 mRequestSignal.signal();
Shuzhen Wang686f6442017-06-20 16:16:04 -07004130
4131 mRequestLatency.log("ProcessCaptureRequest latency histogram");
4132 mRequestLatency.reset();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004133}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004134
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004135void Camera3Device::RequestThread::checkAndStopRepeatingRequest() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004136 ATRACE_CALL();
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07004137 bool surfaceAbandoned = false;
4138 int64_t lastFrameNumber = 0;
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004139 sp<NotificationListener> listener;
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07004140 {
4141 Mutex::Autolock l(mRequestLock);
4142 // Check all streams needed by repeating requests are still valid. Otherwise, stop
4143 // repeating requests.
4144 for (const auto& request : mRepeatingRequests) {
4145 for (const auto& s : request->mOutputStreams) {
4146 if (s->isAbandoned()) {
4147 surfaceAbandoned = true;
4148 clearRepeatingRequestsLocked(&lastFrameNumber);
4149 break;
4150 }
4151 }
4152 if (surfaceAbandoned) {
4153 break;
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004154 }
4155 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004156 listener = mListener.promote();
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004157 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004158
4159 if (listener != NULL && surfaceAbandoned) {
4160 listener->notifyRepeatingRequestError(lastFrameNumber);
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07004161 }
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004162}
4163
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004164bool Camera3Device::RequestThread::sendRequestsBatch() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004165 ATRACE_CALL();
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004166 status_t res;
4167 size_t batchSize = mNextRequests.size();
Emilian Peevf4816702020-04-03 15:44:51 -07004168 std::vector<camera_capture_request_t*> requests(batchSize);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004169 uint32_t numRequestProcessed = 0;
4170 for (size_t i = 0; i < batchSize; i++) {
4171 requests[i] = &mNextRequests.editItemAt(i).halRequest;
Yin-Chia Yeh885691c2018-05-01 15:54:24 -07004172 ATRACE_ASYNC_BEGIN("frame capture", mNextRequests[i].halRequest.frame_number);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004173 }
4174
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004175 res = mInterface->processBatchCaptureRequests(requests, &numRequestProcessed);
4176
4177 bool triggerRemoveFailed = false;
4178 NextRequest& triggerFailedRequest = mNextRequests.editItemAt(0);
4179 for (size_t i = 0; i < numRequestProcessed; i++) {
4180 NextRequest& nextRequest = mNextRequests.editItemAt(i);
4181 nextRequest.submitted = true;
4182
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004183 updateNextRequest(nextRequest);
Emilian Peevaebbe412018-01-15 13:53:24 +00004184
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004185 if (!triggerRemoveFailed) {
4186 // Remove any previously queued triggers (after unlock)
4187 status_t removeTriggerRes = removeTriggers(mPrevRequest);
4188 if (removeTriggerRes != OK) {
4189 triggerRemoveFailed = true;
4190 triggerFailedRequest = nextRequest;
4191 }
4192 }
4193 }
4194
4195 if (triggerRemoveFailed) {
4196 SET_ERR("RequestThread: Unable to remove triggers "
4197 "(capture request %d, HAL device: %s (%d)",
4198 triggerFailedRequest.halRequest.frame_number, strerror(-res), res);
4199 cleanUpFailedRequests(/*sendRequestError*/ false);
4200 return false;
4201 }
4202
4203 if (res != OK) {
4204 // Should only get a failure here for malformed requests or device-level
4205 // errors, so consider all errors fatal. Bad metadata failures should
4206 // come through notify.
4207 SET_ERR("RequestThread: Unable to submit capture request %d to HAL device: %s (%d)",
4208 mNextRequests[numRequestProcessed].halRequest.frame_number,
4209 strerror(-res), res);
4210 cleanUpFailedRequests(/*sendRequestError*/ false);
4211 return false;
4212 }
4213 return true;
4214}
4215
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07004216nsecs_t Camera3Device::RequestThread::calculateMaxExpectedDuration(const camera_metadata_t *request) {
4217 nsecs_t maxExpectedDuration = kDefaultExpectedDuration;
4218 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
4219 find_camera_metadata_ro_entry(request,
4220 ANDROID_CONTROL_AE_MODE,
4221 &e);
4222 if (e.count == 0) return maxExpectedDuration;
4223
4224 switch (e.data.u8[0]) {
4225 case ANDROID_CONTROL_AE_MODE_OFF:
4226 find_camera_metadata_ro_entry(request,
4227 ANDROID_SENSOR_EXPOSURE_TIME,
4228 &e);
4229 if (e.count > 0) {
4230 maxExpectedDuration = e.data.i64[0];
4231 }
4232 find_camera_metadata_ro_entry(request,
4233 ANDROID_SENSOR_FRAME_DURATION,
4234 &e);
4235 if (e.count > 0) {
4236 maxExpectedDuration = std::max(e.data.i64[0], maxExpectedDuration);
4237 }
4238 break;
4239 default:
4240 find_camera_metadata_ro_entry(request,
4241 ANDROID_CONTROL_AE_TARGET_FPS_RANGE,
4242 &e);
4243 if (e.count > 1) {
4244 maxExpectedDuration = 1e9 / e.data.u8[0];
4245 }
4246 break;
4247 }
4248
4249 return maxExpectedDuration;
4250}
4251
Emilian Peeva14b4dd2018-05-15 11:00:31 +01004252bool Camera3Device::RequestThread::skipHFRTargetFPSUpdate(int32_t tag,
4253 const camera_metadata_ro_entry_t& newEntry, const camera_metadata_entry_t& currentEntry) {
4254 if (mConstrainedMode && (ANDROID_CONTROL_AE_TARGET_FPS_RANGE == tag) &&
4255 (newEntry.count == currentEntry.count) && (currentEntry.count == 2) &&
4256 (currentEntry.data.i32[1] == newEntry.data.i32[1])) {
4257 return true;
4258 }
4259
4260 return false;
4261}
4262
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004263void Camera3Device::RequestThread::updateNextRequest(NextRequest& nextRequest) {
4264 // Update the latest request sent to HAL
4265 if (nextRequest.halRequest.settings != NULL) { // Don't update if they were unchanged
4266 Mutex::Autolock al(mLatestRequestMutex);
4267
4268 camera_metadata_t* cloned = clone_camera_metadata(nextRequest.halRequest.settings);
4269 mLatestRequest.acquire(cloned);
4270
4271 mLatestPhysicalRequest.clear();
4272 for (uint32_t i = 0; i < nextRequest.halRequest.num_physcam_settings; i++) {
4273 cloned = clone_camera_metadata(nextRequest.halRequest.physcam_settings[i]);
4274 mLatestPhysicalRequest.emplace(nextRequest.halRequest.physcam_id[i],
4275 CameraMetadata(cloned));
4276 }
4277
4278 sp<Camera3Device> parent = mParent.promote();
4279 if (parent != NULL) {
4280 parent->monitorMetadata(TagMonitor::REQUEST,
4281 nextRequest.halRequest.frame_number,
4282 0, mLatestRequest, mLatestPhysicalRequest);
4283 }
4284 }
4285
4286 if (nextRequest.halRequest.settings != NULL) {
4287 nextRequest.captureRequest->mSettingsList.begin()->metadata.unlock(
4288 nextRequest.halRequest.settings);
4289 }
4290
4291 cleanupPhysicalSettings(nextRequest.captureRequest, &nextRequest.halRequest);
4292}
4293
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004294bool Camera3Device::RequestThread::updateSessionParameters(const CameraMetadata& settings) {
4295 ATRACE_CALL();
4296 bool updatesDetected = false;
4297
Emilian Peev4ec17882019-01-24 17:16:58 -08004298 CameraMetadata updatedParams(mLatestSessionParams);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004299 for (auto tag : mSessionParamKeys) {
4300 camera_metadata_ro_entry entry = settings.find(tag);
Emilian Peev4ec17882019-01-24 17:16:58 -08004301 camera_metadata_entry lastEntry = updatedParams.find(tag);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004302
4303 if (entry.count > 0) {
4304 bool isDifferent = false;
4305 if (lastEntry.count > 0) {
4306 // Have a last value, compare to see if changed
4307 if (lastEntry.type == entry.type &&
4308 lastEntry.count == entry.count) {
4309 // Same type and count, compare values
4310 size_t bytesPerValue = camera_metadata_type_size[lastEntry.type];
4311 size_t entryBytes = bytesPerValue * lastEntry.count;
4312 int cmp = memcmp(entry.data.u8, lastEntry.data.u8, entryBytes);
4313 if (cmp != 0) {
4314 isDifferent = true;
4315 }
4316 } else {
4317 // Count or type has changed
4318 isDifferent = true;
4319 }
4320 } else {
4321 // No last entry, so always consider to be different
4322 isDifferent = true;
4323 }
4324
4325 if (isDifferent) {
4326 ALOGV("%s: Session parameter tag id %d changed", __FUNCTION__, tag);
Emilian Peeva14b4dd2018-05-15 11:00:31 +01004327 if (!skipHFRTargetFPSUpdate(tag, entry, lastEntry)) {
4328 updatesDetected = true;
4329 }
Emilian Peev4ec17882019-01-24 17:16:58 -08004330 updatedParams.update(entry);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004331 }
4332 } else if (lastEntry.count > 0) {
4333 // Value has been removed
4334 ALOGV("%s: Session parameter tag id %d removed", __FUNCTION__, tag);
Emilian Peev4ec17882019-01-24 17:16:58 -08004335 updatedParams.erase(tag);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004336 updatesDetected = true;
4337 }
4338 }
4339
Emilian Peev4ec17882019-01-24 17:16:58 -08004340 bool reconfigureRequired;
4341 if (updatesDetected) {
4342 reconfigureRequired = mInterface->isReconfigurationRequired(mLatestSessionParams,
4343 updatedParams);
4344 mLatestSessionParams = updatedParams;
4345 } else {
4346 reconfigureRequired = false;
4347 }
4348
4349 return reconfigureRequired;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004350}
4351
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004352bool Camera3Device::RequestThread::threadLoop() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004353 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004354 status_t res;
Jayant Chowdhary37eca242019-11-18 08:55:56 -08004355 // Any function called from threadLoop() must not hold mInterfaceLock since
4356 // it could lead to deadlocks (disconnect() -> hold mInterfaceMutex -> wait for request thread
4357 // to finish -> request thread waits on mInterfaceMutex) http://b/143513518
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004358
4359 // Handle paused state.
4360 if (waitIfPaused()) {
4361 return true;
4362 }
4363
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004364 // Wait for the next batch of requests.
4365 waitForNextRequestBatch();
4366 if (mNextRequests.size() == 0) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004367 return true;
4368 }
4369
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004370 // Get the latest request ID, if any
4371 int latestRequestId;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004372 camera_metadata_entry_t requestIdEntry = mNextRequests[mNextRequests.size() - 1].
Emilian Peevaebbe412018-01-15 13:53:24 +00004373 captureRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_ID);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004374 if (requestIdEntry.count > 0) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004375 latestRequestId = requestIdEntry.data.i32[0];
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004376 } else {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004377 ALOGW("%s: Did not have android.request.id set in the request.", __FUNCTION__);
4378 latestRequestId = NAME_NOT_FOUND;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004379 }
4380
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004381 // 'mNextRequests' will at this point contain either a set of HFR batched requests
4382 // or a single request from streaming or burst. In either case the first element
4383 // should contain the latest camera settings that we need to check for any session
4384 // parameter updates.
Emilian Peevaebbe412018-01-15 13:53:24 +00004385 if (updateSessionParameters(mNextRequests[0].captureRequest->mSettingsList.begin()->metadata)) {
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004386 res = OK;
4387
4388 //Input stream buffers are already acquired at this point so an input stream
4389 //will not be able to move to idle state unless we force it.
4390 if (mNextRequests[0].captureRequest->mInputStream != nullptr) {
4391 res = mNextRequests[0].captureRequest->mInputStream->forceToIdle();
4392 if (res != OK) {
4393 ALOGE("%s: Failed to force idle input stream: %d", __FUNCTION__, res);
4394 cleanUpFailedRequests(/*sendRequestError*/ false);
4395 return false;
4396 }
4397 }
4398
4399 if (res == OK) {
Emilian Peev3bead5f2020-05-28 17:29:08 -07004400 sp<Camera3Device> parent = mParent.promote();
4401 if (parent != nullptr) {
4402 mReconfigured |= parent->reconfigureCamera(mLatestSessionParams, mStatusId);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004403 }
Emilian Peev3bead5f2020-05-28 17:29:08 -07004404 setPaused(false);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004405
4406 if (mNextRequests[0].captureRequest->mInputStream != nullptr) {
4407 mNextRequests[0].captureRequest->mInputStream->restoreConfiguredState();
4408 if (res != OK) {
4409 ALOGE("%s: Failed to restore configured input stream: %d", __FUNCTION__, res);
4410 cleanUpFailedRequests(/*sendRequestError*/ false);
4411 return false;
4412 }
4413 }
4414 }
4415 }
4416
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004417 // Prepare a batch of HAL requests and output buffers.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004418 res = prepareHalRequests();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004419 if (res == TIMED_OUT) {
4420 // Not a fatal error if getting output buffers time out.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004421 cleanUpFailedRequests(/*sendRequestError*/ true);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004422 // Check if any stream is abandoned.
4423 checkAndStopRepeatingRequest();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004424 return true;
4425 } else if (res != OK) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004426 cleanUpFailedRequests(/*sendRequestError*/ false);
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004427 return false;
4428 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004429
Zhijun Hecc27e112013-10-03 16:12:43 -07004430 // Inform waitUntilRequestProcessed thread of a new request ID
4431 {
4432 Mutex::Autolock al(mLatestRequestMutex);
4433
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004434 mLatestRequestId = latestRequestId;
Zhijun Hecc27e112013-10-03 16:12:43 -07004435 mLatestRequestSignal.signal();
4436 }
4437
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004438 // Submit a batch of requests to HAL.
4439 // Use flush lock only when submitting multilple requests in a batch.
4440 // TODO: The problem with flush lock is flush() will be blocked by process_capture_request()
4441 // which may take a long time to finish so synchronizing flush() and
4442 // process_capture_request() defeats the purpose of cancelling requests ASAP with flush().
4443 // For now, only synchronize for high speed recording and we should figure something out for
4444 // removing the synchronization.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004445 bool useFlushLock = mNextRequests.size() > 1;
Eino-Ville Talvala17a61ad2013-06-03 16:53:32 -07004446
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004447 if (useFlushLock) {
4448 mFlushLock.lock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004449 }
4450
Zhijun Hef0645c12016-08-02 00:58:11 -07004451 ALOGVV("%s: %d: submitting %zu requests in a batch.", __FUNCTION__, __LINE__,
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004452 mNextRequests.size());
Igor Murashkin1e479c02013-09-06 16:55:14 -07004453
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08004454 sp<Camera3Device> parent = mParent.promote();
4455 if (parent != nullptr) {
4456 parent->mRequestBufferSM.onSubmittingRequest();
4457 }
4458
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004459 bool submitRequestSuccess = false;
Shuzhen Wang686f6442017-06-20 16:16:04 -07004460 nsecs_t tRequestStart = systemTime(SYSTEM_TIME_MONOTONIC);
Yin-Chia Yeh11648852019-05-16 10:42:54 -07004461 submitRequestSuccess = sendRequestsBatch();
4462
Shuzhen Wang686f6442017-06-20 16:16:04 -07004463 nsecs_t tRequestEnd = systemTime(SYSTEM_TIME_MONOTONIC);
4464 mRequestLatency.add(tRequestStart, tRequestEnd);
Igor Murashkin1e479c02013-09-06 16:55:14 -07004465
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004466 if (useFlushLock) {
4467 mFlushLock.unlock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004468 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004469
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004470 // Unset as current request
4471 {
4472 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004473 mNextRequests.clear();
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004474 }
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004475 mRequestSubmittedSignal.signal();
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004476
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004477 return submitRequestSuccess;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004478}
4479
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004480status_t Camera3Device::RequestThread::prepareHalRequests() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004481 ATRACE_CALL();
4482
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07004483 bool batchedRequest = mNextRequests[0].captureRequest->mBatchSize > 1;
Shuzhen Wang4a472662017-02-26 23:29:04 -08004484 for (size_t i = 0; i < mNextRequests.size(); i++) {
4485 auto& nextRequest = mNextRequests.editItemAt(i);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004486 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
Emilian Peevf4816702020-04-03 15:44:51 -07004487 camera_capture_request_t* halRequest = &nextRequest.halRequest;
4488 Vector<camera_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004489
4490 // Prepare a request to HAL
4491 halRequest->frame_number = captureRequest->mResultExtras.frameNumber;
4492
4493 // Insert any queued triggers (before metadata is locked)
4494 status_t res = insertTriggers(captureRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004495 if (res < 0) {
4496 SET_ERR("RequestThread: Unable to insert triggers "
4497 "(capture request %d, HAL device: %s (%d)",
4498 halRequest->frame_number, strerror(-res), res);
4499 return INVALID_OPERATION;
4500 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07004501
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004502 int triggerCount = res;
4503 bool triggersMixedIn = (triggerCount > 0 || mPrevTriggers > 0);
4504 mPrevTriggers = triggerCount;
4505
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004506 bool rotateAndCropChanged = overrideAutoRotateAndCrop(captureRequest);
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004507 bool testPatternChanged = overrideTestPattern(captureRequest);
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004508
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004509 // If the request is the same as last, or we had triggers now or last time or
4510 // changing overrides this time
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004511 bool newRequest =
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004512 (mPrevRequest != captureRequest || triggersMixedIn ||
4513 rotateAndCropChanged || testPatternChanged) &&
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07004514 // Request settings are all the same within one batch, so only treat the first
4515 // request in a batch as new
Zhijun He54c36822018-07-18 09:33:39 -07004516 !(batchedRequest && i > 0);
Emilian Peev00420d22018-02-05 21:33:13 +00004517 if (newRequest) {
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08004518 std::set<std::string> cameraIdsWithZoom;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004519 /**
4520 * HAL workaround:
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004521 * Insert a fake trigger ID if a trigger is set but no trigger ID is
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004522 */
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004523 res = addFakeTriggerIds(captureRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004524 if (res != OK) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004525 SET_ERR("RequestThread: Unable to insert fake trigger IDs "
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004526 "(capture request %d, HAL device: %s (%d)",
4527 halRequest->frame_number, strerror(-res), res);
4528 return INVALID_OPERATION;
4529 }
4530
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07004531 {
4532 // Correct metadata regions for distortion correction if enabled
4533 sp<Camera3Device> parent = mParent.promote();
4534 if (parent != nullptr) {
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -07004535 List<PhysicalCameraSettings>::iterator it;
4536 for (it = captureRequest->mSettingsList.begin();
4537 it != captureRequest->mSettingsList.end(); it++) {
4538 if (parent->mDistortionMappers.find(it->cameraId) ==
4539 parent->mDistortionMappers.end()) {
4540 continue;
4541 }
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07004542
4543 if (!captureRequest->mDistortionCorrectionUpdated) {
4544 res = parent->mDistortionMappers[it->cameraId].correctCaptureRequest(
4545 &(it->metadata));
4546 if (res != OK) {
4547 SET_ERR("RequestThread: Unable to correct capture requests "
4548 "for lens distortion for request %d: %s (%d)",
4549 halRequest->frame_number, strerror(-res), res);
4550 return INVALID_OPERATION;
4551 }
4552 captureRequest->mDistortionCorrectionUpdated = true;
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -07004553 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07004554 }
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08004555
4556 for (it = captureRequest->mSettingsList.begin();
4557 it != captureRequest->mSettingsList.end(); it++) {
4558 if (parent->mZoomRatioMappers.find(it->cameraId) ==
4559 parent->mZoomRatioMappers.end()) {
4560 continue;
4561 }
4562
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07004563 if (!captureRequest->mZoomRatioIs1x) {
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08004564 cameraIdsWithZoom.insert(it->cameraId);
4565 }
4566
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07004567 if (!captureRequest->mZoomRatioUpdated) {
4568 res = parent->mZoomRatioMappers[it->cameraId].updateCaptureRequest(
4569 &(it->metadata));
4570 if (res != OK) {
4571 SET_ERR("RequestThread: Unable to correct capture requests "
4572 "for zoom ratio for request %d: %s (%d)",
4573 halRequest->frame_number, strerror(-res), res);
4574 return INVALID_OPERATION;
4575 }
4576 captureRequest->mZoomRatioUpdated = true;
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08004577 }
4578 }
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07004579 if (captureRequest->mRotateAndCropAuto &&
4580 !captureRequest->mRotationAndCropUpdated) {
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004581 for (it = captureRequest->mSettingsList.begin();
4582 it != captureRequest->mSettingsList.end(); it++) {
4583 auto mapper = parent->mRotateAndCropMappers.find(it->cameraId);
4584 if (mapper != parent->mRotateAndCropMappers.end()) {
4585 res = mapper->second.updateCaptureRequest(&(it->metadata));
4586 if (res != OK) {
4587 SET_ERR("RequestThread: Unable to correct capture requests "
4588 "for rotate-and-crop for request %d: %s (%d)",
4589 halRequest->frame_number, strerror(-res), res);
4590 return INVALID_OPERATION;
4591 }
4592 }
4593 }
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07004594 captureRequest->mRotationAndCropUpdated = true;
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004595 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07004596 }
4597 }
4598
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004599 /**
4600 * The request should be presorted so accesses in HAL
4601 * are O(logn). Sidenote, sorting a sorted metadata is nop.
4602 */
Emilian Peevaebbe412018-01-15 13:53:24 +00004603 captureRequest->mSettingsList.begin()->metadata.sort();
4604 halRequest->settings = captureRequest->mSettingsList.begin()->metadata.getAndLock();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004605 mPrevRequest = captureRequest;
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08004606 mPrevCameraIdsWithZoom = cameraIdsWithZoom;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004607 ALOGVV("%s: Request settings are NEW", __FUNCTION__);
4608
4609 IF_ALOGV() {
4610 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
4611 find_camera_metadata_ro_entry(
4612 halRequest->settings,
4613 ANDROID_CONTROL_AF_TRIGGER,
4614 &e
4615 );
4616 if (e.count > 0) {
4617 ALOGV("%s: Request (frame num %d) had AF trigger 0x%x",
4618 __FUNCTION__,
4619 halRequest->frame_number,
4620 e.data.u8[0]);
4621 }
4622 }
4623 } else {
4624 // leave request.settings NULL to indicate 'reuse latest given'
4625 ALOGVV("%s: Request settings are REUSED",
4626 __FUNCTION__);
4627 }
4628
Emilian Peevaebbe412018-01-15 13:53:24 +00004629 if (captureRequest->mSettingsList.size() > 1) {
4630 halRequest->num_physcam_settings = captureRequest->mSettingsList.size() - 1;
4631 halRequest->physcam_id = new const char* [halRequest->num_physcam_settings];
Emilian Peev00420d22018-02-05 21:33:13 +00004632 if (newRequest) {
4633 halRequest->physcam_settings =
4634 new const camera_metadata* [halRequest->num_physcam_settings];
4635 } else {
4636 halRequest->physcam_settings = nullptr;
4637 }
Emilian Peevaebbe412018-01-15 13:53:24 +00004638 auto it = ++captureRequest->mSettingsList.begin();
4639 size_t i = 0;
4640 for (; it != captureRequest->mSettingsList.end(); it++, i++) {
4641 halRequest->physcam_id[i] = it->cameraId.c_str();
Emilian Peev00420d22018-02-05 21:33:13 +00004642 if (newRequest) {
4643 it->metadata.sort();
4644 halRequest->physcam_settings[i] = it->metadata.getAndLock();
4645 }
Emilian Peevaebbe412018-01-15 13:53:24 +00004646 }
4647 }
4648
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004649 uint32_t totalNumBuffers = 0;
4650
4651 // Fill in buffers
4652 if (captureRequest->mInputStream != NULL) {
4653 halRequest->input_buffer = &captureRequest->mInputBuffer;
4654 totalNumBuffers += 1;
4655 } else {
4656 halRequest->input_buffer = NULL;
4657 }
4658
Emilian Peevf4816702020-04-03 15:44:51 -07004659 outputBuffers->insertAt(camera_stream_buffer_t(), 0,
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004660 captureRequest->mOutputStreams.size());
4661 halRequest->output_buffers = outputBuffers->array();
Shuzhen Wang5c22c152017-12-31 17:12:25 -08004662 std::set<String8> requestedPhysicalCameras;
Yin-Chia Yehb3a80b12018-09-04 12:13:05 -07004663
4664 sp<Camera3Device> parent = mParent.promote();
4665 if (parent == NULL) {
4666 // Should not happen, and nowhere to send errors to, so just log it
4667 CLOGE("RequestThread: Parent is gone");
4668 return INVALID_OPERATION;
4669 }
4670 nsecs_t waitDuration = kBaseGetBufferWait + parent->getExpectedInFlightDuration();
4671
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07004672 SurfaceMap uniqueSurfaceIdMap;
Shuzhen Wang4a472662017-02-26 23:29:04 -08004673 for (size_t j = 0; j < captureRequest->mOutputStreams.size(); j++) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07004674 sp<Camera3OutputStreamInterface> outputStream =
4675 captureRequest->mOutputStreams.editItemAt(j);
4676 int streamId = outputStream->getId();
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07004677
4678 // Prepare video buffers for high speed recording on the first video request.
4679 if (mPrepareVideoStream && outputStream->isVideoStream()) {
4680 // Only try to prepare video stream on the first video request.
4681 mPrepareVideoStream = false;
4682
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07004683 res = outputStream->startPrepare(Camera3StreamInterface::ALLOCATE_PIPELINE_MAX,
4684 false /*blockRequest*/);
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07004685 while (res == NOT_ENOUGH_DATA) {
4686 res = outputStream->prepareNextBuffer();
4687 }
4688 if (res != OK) {
4689 ALOGW("%s: Preparing video buffers for high speed failed: %s (%d)",
4690 __FUNCTION__, strerror(-res), res);
4691 outputStream->cancelPrepare();
4692 }
4693 }
4694
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07004695 std::vector<size_t> uniqueSurfaceIds;
4696 res = outputStream->getUniqueSurfaceIds(
4697 captureRequest->mOutputSurfaces[streamId],
4698 &uniqueSurfaceIds);
4699 // INVALID_OPERATION is normal output for streams not supporting surfaceIds
4700 if (res != OK && res != INVALID_OPERATION) {
4701 ALOGE("%s: failed to query stream %d unique surface IDs",
4702 __FUNCTION__, streamId);
4703 return res;
4704 }
4705 if (res == OK) {
4706 uniqueSurfaceIdMap.insert({streamId, std::move(uniqueSurfaceIds)});
4707 }
4708
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004709 if (mUseHalBufManager) {
Yin-Chia Yeh110342b2018-11-19 11:47:46 -08004710 if (outputStream->isAbandoned()) {
Yin-Chia Yeha1b56c82019-03-27 15:50:39 -07004711 ALOGV("%s: stream %d is abandoned, skipping request", __FUNCTION__, streamId);
Yin-Chia Yeh110342b2018-11-19 11:47:46 -08004712 return TIMED_OUT;
4713 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004714 // HAL will request buffer through requestStreamBuffer API
Emilian Peevf4816702020-04-03 15:44:51 -07004715 camera_stream_buffer_t& buffer = outputBuffers->editItemAt(j);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004716 buffer.stream = outputStream->asHalStream();
4717 buffer.buffer = nullptr;
Emilian Peevf4816702020-04-03 15:44:51 -07004718 buffer.status = CAMERA_BUFFER_STATUS_OK;
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004719 buffer.acquire_fence = -1;
4720 buffer.release_fence = -1;
Emilian Peevf0348ae2021-01-13 13:39:45 -08004721 // Mark the output stream as unpreparable to block clients from calling
4722 // 'prepare' after this request reaches CameraHal and before the respective
4723 // buffers are requested.
4724 outputStream->markUnpreparable();
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004725 } else {
4726 res = outputStream->getBuffer(&outputBuffers->editItemAt(j),
4727 waitDuration,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07004728 captureRequest->mOutputSurfaces[streamId]);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004729 if (res != OK) {
4730 // Can't get output buffer from gralloc queue - this could be due to
4731 // abandoned queue or other consumer misbehavior, so not a fatal
4732 // error
Yin-Chia Yeha1b56c82019-03-27 15:50:39 -07004733 ALOGV("RequestThread: Can't get output buffer, skipping request:"
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004734 " %s (%d)", strerror(-res), res);
4735
4736 return TIMED_OUT;
4737 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004738 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08004739
4740 {
4741 sp<Camera3Device> parent = mParent.promote();
4742 if (parent != nullptr) {
4743 const String8& streamCameraId = outputStream->getPhysicalCameraId();
4744 for (const auto& settings : captureRequest->mSettingsList) {
4745 if ((streamCameraId.isEmpty() &&
4746 parent->getId() == settings.cameraId.c_str()) ||
4747 streamCameraId == settings.cameraId.c_str()) {
4748 outputStream->fireBufferRequestForFrameNumber(
4749 captureRequest->mResultExtras.frameNumber,
4750 settings.metadata);
4751 }
4752 }
4753 }
4754 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07004755
Shuzhen Wang5c22c152017-12-31 17:12:25 -08004756 String8 physicalCameraId = outputStream->getPhysicalCameraId();
4757
4758 if (!physicalCameraId.isEmpty()) {
4759 // Physical stream isn't supported for input request.
4760 if (halRequest->input_buffer) {
4761 CLOGE("Physical stream is not supported for input request");
4762 return INVALID_OPERATION;
4763 }
4764 requestedPhysicalCameras.insert(physicalCameraId);
4765 }
4766 halRequest->num_output_buffers++;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004767 }
4768 totalNumBuffers += halRequest->num_output_buffers;
4769
4770 // Log request in the in-flight queue
Shuzhen Wang4a472662017-02-26 23:29:04 -08004771 // If this request list is for constrained high speed recording (not
4772 // preview), and the current request is not the last one in the batch,
4773 // do not send callback to the app.
4774 bool hasCallback = true;
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07004775 if (batchedRequest && i != mNextRequests.size()-1) {
Shuzhen Wang4a472662017-02-26 23:29:04 -08004776 hasCallback = false;
4777 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01004778 bool isStillCapture = false;
Shuzhen Wang26abaf42018-08-28 15:41:20 -07004779 bool isZslCapture = false;
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08004780 const camera_metadata_t* settings = halRequest->settings;
4781 bool shouldUnlockSettings = false;
4782 if (settings == nullptr) {
4783 shouldUnlockSettings = true;
4784 settings = captureRequest->mSettingsList.begin()->metadata.getAndLock();
4785 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01004786 if (!mNextRequests[0].captureRequest->mSettingsList.begin()->metadata.isEmpty()) {
4787 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08004788 find_camera_metadata_ro_entry(settings, ANDROID_CONTROL_CAPTURE_INTENT, &e);
Emilian Peev9dd21f42018-08-03 13:39:29 +01004789 if ((e.count > 0) && (e.data.u8[0] == ANDROID_CONTROL_CAPTURE_INTENT_STILL_CAPTURE)) {
4790 isStillCapture = true;
4791 ATRACE_ASYNC_BEGIN("still capture", mNextRequests[i].halRequest.frame_number);
4792 }
Shuzhen Wang26abaf42018-08-28 15:41:20 -07004793
Emilian Peevaf8416e2021-02-04 17:52:43 -08004794 e = camera_metadata_ro_entry_t();
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08004795 find_camera_metadata_ro_entry(settings, ANDROID_CONTROL_ENABLE_ZSL, &e);
Shuzhen Wang26abaf42018-08-28 15:41:20 -07004796 if ((e.count > 0) && (e.data.u8[0] == ANDROID_CONTROL_ENABLE_ZSL_TRUE)) {
4797 isZslCapture = true;
4798 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01004799 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004800 res = parent->registerInFlight(halRequest->frame_number,
4801 totalNumBuffers, captureRequest->mResultExtras,
4802 /*hasInput*/halRequest->input_buffer != NULL,
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07004803 hasCallback,
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08004804 calculateMaxExpectedDuration(settings),
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004805 requestedPhysicalCameras, isStillCapture, isZslCapture,
4806 captureRequest->mRotateAndCropAuto, mPrevCameraIdsWithZoom,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07004807 (mUseHalBufManager) ? uniqueSurfaceIdMap :
Shuzhen Wang316781a2020-08-18 18:11:01 -07004808 SurfaceMap{}, captureRequest->mRequestTimeNs);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004809 ALOGVV("%s: registered in flight requestId = %" PRId32 ", frameNumber = %" PRId64
4810 ", burstId = %" PRId32 ".",
4811 __FUNCTION__,
4812 captureRequest->mResultExtras.requestId, captureRequest->mResultExtras.frameNumber,
4813 captureRequest->mResultExtras.burstId);
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08004814
4815 if (shouldUnlockSettings) {
4816 captureRequest->mSettingsList.begin()->metadata.unlock(settings);
4817 }
4818
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004819 if (res != OK) {
4820 SET_ERR("RequestThread: Unable to register new in-flight request:"
4821 " %s (%d)", strerror(-res), res);
4822 return INVALID_OPERATION;
4823 }
4824 }
4825
4826 return OK;
4827}
4828
Igor Murashkin1e479c02013-09-06 16:55:14 -07004829CameraMetadata Camera3Device::RequestThread::getLatestRequest() const {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004830 ATRACE_CALL();
Igor Murashkin1e479c02013-09-06 16:55:14 -07004831 Mutex::Autolock al(mLatestRequestMutex);
4832
4833 ALOGV("RequestThread::%s", __FUNCTION__);
4834
4835 return mLatestRequest;
4836}
4837
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004838bool Camera3Device::RequestThread::isStreamPending(
4839 sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004840 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004841 Mutex::Autolock l(mRequestLock);
4842
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004843 for (const auto& nextRequest : mNextRequests) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004844 if (!nextRequest.submitted) {
4845 for (const auto& s : nextRequest.captureRequest->mOutputStreams) {
4846 if (stream == s) return true;
4847 }
4848 if (stream == nextRequest.captureRequest->mInputStream) return true;
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004849 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004850 }
4851
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004852 for (const auto& request : mRequestQueue) {
4853 for (const auto& s : request->mOutputStreams) {
4854 if (stream == s) return true;
4855 }
4856 if (stream == request->mInputStream) return true;
4857 }
4858
4859 for (const auto& request : mRepeatingRequests) {
4860 for (const auto& s : request->mOutputStreams) {
4861 if (stream == s) return true;
4862 }
4863 if (stream == request->mInputStream) return true;
4864 }
4865
4866 return false;
4867}
Jianing Weicb0652e2014-03-12 18:29:36 -07004868
Emilian Peev40ead602017-09-26 15:46:36 +01004869bool Camera3Device::RequestThread::isOutputSurfacePending(int streamId, size_t surfaceId) {
4870 ATRACE_CALL();
4871 Mutex::Autolock l(mRequestLock);
4872
4873 for (const auto& nextRequest : mNextRequests) {
4874 for (const auto& s : nextRequest.captureRequest->mOutputSurfaces) {
4875 if (s.first == streamId) {
4876 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
4877 if (it != s.second.end()) {
4878 return true;
4879 }
4880 }
4881 }
4882 }
4883
4884 for (const auto& request : mRequestQueue) {
4885 for (const auto& s : request->mOutputSurfaces) {
4886 if (s.first == streamId) {
4887 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
4888 if (it != s.second.end()) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07004889 return true;
Emilian Peev40ead602017-09-26 15:46:36 +01004890 }
4891 }
4892 }
4893 }
4894
4895 for (const auto& request : mRepeatingRequests) {
4896 for (const auto& s : request->mOutputSurfaces) {
4897 if (s.first == streamId) {
4898 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
4899 if (it != s.second.end()) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07004900 return true;
Emilian Peev40ead602017-09-26 15:46:36 +01004901 }
4902 }
4903 }
4904 }
4905
4906 return false;
4907}
4908
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004909void Camera3Device::RequestThread::signalPipelineDrain(const std::vector<int>& streamIds) {
4910 if (!mUseHalBufManager) {
4911 ALOGE("%s called for camera device not supporting HAL buffer management", __FUNCTION__);
4912 return;
4913 }
4914
4915 Mutex::Autolock pl(mPauseLock);
4916 if (mPaused) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07004917 mInterface->signalPipelineDrain(streamIds);
4918 return;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004919 }
4920 // If request thread is still busy, wait until paused then notify HAL
4921 mNotifyPipelineDrain = true;
4922 mStreamIdsToBeDrained = streamIds;
4923}
4924
Yin-Chia Yehe52b8fa2020-07-28 00:17:58 -07004925void Camera3Device::RequestThread::resetPipelineDrain() {
4926 Mutex::Autolock pl(mPauseLock);
4927 mNotifyPipelineDrain = false;
4928 mStreamIdsToBeDrained.clear();
4929}
4930
Emilian Peevc0fe54c2020-03-11 14:05:07 -07004931void Camera3Device::RequestThread::clearPreviousRequest() {
4932 Mutex::Autolock l(mRequestLock);
4933 mPrevRequest.clear();
4934}
4935
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004936status_t Camera3Device::RequestThread::switchToOffline(
4937 const std::vector<int32_t>& streamsToKeep,
4938 /*out*/hardware::camera::device::V3_6::CameraOfflineSessionInfo* offlineSessionInfo,
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004939 /*out*/sp<hardware::camera::device::V3_6::ICameraOfflineSession>* offlineSession,
4940 /*out*/camera3::BufferRecords* bufferRecords) {
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004941 Mutex::Autolock l(mRequestLock);
4942 clearRepeatingRequestsLocked(/*lastFrameNumber*/nullptr);
4943
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004944 // Wait until request thread is fully stopped
4945 // TBD: check if request thread is being paused by other APIs (shouldn't be)
4946
4947 // We could also check for mRepeatingRequests.empty(), but the API interface
4948 // is serialized by Camera3Device::mInterfaceLock so no one should be able to submit any
4949 // new requests during the call; hence skip that check.
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004950 bool queueEmpty = mNextRequests.empty() && mRequestQueue.empty();
4951 while (!queueEmpty) {
4952 status_t res = mRequestSubmittedSignal.waitRelative(mRequestLock, kRequestSubmitTimeout);
4953 if (res == TIMED_OUT) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004954 ALOGE("%s: request thread failed to submit one request within timeout!", __FUNCTION__);
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004955 return res;
4956 } else if (res != OK) {
4957 ALOGE("%s: request thread failed to submit a request: %s (%d)!",
4958 __FUNCTION__, strerror(-res), res);
4959 return res;
4960 }
4961 queueEmpty = mNextRequests.empty() && mRequestQueue.empty();
4962 }
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004963
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004964 return mInterface->switchToOffline(
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004965 streamsToKeep, offlineSessionInfo, offlineSession, bufferRecords);
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004966}
4967
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004968status_t Camera3Device::RequestThread::setRotateAndCropAutoBehavior(
4969 camera_metadata_enum_android_scaler_rotate_and_crop_t rotateAndCropValue) {
4970 ATRACE_CALL();
4971 Mutex::Autolock l(mTriggerMutex);
4972 if (rotateAndCropValue == ANDROID_SCALER_ROTATE_AND_CROP_AUTO) {
4973 return BAD_VALUE;
4974 }
4975 mRotateAndCropOverride = rotateAndCropValue;
4976 return OK;
4977}
4978
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004979status_t Camera3Device::RequestThread::setCameraMute(bool enabled) {
4980 ATRACE_CALL();
4981 Mutex::Autolock l(mTriggerMutex);
4982 if (enabled != mCameraMute) {
4983 mCameraMute = enabled;
4984 mCameraMuteChanged = true;
4985 }
4986 return OK;
4987}
4988
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07004989nsecs_t Camera3Device::getExpectedInFlightDuration() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004990 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004991 std::lock_guard<std::mutex> l(mInFlightLock);
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07004992 return mExpectedInflightDuration > kMinInflightDuration ?
4993 mExpectedInflightDuration : kMinInflightDuration;
4994}
4995
Emilian Peevaebbe412018-01-15 13:53:24 +00004996void Camera3Device::RequestThread::cleanupPhysicalSettings(sp<CaptureRequest> request,
Emilian Peevf4816702020-04-03 15:44:51 -07004997 camera_capture_request_t *halRequest) {
Emilian Peevaebbe412018-01-15 13:53:24 +00004998 if ((request == nullptr) || (halRequest == nullptr)) {
4999 ALOGE("%s: Invalid request!", __FUNCTION__);
5000 return;
5001 }
5002
5003 if (halRequest->num_physcam_settings > 0) {
5004 if (halRequest->physcam_id != nullptr) {
5005 delete [] halRequest->physcam_id;
5006 halRequest->physcam_id = nullptr;
5007 }
5008 if (halRequest->physcam_settings != nullptr) {
5009 auto it = ++(request->mSettingsList.begin());
5010 size_t i = 0;
5011 for (; it != request->mSettingsList.end(); it++, i++) {
5012 it->metadata.unlock(halRequest->physcam_settings[i]);
5013 }
5014 delete [] halRequest->physcam_settings;
5015 halRequest->physcam_settings = nullptr;
5016 }
5017 }
5018}
5019
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005020void Camera3Device::RequestThread::cleanUpFailedRequests(bool sendRequestError) {
5021 if (mNextRequests.empty()) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005022 return;
5023 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005024
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005025 for (auto& nextRequest : mNextRequests) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005026 // Skip the ones that have been submitted successfully.
5027 if (nextRequest.submitted) {
5028 continue;
5029 }
5030
5031 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
Emilian Peevf4816702020-04-03 15:44:51 -07005032 camera_capture_request_t* halRequest = &nextRequest.halRequest;
5033 Vector<camera_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005034
5035 if (halRequest->settings != NULL) {
Emilian Peevaebbe412018-01-15 13:53:24 +00005036 captureRequest->mSettingsList.begin()->metadata.unlock(halRequest->settings);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005037 }
5038
Emilian Peevaebbe412018-01-15 13:53:24 +00005039 cleanupPhysicalSettings(captureRequest, halRequest);
5040
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005041 if (captureRequest->mInputStream != NULL) {
Emilian Peevf4816702020-04-03 15:44:51 -07005042 captureRequest->mInputBuffer.status = CAMERA_BUFFER_STATUS_ERROR;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005043 captureRequest->mInputStream->returnInputBuffer(captureRequest->mInputBuffer);
5044 }
5045
Yin-Chia Yeh21cb47b2019-01-18 15:08:17 -08005046 // No output buffer can be returned when using HAL buffer manager
5047 if (!mUseHalBufManager) {
5048 for (size_t i = 0; i < halRequest->num_output_buffers; i++) {
5049 //Buffers that failed processing could still have
5050 //valid acquire fence.
5051 int acquireFence = (*outputBuffers)[i].acquire_fence;
5052 if (0 <= acquireFence) {
5053 close(acquireFence);
5054 outputBuffers->editItemAt(i).acquire_fence = -1;
5055 }
Emilian Peevf4816702020-04-03 15:44:51 -07005056 outputBuffers->editItemAt(i).status = CAMERA_BUFFER_STATUS_ERROR;
Yin-Chia Yeh21cb47b2019-01-18 15:08:17 -08005057 captureRequest->mOutputStreams.editItemAt(i)->returnBuffer((*outputBuffers)[i], 0,
5058 /*timestampIncreasing*/true, std::vector<size_t> (),
5059 captureRequest->mResultExtras.frameNumber);
Emilian Peevc58cf4c2017-05-11 17:23:41 +01005060 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005061 }
5062
5063 if (sendRequestError) {
5064 Mutex::Autolock l(mRequestLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005065 sp<NotificationListener> listener = mListener.promote();
5066 if (listener != NULL) {
5067 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08005068 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005069 captureRequest->mResultExtras);
5070 }
5071 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07005072
5073 // Remove yet-to-be submitted inflight request from inflightMap
5074 {
5075 sp<Camera3Device> parent = mParent.promote();
5076 if (parent != NULL) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005077 std::lock_guard<std::mutex> l(parent->mInFlightLock);
Shuzhen Wangcadb3302016-11-04 14:17:56 -07005078 ssize_t idx = parent->mInFlightMap.indexOfKey(captureRequest->mResultExtras.frameNumber);
5079 if (idx >= 0) {
5080 ALOGV("%s: Remove inflight request from queue: frameNumber %" PRId64,
5081 __FUNCTION__, captureRequest->mResultExtras.frameNumber);
5082 parent->removeInFlightMapEntryLocked(idx);
5083 }
5084 }
5085 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005086 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07005087
5088 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005089 mNextRequests.clear();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005090}
5091
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005092void Camera3Device::RequestThread::waitForNextRequestBatch() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005093 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005094 // Optimized a bit for the simple steady-state case (single repeating
5095 // request), to avoid putting that request in the queue temporarily.
5096 Mutex::Autolock l(mRequestLock);
5097
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005098 assert(mNextRequests.empty());
5099
5100 NextRequest nextRequest;
5101 nextRequest.captureRequest = waitForNextRequestLocked();
5102 if (nextRequest.captureRequest == nullptr) {
5103 return;
5104 }
5105
Emilian Peevf4816702020-04-03 15:44:51 -07005106 nextRequest.halRequest = camera_capture_request_t();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005107 nextRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005108 mNextRequests.add(nextRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005109
5110 // Wait for additional requests
5111 const size_t batchSize = nextRequest.captureRequest->mBatchSize;
5112
5113 for (size_t i = 1; i < batchSize; i++) {
5114 NextRequest additionalRequest;
5115 additionalRequest.captureRequest = waitForNextRequestLocked();
5116 if (additionalRequest.captureRequest == nullptr) {
5117 break;
5118 }
5119
Emilian Peevf4816702020-04-03 15:44:51 -07005120 additionalRequest.halRequest = camera_capture_request_t();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005121 additionalRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005122 mNextRequests.add(additionalRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005123 }
5124
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005125 if (mNextRequests.size() < batchSize) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08005126 ALOGE("RequestThread: only get %zu out of %zu requests. Skipping requests.",
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005127 mNextRequests.size(), batchSize);
5128 cleanUpFailedRequests(/*sendRequestError*/true);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005129 }
5130
5131 return;
5132}
5133
5134sp<Camera3Device::CaptureRequest>
5135 Camera3Device::RequestThread::waitForNextRequestLocked() {
5136 status_t res;
5137 sp<CaptureRequest> nextRequest;
5138
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005139 while (mRequestQueue.empty()) {
5140 if (!mRepeatingRequests.empty()) {
5141 // Always atomically enqueue all requests in a repeating request
5142 // list. Guarantees a complete in-sequence set of captures to
5143 // application.
5144 const RequestList &requests = mRepeatingRequests;
Shuzhen Wang316781a2020-08-18 18:11:01 -07005145 if (mFirstRepeating) {
5146 mFirstRepeating = false;
5147 } else {
5148 for (auto& request : requests) {
5149 // For repeating requests, override timestamp request using
5150 // the time a request is inserted into the request queue,
5151 // because the original repeating request will have an old
5152 // fixed timestamp.
5153 request->mRequestTimeNs = systemTime();
5154 }
5155 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005156 RequestList::const_iterator firstRequest =
5157 requests.begin();
5158 nextRequest = *firstRequest;
5159 mRequestQueue.insert(mRequestQueue.end(),
5160 ++firstRequest,
5161 requests.end());
5162 // No need to wait any longer
Jianing Weicb0652e2014-03-12 18:29:36 -07005163
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005164 mRepeatingLastFrameNumber = mFrameNumber + requests.size() - 1;
Jianing Weicb0652e2014-03-12 18:29:36 -07005165
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005166 break;
5167 }
5168
5169 res = mRequestSignal.waitRelative(mRequestLock, kRequestTimeout);
5170
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005171 if ((mRequestQueue.empty() && mRepeatingRequests.empty()) ||
5172 exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005173 Mutex::Autolock pl(mPauseLock);
5174 if (mPaused == false) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005175 ALOGV("%s: RequestThread: Going idle", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005176 mPaused = true;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07005177 if (mNotifyPipelineDrain) {
5178 mInterface->signalPipelineDrain(mStreamIdsToBeDrained);
5179 mNotifyPipelineDrain = false;
5180 mStreamIdsToBeDrained.clear();
5181 }
Yin-Chia Yehc300a072019-02-13 14:56:57 -08005182 // Let the tracker know
5183 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5184 if (statusTracker != 0) {
5185 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
5186 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005187 sp<Camera3Device> parent = mParent.promote();
5188 if (parent != nullptr) {
5189 parent->mRequestBufferSM.onRequestThreadPaused();
5190 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005191 }
5192 // Stop waiting for now and let thread management happen
5193 return NULL;
5194 }
5195 }
5196
5197 if (nextRequest == NULL) {
5198 // Don't have a repeating request already in hand, so queue
5199 // must have an entry now.
5200 RequestList::iterator firstRequest =
5201 mRequestQueue.begin();
5202 nextRequest = *firstRequest;
5203 mRequestQueue.erase(firstRequest);
Shuzhen Wang9d066012016-09-30 11:30:20 -07005204 if (mRequestQueue.empty() && !nextRequest->mRepeating) {
5205 sp<NotificationListener> listener = mListener.promote();
5206 if (listener != NULL) {
5207 listener->notifyRequestQueueEmpty();
5208 }
5209 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005210 }
5211
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005212 // In case we've been unpaused by setPaused clearing mDoPause, need to
5213 // update internal pause state (capture/setRepeatingRequest unpause
5214 // directly).
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005215 Mutex::Autolock pl(mPauseLock);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005216 if (mPaused) {
5217 ALOGV("%s: RequestThread: Unpaused", __FUNCTION__);
5218 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5219 if (statusTracker != 0) {
5220 statusTracker->markComponentActive(mStatusId);
5221 }
5222 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005223 mPaused = false;
5224
5225 // Check if we've reconfigured since last time, and reset the preview
5226 // request if so. Can't use 'NULL request == repeat' across configure calls.
5227 if (mReconfigured) {
5228 mPrevRequest.clear();
5229 mReconfigured = false;
5230 }
5231
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005232 if (nextRequest != NULL) {
5233 nextRequest->mResultExtras.frameNumber = mFrameNumber++;
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07005234 nextRequest->mResultExtras.afTriggerId = mCurrentAfTriggerId;
5235 nextRequest->mResultExtras.precaptureTriggerId = mCurrentPreCaptureTriggerId;
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07005236
5237 // Since RequestThread::clear() removes buffers from the input stream,
5238 // get the right buffer here before unlocking mRequestLock
5239 if (nextRequest->mInputStream != NULL) {
5240 res = nextRequest->mInputStream->getInputBuffer(&nextRequest->mInputBuffer);
5241 if (res != OK) {
5242 // Can't get input buffer from gralloc queue - this could be due to
5243 // disconnected queue or other producer misbehavior, so not a fatal
5244 // error
5245 ALOGE("%s: Can't get input buffer, skipping request:"
5246 " %s (%d)", __FUNCTION__, strerror(-res), res);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005247
5248 sp<NotificationListener> listener = mListener.promote();
5249 if (listener != NULL) {
5250 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08005251 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07005252 nextRequest->mResultExtras);
5253 }
5254 return NULL;
5255 }
5256 }
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005257 }
Chien-Yu Chend196d612015-06-22 19:49:01 -07005258
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005259 return nextRequest;
5260}
5261
5262bool Camera3Device::RequestThread::waitIfPaused() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005263 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005264 status_t res;
5265 Mutex::Autolock l(mPauseLock);
5266 while (mDoPause) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005267 if (mPaused == false) {
5268 mPaused = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005269 ALOGV("%s: RequestThread: Paused", __FUNCTION__);
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07005270 if (mNotifyPipelineDrain) {
5271 mInterface->signalPipelineDrain(mStreamIdsToBeDrained);
5272 mNotifyPipelineDrain = false;
5273 mStreamIdsToBeDrained.clear();
5274 }
Yin-Chia Yehc300a072019-02-13 14:56:57 -08005275 // Let the tracker know
5276 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5277 if (statusTracker != 0) {
5278 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
5279 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005280 sp<Camera3Device> parent = mParent.promote();
5281 if (parent != nullptr) {
5282 parent->mRequestBufferSM.onRequestThreadPaused();
5283 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005284 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005285
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005286 res = mDoPauseSignal.waitRelative(mPauseLock, kRequestTimeout);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005287 if (res == TIMED_OUT || exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005288 return true;
5289 }
5290 }
5291 // We don't set mPaused to false here, because waitForNextRequest needs
5292 // to further manage the paused state in case of starvation.
5293 return false;
5294}
5295
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005296void Camera3Device::RequestThread::unpauseForNewRequests() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005297 ATRACE_CALL();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005298 // With work to do, mark thread as unpaused.
5299 // If paused by request (setPaused), don't resume, to avoid
5300 // extra signaling/waiting overhead to waitUntilPaused
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005301 mRequestSignal.signal();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005302 Mutex::Autolock p(mPauseLock);
5303 if (!mDoPause) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005304 ALOGV("%s: RequestThread: Going active", __FUNCTION__);
5305 if (mPaused) {
5306 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5307 if (statusTracker != 0) {
5308 statusTracker->markComponentActive(mStatusId);
5309 }
5310 }
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005311 mPaused = false;
5312 }
5313}
5314
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07005315void Camera3Device::RequestThread::setErrorState(const char *fmt, ...) {
5316 sp<Camera3Device> parent = mParent.promote();
5317 if (parent != NULL) {
5318 va_list args;
5319 va_start(args, fmt);
5320
5321 parent->setErrorStateV(fmt, args);
5322
5323 va_end(args);
5324 }
5325}
5326
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005327status_t Camera3Device::RequestThread::insertTriggers(
5328 const sp<CaptureRequest> &request) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005329 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005330 Mutex::Autolock al(mTriggerMutex);
5331
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07005332 sp<Camera3Device> parent = mParent.promote();
5333 if (parent == NULL) {
5334 CLOGE("RequestThread: Parent is gone");
5335 return DEAD_OBJECT;
5336 }
5337
Emilian Peevaebbe412018-01-15 13:53:24 +00005338 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005339 size_t count = mTriggerMap.size();
5340
5341 for (size_t i = 0; i < count; ++i) {
5342 RequestTrigger trigger = mTriggerMap.valueAt(i);
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005343 uint32_t tag = trigger.metadataTag;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07005344
5345 if (tag == ANDROID_CONTROL_AF_TRIGGER_ID || tag == ANDROID_CONTROL_AE_PRECAPTURE_ID) {
5346 bool isAeTrigger = (trigger.metadataTag == ANDROID_CONTROL_AE_PRECAPTURE_ID);
5347 uint32_t triggerId = static_cast<uint32_t>(trigger.entryValue);
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07005348 if (isAeTrigger) {
5349 request->mResultExtras.precaptureTriggerId = triggerId;
5350 mCurrentPreCaptureTriggerId = triggerId;
5351 } else {
5352 request->mResultExtras.afTriggerId = triggerId;
5353 mCurrentAfTriggerId = triggerId;
5354 }
Emilian Peev7e25e5e2017-04-07 15:48:49 +01005355 continue;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07005356 }
5357
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005358 camera_metadata_entry entry = metadata.find(tag);
5359
5360 if (entry.count > 0) {
5361 /**
5362 * Already has an entry for this trigger in the request.
5363 * Rewrite it with our requested trigger value.
5364 */
5365 RequestTrigger oldTrigger = trigger;
5366
5367 oldTrigger.entryValue = entry.data.u8[0];
5368
5369 mTriggerReplacedMap.add(tag, oldTrigger);
5370 } else {
5371 /**
5372 * More typical, no trigger entry, so we just add it
5373 */
5374 mTriggerRemovedMap.add(tag, trigger);
5375 }
5376
5377 status_t res;
5378
5379 switch (trigger.getTagType()) {
5380 case TYPE_BYTE: {
5381 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
5382 res = metadata.update(tag,
5383 &entryValue,
5384 /*count*/1);
5385 break;
5386 }
5387 case TYPE_INT32:
5388 res = metadata.update(tag,
5389 &trigger.entryValue,
5390 /*count*/1);
5391 break;
5392 default:
5393 ALOGE("%s: Type not supported: 0x%x",
5394 __FUNCTION__,
5395 trigger.getTagType());
5396 return INVALID_OPERATION;
5397 }
5398
5399 if (res != OK) {
5400 ALOGE("%s: Failed to update request metadata with trigger tag %s"
5401 ", value %d", __FUNCTION__, trigger.getTagName(),
5402 trigger.entryValue);
5403 return res;
5404 }
5405
5406 ALOGV("%s: Mixed in trigger %s, value %d", __FUNCTION__,
5407 trigger.getTagName(),
5408 trigger.entryValue);
5409 }
5410
5411 mTriggerMap.clear();
5412
5413 return count;
5414}
5415
5416status_t Camera3Device::RequestThread::removeTriggers(
5417 const sp<CaptureRequest> &request) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005418 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005419 Mutex::Autolock al(mTriggerMutex);
5420
Emilian Peevaebbe412018-01-15 13:53:24 +00005421 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005422
5423 /**
5424 * Replace all old entries with their old values.
5425 */
5426 for (size_t i = 0; i < mTriggerReplacedMap.size(); ++i) {
5427 RequestTrigger trigger = mTriggerReplacedMap.valueAt(i);
5428
5429 status_t res;
5430
5431 uint32_t tag = trigger.metadataTag;
5432 switch (trigger.getTagType()) {
5433 case TYPE_BYTE: {
5434 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
5435 res = metadata.update(tag,
5436 &entryValue,
5437 /*count*/1);
5438 break;
5439 }
5440 case TYPE_INT32:
5441 res = metadata.update(tag,
5442 &trigger.entryValue,
5443 /*count*/1);
5444 break;
5445 default:
5446 ALOGE("%s: Type not supported: 0x%x",
5447 __FUNCTION__,
5448 trigger.getTagType());
5449 return INVALID_OPERATION;
5450 }
5451
5452 if (res != OK) {
5453 ALOGE("%s: Failed to restore request metadata with trigger tag %s"
5454 ", trigger value %d", __FUNCTION__,
5455 trigger.getTagName(), trigger.entryValue);
5456 return res;
5457 }
5458 }
5459 mTriggerReplacedMap.clear();
5460
5461 /**
5462 * Remove all new entries.
5463 */
5464 for (size_t i = 0; i < mTriggerRemovedMap.size(); ++i) {
5465 RequestTrigger trigger = mTriggerRemovedMap.valueAt(i);
5466 status_t res = metadata.erase(trigger.metadataTag);
5467
5468 if (res != OK) {
5469 ALOGE("%s: Failed to erase metadata with trigger tag %s"
5470 ", trigger value %d", __FUNCTION__,
5471 trigger.getTagName(), trigger.entryValue);
5472 return res;
5473 }
5474 }
5475 mTriggerRemovedMap.clear();
5476
5477 return OK;
5478}
5479
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04005480status_t Camera3Device::RequestThread::addFakeTriggerIds(
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005481 const sp<CaptureRequest> &request) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08005482 // Trigger ID 0 had special meaning in the HAL2 spec, so avoid it here
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04005483 static const int32_t fakeTriggerId = 1;
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005484 status_t res;
5485
Emilian Peevaebbe412018-01-15 13:53:24 +00005486 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005487
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04005488 // If AF trigger is active, insert a fake AF trigger ID if none already
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005489 // exists
5490 camera_metadata_entry afTrigger = metadata.find(ANDROID_CONTROL_AF_TRIGGER);
5491 camera_metadata_entry afId = metadata.find(ANDROID_CONTROL_AF_TRIGGER_ID);
5492 if (afTrigger.count > 0 &&
5493 afTrigger.data.u8[0] != ANDROID_CONTROL_AF_TRIGGER_IDLE &&
5494 afId.count == 0) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04005495 res = metadata.update(ANDROID_CONTROL_AF_TRIGGER_ID, &fakeTriggerId, 1);
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005496 if (res != OK) return res;
5497 }
5498
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04005499 // If AE precapture trigger is active, insert a fake precapture trigger ID
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005500 // if none already exists
5501 camera_metadata_entry pcTrigger =
5502 metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER);
5503 camera_metadata_entry pcId = metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_ID);
5504 if (pcTrigger.count > 0 &&
5505 pcTrigger.data.u8[0] != ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_IDLE &&
5506 pcId.count == 0) {
5507 res = metadata.update(ANDROID_CONTROL_AE_PRECAPTURE_ID,
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04005508 &fakeTriggerId, 1);
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005509 if (res != OK) return res;
5510 }
5511
5512 return OK;
5513}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005514
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005515bool Camera3Device::RequestThread::overrideAutoRotateAndCrop(
5516 const sp<CaptureRequest> &request) {
5517 ATRACE_CALL();
5518
5519 if (request->mRotateAndCropAuto) {
5520 Mutex::Autolock l(mTriggerMutex);
5521 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
5522
5523 auto rotateAndCropEntry = metadata.find(ANDROID_SCALER_ROTATE_AND_CROP);
5524 if (rotateAndCropEntry.count > 0) {
5525 if (rotateAndCropEntry.data.u8[0] == mRotateAndCropOverride) {
5526 return false;
5527 } else {
5528 rotateAndCropEntry.data.u8[0] = mRotateAndCropOverride;
5529 return true;
5530 }
5531 } else {
5532 uint8_t rotateAndCrop_u8 = mRotateAndCropOverride;
5533 metadata.update(ANDROID_SCALER_ROTATE_AND_CROP,
5534 &rotateAndCrop_u8, 1);
5535 return true;
5536 }
5537 }
5538 return false;
5539}
5540
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005541bool Camera3Device::RequestThread::overrideTestPattern(
5542 const sp<CaptureRequest> &request) {
5543 ATRACE_CALL();
5544
5545 Mutex::Autolock l(mTriggerMutex);
5546
5547 bool changed = false;
5548
5549 int32_t testPatternMode = request->mOriginalTestPatternMode;
5550 int32_t testPatternData[4] = {
5551 request->mOriginalTestPatternData[0],
5552 request->mOriginalTestPatternData[1],
5553 request->mOriginalTestPatternData[2],
5554 request->mOriginalTestPatternData[3]
5555 };
5556
5557 if (mCameraMute) {
5558 testPatternMode = ANDROID_SENSOR_TEST_PATTERN_MODE_SOLID_COLOR;
5559 testPatternData[0] = 0;
5560 testPatternData[1] = 0;
5561 testPatternData[2] = 0;
5562 testPatternData[3] = 0;
5563 }
5564
5565 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
5566
5567 auto testPatternEntry = metadata.find(ANDROID_SENSOR_TEST_PATTERN_MODE);
5568 if (testPatternEntry.count > 0) {
5569 if (testPatternEntry.data.i32[0] != testPatternMode) {
5570 testPatternEntry.data.i32[0] = testPatternMode;
5571 changed = true;
5572 }
5573 } else {
5574 metadata.update(ANDROID_SENSOR_TEST_PATTERN_MODE,
5575 &testPatternMode, 1);
5576 changed = true;
5577 }
5578
5579 auto testPatternColor = metadata.find(ANDROID_SENSOR_TEST_PATTERN_DATA);
5580 if (testPatternColor.count > 0) {
5581 for (size_t i = 0; i < 4; i++) {
5582 if (testPatternColor.data.i32[i] != (int32_t)testPatternData[i]) {
5583 testPatternColor.data.i32[i] = testPatternData[i];
5584 changed = true;
5585 }
5586 }
5587 } else {
5588 metadata.update(ANDROID_SENSOR_TEST_PATTERN_DATA,
5589 (int32_t*)testPatternData, 4);
5590 changed = true;
5591 }
5592
5593 return changed;
5594}
5595
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005596/**
5597 * PreparerThread inner class methods
5598 */
5599
5600Camera3Device::PreparerThread::PreparerThread() :
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07005601 Thread(/*canCallJava*/false), mListener(nullptr),
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005602 mActive(false), mCancelNow(false), mCurrentMaxCount(0), mCurrentPrepareComplete(false) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005603}
5604
5605Camera3Device::PreparerThread::~PreparerThread() {
5606 Thread::requestExitAndWait();
5607 if (mCurrentStream != nullptr) {
5608 mCurrentStream->cancelPrepare();
5609 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
5610 mCurrentStream.clear();
5611 }
5612 clear();
5613}
5614
Ruben Brunkc78ac262015-08-13 17:58:46 -07005615status_t Camera3Device::PreparerThread::prepare(int maxCount, sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005616 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005617 status_t res;
5618
5619 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005620 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005621
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07005622 res = stream->startPrepare(maxCount, true /*blockRequest*/);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005623 if (res == OK) {
5624 // No preparation needed, fire listener right off
5625 ALOGV("%s: Stream %d already prepared", __FUNCTION__, stream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005626 if (listener != NULL) {
5627 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005628 }
5629 return OK;
5630 } else if (res != NOT_ENOUGH_DATA) {
5631 return res;
5632 }
5633
5634 // Need to prepare, start up thread if necessary
5635 if (!mActive) {
5636 // mRunning will change to false before the thread fully shuts down, so wait to be sure it
5637 // isn't running
5638 Thread::requestExitAndWait();
5639 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
5640 if (res != OK) {
5641 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__, res, strerror(-res));
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005642 if (listener != NULL) {
5643 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005644 }
5645 return res;
5646 }
5647 mCancelNow = false;
5648 mActive = true;
5649 ALOGV("%s: Preparer stream started", __FUNCTION__);
5650 }
5651
5652 // queue up the work
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005653 mPendingStreams.emplace(maxCount, stream);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005654 ALOGV("%s: Stream %d queued for preparing", __FUNCTION__, stream->getId());
5655
5656 return OK;
5657}
5658
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005659void Camera3Device::PreparerThread::pause() {
5660 ATRACE_CALL();
5661
5662 Mutex::Autolock l(mLock);
5663
5664 std::unordered_map<int, sp<camera3::Camera3StreamInterface> > pendingStreams;
5665 pendingStreams.insert(mPendingStreams.begin(), mPendingStreams.end());
5666 sp<camera3::Camera3StreamInterface> currentStream = mCurrentStream;
5667 int currentMaxCount = mCurrentMaxCount;
5668 mPendingStreams.clear();
5669 mCancelNow = true;
5670 while (mActive) {
5671 auto res = mThreadActiveSignal.waitRelative(mLock, kActiveTimeout);
5672 if (res == TIMED_OUT) {
5673 ALOGE("%s: Timed out waiting on prepare thread!", __FUNCTION__);
5674 return;
5675 } else if (res != OK) {
5676 ALOGE("%s: Encountered an error: %d waiting on prepare thread!", __FUNCTION__, res);
5677 return;
5678 }
5679 }
5680
5681 //Check whether the prepare thread was able to complete the current
5682 //stream. In case work is still pending emplace it along with the rest
5683 //of the streams in the pending list.
5684 if (currentStream != nullptr) {
5685 if (!mCurrentPrepareComplete) {
5686 pendingStreams.emplace(currentMaxCount, currentStream);
5687 }
5688 }
5689
5690 mPendingStreams.insert(pendingStreams.begin(), pendingStreams.end());
5691 for (const auto& it : mPendingStreams) {
5692 it.second->cancelPrepare();
5693 }
5694}
5695
5696status_t Camera3Device::PreparerThread::resume() {
5697 ATRACE_CALL();
5698 status_t res;
5699
5700 Mutex::Autolock l(mLock);
5701 sp<NotificationListener> listener = mListener.promote();
5702
5703 if (mActive) {
5704 ALOGE("%s: Trying to resume an already active prepare thread!", __FUNCTION__);
5705 return NO_INIT;
5706 }
5707
5708 auto it = mPendingStreams.begin();
5709 for (; it != mPendingStreams.end();) {
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07005710 res = it->second->startPrepare(it->first, true /*blockRequest*/);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005711 if (res == OK) {
5712 if (listener != NULL) {
5713 listener->notifyPrepared(it->second->getId());
5714 }
5715 it = mPendingStreams.erase(it);
5716 } else if (res != NOT_ENOUGH_DATA) {
5717 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__,
5718 res, strerror(-res));
5719 it = mPendingStreams.erase(it);
5720 } else {
5721 it++;
5722 }
5723 }
5724
5725 if (mPendingStreams.empty()) {
5726 return OK;
5727 }
5728
5729 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
5730 if (res != OK) {
5731 ALOGE("%s: Unable to start preparer stream: %d (%s)",
5732 __FUNCTION__, res, strerror(-res));
5733 return res;
5734 }
5735 mCancelNow = false;
5736 mActive = true;
5737 ALOGV("%s: Preparer stream started", __FUNCTION__);
5738
5739 return OK;
5740}
5741
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005742status_t Camera3Device::PreparerThread::clear() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005743 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005744 Mutex::Autolock l(mLock);
5745
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005746 for (const auto& it : mPendingStreams) {
5747 it.second->cancelPrepare();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005748 }
5749 mPendingStreams.clear();
5750 mCancelNow = true;
5751
5752 return OK;
5753}
5754
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005755void Camera3Device::PreparerThread::setNotificationListener(wp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005756 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005757 Mutex::Autolock l(mLock);
5758 mListener = listener;
5759}
5760
5761bool Camera3Device::PreparerThread::threadLoop() {
5762 status_t res;
5763 {
5764 Mutex::Autolock l(mLock);
5765 if (mCurrentStream == nullptr) {
5766 // End thread if done with work
5767 if (mPendingStreams.empty()) {
5768 ALOGV("%s: Preparer stream out of work", __FUNCTION__);
5769 // threadLoop _must not_ re-acquire mLock after it sets mActive to false; would
5770 // cause deadlock with prepare()'s requestExitAndWait triggered by !mActive.
5771 mActive = false;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005772 mThreadActiveSignal.signal();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005773 return false;
5774 }
5775
5776 // Get next stream to prepare
5777 auto it = mPendingStreams.begin();
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005778 mCurrentStream = it->second;
5779 mCurrentMaxCount = it->first;
5780 mCurrentPrepareComplete = false;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005781 mPendingStreams.erase(it);
5782 ATRACE_ASYNC_BEGIN("stream prepare", mCurrentStream->getId());
5783 ALOGV("%s: Preparing stream %d", __FUNCTION__, mCurrentStream->getId());
5784 } else if (mCancelNow) {
5785 mCurrentStream->cancelPrepare();
5786 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
5787 ALOGV("%s: Cancelling stream %d prepare", __FUNCTION__, mCurrentStream->getId());
5788 mCurrentStream.clear();
5789 mCancelNow = false;
5790 return true;
5791 }
5792 }
5793
5794 res = mCurrentStream->prepareNextBuffer();
5795 if (res == NOT_ENOUGH_DATA) return true;
5796 if (res != OK) {
5797 // Something bad happened; try to recover by cancelling prepare and
5798 // signalling listener anyway
5799 ALOGE("%s: Stream %d returned error %d (%s) during prepare", __FUNCTION__,
5800 mCurrentStream->getId(), res, strerror(-res));
5801 mCurrentStream->cancelPrepare();
5802 }
5803
5804 // This stream has finished, notify listener
5805 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005806 sp<NotificationListener> listener = mListener.promote();
5807 if (listener != NULL) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005808 ALOGV("%s: Stream %d prepare done, signaling listener", __FUNCTION__,
5809 mCurrentStream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005810 listener->notifyPrepared(mCurrentStream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005811 }
5812
5813 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
5814 mCurrentStream.clear();
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005815 mCurrentPrepareComplete = true;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005816
5817 return true;
5818}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005819
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005820status_t Camera3Device::RequestBufferStateMachine::initialize(
5821 sp<camera3::StatusTracker> statusTracker) {
5822 if (statusTracker == nullptr) {
5823 ALOGE("%s: statusTracker is null", __FUNCTION__);
5824 return BAD_VALUE;
5825 }
5826
5827 std::lock_guard<std::mutex> lock(mLock);
5828 mStatusTracker = statusTracker;
Yin-Chia Yeh87b3ec02019-06-03 10:44:39 -07005829 mRequestBufferStatusId = statusTracker->addComponent("BufferRequestSM");
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005830 return OK;
5831}
5832
5833bool Camera3Device::RequestBufferStateMachine::startRequestBuffer() {
5834 std::lock_guard<std::mutex> lock(mLock);
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08005835 if (mStatus == RB_STATUS_READY || mStatus == RB_STATUS_PENDING_STOP) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005836 mRequestBufferOngoing = true;
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08005837 notifyTrackerLocked(/*active*/true);
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005838 return true;
5839 }
5840 return false;
5841}
5842
5843void Camera3Device::RequestBufferStateMachine::endRequestBuffer() {
5844 std::lock_guard<std::mutex> lock(mLock);
5845 if (!mRequestBufferOngoing) {
5846 ALOGE("%s called without a successful startRequestBuffer call first!", __FUNCTION__);
5847 return;
5848 }
5849 mRequestBufferOngoing = false;
5850 if (mStatus == RB_STATUS_PENDING_STOP) {
5851 checkSwitchToStopLocked();
5852 }
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08005853 notifyTrackerLocked(/*active*/false);
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005854}
5855
5856void Camera3Device::RequestBufferStateMachine::onStreamsConfigured() {
5857 std::lock_guard<std::mutex> lock(mLock);
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005858 mSwitchedToOffline = false;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005859 mStatus = RB_STATUS_READY;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005860 return;
5861}
5862
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08005863void Camera3Device::RequestBufferStateMachine::onSubmittingRequest() {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005864 std::lock_guard<std::mutex> lock(mLock);
5865 mRequestThreadPaused = false;
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08005866 // inflight map register actually happens in prepareHalRequest now, but it is close enough
5867 // approximation.
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005868 mInflightMapEmpty = false;
5869 if (mStatus == RB_STATUS_STOPPED) {
5870 mStatus = RB_STATUS_READY;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005871 }
5872 return;
5873}
5874
5875void Camera3Device::RequestBufferStateMachine::onRequestThreadPaused() {
5876 std::lock_guard<std::mutex> lock(mLock);
5877 mRequestThreadPaused = true;
5878 if (mStatus == RB_STATUS_PENDING_STOP) {
5879 checkSwitchToStopLocked();
5880 }
5881 return;
5882}
5883
5884void Camera3Device::RequestBufferStateMachine::onInflightMapEmpty() {
5885 std::lock_guard<std::mutex> lock(mLock);
5886 mInflightMapEmpty = true;
5887 if (mStatus == RB_STATUS_PENDING_STOP) {
5888 checkSwitchToStopLocked();
5889 }
5890 return;
5891}
5892
5893void Camera3Device::RequestBufferStateMachine::onWaitUntilIdle() {
5894 std::lock_guard<std::mutex> lock(mLock);
5895 if (!checkSwitchToStopLocked()) {
5896 mStatus = RB_STATUS_PENDING_STOP;
5897 }
5898 return;
5899}
5900
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005901bool Camera3Device::RequestBufferStateMachine::onSwitchToOfflineSuccess() {
5902 std::lock_guard<std::mutex> lock(mLock);
5903 if (mRequestBufferOngoing) {
5904 ALOGE("%s: HAL must not be requesting buffer after HAL returns switchToOffline!",
5905 __FUNCTION__);
5906 return false;
5907 }
5908 mSwitchedToOffline = true;
5909 mInflightMapEmpty = true;
5910 mRequestThreadPaused = true;
5911 mStatus = RB_STATUS_STOPPED;
5912 return true;
5913}
5914
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005915void Camera3Device::RequestBufferStateMachine::notifyTrackerLocked(bool active) {
5916 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5917 if (statusTracker != nullptr) {
5918 if (active) {
5919 statusTracker->markComponentActive(mRequestBufferStatusId);
5920 } else {
5921 statusTracker->markComponentIdle(mRequestBufferStatusId, Fence::NO_FENCE);
5922 }
5923 }
5924}
5925
5926bool Camera3Device::RequestBufferStateMachine::checkSwitchToStopLocked() {
5927 if (mInflightMapEmpty && mRequestThreadPaused && !mRequestBufferOngoing) {
5928 mStatus = RB_STATUS_STOPPED;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005929 return true;
5930 }
5931 return false;
5932}
5933
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005934bool Camera3Device::startRequestBuffer() {
5935 return mRequestBufferSM.startRequestBuffer();
5936}
Shuzhen Wang268a1362018-10-16 16:32:59 -07005937
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005938void Camera3Device::endRequestBuffer() {
5939 mRequestBufferSM.endRequestBuffer();
5940}
Shuzhen Wang268a1362018-10-16 16:32:59 -07005941
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005942nsecs_t Camera3Device::getWaitDuration() {
5943 return kBaseGetBufferWait + getExpectedInFlightDuration();
5944}
Shuzhen Wang268a1362018-10-16 16:32:59 -07005945
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005946void Camera3Device::getInflightBufferKeys(std::vector<std::pair<int32_t, int32_t>>* out) {
5947 mInterface->getInflightBufferKeys(out);
5948}
Shuzhen Wang268a1362018-10-16 16:32:59 -07005949
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005950void Camera3Device::getInflightRequestBufferKeys(std::vector<uint64_t>* out) {
5951 mInterface->getInflightRequestBufferKeys(out);
5952}
Shuzhen Wang268a1362018-10-16 16:32:59 -07005953
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005954std::vector<sp<Camera3StreamInterface>> Camera3Device::getAllStreams() {
5955 std::vector<sp<Camera3StreamInterface>> ret;
5956 bool hasInputStream = mInputStream != nullptr;
5957 ret.reserve(mOutputStreams.size() + mDeletedStreams.size() + ((hasInputStream) ? 1 : 0));
5958 if (hasInputStream) {
5959 ret.push_back(mInputStream);
Shuzhen Wang268a1362018-10-16 16:32:59 -07005960 }
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005961 for (size_t i = 0; i < mOutputStreams.size(); i++) {
5962 ret.push_back(mOutputStreams[i]);
5963 }
5964 for (size_t i = 0; i < mDeletedStreams.size(); i++) {
5965 ret.push_back(mDeletedStreams[i]);
5966 }
5967 return ret;
Shuzhen Wang268a1362018-10-16 16:32:59 -07005968}
5969
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005970status_t Camera3Device::switchToOffline(
5971 const std::vector<int32_t>& streamsToKeep,
5972 /*out*/ sp<CameraOfflineSessionBase>* session) {
5973 ATRACE_CALL();
5974 if (session == nullptr) {
5975 ALOGE("%s: session must not be null", __FUNCTION__);
5976 return BAD_VALUE;
5977 }
5978
5979 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005980
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005981 bool hasInputStream = mInputStream != nullptr;
5982 int32_t inputStreamId = hasInputStream ? mInputStream->getId() : -1;
5983 bool inputStreamSupportsOffline = hasInputStream ?
5984 mInputStream->getOfflineProcessingSupport() : false;
5985 auto outputStreamIds = mOutputStreams.getStreamIds();
5986 auto streamIds = outputStreamIds;
5987 if (hasInputStream) {
5988 streamIds.push_back(mInputStream->getId());
5989 }
5990
5991 // Check all streams in streamsToKeep supports offline mode
5992 for (auto id : streamsToKeep) {
5993 if (std::find(streamIds.begin(), streamIds.end(), id) == streamIds.end()) {
5994 ALOGE("%s: Unknown stream ID %d", __FUNCTION__, id);
5995 return BAD_VALUE;
5996 } else if (id == inputStreamId) {
5997 if (!inputStreamSupportsOffline) {
5998 ALOGE("%s: input stream %d cannot be switched to offline",
5999 __FUNCTION__, id);
6000 return BAD_VALUE;
6001 }
6002 } else {
6003 sp<camera3::Camera3OutputStreamInterface> stream = mOutputStreams.get(id);
6004 if (!stream->getOfflineProcessingSupport()) {
6005 ALOGE("%s: output stream %d cannot be switched to offline",
6006 __FUNCTION__, id);
6007 return BAD_VALUE;
6008 }
6009 }
6010 }
6011
6012 // TODO: block surface sharing and surface group streams until we can support them
6013
6014 // Stop repeating request, wait until all remaining requests are submitted, then call into
6015 // HAL switchToOffline
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006016 hardware::camera::device::V3_6::CameraOfflineSessionInfo offlineSessionInfo;
6017 sp<hardware::camera::device::V3_6::ICameraOfflineSession> offlineSession;
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006018 camera3::BufferRecords bufferRecords;
6019 status_t ret = mRequestThread->switchToOffline(
6020 streamsToKeep, &offlineSessionInfo, &offlineSession, &bufferRecords);
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006021
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006022 if (ret != OK) {
6023 SET_ERR("Switch to offline failed: %s (%d)", strerror(-ret), ret);
6024 return ret;
6025 }
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006026
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006027 bool succ = mRequestBufferSM.onSwitchToOfflineSuccess();
6028 if (!succ) {
6029 SET_ERR("HAL must not be calling requestStreamBuffers call");
6030 // TODO: block ALL callbacks from HAL till app configured new streams?
6031 return UNKNOWN_ERROR;
6032 }
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006033
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006034 // Verify offlineSessionInfo
6035 std::vector<int32_t> offlineStreamIds;
6036 offlineStreamIds.reserve(offlineSessionInfo.offlineStreams.size());
6037 for (auto offlineStream : offlineSessionInfo.offlineStreams) {
6038 // verify stream IDs
6039 int32_t id = offlineStream.id;
6040 if (std::find(streamIds.begin(), streamIds.end(), id) == streamIds.end()) {
6041 SET_ERR("stream ID %d not found!", id);
6042 return UNKNOWN_ERROR;
6043 }
6044
6045 // When not using HAL buf manager, only allow streams requested by app to be preserved
6046 if (!mUseHalBufManager) {
6047 if (std::find(streamsToKeep.begin(), streamsToKeep.end(), id) == streamsToKeep.end()) {
6048 SET_ERR("stream ID %d must not be switched to offline!", id);
6049 return UNKNOWN_ERROR;
6050 }
6051 }
6052
6053 offlineStreamIds.push_back(id);
6054 sp<Camera3StreamInterface> stream = (id == inputStreamId) ?
6055 static_cast<sp<Camera3StreamInterface>>(mInputStream) :
6056 static_cast<sp<Camera3StreamInterface>>(mOutputStreams.get(id));
6057 // Verify number of outstanding buffers
6058 if (stream->getOutstandingBuffersCount() != offlineStream.numOutstandingBuffers) {
6059 SET_ERR("Offline stream %d # of remaining buffer mismatch: (%zu,%d) (service/HAL)",
6060 id, stream->getOutstandingBuffersCount(), offlineStream.numOutstandingBuffers);
6061 return UNKNOWN_ERROR;
6062 }
6063 }
6064
6065 // Verify all streams to be deleted don't have any outstanding buffers
6066 if (hasInputStream && std::find(offlineStreamIds.begin(), offlineStreamIds.end(),
6067 inputStreamId) == offlineStreamIds.end()) {
6068 if (mInputStream->hasOutstandingBuffers()) {
6069 SET_ERR("Input stream %d still has %zu outstanding buffer!",
6070 inputStreamId, mInputStream->getOutstandingBuffersCount());
6071 return UNKNOWN_ERROR;
6072 }
6073 }
6074
6075 for (const auto& outStreamId : outputStreamIds) {
6076 if (std::find(offlineStreamIds.begin(), offlineStreamIds.end(),
6077 outStreamId) == offlineStreamIds.end()) {
6078 auto outStream = mOutputStreams.get(outStreamId);
6079 if (outStream->hasOutstandingBuffers()) {
6080 SET_ERR("Output stream %d still has %zu outstanding buffer!",
6081 outStreamId, outStream->getOutstandingBuffersCount());
6082 return UNKNOWN_ERROR;
6083 }
6084 }
6085 }
6086
6087 InFlightRequestMap offlineReqs;
6088 // Verify inflight requests and their pending buffers
6089 {
6090 std::lock_guard<std::mutex> l(mInFlightLock);
6091 for (auto offlineReq : offlineSessionInfo.offlineRequests) {
6092 int idx = mInFlightMap.indexOfKey(offlineReq.frameNumber);
6093 if (idx == NAME_NOT_FOUND) {
6094 SET_ERR("Offline request frame number %d not found!", offlineReq.frameNumber);
6095 return UNKNOWN_ERROR;
6096 }
6097
6098 const auto& inflightReq = mInFlightMap.valueAt(idx);
6099 // TODO: check specific stream IDs
6100 size_t numBuffersLeft = static_cast<size_t>(inflightReq.numBuffersLeft);
6101 if (numBuffersLeft != offlineReq.pendingStreams.size()) {
6102 SET_ERR("Offline request # of remaining buffer mismatch: (%d,%d) (service/HAL)",
6103 inflightReq.numBuffersLeft, offlineReq.pendingStreams.size());
6104 return UNKNOWN_ERROR;
6105 }
6106 offlineReqs.add(offlineReq.frameNumber, inflightReq);
6107 }
6108 }
6109
6110 // Create Camera3OfflineSession and transfer object ownership
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006111 // (streams, inflight requests, buffer caches)
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006112 camera3::StreamSet offlineStreamSet;
6113 sp<camera3::Camera3Stream> inputStream;
6114 for (auto offlineStream : offlineSessionInfo.offlineStreams) {
6115 int32_t id = offlineStream.id;
6116 if (mInputStream != nullptr && id == mInputStream->getId()) {
6117 inputStream = mInputStream;
6118 } else {
6119 offlineStreamSet.add(id, mOutputStreams.get(id));
6120 }
6121 }
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006122
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006123 // TODO: check if we need to lock before copying states
6124 // though technically no other thread should be talking to Camera3Device at this point
6125 Camera3OfflineStates offlineStates(
6126 mTagMonitor, mVendorTagId, mUseHalBufManager, mNeedFixupMonochromeTags,
Shuzhen Wangb7b42652020-05-07 11:59:02 -07006127 mUsePartialResult, mNumPartialResults, mLastCompletedRegularFrameNumber,
6128 mLastCompletedReprocessFrameNumber, mLastCompletedZslFrameNumber,
6129 mNextResultFrameNumber, mNextReprocessResultFrameNumber,
6130 mNextZslStillResultFrameNumber, mNextShutterFrameNumber,
6131 mNextReprocessShutterFrameNumber, mNextZslStillShutterFrameNumber,
6132 mDeviceInfo, mPhysicalDeviceInfoMap, mDistortionMappers,
6133 mZoomRatioMappers, mRotateAndCropMappers);
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006134
6135 *session = new Camera3OfflineSession(mId, inputStream, offlineStreamSet,
6136 std::move(bufferRecords), offlineReqs, offlineStates, offlineSession);
6137
6138 // Delete all streams that has been transferred to offline session
6139 Mutex::Autolock l(mLock);
6140 for (auto offlineStream : offlineSessionInfo.offlineStreams) {
6141 int32_t id = offlineStream.id;
6142 if (mInputStream != nullptr && id == mInputStream->getId()) {
6143 mInputStream.clear();
6144 } else {
6145 mOutputStreams.remove(id);
6146 }
6147 }
6148
6149 // disconnect all other streams and switch to UNCONFIGURED state
6150 if (mInputStream != nullptr) {
6151 ret = mInputStream->disconnect();
6152 if (ret != OK) {
6153 SET_ERR_L("disconnect input stream failed!");
6154 return UNKNOWN_ERROR;
6155 }
6156 }
6157
6158 for (auto streamId : mOutputStreams.getStreamIds()) {
6159 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
6160 ret = stream->disconnect();
6161 if (ret != OK) {
6162 SET_ERR_L("disconnect output stream %d failed!", streamId);
6163 return UNKNOWN_ERROR;
6164 }
6165 }
6166
6167 mInputStream.clear();
6168 mOutputStreams.clear();
6169 mNeedConfig = true;
6170 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
6171 mOperatingMode = NO_MODE;
6172 mIsConstrainedHighSpeedConfiguration = false;
Emilian Peevc0fe54c2020-03-11 14:05:07 -07006173 mRequestThread->clearPreviousRequest();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006174
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006175 return OK;
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006176 // TO be done by CameraDeviceClient/Camera3OfflineSession
6177 // register the offline client to camera service
6178 // Setup result passthing threads etc
6179 // Initialize offline session so HAL can start sending callback to it (result Fmq)
6180 // TODO: check how many onIdle callback will be sent
6181 // Java side to make sure the CameraCaptureSession is properly closed
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006182}
6183
Emilian Peevcc0b7952020-01-07 13:54:47 -08006184void Camera3Device::getOfflineStreamIds(std::vector<int> *offlineStreamIds) {
6185 ATRACE_CALL();
6186
6187 if (offlineStreamIds == nullptr) {
6188 return;
6189 }
6190
6191 Mutex::Autolock il(mInterfaceLock);
6192
6193 auto streamIds = mOutputStreams.getStreamIds();
6194 bool hasInputStream = mInputStream != nullptr;
6195 if (hasInputStream && mInputStream->getOfflineProcessingSupport()) {
6196 offlineStreamIds->push_back(mInputStream->getId());
6197 }
6198
6199 for (const auto & streamId : streamIds) {
6200 sp<camera3::Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
6201 // Streams that use the camera buffer manager are currently not supported in
6202 // offline mode
6203 if (stream->getOfflineProcessingSupport() &&
6204 (stream->getStreamSetId() == CAMERA3_STREAM_SET_ID_INVALID)) {
6205 offlineStreamIds->push_back(streamId);
6206 }
6207 }
6208}
6209
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08006210status_t Camera3Device::setRotateAndCropAutoBehavior(
6211 camera_metadata_enum_android_scaler_rotate_and_crop_t rotateAndCropValue) {
6212 ATRACE_CALL();
6213 Mutex::Autolock il(mInterfaceLock);
6214 Mutex::Autolock l(mLock);
6215 if (mRequestThread == nullptr) {
6216 return INVALID_OPERATION;
6217 }
6218 return mRequestThread->setRotateAndCropAutoBehavior(rotateAndCropValue);
6219}
6220
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08006221bool Camera3Device::supportsCameraMute() {
6222 Mutex::Autolock il(mInterfaceLock);
6223 Mutex::Autolock l(mLock);
6224
6225 return mSupportCameraMute;
6226}
6227
6228status_t Camera3Device::setCameraMute(bool enabled) {
6229 ATRACE_CALL();
6230 Mutex::Autolock il(mInterfaceLock);
6231 Mutex::Autolock l(mLock);
6232
6233 if (mRequestThread == nullptr || !mSupportCameraMute) {
6234 return INVALID_OPERATION;
6235 }
6236 return mRequestThread->setCameraMute(enabled);
6237}
6238
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08006239}; // namespace android