blob: 7606d7dc505bc8114c042a308e37044224627471 [file] [log] [blame]
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001/*
Shuzhen Wangc28189a2017-11-27 23:05:10 -08002 * Copyright (C) 2013-2018 The Android Open Source Project
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#define LOG_TAG "Camera3-Device"
18#define ATRACE_TAG ATRACE_TAG_CAMERA
19//#define LOG_NDEBUG 0
20//#define LOG_NNDEBUG 0 // Per-frame verbose logging
21
22#ifdef LOG_NNDEBUG
23#define ALOGVV(...) ALOGV(__VA_ARGS__)
24#else
25#define ALOGVV(...) ((void)0)
26#endif
27
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -070028// Convenience macro for transient errors
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080029#define CLOGE(fmt, ...) ALOGE("Camera %s: %s: " fmt, mId.string(), __FUNCTION__, \
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -070030 ##__VA_ARGS__)
31
Yin-Chia Yeh99fd0972019-06-27 14:22:44 -070032#define CLOGW(fmt, ...) ALOGW("Camera %s: %s: " fmt, mId.string(), __FUNCTION__, \
33 ##__VA_ARGS__)
34
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -070035// Convenience macros for transitioning to the error state
36#define SET_ERR(fmt, ...) setErrorState( \
37 "%s: " fmt, __FUNCTION__, \
38 ##__VA_ARGS__)
39#define SET_ERR_L(fmt, ...) setErrorStateLocked( \
40 "%s: " fmt, __FUNCTION__, \
41 ##__VA_ARGS__)
42
Colin Crosse5729fa2014-03-21 15:04:25 -070043#include <inttypes.h>
44
Shuzhen Wang5c22c152017-12-31 17:12:25 -080045#include <utility>
46
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080047#include <utils/Log.h>
48#include <utils/Trace.h>
49#include <utils/Timers.h>
Zhijun He90f7c372016-08-16 16:19:43 -070050#include <cutils/properties.h>
Eino-Ville Talvala7b82efe2013-07-25 17:12:35 -070051
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -080052#include <android/hardware/camera2/ICameraDeviceUser.h>
53
Igor Murashkinff3e31d2013-10-23 16:40:06 -070054#include "utils/CameraTraces.h"
Eino-Ville Talvalaf99498e2015-09-25 16:52:55 -070055#include "mediautils/SchedulingPolicyService.h"
Eino-Ville Talvala7b82efe2013-07-25 17:12:35 -070056#include "device3/Camera3Device.h"
57#include "device3/Camera3OutputStream.h"
58#include "device3/Camera3InputStream.h"
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -040059#include "device3/Camera3FakeStream.h"
Shuzhen Wang0129d522016-10-30 22:43:41 -070060#include "device3/Camera3SharedOutputStream.h"
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -070061#include "CameraService.h"
Jayant Chowdhary12361932018-08-27 14:46:13 -070062#include "utils/CameraThreadState.h"
Jayant Chowdharyd4776262020-06-23 23:45:57 -070063#include "utils/TraceHFR.h"
Shuzhen Wang316781a2020-08-18 18:11:01 -070064#include "utils/CameraServiceProxyWrapper.h"
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -080065
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -080066#include <algorithm>
Yin-Chia Yeh84be5782019-03-01 11:47:02 -080067#include <tuple>
68
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -080069using namespace android::camera3;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080070using namespace android::hardware::camera;
71using namespace android::hardware::camera::device::V3_2;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080072
73namespace android {
74
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -080075Camera3Device::Camera3Device(const String8 &id):
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080076 mId(id),
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -080077 mOperatingMode(NO_MODE),
Eino-Ville Talvala9a179412015-06-09 13:15:16 -070078 mIsConstrainedHighSpeedConfiguration(false),
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -070079 mStatus(STATUS_UNINITIALIZED),
Ruben Brunk183f0562015-08-12 12:55:02 -070080 mStatusWaiters(0),
Zhijun He204e3292014-07-14 17:09:23 -070081 mUsePartialResult(false),
82 mNumPartialResults(1),
Shuzhen Wangc28dccc2016-02-11 23:48:46 -080083 mTimestampOffset(0),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -070084 mNextResultFrameNumber(0),
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -070085 mNextReprocessResultFrameNumber(0),
Shuzhen Wang5ee99842019-04-12 11:55:48 -070086 mNextZslStillResultFrameNumber(0),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -070087 mNextShutterFrameNumber(0),
Chien-Yu Chen3df11ce2015-09-30 14:13:30 -070088 mNextReprocessShutterFrameNumber(0),
Shuzhen Wang5ee99842019-04-12 11:55:48 -070089 mNextZslStillShutterFrameNumber(0),
Emilian Peev71c73a22017-03-21 16:35:51 +000090 mListener(NULL),
Emilian Peev811d2952018-05-25 11:08:40 +010091 mVendorTagId(CAMERA_METADATA_INVALID_VENDOR_ID),
Shuzhen Wang268a1362018-10-16 16:32:59 -070092 mLastTemplateId(-1),
93 mNeedFixupMonochromeTags(false)
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080094{
95 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080096 ALOGV("%s: Created device for camera %s", __FUNCTION__, mId.string());
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080097}
98
99Camera3Device::~Camera3Device()
100{
101 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800102 ALOGV("%s: Tearing down for camera id %s", __FUNCTION__, mId.string());
Yin-Chia Yehc5248132018-08-15 12:19:20 -0700103 disconnectImpl();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800104}
105
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800106const String8& Camera3Device::getId() const {
Igor Murashkin71381052013-03-04 14:53:08 -0800107 return mId;
108}
109
Emilian Peevbd8c5032018-02-14 23:05:40 +0000110status_t Camera3Device::initialize(sp<CameraProviderManager> manager, const String8& monitorTags) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800111 ATRACE_CALL();
112 Mutex::Autolock il(mInterfaceLock);
113 Mutex::Autolock l(mLock);
114
115 ALOGV("%s: Initializing HIDL device for camera %s", __FUNCTION__, mId.string());
116 if (mStatus != STATUS_UNINITIALIZED) {
117 CLOGE("Already initialized!");
118 return INVALID_OPERATION;
119 }
120 if (manager == nullptr) return INVALID_OPERATION;
121
122 sp<ICameraDeviceSession> session;
123 ATRACE_BEGIN("CameraHal::openSession");
Steven Moreland5ff9c912017-03-09 23:13:00 -0800124 status_t res = manager->openSession(mId.string(), this,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800125 /*out*/ &session);
126 ATRACE_END();
127 if (res != OK) {
128 SET_ERR_L("Could not open camera session: %s (%d)", strerror(-res), res);
129 return res;
130 }
131
Steven Moreland5ff9c912017-03-09 23:13:00 -0800132 res = manager->getCameraCharacteristics(mId.string(), &mDeviceInfo);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800133 if (res != OK) {
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700134 SET_ERR_L("Could not retrieve camera characteristics: %s (%d)", strerror(-res), res);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800135 session->close();
136 return res;
137 }
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800138 mSupportNativeZoomRatio = manager->supportNativeZoomRatio(mId.string());
Yin-Chia Yeh52778d42016-12-22 18:20:43 -0800139
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700140 std::vector<std::string> physicalCameraIds;
Shuzhen Wang03d8cc12018-09-12 14:17:09 -0700141 bool isLogical = manager->isLogicalCamera(mId.string(), &physicalCameraIds);
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700142 if (isLogical) {
143 for (auto& physicalId : physicalCameraIds) {
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -0700144 res = manager->getCameraCharacteristics(
145 physicalId, &mPhysicalDeviceInfoMap[physicalId]);
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700146 if (res != OK) {
147 SET_ERR_L("Could not retrieve camera %s characteristics: %s (%d)",
148 physicalId.c_str(), strerror(-res), res);
149 session->close();
150 return res;
151 }
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -0700152
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800153 bool usePrecorrectArray =
154 DistortionMapper::isDistortionSupported(mPhysicalDeviceInfoMap[physicalId]);
155 if (usePrecorrectArray) {
156 res = mDistortionMappers[physicalId].setupStaticInfo(
157 mPhysicalDeviceInfoMap[physicalId]);
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -0700158 if (res != OK) {
159 SET_ERR_L("Unable to read camera %s's calibration fields for distortion "
160 "correction", physicalId.c_str());
161 session->close();
162 return res;
163 }
164 }
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800165
Shuzhen Wang1c834da2019-12-18 11:17:03 -0800166 mZoomRatioMappers[physicalId] = ZoomRatioMapper(
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800167 &mPhysicalDeviceInfoMap[physicalId],
168 mSupportNativeZoomRatio, usePrecorrectArray);
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700169 }
170 }
171
Yifan Hongf79b5542017-04-11 14:44:25 -0700172 std::shared_ptr<RequestMetadataQueue> queue;
Yifan Honga640c5a2017-04-12 16:30:31 -0700173 auto requestQueueRet = session->getCaptureRequestMetadataQueue(
174 [&queue](const auto& descriptor) {
175 queue = std::make_shared<RequestMetadataQueue>(descriptor);
176 if (!queue->isValid() || queue->availableToWrite() <= 0) {
177 ALOGE("HAL returns empty request metadata fmq, not use it");
178 queue = nullptr;
179 // don't use the queue onwards.
180 }
181 });
182 if (!requestQueueRet.isOk()) {
183 ALOGE("Transaction error when getting request metadata fmq: %s, not use it",
184 requestQueueRet.description().c_str());
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -0700185 return DEAD_OBJECT;
Yifan Hongf79b5542017-04-11 14:44:25 -0700186 }
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700187
188 std::unique_ptr<ResultMetadataQueue>& resQueue = mResultMetadataQueue;
Yifan Honga640c5a2017-04-12 16:30:31 -0700189 auto resultQueueRet = session->getCaptureResultMetadataQueue(
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700190 [&resQueue](const auto& descriptor) {
191 resQueue = std::make_unique<ResultMetadataQueue>(descriptor);
192 if (!resQueue->isValid() || resQueue->availableToWrite() <= 0) {
Yifan Honga640c5a2017-04-12 16:30:31 -0700193 ALOGE("HAL returns empty result metadata fmq, not use it");
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700194 resQueue = nullptr;
195 // Don't use the resQueue onwards.
Yifan Honga640c5a2017-04-12 16:30:31 -0700196 }
197 });
198 if (!resultQueueRet.isOk()) {
199 ALOGE("Transaction error when getting result metadata queue from camera session: %s",
200 resultQueueRet.description().c_str());
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -0700201 return DEAD_OBJECT;
Yifan Honga640c5a2017-04-12 16:30:31 -0700202 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -0700203 IF_ALOGV() {
204 session->interfaceChain([](
205 ::android::hardware::hidl_vec<::android::hardware::hidl_string> interfaceChain) {
206 ALOGV("Session interface chain:");
Chih-Hung Hsieh3ef324d2018-12-11 11:48:12 -0800207 for (const auto& iface : interfaceChain) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -0700208 ALOGV(" %s", iface.c_str());
209 }
210 });
211 }
Yifan Hongf79b5542017-04-11 14:44:25 -0700212
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -0800213 camera_metadata_entry bufMgrMode =
214 mDeviceInfo.find(ANDROID_INFO_SUPPORTED_BUFFER_MANAGEMENT_VERSION);
215 if (bufMgrMode.count > 0) {
216 mUseHalBufManager = (bufMgrMode.data.u8[0] ==
217 ANDROID_INFO_SUPPORTED_BUFFER_MANAGEMENT_VERSION_HIDL_DEVICE_3_5);
218 }
219
Yin-Chia Yehb978c382019-10-30 00:22:37 -0700220 camera_metadata_entry_t capabilities = mDeviceInfo.find(ANDROID_REQUEST_AVAILABLE_CAPABILITIES);
221 for (size_t i = 0; i < capabilities.count; i++) {
222 uint8_t capability = capabilities.data.u8[i];
223 if (capability == ANDROID_REQUEST_AVAILABLE_CAPABILITIES_OFFLINE_PROCESSING) {
224 mSupportOfflineProcessing = true;
225 }
226 }
227
228 mInterface = new HalInterface(session, queue, mUseHalBufManager, mSupportOfflineProcessing);
Emilian Peev71c73a22017-03-21 16:35:51 +0000229 std::string providerType;
230 mVendorTagId = manager->getProviderTagIdLocked(mId.string());
Emilian Peevbd8c5032018-02-14 23:05:40 +0000231 mTagMonitor.initialize(mVendorTagId);
232 if (!monitorTags.isEmpty()) {
233 mTagMonitor.parseTagsToMonitor(String8(monitorTags));
234 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800235
Shuzhen Wang268a1362018-10-16 16:32:59 -0700236 // Metadata tags needs fixup for monochrome camera device version less
237 // than 3.5.
238 hardware::hidl_version maxVersion{0,0};
239 res = manager->getHighestSupportedVersion(mId.string(), &maxVersion);
240 if (res != OK) {
241 ALOGE("%s: Error in getting camera device version id: %s (%d)",
242 __FUNCTION__, strerror(-res), res);
243 return res;
244 }
245 int deviceVersion = HARDWARE_DEVICE_API_VERSION(
246 maxVersion.get_major(), maxVersion.get_minor());
247
248 bool isMonochrome = false;
Yin-Chia Yehb978c382019-10-30 00:22:37 -0700249 for (size_t i = 0; i < capabilities.count; i++) {
250 uint8_t capability = capabilities.data.u8[i];
Shuzhen Wang268a1362018-10-16 16:32:59 -0700251 if (capability == ANDROID_REQUEST_AVAILABLE_CAPABILITIES_MONOCHROME) {
252 isMonochrome = true;
253 }
254 }
255 mNeedFixupMonochromeTags = (isMonochrome && deviceVersion < CAMERA_DEVICE_API_VERSION_3_5);
256
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800257 return initializeCommonLocked();
258}
259
260status_t Camera3Device::initializeCommonLocked() {
261
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700262 /** Start up status tracker thread */
263 mStatusTracker = new StatusTracker(this);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800264 status_t res = mStatusTracker->run(String8::format("C3Dev-%s-Status", mId.string()).string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700265 if (res != OK) {
266 SET_ERR_L("Unable to start status tracking thread: %s (%d)",
267 strerror(-res), res);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800268 mInterface->close();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700269 mStatusTracker.clear();
270 return res;
271 }
272
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -0700273 /** Register in-flight map to the status tracker */
Yin-Chia Yeh87b3ec02019-06-03 10:44:39 -0700274 mInFlightStatusId = mStatusTracker->addComponent("InflightRequests");
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -0700275
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -0700276 if (mUseHalBufManager) {
277 res = mRequestBufferSM.initialize(mStatusTracker);
278 if (res != OK) {
279 SET_ERR_L("Unable to start request buffer state machine: %s (%d)",
280 strerror(-res), res);
281 mInterface->close();
282 mStatusTracker.clear();
283 return res;
284 }
285 }
286
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -0800287 /** Create buffer manager */
288 mBufferManager = new Camera3BufferManager();
289
290 Vector<int32_t> sessionParamKeys;
291 camera_metadata_entry_t sessionKeysEntry = mDeviceInfo.find(
292 ANDROID_REQUEST_AVAILABLE_SESSION_KEYS);
293 if (sessionKeysEntry.count > 0) {
294 sessionParamKeys.insertArrayAt(sessionKeysEntry.data.i32, 0, sessionKeysEntry.count);
295 }
296
Chien-Yu Chenab5135b2015-06-30 11:20:58 -0700297 /** Start up request queue thread */
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -0700298 mRequestThread = new RequestThread(
299 this, mStatusTracker, mInterface, sessionParamKeys, mUseHalBufManager);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800300 res = mRequestThread->run(String8::format("C3Dev-%s-ReqQueue", mId.string()).string());
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800301 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700302 SET_ERR_L("Unable to start request queue thread: %s (%d)",
303 strerror(-res), res);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800304 mInterface->close();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800305 mRequestThread.clear();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800306 return res;
307 }
308
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -0700309 mPreparerThread = new PreparerThread();
310
Ruben Brunk183f0562015-08-12 12:55:02 -0700311 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800312 mNextStreamId = 0;
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -0400313 mFakeStreamId = NO_STREAM;
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -0700314 mNeedConfig = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700315 mPauseStateNotify = false;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800316
Shuzhen Wangc28dccc2016-02-11 23:48:46 -0800317 // Measure the clock domain offset between camera and video/hw_composer
318 camera_metadata_entry timestampSource =
319 mDeviceInfo.find(ANDROID_SENSOR_INFO_TIMESTAMP_SOURCE);
320 if (timestampSource.count > 0 && timestampSource.data.u8[0] ==
321 ANDROID_SENSOR_INFO_TIMESTAMP_SOURCE_REALTIME) {
322 mTimestampOffset = getMonoToBoottimeOffset();
323 }
324
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -0700325 // Will the HAL be sending in early partial result metadata?
Emilian Peev08dd2452017-04-06 16:55:14 +0100326 camera_metadata_entry partialResultsCount =
327 mDeviceInfo.find(ANDROID_REQUEST_PARTIAL_RESULT_COUNT);
328 if (partialResultsCount.count > 0) {
329 mNumPartialResults = partialResultsCount.data.i32[0];
330 mUsePartialResult = (mNumPartialResults > 1);
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -0700331 }
332
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -0700333 camera_metadata_entry configs =
334 mDeviceInfo.find(ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS);
335 for (uint32_t i = 0; i < configs.count; i += 4) {
336 if (configs.data.i32[i] == HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED &&
337 configs.data.i32[i + 3] ==
338 ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS_INPUT) {
339 mSupportedOpaqueInputSizes.add(Size(configs.data.i32[i + 1],
340 configs.data.i32[i + 2]));
341 }
342 }
343
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800344 bool usePrecorrectArray = DistortionMapper::isDistortionSupported(mDeviceInfo);
345 if (usePrecorrectArray) {
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -0700346 res = mDistortionMappers[mId.c_str()].setupStaticInfo(mDeviceInfo);
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -0700347 if (res != OK) {
348 SET_ERR_L("Unable to read necessary calibration fields for distortion correction");
349 return res;
350 }
351 }
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800352
Shuzhen Wang1c834da2019-12-18 11:17:03 -0800353 mZoomRatioMappers[mId.c_str()] = ZoomRatioMapper(&mDeviceInfo,
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800354 mSupportNativeZoomRatio, usePrecorrectArray);
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800355
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -0800356 if (RotateAndCropMapper::isNeeded(&mDeviceInfo)) {
357 mRotateAndCropMappers.emplace(mId.c_str(), &mDeviceInfo);
358 }
359
Eino-Ville Talvala305cec62020-11-12 14:18:17 -0800360 camera_metadata_entry_t availableTestPatternModes = mDeviceInfo.find(
361 ANDROID_SENSOR_AVAILABLE_TEST_PATTERN_MODES);
362 for (size_t i = 0; i < availableTestPatternModes.count; i++) {
363 if (availableTestPatternModes.data.i32[i] == ANDROID_SENSOR_TEST_PATTERN_MODE_SOLID_COLOR) {
364 mSupportCameraMute = true;
365 break;
366 }
367 }
368
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800369 return OK;
370}
371
372status_t Camera3Device::disconnect() {
Yin-Chia Yehc5248132018-08-15 12:19:20 -0700373 return disconnectImpl();
374}
375
376status_t Camera3Device::disconnectImpl() {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800377 ATRACE_CALL();
Yin-Chia Yehe1c80632016-08-08 14:48:05 -0700378 ALOGI("%s: E", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800379
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700380 status_t res = OK;
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700381 std::vector<wp<Camera3StreamInterface>> streams;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700382 {
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800383 Mutex::Autolock il(mInterfaceLock);
384 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
385 {
386 Mutex::Autolock l(mLock);
387 if (mStatus == STATUS_UNINITIALIZED) return res;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700388
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800389 if (mStatus == STATUS_ACTIVE ||
390 (mStatus == STATUS_ERROR && mRequestThread != NULL)) {
391 res = mRequestThread->clearRepeatingRequests();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700392 if (res != OK) {
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800393 SET_ERR_L("Can't stop streaming");
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700394 // Continue to close device even in case of error
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800395 } else {
396 res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
397 if (res != OK) {
398 SET_ERR_L("Timeout waiting for HAL to drain (% " PRIi64 " ns)",
399 maxExpectedDuration);
400 // Continue to close device even in case of error
401 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700402 }
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700403 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800404
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800405 if (mStatus == STATUS_ERROR) {
406 CLOGE("Shutting down in an error state");
407 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700408
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800409 if (mStatusTracker != NULL) {
410 mStatusTracker->requestExit();
411 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700412
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800413 if (mRequestThread != NULL) {
414 mRequestThread->requestExit();
415 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700416
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800417 streams.reserve(mOutputStreams.size() + (mInputStream != nullptr ? 1 : 0));
418 for (size_t i = 0; i < mOutputStreams.size(); i++) {
419 streams.push_back(mOutputStreams[i]);
420 }
421 if (mInputStream != nullptr) {
422 streams.push_back(mInputStream);
423 }
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700424 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700425 }
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800426 // Joining done without holding mLock and mInterfaceLock, otherwise deadlocks may ensue
427 // as the threads try to access parent state (b/143513518)
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700428 if (mRequestThread != NULL && mStatus != STATUS_ERROR) {
429 // HAL may be in a bad state, so waiting for request thread
430 // (which may be stuck in the HAL processCaptureRequest call)
431 // could be dangerous.
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800432 // give up mInterfaceLock here and then lock it again. Could this lead
433 // to other deadlocks
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700434 mRequestThread->join();
435 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700436 {
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800437 Mutex::Autolock il(mInterfaceLock);
438 if (mStatusTracker != NULL) {
439 mStatusTracker->join();
440 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800441
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800442 HalInterface* interface;
443 {
444 Mutex::Autolock l(mLock);
445 mRequestThread.clear();
446 Mutex::Autolock stLock(mTrackerLock);
447 mStatusTracker.clear();
448 interface = mInterface.get();
449 }
Eino-Ville Talvalaefff1c42015-08-28 16:27:27 -0700450
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800451 // Call close without internal mutex held, as the HAL close may need to
452 // wait on assorted callbacks,etc, to complete before it can return.
453 interface->close();
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700454
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800455 flushInflightRequests();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800456
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800457 {
458 Mutex::Autolock l(mLock);
459 mInterface->clear();
460 mOutputStreams.clear();
461 mInputStream.clear();
462 mDeletedStreams.clear();
463 mBufferManager.clear();
464 internalUpdateStatusLocked(STATUS_UNINITIALIZED);
465 }
466
467 for (auto& weakStream : streams) {
468 sp<Camera3StreamInterface> stream = weakStream.promote();
469 if (stream != nullptr) {
470 ALOGE("%s: Stream %d leaked! strong reference (%d)!",
471 __FUNCTION__, stream->getId(), stream->getStrongCount() - 1);
472 }
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700473 }
474 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -0700475 ALOGI("%s: X", __FUNCTION__);
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700476 return res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800477}
478
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700479// For dumping/debugging only -
480// try to acquire a lock a few times, eventually give up to proceed with
481// debug/dump operations
482bool Camera3Device::tryLockSpinRightRound(Mutex& lock) {
483 bool gotLock = false;
484 for (size_t i = 0; i < kDumpLockAttempts; ++i) {
485 if (lock.tryLock() == NO_ERROR) {
486 gotLock = true;
487 break;
488 } else {
489 usleep(kDumpSleepDuration);
490 }
491 }
492 return gotLock;
493}
494
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700495Camera3Device::Size Camera3Device::getMaxJpegResolution() const {
496 int32_t maxJpegWidth = 0, maxJpegHeight = 0;
Emilian Peev08dd2452017-04-06 16:55:14 +0100497 const int STREAM_CONFIGURATION_SIZE = 4;
498 const int STREAM_FORMAT_OFFSET = 0;
499 const int STREAM_WIDTH_OFFSET = 1;
500 const int STREAM_HEIGHT_OFFSET = 2;
501 const int STREAM_IS_INPUT_OFFSET = 3;
502 camera_metadata_ro_entry_t availableStreamConfigs =
503 mDeviceInfo.find(ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS);
504 if (availableStreamConfigs.count == 0 ||
505 availableStreamConfigs.count % STREAM_CONFIGURATION_SIZE != 0) {
506 return Size(0, 0);
507 }
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700508
Emilian Peev08dd2452017-04-06 16:55:14 +0100509 // Get max jpeg size (area-wise).
510 for (size_t i=0; i < availableStreamConfigs.count; i+= STREAM_CONFIGURATION_SIZE) {
511 int32_t format = availableStreamConfigs.data.i32[i + STREAM_FORMAT_OFFSET];
512 int32_t width = availableStreamConfigs.data.i32[i + STREAM_WIDTH_OFFSET];
513 int32_t height = availableStreamConfigs.data.i32[i + STREAM_HEIGHT_OFFSET];
514 int32_t isInput = availableStreamConfigs.data.i32[i + STREAM_IS_INPUT_OFFSET];
515 if (isInput == ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS_OUTPUT
516 && format == HAL_PIXEL_FORMAT_BLOB &&
517 (width * height > maxJpegWidth * maxJpegHeight)) {
518 maxJpegWidth = width;
519 maxJpegHeight = height;
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700520 }
521 }
Emilian Peev08dd2452017-04-06 16:55:14 +0100522
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700523 return Size(maxJpegWidth, maxJpegHeight);
524}
525
Shuzhen Wangc28dccc2016-02-11 23:48:46 -0800526nsecs_t Camera3Device::getMonoToBoottimeOffset() {
527 // try three times to get the clock offset, choose the one
528 // with the minimum gap in measurements.
529 const int tries = 3;
530 nsecs_t bestGap, measured;
531 for (int i = 0; i < tries; ++i) {
532 const nsecs_t tmono = systemTime(SYSTEM_TIME_MONOTONIC);
533 const nsecs_t tbase = systemTime(SYSTEM_TIME_BOOTTIME);
534 const nsecs_t tmono2 = systemTime(SYSTEM_TIME_MONOTONIC);
535 const nsecs_t gap = tmono2 - tmono;
536 if (i == 0 || gap < bestGap) {
537 bestGap = gap;
538 measured = tbase - ((tmono + tmono2) >> 1);
539 }
540 }
541 return measured;
542}
543
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800544hardware::graphics::common::V1_0::PixelFormat Camera3Device::mapToPixelFormat(
545 int frameworkFormat) {
546 return (hardware::graphics::common::V1_0::PixelFormat) frameworkFormat;
547}
548
549DataspaceFlags Camera3Device::mapToHidlDataspace(
550 android_dataspace dataSpace) {
551 return dataSpace;
552}
553
Chia-I Wu67a0c0e2017-04-06 13:37:01 -0700554BufferUsageFlags Camera3Device::mapToConsumerUsage(
Emilian Peev050f5dc2017-05-18 14:43:56 +0100555 uint64_t usage) {
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -0700556 return usage;
557}
558
Emilian Peevf4816702020-04-03 15:44:51 -0700559StreamRotation Camera3Device::mapToStreamRotation(camera_stream_rotation_t rotation) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800560 switch (rotation) {
Emilian Peevf4816702020-04-03 15:44:51 -0700561 case CAMERA_STREAM_ROTATION_0:
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800562 return StreamRotation::ROTATION_0;
Emilian Peevf4816702020-04-03 15:44:51 -0700563 case CAMERA_STREAM_ROTATION_90:
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800564 return StreamRotation::ROTATION_90;
Emilian Peevf4816702020-04-03 15:44:51 -0700565 case CAMERA_STREAM_ROTATION_180:
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800566 return StreamRotation::ROTATION_180;
Emilian Peevf4816702020-04-03 15:44:51 -0700567 case CAMERA_STREAM_ROTATION_270:
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800568 return StreamRotation::ROTATION_270;
569 }
570 ALOGE("%s: Unknown stream rotation %d", __FUNCTION__, rotation);
571 return StreamRotation::ROTATION_0;
572}
573
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800574status_t Camera3Device::mapToStreamConfigurationMode(
Emilian Peevf4816702020-04-03 15:44:51 -0700575 camera_stream_configuration_mode_t operationMode, StreamConfigurationMode *mode) {
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800576 if (mode == nullptr) return BAD_VALUE;
Emilian Peevf4816702020-04-03 15:44:51 -0700577 if (operationMode < CAMERA_VENDOR_STREAM_CONFIGURATION_MODE_START) {
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800578 switch(operationMode) {
Emilian Peevf4816702020-04-03 15:44:51 -0700579 case CAMERA_STREAM_CONFIGURATION_NORMAL_MODE:
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800580 *mode = StreamConfigurationMode::NORMAL_MODE;
581 break;
Emilian Peevf4816702020-04-03 15:44:51 -0700582 case CAMERA_STREAM_CONFIGURATION_CONSTRAINED_HIGH_SPEED_MODE:
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800583 *mode = StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE;
584 break;
585 default:
586 ALOGE("%s: Unknown stream configuration mode %d", __FUNCTION__, operationMode);
587 return BAD_VALUE;
588 }
589 } else {
590 *mode = static_cast<StreamConfigurationMode>(operationMode);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800591 }
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800592 return OK;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800593}
594
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800595int Camera3Device::mapToFrameworkFormat(
596 hardware::graphics::common::V1_0::PixelFormat pixelFormat) {
597 return static_cast<uint32_t>(pixelFormat);
598}
599
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -0700600android_dataspace Camera3Device::mapToFrameworkDataspace(
601 DataspaceFlags dataSpace) {
602 return static_cast<android_dataspace>(dataSpace);
603}
604
Emilian Peev050f5dc2017-05-18 14:43:56 +0100605uint64_t Camera3Device::mapConsumerToFrameworkUsage(
Chia-I Wu67a0c0e2017-04-06 13:37:01 -0700606 BufferUsageFlags usage) {
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -0700607 return usage;
608}
609
Emilian Peev050f5dc2017-05-18 14:43:56 +0100610uint64_t Camera3Device::mapProducerToFrameworkUsage(
Chia-I Wu67a0c0e2017-04-06 13:37:01 -0700611 BufferUsageFlags usage) {
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -0700612 return usage;
613}
614
Zhijun Hef7da0962014-04-24 13:27:56 -0700615ssize_t Camera3Device::getJpegBufferSize(uint32_t width, uint32_t height) const {
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700616 // Get max jpeg size (area-wise).
617 Size maxJpegResolution = getMaxJpegResolution();
618 if (maxJpegResolution.width == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800619 ALOGE("%s: Camera %s: Can't find valid available jpeg sizes in static metadata!",
620 __FUNCTION__, mId.string());
Zhijun Hef7da0962014-04-24 13:27:56 -0700621 return BAD_VALUE;
622 }
623
Zhijun Hef7da0962014-04-24 13:27:56 -0700624 // Get max jpeg buffer size
625 ssize_t maxJpegBufferSize = 0;
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700626 camera_metadata_ro_entry jpegBufMaxSize = mDeviceInfo.find(ANDROID_JPEG_MAX_SIZE);
627 if (jpegBufMaxSize.count == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800628 ALOGE("%s: Camera %s: Can't find maximum JPEG size in static metadata!", __FUNCTION__,
629 mId.string());
Zhijun Hef7da0962014-04-24 13:27:56 -0700630 return BAD_VALUE;
631 }
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700632 maxJpegBufferSize = jpegBufMaxSize.data.i32[0];
Yin-Chia Yeh0c4e56d2015-01-09 15:21:27 -0800633 assert(kMinJpegBufferSize < maxJpegBufferSize);
Zhijun Hef7da0962014-04-24 13:27:56 -0700634
635 // Calculate final jpeg buffer size for the given resolution.
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700636 float scaleFactor = ((float) (width * height)) /
637 (maxJpegResolution.width * maxJpegResolution.height);
Yin-Chia Yeh0c4e56d2015-01-09 15:21:27 -0800638 ssize_t jpegBufferSize = scaleFactor * (maxJpegBufferSize - kMinJpegBufferSize) +
639 kMinJpegBufferSize;
Zhijun Hef7da0962014-04-24 13:27:56 -0700640 if (jpegBufferSize > maxJpegBufferSize) {
641 jpegBufferSize = maxJpegBufferSize;
Zhijun Hef7da0962014-04-24 13:27:56 -0700642 }
643
644 return jpegBufferSize;
645}
646
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700647ssize_t Camera3Device::getPointCloudBufferSize() const {
648 const int FLOATS_PER_POINT=4;
649 camera_metadata_ro_entry maxPointCount = mDeviceInfo.find(ANDROID_DEPTH_MAX_DEPTH_SAMPLES);
650 if (maxPointCount.count == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800651 ALOGE("%s: Camera %s: Can't find maximum depth point cloud size in static metadata!",
652 __FUNCTION__, mId.string());
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700653 return BAD_VALUE;
654 }
655 ssize_t maxBytesForPointCloud = sizeof(android_depth_points) +
656 maxPointCount.data.i32[0] * sizeof(float) * FLOATS_PER_POINT;
657 return maxBytesForPointCloud;
658}
659
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800660ssize_t Camera3Device::getRawOpaqueBufferSize(int32_t width, int32_t height) const {
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800661 const int PER_CONFIGURATION_SIZE = 3;
662 const int WIDTH_OFFSET = 0;
663 const int HEIGHT_OFFSET = 1;
664 const int SIZE_OFFSET = 2;
665 camera_metadata_ro_entry rawOpaqueSizes =
666 mDeviceInfo.find(ANDROID_SENSOR_OPAQUE_RAW_SIZE);
Aurimas Liutikasbc57b122016-02-16 09:59:16 -0800667 size_t count = rawOpaqueSizes.count;
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800668 if (count == 0 || (count % PER_CONFIGURATION_SIZE)) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800669 ALOGE("%s: Camera %s: bad opaque RAW size static metadata length(%zu)!",
670 __FUNCTION__, mId.string(), count);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800671 return BAD_VALUE;
672 }
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700673
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800674 for (size_t i = 0; i < count; i += PER_CONFIGURATION_SIZE) {
675 if (width == rawOpaqueSizes.data.i32[i + WIDTH_OFFSET] &&
676 height == rawOpaqueSizes.data.i32[i + HEIGHT_OFFSET]) {
677 return rawOpaqueSizes.data.i32[i + SIZE_OFFSET];
678 }
679 }
680
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800681 ALOGE("%s: Camera %s: cannot find size for %dx%d opaque RAW image!",
682 __FUNCTION__, mId.string(), width, height);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800683 return BAD_VALUE;
684}
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700685
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800686status_t Camera3Device::dump(int fd, const Vector<String16> &args) {
687 ATRACE_CALL();
688 (void)args;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700689
690 // Try to lock, but continue in case of failure (to avoid blocking in
691 // deadlocks)
692 bool gotInterfaceLock = tryLockSpinRightRound(mInterfaceLock);
693 bool gotLock = tryLockSpinRightRound(mLock);
694
695 ALOGW_IF(!gotInterfaceLock,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800696 "Camera %s: %s: Unable to lock interface lock, proceeding anyway",
697 mId.string(), __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700698 ALOGW_IF(!gotLock,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800699 "Camera %s: %s: Unable to lock main lock, proceeding anyway",
700 mId.string(), __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700701
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800702 bool dumpTemplates = false;
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700703
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800704 String16 templatesOption("-t");
705 int n = args.size();
706 for (int i = 0; i < n; i++) {
707 if (args[i] == templatesOption) {
708 dumpTemplates = true;
709 }
Emilian Peevbd8c5032018-02-14 23:05:40 +0000710 if (args[i] == TagMonitor::kMonitorOption) {
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700711 if (i + 1 < n) {
712 String8 monitorTags = String8(args[i + 1]);
713 if (monitorTags == "off") {
714 mTagMonitor.disableMonitoring();
715 } else {
716 mTagMonitor.parseTagsToMonitor(monitorTags);
717 }
718 } else {
719 mTagMonitor.disableMonitoring();
720 }
721 }
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800722 }
723
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800724 String8 lines;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800725
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800726 const char *status =
727 mStatus == STATUS_ERROR ? "ERROR" :
728 mStatus == STATUS_UNINITIALIZED ? "UNINITIALIZED" :
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700729 mStatus == STATUS_UNCONFIGURED ? "UNCONFIGURED" :
730 mStatus == STATUS_CONFIGURED ? "CONFIGURED" :
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800731 mStatus == STATUS_ACTIVE ? "ACTIVE" :
732 "Unknown";
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700733
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800734 lines.appendFormat(" Device status: %s\n", status);
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700735 if (mStatus == STATUS_ERROR) {
736 lines.appendFormat(" Error cause: %s\n", mErrorCause.string());
737 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800738 lines.appendFormat(" Stream configuration:\n");
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800739 const char *mode =
740 mOperatingMode == static_cast<int>(StreamConfigurationMode::NORMAL_MODE) ? "NORMAL" :
741 mOperatingMode == static_cast<int>(
742 StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE) ? "CONSTRAINED_HIGH_SPEED" :
743 "CUSTOM";
744 lines.appendFormat(" Operation mode: %s (%d) \n", mode, mOperatingMode);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800745
746 if (mInputStream != NULL) {
747 write(fd, lines.string(), lines.size());
748 mInputStream->dump(fd, args);
749 } else {
750 lines.appendFormat(" No input stream.\n");
751 write(fd, lines.string(), lines.size());
752 }
753 for (size_t i = 0; i < mOutputStreams.size(); i++) {
754 mOutputStreams[i]->dump(fd,args);
755 }
756
Zhijun He431503c2016-03-07 17:30:16 -0800757 if (mBufferManager != NULL) {
758 lines = String8(" Camera3 Buffer Manager:\n");
759 write(fd, lines.string(), lines.size());
760 mBufferManager->dump(fd, args);
761 }
Zhijun He125684a2015-12-26 15:07:30 -0800762
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700763 lines = String8(" In-flight requests:\n");
764 if (mInFlightMap.size() == 0) {
765 lines.append(" None\n");
766 } else {
767 for (size_t i = 0; i < mInFlightMap.size(); i++) {
768 InFlightRequest r = mInFlightMap.valueAt(i);
Colin Crosse5729fa2014-03-21 15:04:25 -0700769 lines.appendFormat(" Frame %d | Timestamp: %" PRId64 ", metadata"
Greg Kaiser51b882c2020-06-10 05:41:44 +0000770 " arrived: %s, buffers left: %d\n", mInFlightMap.keyAt(i),
Chien-Yu Chen43e69a62014-11-25 16:38:33 -0800771 r.shutterTimestamp, r.haveResultMetadata ? "true" : "false",
Greg Kaiser51b882c2020-06-10 05:41:44 +0000772 r.numBuffersLeft);
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700773 }
774 }
775 write(fd, lines.string(), lines.size());
776
Shuzhen Wang686f6442017-06-20 16:16:04 -0700777 if (mRequestThread != NULL) {
778 mRequestThread->dumpCaptureRequestLatency(fd,
779 " ProcessCaptureRequest latency histogram:");
780 }
781
Igor Murashkin1e479c02013-09-06 16:55:14 -0700782 {
783 lines = String8(" Last request sent:\n");
784 write(fd, lines.string(), lines.size());
785
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700786 CameraMetadata lastRequest = getLatestRequestLocked();
Igor Murashkin1e479c02013-09-06 16:55:14 -0700787 lastRequest.dump(fd, /*verbosity*/2, /*indentation*/6);
788 }
789
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800790 if (dumpTemplates) {
Emilian Peevf4816702020-04-03 15:44:51 -0700791 const char *templateNames[CAMERA_TEMPLATE_COUNT] = {
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800792 "TEMPLATE_PREVIEW",
793 "TEMPLATE_STILL_CAPTURE",
794 "TEMPLATE_VIDEO_RECORD",
795 "TEMPLATE_VIDEO_SNAPSHOT",
796 "TEMPLATE_ZERO_SHUTTER_LAG",
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -0800797 "TEMPLATE_MANUAL",
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800798 };
799
Emilian Peevf4816702020-04-03 15:44:51 -0700800 for (int i = 1; i < CAMERA_TEMPLATE_COUNT; i++) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800801 camera_metadata_t *templateRequest = nullptr;
802 mInterface->constructDefaultRequestSettings(
Emilian Peevf4816702020-04-03 15:44:51 -0700803 (camera_request_template_t) i, &templateRequest);
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800804 lines = String8::format(" HAL Request %s:\n", templateNames[i-1]);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800805 if (templateRequest == nullptr) {
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800806 lines.append(" Not supported\n");
807 write(fd, lines.string(), lines.size());
808 } else {
809 write(fd, lines.string(), lines.size());
810 dump_indented_camera_metadata(templateRequest,
811 fd, /*verbosity*/2, /*indentation*/8);
812 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800813 free_camera_metadata(templateRequest);
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800814 }
815 }
816
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700817 mTagMonitor.dumpMonitoredMetadata(fd);
818
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800819 if (mInterface->valid()) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -0800820 lines = String8(" HAL device dump:\n");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800821 write(fd, lines.string(), lines.size());
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800822 mInterface->dump(fd);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800823 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800824
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700825 if (gotLock) mLock.unlock();
826 if (gotInterfaceLock) mInterfaceLock.unlock();
827
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800828 return OK;
829}
830
Emilian Peevfaa4bde2020-01-23 12:19:37 -0800831const CameraMetadata& Camera3Device::infoPhysical(const String8& physicalId) const {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800832 ALOGVV("%s: E", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800833 if (CC_UNLIKELY(mStatus == STATUS_UNINITIALIZED ||
834 mStatus == STATUS_ERROR)) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700835 ALOGW("%s: Access to static info %s!", __FUNCTION__,
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800836 mStatus == STATUS_ERROR ?
837 "when in error state" : "before init");
838 }
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700839 if (physicalId.isEmpty()) {
840 return mDeviceInfo;
841 } else {
842 std::string id(physicalId.c_str());
843 if (mPhysicalDeviceInfoMap.find(id) != mPhysicalDeviceInfoMap.end()) {
844 return mPhysicalDeviceInfoMap.at(id);
845 } else {
846 ALOGE("%s: Invalid physical camera id %s", __FUNCTION__, physicalId.c_str());
847 return mDeviceInfo;
848 }
849 }
850}
851
852const CameraMetadata& Camera3Device::info() const {
853 String8 emptyId;
Emilian Peevfaa4bde2020-01-23 12:19:37 -0800854 return infoPhysical(emptyId);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800855}
856
Jianing Wei90e59c92014-03-12 18:29:36 -0700857status_t Camera3Device::checkStatusOkToCaptureLocked() {
858 switch (mStatus) {
859 case STATUS_ERROR:
860 CLOGE("Device has encountered a serious error");
861 return INVALID_OPERATION;
862 case STATUS_UNINITIALIZED:
863 CLOGE("Device not initialized");
864 return INVALID_OPERATION;
865 case STATUS_UNCONFIGURED:
866 case STATUS_CONFIGURED:
867 case STATUS_ACTIVE:
868 // OK
869 break;
870 default:
871 SET_ERR_L("Unexpected status: %d", mStatus);
872 return INVALID_OPERATION;
873 }
874 return OK;
875}
876
877status_t Camera3Device::convertMetadataListToRequestListLocked(
Emilian Peevaebbe412018-01-15 13:53:24 +0000878 const List<const PhysicalCameraSettingsList> &metadataList,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700879 const std::list<const SurfaceMap> &surfaceMaps,
Shuzhen Wang316781a2020-08-18 18:11:01 -0700880 bool repeating, nsecs_t requestTimeNs,
Shuzhen Wang9d066012016-09-30 11:30:20 -0700881 RequestList *requestList) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700882 if (requestList == NULL) {
883 CLOGE("requestList cannot be NULL.");
884 return BAD_VALUE;
885 }
886
Jianing Weicb0652e2014-03-12 18:29:36 -0700887 int32_t burstId = 0;
Emilian Peevaebbe412018-01-15 13:53:24 +0000888 List<const PhysicalCameraSettingsList>::const_iterator metadataIt = metadataList.begin();
Shuzhen Wang0129d522016-10-30 22:43:41 -0700889 std::list<const SurfaceMap>::const_iterator surfaceMapIt = surfaceMaps.begin();
890 for (; metadataIt != metadataList.end() && surfaceMapIt != surfaceMaps.end();
891 ++metadataIt, ++surfaceMapIt) {
892 sp<CaptureRequest> newRequest = setUpRequestLocked(*metadataIt, *surfaceMapIt);
Jianing Wei90e59c92014-03-12 18:29:36 -0700893 if (newRequest == 0) {
894 CLOGE("Can't create capture request");
895 return BAD_VALUE;
896 }
Jianing Weicb0652e2014-03-12 18:29:36 -0700897
Shuzhen Wang9d066012016-09-30 11:30:20 -0700898 newRequest->mRepeating = repeating;
Shuzhen Wang316781a2020-08-18 18:11:01 -0700899 newRequest->mRequestTimeNs = requestTimeNs;
Shuzhen Wang9d066012016-09-30 11:30:20 -0700900
Jianing Weicb0652e2014-03-12 18:29:36 -0700901 // Setup burst Id and request Id
902 newRequest->mResultExtras.burstId = burstId++;
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -0800903 auto requestIdEntry = metadataIt->begin()->metadata.find(ANDROID_REQUEST_ID);
904 if (requestIdEntry.count == 0) {
Jianing Weicb0652e2014-03-12 18:29:36 -0700905 CLOGE("RequestID does not exist in metadata");
906 return BAD_VALUE;
907 }
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -0800908 newRequest->mResultExtras.requestId = requestIdEntry.data.i32[0];
Jianing Weicb0652e2014-03-12 18:29:36 -0700909
Jianing Wei90e59c92014-03-12 18:29:36 -0700910 requestList->push_back(newRequest);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700911
912 ALOGV("%s: requestId = %" PRId32, __FUNCTION__, newRequest->mResultExtras.requestId);
Jianing Wei90e59c92014-03-12 18:29:36 -0700913 }
Shuzhen Wang0129d522016-10-30 22:43:41 -0700914 if (metadataIt != metadataList.end() || surfaceMapIt != surfaceMaps.end()) {
915 ALOGE("%s: metadataList and surfaceMaps are not the same size!", __FUNCTION__);
916 return BAD_VALUE;
917 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -0700918
919 // Setup batch size if this is a high speed video recording request.
920 if (mIsConstrainedHighSpeedConfiguration && requestList->size() > 0) {
921 auto firstRequest = requestList->begin();
922 for (auto& outputStream : (*firstRequest)->mOutputStreams) {
923 if (outputStream->isVideoStream()) {
924 (*firstRequest)->mBatchSize = requestList->size();
Yin-Chia Yeh14ef48d2020-02-10 15:06:37 -0800925 outputStream->setBatchSize(requestList->size());
Chien-Yu Chen85a64552015-08-28 15:46:12 -0700926 break;
927 }
928 }
929 }
930
Jianing Wei90e59c92014-03-12 18:29:36 -0700931 return OK;
932}
933
Yin-Chia Yeh7e5a2042019-02-06 16:01:06 -0800934status_t Camera3Device::capture(CameraMetadata &request, int64_t* lastFrameNumber) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800935 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800936
Emilian Peevaebbe412018-01-15 13:53:24 +0000937 List<const PhysicalCameraSettingsList> requestsList;
Shuzhen Wang0129d522016-10-30 22:43:41 -0700938 std::list<const SurfaceMap> surfaceMaps;
Emilian Peevaebbe412018-01-15 13:53:24 +0000939 convertToRequestList(requestsList, surfaceMaps, request);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700940
Yin-Chia Yeh7e5a2042019-02-06 16:01:06 -0800941 return captureList(requestsList, surfaceMaps, lastFrameNumber);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700942}
943
Emilian Peevaebbe412018-01-15 13:53:24 +0000944void Camera3Device::convertToRequestList(List<const PhysicalCameraSettingsList>& requestsList,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700945 std::list<const SurfaceMap>& surfaceMaps,
946 const CameraMetadata& request) {
Emilian Peevaebbe412018-01-15 13:53:24 +0000947 PhysicalCameraSettingsList requestList;
948 requestList.push_back({std::string(getId().string()), request});
949 requestsList.push_back(requestList);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700950
951 SurfaceMap surfaceMap;
952 camera_metadata_ro_entry streams = request.find(ANDROID_REQUEST_OUTPUT_STREAMS);
953 // With no surface list passed in, stream and surface will have 1-to-1
954 // mapping. So the surface index is 0 for each stream in the surfaceMap.
955 for (size_t i = 0; i < streams.count; i++) {
956 surfaceMap[streams.data.i32[i]].push_back(0);
957 }
958 surfaceMaps.push_back(surfaceMap);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800959}
960
Jianing Wei90e59c92014-03-12 18:29:36 -0700961status_t Camera3Device::submitRequestsHelper(
Emilian Peevaebbe412018-01-15 13:53:24 +0000962 const List<const PhysicalCameraSettingsList> &requests,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700963 const std::list<const SurfaceMap> &surfaceMaps,
964 bool repeating,
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700965 /*out*/
966 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700967 ATRACE_CALL();
Shuzhen Wang316781a2020-08-18 18:11:01 -0700968 nsecs_t requestTimeNs = systemTime();
969
Jianing Wei90e59c92014-03-12 18:29:36 -0700970 Mutex::Autolock il(mInterfaceLock);
971 Mutex::Autolock l(mLock);
972
973 status_t res = checkStatusOkToCaptureLocked();
974 if (res != OK) {
975 // error logged by previous call
976 return res;
977 }
978
979 RequestList requestList;
980
Shuzhen Wang0129d522016-10-30 22:43:41 -0700981 res = convertMetadataListToRequestListLocked(requests, surfaceMaps,
Shuzhen Wang316781a2020-08-18 18:11:01 -0700982 repeating, requestTimeNs, /*out*/&requestList);
Jianing Wei90e59c92014-03-12 18:29:36 -0700983 if (res != OK) {
984 // error logged by previous call
985 return res;
986 }
987
988 if (repeating) {
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700989 res = mRequestThread->setRepeatingRequests(requestList, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -0700990 } else {
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700991 res = mRequestThread->queueRequestList(requestList, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -0700992 }
993
994 if (res == OK) {
995 waitUntilStateThenRelock(/*active*/true, kActiveTimeout);
996 if (res != OK) {
997 SET_ERR_L("Can't transition to active in %f seconds!",
998 kActiveTimeout/1e9);
999 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001000 ALOGV("Camera %s: Capture request %" PRId32 " enqueued", mId.string(),
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07001001 (*(requestList.begin()))->mResultExtras.requestId);
Jianing Wei90e59c92014-03-12 18:29:36 -07001002 } else {
1003 CLOGE("Cannot queue request. Impossible.");
1004 return BAD_VALUE;
1005 }
1006
1007 return res;
1008}
1009
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001010hardware::Return<void> Camera3Device::requestStreamBuffers(
1011 const hardware::hidl_vec<hardware::camera::device::V3_5::BufferRequest>& bufReqs,
1012 requestStreamBuffers_cb _hidl_cb) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001013 RequestBufferStates states {
Shuzhen Wang316781a2020-08-18 18:11:01 -07001014 mId, mRequestBufferInterfaceLock, mUseHalBufManager, mOutputStreams, mSessionStatsBuilder,
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001015 *this, *mInterface, *this};
1016 camera3::requestStreamBuffers(states, bufReqs, _hidl_cb);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001017 return hardware::Void();
1018}
1019
1020hardware::Return<void> Camera3Device::returnStreamBuffers(
1021 const hardware::hidl_vec<hardware::camera::device::V3_2::StreamBuffer>& buffers) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001022 ReturnBufferStates states {
Shuzhen Wang316781a2020-08-18 18:11:01 -07001023 mId, mUseHalBufManager, mOutputStreams, mSessionStatsBuilder, *mInterface};
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001024 camera3::returnStreamBuffers(states, buffers);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001025 return hardware::Void();
1026}
1027
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001028hardware::Return<void> Camera3Device::processCaptureResult_3_4(
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001029 const hardware::hidl_vec<
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001030 hardware::camera::device::V3_4::CaptureResult>& results) {
Yin-Chia Yeh657c1872017-07-18 18:09:57 -07001031 // Ideally we should grab mLock, but that can lead to deadlock, and
1032 // it's not super important to get up to date value of mStatus for this
1033 // warning print, hence skipping the lock here
1034 if (mStatus == STATUS_ERROR) {
1035 // Per API contract, HAL should act as closed after device error
1036 // But mStatus can be set to error by framework as well, so just log
1037 // a warning here.
1038 ALOGW("%s: received capture result in error state.", __FUNCTION__);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07001039 }
Yifan Honga640c5a2017-04-12 16:30:31 -07001040
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001041 sp<NotificationListener> listener;
1042 {
1043 std::lock_guard<std::mutex> l(mOutputLock);
1044 listener = mListener.promote();
1045 }
1046
Yifan Honga640c5a2017-04-12 16:30:31 -07001047 if (mProcessCaptureResultLock.tryLock() != OK) {
1048 // This should never happen; it indicates a wrong client implementation
1049 // that doesn't follow the contract. But, we can be tolerant here.
1050 ALOGE("%s: callback overlapped! waiting 1s...",
1051 __FUNCTION__);
1052 if (mProcessCaptureResultLock.timedLock(1000000000 /* 1s */) != OK) {
1053 ALOGE("%s: cannot acquire lock in 1s, dropping results",
1054 __FUNCTION__);
1055 // really don't know what to do, so bail out.
1056 return hardware::Void();
1057 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001058 }
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001059 CaptureOutputStates states {
1060 mId,
Shuzhen Wangb7b42652020-05-07 11:59:02 -07001061 mInFlightLock, mLastCompletedRegularFrameNumber,
1062 mLastCompletedReprocessFrameNumber, mLastCompletedZslFrameNumber,
1063 mInFlightMap, mOutputLock, mResultQueue, mResultSignal,
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001064 mNextShutterFrameNumber,
1065 mNextReprocessShutterFrameNumber, mNextZslStillShutterFrameNumber,
1066 mNextResultFrameNumber,
1067 mNextReprocessResultFrameNumber, mNextZslStillResultFrameNumber,
1068 mUseHalBufManager, mUsePartialResult, mNeedFixupMonochromeTags,
1069 mNumPartialResults, mVendorTagId, mDeviceInfo, mPhysicalDeviceInfoMap,
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08001070 mResultMetadataQueue, mDistortionMappers, mZoomRatioMappers, mRotateAndCropMappers,
Shuzhen Wang316781a2020-08-18 18:11:01 -07001071 mTagMonitor, mInputStream, mOutputStreams, mSessionStatsBuilder, listener, *this, *this,
1072 *mInterface
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001073 };
1074
Yifan Honga640c5a2017-04-12 16:30:31 -07001075 for (const auto& result : results) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001076 processOneCaptureResultLocked(states, result.v3_2, result.physicalCameraMetadata);
Yifan Honga640c5a2017-04-12 16:30:31 -07001077 }
1078 mProcessCaptureResultLock.unlock();
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001079 return hardware::Void();
1080}
1081
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001082// Only one processCaptureResult should be called at a time, so
1083// the locks won't block. The locks are present here simply to enforce this.
1084hardware::Return<void> Camera3Device::processCaptureResult(
1085 const hardware::hidl_vec<
1086 hardware::camera::device::V3_2::CaptureResult>& results) {
1087 hardware::hidl_vec<hardware::camera::device::V3_4::PhysicalCameraMetadata> noPhysMetadata;
1088
1089 // Ideally we should grab mLock, but that can lead to deadlock, and
1090 // it's not super important to get up to date value of mStatus for this
1091 // warning print, hence skipping the lock here
1092 if (mStatus == STATUS_ERROR) {
1093 // Per API contract, HAL should act as closed after device error
1094 // But mStatus can be set to error by framework as well, so just log
1095 // a warning here.
1096 ALOGW("%s: received capture result in error state.", __FUNCTION__);
1097 }
1098
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001099 sp<NotificationListener> listener;
1100 {
1101 std::lock_guard<std::mutex> l(mOutputLock);
1102 listener = mListener.promote();
1103 }
1104
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001105 if (mProcessCaptureResultLock.tryLock() != OK) {
1106 // This should never happen; it indicates a wrong client implementation
1107 // that doesn't follow the contract. But, we can be tolerant here.
1108 ALOGE("%s: callback overlapped! waiting 1s...",
1109 __FUNCTION__);
1110 if (mProcessCaptureResultLock.timedLock(1000000000 /* 1s */) != OK) {
1111 ALOGE("%s: cannot acquire lock in 1s, dropping results",
1112 __FUNCTION__);
1113 // really don't know what to do, so bail out.
1114 return hardware::Void();
1115 }
1116 }
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001117
1118 CaptureOutputStates states {
1119 mId,
Shuzhen Wangb7b42652020-05-07 11:59:02 -07001120 mInFlightLock, mLastCompletedRegularFrameNumber,
1121 mLastCompletedReprocessFrameNumber, mLastCompletedZslFrameNumber,
1122 mInFlightMap, mOutputLock, mResultQueue, mResultSignal,
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001123 mNextShutterFrameNumber,
1124 mNextReprocessShutterFrameNumber, mNextZslStillShutterFrameNumber,
1125 mNextResultFrameNumber,
1126 mNextReprocessResultFrameNumber, mNextZslStillResultFrameNumber,
1127 mUseHalBufManager, mUsePartialResult, mNeedFixupMonochromeTags,
1128 mNumPartialResults, mVendorTagId, mDeviceInfo, mPhysicalDeviceInfoMap,
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08001129 mResultMetadataQueue, mDistortionMappers, mZoomRatioMappers, mRotateAndCropMappers,
Shuzhen Wang316781a2020-08-18 18:11:01 -07001130 mTagMonitor, mInputStream, mOutputStreams, mSessionStatsBuilder, listener, *this, *this,
1131 *mInterface
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001132 };
1133
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001134 for (const auto& result : results) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001135 processOneCaptureResultLocked(states, result, noPhysMetadata);
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001136 }
1137 mProcessCaptureResultLock.unlock();
1138 return hardware::Void();
1139}
1140
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001141hardware::Return<void> Camera3Device::notify(
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001142 const hardware::hidl_vec<hardware::camera::device::V3_2::NotifyMsg>& msgs) {
Yin-Chia Yeh657c1872017-07-18 18:09:57 -07001143 // Ideally we should grab mLock, but that can lead to deadlock, and
1144 // it's not super important to get up to date value of mStatus for this
1145 // warning print, hence skipping the lock here
1146 if (mStatus == STATUS_ERROR) {
1147 // Per API contract, HAL should act as closed after device error
1148 // But mStatus can be set to error by framework as well, so just log
1149 // a warning here.
1150 ALOGW("%s: received notify message in error state.", __FUNCTION__);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07001151 }
Yin-Chia Yeh657c1872017-07-18 18:09:57 -07001152
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001153 sp<NotificationListener> listener;
1154 {
1155 std::lock_guard<std::mutex> l(mOutputLock);
1156 listener = mListener.promote();
1157 }
1158
1159 CaptureOutputStates states {
1160 mId,
Shuzhen Wangb7b42652020-05-07 11:59:02 -07001161 mInFlightLock, mLastCompletedRegularFrameNumber,
1162 mLastCompletedReprocessFrameNumber, mLastCompletedZslFrameNumber,
1163 mInFlightMap, mOutputLock, mResultQueue, mResultSignal,
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001164 mNextShutterFrameNumber,
1165 mNextReprocessShutterFrameNumber, mNextZslStillShutterFrameNumber,
1166 mNextResultFrameNumber,
1167 mNextReprocessResultFrameNumber, mNextZslStillResultFrameNumber,
1168 mUseHalBufManager, mUsePartialResult, mNeedFixupMonochromeTags,
1169 mNumPartialResults, mVendorTagId, mDeviceInfo, mPhysicalDeviceInfoMap,
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08001170 mResultMetadataQueue, mDistortionMappers, mZoomRatioMappers, mRotateAndCropMappers,
Shuzhen Wang316781a2020-08-18 18:11:01 -07001171 mTagMonitor, mInputStream, mOutputStreams, mSessionStatsBuilder, listener, *this, *this,
1172 *mInterface
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001173 };
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001174 for (const auto& msg : msgs) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001175 camera3::notify(states, msg);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001176 }
1177 return hardware::Void();
1178}
1179
Emilian Peevaebbe412018-01-15 13:53:24 +00001180status_t Camera3Device::captureList(const List<const PhysicalCameraSettingsList> &requestsList,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001181 const std::list<const SurfaceMap> &surfaceMaps,
Jianing Weicb0652e2014-03-12 18:29:36 -07001182 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -07001183 ATRACE_CALL();
1184
Emilian Peevaebbe412018-01-15 13:53:24 +00001185 return submitRequestsHelper(requestsList, surfaceMaps, /*repeating*/false, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -07001186}
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001187
Jianing Weicb0652e2014-03-12 18:29:36 -07001188status_t Camera3Device::setStreamingRequest(const CameraMetadata &request,
1189 int64_t* /*lastFrameNumber*/) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001190 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001191
Emilian Peevaebbe412018-01-15 13:53:24 +00001192 List<const PhysicalCameraSettingsList> requestsList;
Shuzhen Wang0129d522016-10-30 22:43:41 -07001193 std::list<const SurfaceMap> surfaceMaps;
Emilian Peevaebbe412018-01-15 13:53:24 +00001194 convertToRequestList(requestsList, surfaceMaps, request);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001195
Emilian Peevaebbe412018-01-15 13:53:24 +00001196 return setStreamingRequestList(requestsList, /*surfaceMap*/surfaceMaps,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001197 /*lastFrameNumber*/NULL);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001198}
1199
Emilian Peevaebbe412018-01-15 13:53:24 +00001200status_t Camera3Device::setStreamingRequestList(
1201 const List<const PhysicalCameraSettingsList> &requestsList,
1202 const std::list<const SurfaceMap> &surfaceMaps, int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -07001203 ATRACE_CALL();
1204
Emilian Peevaebbe412018-01-15 13:53:24 +00001205 return submitRequestsHelper(requestsList, surfaceMaps, /*repeating*/true, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -07001206}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001207
1208sp<Camera3Device::CaptureRequest> Camera3Device::setUpRequestLocked(
Emilian Peevaebbe412018-01-15 13:53:24 +00001209 const PhysicalCameraSettingsList &request, const SurfaceMap &surfaceMap) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001210 status_t res;
1211
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001212 if (mStatus == STATUS_UNCONFIGURED || mNeedConfig) {
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08001213 // This point should only be reached via API1 (API2 must explicitly call configureStreams)
1214 // so unilaterally select normal operating mode.
Emilian Peevaebbe412018-01-15 13:53:24 +00001215 res = filterParamsAndConfigureLocked(request.begin()->metadata,
Emilian Peevf4816702020-04-03 15:44:51 -07001216 CAMERA_STREAM_CONFIGURATION_NORMAL_MODE);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001217 // Stream configuration failed. Client might try other configuraitons.
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001218 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001219 CLOGE("Can't set up streams: %s (%d)", strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001220 return NULL;
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001221 } else if (mStatus == STATUS_UNCONFIGURED) {
1222 // Stream configuration successfully configure to empty stream configuration.
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001223 CLOGE("No streams configured");
1224 return NULL;
1225 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001226 }
1227
Shuzhen Wang0129d522016-10-30 22:43:41 -07001228 sp<CaptureRequest> newRequest = createCaptureRequest(request, surfaceMap);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001229 return newRequest;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001230}
1231
Jianing Weicb0652e2014-03-12 18:29:36 -07001232status_t Camera3Device::clearStreamingRequest(int64_t *lastFrameNumber) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001233 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001234 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001235 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001236
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001237 switch (mStatus) {
1238 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001239 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001240 return INVALID_OPERATION;
1241 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001242 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001243 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001244 case STATUS_UNCONFIGURED:
1245 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001246 case STATUS_ACTIVE:
1247 // OK
1248 break;
1249 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001250 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001251 return INVALID_OPERATION;
1252 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001253 ALOGV("Camera %s: Clearing repeating request", mId.string());
Jianing Weicb0652e2014-03-12 18:29:36 -07001254
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07001255 return mRequestThread->clearRepeatingRequests(lastFrameNumber);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001256}
1257
1258status_t Camera3Device::waitUntilRequestReceived(int32_t requestId, nsecs_t timeout) {
1259 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001260 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001261
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001262 return mRequestThread->waitUntilRequestProcessed(requestId, timeout);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001263}
1264
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001265status_t Camera3Device::createInputStream(
1266 uint32_t width, uint32_t height, int format, int *id) {
1267 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001268 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001269 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001270 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001271 ALOGV("Camera %s: Creating new input stream %d: %d x %d, format %d",
1272 mId.string(), mNextStreamId, width, height, format);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001273
1274 status_t res;
1275 bool wasActive = false;
1276
1277 switch (mStatus) {
1278 case STATUS_ERROR:
1279 ALOGE("%s: Device has encountered a serious error", __FUNCTION__);
1280 return INVALID_OPERATION;
1281 case STATUS_UNINITIALIZED:
1282 ALOGE("%s: Device not initialized", __FUNCTION__);
1283 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001284 case STATUS_UNCONFIGURED:
1285 case STATUS_CONFIGURED:
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001286 // OK
1287 break;
1288 case STATUS_ACTIVE:
1289 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001290 res = internalPauseAndWaitLocked(maxExpectedDuration);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001291 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001292 SET_ERR_L("Can't pause captures to reconfigure streams!");
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001293 return res;
1294 }
1295 wasActive = true;
1296 break;
1297 default:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001298 SET_ERR_L("%s: Unexpected status: %d", mStatus);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001299 return INVALID_OPERATION;
1300 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001301 assert(mStatus != STATUS_ACTIVE);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001302
1303 if (mInputStream != 0) {
1304 ALOGE("%s: Cannot create more than 1 input stream", __FUNCTION__);
1305 return INVALID_OPERATION;
1306 }
1307
1308 sp<Camera3InputStream> newStream = new Camera3InputStream(mNextStreamId,
1309 width, height, format);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001310 newStream->setStatusTracker(mStatusTracker);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001311
1312 mInputStream = newStream;
1313
1314 *id = mNextStreamId++;
1315
1316 // Continue captures if active at start
1317 if (wasActive) {
1318 ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001319 // Reuse current operating mode and session parameters for new stream config
1320 res = configureStreamsLocked(mOperatingMode, mSessionParams);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001321 if (res != OK) {
1322 ALOGE("%s: Can't reconfigure device for new stream %d: %s (%d)",
1323 __FUNCTION__, mNextStreamId, strerror(-res), res);
1324 return res;
1325 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001326 internalResumeLocked();
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001327 }
1328
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001329 ALOGV("Camera %s: Created input stream", mId.string());
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001330 return OK;
1331}
1332
Eino-Ville Talvala727d1722015-06-09 13:44:19 -07001333status_t Camera3Device::createStream(sp<Surface> consumer,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001334 uint32_t width, uint32_t height, int format,
Emilian Peevf4816702020-04-03 15:44:51 -07001335 android_dataspace dataSpace, camera_stream_rotation_t rotation, int *id,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001336 const String8& physicalCameraId,
Emilian Peev40ead602017-09-26 15:46:36 +01001337 std::vector<int> *surfaceIds, int streamSetId, bool isShared, uint64_t consumerUsage) {
Shuzhen Wang0129d522016-10-30 22:43:41 -07001338 ATRACE_CALL();
1339
1340 if (consumer == nullptr) {
1341 ALOGE("%s: consumer must not be null", __FUNCTION__);
1342 return BAD_VALUE;
1343 }
1344
1345 std::vector<sp<Surface>> consumers;
1346 consumers.push_back(consumer);
1347
1348 return createStream(consumers, /*hasDeferredConsumer*/ false, width, height,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001349 format, dataSpace, rotation, id, physicalCameraId, surfaceIds, streamSetId,
1350 isShared, consumerUsage);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001351}
1352
1353status_t Camera3Device::createStream(const std::vector<sp<Surface>>& consumers,
1354 bool hasDeferredConsumer, uint32_t width, uint32_t height, int format,
Emilian Peevf4816702020-04-03 15:44:51 -07001355 android_dataspace dataSpace, camera_stream_rotation_t rotation, int *id,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001356 const String8& physicalCameraId,
Emilian Peev40ead602017-09-26 15:46:36 +01001357 std::vector<int> *surfaceIds, int streamSetId, bool isShared, uint64_t consumerUsage) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001358 ATRACE_CALL();
Emilian Peev40ead602017-09-26 15:46:36 +01001359
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001360 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001361 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001362 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001363 ALOGV("Camera %s: Creating new stream %d: %d x %d, format %d, dataspace %d rotation %d"
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001364 " consumer usage %" PRIu64 ", isShared %d, physicalCameraId %s", mId.string(),
1365 mNextStreamId, width, height, format, dataSpace, rotation, consumerUsage, isShared,
1366 physicalCameraId.string());
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001367
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001368 status_t res;
1369 bool wasActive = false;
1370
1371 switch (mStatus) {
1372 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001373 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001374 return INVALID_OPERATION;
1375 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001376 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001377 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001378 case STATUS_UNCONFIGURED:
1379 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001380 // OK
1381 break;
1382 case STATUS_ACTIVE:
1383 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001384 res = internalPauseAndWaitLocked(maxExpectedDuration);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001385 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001386 SET_ERR_L("Can't pause captures to reconfigure streams!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001387 return res;
1388 }
1389 wasActive = true;
1390 break;
1391 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001392 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001393 return INVALID_OPERATION;
1394 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001395 assert(mStatus != STATUS_ACTIVE);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001396
1397 sp<Camera3OutputStream> newStream;
Zhijun He5d677d12016-05-29 16:52:39 -07001398
Shuzhen Wang0129d522016-10-30 22:43:41 -07001399 if (consumers.size() == 0 && !hasDeferredConsumer) {
1400 ALOGE("%s: Number of consumers cannot be smaller than 1", __FUNCTION__);
1401 return BAD_VALUE;
1402 }
Zhijun He5d677d12016-05-29 16:52:39 -07001403
Shuzhen Wang0129d522016-10-30 22:43:41 -07001404 if (hasDeferredConsumer && format != HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
Zhijun He5d677d12016-05-29 16:52:39 -07001405 ALOGE("Deferred consumer stream creation only support IMPLEMENTATION_DEFINED format");
1406 return BAD_VALUE;
1407 }
1408
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001409 if (format == HAL_PIXEL_FORMAT_BLOB) {
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -07001410 ssize_t blobBufferSize;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001411 if (dataSpace == HAL_DATASPACE_DEPTH) {
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -07001412 blobBufferSize = getPointCloudBufferSize();
1413 if (blobBufferSize <= 0) {
1414 SET_ERR_L("Invalid point cloud buffer size %zd", blobBufferSize);
1415 return BAD_VALUE;
1416 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001417 } else if (dataSpace == static_cast<android_dataspace>(HAL_DATASPACE_JPEG_APP_SEGMENTS)) {
1418 blobBufferSize = width * height;
1419 } else {
1420 blobBufferSize = getJpegBufferSize(width, height);
1421 if (blobBufferSize <= 0) {
1422 SET_ERR_L("Invalid jpeg buffer size %zd", blobBufferSize);
1423 return BAD_VALUE;
1424 }
Zhijun Hef7da0962014-04-24 13:27:56 -07001425 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001426 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001427 width, height, blobBufferSize, format, dataSpace, rotation,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001428 mTimestampOffset, physicalCameraId, streamSetId);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -08001429 } else if (format == HAL_PIXEL_FORMAT_RAW_OPAQUE) {
1430 ssize_t rawOpaqueBufferSize = getRawOpaqueBufferSize(width, height);
1431 if (rawOpaqueBufferSize <= 0) {
1432 SET_ERR_L("Invalid RAW opaque buffer size %zd", rawOpaqueBufferSize);
1433 return BAD_VALUE;
1434 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001435 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001436 width, height, rawOpaqueBufferSize, format, dataSpace, rotation,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001437 mTimestampOffset, physicalCameraId, streamSetId);
Shuzhen Wang758c2152017-01-10 18:26:18 -08001438 } else if (isShared) {
1439 newStream = new Camera3SharedOutputStream(mNextStreamId, consumers,
1440 width, height, format, consumerUsage, dataSpace, rotation,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07001441 mTimestampOffset, physicalCameraId, streamSetId,
1442 mUseHalBufManager);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001443 } else if (consumers.size() == 0 && hasDeferredConsumer) {
Zhijun He5d677d12016-05-29 16:52:39 -07001444 newStream = new Camera3OutputStream(mNextStreamId,
1445 width, height, format, consumerUsage, dataSpace, rotation,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001446 mTimestampOffset, physicalCameraId, streamSetId);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001447 } else {
Shuzhen Wang0129d522016-10-30 22:43:41 -07001448 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001449 width, height, format, dataSpace, rotation,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001450 mTimestampOffset, physicalCameraId, streamSetId);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001451 }
Emilian Peev40ead602017-09-26 15:46:36 +01001452
1453 size_t consumerCount = consumers.size();
1454 for (size_t i = 0; i < consumerCount; i++) {
1455 int id = newStream->getSurfaceId(consumers[i]);
1456 if (id < 0) {
1457 SET_ERR_L("Invalid surface id");
1458 return BAD_VALUE;
1459 }
1460 if (surfaceIds != nullptr) {
1461 surfaceIds->push_back(id);
1462 }
1463 }
1464
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001465 newStream->setStatusTracker(mStatusTracker);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001466
Emilian Peev08dd2452017-04-06 16:55:14 +01001467 newStream->setBufferManager(mBufferManager);
Zhijun He125684a2015-12-26 15:07:30 -08001468
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08001469 newStream->setImageDumpMask(mImageDumpMask);
1470
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001471 res = mOutputStreams.add(mNextStreamId, newStream);
1472 if (res < 0) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001473 SET_ERR_L("Can't add new stream to set: %s (%d)", strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001474 return res;
1475 }
1476
Shuzhen Wang316781a2020-08-18 18:11:01 -07001477 mSessionStatsBuilder.addStream(mNextStreamId);
1478
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001479 *id = mNextStreamId++;
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07001480 mNeedConfig = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001481
1482 // Continue captures if active at start
1483 if (wasActive) {
1484 ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001485 // Reuse current operating mode and session parameters for new stream config
1486 res = configureStreamsLocked(mOperatingMode, mSessionParams);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001487 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001488 CLOGE("Can't reconfigure device for new stream %d: %s (%d)",
1489 mNextStreamId, strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001490 return res;
1491 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001492 internalResumeLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001493 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001494 ALOGV("Camera %s: Created new stream", mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001495 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001496}
1497
Emilian Peev710c1422017-08-30 11:19:38 +01001498status_t Camera3Device::getStreamInfo(int id, StreamInfo *streamInfo) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001499 ATRACE_CALL();
Emilian Peev710c1422017-08-30 11:19:38 +01001500 if (nullptr == streamInfo) {
1501 return BAD_VALUE;
1502 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001503 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001504 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001505
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001506 switch (mStatus) {
1507 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001508 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001509 return INVALID_OPERATION;
1510 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001511 CLOGE("Device not initialized!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001512 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001513 case STATUS_UNCONFIGURED:
1514 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001515 case STATUS_ACTIVE:
1516 // OK
1517 break;
1518 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001519 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001520 return INVALID_OPERATION;
1521 }
1522
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001523 sp<Camera3StreamInterface> stream = mOutputStreams.get(id);
1524 if (stream == nullptr) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001525 CLOGE("Stream %d is unknown", id);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001526 return BAD_VALUE;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001527 }
1528
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001529 streamInfo->width = stream->getWidth();
1530 streamInfo->height = stream->getHeight();
1531 streamInfo->format = stream->getFormat();
1532 streamInfo->dataSpace = stream->getDataSpace();
1533 streamInfo->formatOverridden = stream->isFormatOverridden();
1534 streamInfo->originalFormat = stream->getOriginalFormat();
1535 streamInfo->dataSpaceOverridden = stream->isDataSpaceOverridden();
1536 streamInfo->originalDataSpace = stream->getOriginalDataSpace();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001537 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001538}
1539
1540status_t Camera3Device::setStreamTransform(int id,
1541 int transform) {
1542 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001543 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001544 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001545
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001546 switch (mStatus) {
1547 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001548 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001549 return INVALID_OPERATION;
1550 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001551 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001552 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001553 case STATUS_UNCONFIGURED:
1554 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001555 case STATUS_ACTIVE:
1556 // OK
1557 break;
1558 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001559 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001560 return INVALID_OPERATION;
1561 }
1562
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001563 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(id);
1564 if (stream == nullptr) {
1565 CLOGE("Stream %d does not exist", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001566 return BAD_VALUE;
1567 }
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001568 return stream->setTransform(transform);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001569}
1570
1571status_t Camera3Device::deleteStream(int id) {
1572 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001573 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001574 Mutex::Autolock l(mLock);
1575 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001576
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001577 ALOGV("%s: Camera %s: Deleting stream %d", __FUNCTION__, mId.string(), id);
Igor Murashkine2172be2013-05-28 15:31:39 -07001578
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001579 // CameraDevice semantics require device to already be idle before
1580 // deleteStream is called, unlike for createStream.
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001581 if (mStatus == STATUS_ACTIVE) {
Yin-Chia Yeh693047d2018-03-08 12:14:19 -08001582 ALOGW("%s: Camera %s: Device not idle", __FUNCTION__, mId.string());
Igor Murashkin52827132013-05-13 14:53:44 -07001583 return -EBUSY;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001584 }
1585
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07001586 if (mStatus == STATUS_ERROR) {
1587 ALOGW("%s: Camera %s: deleteStream not allowed in ERROR state",
1588 __FUNCTION__, mId.string());
1589 return -EBUSY;
1590 }
1591
Igor Murashkin2fba5842013-04-22 14:03:54 -07001592 sp<Camera3StreamInterface> deletedStream;
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001593 sp<Camera3StreamInterface> stream = mOutputStreams.get(id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001594 if (mInputStream != NULL && id == mInputStream->getId()) {
1595 deletedStream = mInputStream;
1596 mInputStream.clear();
1597 } else {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001598 if (stream == nullptr) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001599 CLOGE("Stream %d does not exist", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001600 return BAD_VALUE;
1601 }
Shuzhen Wang316781a2020-08-18 18:11:01 -07001602 mSessionStatsBuilder.removeStream(id);
Zhijun He5f446352014-01-22 09:49:33 -08001603 }
1604
1605 // Delete output stream or the output part of a bi-directional stream.
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001606 if (stream != nullptr) {
1607 deletedStream = stream;
1608 mOutputStreams.remove(id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001609 }
1610
1611 // Free up the stream endpoint so that it can be used by some other stream
1612 res = deletedStream->disconnect();
1613 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001614 SET_ERR_L("Can't disconnect deleted stream %d", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001615 // fall through since we want to still list the stream as deleted.
1616 }
1617 mDeletedStreams.add(deletedStream);
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07001618 mNeedConfig = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001619
1620 return res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001621}
1622
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001623status_t Camera3Device::configureStreams(const CameraMetadata& sessionParams, int operatingMode) {
Igor Murashkine2d167e2014-08-19 16:19:59 -07001624 ATRACE_CALL();
1625 ALOGV("%s: E", __FUNCTION__);
1626
1627 Mutex::Autolock il(mInterfaceLock);
1628 Mutex::Autolock l(mLock);
Chien-Yu Chen17338fc2015-06-18 16:30:12 -07001629
Emilian Peev811d2952018-05-25 11:08:40 +01001630 // In case the client doesn't include any session parameter, try a
1631 // speculative configuration using the values from the last cached
1632 // default request.
1633 if (sessionParams.isEmpty() &&
Emilian Peevf4816702020-04-03 15:44:51 -07001634 ((mLastTemplateId > 0) && (mLastTemplateId < CAMERA_TEMPLATE_COUNT)) &&
Emilian Peev811d2952018-05-25 11:08:40 +01001635 (!mRequestTemplateCache[mLastTemplateId].isEmpty())) {
1636 ALOGV("%s: Speculative session param configuration with template id: %d", __func__,
1637 mLastTemplateId);
1638 return filterParamsAndConfigureLocked(mRequestTemplateCache[mLastTemplateId],
1639 operatingMode);
1640 }
1641
Emilian Peevac3ce6c2017-12-12 15:27:02 +00001642 return filterParamsAndConfigureLocked(sessionParams, operatingMode);
1643}
1644
1645status_t Camera3Device::filterParamsAndConfigureLocked(const CameraMetadata& sessionParams,
1646 int operatingMode) {
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001647 //Filter out any incoming session parameters
1648 const CameraMetadata params(sessionParams);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001649 camera_metadata_entry_t availableSessionKeys = mDeviceInfo.find(
1650 ANDROID_REQUEST_AVAILABLE_SESSION_KEYS);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00001651 CameraMetadata filteredParams(availableSessionKeys.count);
1652 camera_metadata_t *meta = const_cast<camera_metadata_t *>(
1653 filteredParams.getAndLock());
1654 set_camera_metadata_vendor_id(meta, mVendorTagId);
1655 filteredParams.unlock(meta);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001656 if (availableSessionKeys.count > 0) {
1657 for (size_t i = 0; i < availableSessionKeys.count; i++) {
1658 camera_metadata_ro_entry entry = params.find(
1659 availableSessionKeys.data.i32[i]);
1660 if (entry.count > 0) {
1661 filteredParams.update(entry);
1662 }
1663 }
1664 }
1665
1666 return configureStreamsLocked(operatingMode, filteredParams);
Igor Murashkine2d167e2014-08-19 16:19:59 -07001667}
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001668
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07001669status_t Camera3Device::getInputBufferProducer(
1670 sp<IGraphicBufferProducer> *producer) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07001671 ATRACE_CALL();
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07001672 Mutex::Autolock il(mInterfaceLock);
1673 Mutex::Autolock l(mLock);
1674
1675 if (producer == NULL) {
1676 return BAD_VALUE;
1677 } else if (mInputStream == NULL) {
1678 return INVALID_OPERATION;
1679 }
1680
1681 return mInputStream->getInputBufferProducer(producer);
1682}
1683
Emilian Peevf4816702020-04-03 15:44:51 -07001684status_t Camera3Device::createDefaultRequest(camera_request_template_t templateId,
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001685 CameraMetadata *request) {
1686 ATRACE_CALL();
Alex Rayfe7e0c62013-05-30 00:12:13 -07001687 ALOGV("%s: for template %d", __FUNCTION__, templateId);
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08001688
Emilian Peevf4816702020-04-03 15:44:51 -07001689 if (templateId <= 0 || templateId >= CAMERA_TEMPLATE_COUNT) {
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08001690 android_errorWriteWithInfoLog(CameraService::SN_EVENT_LOG_ID, "26866110",
Jayant Chowdhary12361932018-08-27 14:46:13 -07001691 CameraThreadState::getCallingUid(), nullptr, 0);
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08001692 return BAD_VALUE;
1693 }
1694
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001695 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001696
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001697 {
1698 Mutex::Autolock l(mLock);
1699 switch (mStatus) {
1700 case STATUS_ERROR:
1701 CLOGE("Device has encountered a serious error");
1702 return INVALID_OPERATION;
1703 case STATUS_UNINITIALIZED:
1704 CLOGE("Device is not initialized!");
1705 return INVALID_OPERATION;
1706 case STATUS_UNCONFIGURED:
1707 case STATUS_CONFIGURED:
1708 case STATUS_ACTIVE:
1709 // OK
1710 break;
1711 default:
1712 SET_ERR_L("Unexpected status: %d", mStatus);
1713 return INVALID_OPERATION;
1714 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001715
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001716 if (!mRequestTemplateCache[templateId].isEmpty()) {
1717 *request = mRequestTemplateCache[templateId];
Emilian Peev811d2952018-05-25 11:08:40 +01001718 mLastTemplateId = templateId;
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001719 return OK;
1720 }
Zhijun Hea1530f12014-09-14 12:44:20 -07001721 }
1722
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001723 camera_metadata_t *rawRequest;
1724 status_t res = mInterface->constructDefaultRequestSettings(
Emilian Peevf4816702020-04-03 15:44:51 -07001725 (camera_request_template_t) templateId, &rawRequest);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001726
1727 {
1728 Mutex::Autolock l(mLock);
1729 if (res == BAD_VALUE) {
1730 ALOGI("%s: template %d is not supported on this camera device",
1731 __FUNCTION__, templateId);
1732 return res;
1733 } else if (res != OK) {
1734 CLOGE("Unable to construct request template %d: %s (%d)",
1735 templateId, strerror(-res), res);
1736 return res;
1737 }
1738
1739 set_camera_metadata_vendor_id(rawRequest, mVendorTagId);
1740 mRequestTemplateCache[templateId].acquire(rawRequest);
1741
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08001742 // Override the template request with zoomRatioMapper
1743 res = mZoomRatioMappers[mId.c_str()].initZoomRatioInTemplate(
1744 &mRequestTemplateCache[templateId]);
1745 if (res != OK) {
1746 CLOGE("Failed to update zoom ratio for template %d: %s (%d)",
1747 templateId, strerror(-res), res);
1748 return res;
1749 }
1750
Shuzhen Wangd25dc972020-03-24 17:11:43 -07001751 // Fill in JPEG_QUALITY if not available
1752 if (!mRequestTemplateCache[templateId].exists(ANDROID_JPEG_QUALITY)) {
1753 static const uint8_t kDefaultJpegQuality = 95;
1754 mRequestTemplateCache[templateId].update(ANDROID_JPEG_QUALITY,
1755 &kDefaultJpegQuality, 1);
1756 }
1757
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001758 *request = mRequestTemplateCache[templateId];
Emilian Peev811d2952018-05-25 11:08:40 +01001759 mLastTemplateId = templateId;
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001760 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001761 return OK;
1762}
1763
1764status_t Camera3Device::waitUntilDrained() {
1765 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001766 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001767 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001768 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001769
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001770 return waitUntilDrainedLocked(maxExpectedDuration);
Zhijun He69a37482014-03-23 18:44:49 -07001771}
1772
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001773status_t Camera3Device::waitUntilDrainedLocked(nsecs_t maxExpectedDuration) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001774 switch (mStatus) {
1775 case STATUS_UNINITIALIZED:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001776 case STATUS_UNCONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001777 ALOGV("%s: Already idle", __FUNCTION__);
1778 return OK;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001779 case STATUS_CONFIGURED:
1780 // To avoid race conditions, check with tracker to be sure
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001781 case STATUS_ERROR:
1782 case STATUS_ACTIVE:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001783 // Need to verify shut down
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001784 break;
1785 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001786 SET_ERR_L("Unexpected status: %d",mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001787 return INVALID_OPERATION;
1788 }
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07001789 ALOGV("%s: Camera %s: Waiting until idle (%" PRIi64 "ns)", __FUNCTION__, mId.string(),
1790 maxExpectedDuration);
1791 status_t res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
Eino-Ville Talvala9c8a0912014-09-14 14:52:19 -07001792 if (res != OK) {
Yin-Chia Yeh87b3ec02019-06-03 10:44:39 -07001793 mStatusTracker->dumpActiveComponents();
Eino-Ville Talvala9c8a0912014-09-14 14:52:19 -07001794 SET_ERR_L("Error waiting for HAL to drain: %s (%d)", strerror(-res),
1795 res);
1796 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001797 return res;
1798}
1799
Ruben Brunk183f0562015-08-12 12:55:02 -07001800
1801void Camera3Device::internalUpdateStatusLocked(Status status) {
1802 mStatus = status;
1803 mRecentStatusUpdates.add(mStatus);
1804 mStatusChanged.broadcast();
1805}
1806
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001807// Pause to reconfigure
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001808status_t Camera3Device::internalPauseAndWaitLocked(nsecs_t maxExpectedDuration) {
Emilian Peeve86358b2019-02-15 13:51:39 -08001809 if (mRequestThread.get() != nullptr) {
1810 mRequestThread->setPaused(true);
1811 } else {
1812 return NO_INIT;
1813 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001814
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07001815 ALOGV("%s: Camera %s: Internal wait until idle (% " PRIi64 " ns)", __FUNCTION__, mId.string(),
1816 maxExpectedDuration);
1817 status_t res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001818 if (res != OK) {
1819 SET_ERR_L("Can't idle device in %f seconds!",
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07001820 maxExpectedDuration/1e9);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001821 }
1822
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001823 return res;
1824}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001825
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001826// Resume after internalPauseAndWaitLocked
1827status_t Camera3Device::internalResumeLocked() {
1828 status_t res;
1829
1830 mRequestThread->setPaused(false);
1831
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08001832 ALOGV("%s: Camera %s: Internal wait until active (% " PRIi64 " ns)", __FUNCTION__, mId.string(),
1833 kActiveTimeout);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001834 res = waitUntilStateThenRelock(/*active*/ true, kActiveTimeout);
1835 if (res != OK) {
1836 SET_ERR_L("Can't transition to active in %f seconds!",
1837 kActiveTimeout/1e9);
1838 }
1839 mPauseStateNotify = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001840 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001841}
1842
Ruben Brunk183f0562015-08-12 12:55:02 -07001843status_t Camera3Device::waitUntilStateThenRelock(bool active, nsecs_t timeout) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001844 status_t res = OK;
Ruben Brunk183f0562015-08-12 12:55:02 -07001845
1846 size_t startIndex = 0;
1847 if (mStatusWaiters == 0) {
1848 // Clear the list of recent statuses if there are no existing threads waiting on updates to
1849 // this status list
1850 mRecentStatusUpdates.clear();
1851 } else {
1852 // If other threads are waiting on updates to this status list, set the position of the
1853 // first element that this list will check rather than clearing the list.
1854 startIndex = mRecentStatusUpdates.size();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001855 }
1856
Ruben Brunk183f0562015-08-12 12:55:02 -07001857 mStatusWaiters++;
1858
Yin-Chia Yehe52b8fa2020-07-28 00:17:58 -07001859 bool signalPipelineDrain = false;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07001860 if (!active && mUseHalBufManager) {
1861 auto streamIds = mOutputStreams.getStreamIds();
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08001862 if (mStatus == STATUS_ACTIVE) {
1863 mRequestThread->signalPipelineDrain(streamIds);
Yin-Chia Yehe52b8fa2020-07-28 00:17:58 -07001864 signalPipelineDrain = true;
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08001865 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07001866 mRequestBufferSM.onWaitUntilIdle();
1867 }
1868
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001869 bool stateSeen = false;
1870 do {
Ruben Brunk183f0562015-08-12 12:55:02 -07001871 if (active == (mStatus == STATUS_ACTIVE)) {
1872 // Desired state is current
1873 break;
1874 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001875
1876 res = mStatusChanged.waitRelative(mLock, timeout);
1877 if (res != OK) break;
1878
Ruben Brunk183f0562015-08-12 12:55:02 -07001879 // This is impossible, but if not, could result in subtle deadlocks and invalid state
1880 // transitions.
1881 LOG_ALWAYS_FATAL_IF(startIndex > mRecentStatusUpdates.size(),
1882 "%s: Skipping status updates in Camera3Device, may result in deadlock.",
1883 __FUNCTION__);
1884
1885 // Encountered desired state since we began waiting
1886 for (size_t i = startIndex; i < mRecentStatusUpdates.size(); i++) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001887 if (active == (mRecentStatusUpdates[i] == STATUS_ACTIVE) ) {
1888 stateSeen = true;
1889 break;
1890 }
1891 }
1892 } while (!stateSeen);
1893
Yin-Chia Yehe52b8fa2020-07-28 00:17:58 -07001894 if (signalPipelineDrain) {
1895 mRequestThread->resetPipelineDrain();
1896 }
1897
Ruben Brunk183f0562015-08-12 12:55:02 -07001898 mStatusWaiters--;
1899
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001900 return res;
1901}
1902
1903
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001904status_t Camera3Device::setNotifyCallback(wp<NotificationListener> listener) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001905 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001906 std::lock_guard<std::mutex> l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001907
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001908 if (listener != NULL && mListener != NULL) {
1909 ALOGW("%s: Replacing old callback listener", __FUNCTION__);
1910 }
1911 mListener = listener;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001912 mRequestThread->setNotificationListener(listener);
1913 mPreparerThread->setNotificationListener(listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001914
1915 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001916}
1917
Eino-Ville Talvala46910bd2013-07-18 19:15:17 -07001918bool Camera3Device::willNotify3A() {
1919 return false;
1920}
1921
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001922status_t Camera3Device::waitForNextFrame(nsecs_t timeout) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07001923 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001924 std::unique_lock<std::mutex> l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001925
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001926 while (mResultQueue.empty()) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001927 auto st = mResultSignal.wait_for(l, std::chrono::nanoseconds(timeout));
1928 if (st == std::cv_status::timeout) {
1929 return TIMED_OUT;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001930 }
1931 }
1932 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001933}
1934
Jianing Weicb0652e2014-03-12 18:29:36 -07001935status_t Camera3Device::getNextResult(CaptureResult *frame) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001936 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001937 std::lock_guard<std::mutex> l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001938
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001939 if (mResultQueue.empty()) {
1940 return NOT_ENOUGH_DATA;
1941 }
1942
Jianing Weicb0652e2014-03-12 18:29:36 -07001943 if (frame == NULL) {
1944 ALOGE("%s: argument cannot be NULL", __FUNCTION__);
1945 return BAD_VALUE;
1946 }
1947
1948 CaptureResult &result = *(mResultQueue.begin());
1949 frame->mResultExtras = result.mResultExtras;
1950 frame->mMetadata.acquire(result.mMetadata);
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001951 frame->mPhysicalMetadatas = std::move(result.mPhysicalMetadatas);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001952 mResultQueue.erase(mResultQueue.begin());
1953
1954 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001955}
1956
1957status_t Camera3Device::triggerAutofocus(uint32_t id) {
1958 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001959 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001960
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001961 ALOGV("%s: Triggering autofocus, id %d", __FUNCTION__, id);
1962 // Mix-in this trigger into the next request and only the next request.
1963 RequestTrigger trigger[] = {
1964 {
1965 ANDROID_CONTROL_AF_TRIGGER,
1966 ANDROID_CONTROL_AF_TRIGGER_START
1967 },
1968 {
1969 ANDROID_CONTROL_AF_TRIGGER_ID,
1970 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07001971 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001972 };
1973
1974 return mRequestThread->queueTrigger(trigger,
1975 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001976}
1977
1978status_t Camera3Device::triggerCancelAutofocus(uint32_t id) {
1979 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001980 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001981
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001982 ALOGV("%s: Triggering cancel autofocus, id %d", __FUNCTION__, id);
1983 // Mix-in this trigger into the next request and only the next request.
1984 RequestTrigger trigger[] = {
1985 {
1986 ANDROID_CONTROL_AF_TRIGGER,
1987 ANDROID_CONTROL_AF_TRIGGER_CANCEL
1988 },
1989 {
1990 ANDROID_CONTROL_AF_TRIGGER_ID,
1991 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07001992 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001993 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001994
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001995 return mRequestThread->queueTrigger(trigger,
1996 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001997}
1998
1999status_t Camera3Device::triggerPrecaptureMetering(uint32_t id) {
2000 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002001 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002002
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002003 ALOGV("%s: Triggering precapture metering, id %d", __FUNCTION__, id);
2004 // Mix-in this trigger into the next request and only the next request.
2005 RequestTrigger trigger[] = {
2006 {
2007 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER,
2008 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_START
2009 },
2010 {
2011 ANDROID_CONTROL_AE_PRECAPTURE_ID,
2012 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07002013 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002014 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002015
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002016 return mRequestThread->queueTrigger(trigger,
2017 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002018}
2019
Jianing Weicb0652e2014-03-12 18:29:36 -07002020status_t Camera3Device::flush(int64_t *frameNumber) {
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07002021 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002022 ALOGV("%s: Camera %s: Flushing all requests", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002023 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07002024
Zhijun He7ef20392014-04-21 16:04:17 -07002025 {
2026 Mutex::Autolock l(mLock);
Emilian Peeved2ebe42018-09-25 16:59:09 +01002027
2028 // b/116514106 "disconnect()" can get called twice for the same device. The
2029 // camera device will not be initialized during the second run.
2030 if (mStatus == STATUS_UNINITIALIZED) {
2031 return OK;
2032 }
2033
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002034 mRequestThread->clear(/*out*/frameNumber);
Shuzhen Wang316781a2020-08-18 18:11:01 -07002035
2036 // Stop session and stream counter
2037 mSessionStatsBuilder.stopCounter();
Zhijun He7ef20392014-04-21 16:04:17 -07002038 }
2039
Emilian Peev08dd2452017-04-06 16:55:14 +01002040 return mRequestThread->flush();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07002041}
2042
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002043status_t Camera3Device::prepare(int streamId) {
Ruben Brunkc78ac262015-08-13 17:58:46 -07002044 return prepare(camera3::Camera3StreamInterface::ALLOCATE_PIPELINE_MAX, streamId);
2045}
2046
2047status_t Camera3Device::prepare(int maxCount, int streamId) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002048 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002049 ALOGV("%s: Camera %s: Preparing stream %d", __FUNCTION__, mId.string(), streamId);
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07002050 Mutex::Autolock il(mInterfaceLock);
2051 Mutex::Autolock l(mLock);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002052
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002053 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
2054 if (stream == nullptr) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002055 CLOGE("Stream %d does not exist", streamId);
2056 return BAD_VALUE;
2057 }
2058
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002059 if (stream->isUnpreparable() || stream->hasOutstandingBuffers() ) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07002060 CLOGE("Stream %d has already been a request target", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002061 return BAD_VALUE;
2062 }
2063
2064 if (mRequestThread->isStreamPending(stream)) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07002065 CLOGE("Stream %d is already a target in a pending request", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002066 return BAD_VALUE;
2067 }
2068
Ruben Brunkc78ac262015-08-13 17:58:46 -07002069 return mPreparerThread->prepare(maxCount, stream);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002070}
2071
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002072status_t Camera3Device::tearDown(int streamId) {
2073 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002074 ALOGV("%s: Camera %s: Tearing down stream %d", __FUNCTION__, mId.string(), streamId);
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002075 Mutex::Autolock il(mInterfaceLock);
2076 Mutex::Autolock l(mLock);
2077
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002078 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
2079 if (stream == nullptr) {
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002080 CLOGE("Stream %d does not exist", streamId);
2081 return BAD_VALUE;
2082 }
2083
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002084 if (stream->hasOutstandingBuffers() || mRequestThread->isStreamPending(stream)) {
2085 CLOGE("Stream %d is a target of a in-progress request", streamId);
2086 return BAD_VALUE;
2087 }
2088
2089 return stream->tearDown();
2090}
2091
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002092status_t Camera3Device::addBufferListenerForStream(int streamId,
2093 wp<Camera3StreamBufferListener> listener) {
2094 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002095 ALOGV("%s: Camera %s: Adding buffer listener for stream %d", __FUNCTION__, mId.string(), streamId);
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002096 Mutex::Autolock il(mInterfaceLock);
2097 Mutex::Autolock l(mLock);
2098
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002099 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
2100 if (stream == nullptr) {
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002101 CLOGE("Stream %d does not exist", streamId);
2102 return BAD_VALUE;
2103 }
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002104 stream->addBufferListener(listener);
2105
2106 return OK;
2107}
2108
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002109/**
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002110 * Methods called by subclasses
2111 */
2112
2113void Camera3Device::notifyStatus(bool idle) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002114 ATRACE_CALL();
Shuzhen Wang316781a2020-08-18 18:11:01 -07002115 std::vector<int> streamIds;
2116 std::vector<hardware::CameraStreamStats> streamStats;
2117
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002118 {
2119 // Need mLock to safely update state and synchronize to current
2120 // state of methods in flight.
2121 Mutex::Autolock l(mLock);
2122 // We can get various system-idle notices from the status tracker
2123 // while starting up. Only care about them if we've actually sent
2124 // in some requests recently.
2125 if (mStatus != STATUS_ACTIVE && mStatus != STATUS_CONFIGURED) {
2126 return;
2127 }
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08002128 ALOGV("%s: Camera %s: Now %s, pauseState: %s", __FUNCTION__, mId.string(),
2129 idle ? "idle" : "active", mPauseStateNotify ? "true" : "false");
Ruben Brunk183f0562015-08-12 12:55:02 -07002130 internalUpdateStatusLocked(idle ? STATUS_CONFIGURED : STATUS_ACTIVE);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002131
2132 // Skip notifying listener if we're doing some user-transparent
2133 // state changes
2134 if (mPauseStateNotify) return;
Shuzhen Wang316781a2020-08-18 18:11:01 -07002135
2136 // Populate stream statistics in case of Idle
2137 if (idle) {
2138 for (size_t i = 0; i < mOutputStreams.size(); i++) {
2139 auto stream = mOutputStreams[i];
2140 if (stream.get() == nullptr) continue;
2141 streamIds.push_back(stream->getId());
2142 Camera3Stream* camera3Stream = Camera3Stream::cast(stream->asHalStream());
2143 int64_t usage = 0LL;
2144 if (camera3Stream != nullptr) {
2145 usage = camera3Stream->getUsage();
2146 }
2147 streamStats.emplace_back(stream->getWidth(), stream->getHeight(),
2148 stream->getFormat(), stream->getDataSpace(), usage,
2149 stream->getMaxHalBuffers(),
2150 stream->getMaxTotalBuffers() - stream->getMaxHalBuffers());
2151 }
2152 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002153 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002154
2155 sp<NotificationListener> listener;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002156 {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002157 std::lock_guard<std::mutex> l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002158 listener = mListener.promote();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002159 }
2160 if (idle && listener != NULL) {
Shuzhen Wang316781a2020-08-18 18:11:01 -07002161 // Get session stats from the builder, and notify the listener.
2162 int64_t requestCount, resultErrorCount;
2163 bool deviceError;
2164 std::map<int, StreamStats> streamStatsMap;
2165 mSessionStatsBuilder.buildAndReset(&requestCount, &resultErrorCount,
2166 &deviceError, &streamStatsMap);
2167 for (size_t i = 0; i < streamIds.size(); i++) {
2168 int streamId = streamIds[i];
2169 auto stats = streamStatsMap.find(streamId);
2170 if (stats != streamStatsMap.end()) {
2171 streamStats[i].mRequestCount = stats->second.mRequestedFrameCount;
2172 streamStats[i].mErrorCount = stats->second.mDroppedFrameCount;
2173 streamStats[i].mStartLatencyMs = stats->second.mStartLatencyMs;
Shuzhen Wangdb8f2782020-10-30 08:43:37 -07002174 streamStats[i].mHistogramType =
2175 hardware::CameraStreamStats::HISTOGRAM_TYPE_CAPTURE_LATENCY;
2176 streamStats[i].mHistogramBins.assign(
2177 stats->second.mCaptureLatencyBins.begin(),
2178 stats->second.mCaptureLatencyBins.end());
2179 streamStats[i].mHistogramCounts.assign(
2180 stats->second.mCaptureLatencyHistogram.begin(),
2181 stats->second.mCaptureLatencyHistogram.end());
Shuzhen Wang316781a2020-08-18 18:11:01 -07002182 }
2183 }
2184 listener->notifyIdle(requestCount, resultErrorCount, deviceError, streamStats);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002185 }
2186}
2187
Shuzhen Wang758c2152017-01-10 18:26:18 -08002188status_t Camera3Device::setConsumerSurfaces(int streamId,
Emilian Peev40ead602017-09-26 15:46:36 +01002189 const std::vector<sp<Surface>>& consumers, std::vector<int> *surfaceIds) {
Zhijun He5d677d12016-05-29 16:52:39 -07002190 ATRACE_CALL();
Shuzhen Wang758c2152017-01-10 18:26:18 -08002191 ALOGV("%s: Camera %s: set consumer surface for stream %d",
2192 __FUNCTION__, mId.string(), streamId);
Emilian Peev40ead602017-09-26 15:46:36 +01002193
2194 if (surfaceIds == nullptr) {
2195 return BAD_VALUE;
2196 }
2197
Zhijun He5d677d12016-05-29 16:52:39 -07002198 Mutex::Autolock il(mInterfaceLock);
2199 Mutex::Autolock l(mLock);
2200
Shuzhen Wang758c2152017-01-10 18:26:18 -08002201 if (consumers.size() == 0) {
2202 CLOGE("No consumer is passed!");
Zhijun He5d677d12016-05-29 16:52:39 -07002203 return BAD_VALUE;
2204 }
2205
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002206 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
2207 if (stream == nullptr) {
Zhijun He5d677d12016-05-29 16:52:39 -07002208 CLOGE("Stream %d is unknown", streamId);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002209 return BAD_VALUE;
Zhijun He5d677d12016-05-29 16:52:39 -07002210 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002211
2212 // isConsumerConfigurationDeferred will be off after setConsumers
2213 bool isDeferred = stream->isConsumerConfigurationDeferred();
Shuzhen Wang758c2152017-01-10 18:26:18 -08002214 status_t res = stream->setConsumers(consumers);
Zhijun He5d677d12016-05-29 16:52:39 -07002215 if (res != OK) {
2216 CLOGE("Stream %d set consumer failed (error %d %s) ", streamId, res, strerror(-res));
2217 return res;
2218 }
2219
Emilian Peev40ead602017-09-26 15:46:36 +01002220 for (auto &consumer : consumers) {
2221 int id = stream->getSurfaceId(consumer);
2222 if (id < 0) {
2223 CLOGE("Invalid surface id!");
2224 return BAD_VALUE;
2225 }
2226 surfaceIds->push_back(id);
2227 }
2228
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002229 if (isDeferred) {
Shuzhen Wang0129d522016-10-30 22:43:41 -07002230 if (!stream->isConfiguring()) {
2231 CLOGE("Stream %d was already fully configured.", streamId);
2232 return INVALID_OPERATION;
2233 }
Zhijun He5d677d12016-05-29 16:52:39 -07002234
Shuzhen Wang0129d522016-10-30 22:43:41 -07002235 res = stream->finishConfiguration();
2236 if (res != OK) {
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002237 // If finishConfiguration fails due to abandoned surface, do not set
2238 // device to error state.
2239 bool isSurfaceAbandoned =
2240 (res == NO_INIT || res == DEAD_OBJECT) && stream->isAbandoned();
2241 if (!isSurfaceAbandoned) {
2242 SET_ERR_L("Can't finish configuring output stream %d: %s (%d)",
2243 stream->getId(), strerror(-res), res);
2244 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07002245 return res;
2246 }
Zhijun He5d677d12016-05-29 16:52:39 -07002247 }
2248
2249 return OK;
2250}
2251
Emilian Peev40ead602017-09-26 15:46:36 +01002252status_t Camera3Device::updateStream(int streamId, const std::vector<sp<Surface>> &newSurfaces,
2253 const std::vector<OutputStreamInfo> &outputInfo,
2254 const std::vector<size_t> &removedSurfaceIds, KeyedVector<sp<Surface>, size_t> *outputMap) {
2255 Mutex::Autolock il(mInterfaceLock);
2256 Mutex::Autolock l(mLock);
2257
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002258 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
2259 if (stream == nullptr) {
Emilian Peev40ead602017-09-26 15:46:36 +01002260 CLOGE("Stream %d is unknown", streamId);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002261 return BAD_VALUE;
Emilian Peev40ead602017-09-26 15:46:36 +01002262 }
2263
2264 for (const auto &it : removedSurfaceIds) {
2265 if (mRequestThread->isOutputSurfacePending(streamId, it)) {
2266 CLOGE("Shared surface still part of a pending request!");
2267 return -EBUSY;
2268 }
2269 }
2270
Emilian Peev40ead602017-09-26 15:46:36 +01002271 status_t res = stream->updateStream(newSurfaces, outputInfo, removedSurfaceIds, outputMap);
2272 if (res != OK) {
2273 CLOGE("Stream %d failed to update stream (error %d %s) ",
2274 streamId, res, strerror(-res));
2275 if (res == UNKNOWN_ERROR) {
2276 SET_ERR_L("%s: Stream update failed to revert to previous output configuration!",
2277 __FUNCTION__);
2278 }
2279 return res;
2280 }
2281
2282 return res;
2283}
2284
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002285status_t Camera3Device::dropStreamBuffers(bool dropping, int streamId) {
2286 Mutex::Autolock il(mInterfaceLock);
2287 Mutex::Autolock l(mLock);
2288
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002289 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
2290 if (stream == nullptr) {
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002291 ALOGE("%s: Stream %d is not found.", __FUNCTION__, streamId);
2292 return BAD_VALUE;
2293 }
Shuzhen Wang316781a2020-08-18 18:11:01 -07002294
2295 if (dropping) {
2296 mSessionStatsBuilder.stopCounter(streamId);
2297 } else {
2298 mSessionStatsBuilder.startCounter(streamId);
2299 }
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002300 return stream->dropBuffers(dropping);
2301}
2302
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002303/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002304 * Camera3Device private methods
2305 */
2306
2307sp<Camera3Device::CaptureRequest> Camera3Device::createCaptureRequest(
Emilian Peevaebbe412018-01-15 13:53:24 +00002308 const PhysicalCameraSettingsList &request, const SurfaceMap &surfaceMap) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002309 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002310
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08002311 sp<CaptureRequest> newRequest = new CaptureRequest();
Emilian Peevaebbe412018-01-15 13:53:24 +00002312 newRequest->mSettingsList = request;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002313
2314 camera_metadata_entry_t inputStreams =
Emilian Peevaebbe412018-01-15 13:53:24 +00002315 newRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_INPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002316 if (inputStreams.count > 0) {
2317 if (mInputStream == NULL ||
Zhijun Hed1d64672013-09-06 15:00:01 -07002318 mInputStream->getId() != inputStreams.data.i32[0]) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002319 CLOGE("Request references unknown input stream %d",
2320 inputStreams.data.u8[0]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002321 return NULL;
2322 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002323
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002324 if (mInputStream->isConfiguring()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002325 SET_ERR_L("%s: input stream %d is not configured!",
2326 __FUNCTION__, mInputStream->getId());
2327 return NULL;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002328 }
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07002329 // Check if stream prepare is blocking requests.
2330 if (mInputStream->isBlockedByPrepare()) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002331 CLOGE("Request references an input stream that's being prepared!");
2332 return NULL;
2333 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002334
2335 newRequest->mInputStream = mInputStream;
Emilian Peevaebbe412018-01-15 13:53:24 +00002336 newRequest->mSettingsList.begin()->metadata.erase(ANDROID_REQUEST_INPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002337 }
2338
2339 camera_metadata_entry_t streams =
Emilian Peevaebbe412018-01-15 13:53:24 +00002340 newRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_OUTPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002341 if (streams.count == 0) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002342 CLOGE("Zero output streams specified!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002343 return NULL;
2344 }
2345
2346 for (size_t i = 0; i < streams.count; i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002347 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streams.data.i32[i]);
2348 if (stream == nullptr) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002349 CLOGE("Request references unknown stream %d",
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002350 streams.data.i32[i]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002351 return NULL;
2352 }
Zhijun He5d677d12016-05-29 16:52:39 -07002353 // It is illegal to include a deferred consumer output stream into a request
Shuzhen Wang0129d522016-10-30 22:43:41 -07002354 auto iter = surfaceMap.find(streams.data.i32[i]);
2355 if (iter != surfaceMap.end()) {
2356 const std::vector<size_t>& surfaces = iter->second;
2357 for (const auto& surface : surfaces) {
2358 if (stream->isConsumerConfigurationDeferred(surface)) {
2359 CLOGE("Stream %d surface %zu hasn't finished configuration yet "
2360 "due to deferred consumer", stream->getId(), surface);
2361 return NULL;
2362 }
2363 }
Yin-Chia Yeh0b287572018-10-15 12:38:13 -07002364 newRequest->mOutputSurfaces[streams.data.i32[i]] = surfaces;
Zhijun He5d677d12016-05-29 16:52:39 -07002365 }
2366
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002367 if (stream->isConfiguring()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002368 SET_ERR_L("%s: stream %d is not configured!", __FUNCTION__, stream->getId());
2369 return NULL;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002370 }
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07002371 // Check if stream prepare is blocking requests.
2372 if (stream->isBlockedByPrepare()) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002373 CLOGE("Request references an output stream that's being prepared!");
2374 return NULL;
2375 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002376
2377 newRequest->mOutputStreams.push(stream);
2378 }
Emilian Peevaebbe412018-01-15 13:53:24 +00002379 newRequest->mSettingsList.begin()->metadata.erase(ANDROID_REQUEST_OUTPUT_STREAMS);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07002380 newRequest->mBatchSize = 1;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002381
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08002382 auto rotateAndCropEntry =
2383 newRequest->mSettingsList.begin()->metadata.find(ANDROID_SCALER_ROTATE_AND_CROP);
2384 if (rotateAndCropEntry.count > 0 &&
2385 rotateAndCropEntry.data.u8[0] == ANDROID_SCALER_ROTATE_AND_CROP_AUTO) {
2386 newRequest->mRotateAndCropAuto = true;
2387 } else {
2388 newRequest->mRotateAndCropAuto = false;
2389 }
2390
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07002391 auto zoomRatioEntry =
2392 newRequest->mSettingsList.begin()->metadata.find(ANDROID_CONTROL_ZOOM_RATIO);
2393 if (zoomRatioEntry.count > 0 &&
2394 zoomRatioEntry.data.f[0] == 1.0f) {
2395 newRequest->mZoomRatioIs1x = true;
2396 } else {
2397 newRequest->mZoomRatioIs1x = false;
2398 }
2399
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08002400 if (mSupportCameraMute) {
2401 auto testPatternModeEntry =
2402 newRequest->mSettingsList.begin()->metadata.find(ANDROID_SENSOR_TEST_PATTERN_MODE);
2403 newRequest->mOriginalTestPatternMode = testPatternModeEntry.count > 0 ?
2404 testPatternModeEntry.data.i32[0] :
2405 ANDROID_SENSOR_TEST_PATTERN_MODE_OFF;
2406
2407 auto testPatternDataEntry =
2408 newRequest->mSettingsList.begin()->metadata.find(ANDROID_SENSOR_TEST_PATTERN_DATA);
2409 if (testPatternDataEntry.count > 0) {
2410 memcpy(newRequest->mOriginalTestPatternData, testPatternModeEntry.data.i32,
2411 sizeof(newRequest->mOriginalTestPatternData));
2412 } else {
2413 newRequest->mOriginalTestPatternData[0] = 0;
2414 newRequest->mOriginalTestPatternData[1] = 0;
2415 newRequest->mOriginalTestPatternData[2] = 0;
2416 newRequest->mOriginalTestPatternData[3] = 0;
2417 }
2418 }
2419
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002420 return newRequest;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002421}
2422
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002423void Camera3Device::cancelStreamsConfigurationLocked() {
2424 int res = OK;
2425 if (mInputStream != NULL && mInputStream->isConfiguring()) {
2426 res = mInputStream->cancelConfiguration();
2427 if (res != OK) {
2428 CLOGE("Can't cancel configuring input stream %d: %s (%d)",
2429 mInputStream->getId(), strerror(-res), res);
2430 }
2431 }
2432
2433 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002434 sp<Camera3OutputStreamInterface> outputStream = mOutputStreams[i];
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002435 if (outputStream->isConfiguring()) {
2436 res = outputStream->cancelConfiguration();
2437 if (res != OK) {
2438 CLOGE("Can't cancel configuring output stream %d: %s (%d)",
2439 outputStream->getId(), strerror(-res), res);
2440 }
2441 }
2442 }
2443
2444 // Return state to that at start of call, so that future configures
2445 // properly clean things up
2446 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
2447 mNeedConfig = true;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002448
2449 res = mPreparerThread->resume();
2450 if (res != OK) {
2451 ALOGE("%s: Camera %s: Preparer thread failed to resume!", __FUNCTION__, mId.string());
2452 }
2453}
2454
Emilian Peev0d0191e2020-04-21 17:01:18 -07002455bool Camera3Device::checkAbandonedStreamsLocked() {
2456 if ((mInputStream.get() != nullptr) && (mInputStream->isAbandoned())) {
2457 return true;
2458 }
2459
2460 for (size_t i = 0; i < mOutputStreams.size(); i++) {
2461 auto stream = mOutputStreams[i];
2462 if ((stream.get() != nullptr) && (stream->isAbandoned())) {
2463 return true;
2464 }
2465 }
2466
2467 return false;
2468}
2469
Emilian Peev3bead5f2020-05-28 17:29:08 -07002470bool Camera3Device::reconfigureCamera(const CameraMetadata& sessionParams, int clientStatusId) {
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002471 ATRACE_CALL();
2472 bool ret = false;
2473
Shuzhen Wang316781a2020-08-18 18:11:01 -07002474 nsecs_t startTime = systemTime();
2475
Jayant Chowdhary646c31b2020-01-30 13:09:59 -08002476 Mutex::Autolock il(mInterfaceLock);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002477 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
2478
2479 Mutex::Autolock l(mLock);
Emilian Peev0d0191e2020-04-21 17:01:18 -07002480 if (checkAbandonedStreamsLocked()) {
2481 ALOGW("%s: Abandoned stream detected, session parameters can't be applied correctly!",
2482 __FUNCTION__);
2483 return true;
2484 }
2485
Emilian Peev3bead5f2020-05-28 17:29:08 -07002486 status_t rc = NO_ERROR;
2487 bool markClientActive = false;
2488 if (mStatus == STATUS_ACTIVE) {
2489 markClientActive = true;
2490 mPauseStateNotify = true;
2491 mStatusTracker->markComponentIdle(clientStatusId, Fence::NO_FENCE);
2492
2493 rc = internalPauseAndWaitLocked(maxExpectedDuration);
2494 }
2495
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002496 if (rc == NO_ERROR) {
2497 mNeedConfig = true;
2498 rc = configureStreamsLocked(mOperatingMode, sessionParams, /*notifyRequestThread*/ false);
2499 if (rc == NO_ERROR) {
2500 ret = true;
2501 mPauseStateNotify = false;
2502 //Moving to active state while holding 'mLock' is important.
2503 //There could be pending calls to 'create-/deleteStream' which
2504 //will trigger another stream configuration while the already
2505 //present streams end up with outstanding buffers that will
2506 //not get drained.
2507 internalUpdateStatusLocked(STATUS_ACTIVE);
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002508 } else if (rc == DEAD_OBJECT) {
2509 // DEAD_OBJECT can be returned if either the consumer surface is
2510 // abandoned, or the HAL has died.
2511 // - If the HAL has died, configureStreamsLocked call will set
2512 // device to error state,
2513 // - If surface is abandoned, we should not set device to error
2514 // state.
2515 ALOGE("Failed to re-configure camera due to abandoned surface");
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002516 } else {
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002517 SET_ERR_L("Failed to re-configure camera: %d", rc);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002518 }
2519 } else {
2520 ALOGE("%s: Failed to pause streaming: %d", __FUNCTION__, rc);
2521 }
2522
Shuzhen Wang316781a2020-08-18 18:11:01 -07002523 CameraServiceProxyWrapper::logStreamConfigured(mId, mOperatingMode, true /*internalReconfig*/,
2524 ns2ms(systemTime() - startTime));
2525
Emilian Peev3bead5f2020-05-28 17:29:08 -07002526 if (markClientActive) {
2527 mStatusTracker->markComponentActive(clientStatusId);
2528 }
2529
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002530 return ret;
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002531}
2532
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002533status_t Camera3Device::configureStreamsLocked(int operatingMode,
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002534 const CameraMetadata& sessionParams, bool notifyRequestThread) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002535 ATRACE_CALL();
2536 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002537
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002538 if (mStatus != STATUS_UNCONFIGURED && mStatus != STATUS_CONFIGURED) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002539 CLOGE("Not idle");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002540 return INVALID_OPERATION;
2541 }
2542
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08002543 if (operatingMode < 0) {
2544 CLOGE("Invalid operating mode: %d", operatingMode);
2545 return BAD_VALUE;
2546 }
2547
2548 bool isConstrainedHighSpeed =
2549 static_cast<int>(StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE) ==
2550 operatingMode;
2551
2552 if (mOperatingMode != operatingMode) {
2553 mNeedConfig = true;
2554 mIsConstrainedHighSpeedConfiguration = isConstrainedHighSpeed;
2555 mOperatingMode = operatingMode;
2556 }
2557
Shuzhen Wang0cf01cb2019-09-05 13:33:06 -07002558 // In case called from configureStreams, abort queued input buffers not belonging to
2559 // any pending requests.
2560 if (mInputStream != NULL && notifyRequestThread) {
2561 while (true) {
Emilian Peevf4816702020-04-03 15:44:51 -07002562 camera_stream_buffer_t inputBuffer;
Shuzhen Wang0cf01cb2019-09-05 13:33:06 -07002563 status_t res = mInputStream->getInputBuffer(&inputBuffer,
2564 /*respectHalLimit*/ false);
2565 if (res != OK) {
2566 // Exhausted acquiring all input buffers.
2567 break;
2568 }
2569
Emilian Peevf4816702020-04-03 15:44:51 -07002570 inputBuffer.status = CAMERA_BUFFER_STATUS_ERROR;
Shuzhen Wang0cf01cb2019-09-05 13:33:06 -07002571 res = mInputStream->returnInputBuffer(inputBuffer);
2572 if (res != OK) {
2573 ALOGE("%s: %d: couldn't return input buffer while clearing input queue: "
2574 "%s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
2575 }
2576 }
2577 }
2578
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002579 if (!mNeedConfig) {
2580 ALOGV("%s: Skipping config, no stream changes", __FUNCTION__);
2581 return OK;
2582 }
2583
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002584 // Workaround for device HALv3.2 or older spec bug - zero streams requires
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002585 // adding a fake stream instead.
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002586 // TODO: Bug: 17321404 for fixing the HAL spec and removing this workaround.
2587 if (mOutputStreams.size() == 0) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002588 addFakeStreamLocked();
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002589 } else {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002590 tryRemoveFakeStreamLocked();
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002591 }
2592
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002593 // Start configuring the streams
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002594 ALOGV("%s: Camera %s: Starting stream configuration", __FUNCTION__, mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002595
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002596 mPreparerThread->pause();
2597
Emilian Peevf4816702020-04-03 15:44:51 -07002598 camera_stream_configuration config;
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -08002599 config.operation_mode = mOperatingMode;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002600 config.num_streams = (mInputStream != NULL) + mOutputStreams.size();
2601
Emilian Peevf4816702020-04-03 15:44:51 -07002602 Vector<camera3::camera_stream_t*> streams;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002603 streams.setCapacity(config.num_streams);
Emilian Peev192ee832018-01-31 14:46:47 +00002604 std::vector<uint32_t> bufferSizes(config.num_streams, 0);
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002605
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002606
2607 if (mInputStream != NULL) {
Emilian Peevf4816702020-04-03 15:44:51 -07002608 camera3::camera_stream_t *inputStream;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002609 inputStream = mInputStream->startConfiguration();
2610 if (inputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002611 CLOGE("Can't start input stream configuration");
2612 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002613 return INVALID_OPERATION;
2614 }
2615 streams.add(inputStream);
2616 }
2617
2618 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Igor Murashkin2fba5842013-04-22 14:03:54 -07002619
2620 // Don't configure bidi streams twice, nor add them twice to the list
2621 if (mOutputStreams[i].get() ==
2622 static_cast<Camera3StreamInterface*>(mInputStream.get())) {
2623
2624 config.num_streams--;
2625 continue;
2626 }
2627
Emilian Peevf4816702020-04-03 15:44:51 -07002628 camera3::camera_stream_t *outputStream;
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002629 outputStream = mOutputStreams[i]->startConfiguration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002630 if (outputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002631 CLOGE("Can't start output stream configuration");
2632 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002633 return INVALID_OPERATION;
2634 }
2635 streams.add(outputStream);
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002636
Shuzhen Wangb7ab1e42019-02-20 15:42:23 -08002637 if (outputStream->format == HAL_PIXEL_FORMAT_BLOB) {
Emilian Peev192ee832018-01-31 14:46:47 +00002638 size_t k = i + ((mInputStream != nullptr) ? 1 : 0); // Input stream if present should
2639 // always occupy the initial entry.
Shuzhen Wangb7ab1e42019-02-20 15:42:23 -08002640 if (outputStream->data_space == HAL_DATASPACE_V0_JFIF) {
2641 bufferSizes[k] = static_cast<uint32_t>(
2642 getJpegBufferSize(outputStream->width, outputStream->height));
2643 } else if (outputStream->data_space ==
2644 static_cast<android_dataspace>(HAL_DATASPACE_JPEG_APP_SEGMENTS)) {
2645 bufferSizes[k] = outputStream->width * outputStream->height;
2646 } else {
2647 ALOGW("%s: Blob dataSpace %d not supported",
2648 __FUNCTION__, outputStream->data_space);
2649 }
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002650 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002651 }
2652
2653 config.streams = streams.editArray();
2654
2655 // Do the HAL configuration; will potentially touch stream
Shuzhen Wang92653952019-05-07 15:11:43 -07002656 // max_buffers, usage, and priv fields, as well as data_space and format
2657 // fields for IMPLEMENTATION_DEFINED formats.
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002658
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002659 const camera_metadata_t *sessionBuffer = sessionParams.getAndLock();
Emilian Peev192ee832018-01-31 14:46:47 +00002660 res = mInterface->configureStreams(sessionBuffer, &config, bufferSizes);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002661 sessionParams.unlock(sessionBuffer);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002662
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002663 if (res == BAD_VALUE) {
2664 // HAL rejected this set of streams as unsupported, clean up config
2665 // attempt and return to unconfigured state
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002666 CLOGE("Set of requested inputs/outputs not supported by HAL");
2667 cancelStreamsConfigurationLocked();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002668 return BAD_VALUE;
2669 } else if (res != OK) {
2670 // Some other kind of error from configure_streams - this is not
2671 // expected
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002672 SET_ERR_L("Unable to configure streams with HAL: %s (%d)",
2673 strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002674 return res;
2675 }
2676
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002677 // Finish all stream configuration immediately.
2678 // TODO: Try to relax this later back to lazy completion, which should be
2679 // faster
2680
Igor Murashkin073f8572013-05-02 14:59:28 -07002681 if (mInputStream != NULL && mInputStream->isConfiguring()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002682 bool streamReConfigured = false;
2683 res = mInputStream->finishConfiguration(&streamReConfigured);
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002684 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002685 CLOGE("Can't finish configuring input stream %d: %s (%d)",
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002686 mInputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002687 cancelStreamsConfigurationLocked();
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002688 if ((res == NO_INIT || res == DEAD_OBJECT) && mInputStream->isAbandoned()) {
2689 return DEAD_OBJECT;
2690 }
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002691 return BAD_VALUE;
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002692 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002693 if (streamReConfigured) {
2694 mInterface->onStreamReConfigured(mInputStream->getId());
2695 }
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002696 }
2697
2698 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002699 sp<Camera3OutputStreamInterface> outputStream = mOutputStreams[i];
Zhijun He5d677d12016-05-29 16:52:39 -07002700 if (outputStream->isConfiguring() && !outputStream->isConsumerConfigurationDeferred()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002701 bool streamReConfigured = false;
2702 res = outputStream->finishConfiguration(&streamReConfigured);
Igor Murashkin073f8572013-05-02 14:59:28 -07002703 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002704 CLOGE("Can't finish configuring output stream %d: %s (%d)",
Igor Murashkin073f8572013-05-02 14:59:28 -07002705 outputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002706 cancelStreamsConfigurationLocked();
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002707 if ((res == NO_INIT || res == DEAD_OBJECT) && outputStream->isAbandoned()) {
2708 return DEAD_OBJECT;
2709 }
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002710 return BAD_VALUE;
Igor Murashkin073f8572013-05-02 14:59:28 -07002711 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002712 if (streamReConfigured) {
2713 mInterface->onStreamReConfigured(outputStream->getId());
2714 }
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002715 }
2716 }
2717
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002718 // Request thread needs to know to avoid using repeat-last-settings protocol
2719 // across configure_streams() calls
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002720 if (notifyRequestThread) {
2721 mRequestThread->configurationComplete(mIsConstrainedHighSpeedConfiguration, sessionParams);
2722 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002723
Zhijun He90f7c372016-08-16 16:19:43 -07002724 char value[PROPERTY_VALUE_MAX];
2725 property_get("camera.fifo.disable", value, "0");
2726 int32_t disableFifo = atoi(value);
2727 if (disableFifo != 1) {
2728 // Boost priority of request thread to SCHED_FIFO.
2729 pid_t requestThreadTid = mRequestThread->getTid();
2730 res = requestPriority(getpid(), requestThreadTid,
Mikhail Naganov83f04272017-02-07 10:45:09 -08002731 kRequestThreadPriority, /*isForApp*/ false, /*asynchronous*/ false);
Zhijun He90f7c372016-08-16 16:19:43 -07002732 if (res != OK) {
2733 ALOGW("Can't set realtime priority for request processing thread: %s (%d)",
2734 strerror(-res), res);
2735 } else {
2736 ALOGD("Set real time priority for request queue thread (tid %d)", requestThreadTid);
2737 }
Eino-Ville Talvalaf99498e2015-09-25 16:52:55 -07002738 }
2739
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002740 // Update device state
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002741 const camera_metadata_t *newSessionParams = sessionParams.getAndLock();
2742 const camera_metadata_t *currentSessionParams = mSessionParams.getAndLock();
2743 bool updateSessionParams = (newSessionParams != currentSessionParams) ? true : false;
2744 sessionParams.unlock(newSessionParams);
2745 mSessionParams.unlock(currentSessionParams);
2746 if (updateSessionParams) {
2747 mSessionParams = sessionParams;
2748 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002749
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002750 mNeedConfig = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002751
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002752 internalUpdateStatusLocked((mFakeStreamId == NO_STREAM) ?
Ruben Brunk183f0562015-08-12 12:55:02 -07002753 STATUS_CONFIGURED : STATUS_UNCONFIGURED);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002754
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002755 ALOGV("%s: Camera %s: Stream configuration complete", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002756
Zhijun He0a210512014-07-24 13:45:15 -07002757 // tear down the deleted streams after configure streams.
2758 mDeletedStreams.clear();
2759
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002760 auto rc = mPreparerThread->resume();
2761 if (rc != OK) {
2762 SET_ERR_L("%s: Camera %s: Preparer thread failed to resume!", __FUNCTION__, mId.string());
2763 return rc;
2764 }
2765
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002766 if (mFakeStreamId == NO_STREAM) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07002767 mRequestBufferSM.onStreamsConfigured();
2768 }
2769
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002770 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002771}
2772
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002773status_t Camera3Device::addFakeStreamLocked() {
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002774 ATRACE_CALL();
2775 status_t res;
2776
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002777 if (mFakeStreamId != NO_STREAM) {
2778 // Should never be adding a second fake stream when one is already
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002779 // active
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002780 SET_ERR_L("%s: Camera %s: A fake stream already exists!",
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002781 __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002782 return INVALID_OPERATION;
2783 }
2784
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002785 ALOGV("%s: Camera %s: Adding a fake stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002786
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002787 sp<Camera3OutputStreamInterface> fakeStream =
2788 new Camera3FakeStream(mNextStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002789
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002790 res = mOutputStreams.add(mNextStreamId, fakeStream);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002791 if (res < 0) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002792 SET_ERR_L("Can't add fake stream to set: %s (%d)", strerror(-res), res);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002793 return res;
2794 }
2795
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002796 mFakeStreamId = mNextStreamId;
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002797 mNextStreamId++;
2798
2799 return OK;
2800}
2801
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002802status_t Camera3Device::tryRemoveFakeStreamLocked() {
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002803 ATRACE_CALL();
2804 status_t res;
2805
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002806 if (mFakeStreamId == NO_STREAM) return OK;
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002807 if (mOutputStreams.size() == 1) return OK;
2808
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002809 ALOGV("%s: Camera %s: Removing the fake stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002810
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002811 // Ok, have a fake stream and there's at least one other output stream,
2812 // so remove the fake
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002813
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002814 sp<Camera3StreamInterface> deletedStream = mOutputStreams.get(mFakeStreamId);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002815 if (deletedStream == nullptr) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002816 SET_ERR_L("Fake stream %d does not appear to exist", mFakeStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002817 return INVALID_OPERATION;
2818 }
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002819 mOutputStreams.remove(mFakeStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002820
2821 // Free up the stream endpoint so that it can be used by some other stream
2822 res = deletedStream->disconnect();
2823 if (res != OK) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002824 SET_ERR_L("Can't disconnect deleted fake stream %d", mFakeStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002825 // fall through since we want to still list the stream as deleted.
2826 }
2827 mDeletedStreams.add(deletedStream);
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002828 mFakeStreamId = NO_STREAM;
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002829
2830 return res;
2831}
2832
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002833void Camera3Device::setErrorState(const char *fmt, ...) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002834 ATRACE_CALL();
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002835 Mutex::Autolock l(mLock);
2836 va_list args;
2837 va_start(args, fmt);
2838
2839 setErrorStateLockedV(fmt, args);
2840
2841 va_end(args);
2842}
2843
2844void Camera3Device::setErrorStateV(const char *fmt, va_list args) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002845 ATRACE_CALL();
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002846 Mutex::Autolock l(mLock);
2847 setErrorStateLockedV(fmt, args);
2848}
2849
2850void Camera3Device::setErrorStateLocked(const char *fmt, ...) {
2851 va_list args;
2852 va_start(args, fmt);
2853
2854 setErrorStateLockedV(fmt, args);
2855
2856 va_end(args);
2857}
2858
2859void Camera3Device::setErrorStateLockedV(const char *fmt, va_list args) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002860 // Print out all error messages to log
2861 String8 errorCause = String8::formatV(fmt, args);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002862 ALOGE("Camera %s: %s", mId.string(), errorCause.string());
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002863
2864 // But only do error state transition steps for the first error
Zhijun Heb05eeae2013-06-06 13:51:22 -07002865 if (mStatus == STATUS_ERROR || mStatus == STATUS_UNINITIALIZED) return;
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002866
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002867 mErrorCause = errorCause;
2868
Yin-Chia Yeh3d145ae2017-07-27 12:47:03 -07002869 if (mRequestThread != nullptr) {
2870 mRequestThread->setPaused(true);
2871 }
Ruben Brunk183f0562015-08-12 12:55:02 -07002872 internalUpdateStatusLocked(STATUS_ERROR);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002873
2874 // Notify upstream about a device error
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002875 sp<NotificationListener> listener = mListener.promote();
2876 if (listener != NULL) {
2877 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002878 CaptureResultExtras());
Shuzhen Wang316781a2020-08-18 18:11:01 -07002879 mSessionStatsBuilder.onDeviceError();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002880 }
2881
2882 // Save stack trace. View by dumping it later.
2883 CameraTraces::saveTrace();
2884 // TODO: consider adding errorCause and client pid/procname
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002885}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002886
2887/**
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002888 * In-flight request management
2889 */
2890
Jianing Weicb0652e2014-03-12 18:29:36 -07002891status_t Camera3Device::registerInFlight(uint32_t frameNumber,
Chien-Yu Chend196d612015-06-22 19:49:01 -07002892 int32_t numBuffers, CaptureResultExtras resultExtras, bool hasInput,
Shuzhen Wang5c22c152017-12-31 17:12:25 -08002893 bool hasAppCallback, nsecs_t maxExpectedDuration,
Shuzhen Wang26abaf42018-08-28 15:41:20 -07002894 std::set<String8>& physicalCameraIds, bool isStillCapture,
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08002895 bool isZslCapture, bool rotateAndCropAuto, const std::set<std::string>& cameraIdsWithZoom,
Shuzhen Wang316781a2020-08-18 18:11:01 -07002896 const SurfaceMap& outputSurfaces, nsecs_t requestTimeNs) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002897 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002898 std::lock_guard<std::mutex> l(mInFlightLock);
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002899
2900 ssize_t res;
Chien-Yu Chend196d612015-06-22 19:49:01 -07002901 res = mInFlightMap.add(frameNumber, InFlightRequest(numBuffers, resultExtras, hasInput,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07002902 hasAppCallback, maxExpectedDuration, physicalCameraIds, isStillCapture, isZslCapture,
Shuzhen Wang316781a2020-08-18 18:11:01 -07002903 rotateAndCropAuto, cameraIdsWithZoom, requestTimeNs, outputSurfaces));
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002904 if (res < 0) return res;
2905
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07002906 if (mInFlightMap.size() == 1) {
Emilian Peev26d975d2018-07-05 14:52:57 +01002907 // Hold a separate dedicated tracker lock to prevent race with disconnect and also
2908 // avoid a deadlock during reprocess requests.
2909 Mutex::Autolock l(mTrackerLock);
Yin-Chia Yeh38dfde52017-06-27 17:13:33 -07002910 if (mStatusTracker != nullptr) {
2911 mStatusTracker->markComponentActive(mInFlightStatusId);
2912 }
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07002913 }
2914
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07002915 mExpectedInflightDuration += maxExpectedDuration;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002916 return OK;
2917}
2918
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002919void Camera3Device::onInflightEntryRemovedLocked(nsecs_t duration) {
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002920 // Indicate idle inFlightMap to the status tracker
2921 if (mInFlightMap.size() == 0) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07002922 mRequestBufferSM.onInflightMapEmpty();
Emilian Peev26d975d2018-07-05 14:52:57 +01002923 // Hold a separate dedicated tracker lock to prevent race with disconnect and also
2924 // avoid a deadlock during reprocess requests.
2925 Mutex::Autolock l(mTrackerLock);
Yin-Chia Yeh38dfde52017-06-27 17:13:33 -07002926 if (mStatusTracker != nullptr) {
2927 mStatusTracker->markComponentIdle(mInFlightStatusId, Fence::NO_FENCE);
2928 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002929 }
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07002930 mExpectedInflightDuration -= duration;
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002931}
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002932
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002933void Camera3Device::checkInflightMapLengthLocked() {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002934 // Validation check - if we have too many in-flight frames with long total inflight duration,
Yin-Chia Yeh99fd0972019-06-27 14:22:44 -07002935 // something has likely gone wrong. This might still be legit only if application send in
2936 // a long burst of long exposure requests.
2937 if (mExpectedInflightDuration > kMinWarnInflightDuration) {
2938 if (!mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() > kInFlightWarnLimit) {
2939 CLOGW("In-flight list too large: %zu, total inflight duration %" PRIu64,
2940 mInFlightMap.size(), mExpectedInflightDuration);
2941 } else if (mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() >
2942 kInFlightWarnLimitHighSpeed) {
2943 CLOGW("In-flight list too large for high speed configuration: %zu,"
2944 "total inflight duration %" PRIu64,
2945 mInFlightMap.size(), mExpectedInflightDuration);
2946 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002947 }
2948}
2949
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002950void Camera3Device::onInflightMapFlushedLocked() {
2951 mExpectedInflightDuration = 0;
2952}
2953
2954void Camera3Device::removeInFlightMapEntryLocked(int idx) {
Jayant Chowdharyd4776262020-06-23 23:45:57 -07002955 ATRACE_HFR_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002956 nsecs_t duration = mInFlightMap.valueAt(idx).maxExpectedDuration;
2957 mInFlightMap.removeItemsAt(idx, 1);
2958
2959 onInflightEntryRemovedLocked(duration);
2960}
2961
2962
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07002963void Camera3Device::flushInflightRequests() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002964 ATRACE_CALL();
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002965 sp<NotificationListener> listener;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002966 {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002967 std::lock_guard<std::mutex> l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002968 listener = mListener.promote();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002969 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002970
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002971 FlushInflightReqStates states {
2972 mId, mInFlightLock, mInFlightMap, mUseHalBufManager,
Shuzhen Wang316781a2020-08-18 18:11:01 -07002973 listener, *this, *mInterface, *this, mSessionStatsBuilder};
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002974
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002975 camera3::flushInflightRequests(states);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002976}
2977
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002978CameraMetadata Camera3Device::getLatestRequestLocked() {
Igor Murashkin1e479c02013-09-06 16:55:14 -07002979 ALOGV("%s", __FUNCTION__);
2980
Igor Murashkin1e479c02013-09-06 16:55:14 -07002981 CameraMetadata retVal;
2982
2983 if (mRequestThread != NULL) {
2984 retVal = mRequestThread->getLatestRequest();
2985 }
2986
Igor Murashkin1e479c02013-09-06 16:55:14 -07002987 return retVal;
2988}
2989
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07002990void Camera3Device::monitorMetadata(TagMonitor::eventSource source,
Shuzhen Wangc2cba122018-05-17 18:10:24 -07002991 int64_t frameNumber, nsecs_t timestamp, const CameraMetadata& metadata,
2992 const std::unordered_map<std::string, CameraMetadata>& physicalMetadata) {
2993
2994 mTagMonitor.monitorMetadata(source, frameNumber, timestamp, metadata,
2995 physicalMetadata);
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07002996}
2997
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002998/**
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002999 * HalInterface inner class methods
3000 */
3001
Yifan Hongf79b5542017-04-11 14:44:25 -07003002Camera3Device::HalInterface::HalInterface(
3003 sp<ICameraDeviceSession> &session,
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003004 std::shared_ptr<RequestMetadataQueue> queue,
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003005 bool useHalBufManager, bool supportOfflineProcessing) :
Yifan Hongf79b5542017-04-11 14:44:25 -07003006 mHidlSession(session),
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003007 mRequestMetadataQueue(queue),
Emilian Peev4ec17882019-01-24 17:16:58 -08003008 mUseHalBufManager(useHalBufManager),
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003009 mIsReconfigurationQuerySupported(true),
3010 mSupportOfflineProcessing(supportOfflineProcessing) {
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003011 // Check with hardware service manager if we can downcast these interfaces
3012 // Somewhat expensive, so cache the results at startup
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() {
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003046 mHidlSession_3_6.clear();
Emilian Peev644a3e12018-11-23 13:52:39 +00003047 mHidlSession_3_5.clear();
Emilian Peev9e740b02018-01-30 18:28:03 +00003048 mHidlSession_3_4.clear();
3049 mHidlSession_3_3.clear();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003050 mHidlSession.clear();
3051}
3052
3053status_t Camera3Device::HalInterface::constructDefaultRequestSettings(
Emilian Peevf4816702020-04-03 15:44:51 -07003054 camera_request_template_t templateId,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003055 /*out*/ camera_metadata_t **requestTemplate) {
3056 ATRACE_NAME("CameraHal::constructDefaultRequestSettings");
3057 if (!valid()) return INVALID_OPERATION;
3058 status_t res = OK;
3059
Emilian Peev31abd0a2017-05-11 18:37:46 +01003060 common::V1_0::Status status;
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003061
3062 auto requestCallback = [&status, &requestTemplate]
Emilian Peev31abd0a2017-05-11 18:37:46 +01003063 (common::V1_0::Status s, const device::V3_2::CameraMetadata& request) {
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003064 status = s;
3065 if (status == common::V1_0::Status::OK) {
3066 const camera_metadata *r =
3067 reinterpret_cast<const camera_metadata_t*>(request.data());
3068 size_t expectedSize = request.size();
3069 int ret = validate_camera_metadata_structure(r, &expectedSize);
3070 if (ret == OK || ret == CAMERA_METADATA_VALIDATION_SHIFTED) {
3071 *requestTemplate = clone_camera_metadata(r);
3072 if (*requestTemplate == nullptr) {
3073 ALOGE("%s: Unable to clone camera metadata received from HAL",
3074 __FUNCTION__);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003075 status = common::V1_0::Status::INTERNAL_ERROR;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003076 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003077 } else {
3078 ALOGE("%s: Malformed camera metadata received from HAL", __FUNCTION__);
3079 status = common::V1_0::Status::INTERNAL_ERROR;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003080 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003081 }
3082 };
3083 hardware::Return<void> err;
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003084 RequestTemplate id;
3085 switch (templateId) {
Emilian Peevf4816702020-04-03 15:44:51 -07003086 case CAMERA_TEMPLATE_PREVIEW:
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003087 id = RequestTemplate::PREVIEW;
3088 break;
Emilian Peevf4816702020-04-03 15:44:51 -07003089 case CAMERA_TEMPLATE_STILL_CAPTURE:
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003090 id = RequestTemplate::STILL_CAPTURE;
3091 break;
Emilian Peevf4816702020-04-03 15:44:51 -07003092 case CAMERA_TEMPLATE_VIDEO_RECORD:
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003093 id = RequestTemplate::VIDEO_RECORD;
3094 break;
Emilian Peevf4816702020-04-03 15:44:51 -07003095 case CAMERA_TEMPLATE_VIDEO_SNAPSHOT:
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003096 id = RequestTemplate::VIDEO_SNAPSHOT;
3097 break;
Emilian Peevf4816702020-04-03 15:44:51 -07003098 case CAMERA_TEMPLATE_ZERO_SHUTTER_LAG:
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003099 id = RequestTemplate::ZERO_SHUTTER_LAG;
3100 break;
Emilian Peevf4816702020-04-03 15:44:51 -07003101 case CAMERA_TEMPLATE_MANUAL:
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003102 id = RequestTemplate::MANUAL;
3103 break;
3104 default:
3105 // Unknown template ID, or this HAL is too old to support it
3106 return BAD_VALUE;
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003107 }
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003108 err = mHidlSession->constructDefaultRequestSettings(id, requestCallback);
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003109
Emilian Peev31abd0a2017-05-11 18:37:46 +01003110 if (!err.isOk()) {
3111 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3112 res = DEAD_OBJECT;
3113 } else {
3114 res = CameraProviderManager::mapToStatusT(status);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003115 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003116
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003117 return res;
3118}
3119
Emilian Peev4ec17882019-01-24 17:16:58 -08003120bool Camera3Device::HalInterface::isReconfigurationRequired(CameraMetadata& oldSessionParams,
3121 CameraMetadata& newSessionParams) {
3122 // We do reconfiguration by default;
3123 bool ret = true;
3124 if ((mHidlSession_3_5 != nullptr) && mIsReconfigurationQuerySupported) {
3125 android::hardware::hidl_vec<uint8_t> oldParams, newParams;
3126 camera_metadata_t* oldSessioMeta = const_cast<camera_metadata_t*>(
3127 oldSessionParams.getAndLock());
3128 camera_metadata_t* newSessioMeta = const_cast<camera_metadata_t*>(
3129 newSessionParams.getAndLock());
3130 oldParams.setToExternal(reinterpret_cast<uint8_t*>(oldSessioMeta),
3131 get_camera_metadata_size(oldSessioMeta));
3132 newParams.setToExternal(reinterpret_cast<uint8_t*>(newSessioMeta),
3133 get_camera_metadata_size(newSessioMeta));
3134 hardware::camera::common::V1_0::Status callStatus;
3135 bool required;
3136 auto hidlCb = [&callStatus, &required] (hardware::camera::common::V1_0::Status s,
3137 bool requiredFlag) {
3138 callStatus = s;
3139 required = requiredFlag;
3140 };
3141 auto err = mHidlSession_3_5->isReconfigurationRequired(oldParams, newParams, hidlCb);
3142 oldSessionParams.unlock(oldSessioMeta);
3143 newSessionParams.unlock(newSessioMeta);
3144 if (err.isOk()) {
3145 switch (callStatus) {
3146 case hardware::camera::common::V1_0::Status::OK:
3147 ret = required;
3148 break;
3149 case hardware::camera::common::V1_0::Status::METHOD_NOT_SUPPORTED:
3150 mIsReconfigurationQuerySupported = false;
3151 ret = true;
3152 break;
3153 default:
3154 ALOGV("%s: Reconfiguration query failed: %d", __FUNCTION__, callStatus);
3155 ret = true;
3156 }
3157 } else {
3158 ALOGE("%s: Unexpected binder error: %s", __FUNCTION__, err.description().c_str());
3159 ret = true;
3160 }
3161 }
3162
3163 return ret;
3164}
3165
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003166status_t Camera3Device::HalInterface::configureStreams(const camera_metadata_t *sessionParams,
Emilian Peevf4816702020-04-03 15:44:51 -07003167 camera_stream_configuration *config, const std::vector<uint32_t>& bufferSizes) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003168 ATRACE_NAME("CameraHal::configureStreams");
3169 if (!valid()) return INVALID_OPERATION;
3170 status_t res = OK;
3171
Emilian Peev31abd0a2017-05-11 18:37:46 +01003172 // Convert stream config to HIDL
3173 std::set<int> activeStreams;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003174 device::V3_2::StreamConfiguration requestedConfiguration3_2;
3175 device::V3_4::StreamConfiguration requestedConfiguration3_4;
3176 requestedConfiguration3_2.streams.resize(config->num_streams);
3177 requestedConfiguration3_4.streams.resize(config->num_streams);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003178 for (size_t i = 0; i < config->num_streams; i++) {
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003179 device::V3_2::Stream &dst3_2 = requestedConfiguration3_2.streams[i];
3180 device::V3_4::Stream &dst3_4 = requestedConfiguration3_4.streams[i];
Emilian Peevf4816702020-04-03 15:44:51 -07003181 camera3::camera_stream_t *src = config->streams[i];
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003182
Emilian Peev31abd0a2017-05-11 18:37:46 +01003183 Camera3Stream* cam3stream = Camera3Stream::cast(src);
3184 cam3stream->setBufferFreedListener(this);
3185 int streamId = cam3stream->getId();
3186 StreamType streamType;
3187 switch (src->stream_type) {
Emilian Peevf4816702020-04-03 15:44:51 -07003188 case CAMERA_STREAM_OUTPUT:
Emilian Peev31abd0a2017-05-11 18:37:46 +01003189 streamType = StreamType::OUTPUT;
3190 break;
Emilian Peevf4816702020-04-03 15:44:51 -07003191 case CAMERA_STREAM_INPUT:
Emilian Peev31abd0a2017-05-11 18:37:46 +01003192 streamType = StreamType::INPUT;
3193 break;
3194 default:
3195 ALOGE("%s: Stream %d: Unsupported stream type %d",
3196 __FUNCTION__, streamId, config->streams[i]->stream_type);
3197 return BAD_VALUE;
3198 }
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003199 dst3_2.id = streamId;
3200 dst3_2.streamType = streamType;
3201 dst3_2.width = src->width;
3202 dst3_2.height = src->height;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003203 dst3_2.usage = mapToConsumerUsage(cam3stream->getUsage());
Emilian Peevf4816702020-04-03 15:44:51 -07003204 dst3_2.rotation = mapToStreamRotation((camera_stream_rotation_t) src->rotation);
Shuzhen Wang92653952019-05-07 15:11:43 -07003205 // For HidlSession version 3.5 or newer, the format and dataSpace sent
3206 // to HAL are original, not the overriden ones.
3207 if (mHidlSession_3_5 != nullptr) {
3208 dst3_2.format = mapToPixelFormat(cam3stream->isFormatOverridden() ?
3209 cam3stream->getOriginalFormat() : src->format);
3210 dst3_2.dataSpace = mapToHidlDataspace(cam3stream->isDataSpaceOverridden() ?
3211 cam3stream->getOriginalDataSpace() : src->data_space);
3212 } else {
3213 dst3_2.format = mapToPixelFormat(src->format);
3214 dst3_2.dataSpace = mapToHidlDataspace(src->data_space);
3215 }
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003216 dst3_4.v3_2 = dst3_2;
Emilian Peev192ee832018-01-31 14:46:47 +00003217 dst3_4.bufferSize = bufferSizes[i];
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003218 if (src->physical_camera_id != nullptr) {
3219 dst3_4.physicalCameraId = src->physical_camera_id;
3220 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003221
3222 activeStreams.insert(streamId);
3223 // Create Buffer ID map if necessary
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003224 mBufferRecords.tryCreateBufferCache(streamId);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003225 }
3226 // remove BufferIdMap for deleted streams
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003227 mBufferRecords.removeInactiveBufferCaches(activeStreams);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003228
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003229 StreamConfigurationMode operationMode;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003230 res = mapToStreamConfigurationMode(
Emilian Peevf4816702020-04-03 15:44:51 -07003231 (camera_stream_configuration_mode_t) config->operation_mode,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003232 /*out*/ &operationMode);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003233 if (res != OK) {
3234 return res;
3235 }
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003236 requestedConfiguration3_2.operationMode = operationMode;
3237 requestedConfiguration3_4.operationMode = operationMode;
3238 requestedConfiguration3_4.sessionParams.setToExternal(
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003239 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(sessionParams)),
3240 get_camera_metadata_size(sessionParams));
3241
Emilian Peev31abd0a2017-05-11 18:37:46 +01003242 // Invoke configureStreams
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003243 device::V3_3::HalStreamConfiguration finalConfiguration;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003244 device::V3_4::HalStreamConfiguration finalConfiguration3_4;
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003245 device::V3_6::HalStreamConfiguration finalConfiguration3_6;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003246 common::V1_0::Status status;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003247
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003248 auto configStream34Cb = [&status, &finalConfiguration3_4]
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003249 (common::V1_0::Status s, const device::V3_4::HalStreamConfiguration& halConfiguration) {
3250 finalConfiguration3_4 = halConfiguration;
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003251 status = s;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003252 };
3253
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003254 auto configStream36Cb = [&status, &finalConfiguration3_6]
3255 (common::V1_0::Status s, const device::V3_6::HalStreamConfiguration& halConfiguration) {
3256 finalConfiguration3_6 = halConfiguration;
3257 status = s;
3258 };
3259
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003260 auto postprocConfigStream34 = [&finalConfiguration, &finalConfiguration3_4]
3261 (hardware::Return<void>& err) -> status_t {
3262 if (!err.isOk()) {
3263 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3264 return DEAD_OBJECT;
3265 }
3266 finalConfiguration.streams.resize(finalConfiguration3_4.streams.size());
3267 for (size_t i = 0; i < finalConfiguration3_4.streams.size(); i++) {
3268 finalConfiguration.streams[i] = finalConfiguration3_4.streams[i].v3_3;
3269 }
3270 return OK;
3271 };
3272
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003273 auto postprocConfigStream36 = [&finalConfiguration, &finalConfiguration3_6]
3274 (hardware::Return<void>& err) -> status_t {
3275 if (!err.isOk()) {
3276 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3277 return DEAD_OBJECT;
3278 }
3279 finalConfiguration.streams.resize(finalConfiguration3_6.streams.size());
3280 for (size_t i = 0; i < finalConfiguration3_6.streams.size(); i++) {
3281 finalConfiguration.streams[i] = finalConfiguration3_6.streams[i].v3_4.v3_3;
3282 }
3283 return OK;
3284 };
3285
Shuzhen Wang92653952019-05-07 15:11:43 -07003286 // See which version of HAL we have
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003287 if (mHidlSession_3_6 != nullptr) {
3288 ALOGV("%s: v3.6 device found", __FUNCTION__);
3289 device::V3_5::StreamConfiguration requestedConfiguration3_5;
3290 requestedConfiguration3_5.v3_4 = requestedConfiguration3_4;
3291 requestedConfiguration3_5.streamConfigCounter = mNextStreamConfigCounter++;
3292 auto err = mHidlSession_3_6->configureStreams_3_6(
3293 requestedConfiguration3_5, configStream36Cb);
3294 res = postprocConfigStream36(err);
3295 if (res != OK) {
3296 return res;
3297 }
3298 } else if (mHidlSession_3_5 != nullptr) {
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003299 ALOGV("%s: v3.5 device found", __FUNCTION__);
3300 device::V3_5::StreamConfiguration requestedConfiguration3_5;
3301 requestedConfiguration3_5.v3_4 = requestedConfiguration3_4;
3302 requestedConfiguration3_5.streamConfigCounter = mNextStreamConfigCounter++;
3303 auto err = mHidlSession_3_5->configureStreams_3_5(
3304 requestedConfiguration3_5, configStream34Cb);
3305 res = postprocConfigStream34(err);
3306 if (res != OK) {
3307 return res;
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003308 }
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003309 } else if (mHidlSession_3_4 != nullptr) {
3310 // We do; use v3.4 for the call
3311 ALOGV("%s: v3.4 device found", __FUNCTION__);
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003312 auto err = mHidlSession_3_4->configureStreams_3_4(
3313 requestedConfiguration3_4, configStream34Cb);
3314 res = postprocConfigStream34(err);
3315 if (res != OK) {
3316 return res;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003317 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003318 } else if (mHidlSession_3_3 != nullptr) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003319 // We do; use v3.3 for the call
3320 ALOGV("%s: v3.3 device found", __FUNCTION__);
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003321 auto err = mHidlSession_3_3->configureStreams_3_3(requestedConfiguration3_2,
Emilian Peev31abd0a2017-05-11 18:37:46 +01003322 [&status, &finalConfiguration]
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003323 (common::V1_0::Status s, const device::V3_3::HalStreamConfiguration& halConfiguration) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003324 finalConfiguration = halConfiguration;
3325 status = s;
3326 });
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003327 if (!err.isOk()) {
3328 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3329 return DEAD_OBJECT;
3330 }
3331 } else {
3332 // We don't; use v3.2 call and construct a v3.3 HalStreamConfiguration
3333 ALOGV("%s: v3.2 device found", __FUNCTION__);
3334 HalStreamConfiguration finalConfiguration_3_2;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003335 auto err = mHidlSession->configureStreams(requestedConfiguration3_2,
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003336 [&status, &finalConfiguration_3_2]
3337 (common::V1_0::Status s, const HalStreamConfiguration& halConfiguration) {
3338 finalConfiguration_3_2 = halConfiguration;
3339 status = s;
3340 });
3341 if (!err.isOk()) {
3342 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3343 return DEAD_OBJECT;
3344 }
3345 finalConfiguration.streams.resize(finalConfiguration_3_2.streams.size());
3346 for (size_t i = 0; i < finalConfiguration_3_2.streams.size(); i++) {
3347 finalConfiguration.streams[i].v3_2 = finalConfiguration_3_2.streams[i];
3348 finalConfiguration.streams[i].overrideDataSpace =
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003349 requestedConfiguration3_2.streams[i].dataSpace;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003350 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003351 }
3352
3353 if (status != common::V1_0::Status::OK ) {
3354 return CameraProviderManager::mapToStatusT(status);
3355 }
3356
3357 // And convert output stream configuration from HIDL
3358
3359 for (size_t i = 0; i < config->num_streams; i++) {
Emilian Peevf4816702020-04-03 15:44:51 -07003360 camera3::camera_stream_t *dst = config->streams[i];
Emilian Peev31abd0a2017-05-11 18:37:46 +01003361 int streamId = Camera3Stream::cast(dst)->getId();
3362
3363 // Start scan at i, with the assumption that the stream order matches
3364 size_t realIdx = i;
3365 bool found = false;
Eino-Ville Talvala370875f2019-04-12 12:40:27 -07003366 size_t halStreamCount = finalConfiguration.streams.size();
3367 for (size_t idx = 0; idx < halStreamCount; idx++) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003368 if (finalConfiguration.streams[realIdx].v3_2.id == streamId) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003369 found = true;
3370 break;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003371 }
Eino-Ville Talvala370875f2019-04-12 12:40:27 -07003372 realIdx = (realIdx >= halStreamCount - 1) ? 0 : realIdx + 1;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003373 }
3374 if (!found) {
3375 ALOGE("%s: Stream %d not found in stream configuration response from HAL",
3376 __FUNCTION__, streamId);
3377 return INVALID_OPERATION;
3378 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003379 device::V3_3::HalStream &src = finalConfiguration.streams[realIdx];
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003380 device::V3_6::HalStream &src_36 = finalConfiguration3_6.streams[realIdx];
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003381
Emilian Peev710c1422017-08-30 11:19:38 +01003382 Camera3Stream* dstStream = Camera3Stream::cast(dst);
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003383 int overrideFormat = mapToFrameworkFormat(src.v3_2.overrideFormat);
3384 android_dataspace overrideDataSpace = mapToFrameworkDataspace(src.overrideDataSpace);
3385
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003386 if (mHidlSession_3_6 != nullptr) {
3387 dstStream->setOfflineProcessingSupport(src_36.supportOffline);
3388 }
3389
Yin-Chia Yeh90667662019-07-01 15:45:00 -07003390 if (dstStream->getOriginalFormat() != HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
Shuzhen Wang92653952019-05-07 15:11:43 -07003391 dstStream->setFormatOverride(false);
3392 dstStream->setDataSpaceOverride(false);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003393 if (dst->format != overrideFormat) {
3394 ALOGE("%s: Stream %d: Format override not allowed for format 0x%x", __FUNCTION__,
3395 streamId, dst->format);
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003396 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003397 if (dst->data_space != overrideDataSpace) {
3398 ALOGE("%s: Stream %d: DataSpace override not allowed for format 0x%x", __FUNCTION__,
3399 streamId, dst->format);
3400 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003401 } else {
Shuzhen Wang92653952019-05-07 15:11:43 -07003402 bool needFormatOverride =
3403 requestedConfiguration3_2.streams[i].format != src.v3_2.overrideFormat;
3404 bool needDataspaceOverride =
3405 requestedConfiguration3_2.streams[i].dataSpace != src.overrideDataSpace;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003406 // Override allowed with IMPLEMENTATION_DEFINED
Shuzhen Wang92653952019-05-07 15:11:43 -07003407 dstStream->setFormatOverride(needFormatOverride);
3408 dstStream->setDataSpaceOverride(needDataspaceOverride);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003409 dst->format = overrideFormat;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003410 dst->data_space = overrideDataSpace;
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003411 }
3412
Emilian Peevf4816702020-04-03 15:44:51 -07003413 if (dst->stream_type == CAMERA_STREAM_INPUT) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003414 if (src.v3_2.producerUsage != 0) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003415 ALOGE("%s: Stream %d: INPUT streams must have 0 for producer usage",
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003416 __FUNCTION__, streamId);
3417 return INVALID_OPERATION;
3418 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003419 dstStream->setUsage(
3420 mapConsumerToFrameworkUsage(src.v3_2.consumerUsage));
Emilian Peev31abd0a2017-05-11 18:37:46 +01003421 } else {
3422 // OUTPUT
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003423 if (src.v3_2.consumerUsage != 0) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003424 ALOGE("%s: Stream %d: OUTPUT streams must have 0 for consumer usage",
3425 __FUNCTION__, streamId);
3426 return INVALID_OPERATION;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003427 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003428 dstStream->setUsage(
3429 mapProducerToFrameworkUsage(src.v3_2.producerUsage));
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003430 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003431 dst->max_buffers = src.v3_2.maxBuffers;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003432 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003433
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003434 return res;
3435}
3436
Emilian Peevf4816702020-04-03 15:44:51 -07003437status_t Camera3Device::HalInterface::wrapAsHidlRequest(camera_capture_request_t* request,
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003438 /*out*/device::V3_2::CaptureRequest* captureRequest,
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003439 /*out*/std::vector<native_handle_t*>* handlesCreated,
3440 /*out*/std::vector<std::pair<int32_t, int32_t>>* inflightBuffers) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003441 ATRACE_CALL();
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003442 if (captureRequest == nullptr || handlesCreated == nullptr || inflightBuffers == nullptr) {
3443 ALOGE("%s: captureRequest (%p), handlesCreated (%p), and inflightBuffers(%p) "
3444 "must not be null", __FUNCTION__, captureRequest, handlesCreated, inflightBuffers);
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003445 return BAD_VALUE;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003446 }
3447
3448 captureRequest->frameNumber = request->frame_number;
Yifan Hongf79b5542017-04-11 14:44:25 -07003449
3450 captureRequest->fmqSettingsSize = 0;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003451
3452 {
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003453 if (request->input_buffer != nullptr) {
3454 int32_t streamId = Camera3Stream::cast(request->input_buffer->stream)->getId();
3455 buffer_handle_t buf = *(request->input_buffer->buffer);
3456 auto pair = getBufferId(buf, streamId);
3457 bool isNewBuffer = pair.first;
3458 uint64_t bufferId = pair.second;
3459 captureRequest->inputBuffer.streamId = streamId;
3460 captureRequest->inputBuffer.bufferId = bufferId;
3461 captureRequest->inputBuffer.buffer = (isNewBuffer) ? buf : nullptr;
3462 captureRequest->inputBuffer.status = BufferStatus::OK;
3463 native_handle_t *acquireFence = nullptr;
3464 if (request->input_buffer->acquire_fence != -1) {
3465 acquireFence = native_handle_create(1,0);
3466 acquireFence->data[0] = request->input_buffer->acquire_fence;
3467 handlesCreated->push_back(acquireFence);
3468 }
3469 captureRequest->inputBuffer.acquireFence = acquireFence;
3470 captureRequest->inputBuffer.releaseFence = nullptr;
3471
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003472 mBufferRecords.pushInflightBuffer(captureRequest->frameNumber, streamId,
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003473 request->input_buffer->buffer);
3474 inflightBuffers->push_back(std::make_pair(captureRequest->frameNumber, streamId));
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003475 } else {
3476 captureRequest->inputBuffer.streamId = -1;
3477 captureRequest->inputBuffer.bufferId = BUFFER_ID_NO_BUFFER;
3478 }
3479
3480 captureRequest->outputBuffers.resize(request->num_output_buffers);
3481 for (size_t i = 0; i < request->num_output_buffers; i++) {
Emilian Peevf4816702020-04-03 15:44:51 -07003482 const camera_stream_buffer_t *src = request->output_buffers + i;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003483 StreamBuffer &dst = captureRequest->outputBuffers[i];
3484 int32_t streamId = Camera3Stream::cast(src->stream)->getId();
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003485 if (src->buffer != nullptr) {
3486 buffer_handle_t buf = *(src->buffer);
3487 auto pair = getBufferId(buf, streamId);
3488 bool isNewBuffer = pair.first;
3489 dst.bufferId = pair.second;
3490 dst.buffer = isNewBuffer ? buf : nullptr;
3491 native_handle_t *acquireFence = nullptr;
3492 if (src->acquire_fence != -1) {
3493 acquireFence = native_handle_create(1,0);
3494 acquireFence->data[0] = src->acquire_fence;
3495 handlesCreated->push_back(acquireFence);
3496 }
3497 dst.acquireFence = acquireFence;
3498 } else if (mUseHalBufManager) {
3499 // HAL buffer management path
3500 dst.bufferId = BUFFER_ID_NO_BUFFER;
3501 dst.buffer = nullptr;
3502 dst.acquireFence = nullptr;
3503 } else {
3504 ALOGE("%s: cannot send a null buffer in capture request!", __FUNCTION__);
3505 return BAD_VALUE;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003506 }
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003507 dst.streamId = streamId;
3508 dst.status = BufferStatus::OK;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003509 dst.releaseFence = nullptr;
3510
Yin-Chia Yeh5f840f82019-03-05 11:59:04 -08003511 // Output buffers are empty when using HAL buffer manager
3512 if (!mUseHalBufManager) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003513 mBufferRecords.pushInflightBuffer(
3514 captureRequest->frameNumber, streamId, src->buffer);
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003515 inflightBuffers->push_back(std::make_pair(captureRequest->frameNumber, streamId));
Yin-Chia Yeh5f840f82019-03-05 11:59:04 -08003516 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003517 }
3518 }
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003519 return OK;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003520}
3521
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003522void Camera3Device::HalInterface::cleanupNativeHandles(
3523 std::vector<native_handle_t*> *handles, bool closeFd) {
3524 if (handles == nullptr) {
3525 return;
3526 }
3527 if (closeFd) {
3528 for (auto& handle : *handles) {
3529 native_handle_close(handle);
3530 }
3531 }
3532 for (auto& handle : *handles) {
3533 native_handle_delete(handle);
3534 }
3535 handles->clear();
3536 return;
3537}
3538
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003539status_t Camera3Device::HalInterface::processBatchCaptureRequests(
Emilian Peevf4816702020-04-03 15:44:51 -07003540 std::vector<camera_capture_request_t*>& requests,/*out*/uint32_t* numRequestProcessed) {
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003541 ATRACE_NAME("CameraHal::processBatchCaptureRequests");
3542 if (!valid()) return INVALID_OPERATION;
3543
Emilian Peevaebbe412018-01-15 13:53:24 +00003544 sp<device::V3_4::ICameraDeviceSession> hidlSession_3_4;
3545 auto castResult_3_4 = device::V3_4::ICameraDeviceSession::castFrom(mHidlSession);
3546 if (castResult_3_4.isOk()) {
3547 hidlSession_3_4 = castResult_3_4;
3548 }
3549
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003550 hardware::hidl_vec<device::V3_2::CaptureRequest> captureRequests;
Emilian Peevaebbe412018-01-15 13:53:24 +00003551 hardware::hidl_vec<device::V3_4::CaptureRequest> captureRequests_3_4;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003552 size_t batchSize = requests.size();
Emilian Peevaebbe412018-01-15 13:53:24 +00003553 if (hidlSession_3_4 != nullptr) {
3554 captureRequests_3_4.resize(batchSize);
3555 } else {
3556 captureRequests.resize(batchSize);
3557 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003558 std::vector<native_handle_t*> handlesCreated;
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003559 std::vector<std::pair<int32_t, int32_t>> inflightBuffers;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003560
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003561 status_t res = OK;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003562 for (size_t i = 0; i < batchSize; i++) {
Emilian Peevaebbe412018-01-15 13:53:24 +00003563 if (hidlSession_3_4 != nullptr) {
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003564 res = wrapAsHidlRequest(requests[i], /*out*/&captureRequests_3_4[i].v3_2,
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003565 /*out*/&handlesCreated, /*out*/&inflightBuffers);
Emilian Peevaebbe412018-01-15 13:53:24 +00003566 } else {
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003567 res = wrapAsHidlRequest(requests[i], /*out*/&captureRequests[i],
3568 /*out*/&handlesCreated, /*out*/&inflightBuffers);
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003569 }
3570 if (res != OK) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003571 mBufferRecords.popInflightBuffers(inflightBuffers);
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003572 cleanupNativeHandles(&handlesCreated);
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003573 return res;
Emilian Peevaebbe412018-01-15 13:53:24 +00003574 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003575 }
3576
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003577 std::vector<device::V3_2::BufferCache> cachesToRemove;
3578 {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003579 std::lock_guard<std::mutex> lock(mFreedBuffersLock);
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003580 for (auto& pair : mFreedBuffers) {
3581 // The stream might have been removed since onBufferFreed
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003582 if (mBufferRecords.isStreamCached(pair.first)) {
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003583 cachesToRemove.push_back({pair.first, pair.second});
3584 }
3585 }
3586 mFreedBuffers.clear();
3587 }
3588
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003589 common::V1_0::Status status = common::V1_0::Status::INTERNAL_ERROR;
3590 *numRequestProcessed = 0;
Yifan Hongf79b5542017-04-11 14:44:25 -07003591
3592 // Write metadata to FMQ.
3593 for (size_t i = 0; i < batchSize; i++) {
Emilian Peevf4816702020-04-03 15:44:51 -07003594 camera_capture_request_t* request = requests[i];
Emilian Peevaebbe412018-01-15 13:53:24 +00003595 device::V3_2::CaptureRequest* captureRequest;
3596 if (hidlSession_3_4 != nullptr) {
3597 captureRequest = &captureRequests_3_4[i].v3_2;
3598 } else {
3599 captureRequest = &captureRequests[i];
3600 }
Yifan Hongf79b5542017-04-11 14:44:25 -07003601
3602 if (request->settings != nullptr) {
3603 size_t settingsSize = get_camera_metadata_size(request->settings);
3604 if (mRequestMetadataQueue != nullptr && mRequestMetadataQueue->write(
3605 reinterpret_cast<const uint8_t*>(request->settings), settingsSize)) {
3606 captureRequest->settings.resize(0);
3607 captureRequest->fmqSettingsSize = settingsSize;
3608 } else {
3609 if (mRequestMetadataQueue != nullptr) {
3610 ALOGW("%s: couldn't utilize fmq, fallback to hwbinder", __FUNCTION__);
3611 }
3612 captureRequest->settings.setToExternal(
3613 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(request->settings)),
3614 get_camera_metadata_size(request->settings));
3615 captureRequest->fmqSettingsSize = 0u;
3616 }
3617 } else {
3618 // A null request settings maps to a size-0 CameraMetadata
3619 captureRequest->settings.resize(0);
3620 captureRequest->fmqSettingsSize = 0u;
3621 }
Emilian Peevaebbe412018-01-15 13:53:24 +00003622
3623 if (hidlSession_3_4 != nullptr) {
3624 captureRequests_3_4[i].physicalCameraSettings.resize(request->num_physcam_settings);
3625 for (size_t j = 0; j < request->num_physcam_settings; j++) {
Emilian Peev00420d22018-02-05 21:33:13 +00003626 if (request->physcam_settings != nullptr) {
3627 size_t settingsSize = get_camera_metadata_size(request->physcam_settings[j]);
3628 if (mRequestMetadataQueue != nullptr && mRequestMetadataQueue->write(
3629 reinterpret_cast<const uint8_t*>(request->physcam_settings[j]),
3630 settingsSize)) {
3631 captureRequests_3_4[i].physicalCameraSettings[j].settings.resize(0);
3632 captureRequests_3_4[i].physicalCameraSettings[j].fmqSettingsSize =
3633 settingsSize;
3634 } else {
3635 if (mRequestMetadataQueue != nullptr) {
3636 ALOGW("%s: couldn't utilize fmq, fallback to hwbinder", __FUNCTION__);
3637 }
3638 captureRequests_3_4[i].physicalCameraSettings[j].settings.setToExternal(
3639 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(
3640 request->physcam_settings[j])),
3641 get_camera_metadata_size(request->physcam_settings[j]));
3642 captureRequests_3_4[i].physicalCameraSettings[j].fmqSettingsSize = 0u;
Emilian Peevaebbe412018-01-15 13:53:24 +00003643 }
Emilian Peev00420d22018-02-05 21:33:13 +00003644 } else {
Emilian Peevaebbe412018-01-15 13:53:24 +00003645 captureRequests_3_4[i].physicalCameraSettings[j].fmqSettingsSize = 0u;
Emilian Peev00420d22018-02-05 21:33:13 +00003646 captureRequests_3_4[i].physicalCameraSettings[j].settings.resize(0);
Emilian Peevaebbe412018-01-15 13:53:24 +00003647 }
3648 captureRequests_3_4[i].physicalCameraSettings[j].physicalCameraId =
3649 request->physcam_id[j];
3650 }
3651 }
Yifan Hongf79b5542017-04-11 14:44:25 -07003652 }
Emilian Peevaebbe412018-01-15 13:53:24 +00003653
3654 hardware::details::return_status err;
Jayant Chowdharyc8d581e2018-07-16 14:46:23 -07003655 auto resultCallback =
3656 [&status, &numRequestProcessed] (auto s, uint32_t n) {
3657 status = s;
3658 *numRequestProcessed = n;
3659 };
Emilian Peevaebbe412018-01-15 13:53:24 +00003660 if (hidlSession_3_4 != nullptr) {
3661 err = hidlSession_3_4->processCaptureRequest_3_4(captureRequests_3_4, cachesToRemove,
Jayant Chowdharyc8d581e2018-07-16 14:46:23 -07003662 resultCallback);
Emilian Peevaebbe412018-01-15 13:53:24 +00003663 } else {
3664 err = mHidlSession->processCaptureRequest(captureRequests, cachesToRemove,
Jayant Chowdharyc8d581e2018-07-16 14:46:23 -07003665 resultCallback);
Emilian Peevaebbe412018-01-15 13:53:24 +00003666 }
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -07003667 if (!err.isOk()) {
3668 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003669 status = common::V1_0::Status::CAMERA_DISCONNECTED;
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -07003670 }
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003671
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003672 if (status == common::V1_0::Status::OK && *numRequestProcessed != batchSize) {
3673 ALOGE("%s: processCaptureRequest returns OK but processed %d/%zu requests",
3674 __FUNCTION__, *numRequestProcessed, batchSize);
3675 status = common::V1_0::Status::INTERNAL_ERROR;
3676 }
3677
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003678 res = CameraProviderManager::mapToStatusT(status);
3679 if (res == OK) {
3680 if (mHidlSession->isRemote()) {
3681 // Only close acquire fence FDs when the HIDL transaction succeeds (so the FDs have been
3682 // sent to camera HAL processes)
3683 cleanupNativeHandles(&handlesCreated, /*closeFd*/true);
3684 } else {
3685 // In passthrough mode the FDs are now owned by HAL
3686 cleanupNativeHandles(&handlesCreated);
3687 }
3688 } else {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003689 mBufferRecords.popInflightBuffers(inflightBuffers);
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003690 cleanupNativeHandles(&handlesCreated);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003691 }
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003692 return res;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003693}
3694
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003695status_t Camera3Device::HalInterface::flush() {
3696 ATRACE_NAME("CameraHal::flush");
3697 if (!valid()) return INVALID_OPERATION;
3698 status_t res = OK;
3699
Emilian Peev31abd0a2017-05-11 18:37:46 +01003700 auto err = mHidlSession->flush();
3701 if (!err.isOk()) {
3702 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3703 res = DEAD_OBJECT;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003704 } else {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003705 res = CameraProviderManager::mapToStatusT(err);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003706 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003707
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003708 return res;
3709}
3710
Emilian Peev31abd0a2017-05-11 18:37:46 +01003711status_t Camera3Device::HalInterface::dump(int /*fd*/) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003712 ATRACE_NAME("CameraHal::dump");
3713 if (!valid()) return INVALID_OPERATION;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003714
Emilian Peev31abd0a2017-05-11 18:37:46 +01003715 // Handled by CameraProviderManager::dump
3716
3717 return OK;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003718}
3719
3720status_t Camera3Device::HalInterface::close() {
3721 ATRACE_NAME("CameraHal::close()");
3722 if (!valid()) return INVALID_OPERATION;
3723 status_t res = OK;
3724
Emilian Peev31abd0a2017-05-11 18:37:46 +01003725 auto err = mHidlSession->close();
3726 // Interface will be dead shortly anyway, so don't log errors
3727 if (!err.isOk()) {
3728 res = DEAD_OBJECT;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003729 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003730
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003731 return res;
3732}
3733
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003734void Camera3Device::HalInterface::signalPipelineDrain(const std::vector<int>& streamIds) {
3735 ATRACE_NAME("CameraHal::signalPipelineDrain");
3736 if (!valid() || mHidlSession_3_5 == nullptr) {
3737 ALOGE("%s called on invalid camera!", __FUNCTION__);
3738 return;
3739 }
3740
Yin-Chia Yehc300a072019-02-13 14:56:57 -08003741 auto err = mHidlSession_3_5->signalStreamFlush(streamIds, mNextStreamConfigCounter - 1);
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003742 if (!err.isOk()) {
3743 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3744 return;
3745 }
3746}
3747
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003748status_t Camera3Device::HalInterface::switchToOffline(
3749 const std::vector<int32_t>& streamsToKeep,
3750 /*out*/hardware::camera::device::V3_6::CameraOfflineSessionInfo* offlineSessionInfo,
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003751 /*out*/sp<hardware::camera::device::V3_6::ICameraOfflineSession>* offlineSession,
3752 /*out*/camera3::BufferRecords* bufferRecords) {
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003753 ATRACE_NAME("CameraHal::switchToOffline");
3754 if (!valid() || mHidlSession_3_6 == nullptr) {
3755 ALOGE("%s called on invalid camera!", __FUNCTION__);
3756 return INVALID_OPERATION;
3757 }
3758
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003759 if (offlineSessionInfo == nullptr || offlineSession == nullptr || bufferRecords == nullptr) {
3760 ALOGE("%s: output arguments must not be null!", __FUNCTION__);
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003761 return INVALID_OPERATION;
3762 }
3763
3764 common::V1_0::Status status = common::V1_0::Status::INTERNAL_ERROR;
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003765 auto resultCallback =
3766 [&status, &offlineSessionInfo, &offlineSession] (auto s, auto info, auto session) {
3767 status = s;
3768 *offlineSessionInfo = info;
3769 *offlineSession = session;
3770 };
3771 auto err = mHidlSession_3_6->switchToOffline(streamsToKeep, resultCallback);
3772
3773 if (!err.isOk()) {
3774 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3775 return DEAD_OBJECT;
3776 }
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003777
3778 status_t ret = CameraProviderManager::mapToStatusT(status);
3779 if (ret != OK) {
3780 return ret;
3781 }
3782
3783 // TODO: assert no ongoing requestBuffer/returnBuffer call here
3784 // TODO: update RequestBufferStateMachine to block requestBuffer/returnBuffer once HAL
3785 // returns from switchToOffline.
3786
3787
3788 // Validate buffer caches
3789 std::vector<int32_t> streams;
3790 streams.reserve(offlineSessionInfo->offlineStreams.size());
3791 for (auto offlineStream : offlineSessionInfo->offlineStreams) {
3792 int32_t id = offlineStream.id;
3793 streams.push_back(id);
3794 // Verify buffer caches
3795 std::vector<uint64_t> bufIds(offlineStream.circulatingBufferIds.begin(),
3796 offlineStream.circulatingBufferIds.end());
3797 if (!verifyBufferIds(id, bufIds)) {
3798 ALOGE("%s: stream ID %d buffer cache records mismatch!", __FUNCTION__, id);
3799 return UNKNOWN_ERROR;
3800 }
3801 }
3802
3803 // Move buffer records
3804 bufferRecords->takeBufferCaches(mBufferRecords, streams);
3805 bufferRecords->takeInflightBufferMap(mBufferRecords);
3806 bufferRecords->takeRequestedBufferMap(mBufferRecords);
3807 return ret;
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003808}
3809
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003810void Camera3Device::HalInterface::getInflightBufferKeys(
3811 std::vector<std::pair<int32_t, int32_t>>* out) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003812 mBufferRecords.getInflightBufferKeys(out);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003813 return;
3814}
3815
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08003816void Camera3Device::HalInterface::getInflightRequestBufferKeys(
3817 std::vector<uint64_t>* out) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003818 mBufferRecords.getInflightRequestBufferKeys(out);
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08003819 return;
3820}
3821
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003822bool Camera3Device::HalInterface::verifyBufferIds(
3823 int32_t streamId, std::vector<uint64_t>& bufIds) {
3824 return mBufferRecords.verifyBufferIds(streamId, bufIds);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003825}
3826
3827status_t Camera3Device::HalInterface::popInflightBuffer(
Yin-Chia Yehf4650602017-01-10 13:13:39 -08003828 int32_t frameNumber, int32_t streamId,
3829 /*out*/ buffer_handle_t **buffer) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003830 return mBufferRecords.popInflightBuffer(frameNumber, streamId, buffer);
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003831}
3832
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003833status_t Camera3Device::HalInterface::pushInflightRequestBuffer(
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08003834 uint64_t bufferId, buffer_handle_t* buf, int32_t streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003835 return mBufferRecords.pushInflightRequestBuffer(bufferId, buf, streamId);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003836}
3837
3838// Find and pop a buffer_handle_t based on bufferId
3839status_t Camera3Device::HalInterface::popInflightRequestBuffer(
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08003840 uint64_t bufferId,
3841 /*out*/ buffer_handle_t** buffer,
3842 /*optional out*/ int32_t* streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003843 return mBufferRecords.popInflightRequestBuffer(bufferId, buffer, streamId);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003844}
3845
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003846std::pair<bool, uint64_t> Camera3Device::HalInterface::getBufferId(
3847 const buffer_handle_t& buf, int streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003848 return mBufferRecords.getBufferId(buf, streamId);
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003849}
3850
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003851void Camera3Device::HalInterface::onBufferFreed(
3852 int streamId, const native_handle_t* handle) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003853 uint32_t bufferId = mBufferRecords.removeOneBufferCache(streamId, handle);
3854 std::lock_guard<std::mutex> lock(mFreedBuffersLock);
3855 if (bufferId != BUFFER_ID_NO_BUFFER) {
3856 mFreedBuffers.push_back(std::make_pair(streamId, bufferId));
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003857 }
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003858}
3859
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07003860void Camera3Device::HalInterface::onStreamReConfigured(int streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003861 std::vector<uint64_t> bufIds = mBufferRecords.clearBufferCaches(streamId);
3862 std::lock_guard<std::mutex> lock(mFreedBuffersLock);
3863 for (auto bufferId : bufIds) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07003864 mFreedBuffers.push_back(std::make_pair(streamId, bufferId));
3865 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07003866}
3867
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003868/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003869 * RequestThread inner class methods
3870 */
3871
3872Camera3Device::RequestThread::RequestThread(wp<Camera3Device> parent,
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003873 sp<StatusTracker> statusTracker,
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003874 sp<HalInterface> interface, const Vector<int32_t>& sessionParamKeys,
3875 bool useHalBufManager) :
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07003876 Thread(/*canCallJava*/false),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003877 mParent(parent),
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003878 mStatusTracker(statusTracker),
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003879 mInterface(interface),
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07003880 mListener(nullptr),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003881 mId(getId(parent)),
Shuzhen Wang316781a2020-08-18 18:11:01 -07003882 mFirstRepeating(false),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003883 mReconfigured(false),
3884 mDoPause(false),
3885 mPaused(true),
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003886 mNotifyPipelineDrain(false),
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003887 mFrameNumber(0),
Jianing Weicb0652e2014-03-12 18:29:36 -07003888 mLatestRequestId(NAME_NOT_FOUND),
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07003889 mCurrentAfTriggerId(0),
3890 mCurrentPreCaptureTriggerId(0),
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08003891 mRotateAndCropOverride(ANDROID_SCALER_ROTATE_AND_CROP_NONE),
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08003892 mCameraMute(false),
3893 mCameraMuteChanged(false),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003894 mRepeatingLastFrameNumber(
3895 hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES),
Shuzhen Wang686f6442017-06-20 16:16:04 -07003896 mPrepareVideoStream(false),
Emilian Peeva14b4dd2018-05-15 11:00:31 +01003897 mConstrainedMode(false),
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003898 mRequestLatency(kRequestLatencyBinSize),
3899 mSessionParamKeys(sessionParamKeys),
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003900 mLatestSessionParams(sessionParamKeys.size()),
3901 mUseHalBufManager(useHalBufManager) {
Yin-Chia Yeh87b3ec02019-06-03 10:44:39 -07003902 mStatusId = statusTracker->addComponent("RequestThread");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003903}
3904
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003905Camera3Device::RequestThread::~RequestThread() {}
3906
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07003907void Camera3Device::RequestThread::setNotificationListener(
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003908 wp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003909 ATRACE_CALL();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003910 Mutex::Autolock l(mRequestLock);
3911 mListener = listener;
3912}
3913
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003914void Camera3Device::RequestThread::configurationComplete(bool isConstrainedHighSpeed,
3915 const CameraMetadata& sessionParams) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003916 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003917 Mutex::Autolock l(mRequestLock);
3918 mReconfigured = true;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003919 mLatestSessionParams = sessionParams;
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07003920 // Prepare video stream for high speed recording.
3921 mPrepareVideoStream = isConstrainedHighSpeed;
Emilian Peeva14b4dd2018-05-15 11:00:31 +01003922 mConstrainedMode = isConstrainedHighSpeed;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003923}
3924
Jianing Wei90e59c92014-03-12 18:29:36 -07003925status_t Camera3Device::RequestThread::queueRequestList(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003926 List<sp<CaptureRequest> > &requests,
3927 /*out*/
3928 int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003929 ATRACE_CALL();
Jianing Wei90e59c92014-03-12 18:29:36 -07003930 Mutex::Autolock l(mRequestLock);
3931 for (List<sp<CaptureRequest> >::iterator it = requests.begin(); it != requests.end();
3932 ++it) {
3933 mRequestQueue.push_back(*it);
3934 }
3935
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003936 if (lastFrameNumber != NULL) {
3937 *lastFrameNumber = mFrameNumber + mRequestQueue.size() - 1;
3938 ALOGV("%s: requestId %d, mFrameNumber %" PRId32 ", lastFrameNumber %" PRId64 ".",
3939 __FUNCTION__, (*(requests.begin()))->mResultExtras.requestId, mFrameNumber,
3940 *lastFrameNumber);
3941 }
Jianing Weicb0652e2014-03-12 18:29:36 -07003942
Jianing Wei90e59c92014-03-12 18:29:36 -07003943 unpauseForNewRequests();
3944
3945 return OK;
3946}
3947
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003948
3949status_t Camera3Device::RequestThread::queueTrigger(
3950 RequestTrigger trigger[],
3951 size_t count) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003952 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003953 Mutex::Autolock l(mTriggerMutex);
3954 status_t ret;
3955
3956 for (size_t i = 0; i < count; ++i) {
3957 ret = queueTriggerLocked(trigger[i]);
3958
3959 if (ret != OK) {
3960 return ret;
3961 }
3962 }
3963
3964 return OK;
3965}
3966
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003967const String8& Camera3Device::RequestThread::getId(const wp<Camera3Device> &device) {
3968 static String8 deadId("<DeadDevice>");
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003969 sp<Camera3Device> d = device.promote();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003970 if (d != nullptr) return d->mId;
3971 return deadId;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003972}
3973
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003974status_t Camera3Device::RequestThread::queueTriggerLocked(
3975 RequestTrigger trigger) {
3976
3977 uint32_t tag = trigger.metadataTag;
3978 ssize_t index = mTriggerMap.indexOfKey(tag);
3979
3980 switch (trigger.getTagType()) {
3981 case TYPE_BYTE:
3982 // fall-through
3983 case TYPE_INT32:
3984 break;
3985 default:
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003986 ALOGE("%s: Type not supported: 0x%x", __FUNCTION__,
3987 trigger.getTagType());
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003988 return INVALID_OPERATION;
3989 }
3990
3991 /**
3992 * Collect only the latest trigger, since we only have 1 field
3993 * in the request settings per trigger tag, and can't send more than 1
3994 * trigger per request.
3995 */
3996 if (index != NAME_NOT_FOUND) {
3997 mTriggerMap.editValueAt(index) = trigger;
3998 } else {
3999 mTriggerMap.add(tag, trigger);
4000 }
4001
4002 return OK;
4003}
4004
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004005status_t Camera3Device::RequestThread::setRepeatingRequests(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004006 const RequestList &requests,
4007 /*out*/
4008 int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004009 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004010 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004011 if (lastFrameNumber != NULL) {
4012 *lastFrameNumber = mRepeatingLastFrameNumber;
4013 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004014 mRepeatingRequests.clear();
Shuzhen Wang316781a2020-08-18 18:11:01 -07004015 mFirstRepeating = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004016 mRepeatingRequests.insert(mRepeatingRequests.begin(),
4017 requests.begin(), requests.end());
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004018
4019 unpauseForNewRequests();
4020
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004021 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004022 return OK;
4023}
4024
Chih-Hung Hsieh8b0b9712016-08-09 14:25:53 -07004025bool Camera3Device::RequestThread::isRepeatingRequestLocked(const sp<CaptureRequest>& requestIn) {
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07004026 if (mRepeatingRequests.empty()) {
4027 return false;
4028 }
4029 int32_t requestId = requestIn->mResultExtras.requestId;
4030 const RequestList &repeatRequests = mRepeatingRequests;
4031 // All repeating requests are guaranteed to have same id so only check first quest
4032 const sp<CaptureRequest> firstRequest = *repeatRequests.begin();
4033 return (firstRequest->mResultExtras.requestId == requestId);
4034}
4035
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004036status_t Camera3Device::RequestThread::clearRepeatingRequests(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004037 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004038 Mutex::Autolock l(mRequestLock);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004039 return clearRepeatingRequestsLocked(lastFrameNumber);
4040
4041}
4042
4043status_t Camera3Device::RequestThread::clearRepeatingRequestsLocked(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004044 mRepeatingRequests.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004045 if (lastFrameNumber != NULL) {
4046 *lastFrameNumber = mRepeatingLastFrameNumber;
4047 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004048 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004049 return OK;
4050}
4051
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004052status_t Camera3Device::RequestThread::clear(
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004053 /*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004054 ATRACE_CALL();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004055 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004056 ALOGV("RequestThread::%s:", __FUNCTION__);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004057
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004058 mRepeatingRequests.clear();
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07004059
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004060 // Send errors for all requests pending in the request queue, including
4061 // pending repeating requests
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004062 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004063 if (listener != NULL) {
4064 for (RequestList::iterator it = mRequestQueue.begin();
4065 it != mRequestQueue.end(); ++it) {
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004066 // Abort the input buffers for reprocess requests.
4067 if ((*it)->mInputStream != NULL) {
Emilian Peevf4816702020-04-03 15:44:51 -07004068 camera_stream_buffer_t inputBuffer;
Eino-Ville Talvalaba435252017-06-21 16:07:25 -07004069 status_t res = (*it)->mInputStream->getInputBuffer(&inputBuffer,
4070 /*respectHalLimit*/ false);
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004071 if (res != OK) {
4072 ALOGW("%s: %d: couldn't get input buffer while clearing the request "
4073 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
4074 } else {
Emilian Peevf4816702020-04-03 15:44:51 -07004075 inputBuffer.status = CAMERA_BUFFER_STATUS_ERROR;
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004076 res = (*it)->mInputStream->returnInputBuffer(inputBuffer);
4077 if (res != OK) {
4078 ALOGE("%s: %d: couldn't return input buffer while clearing the request "
4079 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
4080 }
4081 }
4082 }
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004083 // Set the frame number this request would have had, if it
4084 // had been submitted; this frame number will not be reused.
4085 // The requestId and burstId fields were set when the request was
4086 // submitted originally (in convertMetadataListToRequestListLocked)
4087 (*it)->mResultExtras.frameNumber = mFrameNumber++;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004088 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004089 (*it)->mResultExtras);
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07004090 }
4091 }
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004092 mRequestQueue.clear();
Jinguang Dongb26e7a02016-11-14 16:04:02 +08004093
4094 Mutex::Autolock al(mTriggerMutex);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004095 mTriggerMap.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004096 if (lastFrameNumber != NULL) {
4097 *lastFrameNumber = mRepeatingLastFrameNumber;
4098 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004099 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Emilian Peev8dae54c2019-12-02 15:17:17 -08004100 mRequestSignal.signal();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004101 return OK;
4102}
4103
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004104status_t Camera3Device::RequestThread::flush() {
4105 ATRACE_CALL();
4106 Mutex::Autolock l(mFlushLock);
4107
Emilian Peev08dd2452017-04-06 16:55:14 +01004108 return mInterface->flush();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004109}
4110
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004111void Camera3Device::RequestThread::setPaused(bool paused) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004112 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004113 Mutex::Autolock l(mPauseLock);
4114 mDoPause = paused;
4115 mDoPauseSignal.signal();
4116}
4117
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004118status_t Camera3Device::RequestThread::waitUntilRequestProcessed(
4119 int32_t requestId, nsecs_t timeout) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004120 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004121 Mutex::Autolock l(mLatestRequestMutex);
4122 status_t res;
4123 while (mLatestRequestId != requestId) {
4124 nsecs_t startTime = systemTime();
4125
4126 res = mLatestRequestSignal.waitRelative(mLatestRequestMutex, timeout);
4127 if (res != OK) return res;
4128
4129 timeout -= (systemTime() - startTime);
4130 }
4131
4132 return OK;
4133}
4134
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004135void Camera3Device::RequestThread::requestExit() {
4136 // Call parent to set up shutdown
4137 Thread::requestExit();
4138 // The exit from any possible waits
4139 mDoPauseSignal.signal();
4140 mRequestSignal.signal();
Shuzhen Wang686f6442017-06-20 16:16:04 -07004141
4142 mRequestLatency.log("ProcessCaptureRequest latency histogram");
4143 mRequestLatency.reset();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004144}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004145
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004146void Camera3Device::RequestThread::checkAndStopRepeatingRequest() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004147 ATRACE_CALL();
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07004148 bool surfaceAbandoned = false;
4149 int64_t lastFrameNumber = 0;
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004150 sp<NotificationListener> listener;
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07004151 {
4152 Mutex::Autolock l(mRequestLock);
4153 // Check all streams needed by repeating requests are still valid. Otherwise, stop
4154 // repeating requests.
4155 for (const auto& request : mRepeatingRequests) {
4156 for (const auto& s : request->mOutputStreams) {
4157 if (s->isAbandoned()) {
4158 surfaceAbandoned = true;
4159 clearRepeatingRequestsLocked(&lastFrameNumber);
4160 break;
4161 }
4162 }
4163 if (surfaceAbandoned) {
4164 break;
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004165 }
4166 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004167 listener = mListener.promote();
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004168 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004169
4170 if (listener != NULL && surfaceAbandoned) {
4171 listener->notifyRepeatingRequestError(lastFrameNumber);
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07004172 }
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004173}
4174
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004175bool Camera3Device::RequestThread::sendRequestsBatch() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004176 ATRACE_CALL();
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004177 status_t res;
4178 size_t batchSize = mNextRequests.size();
Emilian Peevf4816702020-04-03 15:44:51 -07004179 std::vector<camera_capture_request_t*> requests(batchSize);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004180 uint32_t numRequestProcessed = 0;
4181 for (size_t i = 0; i < batchSize; i++) {
4182 requests[i] = &mNextRequests.editItemAt(i).halRequest;
Yin-Chia Yeh885691c2018-05-01 15:54:24 -07004183 ATRACE_ASYNC_BEGIN("frame capture", mNextRequests[i].halRequest.frame_number);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004184 }
4185
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004186 res = mInterface->processBatchCaptureRequests(requests, &numRequestProcessed);
4187
4188 bool triggerRemoveFailed = false;
4189 NextRequest& triggerFailedRequest = mNextRequests.editItemAt(0);
4190 for (size_t i = 0; i < numRequestProcessed; i++) {
4191 NextRequest& nextRequest = mNextRequests.editItemAt(i);
4192 nextRequest.submitted = true;
4193
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004194 updateNextRequest(nextRequest);
Emilian Peevaebbe412018-01-15 13:53:24 +00004195
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004196 if (!triggerRemoveFailed) {
4197 // Remove any previously queued triggers (after unlock)
4198 status_t removeTriggerRes = removeTriggers(mPrevRequest);
4199 if (removeTriggerRes != OK) {
4200 triggerRemoveFailed = true;
4201 triggerFailedRequest = nextRequest;
4202 }
4203 }
4204 }
4205
4206 if (triggerRemoveFailed) {
4207 SET_ERR("RequestThread: Unable to remove triggers "
4208 "(capture request %d, HAL device: %s (%d)",
4209 triggerFailedRequest.halRequest.frame_number, strerror(-res), res);
4210 cleanUpFailedRequests(/*sendRequestError*/ false);
4211 return false;
4212 }
4213
4214 if (res != OK) {
4215 // Should only get a failure here for malformed requests or device-level
4216 // errors, so consider all errors fatal. Bad metadata failures should
4217 // come through notify.
4218 SET_ERR("RequestThread: Unable to submit capture request %d to HAL device: %s (%d)",
4219 mNextRequests[numRequestProcessed].halRequest.frame_number,
4220 strerror(-res), res);
4221 cleanUpFailedRequests(/*sendRequestError*/ false);
4222 return false;
4223 }
4224 return true;
4225}
4226
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07004227nsecs_t Camera3Device::RequestThread::calculateMaxExpectedDuration(const camera_metadata_t *request) {
4228 nsecs_t maxExpectedDuration = kDefaultExpectedDuration;
4229 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
4230 find_camera_metadata_ro_entry(request,
4231 ANDROID_CONTROL_AE_MODE,
4232 &e);
4233 if (e.count == 0) return maxExpectedDuration;
4234
4235 switch (e.data.u8[0]) {
4236 case ANDROID_CONTROL_AE_MODE_OFF:
4237 find_camera_metadata_ro_entry(request,
4238 ANDROID_SENSOR_EXPOSURE_TIME,
4239 &e);
4240 if (e.count > 0) {
4241 maxExpectedDuration = e.data.i64[0];
4242 }
4243 find_camera_metadata_ro_entry(request,
4244 ANDROID_SENSOR_FRAME_DURATION,
4245 &e);
4246 if (e.count > 0) {
4247 maxExpectedDuration = std::max(e.data.i64[0], maxExpectedDuration);
4248 }
4249 break;
4250 default:
4251 find_camera_metadata_ro_entry(request,
4252 ANDROID_CONTROL_AE_TARGET_FPS_RANGE,
4253 &e);
4254 if (e.count > 1) {
4255 maxExpectedDuration = 1e9 / e.data.u8[0];
4256 }
4257 break;
4258 }
4259
4260 return maxExpectedDuration;
4261}
4262
Emilian Peeva14b4dd2018-05-15 11:00:31 +01004263bool Camera3Device::RequestThread::skipHFRTargetFPSUpdate(int32_t tag,
4264 const camera_metadata_ro_entry_t& newEntry, const camera_metadata_entry_t& currentEntry) {
4265 if (mConstrainedMode && (ANDROID_CONTROL_AE_TARGET_FPS_RANGE == tag) &&
4266 (newEntry.count == currentEntry.count) && (currentEntry.count == 2) &&
4267 (currentEntry.data.i32[1] == newEntry.data.i32[1])) {
4268 return true;
4269 }
4270
4271 return false;
4272}
4273
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004274void Camera3Device::RequestThread::updateNextRequest(NextRequest& nextRequest) {
4275 // Update the latest request sent to HAL
4276 if (nextRequest.halRequest.settings != NULL) { // Don't update if they were unchanged
4277 Mutex::Autolock al(mLatestRequestMutex);
4278
4279 camera_metadata_t* cloned = clone_camera_metadata(nextRequest.halRequest.settings);
4280 mLatestRequest.acquire(cloned);
4281
4282 mLatestPhysicalRequest.clear();
4283 for (uint32_t i = 0; i < nextRequest.halRequest.num_physcam_settings; i++) {
4284 cloned = clone_camera_metadata(nextRequest.halRequest.physcam_settings[i]);
4285 mLatestPhysicalRequest.emplace(nextRequest.halRequest.physcam_id[i],
4286 CameraMetadata(cloned));
4287 }
4288
4289 sp<Camera3Device> parent = mParent.promote();
4290 if (parent != NULL) {
4291 parent->monitorMetadata(TagMonitor::REQUEST,
4292 nextRequest.halRequest.frame_number,
4293 0, mLatestRequest, mLatestPhysicalRequest);
4294 }
4295 }
4296
4297 if (nextRequest.halRequest.settings != NULL) {
4298 nextRequest.captureRequest->mSettingsList.begin()->metadata.unlock(
4299 nextRequest.halRequest.settings);
4300 }
4301
4302 cleanupPhysicalSettings(nextRequest.captureRequest, &nextRequest.halRequest);
4303}
4304
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004305bool Camera3Device::RequestThread::updateSessionParameters(const CameraMetadata& settings) {
4306 ATRACE_CALL();
4307 bool updatesDetected = false;
4308
Emilian Peev4ec17882019-01-24 17:16:58 -08004309 CameraMetadata updatedParams(mLatestSessionParams);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004310 for (auto tag : mSessionParamKeys) {
4311 camera_metadata_ro_entry entry = settings.find(tag);
Emilian Peev4ec17882019-01-24 17:16:58 -08004312 camera_metadata_entry lastEntry = updatedParams.find(tag);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004313
4314 if (entry.count > 0) {
4315 bool isDifferent = false;
4316 if (lastEntry.count > 0) {
4317 // Have a last value, compare to see if changed
4318 if (lastEntry.type == entry.type &&
4319 lastEntry.count == entry.count) {
4320 // Same type and count, compare values
4321 size_t bytesPerValue = camera_metadata_type_size[lastEntry.type];
4322 size_t entryBytes = bytesPerValue * lastEntry.count;
4323 int cmp = memcmp(entry.data.u8, lastEntry.data.u8, entryBytes);
4324 if (cmp != 0) {
4325 isDifferent = true;
4326 }
4327 } else {
4328 // Count or type has changed
4329 isDifferent = true;
4330 }
4331 } else {
4332 // No last entry, so always consider to be different
4333 isDifferent = true;
4334 }
4335
4336 if (isDifferent) {
4337 ALOGV("%s: Session parameter tag id %d changed", __FUNCTION__, tag);
Emilian Peeva14b4dd2018-05-15 11:00:31 +01004338 if (!skipHFRTargetFPSUpdate(tag, entry, lastEntry)) {
4339 updatesDetected = true;
4340 }
Emilian Peev4ec17882019-01-24 17:16:58 -08004341 updatedParams.update(entry);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004342 }
4343 } else if (lastEntry.count > 0) {
4344 // Value has been removed
4345 ALOGV("%s: Session parameter tag id %d removed", __FUNCTION__, tag);
Emilian Peev4ec17882019-01-24 17:16:58 -08004346 updatedParams.erase(tag);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004347 updatesDetected = true;
4348 }
4349 }
4350
Emilian Peev4ec17882019-01-24 17:16:58 -08004351 bool reconfigureRequired;
4352 if (updatesDetected) {
4353 reconfigureRequired = mInterface->isReconfigurationRequired(mLatestSessionParams,
4354 updatedParams);
4355 mLatestSessionParams = updatedParams;
4356 } else {
4357 reconfigureRequired = false;
4358 }
4359
4360 return reconfigureRequired;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004361}
4362
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004363bool Camera3Device::RequestThread::threadLoop() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004364 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004365 status_t res;
Jayant Chowdhary37eca242019-11-18 08:55:56 -08004366 // Any function called from threadLoop() must not hold mInterfaceLock since
4367 // it could lead to deadlocks (disconnect() -> hold mInterfaceMutex -> wait for request thread
4368 // to finish -> request thread waits on mInterfaceMutex) http://b/143513518
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004369
4370 // Handle paused state.
4371 if (waitIfPaused()) {
4372 return true;
4373 }
4374
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004375 // Wait for the next batch of requests.
4376 waitForNextRequestBatch();
4377 if (mNextRequests.size() == 0) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004378 return true;
4379 }
4380
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004381 // Get the latest request ID, if any
4382 int latestRequestId;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004383 camera_metadata_entry_t requestIdEntry = mNextRequests[mNextRequests.size() - 1].
Emilian Peevaebbe412018-01-15 13:53:24 +00004384 captureRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_ID);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004385 if (requestIdEntry.count > 0) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004386 latestRequestId = requestIdEntry.data.i32[0];
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004387 } else {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004388 ALOGW("%s: Did not have android.request.id set in the request.", __FUNCTION__);
4389 latestRequestId = NAME_NOT_FOUND;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004390 }
4391
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004392 // 'mNextRequests' will at this point contain either a set of HFR batched requests
4393 // or a single request from streaming or burst. In either case the first element
4394 // should contain the latest camera settings that we need to check for any session
4395 // parameter updates.
Emilian Peevaebbe412018-01-15 13:53:24 +00004396 if (updateSessionParameters(mNextRequests[0].captureRequest->mSettingsList.begin()->metadata)) {
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004397 res = OK;
4398
4399 //Input stream buffers are already acquired at this point so an input stream
4400 //will not be able to move to idle state unless we force it.
4401 if (mNextRequests[0].captureRequest->mInputStream != nullptr) {
4402 res = mNextRequests[0].captureRequest->mInputStream->forceToIdle();
4403 if (res != OK) {
4404 ALOGE("%s: Failed to force idle input stream: %d", __FUNCTION__, res);
4405 cleanUpFailedRequests(/*sendRequestError*/ false);
4406 return false;
4407 }
4408 }
4409
4410 if (res == OK) {
Emilian Peev3bead5f2020-05-28 17:29:08 -07004411 sp<Camera3Device> parent = mParent.promote();
4412 if (parent != nullptr) {
4413 mReconfigured |= parent->reconfigureCamera(mLatestSessionParams, mStatusId);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004414 }
Emilian Peev3bead5f2020-05-28 17:29:08 -07004415 setPaused(false);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004416
4417 if (mNextRequests[0].captureRequest->mInputStream != nullptr) {
4418 mNextRequests[0].captureRequest->mInputStream->restoreConfiguredState();
4419 if (res != OK) {
4420 ALOGE("%s: Failed to restore configured input stream: %d", __FUNCTION__, res);
4421 cleanUpFailedRequests(/*sendRequestError*/ false);
4422 return false;
4423 }
4424 }
4425 }
4426 }
4427
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004428 // Prepare a batch of HAL requests and output buffers.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004429 res = prepareHalRequests();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004430 if (res == TIMED_OUT) {
4431 // Not a fatal error if getting output buffers time out.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004432 cleanUpFailedRequests(/*sendRequestError*/ true);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004433 // Check if any stream is abandoned.
4434 checkAndStopRepeatingRequest();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004435 return true;
4436 } else if (res != OK) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004437 cleanUpFailedRequests(/*sendRequestError*/ false);
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004438 return false;
4439 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004440
Zhijun Hecc27e112013-10-03 16:12:43 -07004441 // Inform waitUntilRequestProcessed thread of a new request ID
4442 {
4443 Mutex::Autolock al(mLatestRequestMutex);
4444
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004445 mLatestRequestId = latestRequestId;
Zhijun Hecc27e112013-10-03 16:12:43 -07004446 mLatestRequestSignal.signal();
4447 }
4448
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004449 // Submit a batch of requests to HAL.
4450 // Use flush lock only when submitting multilple requests in a batch.
4451 // TODO: The problem with flush lock is flush() will be blocked by process_capture_request()
4452 // which may take a long time to finish so synchronizing flush() and
4453 // process_capture_request() defeats the purpose of cancelling requests ASAP with flush().
4454 // For now, only synchronize for high speed recording and we should figure something out for
4455 // removing the synchronization.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004456 bool useFlushLock = mNextRequests.size() > 1;
Eino-Ville Talvala17a61ad2013-06-03 16:53:32 -07004457
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004458 if (useFlushLock) {
4459 mFlushLock.lock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004460 }
4461
Zhijun Hef0645c12016-08-02 00:58:11 -07004462 ALOGVV("%s: %d: submitting %zu requests in a batch.", __FUNCTION__, __LINE__,
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004463 mNextRequests.size());
Igor Murashkin1e479c02013-09-06 16:55:14 -07004464
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08004465 sp<Camera3Device> parent = mParent.promote();
4466 if (parent != nullptr) {
4467 parent->mRequestBufferSM.onSubmittingRequest();
4468 }
4469
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004470 bool submitRequestSuccess = false;
Shuzhen Wang686f6442017-06-20 16:16:04 -07004471 nsecs_t tRequestStart = systemTime(SYSTEM_TIME_MONOTONIC);
Yin-Chia Yeh11648852019-05-16 10:42:54 -07004472 submitRequestSuccess = sendRequestsBatch();
4473
Shuzhen Wang686f6442017-06-20 16:16:04 -07004474 nsecs_t tRequestEnd = systemTime(SYSTEM_TIME_MONOTONIC);
4475 mRequestLatency.add(tRequestStart, tRequestEnd);
Igor Murashkin1e479c02013-09-06 16:55:14 -07004476
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004477 if (useFlushLock) {
4478 mFlushLock.unlock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004479 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004480
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004481 // Unset as current request
4482 {
4483 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004484 mNextRequests.clear();
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004485 }
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004486 mRequestSubmittedSignal.signal();
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004487
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004488 return submitRequestSuccess;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004489}
4490
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004491status_t Camera3Device::RequestThread::prepareHalRequests() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004492 ATRACE_CALL();
4493
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07004494 bool batchedRequest = mNextRequests[0].captureRequest->mBatchSize > 1;
Shuzhen Wang4a472662017-02-26 23:29:04 -08004495 for (size_t i = 0; i < mNextRequests.size(); i++) {
4496 auto& nextRequest = mNextRequests.editItemAt(i);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004497 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
Emilian Peevf4816702020-04-03 15:44:51 -07004498 camera_capture_request_t* halRequest = &nextRequest.halRequest;
4499 Vector<camera_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004500
4501 // Prepare a request to HAL
4502 halRequest->frame_number = captureRequest->mResultExtras.frameNumber;
4503
4504 // Insert any queued triggers (before metadata is locked)
4505 status_t res = insertTriggers(captureRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004506 if (res < 0) {
4507 SET_ERR("RequestThread: Unable to insert triggers "
4508 "(capture request %d, HAL device: %s (%d)",
4509 halRequest->frame_number, strerror(-res), res);
4510 return INVALID_OPERATION;
4511 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07004512
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004513 int triggerCount = res;
4514 bool triggersMixedIn = (triggerCount > 0 || mPrevTriggers > 0);
4515 mPrevTriggers = triggerCount;
4516
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004517 bool rotateAndCropChanged = overrideAutoRotateAndCrop(captureRequest);
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004518 bool testPatternChanged = overrideTestPattern(captureRequest);
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004519
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004520 // If the request is the same as last, or we had triggers now or last time or
4521 // changing overrides this time
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004522 bool newRequest =
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004523 (mPrevRequest != captureRequest || triggersMixedIn ||
4524 rotateAndCropChanged || testPatternChanged) &&
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07004525 // Request settings are all the same within one batch, so only treat the first
4526 // request in a batch as new
Zhijun He54c36822018-07-18 09:33:39 -07004527 !(batchedRequest && i > 0);
Emilian Peev00420d22018-02-05 21:33:13 +00004528 if (newRequest) {
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08004529 std::set<std::string> cameraIdsWithZoom;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004530 /**
4531 * HAL workaround:
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004532 * Insert a fake trigger ID if a trigger is set but no trigger ID is
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004533 */
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004534 res = addFakeTriggerIds(captureRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004535 if (res != OK) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004536 SET_ERR("RequestThread: Unable to insert fake trigger IDs "
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004537 "(capture request %d, HAL device: %s (%d)",
4538 halRequest->frame_number, strerror(-res), res);
4539 return INVALID_OPERATION;
4540 }
4541
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07004542 {
4543 // Correct metadata regions for distortion correction if enabled
4544 sp<Camera3Device> parent = mParent.promote();
4545 if (parent != nullptr) {
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -07004546 List<PhysicalCameraSettings>::iterator it;
4547 for (it = captureRequest->mSettingsList.begin();
4548 it != captureRequest->mSettingsList.end(); it++) {
4549 if (parent->mDistortionMappers.find(it->cameraId) ==
4550 parent->mDistortionMappers.end()) {
4551 continue;
4552 }
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07004553
4554 if (!captureRequest->mDistortionCorrectionUpdated) {
4555 res = parent->mDistortionMappers[it->cameraId].correctCaptureRequest(
4556 &(it->metadata));
4557 if (res != OK) {
4558 SET_ERR("RequestThread: Unable to correct capture requests "
4559 "for lens distortion for request %d: %s (%d)",
4560 halRequest->frame_number, strerror(-res), res);
4561 return INVALID_OPERATION;
4562 }
4563 captureRequest->mDistortionCorrectionUpdated = true;
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -07004564 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07004565 }
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08004566
4567 for (it = captureRequest->mSettingsList.begin();
4568 it != captureRequest->mSettingsList.end(); it++) {
4569 if (parent->mZoomRatioMappers.find(it->cameraId) ==
4570 parent->mZoomRatioMappers.end()) {
4571 continue;
4572 }
4573
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07004574 if (!captureRequest->mZoomRatioIs1x) {
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08004575 cameraIdsWithZoom.insert(it->cameraId);
4576 }
4577
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07004578 if (!captureRequest->mZoomRatioUpdated) {
4579 res = parent->mZoomRatioMappers[it->cameraId].updateCaptureRequest(
4580 &(it->metadata));
4581 if (res != OK) {
4582 SET_ERR("RequestThread: Unable to correct capture requests "
4583 "for zoom ratio for request %d: %s (%d)",
4584 halRequest->frame_number, strerror(-res), res);
4585 return INVALID_OPERATION;
4586 }
4587 captureRequest->mZoomRatioUpdated = true;
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08004588 }
4589 }
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07004590 if (captureRequest->mRotateAndCropAuto &&
4591 !captureRequest->mRotationAndCropUpdated) {
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004592 for (it = captureRequest->mSettingsList.begin();
4593 it != captureRequest->mSettingsList.end(); it++) {
4594 auto mapper = parent->mRotateAndCropMappers.find(it->cameraId);
4595 if (mapper != parent->mRotateAndCropMappers.end()) {
4596 res = mapper->second.updateCaptureRequest(&(it->metadata));
4597 if (res != OK) {
4598 SET_ERR("RequestThread: Unable to correct capture requests "
4599 "for rotate-and-crop for request %d: %s (%d)",
4600 halRequest->frame_number, strerror(-res), res);
4601 return INVALID_OPERATION;
4602 }
4603 }
4604 }
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07004605 captureRequest->mRotationAndCropUpdated = true;
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004606 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07004607 }
4608 }
4609
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004610 /**
4611 * The request should be presorted so accesses in HAL
4612 * are O(logn). Sidenote, sorting a sorted metadata is nop.
4613 */
Emilian Peevaebbe412018-01-15 13:53:24 +00004614 captureRequest->mSettingsList.begin()->metadata.sort();
4615 halRequest->settings = captureRequest->mSettingsList.begin()->metadata.getAndLock();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004616 mPrevRequest = captureRequest;
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08004617 mPrevCameraIdsWithZoom = cameraIdsWithZoom;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004618 ALOGVV("%s: Request settings are NEW", __FUNCTION__);
4619
4620 IF_ALOGV() {
4621 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
4622 find_camera_metadata_ro_entry(
4623 halRequest->settings,
4624 ANDROID_CONTROL_AF_TRIGGER,
4625 &e
4626 );
4627 if (e.count > 0) {
4628 ALOGV("%s: Request (frame num %d) had AF trigger 0x%x",
4629 __FUNCTION__,
4630 halRequest->frame_number,
4631 e.data.u8[0]);
4632 }
4633 }
4634 } else {
4635 // leave request.settings NULL to indicate 'reuse latest given'
4636 ALOGVV("%s: Request settings are REUSED",
4637 __FUNCTION__);
4638 }
4639
Emilian Peevaebbe412018-01-15 13:53:24 +00004640 if (captureRequest->mSettingsList.size() > 1) {
4641 halRequest->num_physcam_settings = captureRequest->mSettingsList.size() - 1;
4642 halRequest->physcam_id = new const char* [halRequest->num_physcam_settings];
Emilian Peev00420d22018-02-05 21:33:13 +00004643 if (newRequest) {
4644 halRequest->physcam_settings =
4645 new const camera_metadata* [halRequest->num_physcam_settings];
4646 } else {
4647 halRequest->physcam_settings = nullptr;
4648 }
Emilian Peevaebbe412018-01-15 13:53:24 +00004649 auto it = ++captureRequest->mSettingsList.begin();
4650 size_t i = 0;
4651 for (; it != captureRequest->mSettingsList.end(); it++, i++) {
4652 halRequest->physcam_id[i] = it->cameraId.c_str();
Emilian Peev00420d22018-02-05 21:33:13 +00004653 if (newRequest) {
4654 it->metadata.sort();
4655 halRequest->physcam_settings[i] = it->metadata.getAndLock();
4656 }
Emilian Peevaebbe412018-01-15 13:53:24 +00004657 }
4658 }
4659
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004660 uint32_t totalNumBuffers = 0;
4661
4662 // Fill in buffers
4663 if (captureRequest->mInputStream != NULL) {
4664 halRequest->input_buffer = &captureRequest->mInputBuffer;
4665 totalNumBuffers += 1;
4666 } else {
4667 halRequest->input_buffer = NULL;
4668 }
4669
Emilian Peevf4816702020-04-03 15:44:51 -07004670 outputBuffers->insertAt(camera_stream_buffer_t(), 0,
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004671 captureRequest->mOutputStreams.size());
4672 halRequest->output_buffers = outputBuffers->array();
Shuzhen Wang5c22c152017-12-31 17:12:25 -08004673 std::set<String8> requestedPhysicalCameras;
Yin-Chia Yehb3a80b12018-09-04 12:13:05 -07004674
4675 sp<Camera3Device> parent = mParent.promote();
4676 if (parent == NULL) {
4677 // Should not happen, and nowhere to send errors to, so just log it
4678 CLOGE("RequestThread: Parent is gone");
4679 return INVALID_OPERATION;
4680 }
4681 nsecs_t waitDuration = kBaseGetBufferWait + parent->getExpectedInFlightDuration();
4682
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07004683 SurfaceMap uniqueSurfaceIdMap;
Shuzhen Wang4a472662017-02-26 23:29:04 -08004684 for (size_t j = 0; j < captureRequest->mOutputStreams.size(); j++) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07004685 sp<Camera3OutputStreamInterface> outputStream =
4686 captureRequest->mOutputStreams.editItemAt(j);
4687 int streamId = outputStream->getId();
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07004688
4689 // Prepare video buffers for high speed recording on the first video request.
4690 if (mPrepareVideoStream && outputStream->isVideoStream()) {
4691 // Only try to prepare video stream on the first video request.
4692 mPrepareVideoStream = false;
4693
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07004694 res = outputStream->startPrepare(Camera3StreamInterface::ALLOCATE_PIPELINE_MAX,
4695 false /*blockRequest*/);
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07004696 while (res == NOT_ENOUGH_DATA) {
4697 res = outputStream->prepareNextBuffer();
4698 }
4699 if (res != OK) {
4700 ALOGW("%s: Preparing video buffers for high speed failed: %s (%d)",
4701 __FUNCTION__, strerror(-res), res);
4702 outputStream->cancelPrepare();
4703 }
4704 }
4705
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07004706 std::vector<size_t> uniqueSurfaceIds;
4707 res = outputStream->getUniqueSurfaceIds(
4708 captureRequest->mOutputSurfaces[streamId],
4709 &uniqueSurfaceIds);
4710 // INVALID_OPERATION is normal output for streams not supporting surfaceIds
4711 if (res != OK && res != INVALID_OPERATION) {
4712 ALOGE("%s: failed to query stream %d unique surface IDs",
4713 __FUNCTION__, streamId);
4714 return res;
4715 }
4716 if (res == OK) {
4717 uniqueSurfaceIdMap.insert({streamId, std::move(uniqueSurfaceIds)});
4718 }
4719
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004720 if (mUseHalBufManager) {
Yin-Chia Yeh110342b2018-11-19 11:47:46 -08004721 if (outputStream->isAbandoned()) {
Yin-Chia Yeha1b56c82019-03-27 15:50:39 -07004722 ALOGV("%s: stream %d is abandoned, skipping request", __FUNCTION__, streamId);
Yin-Chia Yeh110342b2018-11-19 11:47:46 -08004723 return TIMED_OUT;
4724 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004725 // HAL will request buffer through requestStreamBuffer API
Emilian Peevf4816702020-04-03 15:44:51 -07004726 camera_stream_buffer_t& buffer = outputBuffers->editItemAt(j);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004727 buffer.stream = outputStream->asHalStream();
4728 buffer.buffer = nullptr;
Emilian Peevf4816702020-04-03 15:44:51 -07004729 buffer.status = CAMERA_BUFFER_STATUS_OK;
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004730 buffer.acquire_fence = -1;
4731 buffer.release_fence = -1;
Emilian Peevf0348ae2021-01-13 13:39:45 -08004732 // Mark the output stream as unpreparable to block clients from calling
4733 // 'prepare' after this request reaches CameraHal and before the respective
4734 // buffers are requested.
4735 outputStream->markUnpreparable();
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004736 } else {
4737 res = outputStream->getBuffer(&outputBuffers->editItemAt(j),
4738 waitDuration,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07004739 captureRequest->mOutputSurfaces[streamId]);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004740 if (res != OK) {
4741 // Can't get output buffer from gralloc queue - this could be due to
4742 // abandoned queue or other consumer misbehavior, so not a fatal
4743 // error
Yin-Chia Yeha1b56c82019-03-27 15:50:39 -07004744 ALOGV("RequestThread: Can't get output buffer, skipping request:"
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004745 " %s (%d)", strerror(-res), res);
4746
4747 return TIMED_OUT;
4748 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004749 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08004750
4751 {
4752 sp<Camera3Device> parent = mParent.promote();
4753 if (parent != nullptr) {
4754 const String8& streamCameraId = outputStream->getPhysicalCameraId();
4755 for (const auto& settings : captureRequest->mSettingsList) {
4756 if ((streamCameraId.isEmpty() &&
4757 parent->getId() == settings.cameraId.c_str()) ||
4758 streamCameraId == settings.cameraId.c_str()) {
4759 outputStream->fireBufferRequestForFrameNumber(
4760 captureRequest->mResultExtras.frameNumber,
4761 settings.metadata);
4762 }
4763 }
4764 }
4765 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07004766
Shuzhen Wang5c22c152017-12-31 17:12:25 -08004767 String8 physicalCameraId = outputStream->getPhysicalCameraId();
4768
4769 if (!physicalCameraId.isEmpty()) {
4770 // Physical stream isn't supported for input request.
4771 if (halRequest->input_buffer) {
4772 CLOGE("Physical stream is not supported for input request");
4773 return INVALID_OPERATION;
4774 }
4775 requestedPhysicalCameras.insert(physicalCameraId);
4776 }
4777 halRequest->num_output_buffers++;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004778 }
4779 totalNumBuffers += halRequest->num_output_buffers;
4780
4781 // Log request in the in-flight queue
Shuzhen Wang4a472662017-02-26 23:29:04 -08004782 // If this request list is for constrained high speed recording (not
4783 // preview), and the current request is not the last one in the batch,
4784 // do not send callback to the app.
4785 bool hasCallback = true;
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07004786 if (batchedRequest && i != mNextRequests.size()-1) {
Shuzhen Wang4a472662017-02-26 23:29:04 -08004787 hasCallback = false;
4788 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01004789 bool isStillCapture = false;
Shuzhen Wang26abaf42018-08-28 15:41:20 -07004790 bool isZslCapture = false;
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08004791 const camera_metadata_t* settings = halRequest->settings;
4792 bool shouldUnlockSettings = false;
4793 if (settings == nullptr) {
4794 shouldUnlockSettings = true;
4795 settings = captureRequest->mSettingsList.begin()->metadata.getAndLock();
4796 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01004797 if (!mNextRequests[0].captureRequest->mSettingsList.begin()->metadata.isEmpty()) {
4798 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08004799 find_camera_metadata_ro_entry(settings, ANDROID_CONTROL_CAPTURE_INTENT, &e);
Emilian Peev9dd21f42018-08-03 13:39:29 +01004800 if ((e.count > 0) && (e.data.u8[0] == ANDROID_CONTROL_CAPTURE_INTENT_STILL_CAPTURE)) {
4801 isStillCapture = true;
4802 ATRACE_ASYNC_BEGIN("still capture", mNextRequests[i].halRequest.frame_number);
4803 }
Shuzhen Wang26abaf42018-08-28 15:41:20 -07004804
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08004805 find_camera_metadata_ro_entry(settings, ANDROID_CONTROL_ENABLE_ZSL, &e);
Shuzhen Wang26abaf42018-08-28 15:41:20 -07004806 if ((e.count > 0) && (e.data.u8[0] == ANDROID_CONTROL_ENABLE_ZSL_TRUE)) {
4807 isZslCapture = true;
4808 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01004809 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004810 res = parent->registerInFlight(halRequest->frame_number,
4811 totalNumBuffers, captureRequest->mResultExtras,
4812 /*hasInput*/halRequest->input_buffer != NULL,
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07004813 hasCallback,
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08004814 calculateMaxExpectedDuration(settings),
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004815 requestedPhysicalCameras, isStillCapture, isZslCapture,
4816 captureRequest->mRotateAndCropAuto, mPrevCameraIdsWithZoom,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07004817 (mUseHalBufManager) ? uniqueSurfaceIdMap :
Shuzhen Wang316781a2020-08-18 18:11:01 -07004818 SurfaceMap{}, captureRequest->mRequestTimeNs);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004819 ALOGVV("%s: registered in flight requestId = %" PRId32 ", frameNumber = %" PRId64
4820 ", burstId = %" PRId32 ".",
4821 __FUNCTION__,
4822 captureRequest->mResultExtras.requestId, captureRequest->mResultExtras.frameNumber,
4823 captureRequest->mResultExtras.burstId);
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08004824
4825 if (shouldUnlockSettings) {
4826 captureRequest->mSettingsList.begin()->metadata.unlock(settings);
4827 }
4828
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004829 if (res != OK) {
4830 SET_ERR("RequestThread: Unable to register new in-flight request:"
4831 " %s (%d)", strerror(-res), res);
4832 return INVALID_OPERATION;
4833 }
4834 }
4835
4836 return OK;
4837}
4838
Igor Murashkin1e479c02013-09-06 16:55:14 -07004839CameraMetadata Camera3Device::RequestThread::getLatestRequest() const {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004840 ATRACE_CALL();
Igor Murashkin1e479c02013-09-06 16:55:14 -07004841 Mutex::Autolock al(mLatestRequestMutex);
4842
4843 ALOGV("RequestThread::%s", __FUNCTION__);
4844
4845 return mLatestRequest;
4846}
4847
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004848bool Camera3Device::RequestThread::isStreamPending(
4849 sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004850 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004851 Mutex::Autolock l(mRequestLock);
4852
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004853 for (const auto& nextRequest : mNextRequests) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004854 if (!nextRequest.submitted) {
4855 for (const auto& s : nextRequest.captureRequest->mOutputStreams) {
4856 if (stream == s) return true;
4857 }
4858 if (stream == nextRequest.captureRequest->mInputStream) return true;
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004859 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004860 }
4861
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004862 for (const auto& request : mRequestQueue) {
4863 for (const auto& s : request->mOutputStreams) {
4864 if (stream == s) return true;
4865 }
4866 if (stream == request->mInputStream) return true;
4867 }
4868
4869 for (const auto& request : mRepeatingRequests) {
4870 for (const auto& s : request->mOutputStreams) {
4871 if (stream == s) return true;
4872 }
4873 if (stream == request->mInputStream) return true;
4874 }
4875
4876 return false;
4877}
Jianing Weicb0652e2014-03-12 18:29:36 -07004878
Emilian Peev40ead602017-09-26 15:46:36 +01004879bool Camera3Device::RequestThread::isOutputSurfacePending(int streamId, size_t surfaceId) {
4880 ATRACE_CALL();
4881 Mutex::Autolock l(mRequestLock);
4882
4883 for (const auto& nextRequest : mNextRequests) {
4884 for (const auto& s : nextRequest.captureRequest->mOutputSurfaces) {
4885 if (s.first == streamId) {
4886 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
4887 if (it != s.second.end()) {
4888 return true;
4889 }
4890 }
4891 }
4892 }
4893
4894 for (const auto& request : mRequestQueue) {
4895 for (const auto& s : request->mOutputSurfaces) {
4896 if (s.first == streamId) {
4897 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
4898 if (it != s.second.end()) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07004899 return true;
Emilian Peev40ead602017-09-26 15:46:36 +01004900 }
4901 }
4902 }
4903 }
4904
4905 for (const auto& request : mRepeatingRequests) {
4906 for (const auto& s : request->mOutputSurfaces) {
4907 if (s.first == streamId) {
4908 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
4909 if (it != s.second.end()) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07004910 return true;
Emilian Peev40ead602017-09-26 15:46:36 +01004911 }
4912 }
4913 }
4914 }
4915
4916 return false;
4917}
4918
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004919void Camera3Device::RequestThread::signalPipelineDrain(const std::vector<int>& streamIds) {
4920 if (!mUseHalBufManager) {
4921 ALOGE("%s called for camera device not supporting HAL buffer management", __FUNCTION__);
4922 return;
4923 }
4924
4925 Mutex::Autolock pl(mPauseLock);
4926 if (mPaused) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07004927 mInterface->signalPipelineDrain(streamIds);
4928 return;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004929 }
4930 // If request thread is still busy, wait until paused then notify HAL
4931 mNotifyPipelineDrain = true;
4932 mStreamIdsToBeDrained = streamIds;
4933}
4934
Yin-Chia Yehe52b8fa2020-07-28 00:17:58 -07004935void Camera3Device::RequestThread::resetPipelineDrain() {
4936 Mutex::Autolock pl(mPauseLock);
4937 mNotifyPipelineDrain = false;
4938 mStreamIdsToBeDrained.clear();
4939}
4940
Emilian Peevc0fe54c2020-03-11 14:05:07 -07004941void Camera3Device::RequestThread::clearPreviousRequest() {
4942 Mutex::Autolock l(mRequestLock);
4943 mPrevRequest.clear();
4944}
4945
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004946status_t Camera3Device::RequestThread::switchToOffline(
4947 const std::vector<int32_t>& streamsToKeep,
4948 /*out*/hardware::camera::device::V3_6::CameraOfflineSessionInfo* offlineSessionInfo,
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004949 /*out*/sp<hardware::camera::device::V3_6::ICameraOfflineSession>* offlineSession,
4950 /*out*/camera3::BufferRecords* bufferRecords) {
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004951 Mutex::Autolock l(mRequestLock);
4952 clearRepeatingRequestsLocked(/*lastFrameNumber*/nullptr);
4953
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004954 // Wait until request thread is fully stopped
4955 // TBD: check if request thread is being paused by other APIs (shouldn't be)
4956
4957 // We could also check for mRepeatingRequests.empty(), but the API interface
4958 // is serialized by Camera3Device::mInterfaceLock so no one should be able to submit any
4959 // new requests during the call; hence skip that check.
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004960 bool queueEmpty = mNextRequests.empty() && mRequestQueue.empty();
4961 while (!queueEmpty) {
4962 status_t res = mRequestSubmittedSignal.waitRelative(mRequestLock, kRequestSubmitTimeout);
4963 if (res == TIMED_OUT) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004964 ALOGE("%s: request thread failed to submit one request within timeout!", __FUNCTION__);
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004965 return res;
4966 } else if (res != OK) {
4967 ALOGE("%s: request thread failed to submit a request: %s (%d)!",
4968 __FUNCTION__, strerror(-res), res);
4969 return res;
4970 }
4971 queueEmpty = mNextRequests.empty() && mRequestQueue.empty();
4972 }
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004973
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004974 return mInterface->switchToOffline(
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004975 streamsToKeep, offlineSessionInfo, offlineSession, bufferRecords);
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004976}
4977
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004978status_t Camera3Device::RequestThread::setRotateAndCropAutoBehavior(
4979 camera_metadata_enum_android_scaler_rotate_and_crop_t rotateAndCropValue) {
4980 ATRACE_CALL();
4981 Mutex::Autolock l(mTriggerMutex);
4982 if (rotateAndCropValue == ANDROID_SCALER_ROTATE_AND_CROP_AUTO) {
4983 return BAD_VALUE;
4984 }
4985 mRotateAndCropOverride = rotateAndCropValue;
4986 return OK;
4987}
4988
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004989status_t Camera3Device::RequestThread::setCameraMute(bool enabled) {
4990 ATRACE_CALL();
4991 Mutex::Autolock l(mTriggerMutex);
4992 if (enabled != mCameraMute) {
4993 mCameraMute = enabled;
4994 mCameraMuteChanged = true;
4995 }
4996 return OK;
4997}
4998
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07004999nsecs_t Camera3Device::getExpectedInFlightDuration() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005000 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005001 std::lock_guard<std::mutex> l(mInFlightLock);
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07005002 return mExpectedInflightDuration > kMinInflightDuration ?
5003 mExpectedInflightDuration : kMinInflightDuration;
5004}
5005
Emilian Peevaebbe412018-01-15 13:53:24 +00005006void Camera3Device::RequestThread::cleanupPhysicalSettings(sp<CaptureRequest> request,
Emilian Peevf4816702020-04-03 15:44:51 -07005007 camera_capture_request_t *halRequest) {
Emilian Peevaebbe412018-01-15 13:53:24 +00005008 if ((request == nullptr) || (halRequest == nullptr)) {
5009 ALOGE("%s: Invalid request!", __FUNCTION__);
5010 return;
5011 }
5012
5013 if (halRequest->num_physcam_settings > 0) {
5014 if (halRequest->physcam_id != nullptr) {
5015 delete [] halRequest->physcam_id;
5016 halRequest->physcam_id = nullptr;
5017 }
5018 if (halRequest->physcam_settings != nullptr) {
5019 auto it = ++(request->mSettingsList.begin());
5020 size_t i = 0;
5021 for (; it != request->mSettingsList.end(); it++, i++) {
5022 it->metadata.unlock(halRequest->physcam_settings[i]);
5023 }
5024 delete [] halRequest->physcam_settings;
5025 halRequest->physcam_settings = nullptr;
5026 }
5027 }
5028}
5029
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005030void Camera3Device::RequestThread::cleanUpFailedRequests(bool sendRequestError) {
5031 if (mNextRequests.empty()) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005032 return;
5033 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005034
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005035 for (auto& nextRequest : mNextRequests) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005036 // Skip the ones that have been submitted successfully.
5037 if (nextRequest.submitted) {
5038 continue;
5039 }
5040
5041 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
Emilian Peevf4816702020-04-03 15:44:51 -07005042 camera_capture_request_t* halRequest = &nextRequest.halRequest;
5043 Vector<camera_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005044
5045 if (halRequest->settings != NULL) {
Emilian Peevaebbe412018-01-15 13:53:24 +00005046 captureRequest->mSettingsList.begin()->metadata.unlock(halRequest->settings);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005047 }
5048
Emilian Peevaebbe412018-01-15 13:53:24 +00005049 cleanupPhysicalSettings(captureRequest, halRequest);
5050
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005051 if (captureRequest->mInputStream != NULL) {
Emilian Peevf4816702020-04-03 15:44:51 -07005052 captureRequest->mInputBuffer.status = CAMERA_BUFFER_STATUS_ERROR;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005053 captureRequest->mInputStream->returnInputBuffer(captureRequest->mInputBuffer);
5054 }
5055
Yin-Chia Yeh21cb47b2019-01-18 15:08:17 -08005056 // No output buffer can be returned when using HAL buffer manager
5057 if (!mUseHalBufManager) {
5058 for (size_t i = 0; i < halRequest->num_output_buffers; i++) {
5059 //Buffers that failed processing could still have
5060 //valid acquire fence.
5061 int acquireFence = (*outputBuffers)[i].acquire_fence;
5062 if (0 <= acquireFence) {
5063 close(acquireFence);
5064 outputBuffers->editItemAt(i).acquire_fence = -1;
5065 }
Emilian Peevf4816702020-04-03 15:44:51 -07005066 outputBuffers->editItemAt(i).status = CAMERA_BUFFER_STATUS_ERROR;
Yin-Chia Yeh21cb47b2019-01-18 15:08:17 -08005067 captureRequest->mOutputStreams.editItemAt(i)->returnBuffer((*outputBuffers)[i], 0,
5068 /*timestampIncreasing*/true, std::vector<size_t> (),
5069 captureRequest->mResultExtras.frameNumber);
Emilian Peevc58cf4c2017-05-11 17:23:41 +01005070 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005071 }
5072
5073 if (sendRequestError) {
5074 Mutex::Autolock l(mRequestLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005075 sp<NotificationListener> listener = mListener.promote();
5076 if (listener != NULL) {
5077 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08005078 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005079 captureRequest->mResultExtras);
5080 }
5081 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07005082
5083 // Remove yet-to-be submitted inflight request from inflightMap
5084 {
5085 sp<Camera3Device> parent = mParent.promote();
5086 if (parent != NULL) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005087 std::lock_guard<std::mutex> l(parent->mInFlightLock);
Shuzhen Wangcadb3302016-11-04 14:17:56 -07005088 ssize_t idx = parent->mInFlightMap.indexOfKey(captureRequest->mResultExtras.frameNumber);
5089 if (idx >= 0) {
5090 ALOGV("%s: Remove inflight request from queue: frameNumber %" PRId64,
5091 __FUNCTION__, captureRequest->mResultExtras.frameNumber);
5092 parent->removeInFlightMapEntryLocked(idx);
5093 }
5094 }
5095 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005096 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07005097
5098 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005099 mNextRequests.clear();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005100}
5101
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005102void Camera3Device::RequestThread::waitForNextRequestBatch() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005103 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005104 // Optimized a bit for the simple steady-state case (single repeating
5105 // request), to avoid putting that request in the queue temporarily.
5106 Mutex::Autolock l(mRequestLock);
5107
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005108 assert(mNextRequests.empty());
5109
5110 NextRequest nextRequest;
5111 nextRequest.captureRequest = waitForNextRequestLocked();
5112 if (nextRequest.captureRequest == nullptr) {
5113 return;
5114 }
5115
Emilian Peevf4816702020-04-03 15:44:51 -07005116 nextRequest.halRequest = camera_capture_request_t();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005117 nextRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005118 mNextRequests.add(nextRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005119
5120 // Wait for additional requests
5121 const size_t batchSize = nextRequest.captureRequest->mBatchSize;
5122
5123 for (size_t i = 1; i < batchSize; i++) {
5124 NextRequest additionalRequest;
5125 additionalRequest.captureRequest = waitForNextRequestLocked();
5126 if (additionalRequest.captureRequest == nullptr) {
5127 break;
5128 }
5129
Emilian Peevf4816702020-04-03 15:44:51 -07005130 additionalRequest.halRequest = camera_capture_request_t();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005131 additionalRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005132 mNextRequests.add(additionalRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005133 }
5134
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005135 if (mNextRequests.size() < batchSize) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08005136 ALOGE("RequestThread: only get %zu out of %zu requests. Skipping requests.",
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005137 mNextRequests.size(), batchSize);
5138 cleanUpFailedRequests(/*sendRequestError*/true);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005139 }
5140
5141 return;
5142}
5143
5144sp<Camera3Device::CaptureRequest>
5145 Camera3Device::RequestThread::waitForNextRequestLocked() {
5146 status_t res;
5147 sp<CaptureRequest> nextRequest;
5148
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005149 while (mRequestQueue.empty()) {
5150 if (!mRepeatingRequests.empty()) {
5151 // Always atomically enqueue all requests in a repeating request
5152 // list. Guarantees a complete in-sequence set of captures to
5153 // application.
5154 const RequestList &requests = mRepeatingRequests;
Shuzhen Wang316781a2020-08-18 18:11:01 -07005155 if (mFirstRepeating) {
5156 mFirstRepeating = false;
5157 } else {
5158 for (auto& request : requests) {
5159 // For repeating requests, override timestamp request using
5160 // the time a request is inserted into the request queue,
5161 // because the original repeating request will have an old
5162 // fixed timestamp.
5163 request->mRequestTimeNs = systemTime();
5164 }
5165 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005166 RequestList::const_iterator firstRequest =
5167 requests.begin();
5168 nextRequest = *firstRequest;
5169 mRequestQueue.insert(mRequestQueue.end(),
5170 ++firstRequest,
5171 requests.end());
5172 // No need to wait any longer
Jianing Weicb0652e2014-03-12 18:29:36 -07005173
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005174 mRepeatingLastFrameNumber = mFrameNumber + requests.size() - 1;
Jianing Weicb0652e2014-03-12 18:29:36 -07005175
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005176 break;
5177 }
5178
5179 res = mRequestSignal.waitRelative(mRequestLock, kRequestTimeout);
5180
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005181 if ((mRequestQueue.empty() && mRepeatingRequests.empty()) ||
5182 exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005183 Mutex::Autolock pl(mPauseLock);
5184 if (mPaused == false) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005185 ALOGV("%s: RequestThread: Going idle", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005186 mPaused = true;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07005187 if (mNotifyPipelineDrain) {
5188 mInterface->signalPipelineDrain(mStreamIdsToBeDrained);
5189 mNotifyPipelineDrain = false;
5190 mStreamIdsToBeDrained.clear();
5191 }
Yin-Chia Yehc300a072019-02-13 14:56:57 -08005192 // Let the tracker know
5193 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5194 if (statusTracker != 0) {
5195 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
5196 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005197 sp<Camera3Device> parent = mParent.promote();
5198 if (parent != nullptr) {
5199 parent->mRequestBufferSM.onRequestThreadPaused();
5200 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005201 }
5202 // Stop waiting for now and let thread management happen
5203 return NULL;
5204 }
5205 }
5206
5207 if (nextRequest == NULL) {
5208 // Don't have a repeating request already in hand, so queue
5209 // must have an entry now.
5210 RequestList::iterator firstRequest =
5211 mRequestQueue.begin();
5212 nextRequest = *firstRequest;
5213 mRequestQueue.erase(firstRequest);
Shuzhen Wang9d066012016-09-30 11:30:20 -07005214 if (mRequestQueue.empty() && !nextRequest->mRepeating) {
5215 sp<NotificationListener> listener = mListener.promote();
5216 if (listener != NULL) {
5217 listener->notifyRequestQueueEmpty();
5218 }
5219 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005220 }
5221
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005222 // In case we've been unpaused by setPaused clearing mDoPause, need to
5223 // update internal pause state (capture/setRepeatingRequest unpause
5224 // directly).
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005225 Mutex::Autolock pl(mPauseLock);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005226 if (mPaused) {
5227 ALOGV("%s: RequestThread: Unpaused", __FUNCTION__);
5228 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5229 if (statusTracker != 0) {
5230 statusTracker->markComponentActive(mStatusId);
5231 }
5232 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005233 mPaused = false;
5234
5235 // Check if we've reconfigured since last time, and reset the preview
5236 // request if so. Can't use 'NULL request == repeat' across configure calls.
5237 if (mReconfigured) {
5238 mPrevRequest.clear();
5239 mReconfigured = false;
5240 }
5241
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005242 if (nextRequest != NULL) {
5243 nextRequest->mResultExtras.frameNumber = mFrameNumber++;
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07005244 nextRequest->mResultExtras.afTriggerId = mCurrentAfTriggerId;
5245 nextRequest->mResultExtras.precaptureTriggerId = mCurrentPreCaptureTriggerId;
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07005246
5247 // Since RequestThread::clear() removes buffers from the input stream,
5248 // get the right buffer here before unlocking mRequestLock
5249 if (nextRequest->mInputStream != NULL) {
5250 res = nextRequest->mInputStream->getInputBuffer(&nextRequest->mInputBuffer);
5251 if (res != OK) {
5252 // Can't get input buffer from gralloc queue - this could be due to
5253 // disconnected queue or other producer misbehavior, so not a fatal
5254 // error
5255 ALOGE("%s: Can't get input buffer, skipping request:"
5256 " %s (%d)", __FUNCTION__, strerror(-res), res);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005257
5258 sp<NotificationListener> listener = mListener.promote();
5259 if (listener != NULL) {
5260 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08005261 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07005262 nextRequest->mResultExtras);
5263 }
5264 return NULL;
5265 }
5266 }
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005267 }
Chien-Yu Chend196d612015-06-22 19:49:01 -07005268
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005269 return nextRequest;
5270}
5271
5272bool Camera3Device::RequestThread::waitIfPaused() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005273 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005274 status_t res;
5275 Mutex::Autolock l(mPauseLock);
5276 while (mDoPause) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005277 if (mPaused == false) {
5278 mPaused = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005279 ALOGV("%s: RequestThread: Paused", __FUNCTION__);
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07005280 if (mNotifyPipelineDrain) {
5281 mInterface->signalPipelineDrain(mStreamIdsToBeDrained);
5282 mNotifyPipelineDrain = false;
5283 mStreamIdsToBeDrained.clear();
5284 }
Yin-Chia Yehc300a072019-02-13 14:56:57 -08005285 // Let the tracker know
5286 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5287 if (statusTracker != 0) {
5288 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
5289 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005290 sp<Camera3Device> parent = mParent.promote();
5291 if (parent != nullptr) {
5292 parent->mRequestBufferSM.onRequestThreadPaused();
5293 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005294 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005295
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005296 res = mDoPauseSignal.waitRelative(mPauseLock, kRequestTimeout);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005297 if (res == TIMED_OUT || exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005298 return true;
5299 }
5300 }
5301 // We don't set mPaused to false here, because waitForNextRequest needs
5302 // to further manage the paused state in case of starvation.
5303 return false;
5304}
5305
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005306void Camera3Device::RequestThread::unpauseForNewRequests() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005307 ATRACE_CALL();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005308 // With work to do, mark thread as unpaused.
5309 // If paused by request (setPaused), don't resume, to avoid
5310 // extra signaling/waiting overhead to waitUntilPaused
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005311 mRequestSignal.signal();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005312 Mutex::Autolock p(mPauseLock);
5313 if (!mDoPause) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005314 ALOGV("%s: RequestThread: Going active", __FUNCTION__);
5315 if (mPaused) {
5316 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5317 if (statusTracker != 0) {
5318 statusTracker->markComponentActive(mStatusId);
5319 }
5320 }
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005321 mPaused = false;
5322 }
5323}
5324
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07005325void Camera3Device::RequestThread::setErrorState(const char *fmt, ...) {
5326 sp<Camera3Device> parent = mParent.promote();
5327 if (parent != NULL) {
5328 va_list args;
5329 va_start(args, fmt);
5330
5331 parent->setErrorStateV(fmt, args);
5332
5333 va_end(args);
5334 }
5335}
5336
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005337status_t Camera3Device::RequestThread::insertTriggers(
5338 const sp<CaptureRequest> &request) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005339 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005340 Mutex::Autolock al(mTriggerMutex);
5341
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07005342 sp<Camera3Device> parent = mParent.promote();
5343 if (parent == NULL) {
5344 CLOGE("RequestThread: Parent is gone");
5345 return DEAD_OBJECT;
5346 }
5347
Emilian Peevaebbe412018-01-15 13:53:24 +00005348 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005349 size_t count = mTriggerMap.size();
5350
5351 for (size_t i = 0; i < count; ++i) {
5352 RequestTrigger trigger = mTriggerMap.valueAt(i);
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005353 uint32_t tag = trigger.metadataTag;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07005354
5355 if (tag == ANDROID_CONTROL_AF_TRIGGER_ID || tag == ANDROID_CONTROL_AE_PRECAPTURE_ID) {
5356 bool isAeTrigger = (trigger.metadataTag == ANDROID_CONTROL_AE_PRECAPTURE_ID);
5357 uint32_t triggerId = static_cast<uint32_t>(trigger.entryValue);
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07005358 if (isAeTrigger) {
5359 request->mResultExtras.precaptureTriggerId = triggerId;
5360 mCurrentPreCaptureTriggerId = triggerId;
5361 } else {
5362 request->mResultExtras.afTriggerId = triggerId;
5363 mCurrentAfTriggerId = triggerId;
5364 }
Emilian Peev7e25e5e2017-04-07 15:48:49 +01005365 continue;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07005366 }
5367
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005368 camera_metadata_entry entry = metadata.find(tag);
5369
5370 if (entry.count > 0) {
5371 /**
5372 * Already has an entry for this trigger in the request.
5373 * Rewrite it with our requested trigger value.
5374 */
5375 RequestTrigger oldTrigger = trigger;
5376
5377 oldTrigger.entryValue = entry.data.u8[0];
5378
5379 mTriggerReplacedMap.add(tag, oldTrigger);
5380 } else {
5381 /**
5382 * More typical, no trigger entry, so we just add it
5383 */
5384 mTriggerRemovedMap.add(tag, trigger);
5385 }
5386
5387 status_t res;
5388
5389 switch (trigger.getTagType()) {
5390 case TYPE_BYTE: {
5391 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
5392 res = metadata.update(tag,
5393 &entryValue,
5394 /*count*/1);
5395 break;
5396 }
5397 case TYPE_INT32:
5398 res = metadata.update(tag,
5399 &trigger.entryValue,
5400 /*count*/1);
5401 break;
5402 default:
5403 ALOGE("%s: Type not supported: 0x%x",
5404 __FUNCTION__,
5405 trigger.getTagType());
5406 return INVALID_OPERATION;
5407 }
5408
5409 if (res != OK) {
5410 ALOGE("%s: Failed to update request metadata with trigger tag %s"
5411 ", value %d", __FUNCTION__, trigger.getTagName(),
5412 trigger.entryValue);
5413 return res;
5414 }
5415
5416 ALOGV("%s: Mixed in trigger %s, value %d", __FUNCTION__,
5417 trigger.getTagName(),
5418 trigger.entryValue);
5419 }
5420
5421 mTriggerMap.clear();
5422
5423 return count;
5424}
5425
5426status_t Camera3Device::RequestThread::removeTriggers(
5427 const sp<CaptureRequest> &request) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005428 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005429 Mutex::Autolock al(mTriggerMutex);
5430
Emilian Peevaebbe412018-01-15 13:53:24 +00005431 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005432
5433 /**
5434 * Replace all old entries with their old values.
5435 */
5436 for (size_t i = 0; i < mTriggerReplacedMap.size(); ++i) {
5437 RequestTrigger trigger = mTriggerReplacedMap.valueAt(i);
5438
5439 status_t res;
5440
5441 uint32_t tag = trigger.metadataTag;
5442 switch (trigger.getTagType()) {
5443 case TYPE_BYTE: {
5444 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
5445 res = metadata.update(tag,
5446 &entryValue,
5447 /*count*/1);
5448 break;
5449 }
5450 case TYPE_INT32:
5451 res = metadata.update(tag,
5452 &trigger.entryValue,
5453 /*count*/1);
5454 break;
5455 default:
5456 ALOGE("%s: Type not supported: 0x%x",
5457 __FUNCTION__,
5458 trigger.getTagType());
5459 return INVALID_OPERATION;
5460 }
5461
5462 if (res != OK) {
5463 ALOGE("%s: Failed to restore request metadata with trigger tag %s"
5464 ", trigger value %d", __FUNCTION__,
5465 trigger.getTagName(), trigger.entryValue);
5466 return res;
5467 }
5468 }
5469 mTriggerReplacedMap.clear();
5470
5471 /**
5472 * Remove all new entries.
5473 */
5474 for (size_t i = 0; i < mTriggerRemovedMap.size(); ++i) {
5475 RequestTrigger trigger = mTriggerRemovedMap.valueAt(i);
5476 status_t res = metadata.erase(trigger.metadataTag);
5477
5478 if (res != OK) {
5479 ALOGE("%s: Failed to erase metadata with trigger tag %s"
5480 ", trigger value %d", __FUNCTION__,
5481 trigger.getTagName(), trigger.entryValue);
5482 return res;
5483 }
5484 }
5485 mTriggerRemovedMap.clear();
5486
5487 return OK;
5488}
5489
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04005490status_t Camera3Device::RequestThread::addFakeTriggerIds(
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005491 const sp<CaptureRequest> &request) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08005492 // Trigger ID 0 had special meaning in the HAL2 spec, so avoid it here
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04005493 static const int32_t fakeTriggerId = 1;
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005494 status_t res;
5495
Emilian Peevaebbe412018-01-15 13:53:24 +00005496 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005497
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04005498 // If AF trigger is active, insert a fake AF trigger ID if none already
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005499 // exists
5500 camera_metadata_entry afTrigger = metadata.find(ANDROID_CONTROL_AF_TRIGGER);
5501 camera_metadata_entry afId = metadata.find(ANDROID_CONTROL_AF_TRIGGER_ID);
5502 if (afTrigger.count > 0 &&
5503 afTrigger.data.u8[0] != ANDROID_CONTROL_AF_TRIGGER_IDLE &&
5504 afId.count == 0) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04005505 res = metadata.update(ANDROID_CONTROL_AF_TRIGGER_ID, &fakeTriggerId, 1);
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005506 if (res != OK) return res;
5507 }
5508
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04005509 // If AE precapture trigger is active, insert a fake precapture trigger ID
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005510 // if none already exists
5511 camera_metadata_entry pcTrigger =
5512 metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER);
5513 camera_metadata_entry pcId = metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_ID);
5514 if (pcTrigger.count > 0 &&
5515 pcTrigger.data.u8[0] != ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_IDLE &&
5516 pcId.count == 0) {
5517 res = metadata.update(ANDROID_CONTROL_AE_PRECAPTURE_ID,
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04005518 &fakeTriggerId, 1);
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005519 if (res != OK) return res;
5520 }
5521
5522 return OK;
5523}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005524
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005525bool Camera3Device::RequestThread::overrideAutoRotateAndCrop(
5526 const sp<CaptureRequest> &request) {
5527 ATRACE_CALL();
5528
5529 if (request->mRotateAndCropAuto) {
5530 Mutex::Autolock l(mTriggerMutex);
5531 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
5532
5533 auto rotateAndCropEntry = metadata.find(ANDROID_SCALER_ROTATE_AND_CROP);
5534 if (rotateAndCropEntry.count > 0) {
5535 if (rotateAndCropEntry.data.u8[0] == mRotateAndCropOverride) {
5536 return false;
5537 } else {
5538 rotateAndCropEntry.data.u8[0] = mRotateAndCropOverride;
5539 return true;
5540 }
5541 } else {
5542 uint8_t rotateAndCrop_u8 = mRotateAndCropOverride;
5543 metadata.update(ANDROID_SCALER_ROTATE_AND_CROP,
5544 &rotateAndCrop_u8, 1);
5545 return true;
5546 }
5547 }
5548 return false;
5549}
5550
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005551bool Camera3Device::RequestThread::overrideTestPattern(
5552 const sp<CaptureRequest> &request) {
5553 ATRACE_CALL();
5554
5555 Mutex::Autolock l(mTriggerMutex);
5556
5557 bool changed = false;
5558
5559 int32_t testPatternMode = request->mOriginalTestPatternMode;
5560 int32_t testPatternData[4] = {
5561 request->mOriginalTestPatternData[0],
5562 request->mOriginalTestPatternData[1],
5563 request->mOriginalTestPatternData[2],
5564 request->mOriginalTestPatternData[3]
5565 };
5566
5567 if (mCameraMute) {
5568 testPatternMode = ANDROID_SENSOR_TEST_PATTERN_MODE_SOLID_COLOR;
5569 testPatternData[0] = 0;
5570 testPatternData[1] = 0;
5571 testPatternData[2] = 0;
5572 testPatternData[3] = 0;
5573 }
5574
5575 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
5576
5577 auto testPatternEntry = metadata.find(ANDROID_SENSOR_TEST_PATTERN_MODE);
5578 if (testPatternEntry.count > 0) {
5579 if (testPatternEntry.data.i32[0] != testPatternMode) {
5580 testPatternEntry.data.i32[0] = testPatternMode;
5581 changed = true;
5582 }
5583 } else {
5584 metadata.update(ANDROID_SENSOR_TEST_PATTERN_MODE,
5585 &testPatternMode, 1);
5586 changed = true;
5587 }
5588
5589 auto testPatternColor = metadata.find(ANDROID_SENSOR_TEST_PATTERN_DATA);
5590 if (testPatternColor.count > 0) {
5591 for (size_t i = 0; i < 4; i++) {
5592 if (testPatternColor.data.i32[i] != (int32_t)testPatternData[i]) {
5593 testPatternColor.data.i32[i] = testPatternData[i];
5594 changed = true;
5595 }
5596 }
5597 } else {
5598 metadata.update(ANDROID_SENSOR_TEST_PATTERN_DATA,
5599 (int32_t*)testPatternData, 4);
5600 changed = true;
5601 }
5602
5603 return changed;
5604}
5605
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005606/**
5607 * PreparerThread inner class methods
5608 */
5609
5610Camera3Device::PreparerThread::PreparerThread() :
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07005611 Thread(/*canCallJava*/false), mListener(nullptr),
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005612 mActive(false), mCancelNow(false), mCurrentMaxCount(0), mCurrentPrepareComplete(false) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005613}
5614
5615Camera3Device::PreparerThread::~PreparerThread() {
5616 Thread::requestExitAndWait();
5617 if (mCurrentStream != nullptr) {
5618 mCurrentStream->cancelPrepare();
5619 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
5620 mCurrentStream.clear();
5621 }
5622 clear();
5623}
5624
Ruben Brunkc78ac262015-08-13 17:58:46 -07005625status_t Camera3Device::PreparerThread::prepare(int maxCount, sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005626 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005627 status_t res;
5628
5629 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005630 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005631
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07005632 res = stream->startPrepare(maxCount, true /*blockRequest*/);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005633 if (res == OK) {
5634 // No preparation needed, fire listener right off
5635 ALOGV("%s: Stream %d already prepared", __FUNCTION__, stream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005636 if (listener != NULL) {
5637 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005638 }
5639 return OK;
5640 } else if (res != NOT_ENOUGH_DATA) {
5641 return res;
5642 }
5643
5644 // Need to prepare, start up thread if necessary
5645 if (!mActive) {
5646 // mRunning will change to false before the thread fully shuts down, so wait to be sure it
5647 // isn't running
5648 Thread::requestExitAndWait();
5649 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
5650 if (res != OK) {
5651 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__, res, strerror(-res));
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005652 if (listener != NULL) {
5653 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005654 }
5655 return res;
5656 }
5657 mCancelNow = false;
5658 mActive = true;
5659 ALOGV("%s: Preparer stream started", __FUNCTION__);
5660 }
5661
5662 // queue up the work
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005663 mPendingStreams.emplace(maxCount, stream);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005664 ALOGV("%s: Stream %d queued for preparing", __FUNCTION__, stream->getId());
5665
5666 return OK;
5667}
5668
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005669void Camera3Device::PreparerThread::pause() {
5670 ATRACE_CALL();
5671
5672 Mutex::Autolock l(mLock);
5673
5674 std::unordered_map<int, sp<camera3::Camera3StreamInterface> > pendingStreams;
5675 pendingStreams.insert(mPendingStreams.begin(), mPendingStreams.end());
5676 sp<camera3::Camera3StreamInterface> currentStream = mCurrentStream;
5677 int currentMaxCount = mCurrentMaxCount;
5678 mPendingStreams.clear();
5679 mCancelNow = true;
5680 while (mActive) {
5681 auto res = mThreadActiveSignal.waitRelative(mLock, kActiveTimeout);
5682 if (res == TIMED_OUT) {
5683 ALOGE("%s: Timed out waiting on prepare thread!", __FUNCTION__);
5684 return;
5685 } else if (res != OK) {
5686 ALOGE("%s: Encountered an error: %d waiting on prepare thread!", __FUNCTION__, res);
5687 return;
5688 }
5689 }
5690
5691 //Check whether the prepare thread was able to complete the current
5692 //stream. In case work is still pending emplace it along with the rest
5693 //of the streams in the pending list.
5694 if (currentStream != nullptr) {
5695 if (!mCurrentPrepareComplete) {
5696 pendingStreams.emplace(currentMaxCount, currentStream);
5697 }
5698 }
5699
5700 mPendingStreams.insert(pendingStreams.begin(), pendingStreams.end());
5701 for (const auto& it : mPendingStreams) {
5702 it.second->cancelPrepare();
5703 }
5704}
5705
5706status_t Camera3Device::PreparerThread::resume() {
5707 ATRACE_CALL();
5708 status_t res;
5709
5710 Mutex::Autolock l(mLock);
5711 sp<NotificationListener> listener = mListener.promote();
5712
5713 if (mActive) {
5714 ALOGE("%s: Trying to resume an already active prepare thread!", __FUNCTION__);
5715 return NO_INIT;
5716 }
5717
5718 auto it = mPendingStreams.begin();
5719 for (; it != mPendingStreams.end();) {
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07005720 res = it->second->startPrepare(it->first, true /*blockRequest*/);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005721 if (res == OK) {
5722 if (listener != NULL) {
5723 listener->notifyPrepared(it->second->getId());
5724 }
5725 it = mPendingStreams.erase(it);
5726 } else if (res != NOT_ENOUGH_DATA) {
5727 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__,
5728 res, strerror(-res));
5729 it = mPendingStreams.erase(it);
5730 } else {
5731 it++;
5732 }
5733 }
5734
5735 if (mPendingStreams.empty()) {
5736 return OK;
5737 }
5738
5739 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
5740 if (res != OK) {
5741 ALOGE("%s: Unable to start preparer stream: %d (%s)",
5742 __FUNCTION__, res, strerror(-res));
5743 return res;
5744 }
5745 mCancelNow = false;
5746 mActive = true;
5747 ALOGV("%s: Preparer stream started", __FUNCTION__);
5748
5749 return OK;
5750}
5751
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005752status_t Camera3Device::PreparerThread::clear() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005753 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005754 Mutex::Autolock l(mLock);
5755
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005756 for (const auto& it : mPendingStreams) {
5757 it.second->cancelPrepare();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005758 }
5759 mPendingStreams.clear();
5760 mCancelNow = true;
5761
5762 return OK;
5763}
5764
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005765void Camera3Device::PreparerThread::setNotificationListener(wp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005766 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005767 Mutex::Autolock l(mLock);
5768 mListener = listener;
5769}
5770
5771bool Camera3Device::PreparerThread::threadLoop() {
5772 status_t res;
5773 {
5774 Mutex::Autolock l(mLock);
5775 if (mCurrentStream == nullptr) {
5776 // End thread if done with work
5777 if (mPendingStreams.empty()) {
5778 ALOGV("%s: Preparer stream out of work", __FUNCTION__);
5779 // threadLoop _must not_ re-acquire mLock after it sets mActive to false; would
5780 // cause deadlock with prepare()'s requestExitAndWait triggered by !mActive.
5781 mActive = false;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005782 mThreadActiveSignal.signal();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005783 return false;
5784 }
5785
5786 // Get next stream to prepare
5787 auto it = mPendingStreams.begin();
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005788 mCurrentStream = it->second;
5789 mCurrentMaxCount = it->first;
5790 mCurrentPrepareComplete = false;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005791 mPendingStreams.erase(it);
5792 ATRACE_ASYNC_BEGIN("stream prepare", mCurrentStream->getId());
5793 ALOGV("%s: Preparing stream %d", __FUNCTION__, mCurrentStream->getId());
5794 } else if (mCancelNow) {
5795 mCurrentStream->cancelPrepare();
5796 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
5797 ALOGV("%s: Cancelling stream %d prepare", __FUNCTION__, mCurrentStream->getId());
5798 mCurrentStream.clear();
5799 mCancelNow = false;
5800 return true;
5801 }
5802 }
5803
5804 res = mCurrentStream->prepareNextBuffer();
5805 if (res == NOT_ENOUGH_DATA) return true;
5806 if (res != OK) {
5807 // Something bad happened; try to recover by cancelling prepare and
5808 // signalling listener anyway
5809 ALOGE("%s: Stream %d returned error %d (%s) during prepare", __FUNCTION__,
5810 mCurrentStream->getId(), res, strerror(-res));
5811 mCurrentStream->cancelPrepare();
5812 }
5813
5814 // This stream has finished, notify listener
5815 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005816 sp<NotificationListener> listener = mListener.promote();
5817 if (listener != NULL) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005818 ALOGV("%s: Stream %d prepare done, signaling listener", __FUNCTION__,
5819 mCurrentStream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005820 listener->notifyPrepared(mCurrentStream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005821 }
5822
5823 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
5824 mCurrentStream.clear();
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005825 mCurrentPrepareComplete = true;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005826
5827 return true;
5828}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005829
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005830status_t Camera3Device::RequestBufferStateMachine::initialize(
5831 sp<camera3::StatusTracker> statusTracker) {
5832 if (statusTracker == nullptr) {
5833 ALOGE("%s: statusTracker is null", __FUNCTION__);
5834 return BAD_VALUE;
5835 }
5836
5837 std::lock_guard<std::mutex> lock(mLock);
5838 mStatusTracker = statusTracker;
Yin-Chia Yeh87b3ec02019-06-03 10:44:39 -07005839 mRequestBufferStatusId = statusTracker->addComponent("BufferRequestSM");
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005840 return OK;
5841}
5842
5843bool Camera3Device::RequestBufferStateMachine::startRequestBuffer() {
5844 std::lock_guard<std::mutex> lock(mLock);
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08005845 if (mStatus == RB_STATUS_READY || mStatus == RB_STATUS_PENDING_STOP) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005846 mRequestBufferOngoing = true;
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08005847 notifyTrackerLocked(/*active*/true);
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005848 return true;
5849 }
5850 return false;
5851}
5852
5853void Camera3Device::RequestBufferStateMachine::endRequestBuffer() {
5854 std::lock_guard<std::mutex> lock(mLock);
5855 if (!mRequestBufferOngoing) {
5856 ALOGE("%s called without a successful startRequestBuffer call first!", __FUNCTION__);
5857 return;
5858 }
5859 mRequestBufferOngoing = false;
5860 if (mStatus == RB_STATUS_PENDING_STOP) {
5861 checkSwitchToStopLocked();
5862 }
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08005863 notifyTrackerLocked(/*active*/false);
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005864}
5865
5866void Camera3Device::RequestBufferStateMachine::onStreamsConfigured() {
5867 std::lock_guard<std::mutex> lock(mLock);
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005868 mSwitchedToOffline = false;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005869 mStatus = RB_STATUS_READY;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005870 return;
5871}
5872
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08005873void Camera3Device::RequestBufferStateMachine::onSubmittingRequest() {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005874 std::lock_guard<std::mutex> lock(mLock);
5875 mRequestThreadPaused = false;
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08005876 // inflight map register actually happens in prepareHalRequest now, but it is close enough
5877 // approximation.
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005878 mInflightMapEmpty = false;
5879 if (mStatus == RB_STATUS_STOPPED) {
5880 mStatus = RB_STATUS_READY;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005881 }
5882 return;
5883}
5884
5885void Camera3Device::RequestBufferStateMachine::onRequestThreadPaused() {
5886 std::lock_guard<std::mutex> lock(mLock);
5887 mRequestThreadPaused = true;
5888 if (mStatus == RB_STATUS_PENDING_STOP) {
5889 checkSwitchToStopLocked();
5890 }
5891 return;
5892}
5893
5894void Camera3Device::RequestBufferStateMachine::onInflightMapEmpty() {
5895 std::lock_guard<std::mutex> lock(mLock);
5896 mInflightMapEmpty = true;
5897 if (mStatus == RB_STATUS_PENDING_STOP) {
5898 checkSwitchToStopLocked();
5899 }
5900 return;
5901}
5902
5903void Camera3Device::RequestBufferStateMachine::onWaitUntilIdle() {
5904 std::lock_guard<std::mutex> lock(mLock);
5905 if (!checkSwitchToStopLocked()) {
5906 mStatus = RB_STATUS_PENDING_STOP;
5907 }
5908 return;
5909}
5910
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005911bool Camera3Device::RequestBufferStateMachine::onSwitchToOfflineSuccess() {
5912 std::lock_guard<std::mutex> lock(mLock);
5913 if (mRequestBufferOngoing) {
5914 ALOGE("%s: HAL must not be requesting buffer after HAL returns switchToOffline!",
5915 __FUNCTION__);
5916 return false;
5917 }
5918 mSwitchedToOffline = true;
5919 mInflightMapEmpty = true;
5920 mRequestThreadPaused = true;
5921 mStatus = RB_STATUS_STOPPED;
5922 return true;
5923}
5924
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005925void Camera3Device::RequestBufferStateMachine::notifyTrackerLocked(bool active) {
5926 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5927 if (statusTracker != nullptr) {
5928 if (active) {
5929 statusTracker->markComponentActive(mRequestBufferStatusId);
5930 } else {
5931 statusTracker->markComponentIdle(mRequestBufferStatusId, Fence::NO_FENCE);
5932 }
5933 }
5934}
5935
5936bool Camera3Device::RequestBufferStateMachine::checkSwitchToStopLocked() {
5937 if (mInflightMapEmpty && mRequestThreadPaused && !mRequestBufferOngoing) {
5938 mStatus = RB_STATUS_STOPPED;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005939 return true;
5940 }
5941 return false;
5942}
5943
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005944bool Camera3Device::startRequestBuffer() {
5945 return mRequestBufferSM.startRequestBuffer();
5946}
Shuzhen Wang268a1362018-10-16 16:32:59 -07005947
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005948void Camera3Device::endRequestBuffer() {
5949 mRequestBufferSM.endRequestBuffer();
5950}
Shuzhen Wang268a1362018-10-16 16:32:59 -07005951
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005952nsecs_t Camera3Device::getWaitDuration() {
5953 return kBaseGetBufferWait + getExpectedInFlightDuration();
5954}
Shuzhen Wang268a1362018-10-16 16:32:59 -07005955
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005956void Camera3Device::getInflightBufferKeys(std::vector<std::pair<int32_t, int32_t>>* out) {
5957 mInterface->getInflightBufferKeys(out);
5958}
Shuzhen Wang268a1362018-10-16 16:32:59 -07005959
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005960void Camera3Device::getInflightRequestBufferKeys(std::vector<uint64_t>* out) {
5961 mInterface->getInflightRequestBufferKeys(out);
5962}
Shuzhen Wang268a1362018-10-16 16:32:59 -07005963
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005964std::vector<sp<Camera3StreamInterface>> Camera3Device::getAllStreams() {
5965 std::vector<sp<Camera3StreamInterface>> ret;
5966 bool hasInputStream = mInputStream != nullptr;
5967 ret.reserve(mOutputStreams.size() + mDeletedStreams.size() + ((hasInputStream) ? 1 : 0));
5968 if (hasInputStream) {
5969 ret.push_back(mInputStream);
Shuzhen Wang268a1362018-10-16 16:32:59 -07005970 }
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005971 for (size_t i = 0; i < mOutputStreams.size(); i++) {
5972 ret.push_back(mOutputStreams[i]);
5973 }
5974 for (size_t i = 0; i < mDeletedStreams.size(); i++) {
5975 ret.push_back(mDeletedStreams[i]);
5976 }
5977 return ret;
Shuzhen Wang268a1362018-10-16 16:32:59 -07005978}
5979
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005980status_t Camera3Device::switchToOffline(
5981 const std::vector<int32_t>& streamsToKeep,
5982 /*out*/ sp<CameraOfflineSessionBase>* session) {
5983 ATRACE_CALL();
5984 if (session == nullptr) {
5985 ALOGE("%s: session must not be null", __FUNCTION__);
5986 return BAD_VALUE;
5987 }
5988
5989 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005990
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005991 bool hasInputStream = mInputStream != nullptr;
5992 int32_t inputStreamId = hasInputStream ? mInputStream->getId() : -1;
5993 bool inputStreamSupportsOffline = hasInputStream ?
5994 mInputStream->getOfflineProcessingSupport() : false;
5995 auto outputStreamIds = mOutputStreams.getStreamIds();
5996 auto streamIds = outputStreamIds;
5997 if (hasInputStream) {
5998 streamIds.push_back(mInputStream->getId());
5999 }
6000
6001 // Check all streams in streamsToKeep supports offline mode
6002 for (auto id : streamsToKeep) {
6003 if (std::find(streamIds.begin(), streamIds.end(), id) == streamIds.end()) {
6004 ALOGE("%s: Unknown stream ID %d", __FUNCTION__, id);
6005 return BAD_VALUE;
6006 } else if (id == inputStreamId) {
6007 if (!inputStreamSupportsOffline) {
6008 ALOGE("%s: input stream %d cannot be switched to offline",
6009 __FUNCTION__, id);
6010 return BAD_VALUE;
6011 }
6012 } else {
6013 sp<camera3::Camera3OutputStreamInterface> stream = mOutputStreams.get(id);
6014 if (!stream->getOfflineProcessingSupport()) {
6015 ALOGE("%s: output stream %d cannot be switched to offline",
6016 __FUNCTION__, id);
6017 return BAD_VALUE;
6018 }
6019 }
6020 }
6021
6022 // TODO: block surface sharing and surface group streams until we can support them
6023
6024 // Stop repeating request, wait until all remaining requests are submitted, then call into
6025 // HAL switchToOffline
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006026 hardware::camera::device::V3_6::CameraOfflineSessionInfo offlineSessionInfo;
6027 sp<hardware::camera::device::V3_6::ICameraOfflineSession> offlineSession;
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006028 camera3::BufferRecords bufferRecords;
6029 status_t ret = mRequestThread->switchToOffline(
6030 streamsToKeep, &offlineSessionInfo, &offlineSession, &bufferRecords);
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006031
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006032 if (ret != OK) {
6033 SET_ERR("Switch to offline failed: %s (%d)", strerror(-ret), ret);
6034 return ret;
6035 }
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006036
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006037 bool succ = mRequestBufferSM.onSwitchToOfflineSuccess();
6038 if (!succ) {
6039 SET_ERR("HAL must not be calling requestStreamBuffers call");
6040 // TODO: block ALL callbacks from HAL till app configured new streams?
6041 return UNKNOWN_ERROR;
6042 }
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006043
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006044 // Verify offlineSessionInfo
6045 std::vector<int32_t> offlineStreamIds;
6046 offlineStreamIds.reserve(offlineSessionInfo.offlineStreams.size());
6047 for (auto offlineStream : offlineSessionInfo.offlineStreams) {
6048 // verify stream IDs
6049 int32_t id = offlineStream.id;
6050 if (std::find(streamIds.begin(), streamIds.end(), id) == streamIds.end()) {
6051 SET_ERR("stream ID %d not found!", id);
6052 return UNKNOWN_ERROR;
6053 }
6054
6055 // When not using HAL buf manager, only allow streams requested by app to be preserved
6056 if (!mUseHalBufManager) {
6057 if (std::find(streamsToKeep.begin(), streamsToKeep.end(), id) == streamsToKeep.end()) {
6058 SET_ERR("stream ID %d must not be switched to offline!", id);
6059 return UNKNOWN_ERROR;
6060 }
6061 }
6062
6063 offlineStreamIds.push_back(id);
6064 sp<Camera3StreamInterface> stream = (id == inputStreamId) ?
6065 static_cast<sp<Camera3StreamInterface>>(mInputStream) :
6066 static_cast<sp<Camera3StreamInterface>>(mOutputStreams.get(id));
6067 // Verify number of outstanding buffers
6068 if (stream->getOutstandingBuffersCount() != offlineStream.numOutstandingBuffers) {
6069 SET_ERR("Offline stream %d # of remaining buffer mismatch: (%zu,%d) (service/HAL)",
6070 id, stream->getOutstandingBuffersCount(), offlineStream.numOutstandingBuffers);
6071 return UNKNOWN_ERROR;
6072 }
6073 }
6074
6075 // Verify all streams to be deleted don't have any outstanding buffers
6076 if (hasInputStream && std::find(offlineStreamIds.begin(), offlineStreamIds.end(),
6077 inputStreamId) == offlineStreamIds.end()) {
6078 if (mInputStream->hasOutstandingBuffers()) {
6079 SET_ERR("Input stream %d still has %zu outstanding buffer!",
6080 inputStreamId, mInputStream->getOutstandingBuffersCount());
6081 return UNKNOWN_ERROR;
6082 }
6083 }
6084
6085 for (const auto& outStreamId : outputStreamIds) {
6086 if (std::find(offlineStreamIds.begin(), offlineStreamIds.end(),
6087 outStreamId) == offlineStreamIds.end()) {
6088 auto outStream = mOutputStreams.get(outStreamId);
6089 if (outStream->hasOutstandingBuffers()) {
6090 SET_ERR("Output stream %d still has %zu outstanding buffer!",
6091 outStreamId, outStream->getOutstandingBuffersCount());
6092 return UNKNOWN_ERROR;
6093 }
6094 }
6095 }
6096
6097 InFlightRequestMap offlineReqs;
6098 // Verify inflight requests and their pending buffers
6099 {
6100 std::lock_guard<std::mutex> l(mInFlightLock);
6101 for (auto offlineReq : offlineSessionInfo.offlineRequests) {
6102 int idx = mInFlightMap.indexOfKey(offlineReq.frameNumber);
6103 if (idx == NAME_NOT_FOUND) {
6104 SET_ERR("Offline request frame number %d not found!", offlineReq.frameNumber);
6105 return UNKNOWN_ERROR;
6106 }
6107
6108 const auto& inflightReq = mInFlightMap.valueAt(idx);
6109 // TODO: check specific stream IDs
6110 size_t numBuffersLeft = static_cast<size_t>(inflightReq.numBuffersLeft);
6111 if (numBuffersLeft != offlineReq.pendingStreams.size()) {
6112 SET_ERR("Offline request # of remaining buffer mismatch: (%d,%d) (service/HAL)",
6113 inflightReq.numBuffersLeft, offlineReq.pendingStreams.size());
6114 return UNKNOWN_ERROR;
6115 }
6116 offlineReqs.add(offlineReq.frameNumber, inflightReq);
6117 }
6118 }
6119
6120 // Create Camera3OfflineSession and transfer object ownership
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006121 // (streams, inflight requests, buffer caches)
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006122 camera3::StreamSet offlineStreamSet;
6123 sp<camera3::Camera3Stream> inputStream;
6124 for (auto offlineStream : offlineSessionInfo.offlineStreams) {
6125 int32_t id = offlineStream.id;
6126 if (mInputStream != nullptr && id == mInputStream->getId()) {
6127 inputStream = mInputStream;
6128 } else {
6129 offlineStreamSet.add(id, mOutputStreams.get(id));
6130 }
6131 }
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006132
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006133 // TODO: check if we need to lock before copying states
6134 // though technically no other thread should be talking to Camera3Device at this point
6135 Camera3OfflineStates offlineStates(
6136 mTagMonitor, mVendorTagId, mUseHalBufManager, mNeedFixupMonochromeTags,
Shuzhen Wangb7b42652020-05-07 11:59:02 -07006137 mUsePartialResult, mNumPartialResults, mLastCompletedRegularFrameNumber,
6138 mLastCompletedReprocessFrameNumber, mLastCompletedZslFrameNumber,
6139 mNextResultFrameNumber, mNextReprocessResultFrameNumber,
6140 mNextZslStillResultFrameNumber, mNextShutterFrameNumber,
6141 mNextReprocessShutterFrameNumber, mNextZslStillShutterFrameNumber,
6142 mDeviceInfo, mPhysicalDeviceInfoMap, mDistortionMappers,
6143 mZoomRatioMappers, mRotateAndCropMappers);
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006144
6145 *session = new Camera3OfflineSession(mId, inputStream, offlineStreamSet,
6146 std::move(bufferRecords), offlineReqs, offlineStates, offlineSession);
6147
6148 // Delete all streams that has been transferred to offline session
6149 Mutex::Autolock l(mLock);
6150 for (auto offlineStream : offlineSessionInfo.offlineStreams) {
6151 int32_t id = offlineStream.id;
6152 if (mInputStream != nullptr && id == mInputStream->getId()) {
6153 mInputStream.clear();
6154 } else {
6155 mOutputStreams.remove(id);
6156 }
6157 }
6158
6159 // disconnect all other streams and switch to UNCONFIGURED state
6160 if (mInputStream != nullptr) {
6161 ret = mInputStream->disconnect();
6162 if (ret != OK) {
6163 SET_ERR_L("disconnect input stream failed!");
6164 return UNKNOWN_ERROR;
6165 }
6166 }
6167
6168 for (auto streamId : mOutputStreams.getStreamIds()) {
6169 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
6170 ret = stream->disconnect();
6171 if (ret != OK) {
6172 SET_ERR_L("disconnect output stream %d failed!", streamId);
6173 return UNKNOWN_ERROR;
6174 }
6175 }
6176
6177 mInputStream.clear();
6178 mOutputStreams.clear();
6179 mNeedConfig = true;
6180 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
6181 mOperatingMode = NO_MODE;
6182 mIsConstrainedHighSpeedConfiguration = false;
Emilian Peevc0fe54c2020-03-11 14:05:07 -07006183 mRequestThread->clearPreviousRequest();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006184
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006185 return OK;
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006186 // TO be done by CameraDeviceClient/Camera3OfflineSession
6187 // register the offline client to camera service
6188 // Setup result passthing threads etc
6189 // Initialize offline session so HAL can start sending callback to it (result Fmq)
6190 // TODO: check how many onIdle callback will be sent
6191 // Java side to make sure the CameraCaptureSession is properly closed
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006192}
6193
Emilian Peevcc0b7952020-01-07 13:54:47 -08006194void Camera3Device::getOfflineStreamIds(std::vector<int> *offlineStreamIds) {
6195 ATRACE_CALL();
6196
6197 if (offlineStreamIds == nullptr) {
6198 return;
6199 }
6200
6201 Mutex::Autolock il(mInterfaceLock);
6202
6203 auto streamIds = mOutputStreams.getStreamIds();
6204 bool hasInputStream = mInputStream != nullptr;
6205 if (hasInputStream && mInputStream->getOfflineProcessingSupport()) {
6206 offlineStreamIds->push_back(mInputStream->getId());
6207 }
6208
6209 for (const auto & streamId : streamIds) {
6210 sp<camera3::Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
6211 // Streams that use the camera buffer manager are currently not supported in
6212 // offline mode
6213 if (stream->getOfflineProcessingSupport() &&
6214 (stream->getStreamSetId() == CAMERA3_STREAM_SET_ID_INVALID)) {
6215 offlineStreamIds->push_back(streamId);
6216 }
6217 }
6218}
6219
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08006220status_t Camera3Device::setRotateAndCropAutoBehavior(
6221 camera_metadata_enum_android_scaler_rotate_and_crop_t rotateAndCropValue) {
6222 ATRACE_CALL();
6223 Mutex::Autolock il(mInterfaceLock);
6224 Mutex::Autolock l(mLock);
6225 if (mRequestThread == nullptr) {
6226 return INVALID_OPERATION;
6227 }
6228 return mRequestThread->setRotateAndCropAutoBehavior(rotateAndCropValue);
6229}
6230
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08006231bool Camera3Device::supportsCameraMute() {
6232 Mutex::Autolock il(mInterfaceLock);
6233 Mutex::Autolock l(mLock);
6234
6235 return mSupportCameraMute;
6236}
6237
6238status_t Camera3Device::setCameraMute(bool enabled) {
6239 ATRACE_CALL();
6240 Mutex::Autolock il(mInterfaceLock);
6241 Mutex::Autolock l(mLock);
6242
6243 if (mRequestThread == nullptr || !mSupportCameraMute) {
6244 return INVALID_OPERATION;
6245 }
6246 return mRequestThread->setCameraMute(enabled);
6247}
6248
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08006249}; // namespace android