blob: 18eb57e84de7d119106bc22a440f8267bb592820 [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;
Shuzhen Wang83bff122020-11-20 15:51:39 -0800316 mIsInputStreamMultiResolution = false;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800317
Shuzhen Wangc28dccc2016-02-11 23:48:46 -0800318 // Measure the clock domain offset between camera and video/hw_composer
319 camera_metadata_entry timestampSource =
320 mDeviceInfo.find(ANDROID_SENSOR_INFO_TIMESTAMP_SOURCE);
321 if (timestampSource.count > 0 && timestampSource.data.u8[0] ==
322 ANDROID_SENSOR_INFO_TIMESTAMP_SOURCE_REALTIME) {
323 mTimestampOffset = getMonoToBoottimeOffset();
324 }
325
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -0700326 // Will the HAL be sending in early partial result metadata?
Emilian Peev08dd2452017-04-06 16:55:14 +0100327 camera_metadata_entry partialResultsCount =
328 mDeviceInfo.find(ANDROID_REQUEST_PARTIAL_RESULT_COUNT);
329 if (partialResultsCount.count > 0) {
330 mNumPartialResults = partialResultsCount.data.i32[0];
331 mUsePartialResult = (mNumPartialResults > 1);
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -0700332 }
333
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800334 bool usePrecorrectArray = DistortionMapper::isDistortionSupported(mDeviceInfo);
335 if (usePrecorrectArray) {
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -0700336 res = mDistortionMappers[mId.c_str()].setupStaticInfo(mDeviceInfo);
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -0700337 if (res != OK) {
338 SET_ERR_L("Unable to read necessary calibration fields for distortion correction");
339 return res;
340 }
341 }
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800342
Shuzhen Wang1c834da2019-12-18 11:17:03 -0800343 mZoomRatioMappers[mId.c_str()] = ZoomRatioMapper(&mDeviceInfo,
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800344 mSupportNativeZoomRatio, usePrecorrectArray);
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800345
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -0800346 if (RotateAndCropMapper::isNeeded(&mDeviceInfo)) {
347 mRotateAndCropMappers.emplace(mId.c_str(), &mDeviceInfo);
348 }
349
Eino-Ville Talvala305cec62020-11-12 14:18:17 -0800350 camera_metadata_entry_t availableTestPatternModes = mDeviceInfo.find(
351 ANDROID_SENSOR_AVAILABLE_TEST_PATTERN_MODES);
352 for (size_t i = 0; i < availableTestPatternModes.count; i++) {
353 if (availableTestPatternModes.data.i32[i] == ANDROID_SENSOR_TEST_PATTERN_MODE_SOLID_COLOR) {
354 mSupportCameraMute = true;
355 break;
356 }
357 }
358
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800359 return OK;
360}
361
362status_t Camera3Device::disconnect() {
Yin-Chia Yehc5248132018-08-15 12:19:20 -0700363 return disconnectImpl();
364}
365
366status_t Camera3Device::disconnectImpl() {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800367 ATRACE_CALL();
Yin-Chia Yehe1c80632016-08-08 14:48:05 -0700368 ALOGI("%s: E", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800369
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700370 status_t res = OK;
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700371 std::vector<wp<Camera3StreamInterface>> streams;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700372 {
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800373 Mutex::Autolock il(mInterfaceLock);
374 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
375 {
376 Mutex::Autolock l(mLock);
377 if (mStatus == STATUS_UNINITIALIZED) return res;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700378
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800379 if (mStatus == STATUS_ACTIVE ||
380 (mStatus == STATUS_ERROR && mRequestThread != NULL)) {
381 res = mRequestThread->clearRepeatingRequests();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700382 if (res != OK) {
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800383 SET_ERR_L("Can't stop streaming");
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700384 // Continue to close device even in case of error
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800385 } else {
386 res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
387 if (res != OK) {
388 SET_ERR_L("Timeout waiting for HAL to drain (% " PRIi64 " ns)",
389 maxExpectedDuration);
390 // Continue to close device even in case of error
391 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700392 }
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700393 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800394
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800395 if (mStatus == STATUS_ERROR) {
396 CLOGE("Shutting down in an error state");
397 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700398
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800399 if (mStatusTracker != NULL) {
400 mStatusTracker->requestExit();
401 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700402
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800403 if (mRequestThread != NULL) {
404 mRequestThread->requestExit();
405 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700406
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800407 streams.reserve(mOutputStreams.size() + (mInputStream != nullptr ? 1 : 0));
408 for (size_t i = 0; i < mOutputStreams.size(); i++) {
409 streams.push_back(mOutputStreams[i]);
410 }
411 if (mInputStream != nullptr) {
412 streams.push_back(mInputStream);
413 }
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700414 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700415 }
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800416 // Joining done without holding mLock and mInterfaceLock, otherwise deadlocks may ensue
417 // as the threads try to access parent state (b/143513518)
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700418 if (mRequestThread != NULL && mStatus != STATUS_ERROR) {
419 // HAL may be in a bad state, so waiting for request thread
420 // (which may be stuck in the HAL processCaptureRequest call)
421 // could be dangerous.
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800422 // give up mInterfaceLock here and then lock it again. Could this lead
423 // to other deadlocks
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700424 mRequestThread->join();
425 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700426 {
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800427 Mutex::Autolock il(mInterfaceLock);
428 if (mStatusTracker != NULL) {
429 mStatusTracker->join();
430 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800431
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800432 HalInterface* interface;
433 {
434 Mutex::Autolock l(mLock);
435 mRequestThread.clear();
436 Mutex::Autolock stLock(mTrackerLock);
437 mStatusTracker.clear();
438 interface = mInterface.get();
439 }
Eino-Ville Talvalaefff1c42015-08-28 16:27:27 -0700440
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800441 // Call close without internal mutex held, as the HAL close may need to
442 // wait on assorted callbacks,etc, to complete before it can return.
443 interface->close();
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700444
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800445 flushInflightRequests();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800446
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800447 {
448 Mutex::Autolock l(mLock);
449 mInterface->clear();
450 mOutputStreams.clear();
451 mInputStream.clear();
452 mDeletedStreams.clear();
453 mBufferManager.clear();
454 internalUpdateStatusLocked(STATUS_UNINITIALIZED);
455 }
456
457 for (auto& weakStream : streams) {
458 sp<Camera3StreamInterface> stream = weakStream.promote();
459 if (stream != nullptr) {
460 ALOGE("%s: Stream %d leaked! strong reference (%d)!",
461 __FUNCTION__, stream->getId(), stream->getStrongCount() - 1);
462 }
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700463 }
464 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -0700465 ALOGI("%s: X", __FUNCTION__);
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700466 return res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800467}
468
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700469// For dumping/debugging only -
470// try to acquire a lock a few times, eventually give up to proceed with
471// debug/dump operations
472bool Camera3Device::tryLockSpinRightRound(Mutex& lock) {
473 bool gotLock = false;
474 for (size_t i = 0; i < kDumpLockAttempts; ++i) {
475 if (lock.tryLock() == NO_ERROR) {
476 gotLock = true;
477 break;
478 } else {
479 usleep(kDumpSleepDuration);
480 }
481 }
482 return gotLock;
483}
484
Shuzhen Wang83bff122020-11-20 15:51:39 -0800485camera3::Size Camera3Device::getMaxJpegResolution() const {
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700486 int32_t maxJpegWidth = 0, maxJpegHeight = 0;
Emilian Peev08dd2452017-04-06 16:55:14 +0100487 const int STREAM_CONFIGURATION_SIZE = 4;
488 const int STREAM_FORMAT_OFFSET = 0;
489 const int STREAM_WIDTH_OFFSET = 1;
490 const int STREAM_HEIGHT_OFFSET = 2;
491 const int STREAM_IS_INPUT_OFFSET = 3;
492 camera_metadata_ro_entry_t availableStreamConfigs =
493 mDeviceInfo.find(ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS);
494 if (availableStreamConfigs.count == 0 ||
495 availableStreamConfigs.count % STREAM_CONFIGURATION_SIZE != 0) {
Shuzhen Wang83bff122020-11-20 15:51:39 -0800496 return camera3::Size(0, 0);
Emilian Peev08dd2452017-04-06 16:55:14 +0100497 }
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700498
Emilian Peev08dd2452017-04-06 16:55:14 +0100499 // Get max jpeg size (area-wise).
500 for (size_t i=0; i < availableStreamConfigs.count; i+= STREAM_CONFIGURATION_SIZE) {
501 int32_t format = availableStreamConfigs.data.i32[i + STREAM_FORMAT_OFFSET];
502 int32_t width = availableStreamConfigs.data.i32[i + STREAM_WIDTH_OFFSET];
503 int32_t height = availableStreamConfigs.data.i32[i + STREAM_HEIGHT_OFFSET];
504 int32_t isInput = availableStreamConfigs.data.i32[i + STREAM_IS_INPUT_OFFSET];
505 if (isInput == ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS_OUTPUT
506 && format == HAL_PIXEL_FORMAT_BLOB &&
507 (width * height > maxJpegWidth * maxJpegHeight)) {
508 maxJpegWidth = width;
509 maxJpegHeight = height;
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700510 }
511 }
Emilian Peev08dd2452017-04-06 16:55:14 +0100512
Shuzhen Wang83bff122020-11-20 15:51:39 -0800513 return camera3::Size(maxJpegWidth, maxJpegHeight);
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700514}
515
Shuzhen Wangc28dccc2016-02-11 23:48:46 -0800516nsecs_t Camera3Device::getMonoToBoottimeOffset() {
517 // try three times to get the clock offset, choose the one
518 // with the minimum gap in measurements.
519 const int tries = 3;
520 nsecs_t bestGap, measured;
521 for (int i = 0; i < tries; ++i) {
522 const nsecs_t tmono = systemTime(SYSTEM_TIME_MONOTONIC);
523 const nsecs_t tbase = systemTime(SYSTEM_TIME_BOOTTIME);
524 const nsecs_t tmono2 = systemTime(SYSTEM_TIME_MONOTONIC);
525 const nsecs_t gap = tmono2 - tmono;
526 if (i == 0 || gap < bestGap) {
527 bestGap = gap;
528 measured = tbase - ((tmono + tmono2) >> 1);
529 }
530 }
531 return measured;
532}
533
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800534hardware::graphics::common::V1_0::PixelFormat Camera3Device::mapToPixelFormat(
535 int frameworkFormat) {
536 return (hardware::graphics::common::V1_0::PixelFormat) frameworkFormat;
537}
538
539DataspaceFlags Camera3Device::mapToHidlDataspace(
540 android_dataspace dataSpace) {
541 return dataSpace;
542}
543
Chia-I Wu67a0c0e2017-04-06 13:37:01 -0700544BufferUsageFlags Camera3Device::mapToConsumerUsage(
Emilian Peev050f5dc2017-05-18 14:43:56 +0100545 uint64_t usage) {
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -0700546 return usage;
547}
548
Emilian Peevf4816702020-04-03 15:44:51 -0700549StreamRotation Camera3Device::mapToStreamRotation(camera_stream_rotation_t rotation) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800550 switch (rotation) {
Emilian Peevf4816702020-04-03 15:44:51 -0700551 case CAMERA_STREAM_ROTATION_0:
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800552 return StreamRotation::ROTATION_0;
Emilian Peevf4816702020-04-03 15:44:51 -0700553 case CAMERA_STREAM_ROTATION_90:
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800554 return StreamRotation::ROTATION_90;
Emilian Peevf4816702020-04-03 15:44:51 -0700555 case CAMERA_STREAM_ROTATION_180:
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800556 return StreamRotation::ROTATION_180;
Emilian Peevf4816702020-04-03 15:44:51 -0700557 case CAMERA_STREAM_ROTATION_270:
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800558 return StreamRotation::ROTATION_270;
559 }
560 ALOGE("%s: Unknown stream rotation %d", __FUNCTION__, rotation);
561 return StreamRotation::ROTATION_0;
562}
563
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800564status_t Camera3Device::mapToStreamConfigurationMode(
Emilian Peevf4816702020-04-03 15:44:51 -0700565 camera_stream_configuration_mode_t operationMode, StreamConfigurationMode *mode) {
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800566 if (mode == nullptr) return BAD_VALUE;
Emilian Peevf4816702020-04-03 15:44:51 -0700567 if (operationMode < CAMERA_VENDOR_STREAM_CONFIGURATION_MODE_START) {
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800568 switch(operationMode) {
Emilian Peevf4816702020-04-03 15:44:51 -0700569 case CAMERA_STREAM_CONFIGURATION_NORMAL_MODE:
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800570 *mode = StreamConfigurationMode::NORMAL_MODE;
571 break;
Emilian Peevf4816702020-04-03 15:44:51 -0700572 case CAMERA_STREAM_CONFIGURATION_CONSTRAINED_HIGH_SPEED_MODE:
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800573 *mode = StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE;
574 break;
575 default:
576 ALOGE("%s: Unknown stream configuration mode %d", __FUNCTION__, operationMode);
577 return BAD_VALUE;
578 }
579 } else {
580 *mode = static_cast<StreamConfigurationMode>(operationMode);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800581 }
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800582 return OK;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800583}
584
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800585int Camera3Device::mapToFrameworkFormat(
586 hardware::graphics::common::V1_0::PixelFormat pixelFormat) {
587 return static_cast<uint32_t>(pixelFormat);
588}
589
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -0700590android_dataspace Camera3Device::mapToFrameworkDataspace(
591 DataspaceFlags dataSpace) {
592 return static_cast<android_dataspace>(dataSpace);
593}
594
Emilian Peev050f5dc2017-05-18 14:43:56 +0100595uint64_t Camera3Device::mapConsumerToFrameworkUsage(
Chia-I Wu67a0c0e2017-04-06 13:37:01 -0700596 BufferUsageFlags usage) {
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -0700597 return usage;
598}
599
Emilian Peev050f5dc2017-05-18 14:43:56 +0100600uint64_t Camera3Device::mapProducerToFrameworkUsage(
Chia-I Wu67a0c0e2017-04-06 13:37:01 -0700601 BufferUsageFlags usage) {
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -0700602 return usage;
603}
604
Zhijun Hef7da0962014-04-24 13:27:56 -0700605ssize_t Camera3Device::getJpegBufferSize(uint32_t width, uint32_t height) const {
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700606 // Get max jpeg size (area-wise).
Shuzhen Wang83bff122020-11-20 15:51:39 -0800607 camera3::Size maxJpegResolution = getMaxJpegResolution();
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700608 if (maxJpegResolution.width == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800609 ALOGE("%s: Camera %s: Can't find valid available jpeg sizes in static metadata!",
610 __FUNCTION__, mId.string());
Zhijun Hef7da0962014-04-24 13:27:56 -0700611 return BAD_VALUE;
612 }
613
Zhijun Hef7da0962014-04-24 13:27:56 -0700614 // Get max jpeg buffer size
615 ssize_t maxJpegBufferSize = 0;
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700616 camera_metadata_ro_entry jpegBufMaxSize = mDeviceInfo.find(ANDROID_JPEG_MAX_SIZE);
617 if (jpegBufMaxSize.count == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800618 ALOGE("%s: Camera %s: Can't find maximum JPEG size in static metadata!", __FUNCTION__,
619 mId.string());
Zhijun Hef7da0962014-04-24 13:27:56 -0700620 return BAD_VALUE;
621 }
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700622 maxJpegBufferSize = jpegBufMaxSize.data.i32[0];
Yin-Chia Yeh0c4e56d2015-01-09 15:21:27 -0800623 assert(kMinJpegBufferSize < maxJpegBufferSize);
Zhijun Hef7da0962014-04-24 13:27:56 -0700624
625 // Calculate final jpeg buffer size for the given resolution.
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700626 float scaleFactor = ((float) (width * height)) /
627 (maxJpegResolution.width * maxJpegResolution.height);
Yin-Chia Yeh0c4e56d2015-01-09 15:21:27 -0800628 ssize_t jpegBufferSize = scaleFactor * (maxJpegBufferSize - kMinJpegBufferSize) +
629 kMinJpegBufferSize;
Zhijun Hef7da0962014-04-24 13:27:56 -0700630 if (jpegBufferSize > maxJpegBufferSize) {
631 jpegBufferSize = maxJpegBufferSize;
Zhijun Hef7da0962014-04-24 13:27:56 -0700632 }
633
634 return jpegBufferSize;
635}
636
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700637ssize_t Camera3Device::getPointCloudBufferSize() const {
638 const int FLOATS_PER_POINT=4;
639 camera_metadata_ro_entry maxPointCount = mDeviceInfo.find(ANDROID_DEPTH_MAX_DEPTH_SAMPLES);
640 if (maxPointCount.count == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800641 ALOGE("%s: Camera %s: Can't find maximum depth point cloud size in static metadata!",
642 __FUNCTION__, mId.string());
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700643 return BAD_VALUE;
644 }
645 ssize_t maxBytesForPointCloud = sizeof(android_depth_points) +
646 maxPointCount.data.i32[0] * sizeof(float) * FLOATS_PER_POINT;
647 return maxBytesForPointCloud;
648}
649
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800650ssize_t Camera3Device::getRawOpaqueBufferSize(int32_t width, int32_t height) const {
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800651 const int PER_CONFIGURATION_SIZE = 3;
652 const int WIDTH_OFFSET = 0;
653 const int HEIGHT_OFFSET = 1;
654 const int SIZE_OFFSET = 2;
655 camera_metadata_ro_entry rawOpaqueSizes =
656 mDeviceInfo.find(ANDROID_SENSOR_OPAQUE_RAW_SIZE);
Aurimas Liutikasbc57b122016-02-16 09:59:16 -0800657 size_t count = rawOpaqueSizes.count;
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800658 if (count == 0 || (count % PER_CONFIGURATION_SIZE)) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800659 ALOGE("%s: Camera %s: bad opaque RAW size static metadata length(%zu)!",
660 __FUNCTION__, mId.string(), count);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800661 return BAD_VALUE;
662 }
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700663
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800664 for (size_t i = 0; i < count; i += PER_CONFIGURATION_SIZE) {
665 if (width == rawOpaqueSizes.data.i32[i + WIDTH_OFFSET] &&
666 height == rawOpaqueSizes.data.i32[i + HEIGHT_OFFSET]) {
667 return rawOpaqueSizes.data.i32[i + SIZE_OFFSET];
668 }
669 }
670
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800671 ALOGE("%s: Camera %s: cannot find size for %dx%d opaque RAW image!",
672 __FUNCTION__, mId.string(), width, height);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800673 return BAD_VALUE;
674}
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700675
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800676status_t Camera3Device::dump(int fd, const Vector<String16> &args) {
677 ATRACE_CALL();
678 (void)args;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700679
680 // Try to lock, but continue in case of failure (to avoid blocking in
681 // deadlocks)
682 bool gotInterfaceLock = tryLockSpinRightRound(mInterfaceLock);
683 bool gotLock = tryLockSpinRightRound(mLock);
684
685 ALOGW_IF(!gotInterfaceLock,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800686 "Camera %s: %s: Unable to lock interface lock, proceeding anyway",
687 mId.string(), __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700688 ALOGW_IF(!gotLock,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800689 "Camera %s: %s: Unable to lock main lock, proceeding anyway",
690 mId.string(), __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700691
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800692 bool dumpTemplates = false;
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700693
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800694 String16 templatesOption("-t");
695 int n = args.size();
696 for (int i = 0; i < n; i++) {
697 if (args[i] == templatesOption) {
698 dumpTemplates = true;
699 }
Emilian Peevbd8c5032018-02-14 23:05:40 +0000700 if (args[i] == TagMonitor::kMonitorOption) {
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700701 if (i + 1 < n) {
702 String8 monitorTags = String8(args[i + 1]);
703 if (monitorTags == "off") {
704 mTagMonitor.disableMonitoring();
705 } else {
706 mTagMonitor.parseTagsToMonitor(monitorTags);
707 }
708 } else {
709 mTagMonitor.disableMonitoring();
710 }
711 }
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800712 }
713
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800714 String8 lines;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800715
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800716 const char *status =
717 mStatus == STATUS_ERROR ? "ERROR" :
718 mStatus == STATUS_UNINITIALIZED ? "UNINITIALIZED" :
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700719 mStatus == STATUS_UNCONFIGURED ? "UNCONFIGURED" :
720 mStatus == STATUS_CONFIGURED ? "CONFIGURED" :
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800721 mStatus == STATUS_ACTIVE ? "ACTIVE" :
722 "Unknown";
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700723
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800724 lines.appendFormat(" Device status: %s\n", status);
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700725 if (mStatus == STATUS_ERROR) {
726 lines.appendFormat(" Error cause: %s\n", mErrorCause.string());
727 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800728 lines.appendFormat(" Stream configuration:\n");
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800729 const char *mode =
730 mOperatingMode == static_cast<int>(StreamConfigurationMode::NORMAL_MODE) ? "NORMAL" :
731 mOperatingMode == static_cast<int>(
732 StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE) ? "CONSTRAINED_HIGH_SPEED" :
733 "CUSTOM";
734 lines.appendFormat(" Operation mode: %s (%d) \n", mode, mOperatingMode);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800735
736 if (mInputStream != NULL) {
737 write(fd, lines.string(), lines.size());
738 mInputStream->dump(fd, args);
739 } else {
740 lines.appendFormat(" No input stream.\n");
741 write(fd, lines.string(), lines.size());
742 }
743 for (size_t i = 0; i < mOutputStreams.size(); i++) {
744 mOutputStreams[i]->dump(fd,args);
745 }
746
Zhijun He431503c2016-03-07 17:30:16 -0800747 if (mBufferManager != NULL) {
748 lines = String8(" Camera3 Buffer Manager:\n");
749 write(fd, lines.string(), lines.size());
750 mBufferManager->dump(fd, args);
751 }
Zhijun He125684a2015-12-26 15:07:30 -0800752
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700753 lines = String8(" In-flight requests:\n");
754 if (mInFlightMap.size() == 0) {
755 lines.append(" None\n");
756 } else {
757 for (size_t i = 0; i < mInFlightMap.size(); i++) {
758 InFlightRequest r = mInFlightMap.valueAt(i);
Colin Crosse5729fa2014-03-21 15:04:25 -0700759 lines.appendFormat(" Frame %d | Timestamp: %" PRId64 ", metadata"
Greg Kaiser51b882c2020-06-10 05:41:44 +0000760 " arrived: %s, buffers left: %d\n", mInFlightMap.keyAt(i),
Chien-Yu Chen43e69a62014-11-25 16:38:33 -0800761 r.shutterTimestamp, r.haveResultMetadata ? "true" : "false",
Greg Kaiser51b882c2020-06-10 05:41:44 +0000762 r.numBuffersLeft);
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700763 }
764 }
765 write(fd, lines.string(), lines.size());
766
Shuzhen Wang686f6442017-06-20 16:16:04 -0700767 if (mRequestThread != NULL) {
768 mRequestThread->dumpCaptureRequestLatency(fd,
769 " ProcessCaptureRequest latency histogram:");
770 }
771
Igor Murashkin1e479c02013-09-06 16:55:14 -0700772 {
773 lines = String8(" Last request sent:\n");
774 write(fd, lines.string(), lines.size());
775
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700776 CameraMetadata lastRequest = getLatestRequestLocked();
Igor Murashkin1e479c02013-09-06 16:55:14 -0700777 lastRequest.dump(fd, /*verbosity*/2, /*indentation*/6);
778 }
779
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800780 if (dumpTemplates) {
Emilian Peevf4816702020-04-03 15:44:51 -0700781 const char *templateNames[CAMERA_TEMPLATE_COUNT] = {
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800782 "TEMPLATE_PREVIEW",
783 "TEMPLATE_STILL_CAPTURE",
784 "TEMPLATE_VIDEO_RECORD",
785 "TEMPLATE_VIDEO_SNAPSHOT",
786 "TEMPLATE_ZERO_SHUTTER_LAG",
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -0800787 "TEMPLATE_MANUAL",
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800788 };
789
Emilian Peevf4816702020-04-03 15:44:51 -0700790 for (int i = 1; i < CAMERA_TEMPLATE_COUNT; i++) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800791 camera_metadata_t *templateRequest = nullptr;
792 mInterface->constructDefaultRequestSettings(
Emilian Peevf4816702020-04-03 15:44:51 -0700793 (camera_request_template_t) i, &templateRequest);
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800794 lines = String8::format(" HAL Request %s:\n", templateNames[i-1]);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800795 if (templateRequest == nullptr) {
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800796 lines.append(" Not supported\n");
797 write(fd, lines.string(), lines.size());
798 } else {
799 write(fd, lines.string(), lines.size());
800 dump_indented_camera_metadata(templateRequest,
801 fd, /*verbosity*/2, /*indentation*/8);
802 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800803 free_camera_metadata(templateRequest);
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800804 }
805 }
806
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700807 mTagMonitor.dumpMonitoredMetadata(fd);
808
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800809 if (mInterface->valid()) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -0800810 lines = String8(" HAL device dump:\n");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800811 write(fd, lines.string(), lines.size());
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800812 mInterface->dump(fd);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800813 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800814
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700815 if (gotLock) mLock.unlock();
816 if (gotInterfaceLock) mInterfaceLock.unlock();
817
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800818 return OK;
819}
820
Emilian Peevfaa4bde2020-01-23 12:19:37 -0800821const CameraMetadata& Camera3Device::infoPhysical(const String8& physicalId) const {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800822 ALOGVV("%s: E", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800823 if (CC_UNLIKELY(mStatus == STATUS_UNINITIALIZED ||
824 mStatus == STATUS_ERROR)) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700825 ALOGW("%s: Access to static info %s!", __FUNCTION__,
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800826 mStatus == STATUS_ERROR ?
827 "when in error state" : "before init");
828 }
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700829 if (physicalId.isEmpty()) {
830 return mDeviceInfo;
831 } else {
832 std::string id(physicalId.c_str());
833 if (mPhysicalDeviceInfoMap.find(id) != mPhysicalDeviceInfoMap.end()) {
834 return mPhysicalDeviceInfoMap.at(id);
835 } else {
836 ALOGE("%s: Invalid physical camera id %s", __FUNCTION__, physicalId.c_str());
837 return mDeviceInfo;
838 }
839 }
840}
841
842const CameraMetadata& Camera3Device::info() const {
843 String8 emptyId;
Emilian Peevfaa4bde2020-01-23 12:19:37 -0800844 return infoPhysical(emptyId);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800845}
846
Jianing Wei90e59c92014-03-12 18:29:36 -0700847status_t Camera3Device::checkStatusOkToCaptureLocked() {
848 switch (mStatus) {
849 case STATUS_ERROR:
850 CLOGE("Device has encountered a serious error");
851 return INVALID_OPERATION;
852 case STATUS_UNINITIALIZED:
853 CLOGE("Device not initialized");
854 return INVALID_OPERATION;
855 case STATUS_UNCONFIGURED:
856 case STATUS_CONFIGURED:
857 case STATUS_ACTIVE:
858 // OK
859 break;
860 default:
861 SET_ERR_L("Unexpected status: %d", mStatus);
862 return INVALID_OPERATION;
863 }
864 return OK;
865}
866
867status_t Camera3Device::convertMetadataListToRequestListLocked(
Emilian Peevaebbe412018-01-15 13:53:24 +0000868 const List<const PhysicalCameraSettingsList> &metadataList,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700869 const std::list<const SurfaceMap> &surfaceMaps,
Shuzhen Wang316781a2020-08-18 18:11:01 -0700870 bool repeating, nsecs_t requestTimeNs,
Shuzhen Wang9d066012016-09-30 11:30:20 -0700871 RequestList *requestList) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700872 if (requestList == NULL) {
873 CLOGE("requestList cannot be NULL.");
874 return BAD_VALUE;
875 }
876
Jianing Weicb0652e2014-03-12 18:29:36 -0700877 int32_t burstId = 0;
Emilian Peevaebbe412018-01-15 13:53:24 +0000878 List<const PhysicalCameraSettingsList>::const_iterator metadataIt = metadataList.begin();
Shuzhen Wang0129d522016-10-30 22:43:41 -0700879 std::list<const SurfaceMap>::const_iterator surfaceMapIt = surfaceMaps.begin();
880 for (; metadataIt != metadataList.end() && surfaceMapIt != surfaceMaps.end();
881 ++metadataIt, ++surfaceMapIt) {
882 sp<CaptureRequest> newRequest = setUpRequestLocked(*metadataIt, *surfaceMapIt);
Jianing Wei90e59c92014-03-12 18:29:36 -0700883 if (newRequest == 0) {
884 CLOGE("Can't create capture request");
885 return BAD_VALUE;
886 }
Jianing Weicb0652e2014-03-12 18:29:36 -0700887
Shuzhen Wang9d066012016-09-30 11:30:20 -0700888 newRequest->mRepeating = repeating;
Shuzhen Wang316781a2020-08-18 18:11:01 -0700889 newRequest->mRequestTimeNs = requestTimeNs;
Shuzhen Wang9d066012016-09-30 11:30:20 -0700890
Jianing Weicb0652e2014-03-12 18:29:36 -0700891 // Setup burst Id and request Id
892 newRequest->mResultExtras.burstId = burstId++;
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -0800893 auto requestIdEntry = metadataIt->begin()->metadata.find(ANDROID_REQUEST_ID);
894 if (requestIdEntry.count == 0) {
Jianing Weicb0652e2014-03-12 18:29:36 -0700895 CLOGE("RequestID does not exist in metadata");
896 return BAD_VALUE;
897 }
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -0800898 newRequest->mResultExtras.requestId = requestIdEntry.data.i32[0];
Jianing Weicb0652e2014-03-12 18:29:36 -0700899
Jianing Wei90e59c92014-03-12 18:29:36 -0700900 requestList->push_back(newRequest);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700901
902 ALOGV("%s: requestId = %" PRId32, __FUNCTION__, newRequest->mResultExtras.requestId);
Jianing Wei90e59c92014-03-12 18:29:36 -0700903 }
Shuzhen Wang0129d522016-10-30 22:43:41 -0700904 if (metadataIt != metadataList.end() || surfaceMapIt != surfaceMaps.end()) {
905 ALOGE("%s: metadataList and surfaceMaps are not the same size!", __FUNCTION__);
906 return BAD_VALUE;
907 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -0700908
909 // Setup batch size if this is a high speed video recording request.
910 if (mIsConstrainedHighSpeedConfiguration && requestList->size() > 0) {
911 auto firstRequest = requestList->begin();
912 for (auto& outputStream : (*firstRequest)->mOutputStreams) {
913 if (outputStream->isVideoStream()) {
914 (*firstRequest)->mBatchSize = requestList->size();
Yin-Chia Yeh14ef48d2020-02-10 15:06:37 -0800915 outputStream->setBatchSize(requestList->size());
Chien-Yu Chen85a64552015-08-28 15:46:12 -0700916 break;
917 }
918 }
919 }
920
Jianing Wei90e59c92014-03-12 18:29:36 -0700921 return OK;
922}
923
Yin-Chia Yeh7e5a2042019-02-06 16:01:06 -0800924status_t Camera3Device::capture(CameraMetadata &request, int64_t* lastFrameNumber) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800925 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800926
Emilian Peevaebbe412018-01-15 13:53:24 +0000927 List<const PhysicalCameraSettingsList> requestsList;
Shuzhen Wang0129d522016-10-30 22:43:41 -0700928 std::list<const SurfaceMap> surfaceMaps;
Emilian Peevaebbe412018-01-15 13:53:24 +0000929 convertToRequestList(requestsList, surfaceMaps, request);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700930
Yin-Chia Yeh7e5a2042019-02-06 16:01:06 -0800931 return captureList(requestsList, surfaceMaps, lastFrameNumber);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700932}
933
Emilian Peevaebbe412018-01-15 13:53:24 +0000934void Camera3Device::convertToRequestList(List<const PhysicalCameraSettingsList>& requestsList,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700935 std::list<const SurfaceMap>& surfaceMaps,
936 const CameraMetadata& request) {
Emilian Peevaebbe412018-01-15 13:53:24 +0000937 PhysicalCameraSettingsList requestList;
938 requestList.push_back({std::string(getId().string()), request});
939 requestsList.push_back(requestList);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700940
941 SurfaceMap surfaceMap;
942 camera_metadata_ro_entry streams = request.find(ANDROID_REQUEST_OUTPUT_STREAMS);
943 // With no surface list passed in, stream and surface will have 1-to-1
944 // mapping. So the surface index is 0 for each stream in the surfaceMap.
945 for (size_t i = 0; i < streams.count; i++) {
946 surfaceMap[streams.data.i32[i]].push_back(0);
947 }
948 surfaceMaps.push_back(surfaceMap);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800949}
950
Jianing Wei90e59c92014-03-12 18:29:36 -0700951status_t Camera3Device::submitRequestsHelper(
Emilian Peevaebbe412018-01-15 13:53:24 +0000952 const List<const PhysicalCameraSettingsList> &requests,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700953 const std::list<const SurfaceMap> &surfaceMaps,
954 bool repeating,
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700955 /*out*/
956 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700957 ATRACE_CALL();
Shuzhen Wang316781a2020-08-18 18:11:01 -0700958 nsecs_t requestTimeNs = systemTime();
959
Jianing Wei90e59c92014-03-12 18:29:36 -0700960 Mutex::Autolock il(mInterfaceLock);
961 Mutex::Autolock l(mLock);
962
963 status_t res = checkStatusOkToCaptureLocked();
964 if (res != OK) {
965 // error logged by previous call
966 return res;
967 }
968
969 RequestList requestList;
970
Shuzhen Wang0129d522016-10-30 22:43:41 -0700971 res = convertMetadataListToRequestListLocked(requests, surfaceMaps,
Shuzhen Wang316781a2020-08-18 18:11:01 -0700972 repeating, requestTimeNs, /*out*/&requestList);
Jianing Wei90e59c92014-03-12 18:29:36 -0700973 if (res != OK) {
974 // error logged by previous call
975 return res;
976 }
977
978 if (repeating) {
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700979 res = mRequestThread->setRepeatingRequests(requestList, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -0700980 } else {
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700981 res = mRequestThread->queueRequestList(requestList, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -0700982 }
983
984 if (res == OK) {
985 waitUntilStateThenRelock(/*active*/true, kActiveTimeout);
986 if (res != OK) {
987 SET_ERR_L("Can't transition to active in %f seconds!",
988 kActiveTimeout/1e9);
989 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800990 ALOGV("Camera %s: Capture request %" PRId32 " enqueued", mId.string(),
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700991 (*(requestList.begin()))->mResultExtras.requestId);
Jianing Wei90e59c92014-03-12 18:29:36 -0700992 } else {
993 CLOGE("Cannot queue request. Impossible.");
994 return BAD_VALUE;
995 }
996
997 return res;
998}
999
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001000hardware::Return<void> Camera3Device::requestStreamBuffers(
1001 const hardware::hidl_vec<hardware::camera::device::V3_5::BufferRequest>& bufReqs,
1002 requestStreamBuffers_cb _hidl_cb) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001003 RequestBufferStates states {
Shuzhen Wang316781a2020-08-18 18:11:01 -07001004 mId, mRequestBufferInterfaceLock, mUseHalBufManager, mOutputStreams, mSessionStatsBuilder,
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001005 *this, *mInterface, *this};
1006 camera3::requestStreamBuffers(states, bufReqs, _hidl_cb);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001007 return hardware::Void();
1008}
1009
1010hardware::Return<void> Camera3Device::returnStreamBuffers(
1011 const hardware::hidl_vec<hardware::camera::device::V3_2::StreamBuffer>& buffers) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001012 ReturnBufferStates states {
Shuzhen Wang316781a2020-08-18 18:11:01 -07001013 mId, mUseHalBufManager, mOutputStreams, mSessionStatsBuilder, *mInterface};
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001014 camera3::returnStreamBuffers(states, buffers);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001015 return hardware::Void();
1016}
1017
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001018hardware::Return<void> Camera3Device::processCaptureResult_3_4(
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001019 const hardware::hidl_vec<
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001020 hardware::camera::device::V3_4::CaptureResult>& results) {
Yin-Chia Yeh657c1872017-07-18 18:09:57 -07001021 // Ideally we should grab mLock, but that can lead to deadlock, and
1022 // it's not super important to get up to date value of mStatus for this
1023 // warning print, hence skipping the lock here
1024 if (mStatus == STATUS_ERROR) {
1025 // Per API contract, HAL should act as closed after device error
1026 // But mStatus can be set to error by framework as well, so just log
1027 // a warning here.
1028 ALOGW("%s: received capture result in error state.", __FUNCTION__);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07001029 }
Yifan Honga640c5a2017-04-12 16:30:31 -07001030
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001031 sp<NotificationListener> listener;
1032 {
1033 std::lock_guard<std::mutex> l(mOutputLock);
1034 listener = mListener.promote();
1035 }
1036
Yifan Honga640c5a2017-04-12 16:30:31 -07001037 if (mProcessCaptureResultLock.tryLock() != OK) {
1038 // This should never happen; it indicates a wrong client implementation
1039 // that doesn't follow the contract. But, we can be tolerant here.
1040 ALOGE("%s: callback overlapped! waiting 1s...",
1041 __FUNCTION__);
1042 if (mProcessCaptureResultLock.timedLock(1000000000 /* 1s */) != OK) {
1043 ALOGE("%s: cannot acquire lock in 1s, dropping results",
1044 __FUNCTION__);
1045 // really don't know what to do, so bail out.
1046 return hardware::Void();
1047 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001048 }
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001049 CaptureOutputStates states {
1050 mId,
Shuzhen Wangb7b42652020-05-07 11:59:02 -07001051 mInFlightLock, mLastCompletedRegularFrameNumber,
1052 mLastCompletedReprocessFrameNumber, mLastCompletedZslFrameNumber,
1053 mInFlightMap, mOutputLock, mResultQueue, mResultSignal,
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001054 mNextShutterFrameNumber,
1055 mNextReprocessShutterFrameNumber, mNextZslStillShutterFrameNumber,
1056 mNextResultFrameNumber,
1057 mNextReprocessResultFrameNumber, mNextZslStillResultFrameNumber,
1058 mUseHalBufManager, mUsePartialResult, mNeedFixupMonochromeTags,
1059 mNumPartialResults, mVendorTagId, mDeviceInfo, mPhysicalDeviceInfoMap,
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08001060 mResultMetadataQueue, mDistortionMappers, mZoomRatioMappers, mRotateAndCropMappers,
Shuzhen Wang316781a2020-08-18 18:11:01 -07001061 mTagMonitor, mInputStream, mOutputStreams, mSessionStatsBuilder, listener, *this, *this,
1062 *mInterface
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001063 };
1064
Yifan Honga640c5a2017-04-12 16:30:31 -07001065 for (const auto& result : results) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001066 processOneCaptureResultLocked(states, result.v3_2, result.physicalCameraMetadata);
Yifan Honga640c5a2017-04-12 16:30:31 -07001067 }
1068 mProcessCaptureResultLock.unlock();
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001069 return hardware::Void();
1070}
1071
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001072// Only one processCaptureResult should be called at a time, so
1073// the locks won't block. The locks are present here simply to enforce this.
1074hardware::Return<void> Camera3Device::processCaptureResult(
1075 const hardware::hidl_vec<
1076 hardware::camera::device::V3_2::CaptureResult>& results) {
1077 hardware::hidl_vec<hardware::camera::device::V3_4::PhysicalCameraMetadata> noPhysMetadata;
1078
1079 // Ideally we should grab mLock, but that can lead to deadlock, and
1080 // it's not super important to get up to date value of mStatus for this
1081 // warning print, hence skipping the lock here
1082 if (mStatus == STATUS_ERROR) {
1083 // Per API contract, HAL should act as closed after device error
1084 // But mStatus can be set to error by framework as well, so just log
1085 // a warning here.
1086 ALOGW("%s: received capture result in error state.", __FUNCTION__);
1087 }
1088
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001089 sp<NotificationListener> listener;
1090 {
1091 std::lock_guard<std::mutex> l(mOutputLock);
1092 listener = mListener.promote();
1093 }
1094
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001095 if (mProcessCaptureResultLock.tryLock() != OK) {
1096 // This should never happen; it indicates a wrong client implementation
1097 // that doesn't follow the contract. But, we can be tolerant here.
1098 ALOGE("%s: callback overlapped! waiting 1s...",
1099 __FUNCTION__);
1100 if (mProcessCaptureResultLock.timedLock(1000000000 /* 1s */) != OK) {
1101 ALOGE("%s: cannot acquire lock in 1s, dropping results",
1102 __FUNCTION__);
1103 // really don't know what to do, so bail out.
1104 return hardware::Void();
1105 }
1106 }
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001107
1108 CaptureOutputStates states {
1109 mId,
Shuzhen Wangb7b42652020-05-07 11:59:02 -07001110 mInFlightLock, mLastCompletedRegularFrameNumber,
1111 mLastCompletedReprocessFrameNumber, mLastCompletedZslFrameNumber,
1112 mInFlightMap, mOutputLock, mResultQueue, mResultSignal,
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001113 mNextShutterFrameNumber,
1114 mNextReprocessShutterFrameNumber, mNextZslStillShutterFrameNumber,
1115 mNextResultFrameNumber,
1116 mNextReprocessResultFrameNumber, mNextZslStillResultFrameNumber,
1117 mUseHalBufManager, mUsePartialResult, mNeedFixupMonochromeTags,
1118 mNumPartialResults, mVendorTagId, mDeviceInfo, mPhysicalDeviceInfoMap,
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08001119 mResultMetadataQueue, mDistortionMappers, mZoomRatioMappers, mRotateAndCropMappers,
Shuzhen Wang316781a2020-08-18 18:11:01 -07001120 mTagMonitor, mInputStream, mOutputStreams, mSessionStatsBuilder, listener, *this, *this,
1121 *mInterface
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001122 };
1123
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001124 for (const auto& result : results) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001125 processOneCaptureResultLocked(states, result, noPhysMetadata);
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001126 }
1127 mProcessCaptureResultLock.unlock();
1128 return hardware::Void();
1129}
1130
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001131hardware::Return<void> Camera3Device::notify(
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001132 const hardware::hidl_vec<hardware::camera::device::V3_2::NotifyMsg>& msgs) {
Yin-Chia Yeh657c1872017-07-18 18:09:57 -07001133 // Ideally we should grab mLock, but that can lead to deadlock, and
1134 // it's not super important to get up to date value of mStatus for this
1135 // warning print, hence skipping the lock here
1136 if (mStatus == STATUS_ERROR) {
1137 // Per API contract, HAL should act as closed after device error
1138 // But mStatus can be set to error by framework as well, so just log
1139 // a warning here.
1140 ALOGW("%s: received notify message in error state.", __FUNCTION__);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07001141 }
Yin-Chia Yeh657c1872017-07-18 18:09:57 -07001142
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001143 sp<NotificationListener> listener;
1144 {
1145 std::lock_guard<std::mutex> l(mOutputLock);
1146 listener = mListener.promote();
1147 }
1148
1149 CaptureOutputStates states {
1150 mId,
Shuzhen Wangb7b42652020-05-07 11:59:02 -07001151 mInFlightLock, mLastCompletedRegularFrameNumber,
1152 mLastCompletedReprocessFrameNumber, mLastCompletedZslFrameNumber,
1153 mInFlightMap, mOutputLock, mResultQueue, mResultSignal,
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001154 mNextShutterFrameNumber,
1155 mNextReprocessShutterFrameNumber, mNextZslStillShutterFrameNumber,
1156 mNextResultFrameNumber,
1157 mNextReprocessResultFrameNumber, mNextZslStillResultFrameNumber,
1158 mUseHalBufManager, mUsePartialResult, mNeedFixupMonochromeTags,
1159 mNumPartialResults, mVendorTagId, mDeviceInfo, mPhysicalDeviceInfoMap,
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08001160 mResultMetadataQueue, mDistortionMappers, mZoomRatioMappers, mRotateAndCropMappers,
Shuzhen Wang316781a2020-08-18 18:11:01 -07001161 mTagMonitor, mInputStream, mOutputStreams, mSessionStatsBuilder, listener, *this, *this,
1162 *mInterface
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001163 };
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001164 for (const auto& msg : msgs) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001165 camera3::notify(states, msg);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001166 }
1167 return hardware::Void();
1168}
1169
Emilian Peevaebbe412018-01-15 13:53:24 +00001170status_t Camera3Device::captureList(const List<const PhysicalCameraSettingsList> &requestsList,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001171 const std::list<const SurfaceMap> &surfaceMaps,
Jianing Weicb0652e2014-03-12 18:29:36 -07001172 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -07001173 ATRACE_CALL();
1174
Emilian Peevaebbe412018-01-15 13:53:24 +00001175 return submitRequestsHelper(requestsList, surfaceMaps, /*repeating*/false, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -07001176}
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001177
Jianing Weicb0652e2014-03-12 18:29:36 -07001178status_t Camera3Device::setStreamingRequest(const CameraMetadata &request,
1179 int64_t* /*lastFrameNumber*/) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001180 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001181
Emilian Peevaebbe412018-01-15 13:53:24 +00001182 List<const PhysicalCameraSettingsList> requestsList;
Shuzhen Wang0129d522016-10-30 22:43:41 -07001183 std::list<const SurfaceMap> surfaceMaps;
Emilian Peevaebbe412018-01-15 13:53:24 +00001184 convertToRequestList(requestsList, surfaceMaps, request);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001185
Emilian Peevaebbe412018-01-15 13:53:24 +00001186 return setStreamingRequestList(requestsList, /*surfaceMap*/surfaceMaps,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001187 /*lastFrameNumber*/NULL);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001188}
1189
Emilian Peevaebbe412018-01-15 13:53:24 +00001190status_t Camera3Device::setStreamingRequestList(
1191 const List<const PhysicalCameraSettingsList> &requestsList,
1192 const std::list<const SurfaceMap> &surfaceMaps, int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -07001193 ATRACE_CALL();
1194
Emilian Peevaebbe412018-01-15 13:53:24 +00001195 return submitRequestsHelper(requestsList, surfaceMaps, /*repeating*/true, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -07001196}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001197
1198sp<Camera3Device::CaptureRequest> Camera3Device::setUpRequestLocked(
Emilian Peevaebbe412018-01-15 13:53:24 +00001199 const PhysicalCameraSettingsList &request, const SurfaceMap &surfaceMap) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001200 status_t res;
1201
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001202 if (mStatus == STATUS_UNCONFIGURED || mNeedConfig) {
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08001203 // This point should only be reached via API1 (API2 must explicitly call configureStreams)
1204 // so unilaterally select normal operating mode.
Emilian Peevaebbe412018-01-15 13:53:24 +00001205 res = filterParamsAndConfigureLocked(request.begin()->metadata,
Emilian Peevf4816702020-04-03 15:44:51 -07001206 CAMERA_STREAM_CONFIGURATION_NORMAL_MODE);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001207 // Stream configuration failed. Client might try other configuraitons.
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001208 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001209 CLOGE("Can't set up streams: %s (%d)", strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001210 return NULL;
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001211 } else if (mStatus == STATUS_UNCONFIGURED) {
1212 // Stream configuration successfully configure to empty stream configuration.
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001213 CLOGE("No streams configured");
1214 return NULL;
1215 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001216 }
1217
Shuzhen Wang0129d522016-10-30 22:43:41 -07001218 sp<CaptureRequest> newRequest = createCaptureRequest(request, surfaceMap);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001219 return newRequest;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001220}
1221
Jianing Weicb0652e2014-03-12 18:29:36 -07001222status_t Camera3Device::clearStreamingRequest(int64_t *lastFrameNumber) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001223 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001224 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001225 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001226
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001227 switch (mStatus) {
1228 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001229 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001230 return INVALID_OPERATION;
1231 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001232 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001233 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001234 case STATUS_UNCONFIGURED:
1235 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001236 case STATUS_ACTIVE:
1237 // OK
1238 break;
1239 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001240 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001241 return INVALID_OPERATION;
1242 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001243 ALOGV("Camera %s: Clearing repeating request", mId.string());
Jianing Weicb0652e2014-03-12 18:29:36 -07001244
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07001245 return mRequestThread->clearRepeatingRequests(lastFrameNumber);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001246}
1247
1248status_t Camera3Device::waitUntilRequestReceived(int32_t requestId, nsecs_t timeout) {
1249 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001250 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001251
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001252 return mRequestThread->waitUntilRequestProcessed(requestId, timeout);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001253}
1254
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001255status_t Camera3Device::createInputStream(
Shuzhen Wang83bff122020-11-20 15:51:39 -08001256 uint32_t width, uint32_t height, int format, bool isMultiResolution, int *id) {
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001257 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001258 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001259 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001260 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001261 ALOGV("Camera %s: Creating new input stream %d: %d x %d, format %d",
1262 mId.string(), mNextStreamId, width, height, format);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001263
1264 status_t res;
1265 bool wasActive = false;
1266
1267 switch (mStatus) {
1268 case STATUS_ERROR:
1269 ALOGE("%s: Device has encountered a serious error", __FUNCTION__);
1270 return INVALID_OPERATION;
1271 case STATUS_UNINITIALIZED:
1272 ALOGE("%s: Device not initialized", __FUNCTION__);
1273 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001274 case STATUS_UNCONFIGURED:
1275 case STATUS_CONFIGURED:
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001276 // OK
1277 break;
1278 case STATUS_ACTIVE:
1279 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001280 res = internalPauseAndWaitLocked(maxExpectedDuration);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001281 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001282 SET_ERR_L("Can't pause captures to reconfigure streams!");
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001283 return res;
1284 }
1285 wasActive = true;
1286 break;
1287 default:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001288 SET_ERR_L("%s: Unexpected status: %d", mStatus);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001289 return INVALID_OPERATION;
1290 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001291 assert(mStatus != STATUS_ACTIVE);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001292
1293 if (mInputStream != 0) {
1294 ALOGE("%s: Cannot create more than 1 input stream", __FUNCTION__);
1295 return INVALID_OPERATION;
1296 }
1297
1298 sp<Camera3InputStream> newStream = new Camera3InputStream(mNextStreamId,
1299 width, height, format);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001300 newStream->setStatusTracker(mStatusTracker);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001301
1302 mInputStream = newStream;
Shuzhen Wang83bff122020-11-20 15:51:39 -08001303 mIsInputStreamMultiResolution = isMultiResolution;
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001304
1305 *id = mNextStreamId++;
1306
1307 // Continue captures if active at start
1308 if (wasActive) {
1309 ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001310 // Reuse current operating mode and session parameters for new stream config
1311 res = configureStreamsLocked(mOperatingMode, mSessionParams);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001312 if (res != OK) {
1313 ALOGE("%s: Can't reconfigure device for new stream %d: %s (%d)",
1314 __FUNCTION__, mNextStreamId, strerror(-res), res);
1315 return res;
1316 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001317 internalResumeLocked();
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001318 }
1319
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001320 ALOGV("Camera %s: Created input stream", mId.string());
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001321 return OK;
1322}
1323
Eino-Ville Talvala727d1722015-06-09 13:44:19 -07001324status_t Camera3Device::createStream(sp<Surface> consumer,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001325 uint32_t width, uint32_t height, int format,
Emilian Peevf4816702020-04-03 15:44:51 -07001326 android_dataspace dataSpace, camera_stream_rotation_t rotation, int *id,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001327 const String8& physicalCameraId,
Shuzhen Wang83bff122020-11-20 15:51:39 -08001328 std::vector<int> *surfaceIds, int streamSetId, bool isShared,
1329 bool isMultiResolution, uint64_t consumerUsage) {
Shuzhen Wang0129d522016-10-30 22:43:41 -07001330 ATRACE_CALL();
1331
1332 if (consumer == nullptr) {
1333 ALOGE("%s: consumer must not be null", __FUNCTION__);
1334 return BAD_VALUE;
1335 }
1336
1337 std::vector<sp<Surface>> consumers;
1338 consumers.push_back(consumer);
1339
1340 return createStream(consumers, /*hasDeferredConsumer*/ false, width, height,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001341 format, dataSpace, rotation, id, physicalCameraId, surfaceIds, streamSetId,
Shuzhen Wang83bff122020-11-20 15:51:39 -08001342 isShared, isMultiResolution, consumerUsage);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001343}
1344
1345status_t Camera3Device::createStream(const std::vector<sp<Surface>>& consumers,
1346 bool hasDeferredConsumer, uint32_t width, uint32_t height, int format,
Emilian Peevf4816702020-04-03 15:44:51 -07001347 android_dataspace dataSpace, camera_stream_rotation_t rotation, int *id,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001348 const String8& physicalCameraId,
Shuzhen Wang83bff122020-11-20 15:51:39 -08001349 std::vector<int> *surfaceIds, int streamSetId, bool isShared, bool isMultiResolution,
1350 uint64_t consumerUsage) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001351 ATRACE_CALL();
Emilian Peev40ead602017-09-26 15:46:36 +01001352
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001353 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001354 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001355 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001356 ALOGV("Camera %s: Creating new stream %d: %d x %d, format %d, dataspace %d rotation %d"
Shuzhen Wang83bff122020-11-20 15:51:39 -08001357 " consumer usage %" PRIu64 ", isShared %d, physicalCameraId %s, isMultiResolution %d",
1358 mId.string(), mNextStreamId, width, height, format, dataSpace, rotation,
1359 consumerUsage, isShared, physicalCameraId.string(), isMultiResolution);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001360
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001361 status_t res;
1362 bool wasActive = false;
1363
1364 switch (mStatus) {
1365 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001366 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001367 return INVALID_OPERATION;
1368 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001369 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001370 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001371 case STATUS_UNCONFIGURED:
1372 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001373 // OK
1374 break;
1375 case STATUS_ACTIVE:
1376 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001377 res = internalPauseAndWaitLocked(maxExpectedDuration);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001378 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001379 SET_ERR_L("Can't pause captures to reconfigure streams!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001380 return res;
1381 }
1382 wasActive = true;
1383 break;
1384 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001385 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001386 return INVALID_OPERATION;
1387 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001388 assert(mStatus != STATUS_ACTIVE);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001389
1390 sp<Camera3OutputStream> newStream;
Zhijun He5d677d12016-05-29 16:52:39 -07001391
Shuzhen Wang0129d522016-10-30 22:43:41 -07001392 if (consumers.size() == 0 && !hasDeferredConsumer) {
1393 ALOGE("%s: Number of consumers cannot be smaller than 1", __FUNCTION__);
1394 return BAD_VALUE;
1395 }
Zhijun He5d677d12016-05-29 16:52:39 -07001396
Shuzhen Wang0129d522016-10-30 22:43:41 -07001397 if (hasDeferredConsumer && format != HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
Zhijun He5d677d12016-05-29 16:52:39 -07001398 ALOGE("Deferred consumer stream creation only support IMPLEMENTATION_DEFINED format");
1399 return BAD_VALUE;
1400 }
1401
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001402 if (format == HAL_PIXEL_FORMAT_BLOB) {
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -07001403 ssize_t blobBufferSize;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001404 if (dataSpace == HAL_DATASPACE_DEPTH) {
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -07001405 blobBufferSize = getPointCloudBufferSize();
1406 if (blobBufferSize <= 0) {
1407 SET_ERR_L("Invalid point cloud buffer size %zd", blobBufferSize);
1408 return BAD_VALUE;
1409 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001410 } else if (dataSpace == static_cast<android_dataspace>(HAL_DATASPACE_JPEG_APP_SEGMENTS)) {
1411 blobBufferSize = width * height;
1412 } else {
1413 blobBufferSize = getJpegBufferSize(width, height);
1414 if (blobBufferSize <= 0) {
1415 SET_ERR_L("Invalid jpeg buffer size %zd", blobBufferSize);
1416 return BAD_VALUE;
1417 }
Zhijun Hef7da0962014-04-24 13:27:56 -07001418 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001419 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001420 width, height, blobBufferSize, format, dataSpace, rotation,
Shuzhen Wang83bff122020-11-20 15:51:39 -08001421 mTimestampOffset, physicalCameraId, streamSetId, isMultiResolution);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -08001422 } else if (format == HAL_PIXEL_FORMAT_RAW_OPAQUE) {
1423 ssize_t rawOpaqueBufferSize = getRawOpaqueBufferSize(width, height);
1424 if (rawOpaqueBufferSize <= 0) {
1425 SET_ERR_L("Invalid RAW opaque buffer size %zd", rawOpaqueBufferSize);
1426 return BAD_VALUE;
1427 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001428 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001429 width, height, rawOpaqueBufferSize, format, dataSpace, rotation,
Shuzhen Wang83bff122020-11-20 15:51:39 -08001430 mTimestampOffset, physicalCameraId, streamSetId, isMultiResolution);
Shuzhen Wang758c2152017-01-10 18:26:18 -08001431 } else if (isShared) {
1432 newStream = new Camera3SharedOutputStream(mNextStreamId, consumers,
1433 width, height, format, consumerUsage, dataSpace, rotation,
Shuzhen Wang83bff122020-11-20 15:51:39 -08001434 mTimestampOffset, physicalCameraId, streamSetId, mUseHalBufManager);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001435 } else if (consumers.size() == 0 && hasDeferredConsumer) {
Zhijun He5d677d12016-05-29 16:52:39 -07001436 newStream = new Camera3OutputStream(mNextStreamId,
1437 width, height, format, consumerUsage, dataSpace, rotation,
Shuzhen Wang83bff122020-11-20 15:51:39 -08001438 mTimestampOffset, physicalCameraId, streamSetId, isMultiResolution);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001439 } else {
Shuzhen Wang0129d522016-10-30 22:43:41 -07001440 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001441 width, height, format, dataSpace, rotation,
Shuzhen Wang83bff122020-11-20 15:51:39 -08001442 mTimestampOffset, physicalCameraId, streamSetId, isMultiResolution);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001443 }
Emilian Peev40ead602017-09-26 15:46:36 +01001444
1445 size_t consumerCount = consumers.size();
1446 for (size_t i = 0; i < consumerCount; i++) {
1447 int id = newStream->getSurfaceId(consumers[i]);
1448 if (id < 0) {
1449 SET_ERR_L("Invalid surface id");
1450 return BAD_VALUE;
1451 }
1452 if (surfaceIds != nullptr) {
1453 surfaceIds->push_back(id);
1454 }
1455 }
1456
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001457 newStream->setStatusTracker(mStatusTracker);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001458
Emilian Peev08dd2452017-04-06 16:55:14 +01001459 newStream->setBufferManager(mBufferManager);
Zhijun He125684a2015-12-26 15:07:30 -08001460
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08001461 newStream->setImageDumpMask(mImageDumpMask);
1462
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001463 res = mOutputStreams.add(mNextStreamId, newStream);
1464 if (res < 0) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001465 SET_ERR_L("Can't add new stream to set: %s (%d)", strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001466 return res;
1467 }
1468
Shuzhen Wang316781a2020-08-18 18:11:01 -07001469 mSessionStatsBuilder.addStream(mNextStreamId);
1470
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001471 *id = mNextStreamId++;
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07001472 mNeedConfig = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001473
1474 // Continue captures if active at start
1475 if (wasActive) {
1476 ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001477 // Reuse current operating mode and session parameters for new stream config
1478 res = configureStreamsLocked(mOperatingMode, mSessionParams);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001479 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001480 CLOGE("Can't reconfigure device for new stream %d: %s (%d)",
1481 mNextStreamId, strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001482 return res;
1483 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001484 internalResumeLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001485 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001486 ALOGV("Camera %s: Created new stream", mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001487 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001488}
1489
Emilian Peev710c1422017-08-30 11:19:38 +01001490status_t Camera3Device::getStreamInfo(int id, StreamInfo *streamInfo) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001491 ATRACE_CALL();
Emilian Peev710c1422017-08-30 11:19:38 +01001492 if (nullptr == streamInfo) {
1493 return BAD_VALUE;
1494 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001495 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001496 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001497
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001498 switch (mStatus) {
1499 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001500 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001501 return INVALID_OPERATION;
1502 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001503 CLOGE("Device not initialized!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001504 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001505 case STATUS_UNCONFIGURED:
1506 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001507 case STATUS_ACTIVE:
1508 // OK
1509 break;
1510 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001511 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001512 return INVALID_OPERATION;
1513 }
1514
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001515 sp<Camera3StreamInterface> stream = mOutputStreams.get(id);
1516 if (stream == nullptr) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001517 CLOGE("Stream %d is unknown", id);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001518 return BAD_VALUE;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001519 }
1520
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001521 streamInfo->width = stream->getWidth();
1522 streamInfo->height = stream->getHeight();
1523 streamInfo->format = stream->getFormat();
1524 streamInfo->dataSpace = stream->getDataSpace();
1525 streamInfo->formatOverridden = stream->isFormatOverridden();
1526 streamInfo->originalFormat = stream->getOriginalFormat();
1527 streamInfo->dataSpaceOverridden = stream->isDataSpaceOverridden();
1528 streamInfo->originalDataSpace = stream->getOriginalDataSpace();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001529 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001530}
1531
1532status_t Camera3Device::setStreamTransform(int id,
1533 int transform) {
1534 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001535 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001536 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001537
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001538 switch (mStatus) {
1539 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001540 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001541 return INVALID_OPERATION;
1542 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001543 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001544 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001545 case STATUS_UNCONFIGURED:
1546 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001547 case STATUS_ACTIVE:
1548 // OK
1549 break;
1550 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001551 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001552 return INVALID_OPERATION;
1553 }
1554
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001555 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(id);
1556 if (stream == nullptr) {
1557 CLOGE("Stream %d does not exist", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001558 return BAD_VALUE;
1559 }
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001560 return stream->setTransform(transform);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001561}
1562
1563status_t Camera3Device::deleteStream(int id) {
1564 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001565 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001566 Mutex::Autolock l(mLock);
1567 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001568
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001569 ALOGV("%s: Camera %s: Deleting stream %d", __FUNCTION__, mId.string(), id);
Igor Murashkine2172be2013-05-28 15:31:39 -07001570
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001571 // CameraDevice semantics require device to already be idle before
1572 // deleteStream is called, unlike for createStream.
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001573 if (mStatus == STATUS_ACTIVE) {
Yin-Chia Yeh693047d2018-03-08 12:14:19 -08001574 ALOGW("%s: Camera %s: Device not idle", __FUNCTION__, mId.string());
Igor Murashkin52827132013-05-13 14:53:44 -07001575 return -EBUSY;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001576 }
1577
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07001578 if (mStatus == STATUS_ERROR) {
1579 ALOGW("%s: Camera %s: deleteStream not allowed in ERROR state",
1580 __FUNCTION__, mId.string());
1581 return -EBUSY;
1582 }
1583
Igor Murashkin2fba5842013-04-22 14:03:54 -07001584 sp<Camera3StreamInterface> deletedStream;
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001585 sp<Camera3StreamInterface> stream = mOutputStreams.get(id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001586 if (mInputStream != NULL && id == mInputStream->getId()) {
1587 deletedStream = mInputStream;
1588 mInputStream.clear();
1589 } else {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001590 if (stream == nullptr) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001591 CLOGE("Stream %d does not exist", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001592 return BAD_VALUE;
1593 }
Shuzhen Wang316781a2020-08-18 18:11:01 -07001594 mSessionStatsBuilder.removeStream(id);
Zhijun He5f446352014-01-22 09:49:33 -08001595 }
1596
1597 // Delete output stream or the output part of a bi-directional stream.
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001598 if (stream != nullptr) {
1599 deletedStream = stream;
1600 mOutputStreams.remove(id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001601 }
1602
1603 // Free up the stream endpoint so that it can be used by some other stream
1604 res = deletedStream->disconnect();
1605 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001606 SET_ERR_L("Can't disconnect deleted stream %d", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001607 // fall through since we want to still list the stream as deleted.
1608 }
1609 mDeletedStreams.add(deletedStream);
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07001610 mNeedConfig = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001611
1612 return res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001613}
1614
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001615status_t Camera3Device::configureStreams(const CameraMetadata& sessionParams, int operatingMode) {
Igor Murashkine2d167e2014-08-19 16:19:59 -07001616 ATRACE_CALL();
1617 ALOGV("%s: E", __FUNCTION__);
1618
1619 Mutex::Autolock il(mInterfaceLock);
1620 Mutex::Autolock l(mLock);
Chien-Yu Chen17338fc2015-06-18 16:30:12 -07001621
Emilian Peev811d2952018-05-25 11:08:40 +01001622 // In case the client doesn't include any session parameter, try a
1623 // speculative configuration using the values from the last cached
1624 // default request.
1625 if (sessionParams.isEmpty() &&
Emilian Peevf4816702020-04-03 15:44:51 -07001626 ((mLastTemplateId > 0) && (mLastTemplateId < CAMERA_TEMPLATE_COUNT)) &&
Emilian Peev811d2952018-05-25 11:08:40 +01001627 (!mRequestTemplateCache[mLastTemplateId].isEmpty())) {
1628 ALOGV("%s: Speculative session param configuration with template id: %d", __func__,
1629 mLastTemplateId);
1630 return filterParamsAndConfigureLocked(mRequestTemplateCache[mLastTemplateId],
1631 operatingMode);
1632 }
1633
Emilian Peevac3ce6c2017-12-12 15:27:02 +00001634 return filterParamsAndConfigureLocked(sessionParams, operatingMode);
1635}
1636
1637status_t Camera3Device::filterParamsAndConfigureLocked(const CameraMetadata& sessionParams,
1638 int operatingMode) {
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001639 //Filter out any incoming session parameters
1640 const CameraMetadata params(sessionParams);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001641 camera_metadata_entry_t availableSessionKeys = mDeviceInfo.find(
1642 ANDROID_REQUEST_AVAILABLE_SESSION_KEYS);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00001643 CameraMetadata filteredParams(availableSessionKeys.count);
1644 camera_metadata_t *meta = const_cast<camera_metadata_t *>(
1645 filteredParams.getAndLock());
1646 set_camera_metadata_vendor_id(meta, mVendorTagId);
1647 filteredParams.unlock(meta);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001648 if (availableSessionKeys.count > 0) {
1649 for (size_t i = 0; i < availableSessionKeys.count; i++) {
1650 camera_metadata_ro_entry entry = params.find(
1651 availableSessionKeys.data.i32[i]);
1652 if (entry.count > 0) {
1653 filteredParams.update(entry);
1654 }
1655 }
1656 }
1657
1658 return configureStreamsLocked(operatingMode, filteredParams);
Igor Murashkine2d167e2014-08-19 16:19:59 -07001659}
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001660
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07001661status_t Camera3Device::getInputBufferProducer(
1662 sp<IGraphicBufferProducer> *producer) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07001663 ATRACE_CALL();
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07001664 Mutex::Autolock il(mInterfaceLock);
1665 Mutex::Autolock l(mLock);
1666
1667 if (producer == NULL) {
1668 return BAD_VALUE;
1669 } else if (mInputStream == NULL) {
1670 return INVALID_OPERATION;
1671 }
1672
1673 return mInputStream->getInputBufferProducer(producer);
1674}
1675
Emilian Peevf4816702020-04-03 15:44:51 -07001676status_t Camera3Device::createDefaultRequest(camera_request_template_t templateId,
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001677 CameraMetadata *request) {
1678 ATRACE_CALL();
Alex Rayfe7e0c62013-05-30 00:12:13 -07001679 ALOGV("%s: for template %d", __FUNCTION__, templateId);
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08001680
Emilian Peevf4816702020-04-03 15:44:51 -07001681 if (templateId <= 0 || templateId >= CAMERA_TEMPLATE_COUNT) {
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08001682 android_errorWriteWithInfoLog(CameraService::SN_EVENT_LOG_ID, "26866110",
Jayant Chowdhary12361932018-08-27 14:46:13 -07001683 CameraThreadState::getCallingUid(), nullptr, 0);
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08001684 return BAD_VALUE;
1685 }
1686
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001687 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001688
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001689 {
1690 Mutex::Autolock l(mLock);
1691 switch (mStatus) {
1692 case STATUS_ERROR:
1693 CLOGE("Device has encountered a serious error");
1694 return INVALID_OPERATION;
1695 case STATUS_UNINITIALIZED:
1696 CLOGE("Device is not initialized!");
1697 return INVALID_OPERATION;
1698 case STATUS_UNCONFIGURED:
1699 case STATUS_CONFIGURED:
1700 case STATUS_ACTIVE:
1701 // OK
1702 break;
1703 default:
1704 SET_ERR_L("Unexpected status: %d", mStatus);
1705 return INVALID_OPERATION;
1706 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001707
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001708 if (!mRequestTemplateCache[templateId].isEmpty()) {
1709 *request = mRequestTemplateCache[templateId];
Emilian Peev811d2952018-05-25 11:08:40 +01001710 mLastTemplateId = templateId;
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001711 return OK;
1712 }
Zhijun Hea1530f12014-09-14 12:44:20 -07001713 }
1714
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001715 camera_metadata_t *rawRequest;
1716 status_t res = mInterface->constructDefaultRequestSettings(
Emilian Peevf4816702020-04-03 15:44:51 -07001717 (camera_request_template_t) templateId, &rawRequest);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001718
1719 {
1720 Mutex::Autolock l(mLock);
1721 if (res == BAD_VALUE) {
1722 ALOGI("%s: template %d is not supported on this camera device",
1723 __FUNCTION__, templateId);
1724 return res;
1725 } else if (res != OK) {
1726 CLOGE("Unable to construct request template %d: %s (%d)",
1727 templateId, strerror(-res), res);
1728 return res;
1729 }
1730
1731 set_camera_metadata_vendor_id(rawRequest, mVendorTagId);
1732 mRequestTemplateCache[templateId].acquire(rawRequest);
1733
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08001734 // Override the template request with zoomRatioMapper
1735 res = mZoomRatioMappers[mId.c_str()].initZoomRatioInTemplate(
1736 &mRequestTemplateCache[templateId]);
1737 if (res != OK) {
1738 CLOGE("Failed to update zoom ratio for template %d: %s (%d)",
1739 templateId, strerror(-res), res);
1740 return res;
1741 }
1742
Shuzhen Wangd25dc972020-03-24 17:11:43 -07001743 // Fill in JPEG_QUALITY if not available
1744 if (!mRequestTemplateCache[templateId].exists(ANDROID_JPEG_QUALITY)) {
1745 static const uint8_t kDefaultJpegQuality = 95;
1746 mRequestTemplateCache[templateId].update(ANDROID_JPEG_QUALITY,
1747 &kDefaultJpegQuality, 1);
1748 }
1749
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001750 *request = mRequestTemplateCache[templateId];
Emilian Peev811d2952018-05-25 11:08:40 +01001751 mLastTemplateId = templateId;
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001752 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001753 return OK;
1754}
1755
1756status_t Camera3Device::waitUntilDrained() {
1757 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001758 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001759 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001760 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001761
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001762 return waitUntilDrainedLocked(maxExpectedDuration);
Zhijun He69a37482014-03-23 18:44:49 -07001763}
1764
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001765status_t Camera3Device::waitUntilDrainedLocked(nsecs_t maxExpectedDuration) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001766 switch (mStatus) {
1767 case STATUS_UNINITIALIZED:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001768 case STATUS_UNCONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001769 ALOGV("%s: Already idle", __FUNCTION__);
1770 return OK;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001771 case STATUS_CONFIGURED:
1772 // To avoid race conditions, check with tracker to be sure
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001773 case STATUS_ERROR:
1774 case STATUS_ACTIVE:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001775 // Need to verify shut down
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001776 break;
1777 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001778 SET_ERR_L("Unexpected status: %d",mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001779 return INVALID_OPERATION;
1780 }
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07001781 ALOGV("%s: Camera %s: Waiting until idle (%" PRIi64 "ns)", __FUNCTION__, mId.string(),
1782 maxExpectedDuration);
1783 status_t res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
Eino-Ville Talvala9c8a0912014-09-14 14:52:19 -07001784 if (res != OK) {
Yin-Chia Yeh87b3ec02019-06-03 10:44:39 -07001785 mStatusTracker->dumpActiveComponents();
Eino-Ville Talvala9c8a0912014-09-14 14:52:19 -07001786 SET_ERR_L("Error waiting for HAL to drain: %s (%d)", strerror(-res),
1787 res);
1788 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001789 return res;
1790}
1791
Ruben Brunk183f0562015-08-12 12:55:02 -07001792
1793void Camera3Device::internalUpdateStatusLocked(Status status) {
1794 mStatus = status;
1795 mRecentStatusUpdates.add(mStatus);
1796 mStatusChanged.broadcast();
1797}
1798
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001799// Pause to reconfigure
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001800status_t Camera3Device::internalPauseAndWaitLocked(nsecs_t maxExpectedDuration) {
Emilian Peeve86358b2019-02-15 13:51:39 -08001801 if (mRequestThread.get() != nullptr) {
1802 mRequestThread->setPaused(true);
1803 } else {
1804 return NO_INIT;
1805 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001806
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07001807 ALOGV("%s: Camera %s: Internal wait until idle (% " PRIi64 " ns)", __FUNCTION__, mId.string(),
1808 maxExpectedDuration);
1809 status_t res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001810 if (res != OK) {
1811 SET_ERR_L("Can't idle device in %f seconds!",
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07001812 maxExpectedDuration/1e9);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001813 }
1814
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001815 return res;
1816}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001817
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001818// Resume after internalPauseAndWaitLocked
1819status_t Camera3Device::internalResumeLocked() {
1820 status_t res;
1821
1822 mRequestThread->setPaused(false);
1823
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08001824 ALOGV("%s: Camera %s: Internal wait until active (% " PRIi64 " ns)", __FUNCTION__, mId.string(),
1825 kActiveTimeout);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001826 res = waitUntilStateThenRelock(/*active*/ true, kActiveTimeout);
1827 if (res != OK) {
1828 SET_ERR_L("Can't transition to active in %f seconds!",
1829 kActiveTimeout/1e9);
1830 }
1831 mPauseStateNotify = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001832 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001833}
1834
Ruben Brunk183f0562015-08-12 12:55:02 -07001835status_t Camera3Device::waitUntilStateThenRelock(bool active, nsecs_t timeout) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001836 status_t res = OK;
Ruben Brunk183f0562015-08-12 12:55:02 -07001837
1838 size_t startIndex = 0;
1839 if (mStatusWaiters == 0) {
1840 // Clear the list of recent statuses if there are no existing threads waiting on updates to
1841 // this status list
1842 mRecentStatusUpdates.clear();
1843 } else {
1844 // If other threads are waiting on updates to this status list, set the position of the
1845 // first element that this list will check rather than clearing the list.
1846 startIndex = mRecentStatusUpdates.size();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001847 }
1848
Ruben Brunk183f0562015-08-12 12:55:02 -07001849 mStatusWaiters++;
1850
Yin-Chia Yehe52b8fa2020-07-28 00:17:58 -07001851 bool signalPipelineDrain = false;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07001852 if (!active && mUseHalBufManager) {
1853 auto streamIds = mOutputStreams.getStreamIds();
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08001854 if (mStatus == STATUS_ACTIVE) {
1855 mRequestThread->signalPipelineDrain(streamIds);
Yin-Chia Yehe52b8fa2020-07-28 00:17:58 -07001856 signalPipelineDrain = true;
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08001857 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07001858 mRequestBufferSM.onWaitUntilIdle();
1859 }
1860
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001861 bool stateSeen = false;
1862 do {
Ruben Brunk183f0562015-08-12 12:55:02 -07001863 if (active == (mStatus == STATUS_ACTIVE)) {
1864 // Desired state is current
1865 break;
1866 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001867
1868 res = mStatusChanged.waitRelative(mLock, timeout);
1869 if (res != OK) break;
1870
Ruben Brunk183f0562015-08-12 12:55:02 -07001871 // This is impossible, but if not, could result in subtle deadlocks and invalid state
1872 // transitions.
1873 LOG_ALWAYS_FATAL_IF(startIndex > mRecentStatusUpdates.size(),
1874 "%s: Skipping status updates in Camera3Device, may result in deadlock.",
1875 __FUNCTION__);
1876
1877 // Encountered desired state since we began waiting
1878 for (size_t i = startIndex; i < mRecentStatusUpdates.size(); i++) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001879 if (active == (mRecentStatusUpdates[i] == STATUS_ACTIVE) ) {
1880 stateSeen = true;
1881 break;
1882 }
1883 }
1884 } while (!stateSeen);
1885
Yin-Chia Yehe52b8fa2020-07-28 00:17:58 -07001886 if (signalPipelineDrain) {
1887 mRequestThread->resetPipelineDrain();
1888 }
1889
Ruben Brunk183f0562015-08-12 12:55:02 -07001890 mStatusWaiters--;
1891
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001892 return res;
1893}
1894
1895
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001896status_t Camera3Device::setNotifyCallback(wp<NotificationListener> listener) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001897 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001898 std::lock_guard<std::mutex> l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001899
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001900 if (listener != NULL && mListener != NULL) {
1901 ALOGW("%s: Replacing old callback listener", __FUNCTION__);
1902 }
1903 mListener = listener;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001904 mRequestThread->setNotificationListener(listener);
1905 mPreparerThread->setNotificationListener(listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001906
1907 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001908}
1909
Eino-Ville Talvala46910bd2013-07-18 19:15:17 -07001910bool Camera3Device::willNotify3A() {
1911 return false;
1912}
1913
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001914status_t Camera3Device::waitForNextFrame(nsecs_t timeout) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07001915 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001916 std::unique_lock<std::mutex> l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001917
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001918 while (mResultQueue.empty()) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001919 auto st = mResultSignal.wait_for(l, std::chrono::nanoseconds(timeout));
1920 if (st == std::cv_status::timeout) {
1921 return TIMED_OUT;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001922 }
1923 }
1924 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001925}
1926
Jianing Weicb0652e2014-03-12 18:29:36 -07001927status_t Camera3Device::getNextResult(CaptureResult *frame) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001928 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001929 std::lock_guard<std::mutex> l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001930
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001931 if (mResultQueue.empty()) {
1932 return NOT_ENOUGH_DATA;
1933 }
1934
Jianing Weicb0652e2014-03-12 18:29:36 -07001935 if (frame == NULL) {
1936 ALOGE("%s: argument cannot be NULL", __FUNCTION__);
1937 return BAD_VALUE;
1938 }
1939
1940 CaptureResult &result = *(mResultQueue.begin());
1941 frame->mResultExtras = result.mResultExtras;
1942 frame->mMetadata.acquire(result.mMetadata);
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001943 frame->mPhysicalMetadatas = std::move(result.mPhysicalMetadatas);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001944 mResultQueue.erase(mResultQueue.begin());
1945
1946 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001947}
1948
1949status_t Camera3Device::triggerAutofocus(uint32_t id) {
1950 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001951 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001952
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001953 ALOGV("%s: Triggering autofocus, id %d", __FUNCTION__, id);
1954 // Mix-in this trigger into the next request and only the next request.
1955 RequestTrigger trigger[] = {
1956 {
1957 ANDROID_CONTROL_AF_TRIGGER,
1958 ANDROID_CONTROL_AF_TRIGGER_START
1959 },
1960 {
1961 ANDROID_CONTROL_AF_TRIGGER_ID,
1962 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07001963 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001964 };
1965
1966 return mRequestThread->queueTrigger(trigger,
1967 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001968}
1969
1970status_t Camera3Device::triggerCancelAutofocus(uint32_t id) {
1971 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001972 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001973
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001974 ALOGV("%s: Triggering cancel autofocus, id %d", __FUNCTION__, id);
1975 // Mix-in this trigger into the next request and only the next request.
1976 RequestTrigger trigger[] = {
1977 {
1978 ANDROID_CONTROL_AF_TRIGGER,
1979 ANDROID_CONTROL_AF_TRIGGER_CANCEL
1980 },
1981 {
1982 ANDROID_CONTROL_AF_TRIGGER_ID,
1983 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07001984 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001985 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001986
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001987 return mRequestThread->queueTrigger(trigger,
1988 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001989}
1990
1991status_t Camera3Device::triggerPrecaptureMetering(uint32_t id) {
1992 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001993 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001994
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001995 ALOGV("%s: Triggering precapture metering, id %d", __FUNCTION__, id);
1996 // Mix-in this trigger into the next request and only the next request.
1997 RequestTrigger trigger[] = {
1998 {
1999 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER,
2000 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_START
2001 },
2002 {
2003 ANDROID_CONTROL_AE_PRECAPTURE_ID,
2004 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07002005 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002006 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002007
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002008 return mRequestThread->queueTrigger(trigger,
2009 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002010}
2011
Jianing Weicb0652e2014-03-12 18:29:36 -07002012status_t Camera3Device::flush(int64_t *frameNumber) {
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07002013 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002014 ALOGV("%s: Camera %s: Flushing all requests", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002015 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07002016
Zhijun He7ef20392014-04-21 16:04:17 -07002017 {
2018 Mutex::Autolock l(mLock);
Emilian Peeved2ebe42018-09-25 16:59:09 +01002019
2020 // b/116514106 "disconnect()" can get called twice for the same device. The
2021 // camera device will not be initialized during the second run.
2022 if (mStatus == STATUS_UNINITIALIZED) {
2023 return OK;
2024 }
2025
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002026 mRequestThread->clear(/*out*/frameNumber);
Shuzhen Wang316781a2020-08-18 18:11:01 -07002027
2028 // Stop session and stream counter
2029 mSessionStatsBuilder.stopCounter();
Zhijun He7ef20392014-04-21 16:04:17 -07002030 }
2031
Emilian Peev08dd2452017-04-06 16:55:14 +01002032 return mRequestThread->flush();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07002033}
2034
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002035status_t Camera3Device::prepare(int streamId) {
Ruben Brunkc78ac262015-08-13 17:58:46 -07002036 return prepare(camera3::Camera3StreamInterface::ALLOCATE_PIPELINE_MAX, streamId);
2037}
2038
2039status_t Camera3Device::prepare(int maxCount, int streamId) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002040 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002041 ALOGV("%s: Camera %s: Preparing stream %d", __FUNCTION__, mId.string(), streamId);
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07002042 Mutex::Autolock il(mInterfaceLock);
2043 Mutex::Autolock l(mLock);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002044
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002045 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
2046 if (stream == nullptr) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002047 CLOGE("Stream %d does not exist", streamId);
2048 return BAD_VALUE;
2049 }
2050
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002051 if (stream->isUnpreparable() || stream->hasOutstandingBuffers() ) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07002052 CLOGE("Stream %d has already been a request target", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002053 return BAD_VALUE;
2054 }
2055
2056 if (mRequestThread->isStreamPending(stream)) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07002057 CLOGE("Stream %d is already a target in a pending request", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002058 return BAD_VALUE;
2059 }
2060
Ruben Brunkc78ac262015-08-13 17:58:46 -07002061 return mPreparerThread->prepare(maxCount, stream);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002062}
2063
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002064status_t Camera3Device::tearDown(int streamId) {
2065 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002066 ALOGV("%s: Camera %s: Tearing down stream %d", __FUNCTION__, mId.string(), streamId);
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002067 Mutex::Autolock il(mInterfaceLock);
2068 Mutex::Autolock l(mLock);
2069
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002070 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
2071 if (stream == nullptr) {
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002072 CLOGE("Stream %d does not exist", streamId);
2073 return BAD_VALUE;
2074 }
2075
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002076 if (stream->hasOutstandingBuffers() || mRequestThread->isStreamPending(stream)) {
2077 CLOGE("Stream %d is a target of a in-progress request", streamId);
2078 return BAD_VALUE;
2079 }
2080
2081 return stream->tearDown();
2082}
2083
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002084status_t Camera3Device::addBufferListenerForStream(int streamId,
2085 wp<Camera3StreamBufferListener> listener) {
2086 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002087 ALOGV("%s: Camera %s: Adding buffer listener for stream %d", __FUNCTION__, mId.string(), streamId);
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002088 Mutex::Autolock il(mInterfaceLock);
2089 Mutex::Autolock l(mLock);
2090
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002091 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
2092 if (stream == nullptr) {
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002093 CLOGE("Stream %d does not exist", streamId);
2094 return BAD_VALUE;
2095 }
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002096 stream->addBufferListener(listener);
2097
2098 return OK;
2099}
2100
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002101/**
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002102 * Methods called by subclasses
2103 */
2104
2105void Camera3Device::notifyStatus(bool idle) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002106 ATRACE_CALL();
Shuzhen Wang316781a2020-08-18 18:11:01 -07002107 std::vector<int> streamIds;
2108 std::vector<hardware::CameraStreamStats> streamStats;
2109
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002110 {
2111 // Need mLock to safely update state and synchronize to current
2112 // state of methods in flight.
2113 Mutex::Autolock l(mLock);
2114 // We can get various system-idle notices from the status tracker
2115 // while starting up. Only care about them if we've actually sent
2116 // in some requests recently.
2117 if (mStatus != STATUS_ACTIVE && mStatus != STATUS_CONFIGURED) {
2118 return;
2119 }
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08002120 ALOGV("%s: Camera %s: Now %s, pauseState: %s", __FUNCTION__, mId.string(),
2121 idle ? "idle" : "active", mPauseStateNotify ? "true" : "false");
Ruben Brunk183f0562015-08-12 12:55:02 -07002122 internalUpdateStatusLocked(idle ? STATUS_CONFIGURED : STATUS_ACTIVE);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002123
2124 // Skip notifying listener if we're doing some user-transparent
2125 // state changes
2126 if (mPauseStateNotify) return;
Shuzhen Wang316781a2020-08-18 18:11:01 -07002127
2128 // Populate stream statistics in case of Idle
2129 if (idle) {
2130 for (size_t i = 0; i < mOutputStreams.size(); i++) {
2131 auto stream = mOutputStreams[i];
2132 if (stream.get() == nullptr) continue;
2133 streamIds.push_back(stream->getId());
2134 Camera3Stream* camera3Stream = Camera3Stream::cast(stream->asHalStream());
2135 int64_t usage = 0LL;
2136 if (camera3Stream != nullptr) {
2137 usage = camera3Stream->getUsage();
2138 }
2139 streamStats.emplace_back(stream->getWidth(), stream->getHeight(),
2140 stream->getFormat(), stream->getDataSpace(), usage,
2141 stream->getMaxHalBuffers(),
2142 stream->getMaxTotalBuffers() - stream->getMaxHalBuffers());
2143 }
2144 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002145 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002146
2147 sp<NotificationListener> listener;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002148 {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002149 std::lock_guard<std::mutex> l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002150 listener = mListener.promote();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002151 }
2152 if (idle && listener != NULL) {
Shuzhen Wang316781a2020-08-18 18:11:01 -07002153 // Get session stats from the builder, and notify the listener.
2154 int64_t requestCount, resultErrorCount;
2155 bool deviceError;
2156 std::map<int, StreamStats> streamStatsMap;
2157 mSessionStatsBuilder.buildAndReset(&requestCount, &resultErrorCount,
2158 &deviceError, &streamStatsMap);
2159 for (size_t i = 0; i < streamIds.size(); i++) {
2160 int streamId = streamIds[i];
2161 auto stats = streamStatsMap.find(streamId);
2162 if (stats != streamStatsMap.end()) {
2163 streamStats[i].mRequestCount = stats->second.mRequestedFrameCount;
2164 streamStats[i].mErrorCount = stats->second.mDroppedFrameCount;
2165 streamStats[i].mStartLatencyMs = stats->second.mStartLatencyMs;
Shuzhen Wangdb8f2782020-10-30 08:43:37 -07002166 streamStats[i].mHistogramType =
2167 hardware::CameraStreamStats::HISTOGRAM_TYPE_CAPTURE_LATENCY;
2168 streamStats[i].mHistogramBins.assign(
2169 stats->second.mCaptureLatencyBins.begin(),
2170 stats->second.mCaptureLatencyBins.end());
2171 streamStats[i].mHistogramCounts.assign(
2172 stats->second.mCaptureLatencyHistogram.begin(),
2173 stats->second.mCaptureLatencyHistogram.end());
Shuzhen Wang316781a2020-08-18 18:11:01 -07002174 }
2175 }
2176 listener->notifyIdle(requestCount, resultErrorCount, deviceError, streamStats);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002177 }
2178}
2179
Shuzhen Wang758c2152017-01-10 18:26:18 -08002180status_t Camera3Device::setConsumerSurfaces(int streamId,
Emilian Peev40ead602017-09-26 15:46:36 +01002181 const std::vector<sp<Surface>>& consumers, std::vector<int> *surfaceIds) {
Zhijun He5d677d12016-05-29 16:52:39 -07002182 ATRACE_CALL();
Shuzhen Wang758c2152017-01-10 18:26:18 -08002183 ALOGV("%s: Camera %s: set consumer surface for stream %d",
2184 __FUNCTION__, mId.string(), streamId);
Emilian Peev40ead602017-09-26 15:46:36 +01002185
2186 if (surfaceIds == nullptr) {
2187 return BAD_VALUE;
2188 }
2189
Zhijun He5d677d12016-05-29 16:52:39 -07002190 Mutex::Autolock il(mInterfaceLock);
2191 Mutex::Autolock l(mLock);
2192
Shuzhen Wang758c2152017-01-10 18:26:18 -08002193 if (consumers.size() == 0) {
2194 CLOGE("No consumer is passed!");
Zhijun He5d677d12016-05-29 16:52:39 -07002195 return BAD_VALUE;
2196 }
2197
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002198 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
2199 if (stream == nullptr) {
Zhijun He5d677d12016-05-29 16:52:39 -07002200 CLOGE("Stream %d is unknown", streamId);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002201 return BAD_VALUE;
Zhijun He5d677d12016-05-29 16:52:39 -07002202 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002203
2204 // isConsumerConfigurationDeferred will be off after setConsumers
2205 bool isDeferred = stream->isConsumerConfigurationDeferred();
Shuzhen Wang758c2152017-01-10 18:26:18 -08002206 status_t res = stream->setConsumers(consumers);
Zhijun He5d677d12016-05-29 16:52:39 -07002207 if (res != OK) {
2208 CLOGE("Stream %d set consumer failed (error %d %s) ", streamId, res, strerror(-res));
2209 return res;
2210 }
2211
Emilian Peev40ead602017-09-26 15:46:36 +01002212 for (auto &consumer : consumers) {
2213 int id = stream->getSurfaceId(consumer);
2214 if (id < 0) {
2215 CLOGE("Invalid surface id!");
2216 return BAD_VALUE;
2217 }
2218 surfaceIds->push_back(id);
2219 }
2220
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002221 if (isDeferred) {
Shuzhen Wang0129d522016-10-30 22:43:41 -07002222 if (!stream->isConfiguring()) {
2223 CLOGE("Stream %d was already fully configured.", streamId);
2224 return INVALID_OPERATION;
2225 }
Zhijun He5d677d12016-05-29 16:52:39 -07002226
Shuzhen Wang0129d522016-10-30 22:43:41 -07002227 res = stream->finishConfiguration();
2228 if (res != OK) {
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002229 // If finishConfiguration fails due to abandoned surface, do not set
2230 // device to error state.
2231 bool isSurfaceAbandoned =
2232 (res == NO_INIT || res == DEAD_OBJECT) && stream->isAbandoned();
2233 if (!isSurfaceAbandoned) {
2234 SET_ERR_L("Can't finish configuring output stream %d: %s (%d)",
2235 stream->getId(), strerror(-res), res);
2236 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07002237 return res;
2238 }
Zhijun He5d677d12016-05-29 16:52:39 -07002239 }
2240
2241 return OK;
2242}
2243
Emilian Peev40ead602017-09-26 15:46:36 +01002244status_t Camera3Device::updateStream(int streamId, const std::vector<sp<Surface>> &newSurfaces,
2245 const std::vector<OutputStreamInfo> &outputInfo,
2246 const std::vector<size_t> &removedSurfaceIds, KeyedVector<sp<Surface>, size_t> *outputMap) {
2247 Mutex::Autolock il(mInterfaceLock);
2248 Mutex::Autolock l(mLock);
2249
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002250 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
2251 if (stream == nullptr) {
Emilian Peev40ead602017-09-26 15:46:36 +01002252 CLOGE("Stream %d is unknown", streamId);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002253 return BAD_VALUE;
Emilian Peev40ead602017-09-26 15:46:36 +01002254 }
2255
2256 for (const auto &it : removedSurfaceIds) {
2257 if (mRequestThread->isOutputSurfacePending(streamId, it)) {
2258 CLOGE("Shared surface still part of a pending request!");
2259 return -EBUSY;
2260 }
2261 }
2262
Emilian Peev40ead602017-09-26 15:46:36 +01002263 status_t res = stream->updateStream(newSurfaces, outputInfo, removedSurfaceIds, outputMap);
2264 if (res != OK) {
2265 CLOGE("Stream %d failed to update stream (error %d %s) ",
2266 streamId, res, strerror(-res));
2267 if (res == UNKNOWN_ERROR) {
2268 SET_ERR_L("%s: Stream update failed to revert to previous output configuration!",
2269 __FUNCTION__);
2270 }
2271 return res;
2272 }
2273
2274 return res;
2275}
2276
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002277status_t Camera3Device::dropStreamBuffers(bool dropping, int streamId) {
2278 Mutex::Autolock il(mInterfaceLock);
2279 Mutex::Autolock l(mLock);
2280
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002281 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
2282 if (stream == nullptr) {
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002283 ALOGE("%s: Stream %d is not found.", __FUNCTION__, streamId);
2284 return BAD_VALUE;
2285 }
Shuzhen Wang316781a2020-08-18 18:11:01 -07002286
2287 if (dropping) {
2288 mSessionStatsBuilder.stopCounter(streamId);
2289 } else {
2290 mSessionStatsBuilder.startCounter(streamId);
2291 }
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002292 return stream->dropBuffers(dropping);
2293}
2294
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002295/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002296 * Camera3Device private methods
2297 */
2298
2299sp<Camera3Device::CaptureRequest> Camera3Device::createCaptureRequest(
Emilian Peevaebbe412018-01-15 13:53:24 +00002300 const PhysicalCameraSettingsList &request, const SurfaceMap &surfaceMap) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002301 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002302
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08002303 sp<CaptureRequest> newRequest = new CaptureRequest();
Emilian Peevaebbe412018-01-15 13:53:24 +00002304 newRequest->mSettingsList = request;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002305
2306 camera_metadata_entry_t inputStreams =
Emilian Peevaebbe412018-01-15 13:53:24 +00002307 newRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_INPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002308 if (inputStreams.count > 0) {
2309 if (mInputStream == NULL ||
Zhijun Hed1d64672013-09-06 15:00:01 -07002310 mInputStream->getId() != inputStreams.data.i32[0]) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002311 CLOGE("Request references unknown input stream %d",
2312 inputStreams.data.u8[0]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002313 return NULL;
2314 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002315
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002316 if (mInputStream->isConfiguring()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002317 SET_ERR_L("%s: input stream %d is not configured!",
2318 __FUNCTION__, mInputStream->getId());
2319 return NULL;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002320 }
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07002321 // Check if stream prepare is blocking requests.
2322 if (mInputStream->isBlockedByPrepare()) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002323 CLOGE("Request references an input stream that's being prepared!");
2324 return NULL;
2325 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002326
2327 newRequest->mInputStream = mInputStream;
Emilian Peevaebbe412018-01-15 13:53:24 +00002328 newRequest->mSettingsList.begin()->metadata.erase(ANDROID_REQUEST_INPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002329 }
2330
2331 camera_metadata_entry_t streams =
Emilian Peevaebbe412018-01-15 13:53:24 +00002332 newRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_OUTPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002333 if (streams.count == 0) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002334 CLOGE("Zero output streams specified!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002335 return NULL;
2336 }
2337
2338 for (size_t i = 0; i < streams.count; i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002339 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streams.data.i32[i]);
2340 if (stream == nullptr) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002341 CLOGE("Request references unknown stream %d",
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002342 streams.data.i32[i]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002343 return NULL;
2344 }
Zhijun He5d677d12016-05-29 16:52:39 -07002345 // It is illegal to include a deferred consumer output stream into a request
Shuzhen Wang0129d522016-10-30 22:43:41 -07002346 auto iter = surfaceMap.find(streams.data.i32[i]);
2347 if (iter != surfaceMap.end()) {
2348 const std::vector<size_t>& surfaces = iter->second;
2349 for (const auto& surface : surfaces) {
2350 if (stream->isConsumerConfigurationDeferred(surface)) {
2351 CLOGE("Stream %d surface %zu hasn't finished configuration yet "
2352 "due to deferred consumer", stream->getId(), surface);
2353 return NULL;
2354 }
2355 }
Yin-Chia Yeh0b287572018-10-15 12:38:13 -07002356 newRequest->mOutputSurfaces[streams.data.i32[i]] = surfaces;
Zhijun He5d677d12016-05-29 16:52:39 -07002357 }
2358
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002359 if (stream->isConfiguring()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002360 SET_ERR_L("%s: stream %d is not configured!", __FUNCTION__, stream->getId());
2361 return NULL;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002362 }
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07002363 // Check if stream prepare is blocking requests.
2364 if (stream->isBlockedByPrepare()) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002365 CLOGE("Request references an output stream that's being prepared!");
2366 return NULL;
2367 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002368
2369 newRequest->mOutputStreams.push(stream);
2370 }
Emilian Peevaebbe412018-01-15 13:53:24 +00002371 newRequest->mSettingsList.begin()->metadata.erase(ANDROID_REQUEST_OUTPUT_STREAMS);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07002372 newRequest->mBatchSize = 1;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002373
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08002374 auto rotateAndCropEntry =
2375 newRequest->mSettingsList.begin()->metadata.find(ANDROID_SCALER_ROTATE_AND_CROP);
2376 if (rotateAndCropEntry.count > 0 &&
2377 rotateAndCropEntry.data.u8[0] == ANDROID_SCALER_ROTATE_AND_CROP_AUTO) {
2378 newRequest->mRotateAndCropAuto = true;
2379 } else {
2380 newRequest->mRotateAndCropAuto = false;
2381 }
2382
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07002383 auto zoomRatioEntry =
2384 newRequest->mSettingsList.begin()->metadata.find(ANDROID_CONTROL_ZOOM_RATIO);
2385 if (zoomRatioEntry.count > 0 &&
2386 zoomRatioEntry.data.f[0] == 1.0f) {
2387 newRequest->mZoomRatioIs1x = true;
2388 } else {
2389 newRequest->mZoomRatioIs1x = false;
2390 }
2391
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08002392 if (mSupportCameraMute) {
2393 auto testPatternModeEntry =
2394 newRequest->mSettingsList.begin()->metadata.find(ANDROID_SENSOR_TEST_PATTERN_MODE);
2395 newRequest->mOriginalTestPatternMode = testPatternModeEntry.count > 0 ?
2396 testPatternModeEntry.data.i32[0] :
2397 ANDROID_SENSOR_TEST_PATTERN_MODE_OFF;
2398
2399 auto testPatternDataEntry =
2400 newRequest->mSettingsList.begin()->metadata.find(ANDROID_SENSOR_TEST_PATTERN_DATA);
2401 if (testPatternDataEntry.count > 0) {
2402 memcpy(newRequest->mOriginalTestPatternData, testPatternModeEntry.data.i32,
2403 sizeof(newRequest->mOriginalTestPatternData));
2404 } else {
2405 newRequest->mOriginalTestPatternData[0] = 0;
2406 newRequest->mOriginalTestPatternData[1] = 0;
2407 newRequest->mOriginalTestPatternData[2] = 0;
2408 newRequest->mOriginalTestPatternData[3] = 0;
2409 }
2410 }
2411
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002412 return newRequest;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002413}
2414
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002415void Camera3Device::cancelStreamsConfigurationLocked() {
2416 int res = OK;
2417 if (mInputStream != NULL && mInputStream->isConfiguring()) {
2418 res = mInputStream->cancelConfiguration();
2419 if (res != OK) {
2420 CLOGE("Can't cancel configuring input stream %d: %s (%d)",
2421 mInputStream->getId(), strerror(-res), res);
2422 }
2423 }
2424
2425 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002426 sp<Camera3OutputStreamInterface> outputStream = mOutputStreams[i];
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002427 if (outputStream->isConfiguring()) {
2428 res = outputStream->cancelConfiguration();
2429 if (res != OK) {
2430 CLOGE("Can't cancel configuring output stream %d: %s (%d)",
2431 outputStream->getId(), strerror(-res), res);
2432 }
2433 }
2434 }
2435
2436 // Return state to that at start of call, so that future configures
2437 // properly clean things up
2438 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
2439 mNeedConfig = true;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002440
2441 res = mPreparerThread->resume();
2442 if (res != OK) {
2443 ALOGE("%s: Camera %s: Preparer thread failed to resume!", __FUNCTION__, mId.string());
2444 }
2445}
2446
Emilian Peev0d0191e2020-04-21 17:01:18 -07002447bool Camera3Device::checkAbandonedStreamsLocked() {
2448 if ((mInputStream.get() != nullptr) && (mInputStream->isAbandoned())) {
2449 return true;
2450 }
2451
2452 for (size_t i = 0; i < mOutputStreams.size(); i++) {
2453 auto stream = mOutputStreams[i];
2454 if ((stream.get() != nullptr) && (stream->isAbandoned())) {
2455 return true;
2456 }
2457 }
2458
2459 return false;
2460}
2461
Emilian Peev3bead5f2020-05-28 17:29:08 -07002462bool Camera3Device::reconfigureCamera(const CameraMetadata& sessionParams, int clientStatusId) {
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002463 ATRACE_CALL();
2464 bool ret = false;
2465
Shuzhen Wang316781a2020-08-18 18:11:01 -07002466 nsecs_t startTime = systemTime();
2467
Jayant Chowdhary646c31b2020-01-30 13:09:59 -08002468 Mutex::Autolock il(mInterfaceLock);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002469 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
2470
2471 Mutex::Autolock l(mLock);
Emilian Peev0d0191e2020-04-21 17:01:18 -07002472 if (checkAbandonedStreamsLocked()) {
2473 ALOGW("%s: Abandoned stream detected, session parameters can't be applied correctly!",
2474 __FUNCTION__);
2475 return true;
2476 }
2477
Emilian Peev3bead5f2020-05-28 17:29:08 -07002478 status_t rc = NO_ERROR;
2479 bool markClientActive = false;
2480 if (mStatus == STATUS_ACTIVE) {
2481 markClientActive = true;
2482 mPauseStateNotify = true;
2483 mStatusTracker->markComponentIdle(clientStatusId, Fence::NO_FENCE);
2484
2485 rc = internalPauseAndWaitLocked(maxExpectedDuration);
2486 }
2487
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002488 if (rc == NO_ERROR) {
2489 mNeedConfig = true;
2490 rc = configureStreamsLocked(mOperatingMode, sessionParams, /*notifyRequestThread*/ false);
2491 if (rc == NO_ERROR) {
2492 ret = true;
2493 mPauseStateNotify = false;
2494 //Moving to active state while holding 'mLock' is important.
2495 //There could be pending calls to 'create-/deleteStream' which
2496 //will trigger another stream configuration while the already
2497 //present streams end up with outstanding buffers that will
2498 //not get drained.
2499 internalUpdateStatusLocked(STATUS_ACTIVE);
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002500 } else if (rc == DEAD_OBJECT) {
2501 // DEAD_OBJECT can be returned if either the consumer surface is
2502 // abandoned, or the HAL has died.
2503 // - If the HAL has died, configureStreamsLocked call will set
2504 // device to error state,
2505 // - If surface is abandoned, we should not set device to error
2506 // state.
2507 ALOGE("Failed to re-configure camera due to abandoned surface");
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002508 } else {
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002509 SET_ERR_L("Failed to re-configure camera: %d", rc);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002510 }
2511 } else {
2512 ALOGE("%s: Failed to pause streaming: %d", __FUNCTION__, rc);
2513 }
2514
Shuzhen Wang316781a2020-08-18 18:11:01 -07002515 CameraServiceProxyWrapper::logStreamConfigured(mId, mOperatingMode, true /*internalReconfig*/,
2516 ns2ms(systemTime() - startTime));
2517
Emilian Peev3bead5f2020-05-28 17:29:08 -07002518 if (markClientActive) {
2519 mStatusTracker->markComponentActive(clientStatusId);
2520 }
2521
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002522 return ret;
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002523}
2524
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002525status_t Camera3Device::configureStreamsLocked(int operatingMode,
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002526 const CameraMetadata& sessionParams, bool notifyRequestThread) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002527 ATRACE_CALL();
2528 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002529
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002530 if (mStatus != STATUS_UNCONFIGURED && mStatus != STATUS_CONFIGURED) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002531 CLOGE("Not idle");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002532 return INVALID_OPERATION;
2533 }
2534
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08002535 if (operatingMode < 0) {
2536 CLOGE("Invalid operating mode: %d", operatingMode);
2537 return BAD_VALUE;
2538 }
2539
2540 bool isConstrainedHighSpeed =
2541 static_cast<int>(StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE) ==
2542 operatingMode;
2543
2544 if (mOperatingMode != operatingMode) {
2545 mNeedConfig = true;
2546 mIsConstrainedHighSpeedConfiguration = isConstrainedHighSpeed;
2547 mOperatingMode = operatingMode;
2548 }
2549
Shuzhen Wang0cf01cb2019-09-05 13:33:06 -07002550 // In case called from configureStreams, abort queued input buffers not belonging to
2551 // any pending requests.
2552 if (mInputStream != NULL && notifyRequestThread) {
2553 while (true) {
Emilian Peevf4816702020-04-03 15:44:51 -07002554 camera_stream_buffer_t inputBuffer;
Shuzhen Wang83bff122020-11-20 15:51:39 -08002555 camera3::Size inputBufferSize;
Shuzhen Wang0cf01cb2019-09-05 13:33:06 -07002556 status_t res = mInputStream->getInputBuffer(&inputBuffer,
Shuzhen Wang83bff122020-11-20 15:51:39 -08002557 &inputBufferSize, /*respectHalLimit*/ false);
Shuzhen Wang0cf01cb2019-09-05 13:33:06 -07002558 if (res != OK) {
2559 // Exhausted acquiring all input buffers.
2560 break;
2561 }
2562
Emilian Peevf4816702020-04-03 15:44:51 -07002563 inputBuffer.status = CAMERA_BUFFER_STATUS_ERROR;
Shuzhen Wang0cf01cb2019-09-05 13:33:06 -07002564 res = mInputStream->returnInputBuffer(inputBuffer);
2565 if (res != OK) {
2566 ALOGE("%s: %d: couldn't return input buffer while clearing input queue: "
2567 "%s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
2568 }
2569 }
2570 }
2571
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002572 if (!mNeedConfig) {
2573 ALOGV("%s: Skipping config, no stream changes", __FUNCTION__);
2574 return OK;
2575 }
2576
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002577 // Workaround for device HALv3.2 or older spec bug - zero streams requires
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002578 // adding a fake stream instead.
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002579 // TODO: Bug: 17321404 for fixing the HAL spec and removing this workaround.
2580 if (mOutputStreams.size() == 0) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002581 addFakeStreamLocked();
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002582 } else {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002583 tryRemoveFakeStreamLocked();
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002584 }
2585
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002586 // Start configuring the streams
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002587 ALOGV("%s: Camera %s: Starting stream configuration", __FUNCTION__, mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002588
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002589 mPreparerThread->pause();
2590
Emilian Peevf4816702020-04-03 15:44:51 -07002591 camera_stream_configuration config;
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -08002592 config.operation_mode = mOperatingMode;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002593 config.num_streams = (mInputStream != NULL) + mOutputStreams.size();
Shuzhen Wang83bff122020-11-20 15:51:39 -08002594 config.input_is_multi_resolution = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002595
Emilian Peevf4816702020-04-03 15:44:51 -07002596 Vector<camera3::camera_stream_t*> streams;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002597 streams.setCapacity(config.num_streams);
Emilian Peev192ee832018-01-31 14:46:47 +00002598 std::vector<uint32_t> bufferSizes(config.num_streams, 0);
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002599
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002600
2601 if (mInputStream != NULL) {
Emilian Peevf4816702020-04-03 15:44:51 -07002602 camera3::camera_stream_t *inputStream;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002603 inputStream = mInputStream->startConfiguration();
2604 if (inputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002605 CLOGE("Can't start input stream configuration");
2606 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002607 return INVALID_OPERATION;
2608 }
2609 streams.add(inputStream);
Shuzhen Wang83bff122020-11-20 15:51:39 -08002610
2611 config.input_is_multi_resolution = mIsInputStreamMultiResolution;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002612 }
2613
2614 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Igor Murashkin2fba5842013-04-22 14:03:54 -07002615
2616 // Don't configure bidi streams twice, nor add them twice to the list
2617 if (mOutputStreams[i].get() ==
2618 static_cast<Camera3StreamInterface*>(mInputStream.get())) {
2619
2620 config.num_streams--;
2621 continue;
2622 }
2623
Emilian Peevf4816702020-04-03 15:44:51 -07002624 camera3::camera_stream_t *outputStream;
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002625 outputStream = mOutputStreams[i]->startConfiguration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002626 if (outputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002627 CLOGE("Can't start output stream configuration");
2628 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002629 return INVALID_OPERATION;
2630 }
2631 streams.add(outputStream);
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002632
Shuzhen Wangb7ab1e42019-02-20 15:42:23 -08002633 if (outputStream->format == HAL_PIXEL_FORMAT_BLOB) {
Emilian Peev192ee832018-01-31 14:46:47 +00002634 size_t k = i + ((mInputStream != nullptr) ? 1 : 0); // Input stream if present should
2635 // always occupy the initial entry.
Shuzhen Wangb7ab1e42019-02-20 15:42:23 -08002636 if (outputStream->data_space == HAL_DATASPACE_V0_JFIF) {
2637 bufferSizes[k] = static_cast<uint32_t>(
2638 getJpegBufferSize(outputStream->width, outputStream->height));
2639 } else if (outputStream->data_space ==
2640 static_cast<android_dataspace>(HAL_DATASPACE_JPEG_APP_SEGMENTS)) {
2641 bufferSizes[k] = outputStream->width * outputStream->height;
2642 } else {
2643 ALOGW("%s: Blob dataSpace %d not supported",
2644 __FUNCTION__, outputStream->data_space);
2645 }
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002646 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002647 }
2648
2649 config.streams = streams.editArray();
2650
2651 // Do the HAL configuration; will potentially touch stream
Shuzhen Wang92653952019-05-07 15:11:43 -07002652 // max_buffers, usage, and priv fields, as well as data_space and format
2653 // fields for IMPLEMENTATION_DEFINED formats.
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002654
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002655 const camera_metadata_t *sessionBuffer = sessionParams.getAndLock();
Emilian Peev192ee832018-01-31 14:46:47 +00002656 res = mInterface->configureStreams(sessionBuffer, &config, bufferSizes);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002657 sessionParams.unlock(sessionBuffer);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002658
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002659 if (res == BAD_VALUE) {
2660 // HAL rejected this set of streams as unsupported, clean up config
2661 // attempt and return to unconfigured state
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002662 CLOGE("Set of requested inputs/outputs not supported by HAL");
2663 cancelStreamsConfigurationLocked();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002664 return BAD_VALUE;
2665 } else if (res != OK) {
2666 // Some other kind of error from configure_streams - this is not
2667 // expected
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002668 SET_ERR_L("Unable to configure streams with HAL: %s (%d)",
2669 strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002670 return res;
2671 }
2672
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002673 // Finish all stream configuration immediately.
2674 // TODO: Try to relax this later back to lazy completion, which should be
2675 // faster
2676
Igor Murashkin073f8572013-05-02 14:59:28 -07002677 if (mInputStream != NULL && mInputStream->isConfiguring()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002678 bool streamReConfigured = false;
2679 res = mInputStream->finishConfiguration(&streamReConfigured);
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002680 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002681 CLOGE("Can't finish configuring input stream %d: %s (%d)",
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002682 mInputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002683 cancelStreamsConfigurationLocked();
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002684 if ((res == NO_INIT || res == DEAD_OBJECT) && mInputStream->isAbandoned()) {
2685 return DEAD_OBJECT;
2686 }
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002687 return BAD_VALUE;
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002688 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002689 if (streamReConfigured) {
2690 mInterface->onStreamReConfigured(mInputStream->getId());
2691 }
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002692 }
2693
2694 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002695 sp<Camera3OutputStreamInterface> outputStream = mOutputStreams[i];
Zhijun He5d677d12016-05-29 16:52:39 -07002696 if (outputStream->isConfiguring() && !outputStream->isConsumerConfigurationDeferred()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002697 bool streamReConfigured = false;
2698 res = outputStream->finishConfiguration(&streamReConfigured);
Igor Murashkin073f8572013-05-02 14:59:28 -07002699 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002700 CLOGE("Can't finish configuring output stream %d: %s (%d)",
Igor Murashkin073f8572013-05-02 14:59:28 -07002701 outputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002702 cancelStreamsConfigurationLocked();
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002703 if ((res == NO_INIT || res == DEAD_OBJECT) && outputStream->isAbandoned()) {
2704 return DEAD_OBJECT;
2705 }
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002706 return BAD_VALUE;
Igor Murashkin073f8572013-05-02 14:59:28 -07002707 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002708 if (streamReConfigured) {
2709 mInterface->onStreamReConfigured(outputStream->getId());
2710 }
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002711 }
2712 }
2713
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002714 // Request thread needs to know to avoid using repeat-last-settings protocol
2715 // across configure_streams() calls
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002716 if (notifyRequestThread) {
2717 mRequestThread->configurationComplete(mIsConstrainedHighSpeedConfiguration, sessionParams);
2718 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002719
Zhijun He90f7c372016-08-16 16:19:43 -07002720 char value[PROPERTY_VALUE_MAX];
2721 property_get("camera.fifo.disable", value, "0");
2722 int32_t disableFifo = atoi(value);
2723 if (disableFifo != 1) {
2724 // Boost priority of request thread to SCHED_FIFO.
2725 pid_t requestThreadTid = mRequestThread->getTid();
2726 res = requestPriority(getpid(), requestThreadTid,
Mikhail Naganov83f04272017-02-07 10:45:09 -08002727 kRequestThreadPriority, /*isForApp*/ false, /*asynchronous*/ false);
Zhijun He90f7c372016-08-16 16:19:43 -07002728 if (res != OK) {
2729 ALOGW("Can't set realtime priority for request processing thread: %s (%d)",
2730 strerror(-res), res);
2731 } else {
2732 ALOGD("Set real time priority for request queue thread (tid %d)", requestThreadTid);
2733 }
Eino-Ville Talvalaf99498e2015-09-25 16:52:55 -07002734 }
2735
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002736 // Update device state
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002737 const camera_metadata_t *newSessionParams = sessionParams.getAndLock();
2738 const camera_metadata_t *currentSessionParams = mSessionParams.getAndLock();
2739 bool updateSessionParams = (newSessionParams != currentSessionParams) ? true : false;
2740 sessionParams.unlock(newSessionParams);
2741 mSessionParams.unlock(currentSessionParams);
2742 if (updateSessionParams) {
2743 mSessionParams = sessionParams;
2744 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002745
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002746 mNeedConfig = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002747
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002748 internalUpdateStatusLocked((mFakeStreamId == NO_STREAM) ?
Ruben Brunk183f0562015-08-12 12:55:02 -07002749 STATUS_CONFIGURED : STATUS_UNCONFIGURED);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002750
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002751 ALOGV("%s: Camera %s: Stream configuration complete", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002752
Zhijun He0a210512014-07-24 13:45:15 -07002753 // tear down the deleted streams after configure streams.
2754 mDeletedStreams.clear();
2755
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002756 auto rc = mPreparerThread->resume();
2757 if (rc != OK) {
2758 SET_ERR_L("%s: Camera %s: Preparer thread failed to resume!", __FUNCTION__, mId.string());
2759 return rc;
2760 }
2761
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002762 if (mFakeStreamId == NO_STREAM) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07002763 mRequestBufferSM.onStreamsConfigured();
2764 }
2765
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002766 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002767}
2768
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002769status_t Camera3Device::addFakeStreamLocked() {
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002770 ATRACE_CALL();
2771 status_t res;
2772
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002773 if (mFakeStreamId != NO_STREAM) {
2774 // Should never be adding a second fake stream when one is already
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002775 // active
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002776 SET_ERR_L("%s: Camera %s: A fake stream already exists!",
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002777 __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002778 return INVALID_OPERATION;
2779 }
2780
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002781 ALOGV("%s: Camera %s: Adding a fake stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002782
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002783 sp<Camera3OutputStreamInterface> fakeStream =
2784 new Camera3FakeStream(mNextStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002785
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002786 res = mOutputStreams.add(mNextStreamId, fakeStream);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002787 if (res < 0) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002788 SET_ERR_L("Can't add fake stream to set: %s (%d)", strerror(-res), res);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002789 return res;
2790 }
2791
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002792 mFakeStreamId = mNextStreamId;
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002793 mNextStreamId++;
2794
2795 return OK;
2796}
2797
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002798status_t Camera3Device::tryRemoveFakeStreamLocked() {
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002799 ATRACE_CALL();
2800 status_t res;
2801
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002802 if (mFakeStreamId == NO_STREAM) return OK;
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002803 if (mOutputStreams.size() == 1) return OK;
2804
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002805 ALOGV("%s: Camera %s: Removing the fake stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002806
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002807 // Ok, have a fake stream and there's at least one other output stream,
2808 // so remove the fake
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002809
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002810 sp<Camera3StreamInterface> deletedStream = mOutputStreams.get(mFakeStreamId);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002811 if (deletedStream == nullptr) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002812 SET_ERR_L("Fake stream %d does not appear to exist", mFakeStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002813 return INVALID_OPERATION;
2814 }
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002815 mOutputStreams.remove(mFakeStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002816
2817 // Free up the stream endpoint so that it can be used by some other stream
2818 res = deletedStream->disconnect();
2819 if (res != OK) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002820 SET_ERR_L("Can't disconnect deleted fake stream %d", mFakeStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002821 // fall through since we want to still list the stream as deleted.
2822 }
2823 mDeletedStreams.add(deletedStream);
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002824 mFakeStreamId = NO_STREAM;
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002825
2826 return res;
2827}
2828
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002829void Camera3Device::setErrorState(const char *fmt, ...) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002830 ATRACE_CALL();
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002831 Mutex::Autolock l(mLock);
2832 va_list args;
2833 va_start(args, fmt);
2834
2835 setErrorStateLockedV(fmt, args);
2836
2837 va_end(args);
2838}
2839
2840void Camera3Device::setErrorStateV(const char *fmt, va_list args) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002841 ATRACE_CALL();
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002842 Mutex::Autolock l(mLock);
2843 setErrorStateLockedV(fmt, args);
2844}
2845
2846void Camera3Device::setErrorStateLocked(const char *fmt, ...) {
2847 va_list args;
2848 va_start(args, fmt);
2849
2850 setErrorStateLockedV(fmt, args);
2851
2852 va_end(args);
2853}
2854
2855void Camera3Device::setErrorStateLockedV(const char *fmt, va_list args) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002856 // Print out all error messages to log
2857 String8 errorCause = String8::formatV(fmt, args);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002858 ALOGE("Camera %s: %s", mId.string(), errorCause.string());
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002859
2860 // But only do error state transition steps for the first error
Zhijun Heb05eeae2013-06-06 13:51:22 -07002861 if (mStatus == STATUS_ERROR || mStatus == STATUS_UNINITIALIZED) return;
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002862
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002863 mErrorCause = errorCause;
2864
Yin-Chia Yeh3d145ae2017-07-27 12:47:03 -07002865 if (mRequestThread != nullptr) {
2866 mRequestThread->setPaused(true);
2867 }
Ruben Brunk183f0562015-08-12 12:55:02 -07002868 internalUpdateStatusLocked(STATUS_ERROR);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002869
2870 // Notify upstream about a device error
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002871 sp<NotificationListener> listener = mListener.promote();
2872 if (listener != NULL) {
2873 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002874 CaptureResultExtras());
Shuzhen Wang316781a2020-08-18 18:11:01 -07002875 mSessionStatsBuilder.onDeviceError();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002876 }
2877
2878 // Save stack trace. View by dumping it later.
2879 CameraTraces::saveTrace();
2880 // TODO: consider adding errorCause and client pid/procname
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002881}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002882
2883/**
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002884 * In-flight request management
2885 */
2886
Jianing Weicb0652e2014-03-12 18:29:36 -07002887status_t Camera3Device::registerInFlight(uint32_t frameNumber,
Chien-Yu Chend196d612015-06-22 19:49:01 -07002888 int32_t numBuffers, CaptureResultExtras resultExtras, bool hasInput,
Shuzhen Wang5c22c152017-12-31 17:12:25 -08002889 bool hasAppCallback, nsecs_t maxExpectedDuration,
Shuzhen Wang26abaf42018-08-28 15:41:20 -07002890 std::set<String8>& physicalCameraIds, bool isStillCapture,
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08002891 bool isZslCapture, bool rotateAndCropAuto, const std::set<std::string>& cameraIdsWithZoom,
Shuzhen Wang316781a2020-08-18 18:11:01 -07002892 const SurfaceMap& outputSurfaces, nsecs_t requestTimeNs) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002893 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002894 std::lock_guard<std::mutex> l(mInFlightLock);
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002895
2896 ssize_t res;
Chien-Yu Chend196d612015-06-22 19:49:01 -07002897 res = mInFlightMap.add(frameNumber, InFlightRequest(numBuffers, resultExtras, hasInput,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07002898 hasAppCallback, maxExpectedDuration, physicalCameraIds, isStillCapture, isZslCapture,
Shuzhen Wang316781a2020-08-18 18:11:01 -07002899 rotateAndCropAuto, cameraIdsWithZoom, requestTimeNs, outputSurfaces));
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002900 if (res < 0) return res;
2901
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07002902 if (mInFlightMap.size() == 1) {
Emilian Peev26d975d2018-07-05 14:52:57 +01002903 // Hold a separate dedicated tracker lock to prevent race with disconnect and also
2904 // avoid a deadlock during reprocess requests.
2905 Mutex::Autolock l(mTrackerLock);
Yin-Chia Yeh38dfde52017-06-27 17:13:33 -07002906 if (mStatusTracker != nullptr) {
2907 mStatusTracker->markComponentActive(mInFlightStatusId);
2908 }
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07002909 }
2910
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07002911 mExpectedInflightDuration += maxExpectedDuration;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002912 return OK;
2913}
2914
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002915void Camera3Device::onInflightEntryRemovedLocked(nsecs_t duration) {
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002916 // Indicate idle inFlightMap to the status tracker
2917 if (mInFlightMap.size() == 0) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07002918 mRequestBufferSM.onInflightMapEmpty();
Emilian Peev26d975d2018-07-05 14:52:57 +01002919 // Hold a separate dedicated tracker lock to prevent race with disconnect and also
2920 // avoid a deadlock during reprocess requests.
2921 Mutex::Autolock l(mTrackerLock);
Yin-Chia Yeh38dfde52017-06-27 17:13:33 -07002922 if (mStatusTracker != nullptr) {
2923 mStatusTracker->markComponentIdle(mInFlightStatusId, Fence::NO_FENCE);
2924 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002925 }
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07002926 mExpectedInflightDuration -= duration;
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002927}
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002928
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002929void Camera3Device::checkInflightMapLengthLocked() {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002930 // Validation check - if we have too many in-flight frames with long total inflight duration,
Yin-Chia Yeh99fd0972019-06-27 14:22:44 -07002931 // something has likely gone wrong. This might still be legit only if application send in
2932 // a long burst of long exposure requests.
2933 if (mExpectedInflightDuration > kMinWarnInflightDuration) {
2934 if (!mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() > kInFlightWarnLimit) {
2935 CLOGW("In-flight list too large: %zu, total inflight duration %" PRIu64,
2936 mInFlightMap.size(), mExpectedInflightDuration);
2937 } else if (mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() >
2938 kInFlightWarnLimitHighSpeed) {
2939 CLOGW("In-flight list too large for high speed configuration: %zu,"
2940 "total inflight duration %" PRIu64,
2941 mInFlightMap.size(), mExpectedInflightDuration);
2942 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002943 }
2944}
2945
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002946void Camera3Device::onInflightMapFlushedLocked() {
2947 mExpectedInflightDuration = 0;
2948}
2949
2950void Camera3Device::removeInFlightMapEntryLocked(int idx) {
Jayant Chowdharyd4776262020-06-23 23:45:57 -07002951 ATRACE_HFR_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002952 nsecs_t duration = mInFlightMap.valueAt(idx).maxExpectedDuration;
2953 mInFlightMap.removeItemsAt(idx, 1);
2954
2955 onInflightEntryRemovedLocked(duration);
2956}
2957
2958
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07002959void Camera3Device::flushInflightRequests() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002960 ATRACE_CALL();
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002961 sp<NotificationListener> listener;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002962 {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002963 std::lock_guard<std::mutex> l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002964 listener = mListener.promote();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002965 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002966
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002967 FlushInflightReqStates states {
2968 mId, mInFlightLock, mInFlightMap, mUseHalBufManager,
Shuzhen Wang316781a2020-08-18 18:11:01 -07002969 listener, *this, *mInterface, *this, mSessionStatsBuilder};
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002970
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002971 camera3::flushInflightRequests(states);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002972}
2973
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002974CameraMetadata Camera3Device::getLatestRequestLocked() {
Igor Murashkin1e479c02013-09-06 16:55:14 -07002975 ALOGV("%s", __FUNCTION__);
2976
Igor Murashkin1e479c02013-09-06 16:55:14 -07002977 CameraMetadata retVal;
2978
2979 if (mRequestThread != NULL) {
2980 retVal = mRequestThread->getLatestRequest();
2981 }
2982
Igor Murashkin1e479c02013-09-06 16:55:14 -07002983 return retVal;
2984}
2985
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07002986void Camera3Device::monitorMetadata(TagMonitor::eventSource source,
Shuzhen Wangc2cba122018-05-17 18:10:24 -07002987 int64_t frameNumber, nsecs_t timestamp, const CameraMetadata& metadata,
2988 const std::unordered_map<std::string, CameraMetadata>& physicalMetadata) {
2989
2990 mTagMonitor.monitorMetadata(source, frameNumber, timestamp, metadata,
2991 physicalMetadata);
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07002992}
2993
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002994/**
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002995 * HalInterface inner class methods
2996 */
2997
Yifan Hongf79b5542017-04-11 14:44:25 -07002998Camera3Device::HalInterface::HalInterface(
2999 sp<ICameraDeviceSession> &session,
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003000 std::shared_ptr<RequestMetadataQueue> queue,
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003001 bool useHalBufManager, bool supportOfflineProcessing) :
Yifan Hongf79b5542017-04-11 14:44:25 -07003002 mHidlSession(session),
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003003 mRequestMetadataQueue(queue),
Emilian Peev4ec17882019-01-24 17:16:58 -08003004 mUseHalBufManager(useHalBufManager),
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003005 mIsReconfigurationQuerySupported(true),
3006 mSupportOfflineProcessing(supportOfflineProcessing) {
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003007 // Check with hardware service manager if we can downcast these interfaces
3008 // Somewhat expensive, so cache the results at startup
Shuzhen Wang83bff122020-11-20 15:51:39 -08003009 auto castResult_3_7 = device::V3_7::ICameraDeviceSession::castFrom(mHidlSession);
3010 if (castResult_3_7.isOk()) {
3011 mHidlSession_3_7 = castResult_3_7;
3012 }
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003013 auto castResult_3_6 = device::V3_6::ICameraDeviceSession::castFrom(mHidlSession);
3014 if (castResult_3_6.isOk()) {
3015 mHidlSession_3_6 = castResult_3_6;
3016 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003017 auto castResult_3_5 = device::V3_5::ICameraDeviceSession::castFrom(mHidlSession);
3018 if (castResult_3_5.isOk()) {
3019 mHidlSession_3_5 = castResult_3_5;
3020 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003021 auto castResult_3_4 = device::V3_4::ICameraDeviceSession::castFrom(mHidlSession);
3022 if (castResult_3_4.isOk()) {
3023 mHidlSession_3_4 = castResult_3_4;
3024 }
3025 auto castResult_3_3 = device::V3_3::ICameraDeviceSession::castFrom(mHidlSession);
3026 if (castResult_3_3.isOk()) {
3027 mHidlSession_3_3 = castResult_3_3;
3028 }
3029}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003030
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003031Camera3Device::HalInterface::HalInterface() :
3032 mUseHalBufManager(false),
3033 mSupportOfflineProcessing(false) {}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003034
3035Camera3Device::HalInterface::HalInterface(const HalInterface& other) :
Yifan Hongf79b5542017-04-11 14:44:25 -07003036 mHidlSession(other.mHidlSession),
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003037 mRequestMetadataQueue(other.mRequestMetadataQueue),
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003038 mUseHalBufManager(other.mUseHalBufManager),
3039 mSupportOfflineProcessing(other.mSupportOfflineProcessing) {}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003040
3041bool Camera3Device::HalInterface::valid() {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003042 return (mHidlSession != nullptr);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003043}
3044
3045void Camera3Device::HalInterface::clear() {
Shuzhen Wang83bff122020-11-20 15:51:39 -08003046 mHidlSession_3_7.clear();
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003047 mHidlSession_3_6.clear();
Emilian Peev644a3e12018-11-23 13:52:39 +00003048 mHidlSession_3_5.clear();
Emilian Peev9e740b02018-01-30 18:28:03 +00003049 mHidlSession_3_4.clear();
3050 mHidlSession_3_3.clear();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003051 mHidlSession.clear();
3052}
3053
3054status_t Camera3Device::HalInterface::constructDefaultRequestSettings(
Emilian Peevf4816702020-04-03 15:44:51 -07003055 camera_request_template_t templateId,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003056 /*out*/ camera_metadata_t **requestTemplate) {
3057 ATRACE_NAME("CameraHal::constructDefaultRequestSettings");
3058 if (!valid()) return INVALID_OPERATION;
3059 status_t res = OK;
3060
Emilian Peev31abd0a2017-05-11 18:37:46 +01003061 common::V1_0::Status status;
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003062
3063 auto requestCallback = [&status, &requestTemplate]
Emilian Peev31abd0a2017-05-11 18:37:46 +01003064 (common::V1_0::Status s, const device::V3_2::CameraMetadata& request) {
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003065 status = s;
3066 if (status == common::V1_0::Status::OK) {
3067 const camera_metadata *r =
3068 reinterpret_cast<const camera_metadata_t*>(request.data());
3069 size_t expectedSize = request.size();
3070 int ret = validate_camera_metadata_structure(r, &expectedSize);
3071 if (ret == OK || ret == CAMERA_METADATA_VALIDATION_SHIFTED) {
3072 *requestTemplate = clone_camera_metadata(r);
3073 if (*requestTemplate == nullptr) {
3074 ALOGE("%s: Unable to clone camera metadata received from HAL",
3075 __FUNCTION__);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003076 status = common::V1_0::Status::INTERNAL_ERROR;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003077 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003078 } else {
3079 ALOGE("%s: Malformed camera metadata received from HAL", __FUNCTION__);
3080 status = common::V1_0::Status::INTERNAL_ERROR;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003081 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003082 }
3083 };
3084 hardware::Return<void> err;
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003085 RequestTemplate id;
3086 switch (templateId) {
Emilian Peevf4816702020-04-03 15:44:51 -07003087 case CAMERA_TEMPLATE_PREVIEW:
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003088 id = RequestTemplate::PREVIEW;
3089 break;
Emilian Peevf4816702020-04-03 15:44:51 -07003090 case CAMERA_TEMPLATE_STILL_CAPTURE:
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003091 id = RequestTemplate::STILL_CAPTURE;
3092 break;
Emilian Peevf4816702020-04-03 15:44:51 -07003093 case CAMERA_TEMPLATE_VIDEO_RECORD:
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003094 id = RequestTemplate::VIDEO_RECORD;
3095 break;
Emilian Peevf4816702020-04-03 15:44:51 -07003096 case CAMERA_TEMPLATE_VIDEO_SNAPSHOT:
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003097 id = RequestTemplate::VIDEO_SNAPSHOT;
3098 break;
Emilian Peevf4816702020-04-03 15:44:51 -07003099 case CAMERA_TEMPLATE_ZERO_SHUTTER_LAG:
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003100 id = RequestTemplate::ZERO_SHUTTER_LAG;
3101 break;
Emilian Peevf4816702020-04-03 15:44:51 -07003102 case CAMERA_TEMPLATE_MANUAL:
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003103 id = RequestTemplate::MANUAL;
3104 break;
3105 default:
3106 // Unknown template ID, or this HAL is too old to support it
3107 return BAD_VALUE;
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003108 }
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003109 err = mHidlSession->constructDefaultRequestSettings(id, requestCallback);
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003110
Emilian Peev31abd0a2017-05-11 18:37:46 +01003111 if (!err.isOk()) {
3112 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3113 res = DEAD_OBJECT;
3114 } else {
3115 res = CameraProviderManager::mapToStatusT(status);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003116 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003117
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003118 return res;
3119}
3120
Emilian Peev4ec17882019-01-24 17:16:58 -08003121bool Camera3Device::HalInterface::isReconfigurationRequired(CameraMetadata& oldSessionParams,
3122 CameraMetadata& newSessionParams) {
3123 // We do reconfiguration by default;
3124 bool ret = true;
3125 if ((mHidlSession_3_5 != nullptr) && mIsReconfigurationQuerySupported) {
3126 android::hardware::hidl_vec<uint8_t> oldParams, newParams;
3127 camera_metadata_t* oldSessioMeta = const_cast<camera_metadata_t*>(
3128 oldSessionParams.getAndLock());
3129 camera_metadata_t* newSessioMeta = const_cast<camera_metadata_t*>(
3130 newSessionParams.getAndLock());
3131 oldParams.setToExternal(reinterpret_cast<uint8_t*>(oldSessioMeta),
3132 get_camera_metadata_size(oldSessioMeta));
3133 newParams.setToExternal(reinterpret_cast<uint8_t*>(newSessioMeta),
3134 get_camera_metadata_size(newSessioMeta));
3135 hardware::camera::common::V1_0::Status callStatus;
3136 bool required;
3137 auto hidlCb = [&callStatus, &required] (hardware::camera::common::V1_0::Status s,
3138 bool requiredFlag) {
3139 callStatus = s;
3140 required = requiredFlag;
3141 };
3142 auto err = mHidlSession_3_5->isReconfigurationRequired(oldParams, newParams, hidlCb);
3143 oldSessionParams.unlock(oldSessioMeta);
3144 newSessionParams.unlock(newSessioMeta);
3145 if (err.isOk()) {
3146 switch (callStatus) {
3147 case hardware::camera::common::V1_0::Status::OK:
3148 ret = required;
3149 break;
3150 case hardware::camera::common::V1_0::Status::METHOD_NOT_SUPPORTED:
3151 mIsReconfigurationQuerySupported = false;
3152 ret = true;
3153 break;
3154 default:
3155 ALOGV("%s: Reconfiguration query failed: %d", __FUNCTION__, callStatus);
3156 ret = true;
3157 }
3158 } else {
3159 ALOGE("%s: Unexpected binder error: %s", __FUNCTION__, err.description().c_str());
3160 ret = true;
3161 }
3162 }
3163
3164 return ret;
3165}
3166
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003167status_t Camera3Device::HalInterface::configureStreams(const camera_metadata_t *sessionParams,
Emilian Peevf4816702020-04-03 15:44:51 -07003168 camera_stream_configuration *config, const std::vector<uint32_t>& bufferSizes) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003169 ATRACE_NAME("CameraHal::configureStreams");
3170 if (!valid()) return INVALID_OPERATION;
3171 status_t res = OK;
3172
Shuzhen Wang83bff122020-11-20 15:51:39 -08003173 if (config->input_is_multi_resolution && mHidlSession_3_7 == nullptr) {
3174 ALOGE("%s: Camera device doesn't support multi-resolution input stream", __FUNCTION__);
3175 return BAD_VALUE;
3176 }
3177
Emilian Peev31abd0a2017-05-11 18:37:46 +01003178 // Convert stream config to HIDL
3179 std::set<int> activeStreams;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003180 device::V3_2::StreamConfiguration requestedConfiguration3_2;
3181 device::V3_4::StreamConfiguration requestedConfiguration3_4;
Shuzhen Wang83bff122020-11-20 15:51:39 -08003182 device::V3_7::StreamConfiguration requestedConfiguration3_7;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003183 requestedConfiguration3_2.streams.resize(config->num_streams);
3184 requestedConfiguration3_4.streams.resize(config->num_streams);
Shuzhen Wang83bff122020-11-20 15:51:39 -08003185 requestedConfiguration3_7.streams.resize(config->num_streams);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003186 for (size_t i = 0; i < config->num_streams; i++) {
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003187 device::V3_2::Stream &dst3_2 = requestedConfiguration3_2.streams[i];
3188 device::V3_4::Stream &dst3_4 = requestedConfiguration3_4.streams[i];
Shuzhen Wang83bff122020-11-20 15:51:39 -08003189 device::V3_7::Stream &dst3_7 = requestedConfiguration3_7.streams[i];
Emilian Peevf4816702020-04-03 15:44:51 -07003190 camera3::camera_stream_t *src = config->streams[i];
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003191
Emilian Peev31abd0a2017-05-11 18:37:46 +01003192 Camera3Stream* cam3stream = Camera3Stream::cast(src);
3193 cam3stream->setBufferFreedListener(this);
3194 int streamId = cam3stream->getId();
3195 StreamType streamType;
3196 switch (src->stream_type) {
Emilian Peevf4816702020-04-03 15:44:51 -07003197 case CAMERA_STREAM_OUTPUT:
Emilian Peev31abd0a2017-05-11 18:37:46 +01003198 streamType = StreamType::OUTPUT;
3199 break;
Emilian Peevf4816702020-04-03 15:44:51 -07003200 case CAMERA_STREAM_INPUT:
Emilian Peev31abd0a2017-05-11 18:37:46 +01003201 streamType = StreamType::INPUT;
3202 break;
3203 default:
3204 ALOGE("%s: Stream %d: Unsupported stream type %d",
3205 __FUNCTION__, streamId, config->streams[i]->stream_type);
3206 return BAD_VALUE;
3207 }
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003208 dst3_2.id = streamId;
3209 dst3_2.streamType = streamType;
3210 dst3_2.width = src->width;
3211 dst3_2.height = src->height;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003212 dst3_2.usage = mapToConsumerUsage(cam3stream->getUsage());
Emilian Peevf4816702020-04-03 15:44:51 -07003213 dst3_2.rotation = mapToStreamRotation((camera_stream_rotation_t) src->rotation);
Shuzhen Wang92653952019-05-07 15:11:43 -07003214 // For HidlSession version 3.5 or newer, the format and dataSpace sent
3215 // to HAL are original, not the overriden ones.
3216 if (mHidlSession_3_5 != nullptr) {
3217 dst3_2.format = mapToPixelFormat(cam3stream->isFormatOverridden() ?
3218 cam3stream->getOriginalFormat() : src->format);
3219 dst3_2.dataSpace = mapToHidlDataspace(cam3stream->isDataSpaceOverridden() ?
3220 cam3stream->getOriginalDataSpace() : src->data_space);
3221 } else {
3222 dst3_2.format = mapToPixelFormat(src->format);
3223 dst3_2.dataSpace = mapToHidlDataspace(src->data_space);
3224 }
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003225 dst3_4.v3_2 = dst3_2;
Emilian Peev192ee832018-01-31 14:46:47 +00003226 dst3_4.bufferSize = bufferSizes[i];
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003227 if (src->physical_camera_id != nullptr) {
3228 dst3_4.physicalCameraId = src->physical_camera_id;
3229 }
Shuzhen Wang83bff122020-11-20 15:51:39 -08003230 dst3_7.v3_4 = dst3_4;
3231 dst3_7.groupId = cam3stream->getHalStreamGroupId();
Emilian Peev31abd0a2017-05-11 18:37:46 +01003232
3233 activeStreams.insert(streamId);
3234 // Create Buffer ID map if necessary
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003235 mBufferRecords.tryCreateBufferCache(streamId);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003236 }
3237 // remove BufferIdMap for deleted streams
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003238 mBufferRecords.removeInactiveBufferCaches(activeStreams);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003239
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003240 StreamConfigurationMode operationMode;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003241 res = mapToStreamConfigurationMode(
Emilian Peevf4816702020-04-03 15:44:51 -07003242 (camera_stream_configuration_mode_t) config->operation_mode,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003243 /*out*/ &operationMode);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003244 if (res != OK) {
3245 return res;
3246 }
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003247 requestedConfiguration3_2.operationMode = operationMode;
3248 requestedConfiguration3_4.operationMode = operationMode;
3249 requestedConfiguration3_4.sessionParams.setToExternal(
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003250 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(sessionParams)),
3251 get_camera_metadata_size(sessionParams));
Shuzhen Wang83bff122020-11-20 15:51:39 -08003252 requestedConfiguration3_7.operationMode = operationMode;
3253 requestedConfiguration3_7.sessionParams.setToExternal(
3254 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(sessionParams)),
3255 get_camera_metadata_size(sessionParams));
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003256
Emilian Peev31abd0a2017-05-11 18:37:46 +01003257 // Invoke configureStreams
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003258 device::V3_3::HalStreamConfiguration finalConfiguration;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003259 device::V3_4::HalStreamConfiguration finalConfiguration3_4;
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003260 device::V3_6::HalStreamConfiguration finalConfiguration3_6;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003261 common::V1_0::Status status;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003262
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003263 auto configStream34Cb = [&status, &finalConfiguration3_4]
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003264 (common::V1_0::Status s, const device::V3_4::HalStreamConfiguration& halConfiguration) {
3265 finalConfiguration3_4 = halConfiguration;
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003266 status = s;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003267 };
3268
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003269 auto configStream36Cb = [&status, &finalConfiguration3_6]
3270 (common::V1_0::Status s, const device::V3_6::HalStreamConfiguration& halConfiguration) {
3271 finalConfiguration3_6 = halConfiguration;
3272 status = s;
3273 };
3274
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003275 auto postprocConfigStream34 = [&finalConfiguration, &finalConfiguration3_4]
3276 (hardware::Return<void>& err) -> status_t {
3277 if (!err.isOk()) {
3278 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3279 return DEAD_OBJECT;
3280 }
3281 finalConfiguration.streams.resize(finalConfiguration3_4.streams.size());
3282 for (size_t i = 0; i < finalConfiguration3_4.streams.size(); i++) {
3283 finalConfiguration.streams[i] = finalConfiguration3_4.streams[i].v3_3;
3284 }
3285 return OK;
3286 };
3287
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003288 auto postprocConfigStream36 = [&finalConfiguration, &finalConfiguration3_6]
3289 (hardware::Return<void>& err) -> status_t {
3290 if (!err.isOk()) {
3291 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3292 return DEAD_OBJECT;
3293 }
3294 finalConfiguration.streams.resize(finalConfiguration3_6.streams.size());
3295 for (size_t i = 0; i < finalConfiguration3_6.streams.size(); i++) {
3296 finalConfiguration.streams[i] = finalConfiguration3_6.streams[i].v3_4.v3_3;
3297 }
3298 return OK;
3299 };
3300
Shuzhen Wang92653952019-05-07 15:11:43 -07003301 // See which version of HAL we have
Shuzhen Wang83bff122020-11-20 15:51:39 -08003302 if (mHidlSession_3_7 != nullptr) {
3303 ALOGV("%s: v3.7 device found", __FUNCTION__);
3304 requestedConfiguration3_7.streamConfigCounter = mNextStreamConfigCounter++;
3305 requestedConfiguration3_7.multiResolutionInputImage = config->input_is_multi_resolution;
3306 auto err = mHidlSession_3_7->configureStreams_3_7(
3307 requestedConfiguration3_7, configStream36Cb);
3308 res = postprocConfigStream36(err);
3309 if (res != OK) {
3310 return res;
3311 }
3312 } else if (mHidlSession_3_6 != nullptr) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003313 ALOGV("%s: v3.6 device found", __FUNCTION__);
3314 device::V3_5::StreamConfiguration requestedConfiguration3_5;
3315 requestedConfiguration3_5.v3_4 = requestedConfiguration3_4;
3316 requestedConfiguration3_5.streamConfigCounter = mNextStreamConfigCounter++;
3317 auto err = mHidlSession_3_6->configureStreams_3_6(
3318 requestedConfiguration3_5, configStream36Cb);
3319 res = postprocConfigStream36(err);
3320 if (res != OK) {
3321 return res;
3322 }
3323 } else if (mHidlSession_3_5 != nullptr) {
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003324 ALOGV("%s: v3.5 device found", __FUNCTION__);
3325 device::V3_5::StreamConfiguration requestedConfiguration3_5;
3326 requestedConfiguration3_5.v3_4 = requestedConfiguration3_4;
3327 requestedConfiguration3_5.streamConfigCounter = mNextStreamConfigCounter++;
3328 auto err = mHidlSession_3_5->configureStreams_3_5(
3329 requestedConfiguration3_5, configStream34Cb);
3330 res = postprocConfigStream34(err);
3331 if (res != OK) {
3332 return res;
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003333 }
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003334 } else if (mHidlSession_3_4 != nullptr) {
3335 // We do; use v3.4 for the call
3336 ALOGV("%s: v3.4 device found", __FUNCTION__);
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003337 auto err = mHidlSession_3_4->configureStreams_3_4(
3338 requestedConfiguration3_4, configStream34Cb);
3339 res = postprocConfigStream34(err);
3340 if (res != OK) {
3341 return res;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003342 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003343 } else if (mHidlSession_3_3 != nullptr) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003344 // We do; use v3.3 for the call
3345 ALOGV("%s: v3.3 device found", __FUNCTION__);
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003346 auto err = mHidlSession_3_3->configureStreams_3_3(requestedConfiguration3_2,
Emilian Peev31abd0a2017-05-11 18:37:46 +01003347 [&status, &finalConfiguration]
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003348 (common::V1_0::Status s, const device::V3_3::HalStreamConfiguration& halConfiguration) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003349 finalConfiguration = halConfiguration;
3350 status = s;
3351 });
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003352 if (!err.isOk()) {
3353 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3354 return DEAD_OBJECT;
3355 }
3356 } else {
3357 // We don't; use v3.2 call and construct a v3.3 HalStreamConfiguration
3358 ALOGV("%s: v3.2 device found", __FUNCTION__);
3359 HalStreamConfiguration finalConfiguration_3_2;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003360 auto err = mHidlSession->configureStreams(requestedConfiguration3_2,
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003361 [&status, &finalConfiguration_3_2]
3362 (common::V1_0::Status s, const HalStreamConfiguration& halConfiguration) {
3363 finalConfiguration_3_2 = halConfiguration;
3364 status = s;
3365 });
3366 if (!err.isOk()) {
3367 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3368 return DEAD_OBJECT;
3369 }
3370 finalConfiguration.streams.resize(finalConfiguration_3_2.streams.size());
3371 for (size_t i = 0; i < finalConfiguration_3_2.streams.size(); i++) {
3372 finalConfiguration.streams[i].v3_2 = finalConfiguration_3_2.streams[i];
3373 finalConfiguration.streams[i].overrideDataSpace =
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003374 requestedConfiguration3_2.streams[i].dataSpace;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003375 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003376 }
3377
3378 if (status != common::V1_0::Status::OK ) {
3379 return CameraProviderManager::mapToStatusT(status);
3380 }
3381
3382 // And convert output stream configuration from HIDL
3383
3384 for (size_t i = 0; i < config->num_streams; i++) {
Emilian Peevf4816702020-04-03 15:44:51 -07003385 camera3::camera_stream_t *dst = config->streams[i];
Emilian Peev31abd0a2017-05-11 18:37:46 +01003386 int streamId = Camera3Stream::cast(dst)->getId();
3387
3388 // Start scan at i, with the assumption that the stream order matches
3389 size_t realIdx = i;
3390 bool found = false;
Eino-Ville Talvala370875f2019-04-12 12:40:27 -07003391 size_t halStreamCount = finalConfiguration.streams.size();
3392 for (size_t idx = 0; idx < halStreamCount; idx++) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003393 if (finalConfiguration.streams[realIdx].v3_2.id == streamId) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003394 found = true;
3395 break;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003396 }
Eino-Ville Talvala370875f2019-04-12 12:40:27 -07003397 realIdx = (realIdx >= halStreamCount - 1) ? 0 : realIdx + 1;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003398 }
3399 if (!found) {
3400 ALOGE("%s: Stream %d not found in stream configuration response from HAL",
3401 __FUNCTION__, streamId);
3402 return INVALID_OPERATION;
3403 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003404 device::V3_3::HalStream &src = finalConfiguration.streams[realIdx];
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003405 device::V3_6::HalStream &src_36 = finalConfiguration3_6.streams[realIdx];
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003406
Emilian Peev710c1422017-08-30 11:19:38 +01003407 Camera3Stream* dstStream = Camera3Stream::cast(dst);
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003408 int overrideFormat = mapToFrameworkFormat(src.v3_2.overrideFormat);
3409 android_dataspace overrideDataSpace = mapToFrameworkDataspace(src.overrideDataSpace);
3410
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003411 if (mHidlSession_3_6 != nullptr) {
3412 dstStream->setOfflineProcessingSupport(src_36.supportOffline);
3413 }
3414
Yin-Chia Yeh90667662019-07-01 15:45:00 -07003415 if (dstStream->getOriginalFormat() != HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
Shuzhen Wang92653952019-05-07 15:11:43 -07003416 dstStream->setFormatOverride(false);
3417 dstStream->setDataSpaceOverride(false);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003418 if (dst->format != overrideFormat) {
3419 ALOGE("%s: Stream %d: Format override not allowed for format 0x%x", __FUNCTION__,
3420 streamId, dst->format);
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003421 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003422 if (dst->data_space != overrideDataSpace) {
3423 ALOGE("%s: Stream %d: DataSpace override not allowed for format 0x%x", __FUNCTION__,
3424 streamId, dst->format);
3425 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003426 } else {
Shuzhen Wang92653952019-05-07 15:11:43 -07003427 bool needFormatOverride =
3428 requestedConfiguration3_2.streams[i].format != src.v3_2.overrideFormat;
3429 bool needDataspaceOverride =
3430 requestedConfiguration3_2.streams[i].dataSpace != src.overrideDataSpace;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003431 // Override allowed with IMPLEMENTATION_DEFINED
Shuzhen Wang92653952019-05-07 15:11:43 -07003432 dstStream->setFormatOverride(needFormatOverride);
3433 dstStream->setDataSpaceOverride(needDataspaceOverride);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003434 dst->format = overrideFormat;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003435 dst->data_space = overrideDataSpace;
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003436 }
3437
Emilian Peevf4816702020-04-03 15:44:51 -07003438 if (dst->stream_type == CAMERA_STREAM_INPUT) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003439 if (src.v3_2.producerUsage != 0) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003440 ALOGE("%s: Stream %d: INPUT streams must have 0 for producer usage",
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003441 __FUNCTION__, streamId);
3442 return INVALID_OPERATION;
3443 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003444 dstStream->setUsage(
3445 mapConsumerToFrameworkUsage(src.v3_2.consumerUsage));
Emilian Peev31abd0a2017-05-11 18:37:46 +01003446 } else {
3447 // OUTPUT
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003448 if (src.v3_2.consumerUsage != 0) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003449 ALOGE("%s: Stream %d: OUTPUT streams must have 0 for consumer usage",
3450 __FUNCTION__, streamId);
3451 return INVALID_OPERATION;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003452 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003453 dstStream->setUsage(
3454 mapProducerToFrameworkUsage(src.v3_2.producerUsage));
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003455 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003456 dst->max_buffers = src.v3_2.maxBuffers;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003457 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003458
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003459 return res;
3460}
3461
Emilian Peevf4816702020-04-03 15:44:51 -07003462status_t Camera3Device::HalInterface::wrapAsHidlRequest(camera_capture_request_t* request,
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003463 /*out*/device::V3_2::CaptureRequest* captureRequest,
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003464 /*out*/std::vector<native_handle_t*>* handlesCreated,
3465 /*out*/std::vector<std::pair<int32_t, int32_t>>* inflightBuffers) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003466 ATRACE_CALL();
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003467 if (captureRequest == nullptr || handlesCreated == nullptr || inflightBuffers == nullptr) {
3468 ALOGE("%s: captureRequest (%p), handlesCreated (%p), and inflightBuffers(%p) "
3469 "must not be null", __FUNCTION__, captureRequest, handlesCreated, inflightBuffers);
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003470 return BAD_VALUE;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003471 }
3472
3473 captureRequest->frameNumber = request->frame_number;
Yifan Hongf79b5542017-04-11 14:44:25 -07003474
3475 captureRequest->fmqSettingsSize = 0;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003476
3477 {
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003478 if (request->input_buffer != nullptr) {
3479 int32_t streamId = Camera3Stream::cast(request->input_buffer->stream)->getId();
3480 buffer_handle_t buf = *(request->input_buffer->buffer);
3481 auto pair = getBufferId(buf, streamId);
3482 bool isNewBuffer = pair.first;
3483 uint64_t bufferId = pair.second;
3484 captureRequest->inputBuffer.streamId = streamId;
3485 captureRequest->inputBuffer.bufferId = bufferId;
3486 captureRequest->inputBuffer.buffer = (isNewBuffer) ? buf : nullptr;
3487 captureRequest->inputBuffer.status = BufferStatus::OK;
3488 native_handle_t *acquireFence = nullptr;
3489 if (request->input_buffer->acquire_fence != -1) {
3490 acquireFence = native_handle_create(1,0);
3491 acquireFence->data[0] = request->input_buffer->acquire_fence;
3492 handlesCreated->push_back(acquireFence);
3493 }
3494 captureRequest->inputBuffer.acquireFence = acquireFence;
3495 captureRequest->inputBuffer.releaseFence = nullptr;
3496
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003497 mBufferRecords.pushInflightBuffer(captureRequest->frameNumber, streamId,
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003498 request->input_buffer->buffer);
3499 inflightBuffers->push_back(std::make_pair(captureRequest->frameNumber, streamId));
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003500 } else {
3501 captureRequest->inputBuffer.streamId = -1;
3502 captureRequest->inputBuffer.bufferId = BUFFER_ID_NO_BUFFER;
3503 }
3504
3505 captureRequest->outputBuffers.resize(request->num_output_buffers);
3506 for (size_t i = 0; i < request->num_output_buffers; i++) {
Emilian Peevf4816702020-04-03 15:44:51 -07003507 const camera_stream_buffer_t *src = request->output_buffers + i;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003508 StreamBuffer &dst = captureRequest->outputBuffers[i];
3509 int32_t streamId = Camera3Stream::cast(src->stream)->getId();
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003510 if (src->buffer != nullptr) {
3511 buffer_handle_t buf = *(src->buffer);
3512 auto pair = getBufferId(buf, streamId);
3513 bool isNewBuffer = pair.first;
3514 dst.bufferId = pair.second;
3515 dst.buffer = isNewBuffer ? buf : nullptr;
3516 native_handle_t *acquireFence = nullptr;
3517 if (src->acquire_fence != -1) {
3518 acquireFence = native_handle_create(1,0);
3519 acquireFence->data[0] = src->acquire_fence;
3520 handlesCreated->push_back(acquireFence);
3521 }
3522 dst.acquireFence = acquireFence;
3523 } else if (mUseHalBufManager) {
3524 // HAL buffer management path
3525 dst.bufferId = BUFFER_ID_NO_BUFFER;
3526 dst.buffer = nullptr;
3527 dst.acquireFence = nullptr;
3528 } else {
3529 ALOGE("%s: cannot send a null buffer in capture request!", __FUNCTION__);
3530 return BAD_VALUE;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003531 }
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003532 dst.streamId = streamId;
3533 dst.status = BufferStatus::OK;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003534 dst.releaseFence = nullptr;
3535
Yin-Chia Yeh5f840f82019-03-05 11:59:04 -08003536 // Output buffers are empty when using HAL buffer manager
3537 if (!mUseHalBufManager) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003538 mBufferRecords.pushInflightBuffer(
3539 captureRequest->frameNumber, streamId, src->buffer);
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003540 inflightBuffers->push_back(std::make_pair(captureRequest->frameNumber, streamId));
Yin-Chia Yeh5f840f82019-03-05 11:59:04 -08003541 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003542 }
3543 }
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003544 return OK;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003545}
3546
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003547void Camera3Device::HalInterface::cleanupNativeHandles(
3548 std::vector<native_handle_t*> *handles, bool closeFd) {
3549 if (handles == nullptr) {
3550 return;
3551 }
3552 if (closeFd) {
3553 for (auto& handle : *handles) {
3554 native_handle_close(handle);
3555 }
3556 }
3557 for (auto& handle : *handles) {
3558 native_handle_delete(handle);
3559 }
3560 handles->clear();
3561 return;
3562}
3563
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003564status_t Camera3Device::HalInterface::processBatchCaptureRequests(
Emilian Peevf4816702020-04-03 15:44:51 -07003565 std::vector<camera_capture_request_t*>& requests,/*out*/uint32_t* numRequestProcessed) {
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003566 ATRACE_NAME("CameraHal::processBatchCaptureRequests");
3567 if (!valid()) return INVALID_OPERATION;
3568
Emilian Peevaebbe412018-01-15 13:53:24 +00003569 sp<device::V3_4::ICameraDeviceSession> hidlSession_3_4;
Shuzhen Wang83bff122020-11-20 15:51:39 -08003570 sp<device::V3_7::ICameraDeviceSession> hidlSession_3_7;
3571 auto castResult_3_7 = device::V3_7::ICameraDeviceSession::castFrom(mHidlSession);
3572 if (castResult_3_7.isOk()) {
3573 hidlSession_3_7 = castResult_3_7;
3574 }
Emilian Peevaebbe412018-01-15 13:53:24 +00003575 auto castResult_3_4 = device::V3_4::ICameraDeviceSession::castFrom(mHidlSession);
3576 if (castResult_3_4.isOk()) {
3577 hidlSession_3_4 = castResult_3_4;
3578 }
3579
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003580 hardware::hidl_vec<device::V3_2::CaptureRequest> captureRequests;
Emilian Peevaebbe412018-01-15 13:53:24 +00003581 hardware::hidl_vec<device::V3_4::CaptureRequest> captureRequests_3_4;
Shuzhen Wang83bff122020-11-20 15:51:39 -08003582 hardware::hidl_vec<device::V3_7::CaptureRequest> captureRequests_3_7;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003583 size_t batchSize = requests.size();
Shuzhen Wang83bff122020-11-20 15:51:39 -08003584 if (hidlSession_3_7 != nullptr) {
3585 captureRequests_3_7.resize(batchSize);
3586 } else if (hidlSession_3_4 != nullptr) {
Emilian Peevaebbe412018-01-15 13:53:24 +00003587 captureRequests_3_4.resize(batchSize);
3588 } else {
3589 captureRequests.resize(batchSize);
3590 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003591 std::vector<native_handle_t*> handlesCreated;
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003592 std::vector<std::pair<int32_t, int32_t>> inflightBuffers;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003593
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003594 status_t res = OK;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003595 for (size_t i = 0; i < batchSize; i++) {
Shuzhen Wang83bff122020-11-20 15:51:39 -08003596 if (hidlSession_3_7 != nullptr) {
3597 res = wrapAsHidlRequest(requests[i], /*out*/&captureRequests_3_7[i].v3_4.v3_2,
3598 /*out*/&handlesCreated, /*out*/&inflightBuffers);
3599 } else if (hidlSession_3_4 != nullptr) {
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003600 res = wrapAsHidlRequest(requests[i], /*out*/&captureRequests_3_4[i].v3_2,
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003601 /*out*/&handlesCreated, /*out*/&inflightBuffers);
Emilian Peevaebbe412018-01-15 13:53:24 +00003602 } else {
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003603 res = wrapAsHidlRequest(requests[i], /*out*/&captureRequests[i],
3604 /*out*/&handlesCreated, /*out*/&inflightBuffers);
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003605 }
3606 if (res != OK) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003607 mBufferRecords.popInflightBuffers(inflightBuffers);
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003608 cleanupNativeHandles(&handlesCreated);
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003609 return res;
Emilian Peevaebbe412018-01-15 13:53:24 +00003610 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003611 }
3612
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003613 std::vector<device::V3_2::BufferCache> cachesToRemove;
3614 {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003615 std::lock_guard<std::mutex> lock(mFreedBuffersLock);
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003616 for (auto& pair : mFreedBuffers) {
3617 // The stream might have been removed since onBufferFreed
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003618 if (mBufferRecords.isStreamCached(pair.first)) {
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003619 cachesToRemove.push_back({pair.first, pair.second});
3620 }
3621 }
3622 mFreedBuffers.clear();
3623 }
3624
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003625 common::V1_0::Status status = common::V1_0::Status::INTERNAL_ERROR;
3626 *numRequestProcessed = 0;
Yifan Hongf79b5542017-04-11 14:44:25 -07003627
3628 // Write metadata to FMQ.
3629 for (size_t i = 0; i < batchSize; i++) {
Emilian Peevf4816702020-04-03 15:44:51 -07003630 camera_capture_request_t* request = requests[i];
Emilian Peevaebbe412018-01-15 13:53:24 +00003631 device::V3_2::CaptureRequest* captureRequest;
Shuzhen Wang83bff122020-11-20 15:51:39 -08003632 if (hidlSession_3_7 != nullptr) {
3633 captureRequest = &captureRequests_3_7[i].v3_4.v3_2;
3634 } else if (hidlSession_3_4 != nullptr) {
Emilian Peevaebbe412018-01-15 13:53:24 +00003635 captureRequest = &captureRequests_3_4[i].v3_2;
3636 } else {
3637 captureRequest = &captureRequests[i];
3638 }
Yifan Hongf79b5542017-04-11 14:44:25 -07003639
3640 if (request->settings != nullptr) {
3641 size_t settingsSize = get_camera_metadata_size(request->settings);
3642 if (mRequestMetadataQueue != nullptr && mRequestMetadataQueue->write(
3643 reinterpret_cast<const uint8_t*>(request->settings), settingsSize)) {
3644 captureRequest->settings.resize(0);
3645 captureRequest->fmqSettingsSize = settingsSize;
3646 } else {
3647 if (mRequestMetadataQueue != nullptr) {
3648 ALOGW("%s: couldn't utilize fmq, fallback to hwbinder", __FUNCTION__);
3649 }
3650 captureRequest->settings.setToExternal(
3651 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(request->settings)),
3652 get_camera_metadata_size(request->settings));
3653 captureRequest->fmqSettingsSize = 0u;
3654 }
3655 } else {
3656 // A null request settings maps to a size-0 CameraMetadata
3657 captureRequest->settings.resize(0);
3658 captureRequest->fmqSettingsSize = 0u;
3659 }
Emilian Peevaebbe412018-01-15 13:53:24 +00003660
Shuzhen Wang83bff122020-11-20 15:51:39 -08003661 // hidl session 3.7 specific handling.
3662 if (hidlSession_3_7 != nullptr) {
3663 captureRequests_3_7[i].inputWidth = request->input_width;
3664 captureRequests_3_7[i].inputHeight = request->input_height;
3665 }
3666
3667 // hidl session 3.7 and 3.4 specific handling.
3668 if (hidlSession_3_7 != nullptr || hidlSession_3_4 != nullptr) {
3669 hardware::hidl_vec<device::V3_4::PhysicalCameraSetting>& physicalCameraSettings =
3670 (hidlSession_3_7 != nullptr) ?
3671 captureRequests_3_7[i].v3_4.physicalCameraSettings :
3672 captureRequests_3_4[i].physicalCameraSettings;
3673 physicalCameraSettings.resize(request->num_physcam_settings);
Emilian Peevaebbe412018-01-15 13:53:24 +00003674 for (size_t j = 0; j < request->num_physcam_settings; j++) {
Emilian Peev00420d22018-02-05 21:33:13 +00003675 if (request->physcam_settings != nullptr) {
3676 size_t settingsSize = get_camera_metadata_size(request->physcam_settings[j]);
3677 if (mRequestMetadataQueue != nullptr && mRequestMetadataQueue->write(
3678 reinterpret_cast<const uint8_t*>(request->physcam_settings[j]),
3679 settingsSize)) {
Shuzhen Wang83bff122020-11-20 15:51:39 -08003680 physicalCameraSettings[j].settings.resize(0);
3681 physicalCameraSettings[j].fmqSettingsSize = settingsSize;
Emilian Peev00420d22018-02-05 21:33:13 +00003682 } else {
3683 if (mRequestMetadataQueue != nullptr) {
3684 ALOGW("%s: couldn't utilize fmq, fallback to hwbinder", __FUNCTION__);
3685 }
Shuzhen Wang83bff122020-11-20 15:51:39 -08003686 physicalCameraSettings[j].settings.setToExternal(
Emilian Peev00420d22018-02-05 21:33:13 +00003687 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(
3688 request->physcam_settings[j])),
3689 get_camera_metadata_size(request->physcam_settings[j]));
Shuzhen Wang83bff122020-11-20 15:51:39 -08003690 physicalCameraSettings[j].fmqSettingsSize = 0u;
Emilian Peevaebbe412018-01-15 13:53:24 +00003691 }
Emilian Peev00420d22018-02-05 21:33:13 +00003692 } else {
Emilian Peevaebbe412018-01-15 13:53:24 +00003693 captureRequests_3_4[i].physicalCameraSettings[j].fmqSettingsSize = 0u;
Emilian Peev00420d22018-02-05 21:33:13 +00003694 captureRequests_3_4[i].physicalCameraSettings[j].settings.resize(0);
Emilian Peevaebbe412018-01-15 13:53:24 +00003695 }
Shuzhen Wang83bff122020-11-20 15:51:39 -08003696 physicalCameraSettings[j].physicalCameraId = request->physcam_id[j];
Emilian Peevaebbe412018-01-15 13:53:24 +00003697 }
3698 }
Yifan Hongf79b5542017-04-11 14:44:25 -07003699 }
Emilian Peevaebbe412018-01-15 13:53:24 +00003700
3701 hardware::details::return_status err;
Jayant Chowdharyc8d581e2018-07-16 14:46:23 -07003702 auto resultCallback =
3703 [&status, &numRequestProcessed] (auto s, uint32_t n) {
3704 status = s;
3705 *numRequestProcessed = n;
3706 };
Shuzhen Wang83bff122020-11-20 15:51:39 -08003707 if (hidlSession_3_7 != nullptr) {
3708 err = hidlSession_3_7->processCaptureRequest_3_7(captureRequests_3_7, cachesToRemove,
3709 resultCallback);
3710 } else if (hidlSession_3_4 != nullptr) {
Emilian Peevaebbe412018-01-15 13:53:24 +00003711 err = hidlSession_3_4->processCaptureRequest_3_4(captureRequests_3_4, cachesToRemove,
Jayant Chowdharyc8d581e2018-07-16 14:46:23 -07003712 resultCallback);
Emilian Peevaebbe412018-01-15 13:53:24 +00003713 } else {
3714 err = mHidlSession->processCaptureRequest(captureRequests, cachesToRemove,
Jayant Chowdharyc8d581e2018-07-16 14:46:23 -07003715 resultCallback);
Emilian Peevaebbe412018-01-15 13:53:24 +00003716 }
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -07003717 if (!err.isOk()) {
3718 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003719 status = common::V1_0::Status::CAMERA_DISCONNECTED;
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -07003720 }
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003721
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003722 if (status == common::V1_0::Status::OK && *numRequestProcessed != batchSize) {
3723 ALOGE("%s: processCaptureRequest returns OK but processed %d/%zu requests",
3724 __FUNCTION__, *numRequestProcessed, batchSize);
3725 status = common::V1_0::Status::INTERNAL_ERROR;
3726 }
3727
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003728 res = CameraProviderManager::mapToStatusT(status);
3729 if (res == OK) {
3730 if (mHidlSession->isRemote()) {
3731 // Only close acquire fence FDs when the HIDL transaction succeeds (so the FDs have been
3732 // sent to camera HAL processes)
3733 cleanupNativeHandles(&handlesCreated, /*closeFd*/true);
3734 } else {
3735 // In passthrough mode the FDs are now owned by HAL
3736 cleanupNativeHandles(&handlesCreated);
3737 }
3738 } else {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003739 mBufferRecords.popInflightBuffers(inflightBuffers);
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003740 cleanupNativeHandles(&handlesCreated);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003741 }
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003742 return res;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003743}
3744
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003745status_t Camera3Device::HalInterface::flush() {
3746 ATRACE_NAME("CameraHal::flush");
3747 if (!valid()) return INVALID_OPERATION;
3748 status_t res = OK;
3749
Emilian Peev31abd0a2017-05-11 18:37:46 +01003750 auto err = mHidlSession->flush();
3751 if (!err.isOk()) {
3752 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3753 res = DEAD_OBJECT;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003754 } else {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003755 res = CameraProviderManager::mapToStatusT(err);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003756 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003757
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003758 return res;
3759}
3760
Emilian Peev31abd0a2017-05-11 18:37:46 +01003761status_t Camera3Device::HalInterface::dump(int /*fd*/) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003762 ATRACE_NAME("CameraHal::dump");
3763 if (!valid()) return INVALID_OPERATION;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003764
Emilian Peev31abd0a2017-05-11 18:37:46 +01003765 // Handled by CameraProviderManager::dump
3766
3767 return OK;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003768}
3769
3770status_t Camera3Device::HalInterface::close() {
3771 ATRACE_NAME("CameraHal::close()");
3772 if (!valid()) return INVALID_OPERATION;
3773 status_t res = OK;
3774
Emilian Peev31abd0a2017-05-11 18:37:46 +01003775 auto err = mHidlSession->close();
3776 // Interface will be dead shortly anyway, so don't log errors
3777 if (!err.isOk()) {
3778 res = DEAD_OBJECT;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003779 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003780
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003781 return res;
3782}
3783
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003784void Camera3Device::HalInterface::signalPipelineDrain(const std::vector<int>& streamIds) {
3785 ATRACE_NAME("CameraHal::signalPipelineDrain");
3786 if (!valid() || mHidlSession_3_5 == nullptr) {
3787 ALOGE("%s called on invalid camera!", __FUNCTION__);
3788 return;
3789 }
3790
Yin-Chia Yehc300a072019-02-13 14:56:57 -08003791 auto err = mHidlSession_3_5->signalStreamFlush(streamIds, mNextStreamConfigCounter - 1);
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003792 if (!err.isOk()) {
3793 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3794 return;
3795 }
3796}
3797
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003798status_t Camera3Device::HalInterface::switchToOffline(
3799 const std::vector<int32_t>& streamsToKeep,
3800 /*out*/hardware::camera::device::V3_6::CameraOfflineSessionInfo* offlineSessionInfo,
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003801 /*out*/sp<hardware::camera::device::V3_6::ICameraOfflineSession>* offlineSession,
3802 /*out*/camera3::BufferRecords* bufferRecords) {
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003803 ATRACE_NAME("CameraHal::switchToOffline");
3804 if (!valid() || mHidlSession_3_6 == nullptr) {
3805 ALOGE("%s called on invalid camera!", __FUNCTION__);
3806 return INVALID_OPERATION;
3807 }
3808
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003809 if (offlineSessionInfo == nullptr || offlineSession == nullptr || bufferRecords == nullptr) {
3810 ALOGE("%s: output arguments must not be null!", __FUNCTION__);
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003811 return INVALID_OPERATION;
3812 }
3813
3814 common::V1_0::Status status = common::V1_0::Status::INTERNAL_ERROR;
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003815 auto resultCallback =
3816 [&status, &offlineSessionInfo, &offlineSession] (auto s, auto info, auto session) {
3817 status = s;
3818 *offlineSessionInfo = info;
3819 *offlineSession = session;
3820 };
3821 auto err = mHidlSession_3_6->switchToOffline(streamsToKeep, resultCallback);
3822
3823 if (!err.isOk()) {
3824 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3825 return DEAD_OBJECT;
3826 }
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003827
3828 status_t ret = CameraProviderManager::mapToStatusT(status);
3829 if (ret != OK) {
3830 return ret;
3831 }
3832
3833 // TODO: assert no ongoing requestBuffer/returnBuffer call here
3834 // TODO: update RequestBufferStateMachine to block requestBuffer/returnBuffer once HAL
3835 // returns from switchToOffline.
3836
3837
3838 // Validate buffer caches
3839 std::vector<int32_t> streams;
3840 streams.reserve(offlineSessionInfo->offlineStreams.size());
3841 for (auto offlineStream : offlineSessionInfo->offlineStreams) {
3842 int32_t id = offlineStream.id;
3843 streams.push_back(id);
3844 // Verify buffer caches
3845 std::vector<uint64_t> bufIds(offlineStream.circulatingBufferIds.begin(),
3846 offlineStream.circulatingBufferIds.end());
3847 if (!verifyBufferIds(id, bufIds)) {
3848 ALOGE("%s: stream ID %d buffer cache records mismatch!", __FUNCTION__, id);
3849 return UNKNOWN_ERROR;
3850 }
3851 }
3852
3853 // Move buffer records
3854 bufferRecords->takeBufferCaches(mBufferRecords, streams);
3855 bufferRecords->takeInflightBufferMap(mBufferRecords);
3856 bufferRecords->takeRequestedBufferMap(mBufferRecords);
3857 return ret;
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003858}
3859
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003860void Camera3Device::HalInterface::getInflightBufferKeys(
3861 std::vector<std::pair<int32_t, int32_t>>* out) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003862 mBufferRecords.getInflightBufferKeys(out);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003863 return;
3864}
3865
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08003866void Camera3Device::HalInterface::getInflightRequestBufferKeys(
3867 std::vector<uint64_t>* out) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003868 mBufferRecords.getInflightRequestBufferKeys(out);
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08003869 return;
3870}
3871
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003872bool Camera3Device::HalInterface::verifyBufferIds(
3873 int32_t streamId, std::vector<uint64_t>& bufIds) {
3874 return mBufferRecords.verifyBufferIds(streamId, bufIds);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003875}
3876
3877status_t Camera3Device::HalInterface::popInflightBuffer(
Yin-Chia Yehf4650602017-01-10 13:13:39 -08003878 int32_t frameNumber, int32_t streamId,
3879 /*out*/ buffer_handle_t **buffer) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003880 return mBufferRecords.popInflightBuffer(frameNumber, streamId, buffer);
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003881}
3882
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003883status_t Camera3Device::HalInterface::pushInflightRequestBuffer(
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08003884 uint64_t bufferId, buffer_handle_t* buf, int32_t streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003885 return mBufferRecords.pushInflightRequestBuffer(bufferId, buf, streamId);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003886}
3887
3888// Find and pop a buffer_handle_t based on bufferId
3889status_t Camera3Device::HalInterface::popInflightRequestBuffer(
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08003890 uint64_t bufferId,
3891 /*out*/ buffer_handle_t** buffer,
3892 /*optional out*/ int32_t* streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003893 return mBufferRecords.popInflightRequestBuffer(bufferId, buffer, streamId);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003894}
3895
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003896std::pair<bool, uint64_t> Camera3Device::HalInterface::getBufferId(
3897 const buffer_handle_t& buf, int streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003898 return mBufferRecords.getBufferId(buf, streamId);
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003899}
3900
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003901void Camera3Device::HalInterface::onBufferFreed(
3902 int streamId, const native_handle_t* handle) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003903 uint32_t bufferId = mBufferRecords.removeOneBufferCache(streamId, handle);
3904 std::lock_guard<std::mutex> lock(mFreedBuffersLock);
3905 if (bufferId != BUFFER_ID_NO_BUFFER) {
3906 mFreedBuffers.push_back(std::make_pair(streamId, bufferId));
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003907 }
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003908}
3909
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07003910void Camera3Device::HalInterface::onStreamReConfigured(int streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003911 std::vector<uint64_t> bufIds = mBufferRecords.clearBufferCaches(streamId);
3912 std::lock_guard<std::mutex> lock(mFreedBuffersLock);
3913 for (auto bufferId : bufIds) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07003914 mFreedBuffers.push_back(std::make_pair(streamId, bufferId));
3915 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07003916}
3917
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003918/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003919 * RequestThread inner class methods
3920 */
3921
3922Camera3Device::RequestThread::RequestThread(wp<Camera3Device> parent,
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003923 sp<StatusTracker> statusTracker,
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003924 sp<HalInterface> interface, const Vector<int32_t>& sessionParamKeys,
3925 bool useHalBufManager) :
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07003926 Thread(/*canCallJava*/false),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003927 mParent(parent),
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003928 mStatusTracker(statusTracker),
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003929 mInterface(interface),
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07003930 mListener(nullptr),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003931 mId(getId(parent)),
Shuzhen Wang316781a2020-08-18 18:11:01 -07003932 mFirstRepeating(false),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003933 mReconfigured(false),
3934 mDoPause(false),
3935 mPaused(true),
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003936 mNotifyPipelineDrain(false),
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003937 mFrameNumber(0),
Jianing Weicb0652e2014-03-12 18:29:36 -07003938 mLatestRequestId(NAME_NOT_FOUND),
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07003939 mCurrentAfTriggerId(0),
3940 mCurrentPreCaptureTriggerId(0),
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08003941 mRotateAndCropOverride(ANDROID_SCALER_ROTATE_AND_CROP_NONE),
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08003942 mCameraMute(false),
3943 mCameraMuteChanged(false),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003944 mRepeatingLastFrameNumber(
3945 hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES),
Shuzhen Wang686f6442017-06-20 16:16:04 -07003946 mPrepareVideoStream(false),
Emilian Peeva14b4dd2018-05-15 11:00:31 +01003947 mConstrainedMode(false),
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003948 mRequestLatency(kRequestLatencyBinSize),
3949 mSessionParamKeys(sessionParamKeys),
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003950 mLatestSessionParams(sessionParamKeys.size()),
3951 mUseHalBufManager(useHalBufManager) {
Yin-Chia Yeh87b3ec02019-06-03 10:44:39 -07003952 mStatusId = statusTracker->addComponent("RequestThread");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003953}
3954
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003955Camera3Device::RequestThread::~RequestThread() {}
3956
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07003957void Camera3Device::RequestThread::setNotificationListener(
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003958 wp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003959 ATRACE_CALL();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003960 Mutex::Autolock l(mRequestLock);
3961 mListener = listener;
3962}
3963
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003964void Camera3Device::RequestThread::configurationComplete(bool isConstrainedHighSpeed,
3965 const CameraMetadata& sessionParams) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003966 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003967 Mutex::Autolock l(mRequestLock);
3968 mReconfigured = true;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003969 mLatestSessionParams = sessionParams;
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07003970 // Prepare video stream for high speed recording.
3971 mPrepareVideoStream = isConstrainedHighSpeed;
Emilian Peeva14b4dd2018-05-15 11:00:31 +01003972 mConstrainedMode = isConstrainedHighSpeed;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003973}
3974
Jianing Wei90e59c92014-03-12 18:29:36 -07003975status_t Camera3Device::RequestThread::queueRequestList(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003976 List<sp<CaptureRequest> > &requests,
3977 /*out*/
3978 int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003979 ATRACE_CALL();
Jianing Wei90e59c92014-03-12 18:29:36 -07003980 Mutex::Autolock l(mRequestLock);
3981 for (List<sp<CaptureRequest> >::iterator it = requests.begin(); it != requests.end();
3982 ++it) {
3983 mRequestQueue.push_back(*it);
3984 }
3985
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003986 if (lastFrameNumber != NULL) {
3987 *lastFrameNumber = mFrameNumber + mRequestQueue.size() - 1;
3988 ALOGV("%s: requestId %d, mFrameNumber %" PRId32 ", lastFrameNumber %" PRId64 ".",
3989 __FUNCTION__, (*(requests.begin()))->mResultExtras.requestId, mFrameNumber,
3990 *lastFrameNumber);
3991 }
Jianing Weicb0652e2014-03-12 18:29:36 -07003992
Jianing Wei90e59c92014-03-12 18:29:36 -07003993 unpauseForNewRequests();
3994
3995 return OK;
3996}
3997
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003998
3999status_t Camera3Device::RequestThread::queueTrigger(
4000 RequestTrigger trigger[],
4001 size_t count) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004002 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004003 Mutex::Autolock l(mTriggerMutex);
4004 status_t ret;
4005
4006 for (size_t i = 0; i < count; ++i) {
4007 ret = queueTriggerLocked(trigger[i]);
4008
4009 if (ret != OK) {
4010 return ret;
4011 }
4012 }
4013
4014 return OK;
4015}
4016
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004017const String8& Camera3Device::RequestThread::getId(const wp<Camera3Device> &device) {
4018 static String8 deadId("<DeadDevice>");
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004019 sp<Camera3Device> d = device.promote();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004020 if (d != nullptr) return d->mId;
4021 return deadId;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004022}
4023
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004024status_t Camera3Device::RequestThread::queueTriggerLocked(
4025 RequestTrigger trigger) {
4026
4027 uint32_t tag = trigger.metadataTag;
4028 ssize_t index = mTriggerMap.indexOfKey(tag);
4029
4030 switch (trigger.getTagType()) {
4031 case TYPE_BYTE:
4032 // fall-through
4033 case TYPE_INT32:
4034 break;
4035 default:
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004036 ALOGE("%s: Type not supported: 0x%x", __FUNCTION__,
4037 trigger.getTagType());
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004038 return INVALID_OPERATION;
4039 }
4040
4041 /**
4042 * Collect only the latest trigger, since we only have 1 field
4043 * in the request settings per trigger tag, and can't send more than 1
4044 * trigger per request.
4045 */
4046 if (index != NAME_NOT_FOUND) {
4047 mTriggerMap.editValueAt(index) = trigger;
4048 } else {
4049 mTriggerMap.add(tag, trigger);
4050 }
4051
4052 return OK;
4053}
4054
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004055status_t Camera3Device::RequestThread::setRepeatingRequests(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004056 const RequestList &requests,
4057 /*out*/
4058 int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004059 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004060 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004061 if (lastFrameNumber != NULL) {
4062 *lastFrameNumber = mRepeatingLastFrameNumber;
4063 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004064 mRepeatingRequests.clear();
Shuzhen Wang316781a2020-08-18 18:11:01 -07004065 mFirstRepeating = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004066 mRepeatingRequests.insert(mRepeatingRequests.begin(),
4067 requests.begin(), requests.end());
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004068
4069 unpauseForNewRequests();
4070
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004071 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004072 return OK;
4073}
4074
Chih-Hung Hsieh8b0b9712016-08-09 14:25:53 -07004075bool Camera3Device::RequestThread::isRepeatingRequestLocked(const sp<CaptureRequest>& requestIn) {
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07004076 if (mRepeatingRequests.empty()) {
4077 return false;
4078 }
4079 int32_t requestId = requestIn->mResultExtras.requestId;
4080 const RequestList &repeatRequests = mRepeatingRequests;
4081 // All repeating requests are guaranteed to have same id so only check first quest
4082 const sp<CaptureRequest> firstRequest = *repeatRequests.begin();
4083 return (firstRequest->mResultExtras.requestId == requestId);
4084}
4085
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004086status_t Camera3Device::RequestThread::clearRepeatingRequests(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004087 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004088 Mutex::Autolock l(mRequestLock);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004089 return clearRepeatingRequestsLocked(lastFrameNumber);
4090
4091}
4092
4093status_t Camera3Device::RequestThread::clearRepeatingRequestsLocked(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004094 mRepeatingRequests.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004095 if (lastFrameNumber != NULL) {
4096 *lastFrameNumber = mRepeatingLastFrameNumber;
4097 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004098 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004099 return OK;
4100}
4101
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004102status_t Camera3Device::RequestThread::clear(
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004103 /*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004104 ATRACE_CALL();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004105 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004106 ALOGV("RequestThread::%s:", __FUNCTION__);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004107
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004108 mRepeatingRequests.clear();
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07004109
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004110 // Send errors for all requests pending in the request queue, including
4111 // pending repeating requests
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004112 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004113 if (listener != NULL) {
4114 for (RequestList::iterator it = mRequestQueue.begin();
4115 it != mRequestQueue.end(); ++it) {
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004116 // Abort the input buffers for reprocess requests.
4117 if ((*it)->mInputStream != NULL) {
Emilian Peevf4816702020-04-03 15:44:51 -07004118 camera_stream_buffer_t inputBuffer;
Shuzhen Wang83bff122020-11-20 15:51:39 -08004119 camera3::Size inputBufferSize;
Eino-Ville Talvalaba435252017-06-21 16:07:25 -07004120 status_t res = (*it)->mInputStream->getInputBuffer(&inputBuffer,
Shuzhen Wang83bff122020-11-20 15:51:39 -08004121 &inputBufferSize, /*respectHalLimit*/ false);
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004122 if (res != OK) {
4123 ALOGW("%s: %d: couldn't get input buffer while clearing the request "
4124 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
4125 } else {
Emilian Peevf4816702020-04-03 15:44:51 -07004126 inputBuffer.status = CAMERA_BUFFER_STATUS_ERROR;
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004127 res = (*it)->mInputStream->returnInputBuffer(inputBuffer);
4128 if (res != OK) {
4129 ALOGE("%s: %d: couldn't return input buffer while clearing the request "
4130 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
4131 }
4132 }
4133 }
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004134 // Set the frame number this request would have had, if it
4135 // had been submitted; this frame number will not be reused.
4136 // The requestId and burstId fields were set when the request was
4137 // submitted originally (in convertMetadataListToRequestListLocked)
4138 (*it)->mResultExtras.frameNumber = mFrameNumber++;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004139 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004140 (*it)->mResultExtras);
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07004141 }
4142 }
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004143 mRequestQueue.clear();
Jinguang Dongb26e7a02016-11-14 16:04:02 +08004144
4145 Mutex::Autolock al(mTriggerMutex);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004146 mTriggerMap.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004147 if (lastFrameNumber != NULL) {
4148 *lastFrameNumber = mRepeatingLastFrameNumber;
4149 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004150 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Emilian Peev8dae54c2019-12-02 15:17:17 -08004151 mRequestSignal.signal();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004152 return OK;
4153}
4154
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004155status_t Camera3Device::RequestThread::flush() {
4156 ATRACE_CALL();
4157 Mutex::Autolock l(mFlushLock);
4158
Emilian Peev08dd2452017-04-06 16:55:14 +01004159 return mInterface->flush();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004160}
4161
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004162void Camera3Device::RequestThread::setPaused(bool paused) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004163 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004164 Mutex::Autolock l(mPauseLock);
4165 mDoPause = paused;
4166 mDoPauseSignal.signal();
4167}
4168
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004169status_t Camera3Device::RequestThread::waitUntilRequestProcessed(
4170 int32_t requestId, nsecs_t timeout) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004171 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004172 Mutex::Autolock l(mLatestRequestMutex);
4173 status_t res;
4174 while (mLatestRequestId != requestId) {
4175 nsecs_t startTime = systemTime();
4176
4177 res = mLatestRequestSignal.waitRelative(mLatestRequestMutex, timeout);
4178 if (res != OK) return res;
4179
4180 timeout -= (systemTime() - startTime);
4181 }
4182
4183 return OK;
4184}
4185
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004186void Camera3Device::RequestThread::requestExit() {
4187 // Call parent to set up shutdown
4188 Thread::requestExit();
4189 // The exit from any possible waits
4190 mDoPauseSignal.signal();
4191 mRequestSignal.signal();
Shuzhen Wang686f6442017-06-20 16:16:04 -07004192
4193 mRequestLatency.log("ProcessCaptureRequest latency histogram");
4194 mRequestLatency.reset();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004195}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004196
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004197void Camera3Device::RequestThread::checkAndStopRepeatingRequest() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004198 ATRACE_CALL();
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07004199 bool surfaceAbandoned = false;
4200 int64_t lastFrameNumber = 0;
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004201 sp<NotificationListener> listener;
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07004202 {
4203 Mutex::Autolock l(mRequestLock);
4204 // Check all streams needed by repeating requests are still valid. Otherwise, stop
4205 // repeating requests.
4206 for (const auto& request : mRepeatingRequests) {
4207 for (const auto& s : request->mOutputStreams) {
4208 if (s->isAbandoned()) {
4209 surfaceAbandoned = true;
4210 clearRepeatingRequestsLocked(&lastFrameNumber);
4211 break;
4212 }
4213 }
4214 if (surfaceAbandoned) {
4215 break;
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004216 }
4217 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004218 listener = mListener.promote();
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004219 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004220
4221 if (listener != NULL && surfaceAbandoned) {
4222 listener->notifyRepeatingRequestError(lastFrameNumber);
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07004223 }
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004224}
4225
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004226bool Camera3Device::RequestThread::sendRequestsBatch() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004227 ATRACE_CALL();
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004228 status_t res;
4229 size_t batchSize = mNextRequests.size();
Emilian Peevf4816702020-04-03 15:44:51 -07004230 std::vector<camera_capture_request_t*> requests(batchSize);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004231 uint32_t numRequestProcessed = 0;
4232 for (size_t i = 0; i < batchSize; i++) {
4233 requests[i] = &mNextRequests.editItemAt(i).halRequest;
Yin-Chia Yeh885691c2018-05-01 15:54:24 -07004234 ATRACE_ASYNC_BEGIN("frame capture", mNextRequests[i].halRequest.frame_number);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004235 }
4236
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004237 res = mInterface->processBatchCaptureRequests(requests, &numRequestProcessed);
4238
4239 bool triggerRemoveFailed = false;
4240 NextRequest& triggerFailedRequest = mNextRequests.editItemAt(0);
4241 for (size_t i = 0; i < numRequestProcessed; i++) {
4242 NextRequest& nextRequest = mNextRequests.editItemAt(i);
4243 nextRequest.submitted = true;
4244
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004245 updateNextRequest(nextRequest);
Emilian Peevaebbe412018-01-15 13:53:24 +00004246
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004247 if (!triggerRemoveFailed) {
4248 // Remove any previously queued triggers (after unlock)
4249 status_t removeTriggerRes = removeTriggers(mPrevRequest);
4250 if (removeTriggerRes != OK) {
4251 triggerRemoveFailed = true;
4252 triggerFailedRequest = nextRequest;
4253 }
4254 }
4255 }
4256
4257 if (triggerRemoveFailed) {
4258 SET_ERR("RequestThread: Unable to remove triggers "
4259 "(capture request %d, HAL device: %s (%d)",
4260 triggerFailedRequest.halRequest.frame_number, strerror(-res), res);
4261 cleanUpFailedRequests(/*sendRequestError*/ false);
4262 return false;
4263 }
4264
4265 if (res != OK) {
4266 // Should only get a failure here for malformed requests or device-level
4267 // errors, so consider all errors fatal. Bad metadata failures should
4268 // come through notify.
4269 SET_ERR("RequestThread: Unable to submit capture request %d to HAL device: %s (%d)",
4270 mNextRequests[numRequestProcessed].halRequest.frame_number,
4271 strerror(-res), res);
4272 cleanUpFailedRequests(/*sendRequestError*/ false);
4273 return false;
4274 }
4275 return true;
4276}
4277
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07004278nsecs_t Camera3Device::RequestThread::calculateMaxExpectedDuration(const camera_metadata_t *request) {
4279 nsecs_t maxExpectedDuration = kDefaultExpectedDuration;
4280 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
4281 find_camera_metadata_ro_entry(request,
4282 ANDROID_CONTROL_AE_MODE,
4283 &e);
4284 if (e.count == 0) return maxExpectedDuration;
4285
4286 switch (e.data.u8[0]) {
4287 case ANDROID_CONTROL_AE_MODE_OFF:
4288 find_camera_metadata_ro_entry(request,
4289 ANDROID_SENSOR_EXPOSURE_TIME,
4290 &e);
4291 if (e.count > 0) {
4292 maxExpectedDuration = e.data.i64[0];
4293 }
4294 find_camera_metadata_ro_entry(request,
4295 ANDROID_SENSOR_FRAME_DURATION,
4296 &e);
4297 if (e.count > 0) {
4298 maxExpectedDuration = std::max(e.data.i64[0], maxExpectedDuration);
4299 }
4300 break;
4301 default:
4302 find_camera_metadata_ro_entry(request,
4303 ANDROID_CONTROL_AE_TARGET_FPS_RANGE,
4304 &e);
4305 if (e.count > 1) {
4306 maxExpectedDuration = 1e9 / e.data.u8[0];
4307 }
4308 break;
4309 }
4310
4311 return maxExpectedDuration;
4312}
4313
Emilian Peeva14b4dd2018-05-15 11:00:31 +01004314bool Camera3Device::RequestThread::skipHFRTargetFPSUpdate(int32_t tag,
4315 const camera_metadata_ro_entry_t& newEntry, const camera_metadata_entry_t& currentEntry) {
4316 if (mConstrainedMode && (ANDROID_CONTROL_AE_TARGET_FPS_RANGE == tag) &&
4317 (newEntry.count == currentEntry.count) && (currentEntry.count == 2) &&
4318 (currentEntry.data.i32[1] == newEntry.data.i32[1])) {
4319 return true;
4320 }
4321
4322 return false;
4323}
4324
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004325void Camera3Device::RequestThread::updateNextRequest(NextRequest& nextRequest) {
4326 // Update the latest request sent to HAL
Shuzhen Wang83bff122020-11-20 15:51:39 -08004327 camera_capture_request_t& halRequest = nextRequest.halRequest;
4328 if (halRequest.settings != NULL) { // Don't update if they were unchanged
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004329 Mutex::Autolock al(mLatestRequestMutex);
4330
Shuzhen Wang83bff122020-11-20 15:51:39 -08004331 camera_metadata_t* cloned = clone_camera_metadata(halRequest.settings);
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004332 mLatestRequest.acquire(cloned);
4333
4334 mLatestPhysicalRequest.clear();
Shuzhen Wang83bff122020-11-20 15:51:39 -08004335 for (uint32_t i = 0; i < halRequest.num_physcam_settings; i++) {
4336 cloned = clone_camera_metadata(halRequest.physcam_settings[i]);
4337 mLatestPhysicalRequest.emplace(halRequest.physcam_id[i],
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004338 CameraMetadata(cloned));
4339 }
4340
4341 sp<Camera3Device> parent = mParent.promote();
4342 if (parent != NULL) {
4343 parent->monitorMetadata(TagMonitor::REQUEST,
Shuzhen Wang83bff122020-11-20 15:51:39 -08004344 halRequest.frame_number,
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004345 0, mLatestRequest, mLatestPhysicalRequest);
4346 }
4347 }
4348
Shuzhen Wang83bff122020-11-20 15:51:39 -08004349 if (halRequest.settings != NULL) {
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004350 nextRequest.captureRequest->mSettingsList.begin()->metadata.unlock(
Shuzhen Wang83bff122020-11-20 15:51:39 -08004351 halRequest.settings);
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004352 }
4353
Shuzhen Wang83bff122020-11-20 15:51:39 -08004354 cleanupPhysicalSettings(nextRequest.captureRequest, &halRequest);
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004355}
4356
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004357bool Camera3Device::RequestThread::updateSessionParameters(const CameraMetadata& settings) {
4358 ATRACE_CALL();
4359 bool updatesDetected = false;
4360
Emilian Peev4ec17882019-01-24 17:16:58 -08004361 CameraMetadata updatedParams(mLatestSessionParams);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004362 for (auto tag : mSessionParamKeys) {
4363 camera_metadata_ro_entry entry = settings.find(tag);
Emilian Peev4ec17882019-01-24 17:16:58 -08004364 camera_metadata_entry lastEntry = updatedParams.find(tag);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004365
4366 if (entry.count > 0) {
4367 bool isDifferent = false;
4368 if (lastEntry.count > 0) {
4369 // Have a last value, compare to see if changed
4370 if (lastEntry.type == entry.type &&
4371 lastEntry.count == entry.count) {
4372 // Same type and count, compare values
4373 size_t bytesPerValue = camera_metadata_type_size[lastEntry.type];
4374 size_t entryBytes = bytesPerValue * lastEntry.count;
4375 int cmp = memcmp(entry.data.u8, lastEntry.data.u8, entryBytes);
4376 if (cmp != 0) {
4377 isDifferent = true;
4378 }
4379 } else {
4380 // Count or type has changed
4381 isDifferent = true;
4382 }
4383 } else {
4384 // No last entry, so always consider to be different
4385 isDifferent = true;
4386 }
4387
4388 if (isDifferent) {
4389 ALOGV("%s: Session parameter tag id %d changed", __FUNCTION__, tag);
Emilian Peeva14b4dd2018-05-15 11:00:31 +01004390 if (!skipHFRTargetFPSUpdate(tag, entry, lastEntry)) {
4391 updatesDetected = true;
4392 }
Emilian Peev4ec17882019-01-24 17:16:58 -08004393 updatedParams.update(entry);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004394 }
4395 } else if (lastEntry.count > 0) {
4396 // Value has been removed
4397 ALOGV("%s: Session parameter tag id %d removed", __FUNCTION__, tag);
Emilian Peev4ec17882019-01-24 17:16:58 -08004398 updatedParams.erase(tag);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004399 updatesDetected = true;
4400 }
4401 }
4402
Emilian Peev4ec17882019-01-24 17:16:58 -08004403 bool reconfigureRequired;
4404 if (updatesDetected) {
4405 reconfigureRequired = mInterface->isReconfigurationRequired(mLatestSessionParams,
4406 updatedParams);
4407 mLatestSessionParams = updatedParams;
4408 } else {
4409 reconfigureRequired = false;
4410 }
4411
4412 return reconfigureRequired;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004413}
4414
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004415bool Camera3Device::RequestThread::threadLoop() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004416 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004417 status_t res;
Jayant Chowdhary37eca242019-11-18 08:55:56 -08004418 // Any function called from threadLoop() must not hold mInterfaceLock since
4419 // it could lead to deadlocks (disconnect() -> hold mInterfaceMutex -> wait for request thread
4420 // to finish -> request thread waits on mInterfaceMutex) http://b/143513518
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004421
4422 // Handle paused state.
4423 if (waitIfPaused()) {
4424 return true;
4425 }
4426
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004427 // Wait for the next batch of requests.
4428 waitForNextRequestBatch();
4429 if (mNextRequests.size() == 0) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004430 return true;
4431 }
4432
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004433 // Get the latest request ID, if any
4434 int latestRequestId;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004435 camera_metadata_entry_t requestIdEntry = mNextRequests[mNextRequests.size() - 1].
Emilian Peevaebbe412018-01-15 13:53:24 +00004436 captureRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_ID);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004437 if (requestIdEntry.count > 0) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004438 latestRequestId = requestIdEntry.data.i32[0];
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004439 } else {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004440 ALOGW("%s: Did not have android.request.id set in the request.", __FUNCTION__);
4441 latestRequestId = NAME_NOT_FOUND;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004442 }
4443
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004444 // 'mNextRequests' will at this point contain either a set of HFR batched requests
4445 // or a single request from streaming or burst. In either case the first element
4446 // should contain the latest camera settings that we need to check for any session
4447 // parameter updates.
Emilian Peevaebbe412018-01-15 13:53:24 +00004448 if (updateSessionParameters(mNextRequests[0].captureRequest->mSettingsList.begin()->metadata)) {
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004449 res = OK;
4450
4451 //Input stream buffers are already acquired at this point so an input stream
4452 //will not be able to move to idle state unless we force it.
4453 if (mNextRequests[0].captureRequest->mInputStream != nullptr) {
4454 res = mNextRequests[0].captureRequest->mInputStream->forceToIdle();
4455 if (res != OK) {
4456 ALOGE("%s: Failed to force idle input stream: %d", __FUNCTION__, res);
4457 cleanUpFailedRequests(/*sendRequestError*/ false);
4458 return false;
4459 }
4460 }
4461
4462 if (res == OK) {
Emilian Peev3bead5f2020-05-28 17:29:08 -07004463 sp<Camera3Device> parent = mParent.promote();
4464 if (parent != nullptr) {
4465 mReconfigured |= parent->reconfigureCamera(mLatestSessionParams, mStatusId);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004466 }
Emilian Peev3bead5f2020-05-28 17:29:08 -07004467 setPaused(false);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004468
4469 if (mNextRequests[0].captureRequest->mInputStream != nullptr) {
4470 mNextRequests[0].captureRequest->mInputStream->restoreConfiguredState();
4471 if (res != OK) {
4472 ALOGE("%s: Failed to restore configured input stream: %d", __FUNCTION__, res);
4473 cleanUpFailedRequests(/*sendRequestError*/ false);
4474 return false;
4475 }
4476 }
4477 }
4478 }
4479
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004480 // Prepare a batch of HAL requests and output buffers.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004481 res = prepareHalRequests();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004482 if (res == TIMED_OUT) {
4483 // Not a fatal error if getting output buffers time out.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004484 cleanUpFailedRequests(/*sendRequestError*/ true);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004485 // Check if any stream is abandoned.
4486 checkAndStopRepeatingRequest();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004487 return true;
4488 } else if (res != OK) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004489 cleanUpFailedRequests(/*sendRequestError*/ false);
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004490 return false;
4491 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004492
Zhijun Hecc27e112013-10-03 16:12:43 -07004493 // Inform waitUntilRequestProcessed thread of a new request ID
4494 {
4495 Mutex::Autolock al(mLatestRequestMutex);
4496
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004497 mLatestRequestId = latestRequestId;
Zhijun Hecc27e112013-10-03 16:12:43 -07004498 mLatestRequestSignal.signal();
4499 }
4500
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004501 // Submit a batch of requests to HAL.
4502 // Use flush lock only when submitting multilple requests in a batch.
4503 // TODO: The problem with flush lock is flush() will be blocked by process_capture_request()
4504 // which may take a long time to finish so synchronizing flush() and
4505 // process_capture_request() defeats the purpose of cancelling requests ASAP with flush().
4506 // For now, only synchronize for high speed recording and we should figure something out for
4507 // removing the synchronization.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004508 bool useFlushLock = mNextRequests.size() > 1;
Eino-Ville Talvala17a61ad2013-06-03 16:53:32 -07004509
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004510 if (useFlushLock) {
4511 mFlushLock.lock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004512 }
4513
Zhijun Hef0645c12016-08-02 00:58:11 -07004514 ALOGVV("%s: %d: submitting %zu requests in a batch.", __FUNCTION__, __LINE__,
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004515 mNextRequests.size());
Igor Murashkin1e479c02013-09-06 16:55:14 -07004516
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08004517 sp<Camera3Device> parent = mParent.promote();
4518 if (parent != nullptr) {
4519 parent->mRequestBufferSM.onSubmittingRequest();
4520 }
4521
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004522 bool submitRequestSuccess = false;
Shuzhen Wang686f6442017-06-20 16:16:04 -07004523 nsecs_t tRequestStart = systemTime(SYSTEM_TIME_MONOTONIC);
Yin-Chia Yeh11648852019-05-16 10:42:54 -07004524 submitRequestSuccess = sendRequestsBatch();
4525
Shuzhen Wang686f6442017-06-20 16:16:04 -07004526 nsecs_t tRequestEnd = systemTime(SYSTEM_TIME_MONOTONIC);
4527 mRequestLatency.add(tRequestStart, tRequestEnd);
Igor Murashkin1e479c02013-09-06 16:55:14 -07004528
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004529 if (useFlushLock) {
4530 mFlushLock.unlock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004531 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004532
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004533 // Unset as current request
4534 {
4535 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004536 mNextRequests.clear();
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004537 }
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004538 mRequestSubmittedSignal.signal();
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004539
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004540 return submitRequestSuccess;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004541}
4542
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004543status_t Camera3Device::RequestThread::prepareHalRequests() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004544 ATRACE_CALL();
4545
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07004546 bool batchedRequest = mNextRequests[0].captureRequest->mBatchSize > 1;
Shuzhen Wang4a472662017-02-26 23:29:04 -08004547 for (size_t i = 0; i < mNextRequests.size(); i++) {
4548 auto& nextRequest = mNextRequests.editItemAt(i);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004549 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
Emilian Peevf4816702020-04-03 15:44:51 -07004550 camera_capture_request_t* halRequest = &nextRequest.halRequest;
4551 Vector<camera_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004552
4553 // Prepare a request to HAL
4554 halRequest->frame_number = captureRequest->mResultExtras.frameNumber;
4555
4556 // Insert any queued triggers (before metadata is locked)
4557 status_t res = insertTriggers(captureRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004558 if (res < 0) {
4559 SET_ERR("RequestThread: Unable to insert triggers "
4560 "(capture request %d, HAL device: %s (%d)",
4561 halRequest->frame_number, strerror(-res), res);
4562 return INVALID_OPERATION;
4563 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07004564
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004565 int triggerCount = res;
4566 bool triggersMixedIn = (triggerCount > 0 || mPrevTriggers > 0);
4567 mPrevTriggers = triggerCount;
4568
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004569 bool rotateAndCropChanged = overrideAutoRotateAndCrop(captureRequest);
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004570 bool testPatternChanged = overrideTestPattern(captureRequest);
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004571
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004572 // If the request is the same as last, or we had triggers now or last time or
4573 // changing overrides this time
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004574 bool newRequest =
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004575 (mPrevRequest != captureRequest || triggersMixedIn ||
4576 rotateAndCropChanged || testPatternChanged) &&
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07004577 // Request settings are all the same within one batch, so only treat the first
4578 // request in a batch as new
Zhijun He54c36822018-07-18 09:33:39 -07004579 !(batchedRequest && i > 0);
Emilian Peev00420d22018-02-05 21:33:13 +00004580 if (newRequest) {
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08004581 std::set<std::string> cameraIdsWithZoom;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004582 /**
4583 * HAL workaround:
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004584 * Insert a fake trigger ID if a trigger is set but no trigger ID is
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004585 */
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004586 res = addFakeTriggerIds(captureRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004587 if (res != OK) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004588 SET_ERR("RequestThread: Unable to insert fake trigger IDs "
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004589 "(capture request %d, HAL device: %s (%d)",
4590 halRequest->frame_number, strerror(-res), res);
4591 return INVALID_OPERATION;
4592 }
4593
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07004594 {
4595 // Correct metadata regions for distortion correction if enabled
4596 sp<Camera3Device> parent = mParent.promote();
4597 if (parent != nullptr) {
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -07004598 List<PhysicalCameraSettings>::iterator it;
4599 for (it = captureRequest->mSettingsList.begin();
4600 it != captureRequest->mSettingsList.end(); it++) {
4601 if (parent->mDistortionMappers.find(it->cameraId) ==
4602 parent->mDistortionMappers.end()) {
4603 continue;
4604 }
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07004605
4606 if (!captureRequest->mDistortionCorrectionUpdated) {
4607 res = parent->mDistortionMappers[it->cameraId].correctCaptureRequest(
4608 &(it->metadata));
4609 if (res != OK) {
4610 SET_ERR("RequestThread: Unable to correct capture requests "
4611 "for lens distortion for request %d: %s (%d)",
4612 halRequest->frame_number, strerror(-res), res);
4613 return INVALID_OPERATION;
4614 }
4615 captureRequest->mDistortionCorrectionUpdated = true;
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -07004616 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07004617 }
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08004618
4619 for (it = captureRequest->mSettingsList.begin();
4620 it != captureRequest->mSettingsList.end(); it++) {
4621 if (parent->mZoomRatioMappers.find(it->cameraId) ==
4622 parent->mZoomRatioMappers.end()) {
4623 continue;
4624 }
4625
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07004626 if (!captureRequest->mZoomRatioIs1x) {
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08004627 cameraIdsWithZoom.insert(it->cameraId);
4628 }
4629
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07004630 if (!captureRequest->mZoomRatioUpdated) {
4631 res = parent->mZoomRatioMappers[it->cameraId].updateCaptureRequest(
4632 &(it->metadata));
4633 if (res != OK) {
4634 SET_ERR("RequestThread: Unable to correct capture requests "
4635 "for zoom ratio for request %d: %s (%d)",
4636 halRequest->frame_number, strerror(-res), res);
4637 return INVALID_OPERATION;
4638 }
4639 captureRequest->mZoomRatioUpdated = true;
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08004640 }
4641 }
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07004642 if (captureRequest->mRotateAndCropAuto &&
4643 !captureRequest->mRotationAndCropUpdated) {
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004644 for (it = captureRequest->mSettingsList.begin();
4645 it != captureRequest->mSettingsList.end(); it++) {
4646 auto mapper = parent->mRotateAndCropMappers.find(it->cameraId);
4647 if (mapper != parent->mRotateAndCropMappers.end()) {
4648 res = mapper->second.updateCaptureRequest(&(it->metadata));
4649 if (res != OK) {
4650 SET_ERR("RequestThread: Unable to correct capture requests "
4651 "for rotate-and-crop for request %d: %s (%d)",
4652 halRequest->frame_number, strerror(-res), res);
4653 return INVALID_OPERATION;
4654 }
4655 }
4656 }
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07004657 captureRequest->mRotationAndCropUpdated = true;
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004658 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07004659 }
4660 }
4661
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004662 /**
4663 * The request should be presorted so accesses in HAL
4664 * are O(logn). Sidenote, sorting a sorted metadata is nop.
4665 */
Emilian Peevaebbe412018-01-15 13:53:24 +00004666 captureRequest->mSettingsList.begin()->metadata.sort();
4667 halRequest->settings = captureRequest->mSettingsList.begin()->metadata.getAndLock();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004668 mPrevRequest = captureRequest;
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08004669 mPrevCameraIdsWithZoom = cameraIdsWithZoom;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004670 ALOGVV("%s: Request settings are NEW", __FUNCTION__);
4671
4672 IF_ALOGV() {
4673 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
4674 find_camera_metadata_ro_entry(
4675 halRequest->settings,
4676 ANDROID_CONTROL_AF_TRIGGER,
4677 &e
4678 );
4679 if (e.count > 0) {
4680 ALOGV("%s: Request (frame num %d) had AF trigger 0x%x",
4681 __FUNCTION__,
4682 halRequest->frame_number,
4683 e.data.u8[0]);
4684 }
4685 }
4686 } else {
4687 // leave request.settings NULL to indicate 'reuse latest given'
4688 ALOGVV("%s: Request settings are REUSED",
4689 __FUNCTION__);
4690 }
4691
Emilian Peevaebbe412018-01-15 13:53:24 +00004692 if (captureRequest->mSettingsList.size() > 1) {
4693 halRequest->num_physcam_settings = captureRequest->mSettingsList.size() - 1;
4694 halRequest->physcam_id = new const char* [halRequest->num_physcam_settings];
Emilian Peev00420d22018-02-05 21:33:13 +00004695 if (newRequest) {
4696 halRequest->physcam_settings =
4697 new const camera_metadata* [halRequest->num_physcam_settings];
4698 } else {
4699 halRequest->physcam_settings = nullptr;
4700 }
Emilian Peevaebbe412018-01-15 13:53:24 +00004701 auto it = ++captureRequest->mSettingsList.begin();
4702 size_t i = 0;
4703 for (; it != captureRequest->mSettingsList.end(); it++, i++) {
4704 halRequest->physcam_id[i] = it->cameraId.c_str();
Emilian Peev00420d22018-02-05 21:33:13 +00004705 if (newRequest) {
4706 it->metadata.sort();
4707 halRequest->physcam_settings[i] = it->metadata.getAndLock();
4708 }
Emilian Peevaebbe412018-01-15 13:53:24 +00004709 }
4710 }
4711
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004712 uint32_t totalNumBuffers = 0;
4713
4714 // Fill in buffers
4715 if (captureRequest->mInputStream != NULL) {
4716 halRequest->input_buffer = &captureRequest->mInputBuffer;
Shuzhen Wang83bff122020-11-20 15:51:39 -08004717
4718 halRequest->input_width = captureRequest->mInputBufferSize.width;
4719 halRequest->input_height = captureRequest->mInputBufferSize.height;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004720 totalNumBuffers += 1;
4721 } else {
4722 halRequest->input_buffer = NULL;
4723 }
4724
Emilian Peevf4816702020-04-03 15:44:51 -07004725 outputBuffers->insertAt(camera_stream_buffer_t(), 0,
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004726 captureRequest->mOutputStreams.size());
4727 halRequest->output_buffers = outputBuffers->array();
Shuzhen Wang5c22c152017-12-31 17:12:25 -08004728 std::set<String8> requestedPhysicalCameras;
Yin-Chia Yehb3a80b12018-09-04 12:13:05 -07004729
4730 sp<Camera3Device> parent = mParent.promote();
4731 if (parent == NULL) {
4732 // Should not happen, and nowhere to send errors to, so just log it
4733 CLOGE("RequestThread: Parent is gone");
4734 return INVALID_OPERATION;
4735 }
4736 nsecs_t waitDuration = kBaseGetBufferWait + parent->getExpectedInFlightDuration();
4737
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07004738 SurfaceMap uniqueSurfaceIdMap;
Shuzhen Wang4a472662017-02-26 23:29:04 -08004739 for (size_t j = 0; j < captureRequest->mOutputStreams.size(); j++) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07004740 sp<Camera3OutputStreamInterface> outputStream =
4741 captureRequest->mOutputStreams.editItemAt(j);
4742 int streamId = outputStream->getId();
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07004743
4744 // Prepare video buffers for high speed recording on the first video request.
4745 if (mPrepareVideoStream && outputStream->isVideoStream()) {
4746 // Only try to prepare video stream on the first video request.
4747 mPrepareVideoStream = false;
4748
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07004749 res = outputStream->startPrepare(Camera3StreamInterface::ALLOCATE_PIPELINE_MAX,
4750 false /*blockRequest*/);
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07004751 while (res == NOT_ENOUGH_DATA) {
4752 res = outputStream->prepareNextBuffer();
4753 }
4754 if (res != OK) {
4755 ALOGW("%s: Preparing video buffers for high speed failed: %s (%d)",
4756 __FUNCTION__, strerror(-res), res);
4757 outputStream->cancelPrepare();
4758 }
4759 }
4760
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07004761 std::vector<size_t> uniqueSurfaceIds;
4762 res = outputStream->getUniqueSurfaceIds(
4763 captureRequest->mOutputSurfaces[streamId],
4764 &uniqueSurfaceIds);
4765 // INVALID_OPERATION is normal output for streams not supporting surfaceIds
4766 if (res != OK && res != INVALID_OPERATION) {
4767 ALOGE("%s: failed to query stream %d unique surface IDs",
4768 __FUNCTION__, streamId);
4769 return res;
4770 }
4771 if (res == OK) {
4772 uniqueSurfaceIdMap.insert({streamId, std::move(uniqueSurfaceIds)});
4773 }
4774
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004775 if (mUseHalBufManager) {
Yin-Chia Yeh110342b2018-11-19 11:47:46 -08004776 if (outputStream->isAbandoned()) {
Yin-Chia Yeha1b56c82019-03-27 15:50:39 -07004777 ALOGV("%s: stream %d is abandoned, skipping request", __FUNCTION__, streamId);
Yin-Chia Yeh110342b2018-11-19 11:47:46 -08004778 return TIMED_OUT;
4779 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004780 // HAL will request buffer through requestStreamBuffer API
Emilian Peevf4816702020-04-03 15:44:51 -07004781 camera_stream_buffer_t& buffer = outputBuffers->editItemAt(j);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004782 buffer.stream = outputStream->asHalStream();
4783 buffer.buffer = nullptr;
Emilian Peevf4816702020-04-03 15:44:51 -07004784 buffer.status = CAMERA_BUFFER_STATUS_OK;
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004785 buffer.acquire_fence = -1;
4786 buffer.release_fence = -1;
Emilian Peevf0348ae2021-01-13 13:39:45 -08004787 // Mark the output stream as unpreparable to block clients from calling
4788 // 'prepare' after this request reaches CameraHal and before the respective
4789 // buffers are requested.
4790 outputStream->markUnpreparable();
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004791 } else {
4792 res = outputStream->getBuffer(&outputBuffers->editItemAt(j),
4793 waitDuration,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07004794 captureRequest->mOutputSurfaces[streamId]);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004795 if (res != OK) {
4796 // Can't get output buffer from gralloc queue - this could be due to
4797 // abandoned queue or other consumer misbehavior, so not a fatal
4798 // error
Yin-Chia Yeha1b56c82019-03-27 15:50:39 -07004799 ALOGV("RequestThread: Can't get output buffer, skipping request:"
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004800 " %s (%d)", strerror(-res), res);
4801
4802 return TIMED_OUT;
4803 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004804 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08004805
4806 {
4807 sp<Camera3Device> parent = mParent.promote();
4808 if (parent != nullptr) {
4809 const String8& streamCameraId = outputStream->getPhysicalCameraId();
4810 for (const auto& settings : captureRequest->mSettingsList) {
4811 if ((streamCameraId.isEmpty() &&
4812 parent->getId() == settings.cameraId.c_str()) ||
4813 streamCameraId == settings.cameraId.c_str()) {
4814 outputStream->fireBufferRequestForFrameNumber(
4815 captureRequest->mResultExtras.frameNumber,
4816 settings.metadata);
4817 }
4818 }
4819 }
4820 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07004821
Shuzhen Wang5c22c152017-12-31 17:12:25 -08004822 String8 physicalCameraId = outputStream->getPhysicalCameraId();
Shuzhen Wang5c22c152017-12-31 17:12:25 -08004823 if (!physicalCameraId.isEmpty()) {
Shuzhen Wang5c22c152017-12-31 17:12:25 -08004824 requestedPhysicalCameras.insert(physicalCameraId);
4825 }
4826 halRequest->num_output_buffers++;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004827 }
4828 totalNumBuffers += halRequest->num_output_buffers;
4829
4830 // Log request in the in-flight queue
Shuzhen Wang4a472662017-02-26 23:29:04 -08004831 // If this request list is for constrained high speed recording (not
4832 // preview), and the current request is not the last one in the batch,
4833 // do not send callback to the app.
4834 bool hasCallback = true;
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07004835 if (batchedRequest && i != mNextRequests.size()-1) {
Shuzhen Wang4a472662017-02-26 23:29:04 -08004836 hasCallback = false;
4837 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01004838 bool isStillCapture = false;
Shuzhen Wang26abaf42018-08-28 15:41:20 -07004839 bool isZslCapture = false;
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08004840 const camera_metadata_t* settings = halRequest->settings;
4841 bool shouldUnlockSettings = false;
4842 if (settings == nullptr) {
4843 shouldUnlockSettings = true;
4844 settings = captureRequest->mSettingsList.begin()->metadata.getAndLock();
4845 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01004846 if (!mNextRequests[0].captureRequest->mSettingsList.begin()->metadata.isEmpty()) {
4847 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08004848 find_camera_metadata_ro_entry(settings, ANDROID_CONTROL_CAPTURE_INTENT, &e);
Emilian Peev9dd21f42018-08-03 13:39:29 +01004849 if ((e.count > 0) && (e.data.u8[0] == ANDROID_CONTROL_CAPTURE_INTENT_STILL_CAPTURE)) {
4850 isStillCapture = true;
4851 ATRACE_ASYNC_BEGIN("still capture", mNextRequests[i].halRequest.frame_number);
4852 }
Shuzhen Wang26abaf42018-08-28 15:41:20 -07004853
Emilian Peevaf8416e2021-02-04 17:52:43 -08004854 e = camera_metadata_ro_entry_t();
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08004855 find_camera_metadata_ro_entry(settings, ANDROID_CONTROL_ENABLE_ZSL, &e);
Shuzhen Wang26abaf42018-08-28 15:41:20 -07004856 if ((e.count > 0) && (e.data.u8[0] == ANDROID_CONTROL_ENABLE_ZSL_TRUE)) {
4857 isZslCapture = true;
4858 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01004859 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004860 res = parent->registerInFlight(halRequest->frame_number,
4861 totalNumBuffers, captureRequest->mResultExtras,
4862 /*hasInput*/halRequest->input_buffer != NULL,
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07004863 hasCallback,
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08004864 calculateMaxExpectedDuration(settings),
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004865 requestedPhysicalCameras, isStillCapture, isZslCapture,
4866 captureRequest->mRotateAndCropAuto, mPrevCameraIdsWithZoom,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07004867 (mUseHalBufManager) ? uniqueSurfaceIdMap :
Shuzhen Wang316781a2020-08-18 18:11:01 -07004868 SurfaceMap{}, captureRequest->mRequestTimeNs);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004869 ALOGVV("%s: registered in flight requestId = %" PRId32 ", frameNumber = %" PRId64
4870 ", burstId = %" PRId32 ".",
4871 __FUNCTION__,
4872 captureRequest->mResultExtras.requestId, captureRequest->mResultExtras.frameNumber,
4873 captureRequest->mResultExtras.burstId);
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08004874
4875 if (shouldUnlockSettings) {
4876 captureRequest->mSettingsList.begin()->metadata.unlock(settings);
4877 }
4878
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004879 if (res != OK) {
4880 SET_ERR("RequestThread: Unable to register new in-flight request:"
4881 " %s (%d)", strerror(-res), res);
4882 return INVALID_OPERATION;
4883 }
4884 }
4885
4886 return OK;
4887}
4888
Igor Murashkin1e479c02013-09-06 16:55:14 -07004889CameraMetadata Camera3Device::RequestThread::getLatestRequest() const {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004890 ATRACE_CALL();
Igor Murashkin1e479c02013-09-06 16:55:14 -07004891 Mutex::Autolock al(mLatestRequestMutex);
4892
4893 ALOGV("RequestThread::%s", __FUNCTION__);
4894
4895 return mLatestRequest;
4896}
4897
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004898bool Camera3Device::RequestThread::isStreamPending(
4899 sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004900 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004901 Mutex::Autolock l(mRequestLock);
4902
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004903 for (const auto& nextRequest : mNextRequests) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004904 if (!nextRequest.submitted) {
4905 for (const auto& s : nextRequest.captureRequest->mOutputStreams) {
4906 if (stream == s) return true;
4907 }
4908 if (stream == nextRequest.captureRequest->mInputStream) return true;
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004909 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004910 }
4911
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004912 for (const auto& request : mRequestQueue) {
4913 for (const auto& s : request->mOutputStreams) {
4914 if (stream == s) return true;
4915 }
4916 if (stream == request->mInputStream) return true;
4917 }
4918
4919 for (const auto& request : mRepeatingRequests) {
4920 for (const auto& s : request->mOutputStreams) {
4921 if (stream == s) return true;
4922 }
4923 if (stream == request->mInputStream) return true;
4924 }
4925
4926 return false;
4927}
Jianing Weicb0652e2014-03-12 18:29:36 -07004928
Emilian Peev40ead602017-09-26 15:46:36 +01004929bool Camera3Device::RequestThread::isOutputSurfacePending(int streamId, size_t surfaceId) {
4930 ATRACE_CALL();
4931 Mutex::Autolock l(mRequestLock);
4932
4933 for (const auto& nextRequest : mNextRequests) {
4934 for (const auto& s : nextRequest.captureRequest->mOutputSurfaces) {
4935 if (s.first == streamId) {
4936 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
4937 if (it != s.second.end()) {
4938 return true;
4939 }
4940 }
4941 }
4942 }
4943
4944 for (const auto& request : mRequestQueue) {
4945 for (const auto& s : request->mOutputSurfaces) {
4946 if (s.first == streamId) {
4947 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
4948 if (it != s.second.end()) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07004949 return true;
Emilian Peev40ead602017-09-26 15:46:36 +01004950 }
4951 }
4952 }
4953 }
4954
4955 for (const auto& request : mRepeatingRequests) {
4956 for (const auto& s : request->mOutputSurfaces) {
4957 if (s.first == streamId) {
4958 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
4959 if (it != s.second.end()) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07004960 return true;
Emilian Peev40ead602017-09-26 15:46:36 +01004961 }
4962 }
4963 }
4964 }
4965
4966 return false;
4967}
4968
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004969void Camera3Device::RequestThread::signalPipelineDrain(const std::vector<int>& streamIds) {
4970 if (!mUseHalBufManager) {
4971 ALOGE("%s called for camera device not supporting HAL buffer management", __FUNCTION__);
4972 return;
4973 }
4974
4975 Mutex::Autolock pl(mPauseLock);
4976 if (mPaused) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07004977 mInterface->signalPipelineDrain(streamIds);
4978 return;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004979 }
4980 // If request thread is still busy, wait until paused then notify HAL
4981 mNotifyPipelineDrain = true;
4982 mStreamIdsToBeDrained = streamIds;
4983}
4984
Yin-Chia Yehe52b8fa2020-07-28 00:17:58 -07004985void Camera3Device::RequestThread::resetPipelineDrain() {
4986 Mutex::Autolock pl(mPauseLock);
4987 mNotifyPipelineDrain = false;
4988 mStreamIdsToBeDrained.clear();
4989}
4990
Emilian Peevc0fe54c2020-03-11 14:05:07 -07004991void Camera3Device::RequestThread::clearPreviousRequest() {
4992 Mutex::Autolock l(mRequestLock);
4993 mPrevRequest.clear();
4994}
4995
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004996status_t Camera3Device::RequestThread::switchToOffline(
4997 const std::vector<int32_t>& streamsToKeep,
4998 /*out*/hardware::camera::device::V3_6::CameraOfflineSessionInfo* offlineSessionInfo,
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004999 /*out*/sp<hardware::camera::device::V3_6::ICameraOfflineSession>* offlineSession,
5000 /*out*/camera3::BufferRecords* bufferRecords) {
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005001 Mutex::Autolock l(mRequestLock);
5002 clearRepeatingRequestsLocked(/*lastFrameNumber*/nullptr);
5003
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005004 // Wait until request thread is fully stopped
5005 // TBD: check if request thread is being paused by other APIs (shouldn't be)
5006
5007 // We could also check for mRepeatingRequests.empty(), but the API interface
5008 // is serialized by Camera3Device::mInterfaceLock so no one should be able to submit any
5009 // new requests during the call; hence skip that check.
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005010 bool queueEmpty = mNextRequests.empty() && mRequestQueue.empty();
5011 while (!queueEmpty) {
5012 status_t res = mRequestSubmittedSignal.waitRelative(mRequestLock, kRequestSubmitTimeout);
5013 if (res == TIMED_OUT) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005014 ALOGE("%s: request thread failed to submit one request within timeout!", __FUNCTION__);
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005015 return res;
5016 } else if (res != OK) {
5017 ALOGE("%s: request thread failed to submit a request: %s (%d)!",
5018 __FUNCTION__, strerror(-res), res);
5019 return res;
5020 }
5021 queueEmpty = mNextRequests.empty() && mRequestQueue.empty();
5022 }
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005023
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005024 return mInterface->switchToOffline(
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005025 streamsToKeep, offlineSessionInfo, offlineSession, bufferRecords);
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005026}
5027
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005028status_t Camera3Device::RequestThread::setRotateAndCropAutoBehavior(
5029 camera_metadata_enum_android_scaler_rotate_and_crop_t rotateAndCropValue) {
5030 ATRACE_CALL();
5031 Mutex::Autolock l(mTriggerMutex);
5032 if (rotateAndCropValue == ANDROID_SCALER_ROTATE_AND_CROP_AUTO) {
5033 return BAD_VALUE;
5034 }
5035 mRotateAndCropOverride = rotateAndCropValue;
5036 return OK;
5037}
5038
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005039status_t Camera3Device::RequestThread::setCameraMute(bool enabled) {
5040 ATRACE_CALL();
5041 Mutex::Autolock l(mTriggerMutex);
5042 if (enabled != mCameraMute) {
5043 mCameraMute = enabled;
5044 mCameraMuteChanged = true;
5045 }
5046 return OK;
5047}
5048
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07005049nsecs_t Camera3Device::getExpectedInFlightDuration() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005050 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005051 std::lock_guard<std::mutex> l(mInFlightLock);
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07005052 return mExpectedInflightDuration > kMinInflightDuration ?
5053 mExpectedInflightDuration : kMinInflightDuration;
5054}
5055
Emilian Peevaebbe412018-01-15 13:53:24 +00005056void Camera3Device::RequestThread::cleanupPhysicalSettings(sp<CaptureRequest> request,
Emilian Peevf4816702020-04-03 15:44:51 -07005057 camera_capture_request_t *halRequest) {
Emilian Peevaebbe412018-01-15 13:53:24 +00005058 if ((request == nullptr) || (halRequest == nullptr)) {
5059 ALOGE("%s: Invalid request!", __FUNCTION__);
5060 return;
5061 }
5062
5063 if (halRequest->num_physcam_settings > 0) {
5064 if (halRequest->physcam_id != nullptr) {
5065 delete [] halRequest->physcam_id;
5066 halRequest->physcam_id = nullptr;
5067 }
5068 if (halRequest->physcam_settings != nullptr) {
5069 auto it = ++(request->mSettingsList.begin());
5070 size_t i = 0;
5071 for (; it != request->mSettingsList.end(); it++, i++) {
5072 it->metadata.unlock(halRequest->physcam_settings[i]);
5073 }
5074 delete [] halRequest->physcam_settings;
5075 halRequest->physcam_settings = nullptr;
5076 }
5077 }
5078}
5079
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005080void Camera3Device::RequestThread::cleanUpFailedRequests(bool sendRequestError) {
5081 if (mNextRequests.empty()) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005082 return;
5083 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005084
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005085 for (auto& nextRequest : mNextRequests) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005086 // Skip the ones that have been submitted successfully.
5087 if (nextRequest.submitted) {
5088 continue;
5089 }
5090
5091 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
Emilian Peevf4816702020-04-03 15:44:51 -07005092 camera_capture_request_t* halRequest = &nextRequest.halRequest;
5093 Vector<camera_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005094
5095 if (halRequest->settings != NULL) {
Emilian Peevaebbe412018-01-15 13:53:24 +00005096 captureRequest->mSettingsList.begin()->metadata.unlock(halRequest->settings);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005097 }
5098
Emilian Peevaebbe412018-01-15 13:53:24 +00005099 cleanupPhysicalSettings(captureRequest, halRequest);
5100
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005101 if (captureRequest->mInputStream != NULL) {
Emilian Peevf4816702020-04-03 15:44:51 -07005102 captureRequest->mInputBuffer.status = CAMERA_BUFFER_STATUS_ERROR;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005103 captureRequest->mInputStream->returnInputBuffer(captureRequest->mInputBuffer);
5104 }
5105
Yin-Chia Yeh21cb47b2019-01-18 15:08:17 -08005106 // No output buffer can be returned when using HAL buffer manager
5107 if (!mUseHalBufManager) {
5108 for (size_t i = 0; i < halRequest->num_output_buffers; i++) {
5109 //Buffers that failed processing could still have
5110 //valid acquire fence.
5111 int acquireFence = (*outputBuffers)[i].acquire_fence;
5112 if (0 <= acquireFence) {
5113 close(acquireFence);
5114 outputBuffers->editItemAt(i).acquire_fence = -1;
5115 }
Emilian Peevf4816702020-04-03 15:44:51 -07005116 outputBuffers->editItemAt(i).status = CAMERA_BUFFER_STATUS_ERROR;
Yin-Chia Yeh21cb47b2019-01-18 15:08:17 -08005117 captureRequest->mOutputStreams.editItemAt(i)->returnBuffer((*outputBuffers)[i], 0,
5118 /*timestampIncreasing*/true, std::vector<size_t> (),
5119 captureRequest->mResultExtras.frameNumber);
Emilian Peevc58cf4c2017-05-11 17:23:41 +01005120 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005121 }
5122
5123 if (sendRequestError) {
5124 Mutex::Autolock l(mRequestLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005125 sp<NotificationListener> listener = mListener.promote();
5126 if (listener != NULL) {
5127 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08005128 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005129 captureRequest->mResultExtras);
5130 }
5131 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07005132
5133 // Remove yet-to-be submitted inflight request from inflightMap
5134 {
5135 sp<Camera3Device> parent = mParent.promote();
5136 if (parent != NULL) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005137 std::lock_guard<std::mutex> l(parent->mInFlightLock);
Shuzhen Wangcadb3302016-11-04 14:17:56 -07005138 ssize_t idx = parent->mInFlightMap.indexOfKey(captureRequest->mResultExtras.frameNumber);
5139 if (idx >= 0) {
5140 ALOGV("%s: Remove inflight request from queue: frameNumber %" PRId64,
5141 __FUNCTION__, captureRequest->mResultExtras.frameNumber);
5142 parent->removeInFlightMapEntryLocked(idx);
5143 }
5144 }
5145 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005146 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07005147
5148 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005149 mNextRequests.clear();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005150}
5151
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005152void Camera3Device::RequestThread::waitForNextRequestBatch() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005153 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005154 // Optimized a bit for the simple steady-state case (single repeating
5155 // request), to avoid putting that request in the queue temporarily.
5156 Mutex::Autolock l(mRequestLock);
5157
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005158 assert(mNextRequests.empty());
5159
5160 NextRequest nextRequest;
5161 nextRequest.captureRequest = waitForNextRequestLocked();
5162 if (nextRequest.captureRequest == nullptr) {
5163 return;
5164 }
5165
Emilian Peevf4816702020-04-03 15:44:51 -07005166 nextRequest.halRequest = camera_capture_request_t();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005167 nextRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005168 mNextRequests.add(nextRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005169
5170 // Wait for additional requests
5171 const size_t batchSize = nextRequest.captureRequest->mBatchSize;
5172
5173 for (size_t i = 1; i < batchSize; i++) {
5174 NextRequest additionalRequest;
5175 additionalRequest.captureRequest = waitForNextRequestLocked();
5176 if (additionalRequest.captureRequest == nullptr) {
5177 break;
5178 }
5179
Emilian Peevf4816702020-04-03 15:44:51 -07005180 additionalRequest.halRequest = camera_capture_request_t();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005181 additionalRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005182 mNextRequests.add(additionalRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005183 }
5184
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005185 if (mNextRequests.size() < batchSize) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08005186 ALOGE("RequestThread: only get %zu out of %zu requests. Skipping requests.",
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005187 mNextRequests.size(), batchSize);
5188 cleanUpFailedRequests(/*sendRequestError*/true);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005189 }
5190
5191 return;
5192}
5193
5194sp<Camera3Device::CaptureRequest>
5195 Camera3Device::RequestThread::waitForNextRequestLocked() {
5196 status_t res;
5197 sp<CaptureRequest> nextRequest;
5198
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005199 while (mRequestQueue.empty()) {
5200 if (!mRepeatingRequests.empty()) {
5201 // Always atomically enqueue all requests in a repeating request
5202 // list. Guarantees a complete in-sequence set of captures to
5203 // application.
5204 const RequestList &requests = mRepeatingRequests;
Shuzhen Wang316781a2020-08-18 18:11:01 -07005205 if (mFirstRepeating) {
5206 mFirstRepeating = false;
5207 } else {
5208 for (auto& request : requests) {
5209 // For repeating requests, override timestamp request using
5210 // the time a request is inserted into the request queue,
5211 // because the original repeating request will have an old
5212 // fixed timestamp.
5213 request->mRequestTimeNs = systemTime();
5214 }
5215 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005216 RequestList::const_iterator firstRequest =
5217 requests.begin();
5218 nextRequest = *firstRequest;
5219 mRequestQueue.insert(mRequestQueue.end(),
5220 ++firstRequest,
5221 requests.end());
5222 // No need to wait any longer
Jianing Weicb0652e2014-03-12 18:29:36 -07005223
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005224 mRepeatingLastFrameNumber = mFrameNumber + requests.size() - 1;
Jianing Weicb0652e2014-03-12 18:29:36 -07005225
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005226 break;
5227 }
5228
5229 res = mRequestSignal.waitRelative(mRequestLock, kRequestTimeout);
5230
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005231 if ((mRequestQueue.empty() && mRepeatingRequests.empty()) ||
5232 exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005233 Mutex::Autolock pl(mPauseLock);
5234 if (mPaused == false) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005235 ALOGV("%s: RequestThread: Going idle", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005236 mPaused = true;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07005237 if (mNotifyPipelineDrain) {
5238 mInterface->signalPipelineDrain(mStreamIdsToBeDrained);
5239 mNotifyPipelineDrain = false;
5240 mStreamIdsToBeDrained.clear();
5241 }
Yin-Chia Yehc300a072019-02-13 14:56:57 -08005242 // Let the tracker know
5243 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5244 if (statusTracker != 0) {
5245 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
5246 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005247 sp<Camera3Device> parent = mParent.promote();
5248 if (parent != nullptr) {
5249 parent->mRequestBufferSM.onRequestThreadPaused();
5250 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005251 }
5252 // Stop waiting for now and let thread management happen
5253 return NULL;
5254 }
5255 }
5256
5257 if (nextRequest == NULL) {
5258 // Don't have a repeating request already in hand, so queue
5259 // must have an entry now.
5260 RequestList::iterator firstRequest =
5261 mRequestQueue.begin();
5262 nextRequest = *firstRequest;
5263 mRequestQueue.erase(firstRequest);
Shuzhen Wang9d066012016-09-30 11:30:20 -07005264 if (mRequestQueue.empty() && !nextRequest->mRepeating) {
5265 sp<NotificationListener> listener = mListener.promote();
5266 if (listener != NULL) {
5267 listener->notifyRequestQueueEmpty();
5268 }
5269 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005270 }
5271
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005272 // In case we've been unpaused by setPaused clearing mDoPause, need to
5273 // update internal pause state (capture/setRepeatingRequest unpause
5274 // directly).
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005275 Mutex::Autolock pl(mPauseLock);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005276 if (mPaused) {
5277 ALOGV("%s: RequestThread: Unpaused", __FUNCTION__);
5278 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5279 if (statusTracker != 0) {
5280 statusTracker->markComponentActive(mStatusId);
5281 }
5282 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005283 mPaused = false;
5284
5285 // Check if we've reconfigured since last time, and reset the preview
5286 // request if so. Can't use 'NULL request == repeat' across configure calls.
5287 if (mReconfigured) {
5288 mPrevRequest.clear();
5289 mReconfigured = false;
5290 }
5291
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005292 if (nextRequest != NULL) {
5293 nextRequest->mResultExtras.frameNumber = mFrameNumber++;
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07005294 nextRequest->mResultExtras.afTriggerId = mCurrentAfTriggerId;
5295 nextRequest->mResultExtras.precaptureTriggerId = mCurrentPreCaptureTriggerId;
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07005296
5297 // Since RequestThread::clear() removes buffers from the input stream,
5298 // get the right buffer here before unlocking mRequestLock
5299 if (nextRequest->mInputStream != NULL) {
Shuzhen Wang83bff122020-11-20 15:51:39 -08005300 res = nextRequest->mInputStream->getInputBuffer(&nextRequest->mInputBuffer,
5301 &nextRequest->mInputBufferSize);
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07005302 if (res != OK) {
5303 // Can't get input buffer from gralloc queue - this could be due to
5304 // disconnected queue or other producer misbehavior, so not a fatal
5305 // error
5306 ALOGE("%s: Can't get input buffer, skipping request:"
5307 " %s (%d)", __FUNCTION__, strerror(-res), res);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005308
5309 sp<NotificationListener> listener = mListener.promote();
5310 if (listener != NULL) {
5311 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08005312 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07005313 nextRequest->mResultExtras);
5314 }
5315 return NULL;
5316 }
5317 }
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005318 }
Chien-Yu Chend196d612015-06-22 19:49:01 -07005319
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005320 return nextRequest;
5321}
5322
5323bool Camera3Device::RequestThread::waitIfPaused() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005324 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005325 status_t res;
5326 Mutex::Autolock l(mPauseLock);
5327 while (mDoPause) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005328 if (mPaused == false) {
5329 mPaused = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005330 ALOGV("%s: RequestThread: Paused", __FUNCTION__);
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07005331 if (mNotifyPipelineDrain) {
5332 mInterface->signalPipelineDrain(mStreamIdsToBeDrained);
5333 mNotifyPipelineDrain = false;
5334 mStreamIdsToBeDrained.clear();
5335 }
Yin-Chia Yehc300a072019-02-13 14:56:57 -08005336 // Let the tracker know
5337 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5338 if (statusTracker != 0) {
5339 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
5340 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005341 sp<Camera3Device> parent = mParent.promote();
5342 if (parent != nullptr) {
5343 parent->mRequestBufferSM.onRequestThreadPaused();
5344 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005345 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005346
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005347 res = mDoPauseSignal.waitRelative(mPauseLock, kRequestTimeout);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005348 if (res == TIMED_OUT || exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005349 return true;
5350 }
5351 }
5352 // We don't set mPaused to false here, because waitForNextRequest needs
5353 // to further manage the paused state in case of starvation.
5354 return false;
5355}
5356
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005357void Camera3Device::RequestThread::unpauseForNewRequests() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005358 ATRACE_CALL();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005359 // With work to do, mark thread as unpaused.
5360 // If paused by request (setPaused), don't resume, to avoid
5361 // extra signaling/waiting overhead to waitUntilPaused
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005362 mRequestSignal.signal();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005363 Mutex::Autolock p(mPauseLock);
5364 if (!mDoPause) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005365 ALOGV("%s: RequestThread: Going active", __FUNCTION__);
5366 if (mPaused) {
5367 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5368 if (statusTracker != 0) {
5369 statusTracker->markComponentActive(mStatusId);
5370 }
5371 }
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005372 mPaused = false;
5373 }
5374}
5375
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07005376void Camera3Device::RequestThread::setErrorState(const char *fmt, ...) {
5377 sp<Camera3Device> parent = mParent.promote();
5378 if (parent != NULL) {
5379 va_list args;
5380 va_start(args, fmt);
5381
5382 parent->setErrorStateV(fmt, args);
5383
5384 va_end(args);
5385 }
5386}
5387
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005388status_t Camera3Device::RequestThread::insertTriggers(
5389 const sp<CaptureRequest> &request) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005390 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005391 Mutex::Autolock al(mTriggerMutex);
5392
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07005393 sp<Camera3Device> parent = mParent.promote();
5394 if (parent == NULL) {
5395 CLOGE("RequestThread: Parent is gone");
5396 return DEAD_OBJECT;
5397 }
5398
Emilian Peevaebbe412018-01-15 13:53:24 +00005399 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005400 size_t count = mTriggerMap.size();
5401
5402 for (size_t i = 0; i < count; ++i) {
5403 RequestTrigger trigger = mTriggerMap.valueAt(i);
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005404 uint32_t tag = trigger.metadataTag;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07005405
5406 if (tag == ANDROID_CONTROL_AF_TRIGGER_ID || tag == ANDROID_CONTROL_AE_PRECAPTURE_ID) {
5407 bool isAeTrigger = (trigger.metadataTag == ANDROID_CONTROL_AE_PRECAPTURE_ID);
5408 uint32_t triggerId = static_cast<uint32_t>(trigger.entryValue);
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07005409 if (isAeTrigger) {
5410 request->mResultExtras.precaptureTriggerId = triggerId;
5411 mCurrentPreCaptureTriggerId = triggerId;
5412 } else {
5413 request->mResultExtras.afTriggerId = triggerId;
5414 mCurrentAfTriggerId = triggerId;
5415 }
Emilian Peev7e25e5e2017-04-07 15:48:49 +01005416 continue;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07005417 }
5418
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005419 camera_metadata_entry entry = metadata.find(tag);
5420
5421 if (entry.count > 0) {
5422 /**
5423 * Already has an entry for this trigger in the request.
5424 * Rewrite it with our requested trigger value.
5425 */
5426 RequestTrigger oldTrigger = trigger;
5427
5428 oldTrigger.entryValue = entry.data.u8[0];
5429
5430 mTriggerReplacedMap.add(tag, oldTrigger);
5431 } else {
5432 /**
5433 * More typical, no trigger entry, so we just add it
5434 */
5435 mTriggerRemovedMap.add(tag, trigger);
5436 }
5437
5438 status_t res;
5439
5440 switch (trigger.getTagType()) {
5441 case TYPE_BYTE: {
5442 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
5443 res = metadata.update(tag,
5444 &entryValue,
5445 /*count*/1);
5446 break;
5447 }
5448 case TYPE_INT32:
5449 res = metadata.update(tag,
5450 &trigger.entryValue,
5451 /*count*/1);
5452 break;
5453 default:
5454 ALOGE("%s: Type not supported: 0x%x",
5455 __FUNCTION__,
5456 trigger.getTagType());
5457 return INVALID_OPERATION;
5458 }
5459
5460 if (res != OK) {
5461 ALOGE("%s: Failed to update request metadata with trigger tag %s"
5462 ", value %d", __FUNCTION__, trigger.getTagName(),
5463 trigger.entryValue);
5464 return res;
5465 }
5466
5467 ALOGV("%s: Mixed in trigger %s, value %d", __FUNCTION__,
5468 trigger.getTagName(),
5469 trigger.entryValue);
5470 }
5471
5472 mTriggerMap.clear();
5473
5474 return count;
5475}
5476
5477status_t Camera3Device::RequestThread::removeTriggers(
5478 const sp<CaptureRequest> &request) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005479 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005480 Mutex::Autolock al(mTriggerMutex);
5481
Emilian Peevaebbe412018-01-15 13:53:24 +00005482 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005483
5484 /**
5485 * Replace all old entries with their old values.
5486 */
5487 for (size_t i = 0; i < mTriggerReplacedMap.size(); ++i) {
5488 RequestTrigger trigger = mTriggerReplacedMap.valueAt(i);
5489
5490 status_t res;
5491
5492 uint32_t tag = trigger.metadataTag;
5493 switch (trigger.getTagType()) {
5494 case TYPE_BYTE: {
5495 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
5496 res = metadata.update(tag,
5497 &entryValue,
5498 /*count*/1);
5499 break;
5500 }
5501 case TYPE_INT32:
5502 res = metadata.update(tag,
5503 &trigger.entryValue,
5504 /*count*/1);
5505 break;
5506 default:
5507 ALOGE("%s: Type not supported: 0x%x",
5508 __FUNCTION__,
5509 trigger.getTagType());
5510 return INVALID_OPERATION;
5511 }
5512
5513 if (res != OK) {
5514 ALOGE("%s: Failed to restore request metadata with trigger tag %s"
5515 ", trigger value %d", __FUNCTION__,
5516 trigger.getTagName(), trigger.entryValue);
5517 return res;
5518 }
5519 }
5520 mTriggerReplacedMap.clear();
5521
5522 /**
5523 * Remove all new entries.
5524 */
5525 for (size_t i = 0; i < mTriggerRemovedMap.size(); ++i) {
5526 RequestTrigger trigger = mTriggerRemovedMap.valueAt(i);
5527 status_t res = metadata.erase(trigger.metadataTag);
5528
5529 if (res != OK) {
5530 ALOGE("%s: Failed to erase metadata with trigger tag %s"
5531 ", trigger value %d", __FUNCTION__,
5532 trigger.getTagName(), trigger.entryValue);
5533 return res;
5534 }
5535 }
5536 mTriggerRemovedMap.clear();
5537
5538 return OK;
5539}
5540
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04005541status_t Camera3Device::RequestThread::addFakeTriggerIds(
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005542 const sp<CaptureRequest> &request) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08005543 // Trigger ID 0 had special meaning in the HAL2 spec, so avoid it here
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04005544 static const int32_t fakeTriggerId = 1;
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005545 status_t res;
5546
Emilian Peevaebbe412018-01-15 13:53:24 +00005547 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005548
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04005549 // If AF trigger is active, insert a fake AF trigger ID if none already
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005550 // exists
5551 camera_metadata_entry afTrigger = metadata.find(ANDROID_CONTROL_AF_TRIGGER);
5552 camera_metadata_entry afId = metadata.find(ANDROID_CONTROL_AF_TRIGGER_ID);
5553 if (afTrigger.count > 0 &&
5554 afTrigger.data.u8[0] != ANDROID_CONTROL_AF_TRIGGER_IDLE &&
5555 afId.count == 0) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04005556 res = metadata.update(ANDROID_CONTROL_AF_TRIGGER_ID, &fakeTriggerId, 1);
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005557 if (res != OK) return res;
5558 }
5559
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04005560 // If AE precapture trigger is active, insert a fake precapture trigger ID
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005561 // if none already exists
5562 camera_metadata_entry pcTrigger =
5563 metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER);
5564 camera_metadata_entry pcId = metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_ID);
5565 if (pcTrigger.count > 0 &&
5566 pcTrigger.data.u8[0] != ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_IDLE &&
5567 pcId.count == 0) {
5568 res = metadata.update(ANDROID_CONTROL_AE_PRECAPTURE_ID,
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04005569 &fakeTriggerId, 1);
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005570 if (res != OK) return res;
5571 }
5572
5573 return OK;
5574}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005575
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005576bool Camera3Device::RequestThread::overrideAutoRotateAndCrop(
5577 const sp<CaptureRequest> &request) {
5578 ATRACE_CALL();
5579
5580 if (request->mRotateAndCropAuto) {
5581 Mutex::Autolock l(mTriggerMutex);
5582 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
5583
5584 auto rotateAndCropEntry = metadata.find(ANDROID_SCALER_ROTATE_AND_CROP);
5585 if (rotateAndCropEntry.count > 0) {
5586 if (rotateAndCropEntry.data.u8[0] == mRotateAndCropOverride) {
5587 return false;
5588 } else {
5589 rotateAndCropEntry.data.u8[0] = mRotateAndCropOverride;
5590 return true;
5591 }
5592 } else {
5593 uint8_t rotateAndCrop_u8 = mRotateAndCropOverride;
5594 metadata.update(ANDROID_SCALER_ROTATE_AND_CROP,
5595 &rotateAndCrop_u8, 1);
5596 return true;
5597 }
5598 }
5599 return false;
5600}
5601
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005602bool Camera3Device::RequestThread::overrideTestPattern(
5603 const sp<CaptureRequest> &request) {
5604 ATRACE_CALL();
5605
5606 Mutex::Autolock l(mTriggerMutex);
5607
5608 bool changed = false;
5609
5610 int32_t testPatternMode = request->mOriginalTestPatternMode;
5611 int32_t testPatternData[4] = {
5612 request->mOriginalTestPatternData[0],
5613 request->mOriginalTestPatternData[1],
5614 request->mOriginalTestPatternData[2],
5615 request->mOriginalTestPatternData[3]
5616 };
5617
5618 if (mCameraMute) {
5619 testPatternMode = ANDROID_SENSOR_TEST_PATTERN_MODE_SOLID_COLOR;
5620 testPatternData[0] = 0;
5621 testPatternData[1] = 0;
5622 testPatternData[2] = 0;
5623 testPatternData[3] = 0;
5624 }
5625
5626 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
5627
5628 auto testPatternEntry = metadata.find(ANDROID_SENSOR_TEST_PATTERN_MODE);
5629 if (testPatternEntry.count > 0) {
5630 if (testPatternEntry.data.i32[0] != testPatternMode) {
5631 testPatternEntry.data.i32[0] = testPatternMode;
5632 changed = true;
5633 }
5634 } else {
5635 metadata.update(ANDROID_SENSOR_TEST_PATTERN_MODE,
5636 &testPatternMode, 1);
5637 changed = true;
5638 }
5639
5640 auto testPatternColor = metadata.find(ANDROID_SENSOR_TEST_PATTERN_DATA);
5641 if (testPatternColor.count > 0) {
5642 for (size_t i = 0; i < 4; i++) {
5643 if (testPatternColor.data.i32[i] != (int32_t)testPatternData[i]) {
5644 testPatternColor.data.i32[i] = testPatternData[i];
5645 changed = true;
5646 }
5647 }
5648 } else {
5649 metadata.update(ANDROID_SENSOR_TEST_PATTERN_DATA,
5650 (int32_t*)testPatternData, 4);
5651 changed = true;
5652 }
5653
5654 return changed;
5655}
5656
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005657/**
5658 * PreparerThread inner class methods
5659 */
5660
5661Camera3Device::PreparerThread::PreparerThread() :
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07005662 Thread(/*canCallJava*/false), mListener(nullptr),
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005663 mActive(false), mCancelNow(false), mCurrentMaxCount(0), mCurrentPrepareComplete(false) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005664}
5665
5666Camera3Device::PreparerThread::~PreparerThread() {
5667 Thread::requestExitAndWait();
5668 if (mCurrentStream != nullptr) {
5669 mCurrentStream->cancelPrepare();
5670 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
5671 mCurrentStream.clear();
5672 }
5673 clear();
5674}
5675
Ruben Brunkc78ac262015-08-13 17:58:46 -07005676status_t Camera3Device::PreparerThread::prepare(int maxCount, sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005677 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005678 status_t res;
5679
5680 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005681 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005682
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07005683 res = stream->startPrepare(maxCount, true /*blockRequest*/);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005684 if (res == OK) {
5685 // No preparation needed, fire listener right off
5686 ALOGV("%s: Stream %d already prepared", __FUNCTION__, stream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005687 if (listener != NULL) {
5688 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005689 }
5690 return OK;
5691 } else if (res != NOT_ENOUGH_DATA) {
5692 return res;
5693 }
5694
5695 // Need to prepare, start up thread if necessary
5696 if (!mActive) {
5697 // mRunning will change to false before the thread fully shuts down, so wait to be sure it
5698 // isn't running
5699 Thread::requestExitAndWait();
5700 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
5701 if (res != OK) {
5702 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__, res, strerror(-res));
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005703 if (listener != NULL) {
5704 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005705 }
5706 return res;
5707 }
5708 mCancelNow = false;
5709 mActive = true;
5710 ALOGV("%s: Preparer stream started", __FUNCTION__);
5711 }
5712
5713 // queue up the work
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005714 mPendingStreams.emplace(maxCount, stream);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005715 ALOGV("%s: Stream %d queued for preparing", __FUNCTION__, stream->getId());
5716
5717 return OK;
5718}
5719
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005720void Camera3Device::PreparerThread::pause() {
5721 ATRACE_CALL();
5722
5723 Mutex::Autolock l(mLock);
5724
5725 std::unordered_map<int, sp<camera3::Camera3StreamInterface> > pendingStreams;
5726 pendingStreams.insert(mPendingStreams.begin(), mPendingStreams.end());
5727 sp<camera3::Camera3StreamInterface> currentStream = mCurrentStream;
5728 int currentMaxCount = mCurrentMaxCount;
5729 mPendingStreams.clear();
5730 mCancelNow = true;
5731 while (mActive) {
5732 auto res = mThreadActiveSignal.waitRelative(mLock, kActiveTimeout);
5733 if (res == TIMED_OUT) {
5734 ALOGE("%s: Timed out waiting on prepare thread!", __FUNCTION__);
5735 return;
5736 } else if (res != OK) {
5737 ALOGE("%s: Encountered an error: %d waiting on prepare thread!", __FUNCTION__, res);
5738 return;
5739 }
5740 }
5741
5742 //Check whether the prepare thread was able to complete the current
5743 //stream. In case work is still pending emplace it along with the rest
5744 //of the streams in the pending list.
5745 if (currentStream != nullptr) {
5746 if (!mCurrentPrepareComplete) {
5747 pendingStreams.emplace(currentMaxCount, currentStream);
5748 }
5749 }
5750
5751 mPendingStreams.insert(pendingStreams.begin(), pendingStreams.end());
5752 for (const auto& it : mPendingStreams) {
5753 it.second->cancelPrepare();
5754 }
5755}
5756
5757status_t Camera3Device::PreparerThread::resume() {
5758 ATRACE_CALL();
5759 status_t res;
5760
5761 Mutex::Autolock l(mLock);
5762 sp<NotificationListener> listener = mListener.promote();
5763
5764 if (mActive) {
5765 ALOGE("%s: Trying to resume an already active prepare thread!", __FUNCTION__);
5766 return NO_INIT;
5767 }
5768
5769 auto it = mPendingStreams.begin();
5770 for (; it != mPendingStreams.end();) {
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07005771 res = it->second->startPrepare(it->first, true /*blockRequest*/);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005772 if (res == OK) {
5773 if (listener != NULL) {
5774 listener->notifyPrepared(it->second->getId());
5775 }
5776 it = mPendingStreams.erase(it);
5777 } else if (res != NOT_ENOUGH_DATA) {
5778 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__,
5779 res, strerror(-res));
5780 it = mPendingStreams.erase(it);
5781 } else {
5782 it++;
5783 }
5784 }
5785
5786 if (mPendingStreams.empty()) {
5787 return OK;
5788 }
5789
5790 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
5791 if (res != OK) {
5792 ALOGE("%s: Unable to start preparer stream: %d (%s)",
5793 __FUNCTION__, res, strerror(-res));
5794 return res;
5795 }
5796 mCancelNow = false;
5797 mActive = true;
5798 ALOGV("%s: Preparer stream started", __FUNCTION__);
5799
5800 return OK;
5801}
5802
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005803status_t Camera3Device::PreparerThread::clear() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005804 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005805 Mutex::Autolock l(mLock);
5806
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005807 for (const auto& it : mPendingStreams) {
5808 it.second->cancelPrepare();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005809 }
5810 mPendingStreams.clear();
5811 mCancelNow = true;
5812
5813 return OK;
5814}
5815
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005816void Camera3Device::PreparerThread::setNotificationListener(wp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005817 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005818 Mutex::Autolock l(mLock);
5819 mListener = listener;
5820}
5821
5822bool Camera3Device::PreparerThread::threadLoop() {
5823 status_t res;
5824 {
5825 Mutex::Autolock l(mLock);
5826 if (mCurrentStream == nullptr) {
5827 // End thread if done with work
5828 if (mPendingStreams.empty()) {
5829 ALOGV("%s: Preparer stream out of work", __FUNCTION__);
5830 // threadLoop _must not_ re-acquire mLock after it sets mActive to false; would
5831 // cause deadlock with prepare()'s requestExitAndWait triggered by !mActive.
5832 mActive = false;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005833 mThreadActiveSignal.signal();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005834 return false;
5835 }
5836
5837 // Get next stream to prepare
5838 auto it = mPendingStreams.begin();
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005839 mCurrentStream = it->second;
5840 mCurrentMaxCount = it->first;
5841 mCurrentPrepareComplete = false;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005842 mPendingStreams.erase(it);
5843 ATRACE_ASYNC_BEGIN("stream prepare", mCurrentStream->getId());
5844 ALOGV("%s: Preparing stream %d", __FUNCTION__, mCurrentStream->getId());
5845 } else if (mCancelNow) {
5846 mCurrentStream->cancelPrepare();
5847 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
5848 ALOGV("%s: Cancelling stream %d prepare", __FUNCTION__, mCurrentStream->getId());
5849 mCurrentStream.clear();
5850 mCancelNow = false;
5851 return true;
5852 }
5853 }
5854
5855 res = mCurrentStream->prepareNextBuffer();
5856 if (res == NOT_ENOUGH_DATA) return true;
5857 if (res != OK) {
5858 // Something bad happened; try to recover by cancelling prepare and
5859 // signalling listener anyway
5860 ALOGE("%s: Stream %d returned error %d (%s) during prepare", __FUNCTION__,
5861 mCurrentStream->getId(), res, strerror(-res));
5862 mCurrentStream->cancelPrepare();
5863 }
5864
5865 // This stream has finished, notify listener
5866 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005867 sp<NotificationListener> listener = mListener.promote();
5868 if (listener != NULL) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005869 ALOGV("%s: Stream %d prepare done, signaling listener", __FUNCTION__,
5870 mCurrentStream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005871 listener->notifyPrepared(mCurrentStream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005872 }
5873
5874 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
5875 mCurrentStream.clear();
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005876 mCurrentPrepareComplete = true;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005877
5878 return true;
5879}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005880
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005881status_t Camera3Device::RequestBufferStateMachine::initialize(
5882 sp<camera3::StatusTracker> statusTracker) {
5883 if (statusTracker == nullptr) {
5884 ALOGE("%s: statusTracker is null", __FUNCTION__);
5885 return BAD_VALUE;
5886 }
5887
5888 std::lock_guard<std::mutex> lock(mLock);
5889 mStatusTracker = statusTracker;
Yin-Chia Yeh87b3ec02019-06-03 10:44:39 -07005890 mRequestBufferStatusId = statusTracker->addComponent("BufferRequestSM");
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005891 return OK;
5892}
5893
5894bool Camera3Device::RequestBufferStateMachine::startRequestBuffer() {
5895 std::lock_guard<std::mutex> lock(mLock);
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08005896 if (mStatus == RB_STATUS_READY || mStatus == RB_STATUS_PENDING_STOP) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005897 mRequestBufferOngoing = true;
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08005898 notifyTrackerLocked(/*active*/true);
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005899 return true;
5900 }
5901 return false;
5902}
5903
5904void Camera3Device::RequestBufferStateMachine::endRequestBuffer() {
5905 std::lock_guard<std::mutex> lock(mLock);
5906 if (!mRequestBufferOngoing) {
5907 ALOGE("%s called without a successful startRequestBuffer call first!", __FUNCTION__);
5908 return;
5909 }
5910 mRequestBufferOngoing = false;
5911 if (mStatus == RB_STATUS_PENDING_STOP) {
5912 checkSwitchToStopLocked();
5913 }
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08005914 notifyTrackerLocked(/*active*/false);
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005915}
5916
5917void Camera3Device::RequestBufferStateMachine::onStreamsConfigured() {
5918 std::lock_guard<std::mutex> lock(mLock);
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005919 mSwitchedToOffline = false;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005920 mStatus = RB_STATUS_READY;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005921 return;
5922}
5923
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08005924void Camera3Device::RequestBufferStateMachine::onSubmittingRequest() {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005925 std::lock_guard<std::mutex> lock(mLock);
5926 mRequestThreadPaused = false;
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08005927 // inflight map register actually happens in prepareHalRequest now, but it is close enough
5928 // approximation.
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005929 mInflightMapEmpty = false;
5930 if (mStatus == RB_STATUS_STOPPED) {
5931 mStatus = RB_STATUS_READY;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005932 }
5933 return;
5934}
5935
5936void Camera3Device::RequestBufferStateMachine::onRequestThreadPaused() {
5937 std::lock_guard<std::mutex> lock(mLock);
5938 mRequestThreadPaused = true;
5939 if (mStatus == RB_STATUS_PENDING_STOP) {
5940 checkSwitchToStopLocked();
5941 }
5942 return;
5943}
5944
5945void Camera3Device::RequestBufferStateMachine::onInflightMapEmpty() {
5946 std::lock_guard<std::mutex> lock(mLock);
5947 mInflightMapEmpty = true;
5948 if (mStatus == RB_STATUS_PENDING_STOP) {
5949 checkSwitchToStopLocked();
5950 }
5951 return;
5952}
5953
5954void Camera3Device::RequestBufferStateMachine::onWaitUntilIdle() {
5955 std::lock_guard<std::mutex> lock(mLock);
5956 if (!checkSwitchToStopLocked()) {
5957 mStatus = RB_STATUS_PENDING_STOP;
5958 }
5959 return;
5960}
5961
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005962bool Camera3Device::RequestBufferStateMachine::onSwitchToOfflineSuccess() {
5963 std::lock_guard<std::mutex> lock(mLock);
5964 if (mRequestBufferOngoing) {
5965 ALOGE("%s: HAL must not be requesting buffer after HAL returns switchToOffline!",
5966 __FUNCTION__);
5967 return false;
5968 }
5969 mSwitchedToOffline = true;
5970 mInflightMapEmpty = true;
5971 mRequestThreadPaused = true;
5972 mStatus = RB_STATUS_STOPPED;
5973 return true;
5974}
5975
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005976void Camera3Device::RequestBufferStateMachine::notifyTrackerLocked(bool active) {
5977 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5978 if (statusTracker != nullptr) {
5979 if (active) {
5980 statusTracker->markComponentActive(mRequestBufferStatusId);
5981 } else {
5982 statusTracker->markComponentIdle(mRequestBufferStatusId, Fence::NO_FENCE);
5983 }
5984 }
5985}
5986
5987bool Camera3Device::RequestBufferStateMachine::checkSwitchToStopLocked() {
5988 if (mInflightMapEmpty && mRequestThreadPaused && !mRequestBufferOngoing) {
5989 mStatus = RB_STATUS_STOPPED;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005990 return true;
5991 }
5992 return false;
5993}
5994
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005995bool Camera3Device::startRequestBuffer() {
5996 return mRequestBufferSM.startRequestBuffer();
5997}
Shuzhen Wang268a1362018-10-16 16:32:59 -07005998
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005999void Camera3Device::endRequestBuffer() {
6000 mRequestBufferSM.endRequestBuffer();
6001}
Shuzhen Wang268a1362018-10-16 16:32:59 -07006002
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006003nsecs_t Camera3Device::getWaitDuration() {
6004 return kBaseGetBufferWait + getExpectedInFlightDuration();
6005}
Shuzhen Wang268a1362018-10-16 16:32:59 -07006006
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006007void Camera3Device::getInflightBufferKeys(std::vector<std::pair<int32_t, int32_t>>* out) {
6008 mInterface->getInflightBufferKeys(out);
6009}
Shuzhen Wang268a1362018-10-16 16:32:59 -07006010
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006011void Camera3Device::getInflightRequestBufferKeys(std::vector<uint64_t>* out) {
6012 mInterface->getInflightRequestBufferKeys(out);
6013}
Shuzhen Wang268a1362018-10-16 16:32:59 -07006014
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006015std::vector<sp<Camera3StreamInterface>> Camera3Device::getAllStreams() {
6016 std::vector<sp<Camera3StreamInterface>> ret;
6017 bool hasInputStream = mInputStream != nullptr;
6018 ret.reserve(mOutputStreams.size() + mDeletedStreams.size() + ((hasInputStream) ? 1 : 0));
6019 if (hasInputStream) {
6020 ret.push_back(mInputStream);
Shuzhen Wang268a1362018-10-16 16:32:59 -07006021 }
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006022 for (size_t i = 0; i < mOutputStreams.size(); i++) {
6023 ret.push_back(mOutputStreams[i]);
6024 }
6025 for (size_t i = 0; i < mDeletedStreams.size(); i++) {
6026 ret.push_back(mDeletedStreams[i]);
6027 }
6028 return ret;
Shuzhen Wang268a1362018-10-16 16:32:59 -07006029}
6030
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006031status_t Camera3Device::switchToOffline(
6032 const std::vector<int32_t>& streamsToKeep,
6033 /*out*/ sp<CameraOfflineSessionBase>* session) {
6034 ATRACE_CALL();
6035 if (session == nullptr) {
6036 ALOGE("%s: session must not be null", __FUNCTION__);
6037 return BAD_VALUE;
6038 }
6039
6040 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006041
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006042 bool hasInputStream = mInputStream != nullptr;
6043 int32_t inputStreamId = hasInputStream ? mInputStream->getId() : -1;
6044 bool inputStreamSupportsOffline = hasInputStream ?
6045 mInputStream->getOfflineProcessingSupport() : false;
6046 auto outputStreamIds = mOutputStreams.getStreamIds();
6047 auto streamIds = outputStreamIds;
6048 if (hasInputStream) {
6049 streamIds.push_back(mInputStream->getId());
6050 }
6051
6052 // Check all streams in streamsToKeep supports offline mode
6053 for (auto id : streamsToKeep) {
6054 if (std::find(streamIds.begin(), streamIds.end(), id) == streamIds.end()) {
6055 ALOGE("%s: Unknown stream ID %d", __FUNCTION__, id);
6056 return BAD_VALUE;
6057 } else if (id == inputStreamId) {
6058 if (!inputStreamSupportsOffline) {
6059 ALOGE("%s: input stream %d cannot be switched to offline",
6060 __FUNCTION__, id);
6061 return BAD_VALUE;
6062 }
6063 } else {
6064 sp<camera3::Camera3OutputStreamInterface> stream = mOutputStreams.get(id);
6065 if (!stream->getOfflineProcessingSupport()) {
6066 ALOGE("%s: output stream %d cannot be switched to offline",
6067 __FUNCTION__, id);
6068 return BAD_VALUE;
6069 }
6070 }
6071 }
6072
6073 // TODO: block surface sharing and surface group streams until we can support them
6074
6075 // Stop repeating request, wait until all remaining requests are submitted, then call into
6076 // HAL switchToOffline
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006077 hardware::camera::device::V3_6::CameraOfflineSessionInfo offlineSessionInfo;
6078 sp<hardware::camera::device::V3_6::ICameraOfflineSession> offlineSession;
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006079 camera3::BufferRecords bufferRecords;
6080 status_t ret = mRequestThread->switchToOffline(
6081 streamsToKeep, &offlineSessionInfo, &offlineSession, &bufferRecords);
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006082
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006083 if (ret != OK) {
6084 SET_ERR("Switch to offline failed: %s (%d)", strerror(-ret), ret);
6085 return ret;
6086 }
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006087
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006088 bool succ = mRequestBufferSM.onSwitchToOfflineSuccess();
6089 if (!succ) {
6090 SET_ERR("HAL must not be calling requestStreamBuffers call");
6091 // TODO: block ALL callbacks from HAL till app configured new streams?
6092 return UNKNOWN_ERROR;
6093 }
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006094
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006095 // Verify offlineSessionInfo
6096 std::vector<int32_t> offlineStreamIds;
6097 offlineStreamIds.reserve(offlineSessionInfo.offlineStreams.size());
6098 for (auto offlineStream : offlineSessionInfo.offlineStreams) {
6099 // verify stream IDs
6100 int32_t id = offlineStream.id;
6101 if (std::find(streamIds.begin(), streamIds.end(), id) == streamIds.end()) {
6102 SET_ERR("stream ID %d not found!", id);
6103 return UNKNOWN_ERROR;
6104 }
6105
6106 // When not using HAL buf manager, only allow streams requested by app to be preserved
6107 if (!mUseHalBufManager) {
6108 if (std::find(streamsToKeep.begin(), streamsToKeep.end(), id) == streamsToKeep.end()) {
6109 SET_ERR("stream ID %d must not be switched to offline!", id);
6110 return UNKNOWN_ERROR;
6111 }
6112 }
6113
6114 offlineStreamIds.push_back(id);
6115 sp<Camera3StreamInterface> stream = (id == inputStreamId) ?
6116 static_cast<sp<Camera3StreamInterface>>(mInputStream) :
6117 static_cast<sp<Camera3StreamInterface>>(mOutputStreams.get(id));
6118 // Verify number of outstanding buffers
6119 if (stream->getOutstandingBuffersCount() != offlineStream.numOutstandingBuffers) {
6120 SET_ERR("Offline stream %d # of remaining buffer mismatch: (%zu,%d) (service/HAL)",
6121 id, stream->getOutstandingBuffersCount(), offlineStream.numOutstandingBuffers);
6122 return UNKNOWN_ERROR;
6123 }
6124 }
6125
6126 // Verify all streams to be deleted don't have any outstanding buffers
6127 if (hasInputStream && std::find(offlineStreamIds.begin(), offlineStreamIds.end(),
6128 inputStreamId) == offlineStreamIds.end()) {
6129 if (mInputStream->hasOutstandingBuffers()) {
6130 SET_ERR("Input stream %d still has %zu outstanding buffer!",
6131 inputStreamId, mInputStream->getOutstandingBuffersCount());
6132 return UNKNOWN_ERROR;
6133 }
6134 }
6135
6136 for (const auto& outStreamId : outputStreamIds) {
6137 if (std::find(offlineStreamIds.begin(), offlineStreamIds.end(),
6138 outStreamId) == offlineStreamIds.end()) {
6139 auto outStream = mOutputStreams.get(outStreamId);
6140 if (outStream->hasOutstandingBuffers()) {
6141 SET_ERR("Output stream %d still has %zu outstanding buffer!",
6142 outStreamId, outStream->getOutstandingBuffersCount());
6143 return UNKNOWN_ERROR;
6144 }
6145 }
6146 }
6147
6148 InFlightRequestMap offlineReqs;
6149 // Verify inflight requests and their pending buffers
6150 {
6151 std::lock_guard<std::mutex> l(mInFlightLock);
6152 for (auto offlineReq : offlineSessionInfo.offlineRequests) {
6153 int idx = mInFlightMap.indexOfKey(offlineReq.frameNumber);
6154 if (idx == NAME_NOT_FOUND) {
6155 SET_ERR("Offline request frame number %d not found!", offlineReq.frameNumber);
6156 return UNKNOWN_ERROR;
6157 }
6158
6159 const auto& inflightReq = mInFlightMap.valueAt(idx);
6160 // TODO: check specific stream IDs
6161 size_t numBuffersLeft = static_cast<size_t>(inflightReq.numBuffersLeft);
6162 if (numBuffersLeft != offlineReq.pendingStreams.size()) {
6163 SET_ERR("Offline request # of remaining buffer mismatch: (%d,%d) (service/HAL)",
6164 inflightReq.numBuffersLeft, offlineReq.pendingStreams.size());
6165 return UNKNOWN_ERROR;
6166 }
6167 offlineReqs.add(offlineReq.frameNumber, inflightReq);
6168 }
6169 }
6170
6171 // Create Camera3OfflineSession and transfer object ownership
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006172 // (streams, inflight requests, buffer caches)
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006173 camera3::StreamSet offlineStreamSet;
6174 sp<camera3::Camera3Stream> inputStream;
6175 for (auto offlineStream : offlineSessionInfo.offlineStreams) {
6176 int32_t id = offlineStream.id;
6177 if (mInputStream != nullptr && id == mInputStream->getId()) {
6178 inputStream = mInputStream;
6179 } else {
6180 offlineStreamSet.add(id, mOutputStreams.get(id));
6181 }
6182 }
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006183
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006184 // TODO: check if we need to lock before copying states
6185 // though technically no other thread should be talking to Camera3Device at this point
6186 Camera3OfflineStates offlineStates(
6187 mTagMonitor, mVendorTagId, mUseHalBufManager, mNeedFixupMonochromeTags,
Shuzhen Wangb7b42652020-05-07 11:59:02 -07006188 mUsePartialResult, mNumPartialResults, mLastCompletedRegularFrameNumber,
6189 mLastCompletedReprocessFrameNumber, mLastCompletedZslFrameNumber,
6190 mNextResultFrameNumber, mNextReprocessResultFrameNumber,
6191 mNextZslStillResultFrameNumber, mNextShutterFrameNumber,
6192 mNextReprocessShutterFrameNumber, mNextZslStillShutterFrameNumber,
6193 mDeviceInfo, mPhysicalDeviceInfoMap, mDistortionMappers,
6194 mZoomRatioMappers, mRotateAndCropMappers);
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006195
6196 *session = new Camera3OfflineSession(mId, inputStream, offlineStreamSet,
6197 std::move(bufferRecords), offlineReqs, offlineStates, offlineSession);
6198
6199 // Delete all streams that has been transferred to offline session
6200 Mutex::Autolock l(mLock);
6201 for (auto offlineStream : offlineSessionInfo.offlineStreams) {
6202 int32_t id = offlineStream.id;
6203 if (mInputStream != nullptr && id == mInputStream->getId()) {
6204 mInputStream.clear();
6205 } else {
6206 mOutputStreams.remove(id);
6207 }
6208 }
6209
6210 // disconnect all other streams and switch to UNCONFIGURED state
6211 if (mInputStream != nullptr) {
6212 ret = mInputStream->disconnect();
6213 if (ret != OK) {
6214 SET_ERR_L("disconnect input stream failed!");
6215 return UNKNOWN_ERROR;
6216 }
6217 }
6218
6219 for (auto streamId : mOutputStreams.getStreamIds()) {
6220 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
6221 ret = stream->disconnect();
6222 if (ret != OK) {
6223 SET_ERR_L("disconnect output stream %d failed!", streamId);
6224 return UNKNOWN_ERROR;
6225 }
6226 }
6227
6228 mInputStream.clear();
6229 mOutputStreams.clear();
6230 mNeedConfig = true;
6231 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
6232 mOperatingMode = NO_MODE;
6233 mIsConstrainedHighSpeedConfiguration = false;
Emilian Peevc0fe54c2020-03-11 14:05:07 -07006234 mRequestThread->clearPreviousRequest();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006235
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006236 return OK;
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006237 // TO be done by CameraDeviceClient/Camera3OfflineSession
6238 // register the offline client to camera service
6239 // Setup result passthing threads etc
6240 // Initialize offline session so HAL can start sending callback to it (result Fmq)
6241 // TODO: check how many onIdle callback will be sent
6242 // Java side to make sure the CameraCaptureSession is properly closed
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006243}
6244
Emilian Peevcc0b7952020-01-07 13:54:47 -08006245void Camera3Device::getOfflineStreamIds(std::vector<int> *offlineStreamIds) {
6246 ATRACE_CALL();
6247
6248 if (offlineStreamIds == nullptr) {
6249 return;
6250 }
6251
6252 Mutex::Autolock il(mInterfaceLock);
6253
6254 auto streamIds = mOutputStreams.getStreamIds();
6255 bool hasInputStream = mInputStream != nullptr;
6256 if (hasInputStream && mInputStream->getOfflineProcessingSupport()) {
6257 offlineStreamIds->push_back(mInputStream->getId());
6258 }
6259
6260 for (const auto & streamId : streamIds) {
6261 sp<camera3::Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
6262 // Streams that use the camera buffer manager are currently not supported in
6263 // offline mode
6264 if (stream->getOfflineProcessingSupport() &&
6265 (stream->getStreamSetId() == CAMERA3_STREAM_SET_ID_INVALID)) {
6266 offlineStreamIds->push_back(streamId);
6267 }
6268 }
6269}
6270
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08006271status_t Camera3Device::setRotateAndCropAutoBehavior(
6272 camera_metadata_enum_android_scaler_rotate_and_crop_t rotateAndCropValue) {
6273 ATRACE_CALL();
6274 Mutex::Autolock il(mInterfaceLock);
6275 Mutex::Autolock l(mLock);
6276 if (mRequestThread == nullptr) {
6277 return INVALID_OPERATION;
6278 }
6279 return mRequestThread->setRotateAndCropAutoBehavior(rotateAndCropValue);
6280}
6281
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08006282bool Camera3Device::supportsCameraMute() {
6283 Mutex::Autolock il(mInterfaceLock);
6284 Mutex::Autolock l(mLock);
6285
6286 return mSupportCameraMute;
6287}
6288
6289status_t Camera3Device::setCameraMute(bool enabled) {
6290 ATRACE_CALL();
6291 Mutex::Autolock il(mInterfaceLock);
6292 Mutex::Autolock l(mLock);
6293
6294 if (mRequestThread == nullptr || !mSupportCameraMute) {
6295 return INVALID_OPERATION;
6296 }
6297 return mRequestThread->setCameraMute(enabled);
6298}
6299
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08006300}; // namespace android